send_character(current_mode.index(char)) time.sleep(char_pause) # increment counter char_count += 1 while True: print("WAITING...") send_message("\nWAITING...\n") ble.start_advertising(advertisement) while not ble.connected: pass # Connected ble.stop_advertising() print("CONNECTED") send_message("\nCONNECTED\n") # Loop and read packets while ble.connected: if uart_server.in_waiting: raw_bytes = uart_server.read(uart_server.in_waiting) textmsg = raw_bytes.decode().strip() print("received text =", textmsg) send_message("\n") send_message(textmsg.upper()) # Disconnected print("DISCONNECTED") send_message("\nDISCONNECTED\n")
pixels.fill(CYAN) ble.start_advertising(advertisement) while not ble.connected: pass # Now we're connected print ("Connected"); pixels.fill(GREEN) connections = ble.connections device = connections[0] while ble.connected: if uart.in_waiting: # Read the packet command = int.from_bytes(uart.read(1), "little") length =int.from_bytes(uart.read(1), "little") data = uart.read(length) tup = (command, length, data) # Create the command object req = BugCommandFactory.CreateFromTuple(tup) # act upon the command object if isinstance(req, EchoRequest): print("Requested to echo: " + req.getMessage()) res = EchoResponse(req.getMessage()) uart.write(res.getDataBytes()) elif isinstance(req, EchoResponse): print("Response: " + req.getMessage()) pass
""" Used with ble_uart_echo_client.py. Receives characters from the UARTService and transmits them back. """ from adafruit_ble import BLERadio from adafruit_ble.advertising.standard import ProvideServicesAdvertisement from adafruit_ble.services.nordic import UARTService ble = BLERadio() uart = UARTService() advertisement = ProvideServicesAdvertisement(uart) while True: ble.start_advertising(advertisement) while not ble.connected: pass while ble.connected: # Returns b'' if nothing was read. one_byte = uart.read(1) if one_byte: print(one_byte) uart.write(one_byte)
ble = BLERadio() #定义广播名称 ble.name='01Studio' #构建UART服务 Uart_Service = UARTService() #广播添加UART服务 advertisement = ProvideServicesAdvertisement(Uart_Service) while True: #发起广播 ble.start_advertising(advertisement) #等待连接 while not ble.connected: pass #连接蔡成功 while ble.connected: # 读取128个字节数据,如果没数据,则返回 b'' one_byte = Uart_Service.read(128) #收到信息,REPL打印并回发 if one_byte: print(one_byte) Uart_Service.write(one_byte)
ble = BLERadio() ble.name = "JuggleCounter" uart = UARTService() advertisement = ProvideServicesAdvertisement(uart) while True: ble.start_advertising(advertisement) while not ble.connected: pass # Now we're connected while ble.connected: if uart.in_waiting: recvd = uart.read(32) if recvd is not None: # convert bytearray to string data_string = ''.join([chr(b) for b in recvd]) print(data_string, end="") uart.write(data_string) if "Juggle" in data_string: uart.write("enter target") recvd = None while not uart.in_waiting: print("getting target value") time.sleep(1) recvd = uart.read(32) juggle_target = ''.join([chr(b) for b in recvd]) print(juggle_target, end="") uart.write(juggle_target)
# 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")
advertisement = ProvideServicesAdvertisement(uart_server) if ble.connected: for connection in ble.connections: if UARTService in connection: uart_connection = connection break while True: ble.start_advertising(advertisement) while not ble.connected: pass if not uart_connection: print("Scanning...") kPa_tx = uart_server.read() print(kPa_tx) 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() ble.stop_advertising() # 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)
# Wait for a connection. pass connected_led.value = False last_pi_send = time.monotonic() pct = 0 pwm_on = True pi_gen_on = True led.duty_cycle = int((100 - pct) * 65535 / 100) pwm_indicate_time = time.monotonic() pwm_indicate_count = 0 while ble.connected: if uart_service.in_waiting: raw_bytes = uart_service.read(uart_service.in_waiting) pct = int(raw_bytes.decode().strip()) if pct < 0: pct = 0 if pct > 100: pct = 100 if pwm_on: led.duty_cycle = int((100 - pct) * 65535 / 100) if not pwm_on: if (time.monotonic() - pwm_indicate_time > PWM_INDICATE_BLINK_INTERVAL): pwm_indicate_time = time.monotonic() blink_pct = 0 pwm_indicate_count += 1
class Room: def __init__(self, use_debug=False): self.use_debug = use_debug self.subscription_ids = {} self.subscription_messages_on_reconnect = [] self.ble = BLERadio() self.uart_server = UARTService() self.advertisement = ProvideServicesAdvertisement(self.uart_server) self.chunk_size = 20 # adafruit_ble can only write in 20 byte chunks self.recv_msg_cache = "" def debug(self, msg): if self.use_debug: print(msg) def cleanup(self): self.uart_server.write('~:\n'.encode("utf-8")) def claim(self, claim_str): # Cleanup claim = cleanup all previous claims self.uart_server.write('N:{}\n'.format(claim_str).encode("utf-8")) def when(self, query_strings, callback): x = str(random.randint(0, 9999)) subscription_id = '0'*(4-len(x)) + x # like 0568 self.subscription_ids[subscription_id] = callback # S:0568:$ $ value is $x::$ $ $x is open x = 'S:{}:{}\n'.format(subscription_id, '::'.join(query_strings)).encode("utf-8") self.subscription_messages_on_reconnect.append(x) def parse_results(self, val): self.debug("parsing results: {}".format(val)) result_vals = val[1:-1].split("},{") results = [] for result_val in result_vals: result = {} rvs = result_val.split(",") for rv in rvs: kv = rv.strip().split(":") result[kv[0].replace('"', '').replace("'", '')] = kv[1].strip() results.append(result) return results def check_read_msg_cache_and_callbacks(self): lines = self.recv_msg_cache.split("\n") self.debug("lines: {}".format(lines)) if len(lines) > 1: # trim off the last line (either '' if \n is the last char or a partial string) # because it is not part of a string that ends in a \n full_lines = lines[:-1] for line_msg in full_lines: self.debug("Proccesing new sub update: {}".format(line_msg)) # 1234[{x:"5",y:"1"},{"x":1,"y":2}] sub_id = line_msg[:4] # first four characters of message are sub id val = line_msg[4:] if sub_id not in self.subscription_ids: print("Unknown sub id {}".format(sub_id)) continue callback = self.subscription_ids[sub_id] callback(self.parse_results(val)) self.recv_msg_cache = lines[-1] def listen_and_update_subscriptions(self): # self.debug("listening~~~~~") if self.uart_server.in_waiting: read_msg = self.uart_server.read(self.uart_server.in_waiting) self.recv_msg_cache += read_msg.decode("utf-8") self.check_read_msg_cache_and_callbacks() self.debug("sub update: {}".format(self.recv_msg_cache)) def connected(self): if not self.ble.connected: # Advertise when not connected. print("BLE not connected, advertising...") self.ble.start_advertising(self.advertisement) while not self.ble.connected: pass self.ble.stop_advertising() print("BLE now connected") time.sleep(1.0) # Give BLE connector time setup before sending data for sub_msg in self.subscription_messages_on_reconnect: self.debug("Sending sub message: {}".format(sub_msg)) self.uart_server.write(sub_msg) self.listen_and_update_subscriptions() return True
uart_server.write('Checked-in!') #touch_A1.deinit() #touch_A1 = touchio.TouchIn(board.A1) last_send = time.monotonic() pixels.fill((255,0,255)) rainbow = False print(last_send) time.sleep(0.1) #print("Outside loop") #uart_server.write('Checked-in!') #flag = 1 # receive if uart_server.in_waiting: print("Inside uart_server") # note that the reading won't stop until buffer's full pkt = uart_server.read(20) # adjust buffer size as needed if pkt == b'doingwell': pixels.fill((0,255,0)) elif pkt == b'doingokay': pixels.fill((150,150,0)) elif pkt == b'pleasevisit': pixels.fill((150,0,0)) rainbow = False print(pkt) #time.sleep(0.5) else: #led.value = True rainbow = True time.sleep(0.0) #led.value = False #time.sleep(0.5)