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))
def find_equipment(self, equipment): """ Sets the attribute self.discovered_device to a RemoteXBeeDevice given its NI """ if equipment.title() == "E1": x64addr = XBee64BitAddress.from_hex_string(self.devices_64bit_addr['E1']) elif equipment.title() == "E2": x64addr = XBee64BitAddress.from_hex_string(self.devices_64bit_addr['E2']) elif equipment.title() == "E3": x64addr = XBee64BitAddress.from_hex_string(self.devices_64bit_addr['E3']) elif equipment.title() == "E4": x64addr = XBee64BitAddress.from_hex_string(self.devices_64bit_addr['E4']) else: print("Invalid sector. Try again.") return None # print(f"Retrieving router '{equipment.title()}' in the network...") self.discovered_device = self.xbee_network.get_device_by_64(x64addr) if self.discovered_device is None: # If the device was not found print(f"Device {equipment} not found. Try again.") return None self.xbee_network.clear() return self.discovered_device
def switch_message( data ): #process an RPC message received from one of the thingsboard switches. global safety_switch, turbineOnOff_switch print('RPC Switch message recieved') params = data.get("params") method = data.get("method") if (method == "set_safety_switch"): #the safety switch has been toggled print('method == set_safety_switch') safety_switch = params message = {'safety_switch': safety_switch} MQTT.publish(topicGtwyAttr, json.dumps(message), qos=1, retain=True) elif (method == "set_turbineOnOff_switch") & ( safety_switch ): #the on/off switch has been toggled, but the safety is on print('method == set_turbineOnOff_switch and safety_switch == True') if (turbineOnOff_switch != params): #If the thingsboard switch has been flipped message = {'turbineOnOff_switch': params} pub = MQTT.publish( topicGtwyAttr, json.dumps(message), qos=1, retain=True ) #toggle the thingsboard value of turbineOnOff_switch pub.wait_for_publish() message = {'turbineOnOff_switch': turbineOnOff_switch} pub = MQTT.publish(topicGtwyAttr, json.dumps(message), qos=1, retain=True) #then toggle it back elif (method == "set_turbineOnOff_switch") & ( safety_switch == False ): #the on/off switch has been toggled, and the safety is off print('method == set_turbineOnOff_switch and safety_switch == False') message = {'turbineOnOff_switch': params} turbineOnOff_switch = params for name in name2addr.keys(): print(name2addr) print(name) try: if (params == True): print('Starting ', name) remote = RemoteXBeeDevice( xbee, XBee64BitAddress.from_hex_string(name2addr.get(name))) xbee.send_data(remote, "start") elif (params == False): print('Stoping ', name) remote = RemoteXBeeDevice( xbee, XBee64BitAddress.from_hex_string(name2addr.get(name))) xbee.send_data(remote, "stop") except: print(name, ' not found!') #Consider setting some indicator in thingsboard that turbine was unresponsive MQTT.publish(topicGtwyAttr, json.dumps(message), qos=1, retain=True) #toggle the switch #put code here to initiate the turbine start/stop sequence else: print('correct switch method not found!')
def configure_remote(self): if self.xbee.get_64bit_addr() == "0013A2004093DF98": self.remote = RemoteXBeeDevice( self.xbee, XBee64BitAddress.from_hex_string('0013A2004093DFA1')) else: self.remote = RemoteXBeeDevice( self.xbee, XBee64BitAddress.from_hex_string("0013A2004093DF98"))
def __init__(self, port="", remote_address="", verbose=False): self.verbose = verbose if port == "": port = self.find_port() self.port = port self.verbose_print(f"Port: {self.port}") self.last_time_sent = 0 if self.port != "" and remote_address != "": self.device = XBeeDevice(self.port, 9600) self.active = True self.has_remote = True try: self.device.open() except Exception as e: print(e) self.active = False try: add_64 = (XBee64BitAddress.from_hex_string(remote_address)) self.remote_device = RemoteXBeeDevice(self.device, add_64) except Exception as e: self.has_remote = False print("Error on remote device: ", e) else: self.active = False self.device = None self.ready_data = {} self.cur_data = {} self.cur_uts = 0
def xbee_0(): device = XBeeDevice('COM3', 230400) remote_addr = '0013A2004155E2AB' remote_device = RemoteXBeeDevice(device, XBee64BitAddress.from_hex_string(remote_addr)) device.open() msg = "Test from COM3" recording = AudioSegment.from_file("short.wav").get_array_of_samples() recording_arr = split_audio(recording) try: print('Sending from COM3') for i in range(0, len(recording_arr)): bytes_obj = pickle.dumps(recording_arr[i]) #print('Size: {0:}'.format(sys.getsizeof(bytes_obj))) device.send_data(remote_device, bytes_obj) rcv_bytes = device.read_data(1) rcv = pickle.loads(rcv_bytes.data) if rcv is "ACK": print('Transfer complete') print("COM3 received:" + repr(rcv)) except TimeoutException: print('Timeout from COM3')
def xbee_0(): #Master device - polls remote device. device = XBeeDevice('COM4', 230400) remote_addr = '' # Insert remote address remote_device = RemoteXBeeDevice( device, XBee64BitAddress.from_hex_string(remote_addr)) device.open() # Represents the largest single 'packet' that can be transmitted. #msg = b'0' * 249 msg = "Alive?" pickled = pickle.dumps(msg) while True: try: rcv = device.read_data(1) if rcv is None: continue print('COM4 (Master) recieved:\n\tDevice: {0:}\n\t Value: {1:}\n'. format(remote_addr, pickle.loads(rcv.data))) except TimeoutException: device.send_data(remote_device, pickled) continue device.send_data(remote_device, pickled) device.close()
def main(): print(" +--------------------------------------+") print(" | XBee Python Library Send Data Sample |") print(" +--------------------------------------+\n") device = XBeeDevice(PORT, BAUD_RATE) try: device.open() # Obtain the remote XBee device from the XBee network. xbee_network = device.get_network() #remote_device = xbee_network.discover_device(REMOTE_NODE_ID) remote_device = (device, XBee64BitAddress.from_hex_string("0013A200418C5775")) if remote_device is None: print("Could not find the remote device") exit(1) #print("Sending data to %s >> %s..." % (remote_device.get_64bit_addr(), DATA_TO_SEND)) #device.send_data(remote_device, DATA_TO_SEND) device.send_data_broadcast(DATA_TO_SEND) print("Success") finally: if device is not None and device.is_open(): device.close()
def send_till_ack(address, msg, msg_id): # Instantiate a remote XBee device object to send data. send_xbee = RemoteXBeeDevice(xbee, XBee64BitAddress.from_hex_string(address)) packed_data = bytearray(msgpack.packb(msg)) while ack_id != msg_id: xbee.send_data(send_xbee, packed_data) time.sleep(1)
def transmit(self, data: bytes, recipient_address: str = coordinator) -> TransmitStatusPacket: """ Takes the address of the receiver xbee module and transmit the data to the receiver :param data: Data in bytes to be transmitted to the desired xbee module/device :type data: bytes :param recipient_address: 64 bit xbee address of the recipient module/device :type recipient_address: str :return: Digi-xbee 'TransmitStatusPacket' object, which gives us the transmit status of the transmitted data """ try: if type(data) is not bytes or type(recipient_address) is not str: raise TypeError( 'Args "data" must be bytes & "recipient_address" must be a str' ) if not self.xbee.is_open(): self.xbee.open() # Instantiate a remote XBee device object target = RemoteXBeeDevice( self.xbee, XBee64BitAddress.from_hex_string(recipient_address)) # Send data using the remote object status_packet: TransmitStatusPacket = self.xbee.send_data( target, data) return status_packet except TypeError as e: self.get_logger().info('Bad arg types, ERROR: ', e) except TransmitException as e: self.get_logger().info('Failed to transmit data, ERROR: ', e.status)
def switch_message(data): #process an RPC message received from one of the thingsboard switches. global safety_switch, turbineOnOff_switch print('RPC Switch message recieved') params = data.get("data").get("params") name = data.get("device") #method = data.get("method") turbineOnOff_switch = params if (params == True): print('Starting ',name) remote = RemoteXBeeDevice(xbee, XBee64BitAddress.from_hex_string(name2addr.get(name))) xbee.send_data(remote, "start") elif (params == False): print('Stoping ',name) remote = RemoteXBeeDevice(xbee, XBee64BitAddress.from_hex_string(name2addr.get(name))) xbee.send_data(remote, "stop") message = {name:{'turbineOnOff_switch':params}} MQTT.publish(topicAttr, json.dumps({name: {'turbineOnOff_switch':params}}), qos=1, retain=True) #update the device attribute corresponding to the switch status
def xbee_1(): device = XBeeDevice('COM4', 230400) remote_addr = '0013A2004155E2A6' remote_device = RemoteXBeeDevice( device, XBee64BitAddress.from_hex_string(remote_addr)) device.open() msg = "Test from COM4" count = 0 while (True): try: device.flush_queues() rcv_bytes = device.read_data(1) rcv = pickle.loads(rcv_bytes.data) print('New message: {0:}'.format(rcv)) result = [] if rcv.data_type == b'0x01': # Audio byte signature print('Server recieved Audio') result = [] result.append(rcv) for i in range(0, rcv.total_sequence - 1): rcv_bytes = device.read_data(1) rcv = pickle.loads(rcv_bytes.data) result.append(rcv) filename = build_pickle(result) #print('Server recieved Audio message') #print('Sending ACK') bytes_obj = pickle.dumps('ACK') device.send_data(remote_device, bytes_obj) device.flush_queues() if rcv.data_type == b'0x02': # Distress byte signature print('Server recieved distress') #print('Sending ACK') bytes_obj = pickle.dumps('ACK') device.send_data(remote_device, bytes_obj) if rcv.data_type == b'0x03': # GPS byte signature print('Server recieved GPS') #print('Sending ACK') bytes_obj = pickle.dumps('ACK') device.send_data(remote_device, bytes_obj) if rcv.data_type == b'0x00': # Shutdown byte signature print('Server recieved shutdown') #print('Sending ACK') bytes_obj = pickle.dumps('ACK') device.send_data(remote_device, bytes_obj) device.close() return except TimeoutException: #print("Timeout on COM4") continue
def switch_message( data ): #process an RPC message received from one of the thingsboard switches. global safety_switch, turbineOnOff_switch print('RPC Switch message recieved') name = data.get("device") method = data.get("data").get("method") if (method == "startButton"): print('Starting ', name) remote = RemoteXBeeDevice( xbee, XBee64BitAddress.from_hex_string(name2addr.get(name))) xbee.send_data(remote, "start") #Send start message to remote XBee pub = MQTT.publish( topicAttr, json.dumps({name: { 'startButton': True }}), qos=1, retain=True) #toggle the thingsboard value of startButton pub.wait_for_publish() pub = MQTT.publish(topicAttr, json.dumps({name: { 'startButton': False }}), qos=1, retain=True) #then toggle it back elif (method == "stopButton"): print('Stoping ', name) remote = RemoteXBeeDevice( xbee, XBee64BitAddress.from_hex_string(name2addr.get(name))) xbee.send_data(remote, "stop") pub = MQTT.publish( topicAttr, json.dumps({name: { 'stopButton': True }}), qos=1, retain=True) #toggle the thingsboard value of stopButton pub.wait_for_publish() pub = MQTT.publish(topicAttr, json.dumps({name: { 'stopButton': False }}), qos=1, retain=True) #then toggle it back
def send(): start = time.time() device.open() # Instantiate a remote XBee device object. remote_device = RemoteXBeeDevice( device, XBee64BitAddress.from_hex_string(REMOTE_ADDRESS)) # Send data using the remote object. device.send_data(remote_device, "Hello Wolrd!") device.close() print("--- %s seconds ---" % (time.time() - start))
def find_router(self, sector): if sector.title() == "R1": x64addr = XBee64BitAddress.from_hex_string(self.devices_64bit_addr['R1']) elif sector.title() == "R2": x64addr = XBee64BitAddress.from_hex_string(self.devices_64bit_addr['R2']) else: print("Invalid sector. Try again.") return None # Retrieving router from network by 64bit address print(f"Retrieving router '{sector.title()}' in the network...") self.router = self.xbee_network.get_device_by_64(x64addr) if self.router is None: # If the device was not found print(f"[ERROR] Router {sector} not found. Try again.") self.xbee_network.clear() return None self.router_64_bit_addr = self.router.get_64bit_addr() # If the device was found in the network print(f"[OK] {sector.title()} found. Retrieving device information...")
def send(self, mac_address, data): '''sends data over xbee''' remote_device = RemoteXBeeDevice(self.xbee, XBee64BitAddress.from_hex_string(mac_address)) if remote_device is None: print("Invalid MAC Address") return print("Sending '%s' to %s" % (data, remote_device.get_64bit_addr())) self.mutex.xbee_mutex.acquire() self.xbee.send_data(remote_device, data) self.mutex.xbee_mutex.release() print("Success")
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(): start = time.time() #device.open() # Instantiate a remote XBee device object. remote_device = RemoteXBeeDevice( device, XBee64BitAddress.from_hex_string(REMOTE_ADDRESS)) # Send data using the remote object. with open("jpeg.jpg", "rb") as f: buffer = f.read(100) while buffer != b"": device.send_data(remote_device, buffer) buffer = f.read(100) f.close() #device.close() print("--- %s seconds ---" % (time.time() - start))
def interruption_handler(pin): print("capturing") start = time.time() capture() device.open() # Instantiate a remote XBee device object. remote_device = RemoteXBeeDevice(device, XBee64BitAddress.from_hex_string(REMOTE_ADDRESS)) with open("jpeg.jpg","rb") as f: buffer = f.read(100) while buffer != b"": device.send_data(remote_device, buffer) buffer = f.read(100) f.close() device.close() print("--- %s seconds ---" % (time.time() - start))
def communication(input_data): # Instantiate an XBee device object. device = XBeeDevice("COM3", 9600) inp = str(input_data) device.open() # Instantiate a remote XBee device object. remote_device = RemoteXBeeDevice( device, XBee64BitAddress.from_hex_string("0013A20040F655F0")) # Send data using the remote object. device.send_data_async(remote_device, inp) device.close() time.sleep(0)
def acknowledge(address, ackid, autonomyToCV): ack = { "type": "ack", "time": round(time.clock() - connection_timestamp) + gcs_timestamp, "sid": configs['vehicle_id'], "tid": 0, # The ID of GCS "id": new_msg_id(), "ackid": ackid } # xbee is None if comms is simulated if xbee: # Instantiate a remote XBee device object to send data. send_xbee = RemoteXBeeDevice(xbee, XBee64BitAddress.from_hex_string(address)) packed_data = msgpack.packb(ack) autonomyToCv.xbeeMutex.acquire() xbee.send_data(send_xbee, packed_data) autonomyToCV.xbeeMutex.release()
def __init__(self): self.is_local_device_init = 0 # Remote node MAC address in hexadecimal format self.REMOTE_NODE_ADDRESS = "0013A2004148887C" try: self.device = XBeeDevice(LOCAL_PORT, BAUD_RATE) self.device.set_sync_ops_timeout(10) self.device.open() self.is_local_device_init = 1 except serial.SerialException: # raise RadioSerialConnectionException print(ERR + "Serial Exception" + NORM) print("Local radio not connected\n") self.is_local_device_init = 0 def data_receive_callback(msg): data = msg.data.decode("utf8") json_data = json.loads(data) # print(json_data) self.queue.put(json_data) try: self.device.add_data_received_callback(data_receive_callback) except Exception as e: print(ERR + "Callback Failure" + NORM) print(e) print("\n") # self.reset_radio() self.remote_device = None self.queue = None try: self.remote_device = RemoteXBeeDevice( self.device, XBee64BitAddress.from_hex_string(self.REMOTE_NODE_ADDRESS)) print("Remote Device Address: " + str(self.remote_device)) if self.remote_device is None: print(ERR + "Could not find the remote device" + NORM) except XBeeException: print(ERR + "Remote Device Instantiation Error" + NORM)
def initialize_GCS(my_device): print("\n...Discovering GCS...\n") network = my_device.get_network() network.start_discovery_process() while network.is_discovery_running(): time.sleep(0.1) gcs_address = XBee64BitAddress.from_hex_string(GCS_ID) GCS = network.get_device_by_64(gcs_address) if GCS is None: print("GCS not found, Restarting search of GCS") initialize_GCS(my_device) else: print("...Discovering Complete...") print("GCS found with name:", GCS.get_node_id(), " and address:", gcs_address) return GCS
def xbee_slave(): # Slave device - responds to requests from Master (Remote Device) # Set up the GPS serial device ser = serial.Serial() ser.baudrate = 9600 ser.port = '/dev/ttyS0' ser.timeout = 1 ser.open() # Set up the XBee serial device device = XBeeDevice('/dev/ttyUSB0', 230400) remote_device = RemoteXBeeDevice( device, XBee64BitAddress.from_hex_string('')) # Insert remote address device.open() while True: lat, lon = gps_locate(ser) try: rcv = device.read_data( 1) # Listen for 1 seconds (then sleep, to save power?) except TimeoutException: continue if rcv is None: continue if pickle.loads(rcv.data) == 'Alive?': msg = 'Alive recieved at: ' + str( time.time()) + '\tLocation: {0:} {1:}'.format(lat, lon) pickled = pickle.dumps(msg) device.send_data(remote_device, pickled) unpickled = pickle.loads(rcv.data) print('COM4 (Slave) recieved: \n\tValue: {0:}\n'.format(unpickled)) time.sleep(5) #device sleeps for 5 seconds. device.close()
def bad_msg(address, problem, autonomyToCV): msg = { "type": "badMessage", "time": round(time.clock() - connection_timestamp) + gcs_timestamp, "sid": configs['vehicle_id'], "tid": 0, # The ID of GCS "id": new_msg_id(), "error": problem } # xbee is None if comms is simulated if xbee: # Instantiate a remote XBee device object to send data. send_xbee = RemoteXBeeDevice(xbee, XBee64BitAddress.from_hex_string(address)) packed_data = msgpack.packb(msg) autonomyToCV.xbeeMutex.acquire() xbee.send_data(send_xbee, packed_data) autonomyToCV.xbeeMutex.release() else: print("Error:", problem)
def __init__(self, address, gcs, udp_ip, udp_port): # initialize print("Initializing new UDP port at 127.0.0.1:", udp_port, " for drone ID:", address) self.gcs = gcs self.drone_id = address # To check if error occured during initialization self.__initialise_error = False self.xbee_bytes_received = 0 self.udp_bytes_sent = 0 self._time_last_data_rx = time.time() self._connection_ok = True self._speed = 0 #create object for remote xbee device try: self.drone = RemoteXBeeDevice( self.gcs, XBee64BitAddress.from_hex_string(self.drone_id)) except: error = { 'context': 'UDP_INIT', 'msg': 'Drone could not initialize' } logger.error(error) self.__initialise_error = True try: self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.socket.connect((udp_ip, udp_port)) except: error = {'context': 'UDP_INIT', 'msg': 'Socket initializing error'} logger.error(error) self.__initialise_error = True udp_rx = threading.Thread(target=self.udp_rx_thread, daemon=True) udp_rx.start() monitor_data = threading.Thread(target=self.monitor_connection, daemon=True) monitor_data.start()
def main(): pygame.init() pygame.display.set_caption(u'Keyboard events') pygame.display.set_mode((400, 400)) device = XBeeDevice(PORT, BAUD_RATE) try: # Instantiate an XBee device object. device.open() remote_device = RemoteXBeeDevice( device, XBee64BitAddress.from_hex_string("0013A20041981831")) print("Control car with W/A/S/D, close with F") #message = "" run = True while run == True: event = pygame.event.wait() if event.type == pygame.QUIT: break if event.type in (pygame.KEYDOWN, pygame.KEYUP): key_name = pygame.key.name(event.key).upper() if event.type == pygame.KEYDOWN: # Key down print(key_name + " pressed") device.send_data(remote_device, key_name + ",1") elif event.type == pygame.KEYUP: # Key release print(key_name + " released") device.send_data(remote_device, key_name + ",0") finally: print("Remote control closed") if device is not None and device.is_open(): device.close() # finalizes Pygame pygame.quit()
def xbee_1(): device = XBeeDevice('COM4', 230400) remote_addr = '0013A2004155E2A6' remote_device = RemoteXBeeDevice(device, XBee64BitAddress.from_hex_string(remote_addr)) device.open() msg = "Test from COM4" count = 0 try: rcv_bytes = device.read_data(1) rcv = pickle.loads(rcv_bytes.data) result = [] print('First rcv: {0:}'.format(rcv)) print('rcv.data_type: {0:}'.format(rcv.data_type)) if rcv.data_type == 'audio': print('Got "Audio"') result = [] result.append(rcv) for i in range(0, rcv.total_sequence - 1): rcv_bytes = device.read_data(1) rcv = pickle.loads(rcv_bytes.data) result.append(rcv) print("COM4 received:" + repr(rcv)) result_arr = build_data(result) print(result_arr) flat_arr = ndarray.flatten(result_arr) print(flat_arr) newrecording = AudioSegment(flat_arr, sample_width=2, frame_rate=8000, channels=1) newrecording.export('file.flac', format = "flac") print('Sending from 4') bytes_obj = pickle.dumps('ACK') device.send_data(remote_device, bytes_obj) except TimeoutException: print("Timeout on COM4")
def __init__(self): try: self.device = XBeeDevice(LOCAL_PORT, BAUD_RATE) self.device.set_sync_ops_timeout(10) self.device.open() except Exception as e: print(ERR + "Local Device Instantiation Error" + NORM) print(e) def data_receive_callback(msg): data = msg.data.decode("utf8") json_data = json.loads(data) print(json_data) self.queue.put(json_data) try: self.device.add_data_received_callback(data_receive_callback) except Exception as e: print(ERR + "Callback Failure" + NORM) print(e) # self.reset_radio() self.remote_device = None self.queue = None try: self.remote_device = RemoteXBeeDevice( self.device, XBee64BitAddress.from_hex_string(REMOTE_NODE_ADDRESS)) print("Remote Device Address: " + str(self.remote_device)) if self.remote_device is None: print(ERR + "Could not find the remote device" + NORM) except XBeeException: print(ERR + "Remote Device Instantiation Error" + NORM)
def __init__(self): self.device = XBeeDevice(LOCAL_PORT, BAUD_RATE) self.device.open() 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) 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")