我正在努力让我的websocket脚本和I / O串行脚本同时运行。
在继续之前,请提供一些基本信息:
- 我正在使用Windows PC(无法访问linux PC)
- 这就是为什么我使用AIOserial库而不是pyserial-asyncio的原因
- 我没有使用asyncio的“超级”经验,请保持友好:)
这是我的“旧”网络套接字脚本:
from aiohttp import web
import socketio
import aiohttp_cors
import asyncio
import random
# creates a new Async Socket IO Server
sio = socketio.AsyncServer()
# Creates
app = web.Application()
sio.attach(app)
server_is_responding = "Message from the server:"
the_response = "Hello there!"
async def index(request):
with open('index.html') as f:
print("Somebody entered the server from the browser!")
return web.Response(text=f.read(),content_type='text/html')
@sio.on("android-device")
async def message(sid,data):
print("message: ",data)
#return send_message_to_client()
@sio.on('sendTextToServer')
async def message(sid,data)
if data == "hei":
await sio.emit("ServerMessage",{"hehe"})
if data == "lol":
await sio.emit("ServerMessage",{"Message from server:": "hehe,funny right?.."})
else:
await sio.emit("ServerMessage",{"Message from server:": "Hello There!"})
# We bind our aiohttp endpoint to our app
# router
cors = aiohttp_cors.setup(app)
app.router.add_get('/',index)
# We kick off our server
if __name__ == '__main__':
web.run_app(app)
这是我的I / O串行脚本(可以读取数据),我正在尝试将其与上述某些websocket函数一起使用:
import asyncio
import websockets
import socketio
import aiohttp_cors
import logging
from AIOExtensions.AIOSerial import (AIOSerial,AIOSerialClosedException,AIOSerialErrorException,AIOSerialNotOpenException)
logging.basicConfig(level=logging.DEBUG)
sio = socketio.AsyncServer()
async def hello(websocket,path):
name = await websocket.recv()
print(f"< {name}")
greeting = f"Hello {name}!"
await websocket.send(greeting)
print(f"> {greeting}")
@sio.on("android-device")
async def message(sid,data)
async def read_IO_serial():
try:
async with AIOSerial('COM8',baudrate=115200,line_mode=True) as aios:
await asyncio.sleep(100)
try:
while True:
# read with timeout
rcvd = await asyncio.wait_for(aios.read(),timeout=1.0)
# print the data received
print(f"data received: {rcvd}")
if rcvd == b'RF initialized\n':
print("CATCHED THIS LINE!")
except asyncio.TimeoutError:
print("reception timed out ;-(")
except AIOSerialNotOpenException:
print("Unable to open the port!")
print()
print("Have you specified the right port number? COM7? COM8?")
# port fatal error
except AIOSerialErrorException:
print("Port error!")
# port already closed
except AIOSerialClosedException:
print("Serial port is closed!")
start_server = websockets.serve(hello,"http://192.168.1.6",8080)
#sio.attach(start_server) # HOW CAN I ATTACH THIS SO IT CAN BE USED WITH THE SIO FUNCTIONS BELOW?
if start_server:
print("Server started!")
asyncio.run(read_IO_serial())
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
正如您在我的第一个简单的websocket脚本中看到的那样,我可以使用“ sio.attach(app)”,它可以列出来自客户端的事件,因此我需要一种方法来替换当前的“ app”脚本..
有人可以帮助我吗?