main.py 15.9 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#-------------------------------------------------------------------------------
# Author: Nelso G. Jost (nelsojost@gmail.com)
# License: GPL
# Purpose: Get data from the board via serial and send it to the server.
#-------------------------------------------------------------------------------
from __future__ import print_function, division

from datetime import datetime
from pprint import pprint

import logging
import os
import requests
import subprocess
import serial
import sys
import time
import json

from pykwalify.core import Core

def make_current_file_path(filename):
    ''' Append filename to the current __file__ path. '''
    return os.path.join(os.path.abspath(os.path.dirname(__file__)), filename)


class RTCDateTime:
    RTC_DT_FMT = '%Y-%m-%d %H:%M:%S'
    __qualname__ = "RTCDateTime fmt='{}'".format(RTC_DT_FMT)

    def __init__(self, s):
        self.dt = datetime.strptime(s, self.RTC_DT_FMT)

    def __str__(self):
        return self.dt.strftime('%Y%m%d%H%M%S')


class Meteorologger:
    '''
    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.
    '''
labfis's avatar
labfis committed
48
49
    SETTINGS_SCHEMA_FILENAME = make_current_file_path('settings_schema.yaml')
    SETTINGS_FILENAME = make_current_file_path('../../settings.yaml')
50

51
52
    DATALOG_DIR = 'data/'
    EXECUTION_LOG_PATH = 'logger/logs/'
53
54
55
56
57
58
59
60
61
62
63
    OUTGOING_BASENAME = 'outgoing.json'

    FILE_TIMESTAMP_FORMAT = '%Y-%m-%d-%H-%M-%S'

    SERIAL_CSV_SEP = ','
    DATA_FORMATS = {'int': int, 'float': float, 'str': str,
                    'datetime': RTCDateTime}

    SERIAL_READ_TIMEOUT = 1.5  # seconds
    FIND_PORT_TIMEOUT = 10     # seconds
    BOARD_RESET_TIMEOUT = 2    # seconds
64
    BOARD_RESPONSE_DELAY = 3   # seconds
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106

    verbose = True

    def __init__(self, verbose=False):
        self.verbose = verbose
        self.load_settings()

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


    def load_settings(self):
        '''
        Load the configuration file onto the self.CFG attribute.
        Some keys will be tested and filenames will be normalized.
        '''
        c = Core(source_file=self.SETTINGS_FILENAME,
                 schema_files=[self.SETTINGS_SCHEMA_FILENAME])

        try:
            self.CFG = c.validate(raise_exception=True)
        except Exception as e:
            print('-'*60)
            print("There is something wrong with the configuration file '{}'"
                    "\nKeep in mind that it uses YAML syntax which require "
                    "proper identation.\n".format(self.SETTINGS_FILENAME))
            print(e)
            print("\nPlease fix it up or regenerate it.")
            sys.exit(1)

        self.READING_INTERVAL_SECONDS =\
            self.CFG['LOGGER']['INTERVAL']['seconds']\
            + 60 * self.CFG['LOGGER']['INTERVAL']['minutes']\
            + 3600 * self.CFG['LOGGER']['INTERVAL']['hours']\
            + 86400 * self.CFG['LOGGER']['INTERVAL']['days']

107
108
109
        self.DATALOG_CSV_SEP = bytes(self.CFG['DATALOG']['CSV_SEP'],
                                     'utf8').decode('unicode_escape')

110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
    def create_json(self, raw_line):
        '''
        Given the raw serial line response (CSV string), builds and returns
        a JSON dict with validated, server-ready, sensor data.
        '''
        d = {'datetime': {'format': self.CFG['DATALOG']['DATETIME_FORMAT']},
             'sensors': {}}

        rtc = self.CFG['LOGGER']['USE_RTC_DATETIME']
        using_rtc = rtc and rtc in self.CFG['LOGGER']['SENSORS']

        if using_rtc:
            d['datetime']['source'] = rtc
            rtc_datetime_fmt = self.CFG['LOGGER']['RTC_DATETIME_FORMAT']

        for i, v in enumerate(raw_line.split(self.SERIAL_CSV_SEP)):

            nickname = self.CFG['LOGGER']['SENSORS'][i]
            type_name = self.CFG['SENSORS_AVAILABLE'][nickname]['data_format']

            if type_name == 'datetime':
