![](/img/trans.png)
[英]serial_asyncio: read serial port into a queue and read that queue from main() not working
[英]How to pass serial_asyncio between async tasks
我需要在 2 個異步任務之間從 serial_asyncio 傳遞讀取器和寫入器,第一個任務是讀取用戶鍵盤輸入,當用戶按 x 時,function 將信息發送到 Arduino,第二個任務讀取來自 Arduino 的響應並為特定響應做一些事情
代碼:
import warnings
import serial
import serial.tools.list_ports
import requests
import json
import asyncio
import keyboard
import time
from serial_asyncio import open_serial_connection
with open("config.json") as config:
cfg = json.load(config)
config.close()
headers = {'Accept': 'application/json'}
url = f"""https://{cfg["web"]}/login?username={cfg["user"]}&password={cfg["password"]}"""
get_token = requests.post(url, headers=headers)
token = get_token.json()
my_token = token["token"]
arduino_ports = [
p.device
for p in serial.tools.list_ports.comports()
if p.manufacturer and 'Arduino' in p.manufacturer
]
if not arduino_ports:
raise IOError("No Arduino found")
if len(arduino_ports) > 1:
warnings.warn("Multiple arduinos, select first")
async def arduino_listen(cfg, headers, reader):
print('arduino_listen task created')
while True:
await asyncio.sleep(0.1)
info = await reader.readline()
print('arduino respond:', info)
if "good" in str(info):
print('good from arduino')
if "bad" in str(info):
print('bad from arduino')
async def arduino_writer(cfg, headers, writer):
print('arduino_writer task created')
keypress = False
key = 'x'
while True:
if keypress and not keyboard.is_pressed(key):
print('x pressed on keyboard, send 5')
writer.write(b'5')
await asyncio.sleep(0.3)
keypress = False
elif keyboard.is_pressed(key) and not keypress:
keypress = True
async def serial():
print(f'serial task created, arduino port {arduino_ports[0]} selected')
reader, writer = await open_serial_connection(url=arduino_ports[0], baudrate=115200)
#reader, writer = await open_serial_connection(url=arduino_ports[0], baudrate=115200)
loop = asyncio.get_event_loop()
loop.create_task(serial())
loop.create_task(arduino_listen(cfg, headers, reader))
loop.create_task(arduino_writer(cfg, headers, writer))
loop.run_forever()
我的問題是,如何將連接從串行 function 任務傳遞到 arduino_listen 和 arduino_writer 任務,我嘗試在 loop.create_task 之前添加reader, writer = await open_serial_connection(url=arduino_ports[0], baudrate=115200)
但出現意外錯誤
避免提供與您的模塊名稱沖突的函數名稱,在您的情況下它是關於serial
的。 我們稱它為start_serial
。
由於start_serial
是啟動串行連接的初始function arduino_listen
和arduino_writer
應該在它之后並行運行。
將代碼的最后部分更改為以下內容:
async def start_serial():
print(f'serial task created, arduino port {arduino_ports[0]} selected')
reader, writer = await open_serial_connection(url=arduino_ports[0], baudrate=115200)
return reader, writer
async def main():
reader, writer = await start_serial()
await asyncio.gather(
arduino_listen(cfg, headers, reader),
arduino_writer(cfg, headers, writer))
asyncio.run(main())
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.