我正在编写一个 Python 程序来与基于 CAN 总线的设备进行交互。为此,我成功地使用了 python-can 模块。我还使用 asyncio 来响应异步事件。我编写了一个“CanBusSequencer”类使用的“CanBusManager”类。“CanBusManager”类负责生成/发送/接收消息,CanBusSequencer 驱动要发送的消息序列。
在序列中的某个时刻,我想等到收到特定消息以“解锁”序列中要发送的剩余消息。代码概述:
主文件
async def main():
event = asyncio.Event()
sequencer = CanBusSequencer(event)
task = asyncio.create_task(sequencer.doSequence())
await task
asyncio.run(main(), debug=True)
canBusSequencer.py
from canBusManager import CanBusManager
class CanBusSequencer:
def __init__(self, event)
self.event = event
self.canManager = CanBusManager(event)
async def doSequence(self):
for index, row in self.df_sequence.iterrows():
if:...
self.canManager.sendMsg(...)
else:
self.canManager.sendMsg(...)
await self.event.wait()
self.event.clear()
canBusManager.py
import can
class CanBusManager():
def __init__(self, event):
self.event = event
self.startListening()
**EDIT**
def startListening(self):
self.msgNotifier = can.Notifier(self.canBus, self.receivedMsgCallback)
**EDIT**
def receivedMsgCallback(self, msg):
if(msg == ...):
self.event.set()
现在我的程序仍然等待 self.event.wait(),即使收到了相关消息并执行了 self.event.set()。使用 debug = True 运行程序会显示一个
RuntimeError: Non-thread-safe operation invoked on an event loop other than the current one
我真的不明白。它与异步事件循环有关,不知何故没有正确定义/管理。我来自 C++ 世界,目前正在用 Python 编写我的第一个大型程序。任何指导将不胜感激:)