예제 #1
0
def contact_via_bluetooth():
    global uart_connection
    print("I'm inside contact_via_bluetooth()!")
    print("uart_connection = ", uart_connection)
    print("uart_connection.connected = ", uart_connection.connected)
    # while uart_connection and uart_connection.connected:
    sent = False
    while uart_connection.connected and sent == False:
        print("connected!")
        color = (255, 254, 253)

        color_packet = ColorPacket(color)
        try:
            print("trying to send a color packet!")
            uart_connection[UARTService].write(color_packet.to_bytes())
            print("sent a color packet!")
            sending_to_CPB = False
            sent = True
        except OSError:
            print("ERROR: I couldn't send an UP")
            pass
        time.sleep(0.3)
예제 #2
0
ble = BLERadio()
# uart_server = UARTServer()
uart = UARTService()
advertisement = ProvideServicesAdvertisement(uart)

while True:
    ble.start_advertising(advertisement)  # Advertise when not connected.

    while not ble.connected:  # Wait for connection
        pass

    while ble.connected:  # Connected
        if ble.in_waiting:  # Check BLE commands
            packet = Packet.from_stream(uart)
            if isinstance(packet, ButtonPacket):
                if packet.button == '1' and packet.pressed:
                    solenoid.value = True  # Activate solenoid for 1 second
                    sleep(1)
                    solenoid.value = False

        led_intensity = led.value  # Check blue LED detector intensity
        led_on = led_intensity > 1000
        # Color: red = off, green = on
        color_packet = ColorPacket((255 * int(not led_on), 255 * led_on, 0))
        try:
            uart.write(color_packet.to_bytes())  # Transmit state color
        except OSError:
            pass

        sleep(.2)
        if UARTService in connection:
            uart_connection = connection
        break

while True:
    if not uart_connection:
        print("Scanning...")
        for adv in ble.start_scan(ProvideServicesAdvertisement, timeout=5):
            if UARTService in adv.services:
                print("found a UARTService advertisement")
                uart_connection = ble.connect(adv)
                break
        # Stop scanning whether or not we are connected.
        ble.stop_scan()

    while uart_connection and uart_connection.connected:
        r, g, b = map(scale, accelerometer.acceleration)

        color = (r, g, b)
        neopixels.fill(color)
        color_packet = ColorPacket(color)
        try:
            uart_connection[UARTService].write(color_packet.to_bytes())
        except OSError:
            try:
                uart_connection.disconnect()
            except:  # pylint: disable=bare-except
                pass
            uart_connection = None
        time.sleep(0.3)
예제 #4
0
        if not cpb.button_b and button_b_pressed:  # On button release...
            button_b_pressed = False  # Set to False.
            time.sleep(0.05)  # Debounce.
        if cpb.switch is not last_switch_state:  # If the switch state is changed...
            last_switch_state = cpb.switch  # Set state to current switch state.
            if cpb.switch:
                print("Switch is to the left: LEDs off!")
            else:
                print("Switch is to the right: LEDs on!")
            # Send a BUTTON_1 button packet.
            if not send_packet(
                    uart_connection,
                    ButtonPacket(ButtonPacket.BUTTON_1, pressed=cpb.switch)):
                uart_connection = None
                continue
        if cpb.switch:  # If switch is to the left...
            cpb.pixels.fill((0, 0, 0))  # Turn off the LEDs.
        else:  # Otherwise...
            r, g, b = map(
                scale,
                cpb.acceleration)  # Map acceleration values to RGB values...
            color = (r, g, b)  # Set color to current mapped RGB value...
            print("Color:", color)
            cpb.pixels.fill(
                color)  # Fill Remote Control LEDs with current color...
            if not send_packet(uart_connection,
                               ColorPacket(color)):  # And send a color packet.
                uart_connection = None
                continue
        time.sleep(0.1)  # Delay to prevent sending packets too quickly.
