logger.py 8.29 KB
Newer Older
Nelso Jost's avatar
Nelso Jost committed
1
2
#-------------------------------------------------------------------------------
# Author: Nelso G. Jost (nelsojost@gmail.com)
3
4
# License: GPL
# Purpose: Get data from the board via serial and send it to the server.
Nelso Jost's avatar
Nelso Jost committed
5
6
7
8
9
10
11
12
13
14
15
16
17
#-------------------------------------------------------------------------------
from __future__ import print_function, division

from datetime import datetime
from pprint import pprint
import os
import requests
import serial
import time
import json
import yaml

def make_current_file_path(filename):
18
    ''' Append filename to the current __file__ path. '''
Nelso Jost's avatar
Nelso Jost committed
19
20
21
    return os.path.join(os.path.abspath(os.path.dirname(__file__)), filename)

class Meteorologger:
22
23
24
25
26
27
28
29
30
    '''
    Provides a series of mechanisms to collect sensor data from the board
    via serial port, save locally on the machine and upload to the server.

    The functionality of this class relies heavily on the config file given
    by the SETTINGS_FILENAME attribute, which uses YAML syntax.

    Call the run() method to start the logging process.
    '''
Nelso Jost's avatar
Nelso Jost committed
31
32
33
34
35
36
37
38
39
40
41
42
43
    SETTINGS_FILENAME = make_current_file_path('settings.yaml')

    CSV_SEP = ','
    DATA_FORMATS = {'INTEGER': int, 'FLOAT': float, 'STRING': str}

    SERIAL_READ_TIMEOUT = 1.5  # seconds
    FIND_PORT_TIMEOUT = 2      # seconds
    BOARD_RESET_TIMEOUT = 2    # seconds

    def __init__(self):
        self.loadSettings()

    def _normalizePathFilename(self, key):
44
45
        ''' Appends __file__ basedir to config keys that don't have a basedir.
        '''
Nelso Jost's avatar
Nelso Jost committed
46
47
48
49
        if not os.path.dirname(self.CFG[key]):
            self.CFG[key] = make_current_file_path(self.CFG[key])

    def loadSettings(self):
50
51
52
53
        '''
        Load the configuration file onto the self.CFG attribute.
        Some keys will be tested and filenames will be normalized.
        '''
Nelso Jost's avatar
Nelso Jost committed
54
55
56
57
58
        with open(self.SETTINGS_FILENAME) as f:
            self.CFG = yaml.safe_load(f)

        if not self.CFG['BASE_URL'].endswith('/'):
            self.CFG['BASE_URL'] += '/'
59
        self.URL = self.CFG['BASE_URL'] + 'api/post/rawsensordata/{}'\
Nelso Jost's avatar
Nelso Jost committed
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
                                          .format(self.CFG['BOARD_ID'])

        self.SENSORS_CSV_LINE = self.CSV_SEP.join([d['nickname'] for d in
                                                  self.CFG['SENSORS']])

        # convert raw str into normal escaped str (e.g., r'\\t' --> '\t')
        self.CFG['EXPORT_CSV_SEP'] = bytes(self.CFG['EXPORT_CSV_SEP'], 'utf8')\
                                     .decode('unicode_escape')

        self.SERIAL_PORTS = [p.strip() for p in self.CFG['SERIAL_PORT']
                                                .split(',')]

        self._normalizePathFilename('DATA_LOG_FILENAME')
        self._normalizePathFilename('SERVER_OUTGOING_DATA_LOG_FILENAME')

    def create_json_raw_sensor_data(self, raw_line):
76
77
78
79
        '''
        Given the raw serial line response (expected to be a CSV line), returns
        a JSON dict with sensor data including the datetime field.
        '''
Nelso Jost's avatar
Nelso Jost committed
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
        raw_sensor_data = {'datetime': datetime.now().strftime("%Y%m%d%H%M%S"),
                           'sensors': {}}

        for i, v in enumerate(raw_line.split(self.CSV_SEP)):
            v = v.strip()
            try:
                v = self.DATA_FORMATS[self.CFG['SENSORS'][i]['data_format']](v)
            except:
                v = 'NaN'

            raw_sensor_data['sensors'][self.CFG['SENSORS'][i]['nickname']] = v

        print("\nJSON raw sensor data:")
        pprint(raw_sensor_data)

        return raw_sensor_data

    def add_data_log(self, json_data):
98
99
100
        '''
        
        '''
