使用websockets和另一个线程发送消息,没有运行时警告:协程'WebSocketCommonProtocol.send'从未等待过



Am试图在另一个线程中使用websocket客户端以json字符串发送运动传感器数据,以避免MotionSensor类中的无限循环对其余代码的执行阻塞。但显然CCD_ 1需要等待关键字。如果我把它加进去,我会得到一个错误

RuntimeWarning:从未等待协同程序"MotionSensors.run"self.run((RuntimeWarning:启用tracemalloc以获取对象分配回溯并且它不会向服务器发送任何信息

# motionSensor.py
import threading
import time
from client.ClientRequest import Request

class MotionSensors(threading.Thread):
def __init__(self, ws):
threading.Thread.__init__(self)
self.ws = ws
self.open = True
async def run(self):
await self.SendData()
async def SendData(self):
while self.open:
print("Sending motion state....")
state = 1 # Motion state demo value
request = Request()
request.push("mcu/sensors/motion")
request.addBody({
"state_type": "single",
"devices": {"state": state, "device_no": "DVC-876435"}
})
await self.ws.send(request.getAsJsonString())
print("sleeping now for 2 seconds....")
time.sleep(2)

这是我的主要代码客户.py

# client.py
import settings
import asyncio
import websockets
from client.ClientHandler import Devices
from client.Rounte import Route
from ClientRequest import Request
from client.dbHandler import mcuConfig
from client.devices.motionSensor import MotionSensors
def ResponseMSG(request):
print(request)
route = Route()
route.addRoute("/response", ResponseMSG)

def onMessage(request):
route.fireRequest(request)
async def WsClient():
uri = settings.WS_URL
async with websockets.connect(uri) as websocket:
#####################################
###INITIALIZE DEVICES
motion = MotionSensors(websocket)
motion.start()
while True:
print("waiting to recieve......")
message = await websocket.recv()
onMessage(message)
loop = asyncio.get_event_loop()
loop.run_until_complete(WsClient())
loop.run_forever()

伙计们,我需要你们的帮助,用while循环在另一个线程中发送数据,而不会阻止代码的执行,也不会出错。提前感谢

实际上我更改了motionSensor.py的代码我创建了一个新的事件循环,并将其设置为新线程它甚至适用于那些使用python 3.7及以下版本的用户。它是有效的。感谢@user4815162342

# motionSensor.py
import threading
import time
import asyncio
from client.ClientRequest import Request
class MotionSensor(threading.Thread):
def __init__(self, ws):
threading.Thread.__init__(self)
self.loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
self.ws = ws
self.open = True
def run(self):
self.loop.run_until_complete(self.SendData())
# @asyncio.coroutine
async def SendData(self):
while True:
print("Sending motion state....")
state = 0
request = Request()
request.push("mcu/sensors/motion")
request.addBody({
"state_type": "single",
"devices": {"state": state, "device_no": "DVC-876435"}
})
await self.ws.send(request.getAsJsonString())
print("sleeping now for 5 seconds....")
time.sleep(5)

最新更新