python websocket-client,只接收队列中的最新消息 [英] python websocket-client, only receive most recent message in queue

查看:99
本文介绍了python websocket-client,只接收队列中的最新消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在树莓派上运行 websocket-client 以使用跳跃运动 websocket 服务器发送的数据控制伺服.跳跃运动通过 websocket 连接发送的数据量如此之大,以至于 pi 赶上最近的消息有很长的延迟,而且它运行的时间越长,它只会变得更糟.

I'm running websocket-client on a raspberry pi to control a servo using data sent by a leap motion websocket server. The volume of data sent over the websocket connection by the leap motion is so high that there is a long delay with the pi catching up to the most recent message which only gets worse the longer it runs.

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

How can I discard all the old messages in a queue and just use the most recent one when checking? Currently I'm doing this:

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

推荐答案

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

Since the Leap service sends data at roughly 110 frames per second, you have about 9ms to do any processing. If you exceed this, then you will get behind. The easiest solution is probably to create an artificial app frame rate. For each loop, if you haven't reached the time for the next update, then you just get the next message and discard it.

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

(我还没有对您的代码进行过此修改,因此适用通常的警告)

(I haven't run this modification to your code, so the usual caveats apply)

这篇关于python websocket-client,只接收队列中的最新消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