python websocketclient,只接收queu中最新的消息

2024-10-03 09:13:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我在raspberry pi上运行websocket客户机,使用leap motion websocket服务器发送的数据控制伺服。跳跃运动通过websocket连接发送的数据量非常大,以至于pi要赶上最新的消息会有很长的延迟,而这种延迟只会随着运行时间的延长而变得更糟。在

如何丢弃队列中的所有旧消息,而在检查时只使用最新的消息?目前我正在做这个:

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))

Tags: 消息客户机wspiresultdcraspberryleap
1条回答
网友
1楼 · 发布于 2024-10-03 09:13:55

由于Leap服务以大约每秒110帧的速度发送数据,因此您有大约9毫秒的时间进行任何处理。如果你超过这个,你就会落后。最简单的解决方案可能是创建一个人工的应用程序帧速率。对于每个循环,如果您还没有到达下一次更新的时间,那么您只需获取下一条消息并丢弃它。在

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

(我还没有对您的代码运行此修改,因此通常的注意事项适用)

相关问题 更多 >