2016-07-07 65 views
0

我在树莓派上运行websocket-client来控制使用跳跃运动websocket服务器发送的数据的伺服器。通过跳跃运动通过websocket连接发送的数据量非常大,以致于在捕捉到最近的消息时会有很长的延迟,而最近的消息在运行时间越长时越糟。python websocket-client,只接收队列中最近的消息

如何丢弃队列中的所有旧消息,并在检查时只使用最新的消息?目前,我这样做是:由于大跃进服务发送数据每秒大约110帧

ws = create_connection("ws://192.168.1.5:6437") 
    while True: 
     result = ws.recv() 
     resultj = json.loads(result) 
     if "hands" in resultj and len(resultj["hands"]) > 0: 
       # print resultj["hands"][0]["palmNormal"] 
       rotation = math.atan2(resultj["hands"][0]["palmNormal"][0], -resultj["hands"][0]["palmNormal"][1]) 
       dc = translate(rotation, -1, 1, 5, 20) 
       pwm.ChangeDutyCycle(float(dc)) 
+0

你需要一个线程接收到本地队列和线程来处理从队列中的最新消息(丢弃所有其他人)。 – barny

+0

另一个线程是否会遇到同样的问题,并且在websocket消息的队列的前端不会出现问题? – Tom

+0

当你做了recv,在行动之前,你可以测试看看是否有另一条消息,全部阅读并操作最后一条消息? – barny

回答

1

,您对9ms至做任何处理。如果你超过这个,那么你会落后。最简单的解决方案可能是创建一个人为的应用程序帧速率。对于每个循环,如果您还没有到达下一次更新的时间,那么您只需获取下一条消息并放弃它。

ws = create_connection("ws://192.168.1.5:6437") 
allowedProcessingTime = .1 #seconds 
timeStep = 0 
while True: 
    result = ws.recv() 
    if time.clock() - timeStep > allowedProcessingTime: 
     timeStep = time.clock() 
     resultj = json.loads(result) 
     if "hands" in resultj and len(resultj["hands"]) > 0: 
       # print resultj["hands"][0]["palmNormal"] 
       rotation = math.atan2(resultj["hands"][0]["palmNormal"][0], -resultj["hands"][0]["palmNormal"][1]) 
       dc = translate(rotation, -1, 1, 5, 20) 
       pwm.ChangeDutyCycle(float(dc)) 
     print "processing time = " + str(time.clock() - timeStep) #informational 

(我还没有运行这个修改你的代码,所以通常的警告也适用)