Optimized serial plugin

This commit is contained in:
Fabio Manganiello 2018-07-17 23:47:13 +02:00
parent 791ac269b6
commit 5bc7319933
2 changed files with 25 additions and 10 deletions

View file

@ -64,11 +64,6 @@ class SensorBackend(Backend):
elif new_data[measure] < threshold and (self.data is None or ( elif new_data[measure] < threshold and (self.data is None or (
measure in self.data and self.data[measure] >= threshold)): measure in self.data and self.data[measure] >= threshold)):
data_below_threshold[measure] = new_data[measure] data_below_threshold[measure] = new_data[measure]
else:
if new_data > threshold and (self.data is None or self.data <= threshold):
data_above_threshold = new_data
elif new_data < threshold and (self.data is None or self.data >= threshold):
data_below_threshold = new_data
if data_below_threshold: if data_below_threshold:
self.bus.post(SensorDataBelowThresholdEvent(data=data_below_threshold)) self.bus.post(SensorDataBelowThresholdEvent(data=data_below_threshold))

View file

@ -28,6 +28,7 @@ class SerialPlugin(GpioSensorPlugin):
self.device = device self.device = device
self.baud_rate = baud_rate self.baud_rate = baud_rate
self.serial = None
def _read_json(self, serial_port): def _read_json(self, serial_port):
@ -59,18 +60,37 @@ class SerialPlugin(GpioSensorPlugin):
return output.decode().strip() return output.decode().strip()
def _get_serial(self, reset=False):
if self.serial:
if not reset:
return self.serial
self._close_serial()
self.serial = serial.Serial(self.device, self.baud_rate)
return self.serial
def _close_serial(self):
if self.serial:
try:
self.serial.close()
self.serial = None
except Exception as e:
self.logger.warning('Error while closing serial communication: {}')
self.logger.exception(e)
@action @action
def get_measurement(self): def get_measurement(self):
""" """
Reads JSON data from the serial device and returns it as a message Reads JSON data from the serial device and returns it as a message
""" """
ser = serial.Serial(self.device, self.baud_rate)
try: try:
ser = self._get_serial()
except:
ser = self._get_serial(reset=True)
data = self._read_json(ser) data = self._read_json(ser)
finally:
ser.close()
try: try:
data = json.loads(data) data = json.loads(data)