简体   繁体   中英

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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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