Nelso Jost's avatar
Nelso Jost committed
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
        csv_line = json_data['datetime'] + self.CFG['EXPORT_CSV_SEP']
        for sensor in self.CFG['SENSORS']:
            if sensor['nickname'] in json_data['sensors']:
                csv_line += str(json_data['sensors']
                                        [sensor['nickname']])
            csv_line += self.CFG['EXPORT_CSV_SEP']

        with open(self.CFG['DATA_LOG_FILENAME'], "a") as f:
            f.write(csv_line[:-1] + '\n')
            print("\nWrited data log onto\n    {}".format(
                    self.CFG['DATA_LOG_FILENAME']))

    def send_data_to_server(self, json_data):
        print("\nSending data to the server now..", end='')
        r = None
        try:
            if os.path.exists(self.CFG['SERVER_OUTGOING_DATA_LOG_FILENAME']):
                print("\nTrying to send outgoing data first...")
                with open(self.CFG['SERVER_OUTGOING_DATA_LOG_FILENAME']) as f:
                    for i, line in enumerate(f):
                        r = requests.post(self.URL, json=json.loads(line))
                        if r.status_code != 200:
                            raise Exception
                        print('Line {} :'.format(i), r)
                os.remove(self.CFG['SERVER_OUTGOING_DATA_LOG_FILENAME'])
                print("\ndone! Server data is up to date!")

            r = requests.post(self.URL, json=json_data)
            if r.status_code != 200:
                raise Exception
        except:
            print("\nUnable to reach the server at\n    {}".format(self.URL))
            print("Request:", r)

            with open(self.CFG['SERVER_OUTGOING_DATA_LOG_FILENAME'], 'a') as f:
                f.write(json.dumps(json_data))
                f.write('\n')

            print("\nAdded to\n   {}".format(
                self.CFG['SERVER_OUTGOING_DATA_LOG_FILENAME']))
            return
        print(" done.\n   ", r)

    def _decode_bytes(self, raw_bytes):
        result = None
        try:
            result = raw_bytes.decode('ascii').strip()
        except:
            print("Invalid bytes!")
        return result

    def serial_read_sensors(self, csv_nickname_list, serial_port=None):
        result_line, ser = None, None
        try:
            if serial_port is None:
                serial_port = self.SERIAL_PORTS[0]
            elif isinstance(serial_port, int):
                serial_port = self.SERIAL_PORTS[serial_port]

            # if present, the board will be reseted
            ser = serial.Serial(serial_port,
                                self.CFG['BAUD_RATE'],
                                timeout = self.SERIAL_READ_TIMEOUT,
                                xonxoff=True)
            print(ser)
            time.sleep(self.BOARD_RESET_TIMEOUT)

            while bool(result_line) is False:

                result = ser.write(bytes(csv_nickname_list, 'utf8'))
                print("sent '{}':".format(csv_nickname_list), result)

                result_line = ser.readline()
                print("read: ", result_line)

                result_line = self._decode_bytes(result_line)
                if result_line is None:
                    continue

            ser.close()
            return result_line
        except KeyboardInterrupt:
            raise KeyboardInterrupt
        except:
            print("Unable to open serial port '{}'".format(serial_port))
            return None
        finally:
            if ser:
                ser.close()

    def run(self):
192
193
194
195
196
        '''
        Starts the logger main loop, which iterate over the procedures:
            1. Read sensor data via serial port;
            2. If successful, save data on 
        '''
Nelso Jost's avatar
Nelso Jost committed
197
198
199
200
201
202
        serial_port = 0
        try:
            while True:
                print('\n-----------------------------------------------------')
                csv_result = self.serial_read_sensors(self.SENSORS_CSV_LINE,
                                                      serial_port=serial_port)
203
                print("csv_result: '{}'".format(csv_result))
Nelso Jost's avatar
Nelso Jost committed
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
                if csv_result is not None:
                    json_raw_data = self.create_json_raw_sensor_data(csv_result)
                    self.add_data_log(json_raw_data)
                    self.send_data_to_server(json_raw_data)
                else:
                    if serial_port < len(self.SERIAL_PORTS) - 1:
                        serial_port += 1
                    else:
                        serial_port = 0
                    print('Trying another port..')
                    time.sleep(self.FIND_PORT_TIMEOUT)
                    continue

                print('\nGoing to sleep now for {} seconds..'.format(
                        self.CFG['READING_INTERVAL_SECONDS']))
                time.sleep(self.CFG['READING_INTERVAL_SECONDS'])

        except KeyboardInterrupt:
            pass

if __name__ == '__main__':
    Meteorologger().run()