简体   繁体   English

python websocket-client,仅在队列中接收最新消息

[英]python websocket-client, only receive most recent message in queue

I'm running websocket-client on a raspberry pi to control a servo using data sent by a leap motion websocket server. 我正在树莓派上运行websocket-client,以使用跳跃运动websocket服务器发送的数据来控制伺服。 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. 通过跳跃运动通过websocket连接发送的数据量是如此之大,以至于pi赶上最新消息会有很长的延迟,而延迟越长,它运行的时间就越长。

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

Since the Leap service sends data at roughly 110 frames per second, you have about 9ms to do any processing. 由于Leap服务以大约每秒110帧的速度发送数据,因此您有大约9ms的时间进行任何处理。 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) (我尚未对您的代码运行此修改,因此适用通常的警告)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM