-
Notifications
You must be signed in to change notification settings - Fork 14
/
radio_transceiver.py
46 lines (39 loc) · 1.32 KB
/
radio_transceiver.py
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
import os
import serial
import json
from .utils import get_logger, get_serial_stream
class Transceiver:
def __init__(self, log_file_name=None, port=None):
if log_file_name is None:
self.logging = get_logger("TRANSMITTER_LOG_FILE")
else:
self.logging = get_logger(log_file_name)
port = os.environ["RADIO_TRANSMITTER_PORT"] if port is None else port
baudrate = 9600
parity = serial.PARITY_NONE
stopbits = serial.STOPBITS_ONE
bytesize = serial.EIGHTBITS
timeout = 1
self.logging.info("Opening serial")
self.serial = serial.Serial(
port=port,
baudrate=baudrate,
parity=parity,
stopbits=stopbits,
bytesize=bytesize,
timeout=timeout,
)
def send(self, payload):
self.logging.info("sending")
self.serial.write(get_serial_stream(payload))
self.logging.info(payload)
def listen(self):
payload = self.serial.readline().decode("utf-8")
message = "Error: Check logs"
if payload != "":
try:
message = json.loads(payload)
self.logging.info(message)
except json.JSONDecodeError:
self.logging.error(json.JSONDecodeError)
return message