class XBeeHandler(Thread): def __init__(self, inQ, outQ, XBeePort): super(XBeeHandler, self).__init__() self.daemon = True self.name = 'XBH' self.inQ = inQ self.outQ = outQ # Initialize XBee device: self.device = ZigBeeDevice(XBeePort, 9600) self.device.open() self.device.add_data_received_callback(self.receiveCB) def run(self): while (True): msg = self.outQ.get() # Blocking call self.device.send_data(msg.sender, msg.data) if DEBUG: print('XBH - Sent %s bytes to %s' % (len(msg.data), msg.sender.get_64bit_addr())) def receiveCB(self, xbee_message): sender = xbee_message.remote_device data = xbee_message.data msg = MSG(sender, data) self.inQ.put(msg) if DEBUG: print('XBH - Received %s bytes from %s' % (len(msg.data), sender.get_64bit_addr())) def terminate(self): self.device.close() if DEBUG: print('XBH - Closed connection with RF device.')
def main(): zigbee = ZigBeeDevice('/dev/ttyUSB0', 9600) try: zigbee.open() data = 'Zigbee node %s sending data' % (zigbee.get_node_id()) data = data.encode('utf-8') rssi_raw = zigbee.get_parameter("DB") rssi_val = struct.unpack('=B', rssi_raw) print(rssi_val) #packet_receive = zigbee.send_data_broadcast(data) #data_packet = packets.XBeePacket() #packet = data_packet.create_packet(data, OperatingMode.API_MODE) #packet_receive = zigbee.send_packet(packet) def packet_received_callback(packet): packet_dict = packet.to_dict() api_data = packet_dict[DictKeys.FRAME_SPEC_DATA][DictKeys.API_DATA] print(api_data) print(packet_receive) #zigbee.add_packet_received_callback(packet_received_callback) finally: if zigbee is not None and zigbee.is_open(): zigbee.close()
def main(): print(" +-----------------------------------------------+") print(" | XBee Python Library Send Explicit Data Sample |") print(" +-----------------------------------------------+\n") device = ZigBeeDevice(PORT, BAUD_RATE) try: device.open() # Obtain the remote XBee local_xbee from the XBee network. xbee_network = device.get_network() remote_device = xbee_network.discover_device(REMOTE_NODE_ID) if remote_device is None: print("Could not find the remote local_xbee") exit(1) print("Sending explicit data to %s >> %s..." % (remote_device.get_64bit_addr(), DATA_TO_SEND)) device.send_expl_data(remote_device, DATA_TO_SEND, SOURCE_ENDPOINT, DESTINATION_ENDPOINT, CLUSTER_ID, PROFILE_ID) print("Success") finally: if device is not None and device.is_open(): device.close()
def main(): print(" +--------------------------------------------------+") print(" | XBee Python Library Receive Explicit Data Sample |") print(" +--------------------------------------------------+\n") device = ZigBeeDevice(PORT, BAUD_RATE) try: device.open() device.set_api_output_mode(APIOutputMode.EXPLICIT) 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))) device.flush_queues() device.add_expl_data_received_callback(explicit_data_callback) print("Waiting for data in explicit format...\n") input() finally: if device is not None and device.is_open(): device.close()
def SendCommand(): device = ZigBeeDevice(PORT, BAUD_RATE) #print(hora_atual[11:19]) try: device.open() device.flush_queues() cursor.execute("SELECT `MAC` FROM `ESTACAO`") resultado = cursor.fetchall() #verifica se o MAC já foi inserido no banco de dados for linha in resultado: res = str(linha) res = res[2:18] dados = ("\x00\x01\x03\x01\x00\x04") leit = SendCommandEnvRec(res, dados, device) hora_atual = HoraAtual() data_atual = DataAtual() print("Tempertura:" + leit) if leit != '0': cursor.execute( "INSERT INTO `LEITURASENSOR`( `MACROT`, `CODSEN`, `DAT`, `HOR`, `VALO`) VALUES ('" + res + "',1,'" + data_atual + "','" + hora_atual + "','" + leit + "')") conexao.commit() #time.sleep(1) dados = ("\x00\x02\x03\x01\x00\x04") leit = SendCommandEnvRec(res, dados, device) hora_atual = HoraAtual() data_atual = DataAtual() if leit != '0': leit = "%.3f" % float(leit) print("Pressão:" + leit) cursor.execute( "INSERT INTO `LEITURASENSOR`( `MACROT`, `CODSEN`, `DAT`, `HOR`, `VALO`) VALUES ('" + res + "',2,'" + data_atual + "','" + hora_atual + "','" + leit + "')") conexao.commit() #time.sleep(1) dados = ("\x00\x03\x03\x01\x00\x04") leit = SendCommandEnvRec(res, dados, device) print("Umidade:" + leit) hora_atual = HoraAtual() data_atual = DataAtual() if leit != '0': cursor.execute( "INSERT INTO `LEITURASENSOR`( `MACROT`, `CODSEN`, `DAT`, `HOR`, `VALO`) VALUES ('" + res + "',3,'" + data_atual + "','" + hora_atual + "','" + leit + "')") conexao.commit() #time.sleep(1) dados = ("\x00\x00\x01\x02\x00\x01\x01") leit = SendCommandEnvRec(res, dados, device) finally: if device is not None and device.is_open(): device.close()
class xbee_write(): def __init__(self): rospy.init_node("xbee_write") PORT = rospy.get_param("~device", "/dev/ttyUSB0") BAUD_RATE = rospy.get_param("~baud", 115200) REMOTE_NODE_ID = rospy.get_param("~destination", "REMOTE") self.device = ZigBeeDevice(PORT, BAUD_RATE) self.SOURCE_ENDPOINT = 0xA0 self.DESTINATION_ENDPOINT = 0xA1 self.CLUSTER_ID = 0x1554 self.PROFILE_ID = 0x1234 try: self.device.open() xbee_network = self.device.get_network() self.remote_device = xbee_network.discover_device(REMOTE_NODE_ID) if self.remote_device is None: rospy.logerr("Could not find the remote local_xbee: {}".format( REMOTE_NODE_ID)) self.device.close() self.run() except Exception as exc: rospy.logerr(exc) def run(self): formatspec = 'cc?' while not rospy.is_shutdown(): try: cmd = raw_input( "Input commands, press Ctrl+D (linux) or Ctrl+Z+return (Windows) to exit, press h for list of commands:" ) if cmd == 'h': print( "st[X]: start mission X=1, stop mission X=0\nrt[X]: Return home X=1, Resume Mission X=0" ) continue if len(cmd) == 3: cmd = (cmd[0], cmd[1], str2bool(cmd[2])) data = struct.pack(formatspec, *cmd) rospy.loginfo("Sending explicit data to {} >> {}".format( self.remote_device.get_64bit_addr(), data)) self.device.send_expl_data(self.remote_device, data, self.SOURCE_ENDPOINT, self.DESTINATION_ENDPOINT, self.CLUSTER_ID, self.PROFILE_ID) except EOFError: rospy.loginfo("Exiting") rospy.signal_shutdown("User Exit") except struct.error: rospy.logerr( "Bad command, must contain 2 characters and a binary") self.device.close()
def ask_all_sensors(remote_devices_id, status, url, filename, lock): lock.acquire() local_xbee = ZigBeeDevice(PORT, BAUD_RATE) message = {'act': 1} data_string = json.dumps(message) measures = defaultdict(list) try: local_xbee.open() xbee_network = local_xbee.get_network() for xbee_id in remote_devices_id: remote_xbee = xbee_network.discover_device(xbee_id) if remote_xbee is None: print('No se ha podido encontrar el dispositivo remoto') continue print('Enviando datos asincronamente %s >> %s' % (remote_xbee.get_64bit_addr(), data_string)) local_xbee.send_data(remote_xbee, data_string) xbee_message = local_xbee.read_data(3) measure = xbee_message.data.decode() print('Received message from %s: %s' % (xbee_message.remote_device.get_64bit_addr(), measure)) json_measure = json.loads(measure) json_measure['timestamp'] = str(datetime.utcnow()) measures[xbee_id].append(json_measure) #if connected sends the file, if not, keeps it write_to_file(filename, status, measures, url) finally: if local_xbee is not None and local_xbee.is_open(): local_xbee.close() lock.release()
def main(): print(" +---------------------------------------------------------+") print(" | XBee Python Library Send Broadcast Explicit Data Sample |") print(" +---------------------------------------------------------+\n") device = ZigBeeDevice(PORT, BAUD_RATE) try: device.open() print("Sending explicit broadcast data: %s..." % DATA_TO_SEND) device.send_expl_data_broadcast(DATA_TO_SEND, SOURCE_ENDPOINT, DESTINATION_ENDPOINT, CLUSTER_ID, PROFILE_ID) print("Success") finally: if device is not None and device.is_open(): device.close()
def discover_network(remote_devices_id, lock): lock.acquire() local_xbee = ZigBeeDevice(PORT, BAUD_RATE) try: local_xbee.open() xbee_network = local_xbee.get_network() # discovering the xbee network xbee_network.start_discovery_process() while xbee_network.is_discovery_running(): time.sleep(0.5) remote_devices = xbee_network.get_devices() for xbee in remote_devices: remote_devices_id.add(xbee.get_node_id()) finally: if local_xbee is not None and local_xbee.is_open(): local_xbee.close() lock.release()
def ask_sensor(data, message_callback, lock): message = data['message'] data_string = json.dumps(message) REMOTE_NODE_ID = data['sensor'] lock.acquire() local_xbee = ZigBeeDevice(PORT, BAUD_RATE) try: local_xbee.open() xbee_network = local_xbee.get_network() remote_xbee = xbee_network.discover_device(REMOTE_NODE_ID) if remote_xbee is None: print('No se ha podido encontrar el dispositivo remoto') exit(1) print('Enviando datos asincronamente %s >> %s' % (remote_xbee.get_64bit_addr(), data_string)) local_xbee.send_data(remote_xbee, data_string) xbee_message = local_xbee.read_data(3) print('Received message from %s: %s' % (xbee_message.remote_device.get_64bit_addr(), xbee_message.data.decode())) sensor_data = { 'sender': 'section 2', 'receiver': data['sender'], 'message': json.loads(xbee_message.data.decode()) } message_callback(sensor_data) finally: if local_xbee is not None and local_xbee.is_open(): local_xbee.close() lock.release()
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_value( APIOutputModeBit.calculate_api_output_mode_value( device.get_protocol(), {APIOutputModeBit.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(): ser = serial.Serial('/dev/ttyAMA0', 9600) port = '/dev/ttyAMA0' baud = 9600 print('Port Opened') data = 'Hello' remote_node_id = bytearray.fromhex('00 21 2E FF FF 02 45 01') #zigbee = ZigBee(ser) zigbee = ZigBeeDevice(port, baud) zigbee.open() print('Device open') zigbee_net = zigbee.get_network() #remote = zigbee_net.discover_device(remote_node_id) print('Network open...sending data') while True: #zigbee.send('at', frame_id='A', command='DH') #zigbee.write('1') zigbee.send_data(remote_node_id, data) print('...') response = zigbee.wait_read_frame() print(response)
def main(): global SPACE_CONFIGURATION # read in our space configuration with open(os.path.join(ROOT_DIR, 'config', 'garage_a_v2.json')) as f: SPACE_CONFIGURATION = json.load(f) # create and open a serial connection to the device device = ZigBeeDevice(PORT, BAUD_RATE) device.open() try: device.flush_queues() print("Waiting for data...\n") # add a callback for the io sample device.add_io_sample_received_callback(on_io_sample_received) while True: time.sleep(1) finally: if device is not None and device.is_open(): device.close()
print("from: {}, RSSI: {}, Data: {}".format(addr, rssi, bytes(data).decode())) return packet_received_callback # # def do_discovery(device): # network = device.get_network() # network.start_discovery_process() # # while network.is_discovery_running(): # time.sleep(0.5) # # print("Discovery complete!") # devices = network.get_devices() # for d in devices: # name = d.get_parameter("NI").decode("utf-8") # print("Name is: " + name) # if name == "jeremy": # d.set_parameter("NI", "NEWNAME".encode()) # d.execute_command("WR") # print("renamed!") if __name__ == "__main__": my_device = ZigBeeDevice("COM5", 9600) my_device.open() set_node_and_pan(my_device, "test_device", "1234") my_device.add_packet_received_callback(generate_packet_callback(my_device)) print("At startup, last received packet strength: -" + str(ord(my_device.get_parameter("DB"))) + "dB")
import serial import time from digi.xbee.devices import ZigBeeDevice from digi.xbee.models.mode import OperatingMode arduino = ZigBeeDevice('/dev/ttyS6', 9600) arduino.open() print('done') print(arduino.get_64bit_addr())
prev_err = 0 prev_time = 0 Driving_Time = 50 Kp = 1 Ki = 0.5 Kd = 0 servo.ChangeDutyCycle(standard) servo.ChangeDutyCycle(0) dc.ChangeDutyCycle(0) data_set = open("Data_PID.txt", 'a') try: device.open() xbee_network = device.get_network() remote_device = xbee_network.discover_device(REMOTE_NODE_ID) xbee_network.set_discovery_timeout(10) xbee_network.clear() xbee_network.add_device_discovered_callback(callback_device_discovered) xbee_network.add_discovery_process_finished_callback( callback_discovery_finished) xbee_network.start_discovery_process() print("Discovering remote XBee devices...") while xbee_network.is_discovery_running(): time.sleep(0.1)
class xbee_read(): def __init__(self): rospy.init_node("xbee_read") PORT = rospy.get_param("~device", "/dev/ttyUSB1") BAUD_RATE = rospy.get_param("~baud", 115200) self.joy_msg = Joy() self.device = ZigBeeDevice(PORT, BAUD_RATE) hz = rospy.Rate(10) self.pub = rospy.Publisher("joy", Joy, queue_size=10) try: self.device.open() except Exception as exc: rospy.logerr(exc) if self.device.is_open: self.device.close() return self.device.flush_queues() self.device.set_api_output_mode(APIOutputMode.EXPLICIT) rospy.sleep(rospy.Duration.from_sec(2.0)) rospy.on_shutdown(self.shutdown_handle) while not rospy.is_shutdown(): try: data_msg = self.device.read_expl_data() except TimeoutException: rospy.logerr("Timeout!") except InvalidPacketException: rospy.logerr("Bad Checksum") except XBeeException as exc: rospy.logerr("XBee Error!: {}".format(exc)) else: if data_msg: self.handle_data(data_msg) hz.sleep() def shutdown_handle(self): if self.device._is_open: self.device.close() def handle_data(self, data_msg): if len(data_msg.data) == 16: formatspec = '>cchhhhh????' self.parse_joystick(struct.unpack(formatspec, data_msg.data)) elif len(data_msg.data) == 3: formatspec = 'cc?' self.parse_commands(struct.unpack(formatspec, data_msg.data)) def parse_joystick(self, data): rospy.loginfo(data[2:7]) self.joy_msg.axes = data[2:7] self.joy_msg.buttons = data[7:] rospy.logdebug(data) self.joy_msg.header.stamp = rospy.Time.now() self.joy_msg.header.frame_id = "override" self.pub.publish(self.joy_msg) def parse_commands(self, data): cmd = data[0] + data[1] if cmd == 'st': if data[2]: rospy.loginfo("Start Mission Request") try: rospy.wait_for_service("supervisor/start", 2.0) except: rospy.logerr("No supervisor/start service available.") else: service_handle = rospy.ServiceProxy( "supervisor/start", Trigger) response = service_handle() if response.success: rospy.loginfo( "Successful start mission request (xbee)") else: rospy.logerr(response.message) else: rospy.loginfo("Stop Mission Request") try: rospy.wait_for_service("supervisor/pause", 2.0) except: rospy.logerr("No supervisor/pause service available.") else: service_handle = rospy.ServiceProxy( "supervisor/pause", SetBool) response = service_handle(True) if response.success: rospy.loginfo( "Successful pause mission request (xbee)") else: rospy.logerr(response.message) elif cmd == 'rt': if data[2]: rospy.loginfo("Return Home Request") else: rospy.loginfo("Resume Mission Request") try: rospy.wait_for_service("supervisor/pause", 2.0) except: rospy.logerr("No supervisor/pause service available.") else: service_handle = rospy.ServiceProxy( "supervisor/pause", SetBool) response = service_handle(False) if response.success: rospy.loginfo( "Successful resume mission request (xbee)") else: rospy.logerr(response.message) else: rospy.logwarn("Unknown Command: {}".format(cmd))
def main(argv): if len(argv) != 3: print("Usage: long_test.py <port> <baud_rate> <duration_in_seconds>") return print(" +-------------------------------+") print(" | Long duration and stress test |") print(" +-------------------------------+\n") port = argv[0] baud_rate = int(argv[1]) duration = int(argv[2]) device = ZigBeeDevice(port, baud_rate) try: device.open() # Discover the network. network = device.get_network() network.start_discovery_process() print("Discovering network...") # Wait until the discovery process has finished. while network.is_discovery_running(): time.sleep(0.1) if not network.has_devices(): print("No remote modules in the network") return # Get the first device of the network that is not an end device. remote = None for dev in network.get_devices(): if utils.bytes_to_int(dev.get_parameter("SM")) == 0: remote = dev break if remote is None: print("No routers in the network") return print("Selected remote device: %s" % remote) # Add a data received callback. def data_callback(message): if message.remote_device.get_64bit_addr() == remote.get_64bit_addr( ): print("%s - [C] - %s" % (datetime.datetime.now(), message.data.decode())) # Ensure that the sent and received messages are equal. assert (data == message.data.decode()) device.add_data_received_callback(data_callback) print("Sending data...\n") dead_line = time.time() + duration while dead_line > time.time(): retries = MAX_RETRIES data_received = False while not data_received: try: data = ''.join( random.choice(string.ascii_letters) for i in range(random.randint(1, 84))) print("%s - [S] - %s" % (datetime.datetime.now(), data)) # Send explicit data to the loopback cluster. device.send_expl_data(remote, data, SOURCE_ENDPOINT, DEST_ENDPOINT, CLUSTER_ID, PROFILE_ID) # Read new data from the remote device. msg = device.read_data_from(remote, 10) print("%s - [P] - %s" % (datetime.datetime.now(), msg.data.decode())) data_received = True # Ensure that the sent and received messages are equal. assert (data == msg.data.decode()) except TimeoutException as ex: retries -= 1 if retries == 0: raise ex # Wait some time between 1 and 5 seconds. time.sleep(random.randint(1, 5)) print("\nTest finished successfully") finally: if device is not None and device.is_open(): device.close()
# _____ _____ _____ # | | |__ | | | EmbeddedAF/src/master/xbeeTesting.py # | | | | __| | | | Nikolai Nymo # |_|___|_____|_|___| 19-04-18 from digi.xbee.devices import ZigBeeDevice import sys if sys.version_info[0] < 3: raise "Must be using Python 3" from time import sleep # Instantiate device: XBee_zig = ZigBeeDevice('/dev/tty.SLAB_USBtoUART', 9600) # ('port', baud) XBee_zig.open() # Opens serial interface to device # Define callback. def xbRxCallback(xbee_message): address = xbee_message.remote_device.get_64bit_addr() data = xbee_message.data.decode("utf8") print("Received data from %s: %s" % (address, data)) # Add the callback. XBee_zig.add_data_received_callback(xbRxCallback) # Read device information (more getters are availiable): addr_64 = XBee_zig.get_64bit_addr() node_id = XBee_zig.get_node_id() pan_id = XBee_zig.get_pan_id() print('Opened device with addr') print(addr_64) print('and node ID')