I'm working on a CAN reader that uses asyncio. My problem is that right now I'm stuck in an infinite loop when I use the async loop. What I want is that the async loop runs in a thread in the background while the main loop is working on other things. (it also reads data from the serialport etc). When I'm trying to use the Thread the program gets stuck and doesn't do anything.
How do i correctly put a asyncio in a thread?
import asyncio
import platform
import threading
import can
class CanModule:
"""[initialization of the CAN port and starting a thread to recieve CAN messages]
Args:
channel ([String]): [Name of the channel used, has a specific format e.g. "PCAN_USBBUS1"]
baudrate ([String]): [A string of a logical baudrate number]
"""
def __init__(self, channel, baudrate):
global interface
self.parserList = []
os = platform.system()
if os == 'Windows':
interface = 'pcan'
if os == 'Linux':
interface = 'socketcan'
# noinspection PyTypeChecker
self.canBus = can.interface.Bus(interface=interface, channel=channel, bitrate=baudrate)
self.canBus.RECV_LOGGING_LEVEL = 0
self.buffer = can.BufferedReader()
self.notifier = can.Notifier(self.canBus, [self.buffer])
asyncio.run(self.getCanMessage())
#self.canThread = threading.Thread(target=loop.run_forever(), daemon=True).start()
def addParser(self, parser):
"""[adding the device's CAN parser to the parser list]
Args:
parser ([CanParser]): [CAN parser object used to parse the CAN message data]
"""
self.parserList.append(parser)
async def getCanMessage(self):
"""[Getting a CAN message from the bus and checking to which device is belongs to.
If the message ID is found in the list the message is sent to the can parser to be parsed]
"""
while True:
msg = self.buffer.get_message()
if msg is not None:
for parser in self.parserList:
# splitting the tuples in the ID list, only the 2nd list is used.
# Iteration over a list is easier than over a tuple list
messageID, canID = zip(*parser.idList)
if msg.arbitration_id in canID:
parser.parse(msg)