Preventing inconsistent reads from the serial port by making sure that only one reader can read at the time

This commit is contained in:
Fabio Manganiello 2018-07-20 15:54:27 +02:00
parent 0b4cfec8e7
commit 26a57c9d6f

View file

@ -1,5 +1,6 @@
import json import json
import serial import serial
import threading
import time import time
from platypush.plugins import Plugin, action from platypush.plugins import Plugin, action
@ -30,6 +31,8 @@ class SerialPlugin(GpioSensorPlugin):
self.device = device self.device = device
self.baud_rate = baud_rate self.baud_rate = baud_rate
self.serial = None self.serial = None
self.serial_lock = threading.Lock()
self.last_measurement = None
def _read_json(self, serial_port): def _read_json(self, serial_port):
@ -86,19 +89,31 @@ class SerialPlugin(GpioSensorPlugin):
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
""" """
try: data = None
ser = self._get_serial()
except:
time.sleep(1)
ser = self._get_serial(reset=True)
data = self._read_json(ser)
try: try:
data = json.loads(data) serial_available = self.serial_lock.acquire(timeout=2)
except: if serial_available:
self.logger.warning('Invalid JSON message from {}: {}'. try:
format(self.device, data)) ser = self._get_serial()
except:
time.sleep(1)
ser = self._get_serial(reset=True)
data = self._read_json(ser)
try:
data = json.loads(data)
except:
self.logger.warning('Invalid JSON message from {}: {}'.
format(self.device, data))
else:
data = self.last_measurement
finally:
self.serial_lock.release()
if data:
self.last_measurement = data
return data return data