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