예제 #5
0
                break
        ble.stop_scan()  # And stop scanning.
    #  while connected..
    while uart_connection and uart_connection.connected:
        #  iterate through buttons and colors
        for switch_pin in switch_array:
            i = switch_array.index(switch_pin)
            switches_pressed_state = switches_pressed[i]
            colors = color[i]
            #  if the button is released
            #  worked best if placed before the button press portion
            if switch_pin.value and switches_pressed_state:
                print("button off")
                #  send button packet to stop tone & color (happens on CPB)
                if not send_packet(
                        uart_connection,
                        ButtonPacket(ButtonPacket.RIGHT, pressed=True)):
                    uart_connection = None
                    continue
                switches_pressed[i] = False  # Set to False.
                #  time delay for BLE, otherwise issues can arrise
                time.sleep(0.05)
            #  if button is pressed:
            if not switch_pin.value and not switches_pressed_state:  # If button A pressed...
                #  send color packet
                if not send_packet(uart_connection, ColorPacket(colors)):
                    uart_connection = None
                    continue
                switches_pressed[i] = True  # Set to True.
                time.sleep(0.05)  # Debounce.
예제 #6
0
def main():
    # Clear any cached data because both bluez and CoreBluetooth have issues with
    # caching data and it going stale.
    #ble.clear_cached_data() #enabling this will means any BLE devices get disconnected from computer

    # Get the first available BLE network adapter and make sure it's powered on.
    adapter = ble.get_default_adapter()
    adapter.power_on()
    print('Using adapter: {0}'.format(adapter.name))

    # Disconnect any currently connected UART devices.  Good for cleaning up and
    # starting from a fresh state.
    # print('Disconnecting any connected UART devices...')
    # UART.disconnect_devices()

    # Scan for UART devices.
    print('Searching for UART device...')
    connect_to = "yourUniqueName"
    try:
        adapter.start_scan()
        # Search for the first UART device found (will time out after 60 seconds
        # but you can specify an optional timeout_sec parameter to change it).
        device = UART.find_device()
        if device is None:
            raise RuntimeError('Failed to find UART device!')
    finally:
        # Make sure scanning is stopped before exiting.
        adapter.stop_scan()

    # make sure we connect to the device we want
    if device.name == connect_to:
        print('Connecting to device...' + device.name)
        device.connect(
        )  # Will time out after 60 seconds, specify timeout_sec parameter
        # to change the timeout.

        # Once connected do everything else in a try/finally to make sure the device
        # is disconnected when done.
        try:
            # Wait for service discovery to complete for the UART service.  Will
            # time out after 60 seconds (specify timeout_sec parameter to override).
            print('Discovering services...')
            UART.discover(device)

            # Once service discovery is complete create an instance of the service
            # and start interacting with it.
            uart = UART(device)

            # packets are documented here https://learn.adafruit.com/bluefruit-le-connect/controller
            # color_packet_blue = b'!C\x00I\xffS'
            # color_packet_red = b'!C\xff\x02\x08\x92'
            light_value = 0
            while True:
                # build a random color
                if light_value > 10000:
                    print("BRIGHT " + str(light_value))
                    color_packet = ColorPacket((255, 0, 0))
                else:
                    print("DIM " + str(light_value))
                    color_packet = ColorPacket(
                        (randint(0, 255), randint(0, 255), 255))
                uart.write(color_packet.to_bytes())
                print("Sent color packet to the device.")
                time.sleep(0.2)
                print(
                    'Waiting up to 4 seconds to receive data from the device...'
                )
                received = uart.read(timeout_sec=4)
                if received is not None:
                    # Received data, print it out.
                    light_value = int(received)
                else:
                    # Timeout waiting for data, None is returned.
                    print('Received no data!')
        finally:
            # Make sure device is disconnected on exit.
            device.disconnect()
    else:
        print("Not connecting to first device found: " + device.name)
예제 #7
0
    return int(value / 65535 * 255)


scanner = Scanner()
uart_client = UARTClient()

a3 = AnalogIn(board.A4)
a4 = AnalogIn(board.A5)
a5 = AnalogIn(board.A6)

while True:
    uart_addresses = []
    # Keep trying to find a UART peripheral
    while not uart_addresses:
        uart_addresses = uart_client.scan(scanner)
    uart_client.connect(uart_addresses[0], 5)

    while uart_client.connected:
        r = scale(a3.value)
        g = scale(a4.value)
        b = scale(a5.value)

        color = (r, g, b)
        print(color)
        color_packet = ColorPacket(color)
        try:
            uart_client.write(color_packet.to_bytes())
        except OSError:
            pass
        time.sleep(0.3)