def main(): print(" +-----------------------------------------+") print(" | Wireless Sleep Monitoring |") print(" | \"No Strings Attached!\" |") print(" +-----------------------------------------+\n") inp = input("Press enter to start!\nPress enter a second time to stop!") #declaring device and grapher device = XBeeDevice(PORT, BAUD_RATE) try: #Opening device device.open() device.flush_queues() def data_receive_callback(xbee_message): print(xbee_message.data.decode()) device.add_data_received_callback(data_receive_callback) print("Waiting for data...\n") input() #For some reason python 3.8 causes delay here finally: if device is not None and device.is_open(): #Closing device stops callbacks device.close()
def xbeeProcess(module , exitEvent ): global device try: #intialise logging element if module["logging"]["logFile"]: #If File defined load logs to file in write mode logging.basicConfig(filename=module["logging"]["logFile"], filemode='w', level=module["logging"]["level"]) else: #log to stdout logging.basicConfig(level=module["logging"]["level"]) #Initialize the device device = XBeeDevice(module["xbee"]["serialPort"] , module["xbee"]["baudRate"]) #open the Device device.open() #Add Callback for Recieving data device.add_data_received_callback(dataReceiveCallback) #Read configs from xbee Config Command(1 , None , None) server = socketserver.TCPServer(("localhost", module["xbee"]["tcpPort"]) , XbeeTCPHandler) #settimeout for handle requests server.timeout = 0.5 while not exitEvent.is_set(): server.handle_request() time.sleep(0.5) except Exception as e: logging.error("Xbee error " + str(e))
class XBeeClient(UWHProtoHandler): def __init__(self, mgr, serial_port, baud): UWHProtoHandler.__init__(self, mgr) self._xbee = XBeeDevice(serial_port, baud) self._xbee.open() def setup(self, atid, atch, atni): self._xbee.set_parameter('ID', binascii.unhexlify(atid)) self._xbee.set_parameter('CH', binascii.unhexlify(atch)) self._xbee.set_node_id(atni) self._xbee.write_changes() self._xbee.apply_changes() def send_raw(self, recipient, data): try: self._xbee.send_data(recipient, data) except TimeoutException: pass except XBeeException as e: print(e) def listen_thread(self): def callback(xbee_msg): try: self.recv_raw(xbee_msg.remote_device, xbee_msg.data) except ValueError: logging.exception("Problem parsing xbee packet") self._xbee.add_data_received_callback(callback)
def main(): print(" +--------------------------------------+") print(" | XBee Receive Data Node |") print(" +--------------------------------------+\n") device = XBeeDevice(PORT, BAUD_RATE) pub = rospy.Publisher('left_drive', Int16, queue_size=10) # rospy.init_node('teleop_comms', anonymous=True) # rate = rospy.Rate(1000) # 1000hz to be changed later if needed device.open() msg = 0 while not rospy.is_shutdown(): def data_receive_callback(xbee_message): #l_drive = xbee_message.data.decode() l_drive = xbee_message.data msg = hexint(l_drive) #print(msg) pub.publish(Int16(msg)) device.add_data_received_callback(data_receive_callback) print("Waiting for data...\n") #pub.publish(msg) rospy.spin() rate.sleep() # print("*******Closing Device************") device.close()
def main(): if os.path.exists("/tmp/data.sock"): os.remove("/tmp/data.sock") device = XBeeDevice(PORT, BAUD_RATE) socketServer = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) socketServer.bind(data) socketServer.listen(10) socketConnection, _ = socketServer.accept() try: device.open() def data_receive_callback(xbee_message): print("From %s >> %s" % (xbee_message.remote_device.get_16bit_addr(), xbee_message.data.decode())) list = xbee_message.data.decode() list = list.replace('\n', ' ').replace('\r', '').replace('\x00', '') list = list.split(',') msg = ','.join(list).encode('UTF-8') socketConnection.send(msg) device.add_data_received_callback(data_receive_callback) print("Waiting for data...\n") input() except Error: main() finally: if device is not None and device.is_open(): device.close() socketServer.close()
def main(): print(" +-----------------------------------------+") print(" | XBee Python Library Receive Data Sample |") print(" +-----------------------------------------+\n") device = XBeeDevice(PORT, BAUD_RATE) try: device.open() def data_receive_callback(xbee_message): print("From %s >> %s" % (xbee_message.remote_device.get_64bit_addr(), xbee_message.data.decode())) message = xbee_message.data.decode() if message == "cutdown": return CUTDOWN_VALUE else: return SAFE_VALUE device.add_data_received_callback(data_receive_callback) print("Waiting for data...\n") input() finally: if device is not None and device.is_open(): device.close()
class XBee: def __init__(self, port: str, baud_rate: int = 9600): self._device = XBeeDevice(port, baud_rate) def _normalize_data(self, data: typing.Union[bytearray, bytes]): if isinstance(data, bytes): data = bytearray(data) return data def open(self): self._device.open() self._device.add_data_received_callback(self._on_data_received) def close(self): self._device.close() def send_broadcast(self, data: typing.Union[bytearray, bytes]): data = self._normalize_data(data) self._device.send_data_broadcast(data) def send(self, remote_address: bytearray, data: typing.Union[bytearray, bytes]): data = self._normalize_data(data) remote_device = RemoteXBeeDevice( self._device, x64bit_addr=XBee64BitAddress(remote_address)) self._device.send_data(remote_device, data) def on_message_received(self, remote_address: bytearray, data: bytearray): pass def _on_data_received(self, message): self.on_message_received( message.remote_device.get_64bit_addr().address, message.data)
def main(): my_device = XBeeDevice(PORT, BAUD_RATE) my_device.open() #GCS = initialize_GCS(my_device) GCS = RemoteXBeeDevice(my_device, XBee64BitAddress.from_hex_string(GCS_ID)) my_device.add_data_received_callback(receive_data_callback) print("Sending MAVLink messages") while True: # Read from drone, Write to XBee try: if 100 <= drone.in_waiting < BUFFER_LIMIT: data = drone.read(drone.in_waiting) while data: my_device.send_data(GCS, data[:MAX_XBEE_BYTE]) data = data[MAX_XBEE_BYTE:] elif drone.in_waiting == BUFFER_LIMIT: drone.reset_input_buffer() else: pass except Exception as e: print("Conn lost") GCS = RemoteXBeeDevice(my_device, XBee64BitAddress.from_hex_string(GCS_ID))
class Radio: #commandDB where all commands will be stored commandDB = None def __init__(self): self.serialPort = "/dev/tty.SLAB_USBtoUART" # port where Xbee is connected find by doing ls /dev/tty* on terminal self.device = XBeeDevice(self.serialPort, 9600) self.remote_device = RemoteXBeeDevice( self.device, XBee64BitAddress.from_hex_string( "0013A200406343f7")) # "0013A20040XXXXXX" self.callback = None # strores a reference to the radio callback function def __repr__(self): return "Xbee Device at Port {0}\nopen = {1}".format( self.serialPort, self.device.is_open()) def __str__(self): return "Xbee Device at Port {0}\nopen = {1}".format( self.serialPort, self.device.is_open()) def openConnection(self): if (self.device != None and self.device.is_open() == False): self.device.open() def closeConnection(self): if (self.device != None and self.device.is_open()): self.device.close() def send(self, data): try: #self.openConnection() #self.device.send_data_broadcast(data) #self.device.send_data(self.remote_device,data) self.device.send_data_async(self.remote_device, data) #sent async except (KeyboardInterrupt): print("something went wrong when sending data") def my_data_received_callback(xbee_message): address = xbee_message.remote_device.get_64bit_addr() data = xbee_message.data.decode("utf8") #store the XBbee into a command object for decoding etc... command = Command(xbee_message) # add this command to the command dataBase Radio.commandDB.addCommand(command) print("Received data from %s: %s" % (address, data)) # opens the xbee device and sets the recieve call back # parameters: database = command database to store commands def setUP(self, database): Radio.commandDB = database self.openConnection() self.callback = Radio.my_data_received_callback self.device.add_data_received_callback(self.callback) #close xbeeconnection and delete callback def terminate(self): #self.device.del_data_received_callback(self.callback) self.closeConnection()
class ModuleSingleton: def __init__(self): self.device = XBeeDevice(LOCAL_PORT, BAUD_RATE) self.device.open() self.remote_device = None self.queue = None try: self.remote_device = RemoteXBeeDevice( self.device, XBee64BitAddress.from_hex_string(REMOTE_NODE_ADDRESS)) if self.remote_device is None: print("Could not find the remote device") except XBeeException: print("Exception has occurred") def send(self, data): print("Testing data: " + data) try: print("Sending data to %s >> %s..." % (self.remote_device.get_64bit_addr(), DATA_TO_SEND)) logging.basicConfig(stream=sys.stdout, level=logging.DEBUG, format="[root] %(levelname)s - %(message)s") logger = logging.getLogger(self.device.get_node_id()) self.device.send_data(self.remote_device, data) print("Success") finally: if self.device is not None and self.device.is_open(): # self.device.close() print("Commented out close") def bind_queue(self, queue): self.queue = queue def receive(self): try: def data_receive_callback(msg): data = msg.data.decode("utf8") json_data = json.loads(data) self.queue.put(json_data) self.device.add_data_received_callback(data_receive_callback) print("Waiting for data...\n") input() finally: if self.device is not None and self.device.is_open(): #self.device.close() print("Commented out close")
def _open_device(self, port, baud_rate): device = XBeeDevice(port, baud_rate) try: device.open() device.add_data_received_callback(self.receiver) log.info(f'Device ({device.get_64bit_addr()}) connected\n') self._device = device except (InvalidOperatingModeException, SerialException): log.error('Antenna not found')
def main(): print(" +-------------------------------------+") print(" | Image Receive Rest - Xbee to Python |") print(" +-------------------------------------+\n") device = XBeeDevice(PORT, BAUD_RATE) first_message = MessageBuffer() message = MessageBuffer() image_file = MessageBuffer() first_message.cont = True path = "/Users/Michael/Desktop/PICSFROMXBEE/" def data_receive_callback(xbee_message): xbeemsg = device.read_data() data = xbeemsg.data temp = data.decode("utf-8") print(temp) spliter = temp.split(':') if spliter[0] == "BN": first_message.msg_type = spliter[0] first_message.file_size = spliter[1] first_message.offset = spliter[2] first_message.buffer = spliter[3] # file name elif spliter[0] == "DT": message.msg_type = spliter[0] message.offset = spliter[1] message.buffer = spliter[2] image_file.buffer = image_file.buffer + spliter[2] elif spliter[0] == "ED": message.msg_type = spliter[0] message.offset = spliter[1] message.buffer = spliter[2] image_file.buffer = image_file.buffer + spliter[2] print(image_file.buffer) print((len(image_file.buffer))) first_message.cont = False saveimg(image_file.buffer, first_message.buffer, path) image_file.resetbuffer() else: print("ERROR") try: device.open() device.add_data_received_callback(data_receive_callback) print("Waiting for data...\n") while True: if first_message.cont: input() else: break print("here") finally: if device is not None and device.is_open(): device.close()
def main(): print("Starting program") # Instantiate an XBee device object. local_xbee = XBeeDevice("/dev/ttyUSB0", 250000) # Open the device connection. remote_devices = [] # Callback for discovered devices. def callback_device_discovered(remote): # remote_address = str(remote).split()[0] print("Device discovered: %s, inserting into list at element: %s" % (remote.get_64bit_addr(), len(remote_devices))) remote_devices.append(remote) # Callback for discovery finished. def callback_discovery_finished(status): if status == NetworkDiscoveryStatus.SUCCESS: print("Discovery process finished successfully.") else: print("There was an error discovering devices: %s" % status.description) try: local_xbee.open() def data_received_callback(xbee_message): global messageCounter messageCounter += 1 if messageCounter == 1: global start_time start_time = time.time() if messageCounter == 500: global end_time end_time = time.time() rate = (500 * 100) / (end_time - start_time) print(rate) if messageCounter % 10 == 0: print(messageCounter) local_xbee.add_data_received_callback(data_received_callback) print("Waiting for the data...\n") input() finally: global start_time, end_time print(end_time - start_time) print((500 * 100) / (end_time - start_time)) if local_xbee is not None and local_xbee.is_open(): local_xbee.close()
class Radio: def __init__(self): self.serialPort = "COM3" self.device = XBeeDevice(self.serialPort, 9600) self.remote_device = RemoteXBeeDevice( self.device, XBee64BitAddress.from_hex_string( "0013A2004068CC5D")) # "0013A20040XXXXXX" self.callback = None def __repr__(self): return "Xbee Device at Port".format(self.serialPort, self.device.is_open()) def __str__(self): return "Xbee Device at Port".format(self.serialPort, self.device.is_open()) def openConnection(self): if (self.device != None and self.device.is_open() == False): self.device.open() def closeConnection(self): if (self.device != None and self.device.is_open()): self.device.close() def send(self, data): try: self.device.send_data_async(self.remote_device, data) except (KeyboardInterrupt): print("something went wrong when sending data") def data_received_callback(xbee_message): address = xbee_message.remote_device.get_64bit_addr() data = xbee_message.data.decode("utf8") f = open("Balloon_Data.txt", "a") f.write(data + "\n") #writing data to text file print("Received data from %s: %s" % (address, data)) # opens the XBEE device and sets the receive call back # parameters def setUP(self): self.openConnection() self.callback = Radio.data_received_callback self.device.add_data_received_callback(self.callback) #terminate XBEE connection and delete callback def terminate(self): self.device.del_data_received_callback(self.callback) self.closeConnection()
class xBeeConnect: def __init__(self): # TODO: Replace with the serial port where your local module is connected to. self.PORT = "/dev/ttyS0" self.coordenador = "00" * 8 # TODO: Replace with the baud rate of your local module. self.BAUD_RATE = 9600 self.device = None def connect(self): self.device = XBeeDevice(self.PORT, self.BAUD_RATE) def remote_device(self): return RemoteXBeeDevice( self.device, XBee64BitAddress.from_hex_string(self.coordenador)) def get(self, callback): try: self.device.open() respose = self.device.add_data_received_callback(callback) self.device.send(self.remote_device(), response) finally: if self.device is not None and device.is_open(): self.device.close()
def main(): Number = 0 while 1: try: Port = "COM" + str(Number) device = XBeeDevice(Port, Baud_Rate) device.open() break except: print(f"Cannot open {Port}") Number = Number + 1 sleep(0.5) def my_data_received_callback(xbee_message): try: #Read received data predata_utf = xbee_message.data.decode("utf8") data0 = literal_eval(predata_utf) #Extract data EC = float(data0['EC'][0:data0['EC'].find(',')]) #EC = data0['EC'] pH = data0['pH'] + 3.5 DO = data0['DO'] RTD = data0['RTD'] #current time and date time_hhmmss = strftime('%H:%M:%S') date_mmddyyyy = strftime('%d/%m/%Y') #insert record data = { 'Conductivity': EC, 'pH': pH, 'DO': DO, 'Temperature': RTD, 'date': date_mmddyyyy, 'time': time_hhmmss } result = post(firebase_url + '/' + location + '/AquaFarm.json', data=dumps(data)) except: print('Something has been wrong!') # Add the callback. device.add_data_received_callback(my_data_received_callback)
def initXBee(port, baud): global CONTROLLER_ADDR print("Init XBee at {0}, {1:d}".format(port, baud)) #device = ZigBeeDevice(port, baud) device = XBeeDevice(port, baud) device.open() device.add_modem_status_received_callback(xbee_status_callback) device.add_data_received_callback(xbee_received_callback) xnet = device.get_network() xnet.set_discovery_timeout(5) xnet.start_discovery_process() while xnet.is_discovery_running(): time.sleep(0.5) controller16Addr = XBee16BitAddress.COORDINATOR_ADDRESS remote_device = xnet.get_device_by_16(controller16Addr) if remote_device is None: print("Could not find the remote device {0}".format(controller16Addr)) print("init, nodeId= {0}".format(device.get_node_id())) return device, remote_device
def main(): print(" +-----------------------------------------+") print(" | Wireless Sleep Monitoring |") print(" | \"No Strings Attached!\" |") print(" +-----------------------------------------+\n") inp = input("Press enter to start!\nPress enter a second time to stop!") #ignore this for now if inp == 'v': Verbose = True else: Verbose = False #declaring device and grapher device = XBeeDevice(PORT, BAUD_RATE) grapher = data(Verbose) try: #Opening device device.open() device.flush_queues() #Honestly no idea what a callback is. def data_receive_callback(xbee_message): print(xbee_message.data.decode()) raw_data.append(xbee_message.data.decode()) #Think that this function basically runs this code A$AP when it gets a packet device.add_data_received_callback(data_receive_callback) print("Waiting for data...\n") #This just has the device capture data until an input is entered input() #Finally block triggers after input ends finally: if device is not None and device.is_open(): #Closing device stops callbacks device.close() #For now I graph here, but I might have a second thread do this in parallel to the other thread for j in raw_data: grapher.data_stream(j) grapher.data_avg() grapher.graph_data() grapher.sampling_test_squarewave() grapher.csv_data()
def main(): print(" +-----------------------------------------+") print(" | XBee Listening for Data |") print(" +-----------------------------------------+\n") #part1: load PORT and BAUD_RATE from config file to define local XBee connected PORT = get_xbeeData_from_config_file('port') BAUD_RATE = get_xbeeData_from_config_file('baud_rate') device = XBeeDevice(port=PORT, baud_rate=BAUD_RATE) try: #part2: open XBee connection device.open() #reading data does not block your application. Instead, you can be notified when new data has been received. device.add_data_received_callback( data_receive_callback) # calling function here! print("Waiting for data...\n") input() finally: if device is not None and device.is_open(): device.close()
class XBee: def __init__(self, path_to_device, baud_rate=9600): self._device = XBeeDevice(path_to_device, baud_rate) self._device.open() def __del__(self): self._device.close() def write(self, message, address): if len(message) > 256: raise UserWarning("Message to large. Will be truncated") message = message[0:256] remote_device = RemoteXBeeDevice( self._device, XBee64BitAddress.from_hex_string(address)) self._device.send_data_async(remote_device, message) return True def set_callback(self, callback_method): self._device.add_data_received_callback(callback_method) return True
def main(): try: device = XBeeDevice("/dev/ttyAMA0", 9600) device.open() fc = FlightController() print("Hi") def data_receive_callback(xbee_message): global last_received last_received = xbee_message.timestamp fc.update_inputs(xbee_message) fc.do_control() device.add_data_received_callback(data_receive_callback) input() finally: if device is not None and device.is_open(): device.close()
def main(): print(" +-----------------------------------------+") print(" | XBee Python Library Receive Data Sample |") print(" +-----------------------------------------+\n") device = XBeeDevice(PORT, BAUD_RATE) head = ["Time","SOC","FPV","H_Temp","L_Temp","H_Volt","L_Volt","P_Volt","Aux_Volt","IMU_X","IMU_y","IMU_z","GYRO_X","GYRO_Y","GYRO_Z"] try: device.open() def data_receive_callback(xbee_message): message = xbee_message.data.decode() message = message[1:-2] row = [s.strip() for s in message.split(',')] for i in range(len(row)): print("{0}: {1}".format(head[i],row[i])) device.add_data_received_callback(data_receive_callback) input() finally: if device is not None and device.is_open(): device.close()
def main(): print(" +--------------------------------------+") print(" | XBee Python Library Send Data Sample |") print(" +--------------------------------------+\n") device = XBeeDevice(PORT, BAUD_RATE) try: device.open() def data_receive_callback(xbee_message): print("From {} >> {}".format( xbee_message.remote_device.get_64bit_addr(), xbee_message.data.decode())) device.add_data_received_callback(data_receive_callback) print("Waiting for data...\n") # Obtain the remote XBee device 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 device") exit(1) print("Sending data to {} >> {}...".format( remote_device.get_64bit_addr(), DATA_TO_SEND)) device.send_data(remote_device, DATA_TO_SEND) print("Success") input("Press any key to quit...\n") finally: if device is not None and device.is_open(): device.close()
def main(): CLOSED = False # Setting up Xbee communication local_xbee = XBeeDevice("/dev/tty.usbserial-DN02Z6QY", 9600) local_xbee.open() local_xbee.add_data_received_callback(data_received_callback) boat_xbee = discover_boat(local_xbee) if boat_xbee == None: print('device not found!') local_xbee.close() return else: print('device found! Sending start messages') msg = "START!" local_xbee.send_data_async(boat_xbee, msg.encode()) x = 0 y = 0 while True: try: # print("?") x += 10 y += 10 new_msg = "!WP, %d, %d" % (x, y) origin_msg = "!ORIGIN, 33.119211, 118.229211" local_xbee.send_data_async(boat_xbee, origin_msg.encode()) time.sleep(0.5) continue except KeyboardInterrupt: local_xbee.del_data_received_callback(data_received_callback) end_msg = "!STOP".encode() local_xbee.send_data_async(boat_xbee, end_msg) break # Terminating the data aquisition local_xbee.close()
class SerialConnection(Connection): def __init__(self, comPort: str, baudRate: int): self.device = XBeeDevice(comPort, baudRate) self.device.set_sync_ops_timeout(5) # 5 seconds self.device.open() self.device.add_data_received_callback(self._newData) self.callback = None def _newData(self, xbee_message): if self.callback: message = ConnectionMessage(device_address=str( xbee_message.remote_device.get_64bit_addr()), connection=self, data=xbee_message.data) self.callback(message) def registerCallback(self, fn): self.callback = fn def send(self, device_address, data): remote_device = RemoteXBeeDevice( self.device, XBee64BitAddress.from_hex_string(device_address)) self.device.send_data(remote_device, bytes) def broadcast(self, data): self.device.send_data_broadcast(bytes) def shutdown(self): self.device.close() def isIntBigEndian(self): return True def isFloatBigEndian(self): return False
def main(): print(" +-----------------------------------------+") print(" | XBee Python Library Receive Data Sample |") print(" +-----------------------------------------+\n") device = XBeeDevice(PORT, BAUD_RATE) try: device.open() def data_receive_callback(xbee_message): xbeemsg = device.read_data() data = xbeemsg.data print(data) #print("From %s >> %s" % (xbee_message.remote_device.get_64bit_addr(),xbee_message.data.decode())) device.add_data_received_callback(data_receive_callback) print("Waiting for data...\n") input() finally: if device is not None and device.is_open(): device.close()
class Simple_controller(): def __init__(self): self.xbee_port = "/dev/tty.usbserial-DN02Z6QY" self.local_xbee = XBeeDevice(self.xbee_port, 9600) self.local_xbee.open() self.local_xbee.serial_port.reset_input_buffer() self.boat_xbee = [] self.hem_lat = 'N/A' self.hem_long = 'N/A' self.adcp_lat = 'N/A' self.velocity = 'N/A' self.depth = 'N/A' self.roll = 'N/A' self.pitch = 'N/A' self.yaw = 'N/A' self.adcp_lat = 'N/A' self.adcp_long = 'N/A' self.last_gps_received = datetime.datetime.now() self.last_adcp_received = datetime.datetime.now() ''' Discover the boat xbee Modify: self.boat_xbee ''' def discover_boat(self): print('Discovering device') xbee_network = self.local_xbee.get_network() xbee_network.start_discovery_process() while xbee_network.is_discovery_running(): time.sleep(0.5) self.boat_xbee = xbee_network.discover_device('boat') ''' Call back function whenever a message arrived. Sort out GPS and ADCP information Input: xbee_message: messages from the other xbee ''' def data_received_callback(self, xbee_message): data = xbee_message.data.decode() parsed_data = data.split(',') if parsed_data[0] == '$GPGGA': self.last_gps_received = datetime.datetime.now() print('Received GPS: ', data) elif parsed_data[0] == '$ADCP': self.adcp_gps_received = datetime.datetime.now() print('Received ADCP: ', data) ''' Initialize connection between boat and controller ''' def start_connection(self): # setting up xbee communication self.local_xbee.add_data_received_callback(self.data_received_callback) self.discover_boat() if self.boat_xbee == None: print('device not found!') return False else: print('device found! Sending start messages') # sending start command to the boat start_msg = "START".encode() self.local_xbee.send_data_async(self.boat_xbee, start_msg) return True ''' End connection between boat and controller ''' def end_connection(): end_msg = "STOP".encode() self.local_xbee.send_data_async(self.boat_xbee, end_msg) self.local_xbee.close()
def run(): global device #dev_logger = utils.enable_logger("digi.xbee.devices", logging.DEBUG) dev_logger = utils.disable_logger("digi.xbee.devices") ################################################################################################### # Look for XBee USB port, to avoid conflicts with other USB devices ################################################################################################### rospy.init_node('fleetCoordinator', anonymous=True) rospy.loginfo("Looking for XBee...") context = pyudev.Context() usbPort = 'No XBee found' for device in context.list_devices(subsystem='tty'): if 'ID_VENDOR' in device and device['ID_VENDOR'] == 'FTDI': usbPort = device['DEVNAME'] device = XBeeDevice(usbPort, 57600) #device = XBeeDevice("/dev/ttyUSB0", 57600) device.open() print("Current timeout: %d seconds" % device.get_sync_ops_timeout()) device.set_sync_ops_timeout(0.1) ################################################################################################### # Get local XBee ID (should be 0, convention for Coordinator) ################################################################################################### ID = utils.bytes_to_int(device.get_16bit_addr().address) if ID == 0: rospy.loginfo("\nHello,\nI am Coordinator " + str(ID)+'\n') else: raise Exception("This XBee device is not the coordinator of the network,\nlook for the XBee device stamped with 'C'.") ################################################################################################### # Initialisation ################################################################################################### #Variables storing the data received by the subscribers global remote_devices, pubGps, pubEuler, pubLB, pubLE, lastDataStr, lastData remote_devices = {} lastDataStr = {} lastData = {} pubGps = [] pubEuler = [] pubLB = [] pubLE = [] xnet = device.get_network() xnet.add_device_discovered_callback(network_callback) xnet.add_discovery_process_finished_callback(network_finished) device.add_data_received_callback(data_received) rate = rospy.Rate(10) GPSdata = GPSFix() eulerAnglesData = Vector3() lineStartData, lineEndData = Pose2D(), Pose2D() global chosen, mode, cmd mode = 0 chosen = 0 cmd = Twist() pygame.init() screen = pygame.display.set_mode( (640,480) ) pygame.display.set_caption('Python numbers') ################################################################################################### # Transmission Loop ################################################################################################### while not rospy.is_shutdown(): if(xnet.is_discovery_running() is False): xnet.start_discovery_process() display(screen) send_command() rate.sleep() if(xnet.is_discovery_running()): xnet.stop_discovery_process() device.close()
if (io_sample.get_digital_value(x) == IOValue.HIGH): IOData[faultMap[x]] = 'true' any_fault = 'true' else: IOData[faultMap[x]] = 'false' IOData['any_fault'] = any_fault print('IOData: ', IOData) #finally, put everything together and publish the data to thingsboard turbineName = addr2name[str(remote_xbee.get_64bit_addr( ))] #find the name of the turbine that sent this message print(turbineName) message = {turbineName: IOData} print(message) MQTT.publish(topicAttr, json.dumps(message), qos=1, retain=True) xbee = XBeeDevice(localXBeePort, 9600) xbee.open() try: xbee.add_data_received_callback( data_receive_callback ) # Subscribe to data message reception (for power pulse count data). xbee.add_io_sample_received_callback( io_sample_callback) # Subscribe to IO samples reception. print("Waiting for data...\n") input() finally: if xbee is not None and xbee.is_open(): xbee.close()
def main(): xbee_remote_devices = {} device = XBeeDevice(PORT, BAUD_RATE) def load_remote_device_info(): xbee_network = device.get_network() xbee_network.start_discovery_process() while xbee_network.is_discovery_running(): sleep(0.5) xbee_devices = xbee_network.get_devices() for remote_device in xbee_devices: try: remote_device.read_device_info() except: continue xbee_remote_devices[str(remote_device.get_16bit_addr())] = { "node_id": remote_device.get_node_id() } 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)) try: device.open() load_remote_device_info() device.add_data_received_callback(data_receive_callback) print(f"Node {device.get_node_id()} is waiting for data...\n") input() finally: if device is not None and device.is_open(): print("Closing device") device.close()