python - pyserial 线程挂在 serial.in_waiting() 语句上
问题描述
我有一个 pyserial 线程挂在一个意想不到的地方;检查串行端口的排队字节。所有串行输入都在这个线程中完成;main 主要是显示管理器。init执行得很好,一旦在 run 子例程中,它就会挂在语句“Trace('In_waiting={}'.format(self.serial.in_waiting()))”处。main 不是 cpu hog - 它更新显示然后等待 1.0 秒 - 该代码已调试好(天真的程序员说 ;-))。尽管有 GPIO 引脚的回调,但没有其他线程。输入来自 RasPi UART 引脚。
将代码挂在这个位置对我来说毫无意义。我已经尝试过使用各种超时值,包括 None 和 0。文档似乎清楚地表明返回 0 或 n 是唯一的选项。我可能遗漏了一些明显的东西,但它让我望而却步。
class Monitor_PE_Devices_Thread(threading.Thread):
# Thread to monitor all of the PE devices. All updating of the device_list items occurs
# here.
def __init__(self):
global device_list
threading.Thread.__init__(self)
Log.Debug('PE Monitoring thread initialized')
self.buffer = ''
self.port = '/dev/ttyAMA0'
self.speed = 9600
self.serial = serial.Serial(port=self.port, baudrate=self.speed, timeout=0.5)
if self.serial.is_open: Trace('Serial port {} opened'.format(self.serial.name))
Log.Debug('Monitoring the following devices:')
for d in device_list:
Log.Debug(' DevID[{}]: Name={}'.format(d, device_list[d][0]))
def process_PE_response(self, devid, data): <block compressed>
def read_line(self): <block compressed>
def run(self):
# Main loop for PE device monitoring
global kill_threads, device_list
Log.Debug('PE Monitoring thread started')
while not kill_threads:
Trace('Top of read serial loop')
Trace('Port status={}'.format(self.serial.is_open))
Trace('In_waiting={}'.format(self.serial.in_waiting()))
if self.serial.in_waiting() > 0:
line = self.read_line()
if len(line) > 0 and line[0] == 'a':
devid = line[1:3]
data = line[3:]
Trace('Data recieved for dev[{}]: {}'.format(devid, data))
dev = device_list.get(devid, None)
if dev != None:
device_list[devid][3] = utcnow()
self.process_PE_response(devid, data)
else:
Log.Debug('Unknown device id {} - ignored'.format(devid))
else:
Log.Info('Invalid serial data: {}'.format(line))
环境:python 3、pyserial 3、树莓派 3、Buster Lite、pygame
解决方案
在 pySerial 3.0 中,in_waiting
是一个属性,而不是一个方法。
因此,当您使用 时self.serial.in_waiting()
,Python 应该引发 a TypeError
,因为in_waiting
in 的值int
不是可调用的。
一个小例子:
In [5]: class Test:
...: def __init__(self, a):
...: self._a = a
...:
...: @property
...: def a(self):
...: return self._a
...:
In [6]: t = Test(2)
Out[6]: <__main__.Test at 0x8042660d0>
In [7]: t.a
Out[7]: 2
In [8]: t.a()
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-8-47b4c8d89978> in <module>
----> 1 t.a()
TypeError: 'int' object is not callable
可能是您的程序似乎挂起,因为这发生在另一个线程中。
一个未处理的异常应该终止Monitor_PE_Devices_Thread.run()
。
Monitor_PE_Devices_Thread
在您的主线程中,如果仍然使用其is_alive()
方法运行,则更新显示测试。
推荐阅读
- django - 如果我使用 forms.Form,我可以指定实例参数吗?
- csv - 如何在 Python 3 中使用带有 tkinter 的 GUI 从 Excel 文件中探索数据
- ansible - 在循环中设置注册变量并将其用于另一个角色
- typescript - 从对象属性设置变量的类型
- c++ - 将多个纹理OpenGL绑定到不同的四边形
- java - 在 IntelliJ 中使用 JDK 的本地文档
- flutter - 如何在底板模态中创建 ARC 形状?
- python - 我无法从全局 process.stdout.on 获取数据
- javascript - React 中的条件导航渲染
- url - 什么是最常用的 URL 参数?