def __init__(self): # connect to Digi Remote Manager over TCP xbee.atcmd("DO", 1) xbee.atcmd("MO", 7) self.data = None self.body = b"" self.connected = True
def handle_zdo_message(message): tsn, args = zdo.deserialize_frame(message['cluster'], message['payload']) print("ZDO request cluster {:04X}, args: ".format(message['cluster']), args) if message['cluster'] == zdo.ZDOCmd.Active_EP_req: if args[0] == xbee.atcmd('MY'): response_frame = zdo.serialize_frame( tsn, zdo.ZDOCmd.Active_EP_rsp, (zdo.Status.SUCCESS, ), (args[0], ), ([base_ep + r for r in range(relay_count)], )) xbee.transmit(message['sender_eui64'], response_frame, source_ep=message['source_ep'], dest_ep=message['dest_ep'], cluster=zdo.ZDOCmd.Active_EP_rsp, profile=message['profile']) elif message['cluster'] == zdo.ZDOCmd.Simple_Desc_req: if args[0] == xbee.atcmd('MY'): # n, t = param_schema(ZDOCmd.Simple_Desc_rsp, 2) # print(n, t) response_frame = zdo.serialize_frame( tsn, zdo.ZDOCmd.Simple_Desc_rsp, (zdo.Status.SUCCESS, ), (args[0], ), (args[1], 260, 0x0, 0x0, [0x6], [])) xbee.transmit(message['sender_eui64'], response_frame, source_ep=message['source_ep'], dest_ep=message['dest_ep'], cluster=zdo.ZDOCmd.Simple_Desc_rsp, profile=message['profile']) else: print("No handler for ZDO message:") print_message(message)
def demo_hard_reboot(): ''' Demonstrates a hard boot of the entire XBee3 device using the ATFR command. https://www.digi.com/resources/documentation/digidocs/90002219/#tasks/t_reset_repl.htm) Note that this is the preferred mechanism to implement a hard reboot of the XBee3 device; there does not appear to be a MicroPython call that wraps this. ''' import xbee xbee.atcmd('FR')
def config_advertisement(): """ Configures the Bluetooth advertisement name of the device. """ # Get the IMEI number. imei_number = get_imei() # Write the BI setting adding the lower part of the IMEI to the name. xbee.atcmd(AT_CMD_BI, "%s%s" % (ADVERT_PREFIX, imei_number[-8:])) # Write settings in the device. xbee.atcmd(AT_CMD_WR)
def config_advertisement(): """ Configures the Bluetooth advertisement name of the device. """ # Get the XBee MAC address. mac_address = get_mac() # Write the BI setting adding the lower part of the MAC to the name. xbee.atcmd(AT_CMD_BI, "%s%s" % (ADVERT_PREFIX, mac_address[-8:])) # Write settings in the device. xbee.atcmd(AT_CMD_WR)
def main(): module = xbee.XBee() # Idle the radio. While the radio is idled, the radio cannot receive # transmissions and current draw is reduced. xbee.idle_radio(True) # register handle_rx_packet to be called whenever a packet is received. xbee.receive_callback(handle_rx_packet) # Send transmissions to the address configured by DH/DL dest_addr = xbee.atcmd("DH") + xbee.atcmd("DL") samples = [] # Since this application spends most of its time asleep, stopping # the application through the UART can be difficult. To make the # example easier to work with, it will only run for about a minute # instead of indefinitely. for _ in range(12): # Sleep for 5 seconds module.sleep_now(5000) # Upon waking, take a sample sample = read_sensor() samples.append(sample) print(" Sample: {}".format(sample)) if len(samples) == 4: # Once we have four samples, Send the samples to # the coordinator. Note that we don't have to call # xbee.idle_radio(True) to be able to do this--the radio is # enabled just long enough to send the transmission. print("Transmit samples: {}".format(samples)) xbee.transmit(dest_addr, str(samples)) # Clear the stored samples samples.clear() # If the server is ever going to send transmissions to the # end device, the end device needs to enable the radio at # some point, and the server needs to know when that is. For # this example, that is achieved by leaving the radio on for # 1 second after transmitting a sample. If this end device # never needs to receive transmissions, this can be left # out. print("Enable the radio for a bit to receive transmissions...") xbee.idle_radio(False) # Wait 1 second with the radio enabled. This is the only # time the radio can receive transmissions. time.sleep(1) print("Disable the radio again") xbee.idle_radio(True) print("Example complete, re-enabling radio") xbee.idle_radio(False)
def main(): module = xbee.XBee() # Wait until the module has joined a network before starting ai = xbee.atcmd("AI") while ai != 0: print("Waiting to join a network, AI=%x" % ai) time.sleep(1) ai = xbee.atcmd("AI") # Put the radio to sleep. Note that by doing so the MicroPython # application assumes the responsibility of fequently calling poll_now() # or data sent to this device may be lost. xbee.idle_radio(True) # register handle_rx_packet to be called whenever a packet is received. xbee.receive_callback(handle_rx_packet) samples = [] # Since this application spends most of its time asleep, stopping # the application through the UART can be difficult. To make the # example easier to work with, it will only run for about a minute # instead of indefinitely. for _ in range(12): # Sleep for 5 seconds module.sleep_now(5000) # Upon waking, take a sample sample = read_sensor() samples.append(sample) print(" Sample: {}".format(sample)) if len(samples) == 4: # Once we have four samples, Send the samples to # the coordinator. Note that we don't have to call # xbee.idle_radio(True) to be able to do this--the radio is # enabled just long enough to send the transmission. print("Transmit samples: {}".format(samples)) xbee.transmit(xbee.ADDR_COORDINATOR, str(samples)) # Clear the stored samples samples.clear() # We need to call poll_now() periodically to check for incoming # messages, so do that now. xbee.poll_now() # handle_rx_packet() is registered as the receive callback, so # it will be called automatically if the poll comes back with # any data. print("Example complete, re-enabling radio") xbee.idle_radio(False)
def read_properties(): """ Reads the application properties from the XBee firmware and returns a dictionary with all the properties. Returns: A dictionary containing all the properties of the application with their corresponding values. """ # Initialize variables. properties = {} for prop in config_properties: properties[prop] = None # Read the XBee settings saved in the firmware. for prop, atcmd in xbee_properties.items(): read_value = xbee.atcmd(atcmd) if read_value is None: properties[prop] = None elif prop in text_properties: properties[prop] = read_value else: properties[prop] = binascii.hexlify(read_value).decode() print(" - Read property '%s' from the XBee device: '%s'" % (prop, properties[prop])) # Return the properties dictionary. return properties
def detect_platform() -> str: """ detect_platform demonstrates how to determine the current running architecture. """ import sys if sys.platform == "xbee3-zigbee": return "xbee3-zigbee" if sys.platform == "xbee-cellular": import xbee hv = ( xbee.atcmd("HV") >> 8 ) & 0xFF # https://xbplib.readthedocs.io/en/latest/api/digi.xbee.models.hw.html if hv == 0x49: return "xbee-cellular-CAT-1-AT&T" elif hv == 0x4A: return "xbee-cellular-LTE-M-Verizon" elif hv == 0x4B: return "xbee-cellular-LTE-M-AT&T" elif hv == 0x4D: return "xbee-cellular-CAT-1-Verizon" else: return "xbee-cellular-unknown" if sys.platform in ("linux", "win32") and sys.version_info[0] == 3: return "cpython3" return "unknown"
def initialize(): global mydevid, lasttime #print("Waiting on connection...") lasttime = time.time() # read the IMEI and creat a device ID to that matches the device ID created in Remote Manager device_im = xbee.atcmd("IM") last = device_im[-8:] first = device_im[:7] total = first + "-" + last mydevid = "00010000-00000000-0" + total + "/" #print("Device ID = "+mydevid) hum_stream_info = { 'description': 'Humidity', 'id': mydevid + 'Humidity', 'type': "DOUBLE", 'units': '%' } temp_stream_info = { 'description': 'Temperature', 'id': mydevid + 'Temperature', 'type': "DOUBLE", 'units': 'C' } rm.create_datastream(hum_stream_info) rm.create_datastream(temp_stream_info)
def initialize(): global mydevid wait_for_connection() device_im = xbee.atcmd("IM") im = device_im[-8:] + "-" + device_im[:7] mydevid = "00010000-00000000-0" + im + "/" print("Device ID = " + mydevid)
def watch_ai(): old_ai = -1 while old_ai != 0x00: new_ai = xbee.atcmd('AI') if new_ai != old_ai: print("ATAI=0x%02X (%s)" % (new_ai, ai_desc.get(new_ai, 'UNKNOWN'))) old_ai = new_ai else: time.sleep(0.01)
def is_connected_drm(): """ Returns whether the device is connected to Digi Remote Manager or not. Returns: ``True`` if the device is connected to DRM, ``False`` otherwise. """ drm_status = xbee.atcmd(AT_CMD_DI) if drm_status is None or drm_status not in drm_status_connected: return False return True
def get_imei(): """ Returns the IMEI number of the device. Returns: String: the IMEI number of the device in string format. """ # Read the IMEI number high and low from the XBee device. sh = xbee.atcmd(AT_CMD_SH) sl = xbee.atcmd(AT_CMD_SL) if sh is None or sl is None: return None # Transform the values to hexadecimal strings. sh_string = binascii.hexlify(sh).decode().upper() sl_string = binascii.hexlify(sl).decode().upper() imei = sh_string + sl_string if len(imei) > 15: imei = imei[-15:] return imei
def save_properties(properties): """ Saves the given properties in the XBee firmware of the device. Args: properties (dict): dictionary containing the properties to save. Returns: Boolean: ``True`` if the properties were saved successfully, ``False`` otherwise. """ # Save XBee properties in the XBee firmware. for prop in xbee_properties: # Skip empty settings. if properties.get(prop) is None: continue print(" - Saving property '%s' with '%s' in the XBee device" % (prop, properties[prop])) if prop in text_properties: xbee.atcmd(xbee_properties[prop], properties[prop]) else: xbee.atcmd(xbee_properties[prop], binascii.unhexlify(properties[prop])) # Write settings in the device. xbee.atcmd(AT_CMD_WR) return True
def get_mac(): """ Returns the XBee MAC address of the device. Returns: The XBee MAC address of the device in string format. """ # Read the serial number high and low from the XBee device. sh = xbee.atcmd(AT_CMD_SH) sl = xbee.atcmd(AT_CMD_SL) if sh is None or sl is None: return None # Transform the values to hexadecimal strings. sh_string = binascii.hexlify(sh).decode().upper() sl_string = binascii.hexlify(sl).decode().upper() # Add 0s at the beginning of each value if necessary. sh_string = (8 - len(sh_string)) * "0" + sh_string sl_string = (8 - len(sl_string)) * "0" + sl_string return sh_string + sl_string
def __init__(self, name, coord_64_address=None): self.self_addr64 = xbee.atcmd('SH') + xbee.atcmd('SL') # # AT commands 'SH' + 'SL' combine to form the module's 64-bit address. # print("64-bit address: " + repr(self.self_addr64)) # # AT Command 'MY' is the module's self 16-bit network address. # print("16-bit address: " + repr(xbee.atcmd('MY'))) # # Set the Network Identifier of the radio ## xbee.atcmd("NI", name) # Configure a destination address to the Coordinator ('2nd kit coord') # xbee.atcmd("DH", 0x0013A200) # Hex # xbee.atcmd("DL", 0x41B763AE) # Hex # dest = xbee.atcmd("DH") + xbee.atcmd("DL") # formatted_dest = ':'.join('%02x' % b for b in dest) # print("Destination address set to: " + formatted_dest) # 'TP' records the current temperature measure on the module # tp= xbee.atcmd('TP') # if tp > 0x7FFF: # tp = tp - 0x10000 # print("The XBee is %.1F degrees F" % (tp * 9.0 / 5.0 + 32.0)) # print("The XBee is %.1F degrees C" % tp) self.COORD_64_ADDRESS = coord_64_address self.health = {"stat_v": 'ok2', "idx": 0} self.sent_idx = 100
def watch_ai(): """ Monitors the value of the AI parameter. Whenever it changes it displays the new value. """ old_ai = -1 while old_ai != 0x00: new_ai = xbee.atcmd("AI") if new_ai != old_ai: print("- AI Changed!") print(" * New AI: 0x%02X (%s)" % (new_ai, AI_DESC.get(new_ai, "UNKNOWN"))) old_ai = new_ai else: time.sleep(0.01)
def gpo(port, val): # getTemp関数を定義する ret = False out = 0x00 if isinstance(val, bool): if val == False: out = 0x04 else: out = 0x05 if type(val) is int: if val == 0: out = 0x04 else: out = 0x05 if out == 0x00 or port not in pinout: print('usage: gpo port =', pinout) print(' val = {0,1,False,True}') return 'ERROR' ret = xbee.atcmd(pinout[port], out) return {'port': port, 'out': out - 4, 'return': ret}
def publish_relay_state(relay_id): _ai = xbee.atcmd('AI') if _ai != 0: print( 'publish_relay_state: Not associated to a PAN (current state is {}. Cannot publish' .format(_ai)) return global reporting_tsn state = True if relay_state & (1 << relay_id) else False msg = zha.serialize_on_off_report(reporting_tsn & 0xFF, state) reporting_tsn += 1 ep = relay_id + base_ep xbee.transmit(xbee.ADDR_COORDINATOR, msg, source_ep=ep, dest_ep=ep, cluster=0x0006, profile=260)
def save_properties(properties): """ Saves the given properties in the XBee firmware of the device. Args: properties (dict): dictionary containing the properties to save. Returns: ``True`` if the properties were saved successfully, ``False`` otherwise. """ # Save XBee properties in the XBee firmware. for prop in xbee_properties: # Skip empty settings. if properties.get(prop) is None: continue print(" - Saving property '%s' with '%s' in the XBee device" % (prop, properties[prop])) if prop in text_properties: xbee.atcmd(xbee_properties[prop], properties[prop]) else: value = properties[prop] if len(value) % 2 != 0: value = "0" + value xbee.atcmd(xbee_properties[prop], binascii.unhexlify(value)) # Configure the network encryption based on the given password. if properties.get(PROP_PASS) is None: print(" - Password not provided - Disabling network encryption.") xbee.atcmd(AT_CMD_EE, VALUE_DISABLED) else: print(" - Password provided - Enabling network encryption.") xbee.atcmd(AT_CMD_EE, VALUE_ENABLED) print(" - Configuring router role parameters.") # Configure the module to join a network. xbee.atcmd(AT_CMD_CE, VALUE_DISABLED) # Enable the join notification. xbee.atcmd(AT_CMD_JN, VALUE_ENABLED) # Enable the coordinator verification. xbee.atcmd(AT_CMD_JV, VALUE_ENABLED) # Write settings in the device. xbee.atcmd(AT_CMD_WR) return True
print(" | i2crelay |") print(" +-------------------------------------+\n") print("Waiting for data...\n") btn = Pin(Pin.board.D4, Pin.IN) last_button_state = 1 i2c = I2C(1) CMD_CHANNEL_CTRL = 0x10 relay_state = 0x0 base_ep = 0xc0 relay_count = 4 serial_h = struct.unpack('I', xbee.atcmd('SH'))[0] serial_l = struct.unpack('I', xbee.atcmd('SL'))[0] capability_flags = 0x8E reporting_tsn = 0 heartbeat_timeout = 300000 def print_message(message): print("Data received from {} >>".format(''.join( '{:02x}'.format(x).upper() for x in message['sender_eui64']))) print("cluster: {0:X}".format(message['cluster'])) print("dest_ep: {}".format(message['dest_ep'])) print("source_ep: {}".format(message['source_ep']))
def discover(next_ms): # discover関数の定義 if time.ticks_ms() < next_ms: # 現在時刻が次回の実行時刻に満たない時 return next_ms # 処理を中止 disc_devs = xbee.discover() # デバイスを検索し、結果をdisc_devsへ代入 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'))
r_c6 = const(0xAC) # read PROM C6 command r_adc = const(0x00) # read ADC command r_d1 = const(0x44) # convert D1 (OSR=1024) r_d2 = const(0x54) # convert D2 (OSR=1024) # set i2c clock to 100KHz # TE MS5837 i2c adress = 0x76 i2c = machine.I2C(1, freq=100000) slave_addr = 0x76 # reset device to make sure PROM loaded data = bytearray([c_reset]) i2c.writeto(slave_addr, data) # check zigbee connection while xbee.atcmd("AI") != 0: print("#Trying to Connect...") utime.sleep(0.5) print("#Online...") # scan i2c bus for active addresses def scan_I2C(): devices = i2c.scan() return devices def read_c1(): #read PROM value C1 data = bytearray([r_c1]) i2c.writeto(slave_addr, data)
def measure(self): new_temp = xbee.atcmd('TP') if new_temp > 0x7FFF: new_temp = new_temp - 0x10000 return new_temp
#Pull pending topic/msg from log files try: log = uio.open(topic_File) log.close() files_Exist = True except OSError: files_Exist = False pass if files_Exist == True: readFiles() else: createFiles() xbee.atcmd("AN", "super") xbee.atcmd("CP", 0) xbee.atcmd("AM", 0) xbee.atcmd("N#", 0) xbee.atcmd("TM", 0x258) xbee.atcmd("TS", 0x258) xbee.atcmd("DO", 0x21) xbee.atcmd("K1", 0x3C) xbee.atcmd("K2", 0x3C) xbee.atcmd("MO", 0x7) xbee.atcmd("HM", 0x1) xbee.atcmd("HF", 0x3C) xbee.atcmd("DL", "0.0.0.0") xbee.atcmd("DE", 0x0) xbee.atcmd("C0", 0x0) xbee.atcmd("DX", 0xA0000)
def rx_callback(packet): micropython.kbd_intr(-1) if (packet != None): stdout.buffer.write(packet["payload"]) micropython.kbd_intr(3) #for i in range(0,3): # print("{}".format(packet["payload"][i])) #stdout.buffer.write(data.encode("utf-8")); #print("{}".format(packet["payload"])) # set name xbee.atcmd("NI", "XBee B") # configure network network_settings = {"CE": 0, "ID": 0x0, "EE": 0, "NT": 0x20} for command, value in network_settings.items(): print("SET {}: {}".format(command, value)) xbee.atcmd(command, value) xbee.atcmd("AC") # apply changes time.sleep(1) # wait for success print("Connecting to network, please wait...") while xbee.atcmd("AI") != 0: time.sleep(0.1) print("Connected to Network") xbee.receive_callback(None) # print network parameters operating_network = ["OI", "OP", "CH"]
def read_sensor(): """This example uses ATTP to read the internal temperature sensor.""" return xbee.atcmd("TP")
def wait_for_sms(): print('Waiting for SMS to', xbee.atcmd('PH')) while not check_sms(): time.sleep_ms(100)
def relay_frame_callback(relay_frame): """ Callback executed every time the XBee module receives a relay packet. Processes the packet, executes the proper actions and sends a response back. Args: relay_frame (dict): the relay packet to process. """ # Initialize variables. global identified global finished response = {} # Discard non BLE packets. sender = relay_frame["sender"] if sender != relay.BLUETOOTH: return # Get the packet payload. message = relay_frame["message"].decode("utf-8") # Parse the JSON items try: json_items = ujson.loads(message) except ValueError: return # Get the operation to perform. operation = json_items[ITEM_OP] if operation is None: return elif operation == OP_READ: print("- BLE: Read parameters request received.") # Set the response command command ID. response[ITEM_OP] = OP_READ # Read the properties. read_settings = read_properties() if read_settings is None: response[ITEM_STATUS] = STATUS_ERROR response[ITEM_MSG] = "Error reading settings from the XBee module." else: response[ITEM_STATUS] = STATUS_SUCCESS response[ITEM_PROP] = read_settings elif operation == OP_WRITE: print("- BLE: Write parameters request received.") # Set the response command ID. response[ITEM_OP] = OP_WRITE # Write the given properties. success = save_properties(json_items[ITEM_PROP]) if success: response[ITEM_STATUS] = STATUS_SUCCESS else: response[ITEM_STATUS] = STATUS_ERROR response[ITEM_MSG] = "Error writing settings to the XBee module." elif operation == OP_ID: print("- BLE: Identification request received.") # Set the response command ID. response[ITEM_OP] = OP_ID # Get the XBee MAC address. mac_address = get_mac() if mac_address is None: response[ITEM_STATUS] = STATUS_ERROR response[ITEM_MSG] = "Error getting the MAC address from the " \ "XBee module." else: response[ITEM_STATUS] = STATUS_SUCCESS response[ITEM_MAC] = mac_address response[ITEM_VALUE] = VALUE_IRRIGATION identified = True elif operation == OP_FINISH: print("- BLE: Finish request received.") # Disable BLE interface. This operation does not require a response. xbee.atcmd(AT_CMD_BT, VALUE_DISABLED) # Write settings in the device. xbee.atcmd(AT_CMD_WR) finished = True else: return # Send back the response. try: print("- Sending BLE response.") relay.send(sender, ujson.dumps(response)) except Exception as e: print(" - Transmit failure: %s" % str(e))