for dev in disc_devs: # 個々のデバイスの処理 addr = str(binascii.hexlify(dev['sender_eui64']).decode('utf-8')) type = DEV_TYPES[ dev['node_type'] ] if addr not in devs: # 過去に発見されていないデバイス発見時 devs.append(addr) # 配列に送信元アドレスを追加 addr=addr[:8] + ' ' + addr[8:] # 送信元アドレスを表示用(8+8文字)に分離 print('found',addr,type) # 発見したデバイスを表示する next_ms = time.ticks_ms() + 6000 # 次回の実行は6秒後 return next_ms while True: status = xbee.atcmd('AI') # ネットワーク参加状態を確認する print('.',end='') if status == 0x00: # 参加状態の時にループを抜ける break xbee.atcmd('CB',0x01) # コミッショニング(ネットワーク参加) time.sleep_ms(2000) # 2秒間の待ち時間処理 print('\nJoined') xbee.atcmd('CB',0x01) # コミッショニング(ネットワーク参加通知) time.sleep_ms(2000) # 2秒間の待ち時間処理 while True: next_ms = discover(next_ms) # discover関数の呼び出し packet = xbee.receive() # パケットの受信を行う if packet: # 受信データがある時 addr = str(binascii.hexlify(packet['sender_eui64']).decode('utf-8')) addr = addr[:8] + ' ' + addr[8:] # 送信元アドレスを表示用(8+8文字)に分離 payload = str(packet['payload'].decode('utf-8')) # 受信データを抽出 print(addr + ', ' + payload) # アドレスと受信データを表示する
xbee.transmit(xbee.ADDR_COORDINATOR, msg, source_ep=ep, dest_ep=ep, cluster=0x0006, profile=260) set_relays() for r in range(relay_count): publish_relay_state(r) heartbeat_time = time.ticks_ms() while True: # Check if the XBee has any messages in the queue. received_msg = xbee.receive() if received_msg: ai = xbee.atcmd('AI') if ai != 0: print( 'handle message: Not associated to a PAN (current state is {}. Cannot handle message' .format(ai)) else: # print_message(received_msg) if received_msg['profile'] == 0 and received_msg['dest_ep'] == 0: handle_zdo_message(received_msg) elif received_msg['profile'] == 260: # zha profile handle_zha_message(received_msg) else: print("No handler for message:") print_message(received_msg)
def main(): """ Main execution of the application. """ # Initialize variables. global sensor global identified global finished global simulate_temp print(" +-----------------------------------+") print(" | End-to-End IoT Agriculture Sample |") print(" +-----------------------------------+\n") # Instantiate the HDC1080 peripheral. try: sensor = HDC1080(I2C(1)) except AssertionError: pass # Configure the Bluetooth advertisement. config_advertisement() # Register relay callback to handle incoming relay packets. relay.callback(relay_frame_callback) # Set the LED pin initial value to off (0). led_pin.off() was_btn_pressed = is_button_pressed() # Start the main application loop. while True: # Sleep 100 ms. time.sleep_ms(100) if sensor is not None: # If the button has been pressed, swap the temperature source # (reading or simulation). if not was_btn_pressed and is_button_pressed(): simulate_temp = not simulate_temp print("- Temperature source changed to %s" % ("simulation" if simulate_temp else "reading")) was_btn_pressed = is_button_pressed() # Blink identification LED if necessary. if identified: if finished: identified = False finished = False else: led_pin.value(not led_pin.value()) # Check if we received any XBee packet from the gateway. incoming = xbee.receive() if incoming is not None: print("- Packet received with payload '%s'" % list(incoming["payload"])) # Get the packet payload. message = incoming["payload"].decode("utf-8") # Parse the JSON items. try: json_items = ujson.loads(message) print(" - Parsed status: %s" % json_items) except ValueError as e: json_items = None print(" - Error parsing status: %s" % str(e)) if json_items is not None: # Get the operation to perform. operation = json_items[ITEM_OP] if operation is None: return elif operation == OP_STATUS: # Configure status values. statuses = json_items[ITEM_PROP] for status_id in statuses: set_status_value(status_id, statuses[status_id]) # Return the sensor values. status_response = { ITEM_OP: OP_STATUS, ITEM_PROP: get_sensors_values() } print("- Reporting status data: %s" % status_response) try: xbee.transmit(xbee.ADDR_COORDINATOR, ujson.dumps(status_response)) except Exception as e: print(" - Transmit failure: %s" % str(e))
while network_status() != 0: time.sleep(0.1) print("Connected to Network\n") last_sent = time.ticks_ms() interval = 1000 # How often to send a message in ms # read digital input D12 and set D19 output D12 = Pin("D12", Pin.IN, Pin.PULL_UP) D19 = Pin("D19", Pin.OUT, value=0) # Start the transmit/receive loop print("Sending temp data every {} seconds".format(interval / 1000)) while True: p = xbee.receive() if p: format_packet(p) else: # Transmit sensor state if ready if time.ticks_diff(time.ticks_ms(), last_sent) > interval: # TE sensor state is monitored by D12 input sensor = str(D12.value()) D19.value(D12.value()) print("\tsending sensor state= " + sensor) try: xbee.transmit(xbee.ADDR_COORDINATOR, sensor) except Exception as err: print(err) last_sent = time.ticks_ms() time.sleep(0.25)
while True: # bufferRead = stdin.buffer.read(-1) # if bufferRead != None: # print(bufferRead) # incomingMessage = bufferRead # lcd.move_to(0,2) # lcd.putstr(incomingMessage) # if bufferRead == "\n": # lcd.move_to(0,2) # lcd.putstr(incomingMessage) # incomingMessage = "" # else: # incomingMessage += bufferRead packet = xbee.receive() if packet != None: message = packet["payload"].decode("utf8") line = int(message[0:1]) message = message[1:] while len(message) < 20: message = message + " " lcd.move_to(0, line) lcd.putstr(message) lcd.move_to(0, 3) lcd.putstr("%4d" % (utime.ticks_ms() // 1000)) # utime.sleep_ms(10000) #lcd.clear() #lcd.move_to(0, 0) #lcd.putstr("%7d" % (utime.ticks_ms() // 1000))
# Instantiate the XBee device. xb = xbee.XBee() # Configure sleep mode to be managed by MicroPython. xb.atcmd("SM", 0x06) sleep_time = SLEEP_TIME_MS # Start reading temperature and humidity measures. while True: # Notify the gateway that the XBee is awake. xbee.transmit(xbee.ADDR_COORDINATOR, MSG_AWAKE) # Wait during the configured time for incoming messages. start_time_ms = time.ticks_ms() while time.ticks_diff(time.ticks_ms(), start_time_ms) < AWAKE_TIME_MS: incoming = xbee.receive() if incoming is not None and incoming[ "sender_nwk"] == 0 and not incoming["broadcast"]: try: payload = int(incoming["payload"].decode()) except ValueError: continue if payload < 0: continue # Update the sleep time. sleep_time = payload * 1000 print("Temperature/humidity service stopped.\n" if sleep_time == 0 else "Changed sleep time to %d s.\n" % payload) if sleep_time > 0: # Read the temperature and humidity.
def flush_rx_buffer(): for i in range(100): xbee.receive()