Skip to content

pybricks.iodevices.LWP3Device: Buffer incoming notifications. #308

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

laurensvalk
Copy link
Member

Allows to read without blocking and allows subscribing to multiple sensor values without losing data.

As an example, here's how you can read both the color and the speed of the Duplo Train:

Fixes pybricks/support#1648

It works well, but it can sometimes crash the hub when stopping the program. Perhaps because of the buffer being freed before the connection is closed, so this might need some more work.

from pybricks.iodevices import LWP3Device
from pybricks.tools import wait

from ustruct import unpack

DUPLO_TRAIN_ID = 0x20
PORT_VALUE_MSG = const(0x45)

PORT_COLOR_SENSOR = 0x12
MODE_RGB = 0x03

PORT_SPEED = 0x13
MODE_SPEED = 0x00
MODE_POSITION = 0x01

print("Searching for the train. Make sure it is on and blinking its front light.")

# Buffer latest 16 notifications. Can reduce this if you read often.
device = LWP3Device(DUPLO_TRAIN_ID, num_notifications=16)

# Subscribe to color sensor and speed
device.write(bytes([0x0a, 0x00, 0x41, PORT_COLOR_SENSOR, MODE_RGB, 0x01, 0x00, 0x00, 0x00, 0x01]))
device.write(bytes([0x0a, 0x00, 0x41, PORT_SPEED, MODE_SPEED, 0x01, 0x00, 0x00, 0x00, 0x01]))

print("Connected!")
wait(500)

def parse_all():
    while (data := device.read()) is not None:

        if len(data) < 4:
            continue

        kind = data[2]
        port = data[3]
        
        if kind != PORT_VALUE_MSG:
            continue

        if port == PORT_COLOR_SENSOR and len(data) == 10:
            r, g, b = unpack("<hhh", data[4:10])
            print(r, g, b)

        if port == PORT_SPEED and len(data) == 6:
            speed, = unpack("<h", data[4:6])
            print(speed)

while True:

    parse_all()

    # All data parsed, go do something else here.
    wait(100)

Tagging @NStrijbosch.

Allows to read without blocking and allows subscribing to multiple sensor values without losing data.
@coveralls
Copy link

Coverage Status

coverage: 57.124%. remained the same
when pulling 9632542 on lwp3
into 3198a85 on master.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

[Bug] LWP3Device.read is blocking
2 participants