def main(): print(" +-----------------------------------------------------+") print(" | XBee Python Library Manage Common parameters Sample |") print(" +-----------------------------------------------------+\n") device = XBeeDevice(PORT, BAUD_RATE) try: device.open() print("Cached parameters\n" + "-" * 50) print("64-bit address: %s" % device.get_64bit_addr()) print("16-bit address: %s" % device.get_16bit_addr()) print("Node Identifier: %s" % device.get_node_id()) print("Firmware version: %s" % utils.hex_to_string(device.get_firmware_version())) print("Hardware version: %s" % device.get_hardware_version().description) print("") # Configure and read non-cached parameters. device.set_pan_id(PARAM_VALUE_PAN_ID) device.set_dest_address(PARAM_DESTINATION_ADDR) device.set_power_level(PARAM_POWER_LEVEL) print("Non-Cached parameters\n" + "-" * 50) print("PAN ID: %s" % utils.hex_to_string(device.get_pan_id())) print("Dest address: %s" % device.get_dest_address()) print("Power level: %s" % device.get_power_level().description) finally: if device is not None and device.is_open(): device.close()
def main(): print(" +--------------------------------------------------+") print(" | XBee Python Library Explicit Data Polling Sample |") print(" +--------------------------------------------------+\n") device = ZigBeeDevice(PORT, BAUD_RATE) try: device.open() device.set_api_output_mode(APIOutputMode.EXPLICIT) device.flush_queues() print("Waiting for data in explicit format...\n") while True: explicit_xbee_message = device.read_expl_data(None) if explicit_xbee_message is not None: print("From %s >> %s" % (explicit_xbee_message.remote_device.get_64bit_addr(), explicit_xbee_message.data.decode())) print(" - Source endpoint: %s" % utils.hex_to_string(utils.int_to_length(explicit_xbee_message.source_endpoint))) print(" - Destination endpoint: %s" % utils.hex_to_string(utils.int_to_length(explicit_xbee_message.dest_endpoint))) print(" - Cluster ID: %s" % utils.hex_to_string(utils.int_to_length(explicit_xbee_message.cluster_id))) print(" - Profile ID: %s" % utils.hex_to_string(utils.int_to_length(explicit_xbee_message.profile_id))) finally: if device is not None and device.is_open(): device.close()
def main(): print(" +-----------------------------------------------+") print(" | XBee Python Library Set/Get parameters Sample |") print(" +-----------------------------------------------+\n") device = XBeeDevice(PORT, BAUD_RATE) try: device.open() # Set parameters. device.set_parameter(PARAM_NODE_ID, bytearray(PARAM_VALUE_NODE_ID, 'utf8')) device.set_parameter(PARAM_PAN_ID, PARAM_VALUE_PAN_ID) device.set_parameter(PARAM_DEST_ADDRESS_H, PARAM_VALUE_DEST_ADDRESS_H) device.set_parameter(PARAM_DEST_ADDRESS_L, PARAM_VALUE_DEST_ADDRESS_L) # Get parameters. print("Node ID: %s" % device.get_parameter(PARAM_NODE_ID).decode()) print("PAN ID: %s" % utils.hex_to_string(device.get_parameter(PARAM_PAN_ID))) print("Destination address high: %s" % utils.hex_to_string(device.get_parameter(PARAM_DEST_ADDRESS_H))) print("Destination address low: %s" % utils.hex_to_string(device.get_parameter(PARAM_DEST_ADDRESS_L))) print("") print("All parameters were set correctly!") finally: if device is not None and device.is_open(): device.close()
def run(self): """ This is the method that will be executing for listening packets. For each packet, it will execute the proper callbacks. """ try: self.__stop = False while not self.__stop: # Try to read a packet. Read packet is unescaped. raw_packet = self.__try_read_packet( self.__xbee_device.operating_mode) if raw_packet is not None: # If the current protocol is 802.15.4, the packet may have to be discarded. if (self.__xbee_device.get_protocol() == XBeeProtocol.RAW_802_15_4 and not self.__check_packet_802_15_4(raw_packet)): continue # Build the packet. try: read_packet = factory.build_frame( raw_packet, self.__xbee_device.operating_mode) except InvalidPacketException as e: self._log.error( "Error processing packet '%s': %s" % (utils.hex_to_string(raw_packet), str(e))) continue self._log.debug( self.__xbee_device.LOG_PATTERN.format( port=self.__xbee_device.serial_port.port, event="RECEIVED", opmode=self.__xbee_device.operating_mode, content=utils.hex_to_string(raw_packet))) # Add the packet to the queue. self.__add_packet_queue(read_packet) # If the packet has information about a remote device, extract it # and add/update this remote device to/in this XBee's network. remote = self.__try_add_remote_device(read_packet) # Execute API internal callbacks. self.__packet_received_API(read_packet) # Execute all user callbacks. self.__execute_user_callbacks(read_packet, remote) except Exception as e: if not self.__stop: self._log.exception(e) finally: if not self.__stop: self.__stop = True if self.__serial_port.isOpen(): self.__serial_port.close()
def __str__(self): return "ID: 0x%s\n" \ "State: %s\n" \ "Protocol: %s\n" \ "Local port: 0x%s\n" \ "Remote port: 0x%s\n" \ "Remote address: %s"\ % (utils.hex_to_string(utils.int_to_bytes(self.__socket_id, num_bytes=1), False), self.__state.description, self.__protocol.description, utils.hex_to_string(utils.int_to_bytes(self.__local_port, num_bytes=2), False), utils.hex_to_string(utils.int_to_bytes(self.__remote_port, num_bytes=2), False), self.__remote_addr)
def explicit_data_callback(explicit_xbee_message): print("From %s >> %s" % (explicit_xbee_message.remote_device.get_64bit_addr(), explicit_xbee_message.data.decode())) print(" - Source endpoint: %s" % utils.hex_to_string(utils.int_to_length(explicit_xbee_message.source_endpoint))) print(" - Destination endpoint: %s" % utils.hex_to_string(utils.int_to_length(explicit_xbee_message.dest_endpoint))) print(" - Cluster ID: %s" % utils.hex_to_string(utils.int_to_length(explicit_xbee_message.cluster_id))) print(" - Profile ID: %s" % utils.hex_to_string(utils.int_to_length(explicit_xbee_message.profile_id)))
def main(): print(" +-----------------------------------------------+") print(" | XBee Python Library Set/Get parameters Sample |") print(" +-----------------------------------------------+\n") local_device = XBeeDevice(PORT, BAUD_RATE) try: local_device.open() remote_device = RemoteZigBeeDevice(local_device, PARAM_VALUE_REMOTE_NODE_ADDR) # Set parameters. local_device.set_parameter(PARAM_NODE_ID, bytearray(PARAM_VALUE_NODE_ID, 'utf8')) local_device.set_parameter(PARAM_PAN_ID, PARAM_VALUE_PAN_ID) local_device.set_parameter(PARAM_DEST_ADDRESS_H, PARAM_VALUE_DEST_ADDRESS_H) local_device.set_parameter(PARAM_DEST_ADDRESS_L, PARAM_VALUE_DEST_ADDRESS_L) # Get parameters. print("Node ID: %s" % local_device.get_parameter(PARAM_NODE_ID).decode()) print("PAN ID: %s" % utils.hex_to_string(local_device.get_parameter(PARAM_PAN_ID))) print("Destination address high: %s" % utils.hex_to_string( local_device.get_parameter(PARAM_DEST_ADDRESS_H))) print("Destination address low: %s" % utils.hex_to_string( local_device.get_parameter(PARAM_DEST_ADDRESS_L))) # Set remote parameters. remote_device.set_parameter( PARAM_NODE_ID, bytearray(PARAM_VALUE_REMOTE_NODE_ID, 'utf8')) remote_device.set_parameter(PARAM_SLEEP_PER, PARAM_VALUE_REMOTE_NODE_SP) remote_device.write_changes() #make changes permanet # Get remote parameters. print("Remote Node ID: %s" % remote_device.get_parameter(PARAM_NODE_ID).decode()) print( "Remote Node SP: %s" % utils.hex_to_string(remote_device.get_parameter(PARAM_SLEEP_PER))) print("") print("All parameters were set correctly!") finally: if local_device is not None and local_device.is_open(): local_device.close()
def _generate_node_xml(node, level=0): """ Generates the XML element representing the given XBee node. Params: xbee (:class:`.AbstractXBeeDevice`): XBee node. level (Integer, optional, default=0): Indentation level. Return: :class:`xml.etree.ElementTree.Element`: Generated XML element. """ device_node = Element("device", attrib={"address": str(node.get_64bit_addr())}) device_node.text = "\n" + '\t' * level device_node.tail = "\n" + '\t' * (level - 1) net_addr = SubElement(device_node, "nwk_address") net_addr.text = str(node.get_16bit_addr()) net_addr.tail = "\n" + '\t' * level node_id = SubElement(device_node, "node_id") node_id.text = node.get_node_id() node_id.tail = "\n" + '\t' * level role = SubElement(device_node, "role") role.text = node.get_role().description role.tail = "\n" + '\t' * level if isinstance(node, RemoteZigBeeDevice) and node.parent: parent = SubElement(device_node, "parent_address") parent.text = str(node.parent.get_64bit_addr()) parent.tail = "\n" + '\t' * level hw_version = SubElement(device_node, "hw_version") if node.get_hardware_version(): hw_version.text = "0x%s" % utils.hex_to_string( [node.get_hardware_version().code], pretty=False) hw_version.tail = "\n" + '\t' * level fw_version = SubElement(device_node, "fw_version") if node.get_firmware_version(): fw_version.text = utils.hex_to_string(node.get_firmware_version(), pretty=False) fw_version.tail = "\n" + '\t' * level if not node.is_remote(): device_node.append( _generate_serial_config_xml(node.serial_port, level + 1)) network = node.get_local_xbee_device().get_network() \ if node.is_remote() else node.get_network() device_node.append( _generate_connections_xml(node, network.get_node_connections(node), level + 1)) return device_node
def main(): print(" +---------------------------------+") print(" | Get and Set Params Local/Remote |") print(" +---------------------------------+\n") local_xbee = XBeeDevice(PORT, BAUD_RATE) try: local_xbee.open() remote_xbee = RemoteXBeeDevice(local_xbee, x64bit_addr=REMOTE_DEVICE_ADDRESS) local_xbee.read_device_info() print("Read device info of local device successfully") remote_xbee.read_device_info() print("Read device info of remote device successfully") print("\nLocal:") print(local_xbee.get_node_id()) print(local_xbee.get_hardware_version()) print(hex_to_string(local_xbee.get_firmware_version())) print(local_xbee.get_protocol()) print("\nRemote:") print(remote_xbee.get_node_id()) print(remote_xbee.get_hardware_version()) print(hex_to_string(remote_xbee.get_firmware_version())) print(remote_xbee.get_protocol()) ni = ''.join( random.choice(string.ascii_letters) for i in range(random.randint(1, 20))) local_xbee.set_parameter("NI", bytearray(ni, "utf8")) param = local_xbee.get_parameter("NI") assert (param.decode() == ni) ni = ''.join( random.choice(string.ascii_letters) for i in range(random.randint(1, 20))) remote_xbee.set_parameter("NI", bytearray(ni, "utf8")) param = remote_xbee.get_parameter("NI") assert (param.decode() == ni) print("\nTest finished successfully") finally: if local_xbee is not None and local_xbee.is_open(): local_xbee.close()
def print_node_info(self): """ Print node information """ print("Node ID: %s" % (self.get_parameter("NI").decode())) print("PAN ID: %s" % (utils.hex_to_string(self.get_pan_id()))) print("MAC Address: %s" % (utils.hex_to_string(self.get_64bit_addr()))) print("Operating Mode: %s" % (self.get_operating_mode())) print("Firmware Version: %s" % (utils.hex_to_string(self.get_firmware_version()))) print("Hardware Version: %s" % (self.get_hardware_version())) print("Is Remote: %s" % (self.is_remote())) print("Is Network Co-ordinator: %s" % (self.is_coordinator()))
def send_packet(self, packet): """ Sends a packet to the XBee. The packet to send is escaped depending on the current operating mode. Args: packet (:class:`.XBeePacket`): The packet to send. Raises: InvalidOperatingModeException: If the XBee device's operating mode is not API or ESCAPED API. This method only checks the cached value of the operating mode. XBeeException: if the XBee device's communication interface is closed. .. seealso:: | :class:`.XBeePacket` """ f_type = packet.get_frame_type() # Do not allow to set a non API operating mode in the local XBee if (f_type in (ApiFrameType.AT_COMMAND, ApiFrameType.AT_COMMAND_QUEUE) and packet.parameter and packet.command.upper() == ATStringCommand.AP.command and not self.is_op_mode_valid(packet.parameter)): return comm_iface = self.__xbee.comm_iface op_mode = self.__xbee.operating_mode if self.__xbee._serial_port: self.__xbee._update_tx_stats(packet) out = packet.output(escaped=op_mode == OperatingMode.ESCAPED_API_MODE) comm_iface.write_frame(out) self._log.debug( self._LOG_PATTERN.format(comm_iface=str(comm_iface), event="SENT", opmode=op_mode, content=utils.hex_to_string(out))) # Refresh cached parameters if this method modifies some of them. if self.__xbee.serial_port and f_type in ( ApiFrameType.AT_COMMAND, ApiFrameType.AT_COMMAND_QUEUE, ApiFrameType.REMOTE_AT_COMMAND_REQUEST): node = self.__xbee # Get remote node in case of a remote at command if (f_type == ApiFrameType.REMOTE_AT_COMMAND_REQUEST and XBee64BitAddress.is_known_node_addr( packet.x64bit_dest_addr)): node = self.__xbee.get_network().get_device_by_64( packet.x64bit_dest_addr) # Store the sent AT command packet if node: if not node.get_64bit_addr(): return key = str(node.get_64bit_addr()) if key not in self._at_cmds_sent: self._at_cmds_sent[key] = {} self._at_cmds_sent[key].update({packet.frame_id: packet})
def read_AD(self, indice): logging.debug('Waiting for lock') self.lock.acquire() try: self.timeout = False logging.debug('Acquired lock') vcc = nodos_activos[indice].get_parameter("%V") vcc = int(utils.hex_to_string(vcc).replace(' ', ''), 16) # Leemos el valor crudo de las entradas analógicas raw_value_1 = nodos_activos[indice].get_adc_value(IOLINE_IN_0) raw_value_2 = nodos_activos[indice].get_adc_value(IOLINE_IN_1) raw_value_3 = nodos_activos[indice].get_adc_value(IOLINE_IN_2) raw_value_4 = nodos_activos[indice].get_adc_value(IOLINE_IN_3) # Calculamos el valor de temperatura en cada entrada en función de la tensión de alimentación y del tntc_1 = ntc10k_calculate_temp(raw_value_1, vcc) tntc_2 = ntc10k_calculate_temp(raw_value_2, vcc) tntc_3 = ntc10k_calculate_temp(raw_value_3, vcc) tntc_4 = ntc10k_calculate_temp(raw_value_4, vcc) # ************************************************************************ # ESTA ES LA PARTE DE TELEGRAF send_data_to_telegraf.main(REMOTE_NODES_ID[indice], tntc_1, tntc_2, tntc_3, tntc_4, float(vcc)) except TimeoutException: self.timeout = True logging.debug('ADC error') local_device.reset() finally: self.lock.release() return self.timeout
def create_socket_info(raw): """ Parses the given bytearray data and returns a `SocketInfo` object. Args: raw (Bytearray): received data from the `SI` command with a socket ID as argument. Returns: :class:`.SocketInfo`: The socket information, or `None` if the provided data is invalid. """ info_array = bytearray.fromhex( utils.hex_to_string(raw)).decode("utf8").strip().split( SocketInfo.__SEPARATOR) if len(info_array) != SocketInfo.__LIST_LENGTH: return None socket_id = int(info_array[0], 0) state = SocketInfoState.get_by_description(info_array[1]) protocol = IPProtocol.get_by_description(info_array[2]) local_port = int(info_array[3], 0) remote_port = int(info_array[4], 0) remote_addr = info_array[5] return SocketInfo(socket_id, state, protocol, local_port, remote_port, remote_addr)
def data_receive_callback(xbee_message): time_zone = datetime.now(timezone.utc).astimezone().tzinfo timestamp = datetime.fromtimestamp(xbee_message.timestamp, tz=time_zone).isoformat() addr = xbee_message.remote_device.get_16bit_addr() node_id = xbee_remote_devices[str(addr)]["node_id"] data = { "timestamp": timestamp, "device": { "node_id": node_id, "16bit_addr": utils.hex_to_string(addr.address) } } if xbee_message.data[0]: data["error"] = { "id": xbee_message.data[1], "message": DHT_ERROR_CODES[xbee_message.data[1]] } else: data["observations"] = { "temperature": xbee_message.data[2], "humidity": xbee_message.data[3] } print(json.dumps(data))
def _enter_in_recovery(self): """ Enters the device in recovery mode. Returns: Int: The baudrate if success or ``None`` in case of failure. """ # Set break line and baudrate self._xbee_serial_port.apply_settings(_RECOVERY_PORT_PARAMETERS) self._xbee_serial_port.purge_port() self._xbee_serial_port.break_condition = True recovery_baudrate = None timeout = time.time() + _DEVICE_BREAK_RESET_TIMEOUT while time.time() < timeout: time.sleep(0.2) try: # The first byte indicates the baudrate if self._xbee_serial_port.in_waiting > 0: read_bytes = self._xbee_serial_port.read(self._xbee_serial_port.in_waiting) _log.debug("Databytes read from recovery are %s" % repr(utils.hex_to_string(read_bytes))) if read_bytes[0] in _RECOVERY_CHAR_TO_BAUDRATE.keys(): recovery_baudrate = _RECOVERY_CHAR_TO_BAUDRATE[read_bytes[0]] # The valid byte is only the first one, so do not retry the loop break except SerialException as e: _log.exception(e) self._xbee_serial_port.break_condition = False return recovery_baudrate
def io_samples_callback(sample, remote, time): print("New sample received from %s - %s" % (remote.get_64bit_addr(), sample)) vcc = remote.get_parameter("%V") vcc = int(utils.hex_to_string(vcc).replace(' ', ''), 16) print(vcc) raw_values = parse_sample (sample) temp_1= ntc10k_calculate_temp(raw_values[0],3300) print(temp_1)
def __str__(self): """ Returns a string representation of this ATCommand. Returns: String: representation of this ATCommand. """ return "Command: %s - Parameter: %s" \ % (self.__cmd, utils.hex_to_string(self.__param))
def read_adc_task(indice): global systembusy while True or intentos[indice] < MAX_INTENTOS_LEER_DATOS: try: print("entro hilo") lock.acquire() print(threading.current_thread().getName()) # Leemos el valor del nodo para luego calcular el valor de la resistencia del termistor mediante la # ley de Ohm para un divisor de tensión #time.sleep(1) vcc = nodos_activos[indice].get_parameter("%V") vcc = int(utils.hex_to_string(vcc).replace(' ', ''), 16) # Leemos el valor crudo de las entradas analógicas raw_value_1 = nodos_activos[indice].get_adc_value(IOLINE_IN_0) raw_value_2 = nodos_activos[indice].get_adc_value(IOLINE_IN_1) raw_value_3 = nodos_activos[indice].get_adc_value(IOLINE_IN_2) raw_value_4 = nodos_activos[indice].get_adc_value(IOLINE_IN_3) # Calculamos el valor de temperatura en cada entrada en función de la tensión de alimentación y del # valor crudo #print("Nodo %s" % nodos_activos[indice]) tntc_1 = ntc10k_calculate_temp(raw_value_1, vcc) tntc_2 = ntc10k_calculate_temp(raw_value_2, vcc) tntc_3 = ntc10k_calculate_temp(raw_value_3, vcc) tntc_4 = ntc10k_calculate_temp(raw_value_4, vcc) # ************************************************************************ # ESTA ES LA PARTE DE TELEGRAF intentos[indice] = 0 print(str(datetime.now())) send_data_to_telegraf.main(REMOTE_NODES_ID[indice], tntc_1, tntc_2, tntc_3, tntc_4, float(vcc)) print("Telegraf!") # Esperamos hasta la siguiente toma de muestras espera[indice] = LONG_WAIT print("Systembusy: %s" % systembusy) print("indice %s" % indice) print("Nodos esperas %s" % espera) lock.release() #except TimeoutException as ex: except: intentos[indice] += 1 lock.release() espera[indice] = SHORT_WAIT print(REMOTE_NODES_ID[indice]) print("Systembusy: %s" % systembusy) print("ADC timeouts %s" % intentos) print("Nodos esperas %s" % espera) if intentos[indice] > MAX_INTENTOS_LEER_DATOS: #th[indice].join() raise #print("Espera: %s" % espera) print(espera[indice]) time.sleep(espera[indice])
def __str__(self): """ Called by the str() built-in function and by the print statement to compute the "informal" string representation of an object. This differs from __repr__() in that it does not have to be a valid Python expression: a more convenient or concise representation may be used instead. Returns: String: "informal" representation of this XBee16BitAddress. """ return utils.hex_to_string(self.__address)
def check_hash(f_mng, xbee_file, local_file): xb_path = xbee_file if isinstance(xbee_file, FileSystemElement): xb_path = xbee_file.path print(" Check local and XBee files ('%s', '%s')..." % (local_file, xb_path), end=" ") start = time.time() xb_hash = f_mng.get_file_hash(xb_path) print("%f" % (time.time() - start)) local_hash = get_local_file_hash(local_file) print(" XBee: %s" % utils.hex_to_string(xb_hash, pretty=False)) print(" Local: %s" % utils.hex_to_string(local_hash, pretty=False)) if xb_hash != local_hash: print(" ERROR: Hash are different!!!!\n") return False print(" Same hash!!!\n") return True
def _get_api_packet_spec_data_dict(self): """ Override method. .. seealso:: | :meth:`.XBeeAPIPacket._get_api_packet_spec_data_dict` """ base = { DictKeys.SRC_IPV4_ADDR: "%s (%s)" % (self.__source_address.packed, self.__source_address.exploded), DictKeys.RSSI: self.__rssi, DictKeys.RECEIVE_OPTIONS: self.__receive_options } if self.__io_sample is not None: base[DictKeys.NUM_SAMPLES] = 1 base[DictKeys.DIGITAL_MASK] = self.__io_sample.digital_mask base[DictKeys.ANALOG_MASK] = self.__io_sample.analog_mask # Digital values for i in range(16): if self.__io_sample.has_digital_value(IOLine.get(i)): base[IOLine.get(i).description + "digital value"] = \ utils.hex_to_string(self.__io_sample.get_digital_value(IOLine.get(i))) # Analog values for i in range(6): if self.__io_sample.has_analog_value(IOLine.get(i)): base[IOLine.get(i).description + "analog value"] = \ utils.hex_to_string(self.__io_sample.get_analog_value(IOLine.get(i))) # Power supply if self.__io_sample.has_power_supply_value(): base[ "Power supply value "] = "%02X" % self.__io_sample.power_supply_value elif self.__rf_data is not None: base[DictKeys.RF_DATA] = utils.hex_to_string(self.__rf_data) return base
def main(): print(" +------------------------------------------------+") print(" | XBee Python Library Get XBee Statistics Sample |") print(" +------------------------------------------------+\n") device = XBeeDevice(PORT, BAUD_RATE) try: device.open() # Set parameters. device.set_parameter(PARAM_NODE_ID, bytearray(PARAM_VALUE_NODE_ID, 'utf8')) device.set_parameter(PARAM_PAN_ID, PARAM_VALUE_PAN_ID) device.set_parameter(PARAM_DEST_ADDRESS_H, PARAM_VALUE_DEST_ADDRESS_H) device.set_parameter(PARAM_DEST_ADDRESS_L, PARAM_VALUE_DEST_ADDRESS_L) # Get parameters. print("Node ID: %s" % device.get_parameter(PARAM_NODE_ID).decode()) print("PAN ID: %s" % utils.hex_to_string(device.get_parameter(PARAM_PAN_ID))) print("Destination address high: %s" % utils.hex_to_string(device.get_parameter(PARAM_DEST_ADDRESS_H))) print("Destination address low: %s" % utils.hex_to_string(device.get_parameter(PARAM_DEST_ADDRESS_L))) print("") print("All parameters were set correctly!") print("Showing XBee statistics") print(" RX: packets=%d, bytes=%d" % (device.stats.rx_packets, device.stats.rx_bytes)) print(" TX: packets=%d, bytes=%d" % (device.stats.tx_packets, device.stats.tx_bytes)) print("Showing network errors") print(" Remote AT commands errors=%d" % device.stats.rmt_cmd_errors) print(" TX errors=%d" % device.stats.tx_errors) print("All XBee statistics displayed!") finally: if device is not None and device.is_open(): device.close()
def write_info_clicked(self): param_pan_id = self.pan_id_edit.text() param_node_id = self.node_id_edit.text() parameters_tuple = (param_pan_id, param_node_id) self.signal_write_info.emit(parameters_tuple) self.pan_id_edit.setText( str(hex_to_string(self.xbee_connect.new_pan_id))) self.node_id_edit.setText(str(self.xbee_connect.new_node_id))
def parse_socket_list(raw): """ Parses the given bytearray data and returns a list with the active socket IDs. Args: raw (Bytearray): received data from the ``SI`` command. Returns: List: list with the IDs of all active (open) sockets, or empty list if there is not any active socket. """ socket_list = list() ids_array = bytearray.fromhex(utils.hex_to_string(raw)).decode("utf8").strip().split(SocketInfo.__SEPARATOR) for x in ids_array: if x != "": socket_list.append(int(x, 0)) return socket_list
def type_firmware_devices(self): # Определение типа устройства и прошивки if self.xbee_connect.type_device[0:2] == '21': self.info_type_device.setText(module_type_dict.get('21')) self.hide_fields() print(module_type_dict.get('21')) if self.xbee_connect.type_device[0:2] == '23': self.info_type_device.setText(module_type_dict.get('23')) self.coord_en_lbl.hide() self.coord_en_edit.hide() self.update_info_ce_btn.hide() self.apply_change_ce_btn.hide() self.channel_ver_lbl.show() self.channel_ver_edit.show() self.update_info_jv_btn.show() self.apply_change_jv_btn.show() self.sleep_mode_lbl.hide() self.sleep_mode_edit.hide() self.update_info_sm_btn.hide() self.apply_change_sm_btn.hide() print(module_type_dict.get('23')) if self.xbee_connect.type_device[0:2] == '29': self.info_type_device.setText(module_type_dict.get('29')) print(module_type_dict.get('29')) elif self.xbee_connect.type_device[0:2] == '40': self.coord_en_lbl.show() self.coord_en_edit.show() self.update_info_ce_btn.show() self.apply_change_ce_btn.show() self.channel_ver_lbl.show() self.channel_ver_edit.show() self.update_info_jv_btn.show() self.apply_change_jv_btn.show() self.sleep_mode_lbl.show() self.sleep_mode_edit.show() self.update_info_sm_btn.show() self.apply_change_sm_btn.show() self.signal_info_type_s2c_dev.emit() if (str(hex_to_string( self.xbee_connect.coordinator_enabled)) == '01' and str( hex_to_string(self.xbee_connect.sleep_mode)) == '00'): self.info_type_device.setText( module_type_dict.get('40') + ': ' + 'Coordinator') elif (str(hex_to_string( self.xbee_connect.coordinator_enabled)) == '00' and str( hex_to_string(self.xbee_connect.sleep_mode)) == '00'): self.info_type_device.setText( module_type_dict.get('40') + ': ' + 'Router') elif (str(hex_to_string(self.xbee_connect.sleep_mode)) == '04' or str(hex_to_string(self.xbee_connect.sleep_mode)) == '05'): self.info_type_device.setText( module_type_dict.get('40') + ': ' + 'End Device')
def main(): print(" +-------------------------------------------------+") print(" | XBee Python Library Upload/Download File Sample |") print(" +-------------------------------------------------+\n") local_xbee = XBeeDevice(PORT, BAUD_RATE) fs_xbee = local_xbee try: local_xbee.open() if REMOTE_NODE_ID: # Obtain the remote XBee from the network. xbee_network = local_xbee.get_network() fs_xbee = xbee_network.discover_device(REMOTE_NODE_ID) if not fs_xbee: print("Could not find remote device '%s'" % REMOTE_NODE_ID) exit(1) filesystem_manager = fs_xbee.get_file_manager() xb_upload_path = os.path.join(XBEE_UPLOAD_DIR_PATH, os.path.basename(FILE_TO_UPLOAD_PATH)) filesystem_manager.put_file(FILE_TO_UPLOAD_PATH, xb_upload_path, overwrite=True, progress_cb=progress_upload_callback) download_path = os.path.join(LOCAL_DOWNLOAD_DIR_PATH, os.path.basename(FILE_TO_UPLOAD_PATH)) filesystem_manager.get_file(xb_upload_path, download_path, progress_cb=progress_download_callback) print("\nFile hash summary\n-----------------------") print("%s %s" % ("Local:".ljust(15), get_sha256_hash(FILE_TO_UPLOAD_PATH).upper())) print("%s %s" % ("Uploaded:".ljust(15), utils.hex_to_string(filesystem_manager.get_file_hash(xb_upload_path), pretty=False))) print("%s %s\n" % ("Downloaded:".ljust(15), get_sha256_hash(download_path).upper())) except (XBeeException, FileSystemException) as e: print("ERROR: %s" % str(e)) exit(1) finally: if local_xbee and local_xbee.is_open(): local_xbee.close()
def start_connection(self): self.local_device = XBeeDevice(self.com, self.speed) try: self.local_device.open() self.connected = True # делаем для теста print print('ПОРТ ОТКРЫТ. Устройство готово к работе') self.type_device = hex_to_string( self.local_device.get_firmware_version()) print("Firmware version: %s" % self.type_device) self.successful_connection_signal.emit() except Exception as e: self.connected = False print(e) self.error_connection_signal.emit() self.local_device.close()
def write_read_chunks(f_mng, path): file_path = os.path.join(path, os.path.basename(LOCAL_FILE_5K)) print(" * Writing to file chunk by chunk '%s'..." % file_path) def w_chunk_cb(n_bytes, percent, status): if status: st = FSCommandStatus.get(status) msg = str(st) if st else "Unknown status (0x%0.2X)" % status print(" ERROR WRITE '%s': %s" % (file_path, msg)) return print(" '%s' written %d bytes: %f%%" % (file_path, n_bytes, percent)) start = time.time() w_proc = f_mng.write_file(file_path, offset=0, secure=False, options=[], progress_cb=w_chunk_cb) with open(LOCAL_FILE_5K, "rb+") as file: try: data = file.read(1024) while data: w_proc.next(data, last=False) data = file.read(1024) finally: w_proc.next("", last=True) print(" Time: %f\n" % (time.time() - start)) print(" * Reading file chunk by chunk '%s'..." % file_path) def r_chunk_cb(r_data, percent, _size, status): if status: st = FSCommandStatus.get(status) msg = str(st) if st else "Unknown status (0x%0.2X)" % status print(" ERROR READ: '%s': %s" % (file_path, msg)) return print(" '%s' read %d bytes: %f%%" % (file_path, len(r_data), percent)) # print(" Data: %s" % r_data.decode('utf-8')) start = time.time() r_proc = f_mng.read_file(file_path, offset=0, progress_cb=r_chunk_cb) data = bytearray() c_data = r_proc.next(size=1024, last=False) data += c_data while c_data: # print(" Chunk: %s\n" % c_data.decode('utf-8')) c_data = r_proc.next(size=1024, last=False) data += c_data print(" Time: %f\n" % (time.time() - start)) # print(" Complete data read '%s':\n %s\n" % (file_path, data.decode('utf-8'))) xb_hash = f_mng.get_file_hash(file_path) local_hash = data_hash(data) print(" Hash XBee: %s" % utils.hex_to_string(xb_hash, pretty=False)) print(" Hash Local: %s" % utils.hex_to_string(local_hash, pretty=False)) if xb_hash != local_hash: print(" ERROR HASH: Hash are different!!!!\n") return False print(" Same hash!!!\n") return True
def main(argv): if len(argv) < 2: print("Usage: fs_test.py <port> <baud_rate> <r_name> <ota-len>") exit(1) print(" +------------------+") print(" | File System test |") print(" +------------------+\n") log_enabled = False test_cnt = 1 if log_enabled: utils.enable_logger("digi.xbee.devices", logging.DEBUG) utils.enable_logger("digi.xbee.reader", logging.DEBUG) utils.enable_logger("digi.xbee.filesystem", logging.DEBUG) local_xbee = XBeeDevice(argv[0], int(argv[1])) dut = local_xbee try: local_xbee.open() if len(argv) > 2: dut = local_xbee.get_network().discover_device(argv[2]) dut.set_ota_max_block_size(int(argv[3], 0) if len(argv) > 3 else 0) script_start = time.time() f_mng = dut.get_file_manager() print("%2d. Formatting..." % test_cnt) start = time.time() info = f_mng.format(vol="/flash") print(" Time: %f" % (time.time() - start)) print(" %s\n" % info) test_cnt += 1 root = f_mng.get_root() print("%2d. Listing directory '%s'..." % (test_cnt, root.path)) start = time.time() files = f_mng.list_directory(root) flash_dir = files[0] print(" Time: %f" % (time.time() - start)) print(" Contents of '%s'" % root.path) for file in files: print(" %s" % str(file)) print("") test_cnt += 1 print("%2d. Getting volume info '%s'..." % (test_cnt, flash_dir.path)) start = time.time() info = f_mng.get_volume_info(vol=flash_dir) print(" Time: %f" % (time.time() - start)) print(" %s\n" % info) test_cnt += 1 print("%2d. Creating directory '%s'..." % (test_cnt, PATH_TO_UPLOAD)) start = time.time() upload_dir = f_mng.make_directory(PATH_TO_UPLOAD, mk_parents=True)[0] print(" Time: %f" % (time.time() - start)) print("") test_cnt += 1 print("%2d. Putting complete directory '%s'..." % (test_cnt, PATH_TO_UPLOAD)) def put_dir_cb(percent, dest, src): print(" Uploading '%s' to '%s' bytes: %f%%" % (src, dest, percent)) start = time.time() f_mng.put_dir(os.path.dirname(RESOURCES), dest=PATH_TO_UPLOAD, verify=True, progress_cb=put_dir_cb) print(" Time: %f" % (time.time() - start)) print("") test_cnt += 1 print("%2d. Put/get secure file '%s'..." % (test_cnt, os.path.join(upload_dir.path, "secure.txt"))) try: if not put_get_file(f_mng, LOCAL_FILE_2K, upload_dir.path, name="secure.txt", secure=True): exit(1) except FileSystemException as exc: if exc.status == FSCommandStatus.INVALID_PARAMETER.code: print(" ***** SECURE NOT SUPPORTED: %s" % str(exc)) test_cnt += 1 print("\n%2d. Write/read file chunks '%s'..." % (test_cnt, os.path.join(flash_dir.path, os.path.basename(LOCAL_FILE_5K)))) if not write_read_chunks(f_mng, flash_dir.path): exit(1) test_cnt += 1 print("%2d. Overwrite file '%s'..." % (test_cnt, os.path.join(flash_dir.path, os.path.basename(LOCAL_FILE_5K)))) if not put_get_file(f_mng, LOCAL_FILE_2K, flash_dir.path, name=os.path.basename(LOCAL_FILE_5K), overwrite=True): exit(1) test_cnt += 1 path_long = "/flash" for i in range(1, 26): path_long = os.path.join(path_long, "directory%d" % i) print("%2d. Creating long directory '%s'..." % (test_cnt, path_long)) start = time.time() dirs = f_mng.make_directory(path_long, mk_parents=True) print(" Time: %f" % (time.time() - start)) print("") test_cnt += 1 print("%2d. Put/get file to long directory '%s'..." % (test_cnt, os.path.join(dirs[len(dirs) - 1].path, os.path.basename(LOCAL_FILE_1K)))) if not put_get_file(f_mng, LOCAL_FILE_1K, dirs[len(dirs) - 1].path): exit(1) test_cnt += 1 print("%2d. Creating files in created directories '%s'..." % (test_cnt, dirs[0].path)) cnt = 0 for directory in dirs: cnt += 1 file_name = "file_%d.txt" % cnt file_path = os.path.join(directory.path, file_name) def w_p_cb(n_bytes, percent, status): if status: st = FSCommandStatus.get(status) msg = str( st) if st else "Unknown status (0x%0.2X)" % status print(" ERROR WRITE '%s': %s" % (file_name, msg)) return print(" '%s' written %d bytes: %f%%" % (file_name, n_bytes, percent)) def r_p_cb(r_data, percent, _size, status): if status: st = FSCommandStatus.get(status) msg = str( st) if st else "Unknown status (0x%0.2X)" % status print(" ERROR READ: '%s': %s" % (file_name, msg)) return print(" '%s' read %d bytes: %f%%" % (file_name, len(r_data), percent)) # print(" Data: %s" % r_data.decode('utf-8')) size = cnt * 20 offset = cnt + 31 data = read_local_file(LOCAL_FILE_3K, offset=offset, size=size) print(" Writing to file '%s'..." % file_path) start = time.time() w_proc = f_mng.write_file(file_path, offset=0, secure=False, options=[], progress_cb=w_p_cb) w_proc.next(data, last=True) print(" Time: %f" % (time.time() - start)) print(" Reading file '%s'..." % file_path) start = time.time() r_proc = f_mng.read_file(file_path, offset=0, progress_cb=r_p_cb) c_data = r_proc.next(size=-1, last=True) print(" Time: %f" % (time.time() - start)) # print(" Complete data read '%s':\n %s\n" % (file_name, c_data.decode('utf-8'))) xb_hash = f_mng.get_file_hash(file_path) local_hash = data_hash(data) print(" Hash XBee: %s" % utils.hex_to_string(xb_hash, pretty=False)) print(" Hash Local: %s" % utils.hex_to_string(local_hash, pretty=False)) if xb_hash != local_hash: print(" ERROR HASH: Hash are different!!!!\n") exit(1) print(" Same hash!!!\n") test_cnt += 1 print("%2d. Listing files in subdirectories of '%s'..." % (test_cnt, dirs[0].path)) for directory in dirs: print(" Listing directory '%s'..." % directory.name) start = time.time() file_list = f_mng.list_directory(directory) print(" Time: %f" % (time.time() - start)) print(" Contents of '%s':" % directory.name) for file in file_list: print(" %s" % str(file)) print("") test_cnt += 1 print("%2d. Listing directory '%s'..." % (test_cnt, flash_dir.path)) start = time.time() flash_files = f_mng.list_directory(flash_dir) print(" Time: %f" % (time.time() - start)) print(" Contents of '%s'" % flash_dir.path) for file in flash_files: print(" %s" % str(file)) print("") test_cnt += 1 print("%2d. Getting volume info '%s'..." % (test_cnt, flash_dir.path)) start = time.time() info = f_mng.get_volume_info(vol=flash_dir) print(" Time: %f" % (time.time() - start)) print(" %s\n" % info) test_cnt += 1 print("%2d. Full volume ..." % test_cnt) for i in range(1, 51): try: if not put_get_file(f_mng, LOCAL_FILE_10K, upload_dir.path, name="f_10K_%d.txt" % i): exit(1) except FileSystemException as exc: if exc.status == FSCommandStatus.VOLUME_FULL.code: print(" VOLUME FULL: %s" % str(exc)) break test_cnt += 1 # Sometimes (802.15.4) when the volume is full the device resets itself, # so reset it before continuing, and wait for it to be joined and to # accommodate the file system. dut.reset() if dut.is_remote(): time.sleep(20) print("%2d. Listing directory '%s'..." % (test_cnt, upload_dir.path)) start = time.time() upload_files = f_mng.list_directory(upload_dir) print(" Time: %f" % (time.time() - start)) print(" Contents of '%s'" % upload_dir.path) for file in upload_files: print(" %s" % str(file)) print("") test_cnt += 1 print("%2d. Getting volume info '%s'..." % (test_cnt, flash_dir.path)) start = time.time() info = f_mng.get_volume_info(vol=flash_dir) print(" Time: %f" % (time.time() - start)) print(" %s\n" % info) test_cnt += 1 print("%2d. Removing all entries in '%s'..." % (test_cnt, flash_dir.path)) for file in flash_files: print(" Removing '%s'..." % file.path, end=" ") start = time.time() f_mng.remove(file.path, rm_children=True) print("%f" % (time.time() - start)) print("") test_cnt += 1 print("%2d. Getting volume info '%s'..." % (test_cnt, flash_dir.path)) start = time.time() info = f_mng.get_volume_info(vol=flash_dir) print(" Time: %f" % (time.time() - start)) print(" %s\n" % info) test_cnt += 1 print("\nTest finished successfully: %f s" % (time.time() - script_start)) except (XBeeException, FileSystemException) as e: print("ERROR: %s" % str(e)) exit(1) finally: if local_xbee is not None and local_xbee.is_open(): local_xbee.close()
def __execute_user_callbacks(self, xbee_packet, remote=None): """ Executes callbacks corresponding to the received packet. Args: xbee_packet (:class:`.XBeeAPIPacket`): the received packet. remote (:class:`.RemoteXBeeDevice`): the XBee device that sent the packet. """ # All packets callback. self.__packet_received(xbee_packet) # Data reception callbacks if (xbee_packet.get_frame_type() == ApiFrameType.RX_64 or xbee_packet.get_frame_type() == ApiFrameType.RX_16 or xbee_packet.get_frame_type() == ApiFrameType.RECEIVE_PACKET): _data = xbee_packet.rf_data is_broadcast = xbee_packet.receive_options == ReceiveOptions.BROADCAST_PACKET self.__data_received(XBeeMessage(_data, remote, time.time(), is_broadcast)) self._log.info(self._LOG_PATTERN.format(port=self.__xbee_device.serial_port.port, event="RECEIVED", fr_type="DATA", sender=str(remote.get_64bit_addr()) if remote is not None else "None", more_data=utils.hex_to_string(xbee_packet.rf_data))) # Modem status callbacks elif xbee_packet.get_frame_type() == ApiFrameType.MODEM_STATUS: self.__modem_status_received(xbee_packet.modem_status) self._log.info(self._LOG_PATTERN.format(port=self.__xbee_device.serial_port.port, event="RECEIVED", fr_type="MODEM STATUS", sender=str(remote.get_64bit_addr()) if remote is not None else "None", more_data=xbee_packet.modem_status)) # IO_sample callbacks elif (xbee_packet.get_frame_type() == ApiFrameType.RX_IO_16 or xbee_packet.get_frame_type() == ApiFrameType.RX_IO_64 or xbee_packet.get_frame_type() == ApiFrameType.IO_DATA_SAMPLE_RX_INDICATOR): self.__io_sample_received(xbee_packet.io_sample, remote, time.time()) self._log.info(self._LOG_PATTERN.format(port=self.__xbee_device.serial_port.port, event="RECEIVED", fr_type="IOSAMPLE", sender=str(remote.get_64bit_addr()) if remote is not None else "None", more_data=str(xbee_packet.io_sample))) # Explicit packet callbacks elif xbee_packet.get_frame_type() == ApiFrameType.EXPLICIT_RX_INDICATOR: is_broadcast = False # If it's 'special' packet, notify the data_received callbacks too: if self.__is_special_explicit_packet(xbee_packet): self.__data_received(XBeeMessage(xbee_packet.rf_data, remote, time.time(), is_broadcast)) self.__explicit_packet_received(PacketListener.__expl_to_message(remote, is_broadcast, xbee_packet)) self._log.info(self._LOG_PATTERN.format(port=self.__xbee_device.serial_port.port, event="RECEIVED", fr_type="EXPLICIT DATA", sender=str(remote.get_64bit_addr()) if remote is not None else "None", more_data=utils.hex_to_string(xbee_packet.rf_data))) # IP data elif xbee_packet.get_frame_type() == ApiFrameType.RX_IPV4: self.__ip_data_received( IPMessage(xbee_packet.source_address, xbee_packet.source_port, xbee_packet.dest_port, xbee_packet.ip_protocol, xbee_packet.data)) self._log.info(self._LOG_PATTERN.format(port=self.__xbee_device.serial_port.port, event="RECEIVED", fr_type="IP DATA", sender=str(xbee_packet.source_address), more_data=utils.hex_to_string(xbee_packet.data))) # SMS elif xbee_packet.get_frame_type() == ApiFrameType.RX_SMS: self.__sms_received(SMSMessage(xbee_packet.phone_number, xbee_packet.data)) self._log.info(self._LOG_PATTERN.format(port=self.__xbee_device.serial_port.port, event="RECEIVED", fr_type="SMS", sender=str(xbee_packet.phone_number), more_data=xbee_packet.data))