131
                if using_rtc and not 'not_found' in v.strip():
132
133
134
135
136
137
138
                    d['datetime']['value'] = datetime.strptime(
                        v, rtc_datetime_fmt).strftime(d['datetime']['format'])
                continue

            try:
                v = self.DATA_FORMATS[type_name](v.strip())
            except:
139
                logging.warning("[{}]: '{}' is not a valid {}"
140
                              .format(nickname, v, type_name))
141
                d['sensors'][nickname] = 'NaN'
142
143
144
145
                continue

            d['sensors'][nickname] = v

146
147
148
149
150
        if not 'value' in d['datetime']:
            d['datetime']['source'] = 'logger'
            d['datetime']['value'] = datetime.now().strftime(
                    d['datetime']['format'])

151
152
153
154
155
156
157
158
159
160
161
        logging.info("Validated JSON: {}".format(d))

        return d

    def write_datalog(self, json_data):
        '''
        For backup purposes, write the given JSON data onto the file
        DATALOG_CSV as specficied on self.SETTINGS_FILENAME.
        '''
        # convert raw str into normal escaped str (e.g., r'\\t' --> '\t')

162
        csv_line = json_data['datetime']['value'] + self.DATALOG_CSV_SEP
163
164
165
166

        for nickname in self.CFG['LOGGER']['SENSORS']:
            if nickname in json_data['sensors']:
                csv_line += str(json_data['sensors'][nickname])
167
            csv_line += self.DATALOG_CSV_SEP
168
169
170
        csv_line = csv_line[:-1]

        try:
171
            datalog_filename = self.SESSION_DATALOG_FILENAME
172
173
174
175
176
177
178
179
180
181
182
            with open(datalog_filename, 'a') as f:
                f.write(csv_line + '\n')
            logging.info("Updated datalog file: '{}'".format(datalog_filename))
        except Exception as e:
            logging.error("Unable to write datalog at '{}'"
                          .format(datalog_filename))
            logging.info("Exception: {}".format(e))


    def send_to_server(self, json_data):
        r = None
183
        outgoing_filename = self.SESSION_OUTGOING_FILENAME
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
        URL = self.CFG['SERVER']['API_POST_URL']
        try:
            if os.path.exists(outgoing_filename):
                logging.debug("Outgoing data exists! Will try to send it.")

                with open(outgoing_filename) as f:
                    for i, line in enumerate(f):
                        d = json.loads(line, encoding='utf-8')
                        r = requests.post(URL, json=d)
                        if r.status_code != 200:
                            raise Exception

                        logging.info('Line {}: {}'.format(i, r))

                os.remove(outgoing_filename)
                logging.info("Removed file '{}'".format(outgoing_filename))

            r = requests.post(URL, json=json_data)
            if r.status_code != 200:
                raise Exception
            logging.info("Request: {}".format(r))

        except:
            logging.error("Unable to reach the server at '{}'. Request: {}"
                          .format(URL, r))

            try:
                with open(outgoing_filename, 'a') as f:
                    f.write(json.dumps(json_data) + '\n')

                logging.info("Updated outgoing file '{}'"
                             .format(outgoing_filename))
            except Exception as e:
                logging.error("[DATALOST] Unable to write outgoing file '{}'".
                              format(outgoing_filename))
                logging.info("Exception: {}".format(e))

    def serial_read(self, port_index=None):
        '''
        Sends the 'csv_nickname_list' string to the serial port of index
224
225
        'port_index' (self.CFG['ARDUINO']['SERIAL_PORTS']) and returns
        the response line.
226
227
228
229
230
231
232
233
234

        csv_nickname_list example: str
            Example: 'DHT22_TEMP,DHT22_AH,BMP085_PRESSURE,LDR'
        '''
        result_line, ser = None, None
        read_command = self.SERIAL_CSV_SEP.join(
            ['read'] + self.CFG['LOGGER']['SENSORS'])
        try:
            if isinstance(port_index, int):
