def read_packet(timeout=None): """Read a packet with an optional locally implemented timeout. This is a workaround due to the timeout not being configurable.""" if timeout is None: return Packet.from_stream(uart) # Current fixed timeout is 1s packet = None read_start_t = time.monotonic() while packet is None and time.monotonic() - read_start_t < timeout: packet = Packet.from_stream(uart) return packet
def accept_requests(self): while self.connected: # resets the board # microcontroller.reset() if self.ble_service.in_waiting: packet = Packet.from_stream(self.ble_service) if isinstance(packet, ColorPacket): self.set_color(packet.color, self.config['color']) elif isinstance(packet, BrightnessPacket): self.set_brightness(packet.brightness) elif isinstance(packet, SettingsRequestPacket): self.send_config()
def coloring(): global packet for j in range(255): if uart.in_waiting: packet = Packet.from_stream(uart) if packet.button == ButtonPacket.LEFT: leftwards() elif packet.button == ButtonPacket.RIGHT: rightwards() for i in range(10): rc_index = (i * 256 // 10) + j * 5 px[i] = wheel(rc_index & 255) px.show() time.sleep(0.1)
def _tick(self): if self.__uart: if self.__pending_plot_values: self.__uart.write('{}\n'.format(','.join( [str(v) for v in self.__pending_plot_values]))) self.__pending_plot_values = None if self.__uart.in_waiting: packet = Packet.from_stream(self.__uart) if isinstance(packet, ButtonPacket): if packet.button == ButtonPacket.BUTTON_1: self.button_1 = packet.pressed elif packet.button == ButtonPacket.BUTTON_2: self.button_2 = packet.pressed elif packet.button == ButtonPacket.BUTTON_3: self.button_3 = packet.pressed elif packet.button == ButtonPacket.BUTTON_4: self.button_4 = packet.pressed elif packet.button == ButtonPacket.UP: self.button_up = packet.pressed elif packet.button == ButtonPacket.DOWN: self.button_down = packet.pressed elif packet.button == ButtonPacket.LEFT: self.button_left = packet.pressed elif packet.button == ButtonPacket.RIGHT: self.button_right = packet.pressed if isinstance(packet, AccelerometerPacket): self.acceleration = Axes(x=packet.x, y=packet.y, z=packet.z) if isinstance(packet, MagnetometerPacket): self.magnetometer = Axes(x=packet.x, y=packet.y, z=packet.z) if isinstance(packet, GyroPacket): self.gyro = Axes(x=packet.x, y=packet.y, z=packet.z) if isinstance(packet, QuaternionPacket): self.quaternion = Quaternion(x=packet.x, y=packet.y, z=packet.z, w=packet.w) if isinstance(packet, ColorPacket): self.color = packet.color if isinstance(packet, LocationPacket): self.location = Location(latitude=packet.latitude, longitude=packet.longitude, altitude=packet.altitude)
def rightwards(): global packet k = 5 for j in range(255): if uart.in_waiting: packet = Packet.from_stream(uart) if not packet.pressed: return for i in range(10): rc_index = (i * 256 // 10) + j * 5 px[i] = wheel(rc_index & 255) px[k] = lighten(px[k], 3) px[(k + 1) % 10] = lighten(px[(k + 1) % 10], 2) px[(k + 2) % 10] = lighten(px[(k + 2) % 10], 1) k = (k - 1) % 10 px.show() time.sleep(0.1)
#定义广播名称 ble.name = '01Studio' #构建UART服务 uart_server = UARTService() #广播添加UART服务 advertisement = ProvideServicesAdvertisement(uart_server) #定义neopixel引脚,默认使用板载neopixel pixels = neopixel.NeoPixel(board.NEOPIXEL, 1, brightness=0.1) while True: # 广播 ble.start_advertising(advertisement) #等待连接 while not ble.connected: pass #已连接 while ble.connected: #获取UART服务数据 packet = Packet.from_stream(uart_server) #判断收到的包和颜色包类型是否一致 if isinstance(packet, ColorPacket): print(packet.color) pixels.fill(packet.color) #修改灯珠颜色
while True: print("WAITING...") # Advertise when not connected. ble.start_advertising(advertisement) while not ble.connected: pass # Connected ble.stop_advertising() print("CONNECTED") # Loop and read packets while ble.connected: if uart.in_waiting: packet = Packet.from_stream(uart) if isinstance(packet, ButtonPacket): # if buttons in the app are pressed if packet.pressed: if packet.button == ButtonPacket.DOWN: print("pressed down") for angle in range( 90, 170, 90): # 90 - 170 degrees, 90 degrees at a time. my_servo.angle = angle time.sleep(0.05) if packet.button == ButtonPacket.UP: print("pressed up") for angle in range( 170, 90, -90): # 170 - 90 degrees, 9 degrees at a time.
uart = UARTService() advertisement = ProvideServicesAdvertisement(uart) while True: # connect via BLE ble.start_advertising(advertisement) # Start advertising. was_connected = False while not was_connected or ble.connected: if ble.connected: # If BLE is connected... was_connected = True # start animations animations.animate() # look for packets if uart.in_waiting: try: packet = Packet.from_stream( uart) # Create the packet object. except ValueError: continue # if it's a color packet: if isinstance(packet, ColorPacket): for i in range(12): colors = color[i] notes = note[i] # if the packet matches one of our colors: if packet.color == colors and not tone: # animate with that color animations.color = colors # play matching note cpb.start_tone(notes) tone = True # if it's a button packet aka feather's button has been released:
while not uart_addresses: uart_addresses = uart_client.scan(scanner) for address in uart_addresses: if TARGET in str(address): uart_client.connect(address, 5) # Connect to target while uart_client.connected: # Connected switch.update() if switch.fell: # Check for button press try: uart_client.write(button_packet.to_bytes()) # Transmit press except OSError: pass # Check for LED status receipt if uart_client.in_waiting: packet = Packet.from_stream(uart_client) if isinstance(packet, ColorPacket): if fancy.CRGB(*packet.color).pack() == GREEN: # Color match # Green indicates on state palette = fancy.expand_gradient(gradients['On'], 30) else: # Otherwise red indicates off palette = fancy.expand_gradient(gradients['Off'], 30) # NeoPixel color fading routing color = fancy.palette_lookup(palette, color_index / 29) color = fancy.gamma_adjust(color, brightness=gamma_levels) c = color.pack() pixels[0] = c pixels.show() if color_index == 0 or color_index == 28:
break pass # Do nothing this loop. # Connected ble.stop_advertising() # Stop telling other devices about the Clue's Bluetooth UART Connection. print("CONNECTED") # Loop and read packets while ble.connected: # Check to see if we are still connected. if clue.button_a: break # Keeping trying until a good packet is received try: packet = Packet.from_stream(uart_server) # Try to get new messages from connected device. except ValueError: continue # Only handle button packets if isinstance(packet, ButtonPacket) and packet.pressed: # Check to see if new messages have anything we can use. if packet.button == ButtonPacket.UP: # Check to see if the useful message says the up button was pressed. print("Button UP") cutebot.motors(maxSpeed,maxSpeed) cutebot.headlights(3,[255,255,255]) elif packet.button == ButtonPacket.DOWN: # Check to see if the useful message says the down button was pressed. print("Button DOWN") cutebot.motors(-maxSpeed,-maxSpeed) cutebot.headlights(0,[0,0,0]) elif packet.button == ButtonPacket.LEFT: # Check to see if the useful message says the left button was pressed. print("Button LEFT")
# Loop forever while True: # advertise and wait for connection print("WAITING...") ble.start_advertising(advertisement) while not ble.connected: pass # connected print("CONNECTED") ble.stop_advertising() # receive and handle BLE traffic while ble.connected: if uart.in_waiting: raw_bytes = uart.read(uart.in_waiting) if raw_bytes[0] == ord('!'): # BLE Connect Control Packet packet = Packet.from_bytes(raw_bytes) if isinstance(packet, ColorPacket): print("color = ", color) color = packet.color else: # Just plain text text = raw_bytes.decode("utf-8").strip() print("text = ", text) update_heart(text, color) # disconnected print("DISCONNECTED")
def ping_for_rtt(): # pylint: disable=too-many-branches,too-many-statements """Calculate the send time for Bluetooth Low Energy based from a series of round-trip time measurements and assuming that half of that is the send time. This code must be run at approximately the same time on each device as the timeout per packet is one second.""" # The rtt is sent to server but for first packet client # sent there's no value to send, -1.0 is specal first packet value rtt = TIME_NONE rtts = [] offsets = [] if master_device: # Master code while True: gc.collect() # an opportune moment request = TimePacket(rtt, TIME_NONE) d_print(2, "TimePacket TX") uart.write(request.to_bytes()) response = Packet.from_stream(uart) t2 = time.monotonic() if isinstance(response, TimePacket): d_print(2, "TimePacket RX", response.sendtime) rtt = t2 - request.sendtime rtts.append(rtt) time_remote_cpb = response.sendtime + rtt / 2.0 offset = time_remote_cpb - t2 offsets.append(offset) d_print(3, "RTT plus a bit={:f},".format(rtt), "remote_time={:f},".format(time_remote_cpb), "offset={:f}".format(offset)) if len(rtts) >= NUM_PINGS: break pixels.fill(blue) time.sleep(SYNC_FLASH_DUR) pixels.fill(black) # This second sleep is very important to ensure that the # server is already awaiting the next packet before client # sends it to avoid server instantly reading buffered packets time.sleep(SYNC_FLASH_DUR) else: responses = 0 while True: gc.collect() # an opportune moment packet = Packet.from_stream(uart) if isinstance(packet, TimePacket): d_print(2, "TimePacket RX", packet.sendtime) # Send response uart.write(TimePacket(TIME_NONE, TIME_NONE).to_bytes()) responses += 1 rtts.append(packet.duration) pixels.fill(blue) time.sleep(SYNC_FLASH_DUR) pixels.fill(black) elif packet is None: # This could be a timeout or an indication of a disconnect d_print(2, "None from from_stream()") else: print("Unexpected packet type", packet) if responses >= NUM_PINGS: break # indicate a good rtt calculate, skip first one # as it's not present on slave if debug >= 3: print("RTTs:", rtts) if master_device: rtt_start = 1 rtt_end = len(rtts) - 1 else: rtt_start = 2 rtt_end = len(rtts) # Use quickest ones and hope any outlier times don't reoccur! quicker_rtts = sorted(rtts[rtt_start:rtt_end])[0:(NUM_PINGS // 2) + 1] mean_rtt = sum(quicker_rtts) / len(quicker_rtts) # Assuming symmetry between send and receive times # this may not be perfectly true, parsing is one factor here send_time = mean_rtt / 2.0 d_print(2, "send_time=", send_time) # Indicate sync with a longer 2 second blue flash pixels.fill(brightblue) time.sleep(SYNCED_LONGFLASH_DUR) pixels.fill(black) return send_time