forked from platypush/platypush
Preventing inconsistent reads from the serial port by making sure that only one reader can read at the time
This commit is contained in:
parent
0b4cfec8e7
commit
26a57c9d6f
1 changed files with 26 additions and 11 deletions
|
@ -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,6 +89,11 @@ 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
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
data = None
|
||||||
|
|
||||||
|
try:
|
||||||
|
serial_available = self.serial_lock.acquire(timeout=2)
|
||||||
|
if serial_available:
|
||||||
try:
|
try:
|
||||||
ser = self._get_serial()
|
ser = self._get_serial()
|
||||||
except:
|
except:
|
||||||
|
@ -99,6 +107,13 @@ class SerialPlugin(GpioSensorPlugin):
|
||||||
except:
|
except:
|
||||||
self.logger.warning('Invalid JSON message from {}: {}'.
|
self.logger.warning('Invalid JSON message from {}: {}'.
|
||||||
format(self.device, data))
|
format(self.device, data))
|
||||||
|
else:
|
||||||
|
data = self.last_measurement
|
||||||
|
finally:
|
||||||
|
self.serial_lock.release()
|
||||||
|
|
||||||
|
if data:
|
||||||
|
self.last_measurement = data
|
||||||
|
|
||||||
return data
|
return data
|
||||||
|
|
||||||
|
|
Loading…
Reference in a new issue