235
                serial_port = self.CFG['ARDUINO']['SERIAL_PORTS'][port_index]
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
            else:
                serial_port = self.SERIAL_PORTS[0]

            # if present, the board will be reseted
            ser = serial.Serial(serial_port, self.CFG['ARDUINO']['BAUD_RATE'],
                                timeout=self.SERIAL_READ_TIMEOUT, xonxoff=True)
            logging.info("Serial open <port='{}', baudrate={}>"
                         .format(ser.port, ser.baudrate))

            time.sleep(self.BOARD_RESET_TIMEOUT)

            ser.flush()

            while bool(result_line) is False:

                result = ser.write(bytes(read_command, 'utf8'))

                logging.info("sent: '{}' ({} bytes)".format(
                              read_command, result))

256
                time.sleep(self.BOARD_RESPONSE_DELAY)
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282

                result_line = ser.readline()

                logging.info("read: {} ({} bytes)".format(result_line,
                                                           len(result_line)))

                result_line = self._decode_bytes(result_line)
                if result_line is None:
                    logging.error("Unable to decode line as ASCII.")
                    logging.debug("Trying a new reading..")
                    continue

            ser.close()
            return result_line
        except KeyboardInterrupt:
            raise KeyboardInterrupt
        except Exception as e:
            logging.error("Unable to open serial port '{}'"
                          .format(serial_port))
            logging.error(e)
        finally:
            if ser:
                ser.close()
                logging.debug("serial closed")
        return None

Nelso Jost's avatar
Nelso Jost committed
283
284
285
    def sync_rtc(self, port_index=None):

        if isinstance(port_index, int):
286
            serial_port = self.CFG['ARDUINO']['SERIAL_PORT'][port_index]
Nelso Jost's avatar
Nelso Jost committed
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
        else:
            serial_port = self.SERIAL_PORTS[0]

        # if present, the board will be reseted
        ser = serial.Serial(serial_port, self.CFG['ARDUINO']['BAUD_RATE'],
                            timeout=self.SERIAL_READ_TIMEOUT, xonxoff=True)
        print("Serial open <port='{}', baudrate={}>"
              .format(ser.port, ser.baudrate))

        time.sleep(self.BOARD_RESET_TIMEOUT)

        ser.flush()

        command_ser = 'setrtc' + self.SERIAL_CSV_SEP + \
            datetime.now().strftime('%Y-%m-%d-%H-%M-%S'
                                    .replace('-', self.SERIAL_CSV_SEP))

        result = ser.write(bytes(command_ser, 'utf8'))

        print("sent: '{}' ({} bytes)".format(command_ser, result))

308
        time.sleep(self.BOARD_RESPONSE_DELAY)
Nelso Jost's avatar
Nelso Jost committed
309
310
311
312
313
314
315

        result_line = ser.readline()

        print("read: {} ({} bytes)".format(result_line, len(result_line)))

        ser.close()

316
317
318
319
    def get_serial(self):
        port_index = 0

        while True:
320
            serial_port = self.CFG['ARDUINO']['SERIAL_PORTS'][port_index]
321
322
323
324
325
326
327
328
329
330
331
332
333
334
            try:
                print("\n" + "="*60)
                print("Attempting serial connection at {}".format(serial_port))
                ser = serial.Serial(port=serial_port,
                                    baudrate=self.CFG['ARDUINO']['BAUD_RATE'],
                                    timeout=self.SERIAL_READ_TIMEOUT,
                                    xonxoff=True)

                print("Done! Check object 'ser'")
                return ser

            except:
                print("Unable do establish the connection.")

335
                if port_index < len(self.CFG['ARDUINO']['SERIAL_PORTS'])-1:
336
337
338
339
340
341
342
                    port_index += 1
                else:
                    port_index = 0

                print("Trying another port in about {} seconds.."
                      .format(self.FIND_PORT_TIMEOUT))
                time.sleep(self.FIND_PORT_TIMEOUT)
