我还没有很好地理解异步功能,我需要澄清。我已经检查过这个代码是否有效:
from asyncio import get_event_loop
from serial_asyncio import open_serial_connection
async def main():
reader, writer = await open_serial_connection(url='COM10', baudrate=115200)
while True:
line = await reader.readline()
print(str(line, 'utf-8'))
asyncio.run(main())
基本上连接已经建立,我看到来自串行端口的消息,但这不是我所期望的。我想从串行开始采集,同时我想继续在我的代码中做其他事情。
基本上类似于scapy中的
t = AsyncSniffer()
t.start()
print("Acquisition started")
wait (10)
t.stop()
我也尝试过使用这样的线程选项:
import serial
import threading
global stop_threads
import time
stop_threads=False
def thread_function_1():
ser = serial.Serial('COM1',115200)
while thread_function_1():
line=ser.readline()
if line:
string=line.decode()
print(string)
if stop_threads==true:
ser.close()
break
print ('print_1')
x= threading.Thread(name = "thread_function_1", target = thread_function_1)
x.start()
time.sleep(100)
stop_threads = True
print ('print_2')
x.join()
我得到了这个错误,我无法解决:
Traceback (most recent call last):
File "C:UsersSIMAppDataLocalProgramsPythonPython38libthreading.py", line 932, in _bootstrap_inner
self.run()
File "C:UsersSIMAppDataLocalProgramsPythonPython38libthreading.py", line 870, in run
self._target(*self._args, **self._kwargs)
File "C:pythonconnessione_seriale.py", line 31, in thread_function_1
while thread_function_1():
File "C:pythonconnessione_seriale.py", line 14, in thread_function_1
ser = serial.Serial('COM1',115200)
File "C:UsersSIMAppDataLocalProgramsPythonPython38libsite-packagesserialserialwin32.py", line 33, in __init__
super(Serial, self).__init__(*args, **kwargs)
File "C:UsersSIMAppDataLocalProgramsPythonPython38libsite-packagesserialserialutil.py", line 244, in __init__
self.open()
File "C:UsersSIMAppDataLocalProgramsPythonPython38libsite-packagesserialserialwin32.py", line 64, in open
raise SerialException("could not open port {!r}: {!r}".format(self.portstr, ctypes.WinError()))
serial.serialutil.SerialException: could not open port 'COM1': PermissionError(13, 'Access is denied.', None, 5)
COM1是可用的。我试着用油灰把它打开,效果很好。
这就是我找到的解决方案。我在一个类中使用了一个线程,以便在需要时启动/停止串行采集。
class ThreadTest:
def seriale(self, n):
ser = serial.Serial('COM9', 115200, timeout=1)
time.sleep(2)
with open('C:/python/test.txt', 'w') as output:
if self._running==False:
ser.close()
while self._running and n > 0:
line = ser.readline()
#print (line)
n -= 1
if line:
# Converting Byte Strings into unicode strings
string = line.decode()
#print (string)
output.write(string)
def terminate(self):
self._running = False
def __init__(self):
self._running = True
c = ThreadTest()
t1 = Thread(target=c.seriale, args=(10,)) #10 are the seconds of the acquisition via serial and can be replaced
t1.start() # start of the serial acquisition
time.sleep(10)# here the sleep can be replaced with code
c.terminate()