Skip to content

Commit

Permalink
Update serial_pm.py
Browse files Browse the repository at this point in the history
In Home Assistant Particulate Matter result was inconsistent in time. It was because serial device is open once, so data from sensor was collected by system in device buffer and slowly read from it. So results was "extended" in time. So added here is cleaning input buffer before next read of PM value. Additionally during research was added check sum control for PLANTOWER1 config.
  • Loading branch information
noisyfly committed Oct 29, 2017
1 parent 839759d commit d9725ed
Showing 1 changed file with 21 additions and 1 deletion.
22 changes: 21 additions & 1 deletion pmsensor/serial_pm.py
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,8 @@ def __init__(self,
baudrate=configuration[BAUD_RATE],
parity=serial.PARITY_NONE,
stopbits=serial.STOPBITS_ONE,
bytesize=serial.EIGHTBITS)
bytesize=serial.EIGHTBITS,
timeout=0.1)

# Update date in using a background thread
if self.scan_interval > 0:
Expand Down Expand Up @@ -163,6 +164,12 @@ def read_data(self):
finished = False
sbuf = bytearray()
starttime = time.time()
checkCode = int(0);
expectedCheckCode = int()
#it is necessary to reset input buffer because data is cotinously received by the system and placed in the device buffer when serial is open.
#But "Home Assistant" code read it only from time to time so the data we read here would be placed in the past.
#Better is to clean the buffer and read new data from "present" time.
self.ser.reset_input_buffer()
while not finished:
mytime = time.time()
if mytime - starttime > self.timeout:
Expand All @@ -182,6 +189,19 @@ def read_data(self):
sbuf = sbuf[1:]

if len(sbuf) == self.record_length:
#Check the control sum if it is known how to do it
if self.config == PLANTOWER1:
for c in sbuf[0:(self.record_length-2)]:
checkCode += c
expectedCheckCode = sbuf[30]*256 + sbuf[31]
if checkCode != expectedCheckCode:
#because of data inconsistency clean the buffer
LOGGER.error("PM sensor data sum error %d, expected %d", checkCode, expectedCheckCode)
sbuf = []
checkCode = 0
continue

#if it is ok then send it for interpretation
res = self.parse_buffer(sbuf)
LOGGER.debug("Finished reading data %s", sbuf)
finished = True
Expand Down

0 comments on commit d9725ed

Please sign in to comment.