Add Python script for logging.
[toast/airingbutler.git] / log_mhz19.py
1 import argparse
2 import asyncio
3 import logging
4
5 import serial_asyncio  # pyserial-asyncio Debian: python3-serial-asyncio
6
7
8 log = logging.getLogger(__name__)
9
10
11 class LineBuffer:
12     def __init__(self):
13         self.buffer = ''
14
15     def write(self, data: bytes):
16         self.buffer += data.decode()
17
18
19 class Receiver(asyncio.Protocol):
20     def __init__(self):
21         self.transport = None
22
23     def connection_made(self, transport):
24         self.transport = transport
25         log.debug('port opened')
26
27     def data_received(self, data):
28         data = data.decode()
29         print(data, end='')
30
31     def connection_lost(self, exc):
32         log.debug('port closed')
33         self.transport.loop.stop()
34
35
36 def main():
37     parser = argparse.ArgumentParser('Logs CO2 and temperature from MH-Z19B sensor.')
38     parser.add_argument('--device', '-d', default='/dev/ttyACM0', help='Device where Arduino is connected to')
39     args = parser.parse_args()
40     logging.basicConfig(level=logging.INFO, format='%(asctime)-15s %(message)s')
41     loop = asyncio.get_event_loop()
42     coro = serial_asyncio.create_serial_connection(loop, Receiver, args.device, baudrate=115200)
43     loop.run_until_complete(coro)
44     loop.run_forever()
45     loop.close()
46
47
48 if __name__ == '__main__':
49     main()