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 main(): global target_x global target_y global List_Target_X global List_Target_Y global List_X global List_Y global start_time global split_time global wb global cont_linhas_planilha global ws device = XBeeDevice(PORT, BUS) device.open() i = 0 target = targets[i] target_x = int(target.split(',')[0]) target_y = int(target.split(',')[1]) List_Target_X.append(target_x) List_Target_Y.append(target_y) start_time = time.time() while True: print('Alvo: ' + str(target)) if target is not None: robot_info = device.read_data() while robot_info is None: robot_info = device.read_data() robot_info = robot_info.data.decode() print ('Informacao Recebida do Robo: ' + str(robot_info)) if 'Posicao' in robot_info: device.send_data_broadcast(VerificaPosicao()) elif 'Cheguei' in robot_info: ws['H' + str(cont_linhas_planilha - 1)] = 'Cheguei' if i < len(targets) - 1: i += 1 target = targets[i] target_x = int(target.split(',')[0]) target_y = int(target.split(',')[1]) List_Target_X.append(target_x) List_Target_Y.append(target_y) device.send_data_broadcast(VerificaPosicao()) else: break wb.save('relatório.xlsx') print ("\n\n") device.close() print ("\n\n") print ("O robo chegou a todos os alvos. Aplicacao encerrada.") plt.plot(List_X, List_Y, 'r--', List_Target_X, List_Target_Y, 'bo', List_X[0], List_Y[0], 'go') plt.axis([0, dist_x, 0, dist_y]) plt.show()
def main(): print(" +-------------------------------------------------+") print(" | Bote |") print(" +-------------------------------------------------+\n") device = XBeeDevice(PORT, BAUD_RATE) try: device.open() device.flush_queues() print("Waiting conversation...\n") #Variable to stop the conversation commActive = True while commActive : #Read data and chek if something has been received xbee_message = device.read_data() if xbee_message is not None: #Print the message and print("Received Message: " , xbee_message.data.decode()) print(xbee_message.data.decode()) #if it's different than exit continue listening if xbee_message.data.decode() == 'exit': commActive = False #If the device is not closed, close it. finally: if device is not None and device.is_open(): device.close()
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(): coord = XBeeDevice('COM7', 9600) #create Xbeedevice Coord at COM7 & baud rate 9600 try: coord.open() #calling method to open communication with Xbee device coord.flush_queues() xbee_network = coord.get_network() #getting a newtwork and assigning it to the xbee router2 = xbee_network.discover_device('R3') # find the remote device on the network at R1 if router2 is None: print("Could not find the remote device") else : print("Remote device found") while True: xbee_message = coord.read_data() if xbee_message is not None: timestamp = round(time.time()) data_raw = xbee_message.data.decode().split(",") data = [float(element) for element in data_raw] # Temperature print("At {0} Temperature is {1}".format(timestamp, data[0]), end=": ") if data[0] > 23.7: print("Unsafe") if router2 is not None: coord.send_data(router2, "T1") else: print("Safe") if router2 is not None: coord.send_data(router2, "T0") finally: if coord is not None and coord.is_open(): coord.close()
def main(): print("Libelium Waspmote data receiver\n") device = XBeeDevice(PORT, BAUD_RATE) try: device.open() device.flush_queues() print("Waiting for data...\n") while True: xbee_message = device.read_data(300) if xbee_message is not None: # print("From %s >> %s" % (xbee_message.remote_device.get_64bit_addr(), # xbee_message.data)) if b"<=>" in xbee_message.data: data = xbee_message.data[5:] print(data.decode()) except KeyboardInterrupt: print("Exit") finally: if device is not None and device.is_open(): device.close()
def main(): print(" +-------------------+") print(" | Send Data 16 Test |") print(" +-------------------+\n") local = XBeeDevice(PORT_LOCAL, BAUD_RATE_LOCAL) local_remote = XBeeDevice(PORT_REMOTE, BAUD_RATE_REMOTE) try: local.open() local_remote.open() remote = RemoteXBeeDevice(local, x16bit_addr=local_remote.get_16bit_addr()) local.send_data(remote, "Test message") time.sleep(1) message = local_remote.read_data() assert (message is not None) assert ( message.remote_device.get_16bit_addr() == local.get_16bit_addr()) print("Test finished successfully") finally: if local is not None and local.is_open(): local.close() if local_remote is not None and local_remote.is_open(): local_remote.close()
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 main(): print(" +------------------------+") print(" | Read Data Timeout Test |") print(" +------------------------+\n") local = XBeeDevice(PORT_LOCAL, BAUD_RATE_LOCAL) local_remote = XBeeDevice(PORT_REMOTE, BAUD_RATE_REMOTE) message = None timeout_exception = None try: local.open() local_remote.open() message = local_remote.read_data() assert (message is None) remote = RemoteXBeeDevice(local, x64bit_addr=local_remote.get_64bit_addr()) local.send_data(remote, "Test message") time.sleep(1) message = local_remote.read_data() assert (message is not None) message = None message = local_remote.read_data(3) except TimeoutException as e: timeout_exception = e finally: assert (timeout_exception is not None) assert (message is None) print("Test finished successfully") if local is not None and local.is_open(): local.close() if local_remote is not None and local_remote.is_open(): local_remote.close()
class Radio(object): # current xbee only can send once every ~60ms, sending faster may block MESSAGE_DELAY = .1 def __init__(self, is_second_radio=False): # Find our XBee device connected to this computer port = RADIO_PORT_2 if is_second_radio else RADIO_PORT_1 self.device = XBeeDevice(port, BAUD_RATE) # TODO: sometimes it errors about operating mode, try replugging xbee self.device.open() # Obtain the remote XBee devices from the XBee network. xbee_network = self.device.get_network() # Try to find devices xbee_network.start_discovery_process() time.sleep(3) # wait a few seconds to find all of the xbees xbee_network.stop_discovery_process() self.net_devs = xbee_network.get_devices() if not self.net_devs: raise RuntimeError("Cound not find any XBEE devices on network") def send(self, message): for remote_device in self.net_devs: try: start = time.time() # asynchronous send is fast for first msg, but waits if more # long messages (>30?) take longer because they must be split try: self.device.send_data_async(remote_device, message) except Exception as e: print('xbee error - something using same port? (xtcu):') print(e) # TODO: reconnect when error? delta = time.time() - start if delta > .003: print('xbee send is taking a long time, too long/many?') print("time taken: " + str(delta)) print("message length: " + str(len(message))) except XBeeException as xbee_exp: print(str(xbee_exp)) def read(self): for remote_device in self.net_devs: try: return self.device.read_data() except XBeeException as xbee_exp: print(str(xbee_exp)) def close(self): if self.device.is_open(): self.device.close()
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 test_receive2(my_port, my_baud): # Start Test print("Start Receive Test 2 - Receive once") device = XBeeDevice(my_port, my_baud) print("Waiting for data...\n") device.open() # Read data. while True: xbee_message = device.read_data() if xbee_message: print(xbee_message.data.decode("utf-8")) break device.close() print("Receive Test 2 Complete")
def main(): device = None while True: try: if device is None: sys.stderr.write("recreating device...\n") if args.arduino: device = serial.Serial(args.xbee, 9600) else: try: device = XBeeDevice(args.xbee, 9600) device.open() except Exception as e: device = None sys.stderr.write(str(e)+"\n") time.sleep(10) continue time.sleep(1) address = None if args.arduino: data = device.readline().strip() timestamp = time.time() else: data = device.read_data() if data is None: time.sleep(0.1) continue address = str(data.remote_device.get_64bit_addr()) timestamp = data.timestamp data = data.data dispatch(data, address=address, timestamp=timestamp) except KeyboardInterrupt: if device: device.close() device = None sys.exit(0) except Exception as e: sys.stderr.write(str(e)+"\n") time.sleep(10) try: device.close() except: pass device = None
class Controller: def __init__(self, xbee): if(xbee): self.device = XBeeDevice("COM1", 9600) self.device.open() self.inputs = [None] * 17 def readData(self): ip_message = self.device.read_data() self.decodeMsg(ip_message) def decodeMsg(self, message): #HX: 0 HY: 0 A0:-1471 A1: 52 A2:-52 A3:3178 Y:0 B:0 A:0 X:0 THL:0 THR:0 TL:0 TR:0 TL2:0 TR3:0 M:0 ST:0 N:0 E:0 S:0 W:0 SL:0 EN: 0 AE: 0 messages = message.split() for i in range(17): self.inputs[i] = float(messages[2*i+1].strip(""))
def read_xbee_data(self, xbee: XBeeDevice, coordinator: RemoteXBeeDevice): """ Error tolerant XBee reading - returns an XBee packed upon a successful read - otherwise None if an error occurs due to the link between xbee and coordinator radios being compromised. :param xbee: XBeeDevice representing XBee connected via USB to the computer running this script :param coordinator: RemoteXBeeDevice representing the UAV coordinator's XBee radio :return: XBee message from a successful read, or None if the read raised an XBeeException """ try: message = xbee.read_data() # Read XBee for Coordinator messages except XBeeException as e: logging.exception(e) reconnect_blocker(xbee, coordinator) # Block script until coordinator has been reconnected self.queue_out.clear() # Clear queue once reconnected message = None return message
def main(): if len(sys.argv) < 2: output_log = logfile xbee_port = default_port elif len(sys.argv) < 3: output_log = sys.argv[1] xbee_port = default_port else: output_log = sys.argv[1] xbee_port = sys.argv[2] device = XBeeDevice(xbee_port, baud_rate) device.open() while True: try: # Returns an object # .remote_device # .data # .is_broadcast # .timestamp xbee_msg = device.read_data() if (xbee_msg): remote_device = xbee_msg.remote_device data = xbee_msg.data # We also want RSSI info rssi = device.get_parameter("DB") log(xbee_msg, rssi, output_log) ''' # DEBUG print("Received: {}\nFrom: {}".format(data, remote_device)) hexdump(data) print("RSSI: {}".format(rssi)) hexdump(rssi) print("\n") ''' except KeyboardInterrupt: break device.close()
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()
class Router: def __init__(self, node_id, router_port, baud_rate): self.node_id = node_id self.router_port = router_port self.baud_rate = baud_rate self.device = XBeeDevice(self.port, self.baud_rate) def receive_message(self, remote_node_id): xbee_message = None try: self.device.open() remote_device = RemoteXbeeDevice( self.device, Xbee64BitAddress.from_hex_strin(remote_node_id)) xbee_message = self.device.read_data(remote_device) finally: if self.device is not None and self.device.is_open(): device.close() return (xbee_message) def send_message(self, remote_node_id, xbee_message): try: self.device.open() xbee_network = device.get_network() remote_device = xbee_network.discover_device(remote_node_id) if remote_device is None: print("Could not find remote device") return False device.send_data(remote_device, xbee_message) finally: if self.device is not None and self.device.is_open(): device.close() return True
def main(): device = XBeeDevice(xbee_port, baud_rate) if device.open(): print("ERROR. DEVICE DID NOT OPEN") num = 0 #signaler.ledOff() #TO assure that it is not left on from the last run while True: try: # Returns an object # .remote_device # .data # .is_broadcast # .timestamp xbee_msg = device.read_data() if (xbee_msg): remote_device = xbee_msg.remote_device data = xbee_msg.data # We also want RSSI info rssi = device.get_parameter("DB") log(xbee_msg, rssi, output_log) # DEBUG ''' print("Received: {}\nFrom: {}".format(data, remote_device)) hexdump(data) print("RSSI: {}".format(rssi)) hexdump(rssi) print("\n") ''' print("received \n") except KeyboardInterrupt: print("KeyboardInterrupt..... ") break device.close() signaler.ledOff()
def main(): print(" +-------------------------------------------------+") print(" | XBee Python Library Receive Data Polling Sample |") print(" +-------------------------------------------------+\n") device = XBeeDevice(PORT, BAUD_RATE) try: device.open() device.flush_queues() print("Waiting for data...\n") while True: xbee_message = device.read_data() if xbee_message is not None: print("From %s >> %s" % (xbee_message.remote_device.get_64bit_addr(), xbee_message.data.decode())) finally: if device is not None and device.is_open(): device.close()
def main(): coord = XBeeDevice('COM7', 9600) #create Xbeedevice Coord at COM7 & baud rate 9600 try: coord.open() #calling method to open communication with Xbee device coord.flush_queues() xbee_network = coord.get_network( ) #getting a newtwork and assigning it to the xbee router2 = xbee_network.discover_device( 'R3') # find the remote device on the network at R1 if router2 is None: print("Could not find the remote device") else: print("Remote device found") while True: xbee_message = coord.read_data() if xbee_message is not None: timestamp = round(time.time()) data_raw = xbee_message.data.decode().split(",") data = [float(element) for element in data_raw] # Temperature print("At {0} Temperature is {1}".format(timestamp, data[0]), end=": ") if data[0] > 23.7: print("Unsafe") if router2 is not None: coord.send_data(router2, "T1") else: print("Safe") if router2 is not None: coord.send_data(router2, "T0") finally: if coord is not None and coord.is_open(): coord.close()
def main(): rep_counter = RepCounter(REST_ADDR, REST_PORT) bio_reporter = BioReporter(REST_ADDR, REST_PORT) device = XBeeDevice(SERIAL_PORT, SERIAL_BPS) try: device.open() device.flush_queues() while True: try: xbee_message = device.read_data() if xbee_message is not None: data = xbee_message.data #msg = data.decode() source = xbee_message.remote_device.get_64bit_addr() print("Msg from %s" % (source)) if (source == THIGH_SOURCE): x = struct.unpack(">h", data[0:2]) y = struct.unpack(">h", data[2:4]) z = struct.unpack(">h", data[4:6]) d = struct.unpack(">h", data[6:8]) pos_vector = [ x[0] / 100.0, y[0] / 100.0, z[0] / 100.0, d[0] ] rep_counter.update_position(pos_vector) elif (source == ECG_SOURCE): #convert bytearrays to String hr = "".join(map(chr, data[1:6])) temp = "".join(map(chr, data[7:11])) bio_reporter.report_bio(temp, hr) except InvalidPacketException: print("Invalid Packet") finally: if device is not None and device.is_open(): device.close()
retain=True) addr2name, name2addr = readTurbineInputFile() new_MQTT_message = False T = threading.Thread(target=listener) T.daemon = True #This means the thread will automatically quit if main program quits T.start() #serial_port = serial.Serial('/dev/tty.usbserial-A505N9YU', 9600) xbee = XBeeDevice('/dev/tty.usbserial-A505N9YU', 9600) xbee.open() while True: try: response = xbee.read_data(1000) #response = xbee.wait_read_frame() #Wait for an API frame to arrive. Note: this blocks while it is waiting. print(response) print(response.remote_device) print(response.data) print(response.is_broadcast) print(response.timestamp) print(response.data.decode()) # if ('samples' in response): #Is this a DIO sample frame? # IO_Data = response.get('samples')[0] #The .get() outputs a 1 element long list, where the element is a dict. Adding the [0] stores the dict in IO_Data instead of the list containing the dict. # dataKeys = IO_Data.keys() #get a list of all the data samples IO_Data # turbineName = addr2name.get(response.get('source_addr_long')) #find the name of the turbine that sent this message # print(turbineName) # for X in dataKeys: # rename data keys to be compatible with thingsboard (ex: dio-2 to brake_on) # IO_Data[pinMap.get(X)]=IO_Data.pop(X) # print(IO_Data)
class Coms(): '''compartenmentalizes coms functionality and scope''' configs = None con_timestamp = 0 gcs_timestamp = 0 msg_id = 0 # unique ID increments for each message sent ack_id = None xbee = None # XBee radio object xbee_callback = None def __init__(self, configs, xbee_callback): '''initializes coms object''' self.configs = configs self.xbee_callback = xbee_callback self.mutex = ComsMutex() if configs['coms_simulated'] is True: sim_file = configs["comm_sim_file"] comm_sim = Thread(target=self.comm_simulation, args=(sim_file, )) comm_sim.start() else: try: port_name = "" if sys.platform == "darwin": port_name = mac_xbee_port_name() elif sys.platform == "linux" or sys.platform == "linux2": port_name = "/dev/ttyUSB0" # TODO: figure out windows port name elif sys.platform == "win32": port_name = "COMS1" # Instantiate XBee device object. self.xbee = XBeeDevice(port_name, 57600) self.xbee.open() # If error in setting up XBee, try again except TimeoutError as ex: print(ex) print("Connect the XBee radio!") time.sleep(5) def send_till_ack(self, address, msg, msg_id): '''Continuously sends message to given address until acknowledgement message is recieved with the corresponding ackid.''' # Instantiate a remote XBee device object to send data. packed_data = bytearray(msgpack.packb(msg)) while self.ack_id != msg_id: self.send(address, packed_data) time.sleep(1) def acknowledge(self, address, ack_id): '''Sends message received acknowledgement to GCS param address: address of GCS''' ack = { "type": "ack", "time": round(time.clock() - self.con_timestamp) + self.gcs_timestamp, "sid": self.configs['vehicle_id'], "tid": 0, # The ID of GCS "id": self.new_msg_id(), "ackid": ack_id } self.send(address, ack) def new_msg_id(self): '''Increments msg_id and returns unique id for new message''' self.msg_id += 1 return self.msg_id def recieve(self): '''Instantiate XBee device''' try: self.xbee.flush_queues() print("Waiting for data...\n") while True: xbee_message = self.xbee.read_data() if xbee_message is not None: print("Received '%s' from %s" % (xbee_message.data.decode(), \ xbee_message.remote_self.xbee.get_64bit_addr())) finally: if self.xbee is not None and self.xbee.is_open(): self.xbee.close() 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 bad_msg(self, address, problem): '''Sends "bad message" to GCS if message received was poorly formatted/unreadable and describes error from parsing original message. :param address: address of GCS :param problem: string describing error from parsing original message''' msg = { "type": "badMessage", "time": round(time.clock() - self.con_timestamp) + self.gcs_timestamp, "sid": self.configs['vehicle_id'], "tid": 0, # The ID of GCS "id": self.new_msg_id(), "error": problem } self.send(address, msg) # TODO: needs to be updated def comm_simulation(self, comm_file): '''Reads through comm simulation file from configs and calls xbee_callback to simulate radio messages.''' with open(comm_file, "r") as com_data: comms = json.load(com_data) # reads the json file prev_time = 0 for instr in comms: # gets time and message from each json object (instruction) curr_time = instr["time"] time.sleep(curr_time - prev_time) # waits for the next instruction # Send message to xbee_callback self.xbee_callback(DummyMessage(json.dumps(instr["message"])), self.mutex) prev_time = curr_time
class Coms(): '''compartenmentalizes coms functionality and scope''' configs = None con_timestamp = 0 gcs_timestamp = 0 msg_id = 0 # unique ID increments for each message sent ack_id = None xbee = None # XBee radio object xbee_callback = None def __init__(self, configs, xbee_callback): '''initializes coms object''' self.configs = configs self.xbee_callback = xbee_callback self.mutex = ComsMutex() if configs['coms_simulated'] is True: comm_sim = Thread(target=self.comm_simulation) comm_sim.start() else: try: port_name = "" if sys.platform == "darwin": port_name = mac_xbee_port_name() elif sys.platform == "linux" or sys.platform == "linux2": port_name = "/dev/ttyUSB0" # TODO: figure out windows port name elif sys.platform == "win32": port_name = "COMS1" # Instantiate XBee device object. self.xbee = XBeeDevice(port_name, 57600) self.xbee.open() # If error in setting up XBee, try again except TimeoutError as ex: print(ex) print("Connect the XBee radio!") time.sleep(5) def send_till_ack(self, address, msg, msg_id): '''Continuously sends message to given address until acknowledgement message is recieved with the corresponding ackid.''' # Instantiate a remote XBee device object to send data. packed_data = bytearray(msgpack.packb(msg)) while self.ack_id != msg_id: self.send(address, packed_data) time.sleep(1) def acknowledge(self, address, ack_id): '''Sends message received acknowledgement to GCS param address: address of GCS''' ack = { "type": "ack", "time": round(time.clock() - self.con_timestamp) + self.gcs_timestamp, "sid": self.configs['vehicle_id'], "tid": 0, # The ID of GCS "id": self.new_msg_id(), "ackid": ack_id } self.send(address, ack) def new_msg_id(self): '''Increments msg_id and returns unique id for new message''' self.msg_id += 1 return self.msg_id def recieve(self): '''Instantiate XBee device''' try: self.xbee.flush_queues() print("Waiting for data...\n") while True: xbee_message = self.xbee.read_data() if xbee_message is not None: print("Received '%s' from %s" % (xbee_message.data.decode(), \ xbee_message.remote_self.xbee.get_64bit_addr())) finally: if self.xbee is not None and self.xbee.is_open(): self.xbee.close() 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 bad_msg(self, address, problem): '''Sends "bad message" to GCS if message received was poorly formatted/unreadable and describes error from parsing original message. :param address: address of GCS :param problem: string describing error from parsing original message''' msg = { "type": "badMessage", "time": round(time.clock() - self.con_timestamp) + self.gcs_timestamp, "sid": self.configs['vehicle_id'], "tid": 0, # The ID of GCS "id": self.new_msg_id(), "error": problem } self.send(address, msg) # TODO: needs to be updated def comm_simulation(self): '''Connects to HTTP server at a specific port''' logging.basicConfig(level=logging.INFO) server_address = ('', 8080) partial_server = partial(ComsServer, self.xbee_callback) httpd = HTTPServer(server_address, partial_server) logging.info('Starting httpd...\n') try: httpd.serve_forever() except KeyboardInterrupt: pass httpd.server_close() logging.info('Stopping httpd...\n')
def main(): global target_x global target_y global List_Target_X global List_Target_Y global List_X global List_Y global start_time global split_time target_x = 0 target_y = 0 i = 0 target = targets[i] target_x = int(target.split(',')[0]) target_y = int(target.split(',')[1]) List_Target_X.append(target_x) List_Target_Y.append(target_y) start_time = time.time() device = XBeeDevice("COM4", 9600) device.open() remote_device = RemoteXBeeDevice(device,XBee64BitAddress.from_hex_string("0013A20040631612")) device.send_data(remote_device, "0") xbee_message = device.read_data() while xbee_message is None: xbee_message = device.read_data() xbee_message = xbee_message.data.decode() ok = 1 print(xbee_message) while True: print('Alvo: ' + str(target)) if target is not None: if ok == 1: device.send_data(remote_device,VerificaPosicao()) ok = 0 elif ok==0: robot_info = device.read_data() while robot_info is None: robot_info = device.read_data() robot_info = robot_info.data.decode() print ('Informacao Recebida do Robo: ' + str(robot_info)) if 'Posicao' in robot_info: device.send_data_broadcast(VerificaPosicao()) elif 'Cheguei' in robot_info: #ws['H' + str(cont_linhas_planilha - 1)] = 'Cheguei' if i < len(targets) - 1: i += 1 target = targets[i] target_x = int(target.split(',')[0]) target_y = int(target.split(',')[1]) List_Target_X.append(target_x) List_Target_Y.append(target_y) device.send_data(remote_device,VerificaPosicao()) else: break #wb.save('relatório.xlsx') print ("\n\n") device.close() print ("\n\n") print ("O robo chegou a todos os alvos. Aplicacao encerrada.") plt.plot(List_X, List_Y, 'r--', List_Target_X, List_Target_Y, 'bo', List_X[0], List_Y[0], 'go') plt.axis([0, dist_x, 0, dist_y]) plt.show()
gpsport="/dev/ttyAMA0" CONNECTION_STRING = "HostName=xbeeiothub.azure-devices.net;DeviceId=xbeedevice;SharedAccessKey=a8wgnR2w1H6f3Ch6QcUV+dJ2sU/ca3XpZ28in2nD1eo=" device = XBeeDevice(XBEEPORT, BAUD_RATE) device.open() while True: ser=serial.Serial(gpsport, BAUD_RATE, timeout=0.5) dataout = pynmea2.NMEAStreamReader() newdata=ser.readline() if newdata[0:6] == "$GPRMC": newmsg=pynmea2.parse(newdata) lat=newmsg.latitude lng=newmsg.longitude gps = "Latitude=" + str(lat) + "and Longitude=" + str(lng) xbee_message = device.read_data() remote_device = xbee_message.remote_device client = IoTHubDeviceClient.create_from_connection_string(CONNECTION_STRING) if xbee_message is not None: if remote_device == "XBee B": message=xbee_message.data.decode() if message>28: client.send_message("Forest Fire Detected by XBee B at Coordinates:" + gps) if remote_device == "XBee C": message=xbee_message.data.decode() if message>45: client.send_message("Forest Fire Detected by XBee C at Coordinates:" + gps) if remote_device == "XBee D": message=xbee_message.data.decode() if message>45: client.send_message("Forest Fire Detected by XBee D at Coordinates:" + gps)
class WaspServer: def __init__(self, usb="/dev/ttyUSB0", freq=115200): self._device = XBeeDevice(usb, freq) try: self._device.open() except XBeeException: logging.error("Error while opening xbee") self._reachable_devices = {} def close_server(self): self._device.close() try: logger = logging.getLogger("waspserver") logger.info(" *** Server closed") print(" *** Server closed") except: pass def start_scanner(self, scan_time=10, deeptime=10): def scan(): while self._device.is_open(): print(" *** Start scanning *** ") # Scan network xnet = self._device.get_network() xnet.start_discovery_process(deep=True, n_deep_scans=1) while xnet.is_discovery_running(): time.sleep(0.5) nodes = xnet.get_devices() new_remotes = {} infostr = " *** All reachable devices ***\n" for n in nodes: new_remotes[str(n.get_64bit_addr())] = n infostr += "\t" + str(n) logger = logging.getLogger("waspserver") logger.info(infostr) print(infostr) avail_remotes = {} # Communicate with new remotes for k in new_remotes.keys(): new_dev = new_remotes[k] if commands.generate_start_communication( self._device, new_dev, deeptime): logger = logging.getLogger("waspserver") logger.info(f"{k} connected!\n") self._reachable_devices = new_remotes time.sleep(scan_time) thread = threading.Thread(target=scan, daemon=True) thread.start() def recv_message(self): def recv_fun(): logger = logging.getLogger("waspserver") while True: try: # Receive message from any source msg = self._device.read_data() if msg is not None: # Receive message ? # Ignore previously undetected devices addr = str(msg.remote_device.get_64bit_addr()) if addr not in self._reachable_devices.keys(): continue # Checks if message is a status packet if commands.parse_status_packet(msg): logger.info( f"Parse status packet received : {msg.data.decode()} from {msg.remote_device.get_64bit_addr()}" ) continue except Exception as ex: logger.debug(f"{ex}") thread = threading.Thread(target=recv_fun, daemon=True) thread.start() def loop(self): try: while True: self.__loop() except KeyboardInterrupt: self.close_server() def __loop(self): pass def __del__(self): self.close_server()
class Antenna: 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 find_port(self): ports = prtlst.comports() for port in ports: try: if "FTDI" in port.manufacturer: return port.device except Exception: pass return "" def send(self, data, time=None, data_key=None, skip_time=0, parent="", as_json=False): """ Recursively send asynchronous data. """ if as_json: data = loads(data) # Update Time if time == None: time = unixtimestamp() #self.last_time_sent = time # Skip if time buffer too low if skip_time != 0: if time - self.last_time_sent < skip_time: return None self.last_time_sent = time self.verbose_print((self.active, data)) if self.active: try: data["uts"] = time to_send = dumps(data).encode() self.device.send_data_async(self.remote_device, to_send) """ try: if type(data) == dict: for key in data: parent = "" if data_key == None else data_key self.send( data[key], time=time, data_key=key, parent=parent ) else: send_data = { "uts" : time, f"{parent}_{str(data_key)}" : data } to_send = dumps(send_data).encode() self.verbose_print(to_send) self.device.send_data_async( self.remote_device, to_send ) """ except Exception as e: self.verbose_print(f"COULDN'T SEND {data}, ERROR {e}") return None def verbose_print(self, message): if self.verbose: print(message) def read_time(self, time): if not self.active: print("NOT ACTIVE") return "{}" new_data = self.device.read_data(time) try: new_data_processed = loads(new_data.data.decode()) except Exception as e: print(e) return key_name = "" val = 0 for key in new_data_processed: if "uts" in key: self.cur_uts = new_data_processed[key] else: key_name = key val = new_data_processed[key] if self.cur_uts in self.cur_data: self.cur_data[self.cur_uts][key_name] = val if self.cur_uts not in self.cur_data: self.ready_data.update(self.cur_data) self.cur_data = {self.cur_uts: {key_name: val}} def send_halt(self): print("[send_halt] sending halt") self.send({"key": SECRET_KEY, "command": "h"}) def send_arm(self): print("[send_arm] sending arm") self.send({"key": SECRET_KEY, "command": "a"}) def send_eject(self, para): print("[send_eject] sending eject for", para) self.send({"key": SECRET_KEY, "command": "e" + str(para)}) def start_sim(self): return def get_finished_data(self): finished_data = deepcopy(self.ready_data) if finished_data == {}: return {} self.ready_data = {} time_key = max(finished_data.keys()) finished_data = finished_data[time_key] if "_time" in finished_data: finished_data["time"] = finished_data["_time"] finished_data["sensors"] = {"gyro": {}} finished_data["sensors"]["alt"] = finished_data.get("sensors_alt", 0) for i in ["x", "y", "z"]: finished_data["sensors"]["gyro"][i] = finished_data.get( f"gyro_{i}", 0) return finished_data
class Antenna: def __init__(self, port="", remote_address="", verbose=False): self.verbose = verbose if port is "": 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: self.active = False try: add_64 = ( FalseXBee64BitAddress.from_hex_string(remote_address)) self.remote_device = RemoteXBeeDevice(self.device, add_64) except Exception: self.has_remote = False else: self.active = False self.device = None def find_port(self): ports = prtlst.comports() for port in ports: try: if "FTDI" in port.manufacturer: return port.device except Exception: pass return "" def send(self, data, time=None, data_key=None, skip_time=0, parent="", as_json=False): """ Recursively send asynchronous data. """ if as_json: data = loads(data) # Update Time if time == None: time = unixtimestamp() #self.last_time_sent = time # Skip if time buffer too low if skip_time != 0: if time - self.last_time_sent < skip_time: return None self.last_time_sent = time print("SENDING") self.verbose_print((self.active, data)) if self.active: try: if type(data) == dict: for key in data: parent = "" if data_key == None else data_key self.send(data[key], time=time, data_key=key, parent=parent) else: send_data = { "uts": time, f"{parent}_{str(data_key)}": data } to_send = dumps(send_data).encode() self.verbose_print(to_send) self.device.send_data_async(self.remote_device, to_send) except Exception as e: self.verbose_print(f"COULDN'T SEND {data}, ERROR {e}") return None def verbose_print(self, message): if self.verbose: print(message) def read_time(self, time): if not self.active: return "{}" return self.device.read_data(time)
from digi.xbee.devices import XBeeDevice import array import struct PORT = "COM9" # TODO: Replace with the baud rate of your local module. BAUD_RATE = 9600 xbee = XBeeDevice(PORT, BAUD_RATE) xbee.open() while True: try: # print(xbee.read_data_from(0x13A200409F5BA2,5)) #specific xbee on teensy 64bit addr xbee_message = xbee.read_data(10) #Timeout value data_output = xbee_message.data #print(data_output) fmt = "<%dd" % (len(data_output) // 8) #print(fmt) print(list(struct.unpack(fmt, data_output))) #print(array.array('d', data_output)) #print(data_output.decode("utf-8")) except KeyboardInterrupt: break xbee.close()