Skip to content

Commit 6841faf

Browse files
committed
refs #5 - use blocking reads instead of polling with sleeps to save CPU cycles
1 parent a3bd5af commit 6841faf

File tree

1 file changed

+14
-16
lines changed

1 file changed

+14
-16
lines changed

certabo/serialreader.py

+14-16
Original file line numberDiff line numberDiff line change
@@ -54,10 +54,13 @@ def __init__ (self, handler, device='auto'):
5454
self.device = device
5555
self.connected = False
5656
self.handler = handler
57-
self.serial_out = queue.Queue()
57+
self.uart = None
5858

5959
def send_led(self, message: bytes):
60-
self.serial_out.put(message)
60+
# logging.debug(f'Sending to serial: {message}')
61+
if self.connected:
62+
return self.uart.write(message)
63+
return None
6164

6265
def run(self):
6366
while True:
@@ -73,27 +76,28 @@ def run(self):
7376
time.sleep(1)
7477
continue
7578
logging.info(f'Opening serial port {serialport}')
76-
uart = serial.Serial(serialport, 38400, timeout=2.5) # 0-COM1, 1-COM2 / speed /
79+
self.uart = serial.Serial(serialport, 38400) # 0-COM1, 1-COM2 / speed /
80+
# self.uart = serial.Serial(serialport, 38400, timeout=2.5) # 0-COM1, 1-COM2 / speed /
7781
if os.name == 'posix':
7882
logging.debug(f'Attempting to lock {serialport}')
79-
fcntl.flock(uart.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
83+
fcntl.flock(self.uart.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
8084
logging.debug(f'Flushing input on {serialport}')
81-
uart.flushInput()
82-
uart.write(b'U\xaaU\xaaU\xaaU\xaa')
85+
self.uart.flushInput()
86+
self.uart.write(b'U\xaaU\xaaU\xaaU\xaa')
8387
time.sleep(1)
84-
uart.write(b'\xaaU\xaaU\xaaU\xaaU')
88+
self.uart.write(b'\xaaU\xaaU\xaaU\xaaU')
8589
time.sleep(1)
86-
uart.write(b'\x00\x00\x00\x00\x00\x00\x00\x00')
90+
self.uart.write(b'\x00\x00\x00\x00\x00\x00\x00\x00')
8791
self.connected = True
8892
except Exception as e:
8993
logging.info(f'ERROR: Cannot open serial port {serialport}: {str(e)}')
9094
self.connected = False
9195
time.sleep(0.1)
9296
else:
9397
try:
94-
while uart.inWaiting():
98+
while True:
9599
# logging.debug(f'serial data pending')
96-
raw_message = uart.readline()
100+
raw_message = self.uart.readline()
97101
try:
98102
message = raw_message.decode("ascii")[1: -3]
99103
#if DEBUG:
@@ -103,12 +107,6 @@ def run(self):
103107
message = ""
104108
except Exception as e:
105109
logging.info(f'Exception during message decode: {str(e)}')
106-
time.sleep(0.001)
107-
if not self.serial_out.empty():
108-
data = self.serial_out.get()
109-
self.serial_out.task_done()
110-
# logging.debug(f'Sending to serial: {data}')
111-
uart.write(data)
112110
except Exception as e:
113111
logging.info(f'Exception during serial communication: {str(e)}')
114112
self.connected = False

0 commit comments

Comments
 (0)