Nelso Jost's avatar
Nelso Jost committed
343

344
345
    def setup_logging(self):

346
347
348
349
350
351
352
        logging.basicConfig(
            level=logging.INFO,
            filename=self.SESSION_EXECUTION_LOG_FILENAME,
            format='%(asctime)s : %(levelname)s : %(message)s',
            datefmt='%Y-%m-%d %H:%M:%S')

        if self.verbose:
353
354
355
356
357
358
359
            root = logging.getLogger('')
            root.setLevel(logging.INFO)
            console = logging.StreamHandler()
            console.setFormatter(logging.Formatter(
                fmt='%(asctime)s : %(levelname)s : %(message)s',
                datefmt='%Y-%m-%d %H:%M:%S'))
            root.addHandler(console)
360
361
362
363
364

    def setup_files(self):
        session_datetime = datetime.now().strftime('%Y-%m-%d-%H-%M-%S')

        try:
labfis's avatar
labfis committed
365
            os.system('mkdir -p {}'.format(self.DATALOG_DIR))
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
        except Exception as e:
            print("Unable to create directory data/ to store datalog")
            print(e)
            return False

        self.SESSION_DATALOG_FILENAME = self.DATALOG_DIR \
            + 'datalog-' + session_datetime + '.csv'
        self.SESSION_OUTGOING_FILENAME = self.DATALOG_DIR \
            + 'outgoing/outgoing-' + session_datetime + '.json'
        self.SESSION_EXECUTION_LOG_FILENAME = self.EXECUTION_LOG_PATH \
            + 'execution-' + session_datetime + '.log'

        try:
            with open(self.SESSION_DATALOG_FILENAME, 'w') as f:
                f.write(self.DATALOG_CSV_SEP.join(
                    ['dt' + self.CFG['DATALOG']['DATETIME_FORMAT']] +
                    [x for x in self.CFG['LOGGER']['SENSORS']
                                if x != 'RTC_DS1307'])
                    + '\n')
        except Exception as e:
            print("Unable to write datalog file at data/")
            print(e)
            return False

        return True
391
392
393
394
395
396
397
398
399
400
401
402
403

    def run(self):
        '''
        Starts the logger main loop, which keeps reading data from the serial
        port and trying to send it to the server.

        Basically, the loop consists of the following steps:

            1. serial_read()     # send a string, recieves a string
            2. create_json()     # validate data and make it server-ready
            3. write_datalog()   # write current data on local file for backup
            4. send_to_server()  # try to send; if fails, save data for later
        '''
404
405
        if not self.setup_files():
            return
406
407
408
409
410
411
        self.setup_logging()
        logging.info('EXECUTION START')
        port_index = 0
        try:
            while True:
                logging.info('='*40)
412
                logging.debug('Attempting to serial connection')
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428

                csv_result = self.serial_read(port_index)

                if csv_result is not None:
                    logging.debug('-'*40)
                    logging.debug('Attempting create valid JSON data')
                    json_data = self.create_json(csv_result)

                    logging.debug('-'*40)
                    logging.debug('Attempting to write local data log')
                    self.write_datalog(json_data)

                    logging.debug('-'*40)
                    logging.debug('Attempting to send data to the server')
                    self.send_to_server(json_data)
                else:
429
                    if port_index < len(self.CFG['ARDUINO']['SERIAL_PORTS'])-1:
430
431
432
433
                        port_index += 1
                    else:
                        port_index = 0

434
                    logging.info("Trying another port in about {} seconds.."
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
                                 .format(self.FIND_PORT_TIMEOUT))
                    time.sleep(self.FIND_PORT_TIMEOUT)
                    continue

                logging.debug('-'*40)
                logging.info("Going to sleep now for {days} days, {hours} "
                             "hours, {minutes} minutes and {seconds} seconds.."
                             .format(**self.CFG['LOGGER']['INTERVAL']))

                time.sleep(self.READING_INTERVAL_SECONDS)

        except KeyboardInterrupt:
            logging.info('KeyboardInterrupt: EXECUTION FINISHED')
            pass