adafruit / Adafruit_CircuitPython_BluefruitConnect

This module helps you to communicate with the Adafruit Bluefruit Connect app or use its protocols
MIT License
17 stars 16 forks source link

Robust packet reading #10

Closed dhalbert closed 5 years ago

dhalbert commented 5 years ago

This fixes some but not all issues with https://github.com/adafruit/circuitpython/issues/1568.

dhalbert commented 5 years ago

More comprehensive test program:

from adafruit_ble.uart import UARTServer
from adafruit_bluefruit_connect.packet import Packet
from adafruit_bluefruit_connect.accelerometer_packet import AccelerometerPacket
from adafruit_bluefruit_connect.button_packet import ButtonPacket
from adafruit_bluefruit_connect.color_packet import ColorPacket
from adafruit_bluefruit_connect.gyro_packet import GyroPacket
from adafruit_bluefruit_connect.location_packet import LocationPacket
from adafruit_bluefruit_connect.magnetometer_packet import MagnetometerPacket
from adafruit_bluefruit_connect.quaternion_packet import QuaternionPacket

uart_server = UARTServer(buffer_size=256)

while True:
    uart_server.start_advertising()
    while not uart_server.connected:
        pass

    # Now we're connected

    while uart_server.connected:
        if uart_server.in_waiting:
            packet = Packet.from_stream(uart_server)
            if isinstance(packet, AccelerometerPacket):
                print("Acceleration:", packet.x, packet.y, packet.z)
            elif isinstance(packet, ButtonPacket):
                print("Button", packet.button, packet.pressed)
            elif isinstance(packet, ColorPacket):
                print("Color:", packet.color)
            elif isinstance(packet, GyroPacket):
                print("Gyro:", packet.x, packet.y, packet.z)
            elif isinstance(packet, LocationPacket):
                print("Location:", packet.latitude, packet.longitude, packet.altitude)
            elif isinstance(packet, MagnetometerPacket):
                print("Magnetometer:", packet.x, packet.y, packet.z)
            elif isinstance(packet, QuaternionPacket):
                print("Quaternion:", packet.x, packet.y, packet.z, packet.w)

    # If we got here, we lost the connection. Go up to the top and start
    # advertising again and waiting for a connection.