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 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(" | 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 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
class XbeeBoat: def __init__(self, _port, _baud_rate, _remote_id, _ros_rate): self.usv_master_status = "" # Initialize and configure the DigiXTend Xbee Device self.device = XBeeDevice(_port, _baud_rate) self.device.open() if not self.device.is_open(): rospy.loginfo('[USV] Device could not be opened.') raise Exception() self.device.flush_queues() self.xnetwork = self.device.get_network() self.remote_device = self.xnetwork.discover_device(_remote_id) if self.remote_device is None: rospy.loginfo('[USV] Could not find the remote device.') self.device.close() raise Exception() rospy.loginfo('[USV] Digi XTend device initialized.') # ROS Configuration self.ros_rate = rospy.Rate(_ros_rate) # ROS Subscriber rospy.Subscriber("/usv_comms/boat_transceiver/data_input", String, self.data_callback) rospy.Subscriber("/usv_master/usv_master_status", String, self.usv_master_callback) # ROS Publisher self.stop_pub = rospy.Publisher( "/usv_comms/boat_transceiver/stop_mission", Empty, queue_size=10) self.course_pub = rospy.Publisher( "/usv_comms/boat_transceiver/course_config", String, queue_size=10) self.start_pub = rospy.Publisher( "/usv_comms/boat_transceiver/start_mission", Empty, queue_size=10) self.general_status_pub = rospy.Publisher( "/usv_comms/boat_transceiver/general_status", String, queue_size=10) self.empty_msg = Empty() self.boat_data = String() self.comm_active = True rospy.loginfo('[USV] Awaiting conversation...\n') def data_callback(self, _data): self.boat_data = _data.data #rospy.loginfo('[USV] Sending data: ', self.boat_data) #self.device.send_data_async(self.remote_device, self.boat_data) def usv_master_callback(self, status): self.usv_master_status = status.data
class XbeeStation: def __init__(self, _port, _baud_rate, _remote_id, _ros_rate): # Initialize and configure the DigiXTend Xbee Device self.device = XBeeDevice(_port, _baud_rate) self.device.open() if not self.device.is_open(): rospy.loginfo('[STATION] Device could not be opened.') raise Exception() self.device.flush_queues() self.xnetwork = self.device.get_network() self.remote_device = self.xnetwork.discover_device(_remote_id) if self.remote_device is None: rospy.loginfo('[STATION] Could not find the remote device.') self.device.close() raise Exception() rospy.loginfo('[STATION] Digi XTend device initialized.') # ROS Configuration self.ros_rate = rospy.Rate(_ros_rate) # ROS Publisher self.boat_data_pub = rospy.Publisher( '/usv_comms/station_transceiver/boat_data', String, queue_size=10) # ROS Subscriber rospy.Subscriber('/usv_comms/station_transceiver/course_config', String, self.config_callback) rospy.Subscriber("/usv_comms/boat_transceiver/general_status", String, self.general_status_callback) rospy.loginfo('[STATION] ROS Node initialized.') self.comm_active = True rospy.loginfo('[STATION] Awaiting conversation...\n') def config_callback(self, _config): rospy.loginfo('[STATION] Sending following message: ' + str(_config.data)) self.device.send_data_async(self.remote_device, str(_config.data)) if str(_config.data) == 'exit': self.comm_active = False def general_status_callback(self, status): self.boat_general_status = status.data
def connect_to_device(): try: reset_xbee() except Exception as e: print(str(e)) print("COULD NOT RESET THE XBEE!") try: port = current_app.config.get("DEVICE_PORT") baud_rate = current_app.config.get("BAUD_RATE") device = XBeeDevice(port, baud_rate) device.open() device.flush_queues() current_app.config['CACHE']['device'] = device except Exception as e: print("!!!...CONNECTION TO THE DEVICE FAILED...!!!") print(str(e))
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 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()
def main(gps_queue_out, audio_queue_in, audio_queue_out, ui_queue_in, ui_queue_out): print('Begin Wireless') device = XBeeDevice('/dev/ttyUSB0', 230400) device.open() device.flush_queues() remote_addr = '0013A2004155E2A6' remote_device = RemoteXBeeDevice( device, XBee64BitAddress.from_hex_string(remote_addr)) last_sent = datetime.datetime.timestamp(datetime.datetime.now()) while (True): #print('Trying the ui_queue.get()') try: distress_msg = ui_queue_out.get(block=False) # Distress messages? #print('Got distress_msg from queue') if distress_msg is not None: if distress_msg == 'exit': print( 'Exit command recieved, sending termination message to remote devices' ) result = xbee_write(device, remote_device, data_segment) if result != 'ACK': print( 'Data_Segment: {0:} failed to send, remote devices not commanded to exit.\n Exiting...' .format(data_segment)) device.close() return print('Exit sucessfully sent from client to server') if distress_msg == 'Distress beacon active': device_id = '0013A2004155E2AB' date_time = datetime.datetime.utcfromtimestamp(0) gps = '150.112,-45.555' # Should read latest GPS stamp from benn_gps?? data_segment = Data_Segment( 'distress', '0013A2004155E2AB' + ',' + str( datetime.datetime.timestamp( datetime.datetime.now())) + ',' + '150.111,-45.444') #print('Sending distress to xbee_write()') result = xbee_write(device, remote_device, data_segment) # Write distress to xbee if result != 'ACK': print( 'Distress Data_Segment: {0:} failed to send, dropping packet' .format(distress_segment)) #print('Distress sucessfully sent from client to server') except queue.Empty: pass #print('Empty ui_queue, continuing') #print('Trying the gps_queue.get()') try: gps_msg = gps_queue_out.get(block=False) #print('Got data_segment from gps_queue_out: {0:}'.format(gps_msg)) if gps_msg is not None: now = datetime.datetime.timestamp(datetime.datetime.now()) if now - last_sent > 15: last_sent = now data_segment = Data_Segment('gps', gps_msg.data) print('Sending gps to xbee_write()') result = xbee_write(device, remote_device, data_segment) if result != 'ACK': print( 'GPS Data_Segment: {0:} failed to send, dropping packet' .format(data_segment)) #print('GPS sucessfully sent from client to server') except queue.Empty: pass #print('Empty gps queue, continuing') #print('Trying the audio_out.get()') try: audio_file = audio_queue_out.get(block=False) print('Got filename from audio_queue_out: {0:}'.format(audio_file)) if audio_file is not None: data_segment = Data_Segment('audio', audio_file) #print('Sending audio to xbee_write()') result = xbee_write(device, remote_device, data_segment) if result != 'ACK': print( 'Audio Data_Segment: {0:} failed to send, dropping packet' .format(data_segment)) #print('Audio sucessfully sent from client to server') except queue.Empty: pass #print('Empty gps queue, continuing') print('xbee_read()') data_segment = xbee_read(device) # This device if data_segment is not None: if data_segment.data_type == 'audio': audio_queue_in.put(data_segment.data) # .data = filename if data_segment.data_type == 'message': ui_queue_in.put(data_segment.data) # .data = msg string elif data_segment.data_type == 'TIMEOUT': print('Timeout at Client wireless read(), retrying') continue elif data_segment.data_type == 'ERROR': print('XBee read error in main()') continue else: # Probably shutdown signal, so exit print('Shutdown signal at wireless read(), exiting') device.close() return print('End wireless')
class XBee2UDP(object): def __init__(self, ip, serial_port, baud_rate, **kwargs): """ Version 2 of the XBee to UDP class :param serial_port: Device location :param baud_rate: Baud rate :param udp: udp connection defaults (ip, port) :param kwargs: Other arguments passed to the XBee device initializer """ # Initialize LUT for queues, MAVLink UDP sockets and stream parsers self.vehicles = [] self.ip = ip # Initialize XBee device connection self.xbee = XBeeDevice(port=serial_port, baud_rate=baud_rate, **kwargs) while not self.xbee.is_open(): try: self.xbee.open() except (InvalidPacketException, InvalidOperatingModeException, TimeoutException) as e: logging.exception(e) time.sleep(3) logging.info('XBee opened successfully.') self.main_running = False self.dev_running = {} self._udp_tx_closed = True def start(self): """ Starts all processes and threads in appropriate order """ self.main_running = True # Spawn UDP Tx thread _udp_tx_thread = threading.Thread(target=self._udp_tx_thread, daemon=True) _udp_tx_thread.start() # Once discovery has successfully completed, begin main loops _main_thread = threading.Thread(target=self._main_thread, daemon=True) _main_thread.start() def close(self): """ Sets while-loop conditions to False for all threads, so each will run to completion and appropriate clean-up processes will be executed prior to the script terminating. """ logging.info(f'Closing script...') self.main_running = False while self.vehicles: self.del_uav(self.vehicles[0]) def del_uav(self, vehicle: UAVObject): """ Deletes a UAVObject when a connection has been lost, or for whatever other reason a deletion is required :param vehicle: UAVObject unique to the vehicle in question """ vehicle.connected = False time.sleep(0.02) self.vehicles.remove(vehicle) logging.info(f'Deleting connection with {vehicle}') del vehicle def new_uav(self, request_message): """ Helper function for extracting useful data from a connection request, then initializing a UAVObject or the newly connected vehicle :param request_message: XBee packet containing information about the new UAV requesting a connection """ # Extract information data = request_message.data identifier, port = struct.unpack('>BH', data) name = f'Navi {identifier}' device = request_message.remote_device # Create new vehicle object and acknowledge vehicle over radio vehicle = UAVObject(name, self.ip, port, device) self.vehicles.append(vehicle) self.xbee.send_data(device, b'COORD') # Start Rx UDP thread for this vehicle _udp_rx_thread_x = threading.Thread(target=self._udp_rx_thread, args=(vehicle, ), daemon=True) _udp_rx_thread_x.start() def _main_thread(self): """ Primary loop for servicing and passing data to the correct place: I. Read messages from the XBee's Rx FIFO buffer, parse and place the in the appropriate queue. New messages from undiscovered vehicles will trigger a process creating a UAVObject for the new vehicle. II. Iterate through known devices, clear outgoing queue for each and attempt to transmit. If there is an error in transmission this device will be deleted, along with all associated queues and UDP connections. III. TODO Check for a handover command. IV. TODO Send broadcast to all UAVs if a hand-over is to occur. """ while self.main_running: # I. Service messages from vehicles (incoming/Rx) rx_packet = self.xbee.read_data() # will replace with a walrus statement in python 3.8 (rx_packet := self.xbee.read_data()) while rx_packet: # Check whether transmitting device is known or not if any([v == rx_packet.remote_device for v in self.vehicles]): index = self.vehicles.index(rx_packet.remote_device) vehicle = self.vehicles[index] try: mav_msgs = vehicle.parser.parse_buffer(rx_packet.data) except mavlink.MAVError as e: # Check MAVLink message for errors logging.exception(e) else: if mav_msgs: vehicle.queue_in.extend(mav_msgs) else: self.new_uav( rx_packet ) # Unknown transmitter - reply to connection request time.sleep(0.01) self.xbee.flush_queues( ) # XBee queue may contain multiple connection requests from this device time.sleep(0.01) rx_packet = self.xbee.read_data() # II. Service queues from GCS (outgoing/Tx) for vehicle in self.vehicles: outgoing = vehicle.queue_out.read_bytes() try: while outgoing: self.xbee.send_data(vehicle.device, outgoing[:XBEE_PKT_SIZE]) outgoing = outgoing[XBEE_PKT_SIZE:] except XBeeException as e: logging.exception(e) self.del_uav(vehicle) break time.sleep(0.001) self.xbee.close() @staticmethod def _udp_rx_thread(vehicle: UAVObject): """ One thread is created for each UDP-XBee connection required, as socket.recvfrom() is a blocking function, and will wait until data has been received from QGroundControl (or other GCS software). By doing this, new data that is forwarded on from the XBee to QGroundControl is not held up by the recvfrom function. :param vehicle: UAVObject representing a connected vehicle """ logging.info(f'Started UDP Rx thread for {vehicle}') while vehicle.connected: msg = vehicle.socket.recv_msg() if msg: vehicle.queue_out.write(msg) time.sleep(0.01) def _udp_tx_thread(self): """ UDP transmission thread that iterates through the queues of each remote XBee device by Node ID and sends any data directly along the associated UDP socket to QGroundControl or other GCS. """ logging.info(f'Started UDP Tx thread') while self.main_running: for vehicle in self.vehicles: if vehicle.queue_in: msg = vehicle.queue_in.read() vehicle.socket.write(msg.get_msgbuf()) time.sleep(0.01)
import time import os import sys from influxdb import InfluxDBClient from digi.xbee.devices import XBeeDevice #TODO: change Influxport if configured differenly client = InfluxDBClient(host='localhost', port=8086) #TODO: change to the database that you would like to use client.switch_database('service') #TODO: configure with the port using #if the xbeedevice is connected without usb PI should be ttyAMA0, or ttySerial0 device = XBeeDevice("/dev/ttyUSB0", 230400) device.open() device.flush_queues() p1 = 0.00 p2 = 0.00 #main will recieve the data from the sending xbees and split it based on the MAC addresses #of the xbee chips def main(): global p1, p2 #read the incoming messages xbee_message = device.read_data() if xbee_message is not None: #the variable x will pull the MAC address of the data that it recieved x = str(xbee_message.remote_device.get_64bit_addr()) #the variable mes will be the actual data that was sent
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 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" #resamples = resample_audio('30second_48.wav') # Sarah's example; typical - may change prepared_audio = prepare_audio('resample.mp3') audio_ack = False GPS_ack = False SOS_ack = False while (True): try: if not audio_ack: print('Sending Audio from COM3') for i in range(0, len(prepared_audio)): bytes_obj = pickle.dumps(prepared_audio[i]) device.send_data(remote_device, bytes_obj) rcv_bytes = device.read_data(1) rcv = pickle.loads(rcv_bytes.data) #print('Audio rcv: {0:}'.format(rcv)) if rcv == 'ACK': #print('Audio Transfer complete') audio_ack = True device.flush_queues() else: #print('Audio transfer failed') continue if not SOS_ack: print('Sending SOS from COM3') x = Bytes_Segment(b'0x02', 1, 1, 'SOS') pickled = pickle.dumps(x) device.send_data(remote_device, pickled) rcv_bytes = device.read_data(1) rcv = pickle.loads(rcv_bytes.data) #print('SOS rcv: {0:}'.format(rcv)) if rcv == 'ACK': #print('SOS complete') SOS_ack = True else: #print('SOS transfer failed') continue if not GPS_ack: print('Sending GPS from COM3') x = Bytes_Segment(b'0x03', 1, 1, '150,45,130012312312') pickled = pickle.dumps(x) device.send_data(remote_device, pickled) rcv_bytes = device.read_data(1) rcv = pickle.loads(rcv_bytes.data) #print('GPS rcv: {0:}'.format(rcv)) if rcv == 'ACK': #print('GPS complete') GPS_ack = True else: #print('GPS transfer failed') continue if audio_ack and GPS_ack and SOS_ack: #if True: print('Sending Shutdown from COM3') x = Bytes_Segment(b'0x00', 1, 1, '') pickled = pickle.dumps(x) device.send_data(remote_device, pickled) rcv_bytes = device.read_data(1) rcv = pickle.loads(rcv_bytes.data) #print('Shutdown rcv: {0:}'.format(rcv)) if rcv == 'ACK': print('Shutting down') device.close() return else: print('Shutdown transfer failed') continue device.close() return except TimeoutException: #print('Timeout from COM3') continue
def main(argv): global FILE_OUT global device_path_computer global device_bb_64 global device_path global BAUD if (len(argv) == 1): print( '\n\nUsage: %s <file to save to> [<remote xbee 64 bit address> <BAUD>]\n\n' % argv[0]) raise IncorrectUsage() elif (len(argv) == 2): FILE_OUT = argv[1] elif (len(argv) == 3): device_bb_64 = argv[2] elif (len(argv) == 4): BAUD = int(argv[3]) device = XBeeDevice(device_path, BAUD) device.open() remote_device = RemoteXBeeDevice( device, XBee64BitAddress.from_hex_string(device_bb_64)) # TX/RX :: First message sent is the length of the file print('\n\n') b_continue = True while (b_continue): xbee_message = device.read_data() if xbee_message is not None: data = xbee_message.data data_length = int(data) bar = Bar('Processing', max=int(data_length / 256)) device.flush_queues() b_continue = False # TX/RX b_continue = True fo = open(FILE_OUT, 'wb') while (b_continue): xbee_message = device.read_data() if xbee_message is not None: data = xbee_message.data if (data[-24:] == bytearray(b'End of the file transfer')): b_continue = False data = data[0:-24] device.flush_queues() fo.write(data) if (b_continue): bar.next() fo.close() # compute the md5 sum md5 = hashlib.md5(open(FILE_OUT, 'rb').read()).hexdigest() # check the md5 sum of the local file and compare it to that of the remote file device.send_data(remote_device, 'Send the md5 please.') b_continue = True # Get the message while (b_continue): xbee_message = device.read_data() if xbee_message is not None: data = xbee_message.data b_continue = False if (md5 == data.decode()): print('File transfer successful.\n\n') else: print('File transfer did not work.') raise FileTransferError() device.close()
def main(gps_queue, distress_queue, message_queue, audio_queue_in, audio_queue_out): print('Begin Wireless') device = XBeeDevice('COM3', 230400) device.open() device.flush_queues() while(True): data_segment = xbee_read(device) # This device, Set timeout #print('Got data_segment from xbee_read: {0:}'.format(data_segment)) #print('data_segment type: {0:}'.format(type(data_segment))) #print('data_segment isinstance: {0:}'.format(isinstance(data_segment, Data_Segment))) if data_segment is not None: if data_segment.data_type == 'TIMEOUT': pass if data_segment.data_type == 'gps': #print('Server got: {0:}'.format(data_segment)) gps_queue.put(data_segment) if data_segment.data_type == 'audio': #print('Got audio segment from xbee read in main()') audio_queue_in.put(data_segment) print('audio put on queue') if data_segment.data_type == 'distress': distress_queue.put(data_segment) if data_segment.data_type == 'TIMEOUT': pass # print('Timeout at server wireless read(), retrying') else: # Probably shutdown signal, so exit print('Shutdown signal at wireless read(), exiting') device.close() return try: #print('checking message queue') old_segment = message_queue.get(timeout=2) #print('Got data_segment from message_queue: {0:}'.format(data_segment)) #print('data_segment type: {0:}'.format(type(data_segment))) #print('data_segment isinstance: {0:}'.format(isinstance(data_segment, Data_Segment))) if data_segment is not None: if old_segment.data_type == 'exit': data_segment = Data_Segment('exit', old_segment.data) print('Exit command recieved, sending termination message to remote devices') result = xbee_write(device, data_segment) if result != 'ACK': print('Data_Segment: {0:} failed to send, remote devices not commanded to exit.\n Exiting...'.format(data_segment)) device.close() return data_segment = Data_Segment('message', old_segment.data) #print('Got message from message queue in wireless.main(), writing to xbee') result = xbee_write(device, data_segment) if result != 'ACK': print('Data_Segment: {0:} failed to send, dropping packet'.format(data_segment)) except queue.Empty: pass #print('Empty message_out queue, continuing') try: #print('checking audio queue') data_segment = audio_queue_out.get(timeout=2) #print('Got data_segment from message_queue: {0:}'.format(data_segment)) #print('data_segment type: {0:}'.format(type(data_segment))) #print('data_segment isinstance: {0:}'.format(isinstance(data_segment, Data_Segment))) if data_segment is not None: result = xbee_write(device, data_segment) if result != 'ACK': print('Data_Segment: {0:} failed to send, dropping packet'.format(data_segment)) except queue.Empty: pass #print('Empty audio_out queue, continuing') print('End wireless')
def subscriber(xbee, imu): '''Esto es para el bote, el bote envia a la estacion cada 500ms''' #****************************************************************************************# # Replace with the serial port where your local module is connected to. PORT = "/dev/ttyUSB1" # Replace with the baud rate of your local module. BAUD_RATE = 9600 REMOTE_NODE_ID = "vtecstation" #El nodo con el que se quiere comunicar. #****************************************************************************************# print(" +-------------------------------------------------+") print(" | Bote |") print(" +-------------------------------------------------+\n") device = XBeeDevice(PORT, BAUD_RATE) gps_navigation = GPSNavigation(imu) try: device.open() device.flush_queues() print("Waiting conversation...\n") while True: xbee_message = device.read_data() if xbee_message is not None: #Imprime el json para prueba jmessage = json.loads(bytes(xbee_message.data).decode()) print(jmessage) # Set current coords coords = imu.get_gps_coords() lat = coords['latitude'] lon = coords['longitud'] xbee.set_latlong(lat,lon) # Set target coords if jmessage['action'] == '2': xbee.set_target(float(jmessage['target_lat']),float(jmessage['target_lon'])) gps_navigation.update_nav(xbee.target_lat, xbee.target_lon) # Waypoint elif jmessage['action'] == '3': # Until there is a resutl res = 'not found pair of posts' while res == 'not found pair of posts' or res is None: res = main_caller('autonomus_navigation') gps_navigation.navigation.search() gps_navigation.auto_nav(res[0], res[1]) # Waypoint Carlos res = 'not found pair of posts' while res == 'not found pair of posts' or res is None: res = main_caller('autonomus_navigation') gps_navigation.navigation.search() gps_navigation.auto_nav(res[0], res[1]) # Waypoint Carlos elif jmessage['action'] == '4': # Until there is a resutl res = 'not found pair of posts' or res is None: while res == 'not found pair of posts': res = main_caller('autonomus_navigation') gps_navigation.navigation.search() gps_navigation.auto_nav2(res[0], res[1]) # Waypoint Carlos res = 'not found pair of posts' while res == 'not found pair of posts' or res is None: res = main_caller('autonomus_navigation') gps_navigation.navigation.search() gps_navigation.auto_nav2(res[0], res[1]) # Waypoint Carlos elif jmessage['action'] == '5': # Until there is a resutl res = 'not found pair of posts' while res == 'not found pair of posts': res = main_caller('autonomus_navigation') gps_navigation.navigation.search() gps_navigation.auto_nav(res[0], res[1]) # Waypoint Carlos res = 'not found pair of posts' while res == 'not found pair of posts': res = main_caller('autonomus_navigation') gps_navigation.navigation.search() gps_navigation.auto_nav(res[0], res[1]) # Waypoint Carlos xbee_network = device.get_network() remote_device = xbee_network.discover_device(REMOTE_NODE_ID) #Aqui debe enviarlo al servidor device.send_data(remote_device, xbee.send()) finally: if device is not None and device.is_open(): device.close()
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
def main(): coord = XBeeDevice('COM7', 9600) # Create XBeeDevice object for the coordinator at COM7 with Baud Rate 9600 try: coord.open() # Open communication with the XBee device coord.flush_queues() xbee_network = coord.get_network() # Get the network that coord is connected to router2 = xbee_network.discover_device('R2') # Find the remote device on the network with ID 'R2' if router2 is None: # If we could not find R2 then the program will continue to run print("Could not find the remote alert device (R2)") else : print("Remote alert device (R2) found") timestamp, date, time_ = getTime(True) with open(".\\logs\\{0}-{1}.log".format(date, time_), mode="a") as myFile: # Creates a new log file myFile.write("# Date\t\tTime\t\tTimestamp\tTemperature\tHumidity\n") while True: xbee_message = coord.read_data() # Read the data from R1 on the Sensor Arduino if xbee_message is not None: timestamp, date, time_ = getTime() # Get the time data_raw = xbee_message.data.decode().split(",") # Turn the sensor data into a list data = [float(element) for element in data_raw] # Turn each element of data_raw into a float dataToSend = "" # Temperature print("\nAt {0} {1} Temperature is {2}".format(date, time_, data[0]), end=": ") if data[0] > 24.65: print("Unsafe") dataToSend += "T1" stateT = "U" else: print("Safe") dataToSend += "T0" stateT = "S" ## Pressure #print("At {0} {1} Pressure is {2}".format(date, time_, data[1]), end=": ") #if data[1] > 1000: # print("Unsafe") # dataToSend += "P1" # stateP = "U" #else: # print("Safe") # dataToSend += "P0" # stateP = "S" # Humidity print("At {0} {1} Humidity is {2}".format(date, time_, data[2]), end=": ") if data[2] > 70: print("Unsafe") dataToSend += "H1" stateH = "U" else: print("Safe") stateH = "S" dataToSend += "H0" if router2 is not None: coord.send_data(router2, dataToSend) text = "{0}\t{1}\t{2}\t{3}{4}\t\t{5}{6}\n".format(date, time_, timestamp, stateT, data[0], stateH, data[2]) myFile.write(text) finally: if coord is not None and coord.is_open(): # Closes the communications to the coordinator when the program closes coord.close()