Beispiel #1
0
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()
Beispiel #2
0
def main():
    device = XBeeDevice("/dev/ttyS0", 9600)
    A_O = -50
    d_O = 1
    rssi_val = []

    # Formula used to calculate distance from RSSI
    # RSSI = -10*n log(d/d_O) + A_O
    # Where A_O is the RSSI for d_O = 1m
    # By performing the experiments the value of RSSI is found to be 50
    
    try:
        device.open()

        def packets_received_callback(packet):
            packet_dict = packet.to_dict()
            api_data = packet_dict[DictKeys.FRAME_SPEC_DATA][DictKeys.API_DATA]
            data = api_data[DictKeys.RF_DATA]
            rssi = api_data[DictKeys.RSSI]
            rssi_val.append(rssi)
            print(rssi)
            
        device.add_packet_received_callback(packets_received_callback)

        print("Waiting for data ...\n")
        input()


    # The value of the distance obtained is approximate to a few centimeters
    # And hence we can choose to use an average value instead of an actual value
    # This small variation in the distance should not affect the algorithm by a lot
    finally:
        if device is not None and device.is_open():
            print("\n")
            d_base = (A_O - ((-1)*rssi_val[0]))/20.0
            relative_distance = 10 ** d_base 
            print(relative_distance)
            device.close()
def main():
    print(" +-----------------------------------------------------+")
    print(" | XBee Python Library Receive MicroPython Data Sample |")
    print(" +-----------------------------------------------------+\n")

    device = XBeeDevice(PORT, BAUD_RATE)

    try:
        device.open()

        def micropython_data_callback(data):
            print("Data received from MicroPython >> '%s'" %
                  data.decode("utf-8"))

        device.add_micropython_data_received_callback(
            micropython_data_callback)

        print("Waiting for data from the MicroPython interface...\n")
        input()

    finally:
        if device is not None and device.is_open():
            device.close()
def main():
    print(" +----------------------------------------------------+")
    print(" | XBee Python Library Receive User Data Relay Sample |")
    print(" +----------------------------------------------------+\n")

    device = XBeeDevice(PORT, BAUD_RATE)

    try:
        device.open()

        def relay_data_callback(relay_message):
            print("Relay data received from %s >> '%s'" %
                  (relay_message.local_interface.name,
                   relay_message.data.decode("utf-8")))

        device.add_user_data_relay_received_callback(relay_data_callback)

        print("Waiting for User Data Relay messages...\n")
        input()

    finally:
        if device is not None and device.is_open():
            device.close()
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():
    print(" +-------------------------------------------------+")
    print(" | XBee Python Library Receive Modem Status Sample |")
    print(" +-------------------------------------------------+\n")

    device = XBeeDevice(PORT, BAUD_RATE)

    try:
        device.open()

        def modem_status_receive_callback(modem_status):
            print("Modem Status event received: %s: %s" % (utils.hex_to_string(utils.int_to_bytes(modem_status.code,
                                                                                                  1)),
                                                           modem_status.description))

        device.add_modem_status_received_callback(modem_status_receive_callback)

        print("Waiting for Modem Status events...\n")
        input()

    finally:
        if device is not None and device.is_open():
            device.close()
Beispiel #7
0
def main():
    print(" +--------------------------------------------------+")
    print(" | XBee Python Library Send MicroPython Data Sample |")
    print(" +--------------------------------------------------+\n")

    device = XBeeDevice(PORT, BAUD_RATE)

    try:
        device.open()

        for i in range(10):
            data = DATA_ON if i % 2 == 0 else DATA_OFF

            print("Sending data to MicroPython interface >> '%s'... " % data, end="")

            device.send_micropython_data(data.encode("utf-8"))

            print("Success")

            time.sleep(1)
    finally:
        if device is not None and device.is_open():
            device.close()
Beispiel #8
0
def main():
    print(" +-----------------------------------------+")
    print(" | XBee Python Library Receive Data Sample |")
    print(" +-----------------------------------------+\n")

    device = XBeeDevice(PORT, BAUD_RATE)

    try:
        device.open()

        def data_receive_callback(xbee_message):
            print("From %s >> %s" %
                  (xbee_message.remote_device.get_64bit_addr(),
                   xbee_message.data.decode()))

        device.add_data_received_callback(data_receive_callback)

        print("Waiting for data...\n")
        input()

    finally:
        if device is not None and device.is_open():
            device.close()
Beispiel #9
0
def read_xbee_data():
    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
                message = xbee_message.data.decode()
                print("Received Message: ", message)

                ##If the receive message is an instruction
                ##Send the instruction to the server.
                check_instruction(message)

                #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()
class SerialConnection(Connection):
    def __init__(self, comPort: str, baudRate: int):
        self.device = XBeeDevice(comPort, baudRate)
        self.device.set_sync_ops_timeout(5)  # 5 seconds
        self.device.open()
        self.device.add_data_received_callback(self._newData)

        self.callback = None

    def _newData(self, xbee_message):
        if self.callback:
            message = ConnectionMessage(device_address=str(
                xbee_message.remote_device.get_64bit_addr()),
                                        connection=self,
                                        data=xbee_message.data)

            self.callback(message)

    def registerCallback(self, fn):
        self.callback = fn

    def send(self, device_address, data):
        remote_device = RemoteXBeeDevice(
            self.device, XBee64BitAddress.from_hex_string(device_address))
        self.device.send_data(remote_device, bytes)

    def broadcast(self, data):
        self.device.send_data_broadcast(bytes)

    def shutdown(self):
        self.device.close()

    def isIntBigEndian(self):
        return True

    def isFloatBigEndian(self):
        return False
Beispiel #11
0
def main():
    CLOSED = False
    # Setting up Xbee communication
    local_xbee = XBeeDevice("/dev/tty.usbserial-DN02Z6QY", 9600)
    local_xbee.open()
    local_xbee.add_data_received_callback(data_received_callback)

    boat_xbee = discover_boat(local_xbee)
    if boat_xbee == None:
        print('device not found!')
        local_xbee.close()
        return
    else:
        print('device found! Sending start messages')
        msg = "START!"
        local_xbee.send_data_async(boat_xbee, msg.encode())

    x = 0
    y = 0
    while True:
        try:
            # print("?")
            x += 10
            y += 10
            new_msg = "!WP, %d, %d" % (x, y)
            origin_msg = "!ORIGIN, 33.119211, 118.229211"
            local_xbee.send_data_async(boat_xbee, origin_msg.encode())
            time.sleep(0.5)
            continue
        except KeyboardInterrupt:
            local_xbee.del_data_received_callback(data_received_callback)
            end_msg = "!STOP".encode()
            local_xbee.send_data_async(boat_xbee, end_msg)
            break

    # Terminating the data aquisition
    local_xbee.close()
Beispiel #12
0
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()
Beispiel #13
0
def main():
    print(" +----------------------------------------------+")
    print(" | XBee Python Library Format Filesystem Sample |")
    print(" +----------------------------------------------+\n")

    local_xbee = XBeeDevice(PORT, BAUD_RATE)
    fs_xbee = local_xbee

    try:
        local_xbee.open()

        if REMOTE_NODE_ID:
            # Obtain the remote XBee from the network.
            xbee_network = local_xbee.get_network()
            fs_xbee = xbee_network.discover_device(REMOTE_NODE_ID)
            if not fs_xbee:
                print("Could not find remote device '%s'" % REMOTE_NODE_ID)
                exit(1)

        filesystem_manager = fs_xbee.get_file_manager()

        get_volume_info(filesystem_manager)

        print("\nFormatting filesystem of '%s' XBee..." %
              (fs_xbee if fs_xbee.is_remote() else "local"),
              end=" ")
        info = filesystem_manager.format()
        print("OK\n")

        print_fs_info(fs_xbee, info)

    except (XBeeException, FileSystemException) as e:
        print("ERROR: %s" % str(e))
        exit(1)
    finally:
        if local_xbee and local_xbee.is_open():
            local_xbee.close()
def main():

    print(" +----------------------------------+")
    print(" | Get and Set API Output Mode Test |")
    print(" +----------------------------------+\n")

    device = XBeeDevice(PORT, BAUD_RATE)

    try:
        device.open()

        for api_output_mode in [
                APIOutputMode.EXPLICIT, APIOutputMode.EXPLICIT_ZDO_PASSTHRU,
                APIOutputMode.NATIVE
        ]:
            device.set_api_output_mode(api_output_mode)
            ao_mode = device.get_api_output_mode()
            assert (ao_mode == api_output_mode)

        print("Test finished successfully")

    finally:
        if device is not None and device.is_open():
            device.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():
    print(" +--------------------------------------------------+")
    print(" | XBee Python Library Local Firmware Update Sample |")
    print(" +--------------------------------------------------+\n")

    device = XBeeDevice(PORT, BAUD_RATE)

    try:
        device.open()
        print("Starting firmware update process...")
        device.update_firmware(
            XML_FIRMWARE_FILE,
            xbee_firmware_file=XBEE_FIRMWARE_FILE,
            bootloader_firmware_file=BOOTLOADER_FIRMWARE_FILE,
            progress_callback=progress_callback,
        )
        print("Firmware updated successfully!")
    except (XBeeException, FirmwareUpdateException,
            OperationNotSupportedException) as e:
        print("ERROR: %s" % str(e))
        exit(1)
    finally:
        if device is not None and device.is_open():
            device.close()
Beispiel #17
0
def main():
    print(" | MyoCarta V1.0 07/18/18 |")
    print("S1: Configuring local receiver")

    local_device = XBeeDevice(PORT, BAUD_RATE)
    local_device.open()

    print("S1: SUCCESS")
    print("S2: Initiating all wireless sensor connections")
    xbee_network = local_device.get_network()

    remote_device = None
    while (remote_device == None):
        remote_device = xbee_network.discover_device(REMOTE_NODE_ID)
    print("S2: SUCCESS")

    remote_device.set_io_configuration(IOLINE_IN, IOMode.ADC)

    while True:
        value = remote_device.get_adc_value(IOLINE_IN)
        print(value)
        time.sleep(0.2)

    local_device.close()
Beispiel #18
0
def main():
    print(" +------------------------+")
    print(" | XBee Send Data From Pi |")
    print(" +------------------------+\n")

    device = XBeeDevice(PORT, BAUD_RATE)

    try:
        device.open()
        i = 0

        CoordFile = open("coords.txt")

        for line in CoordFile:
            i = i + 1
            DATA_TO_SEND = line
            device.send_data_broadcast(DATA_TO_SEND)
            print("Success on line: ", i, "Containing: ", DATA_TO_SEND)

        CoordFile.close()

    finally:
        if device is not None and device.is_open():
            device.close()
Beispiel #19
0
def main():
    print(" +-----------------------------------------+")
    print(" | XBee Python Library Send Data Sample |")
    print(" +-----------------------------------------+\n")

    device = XBeeDevice(PORT, BAUD_RATE)

    try:
        device.open()
        inputfile = 'data2.csv'
        with open(inputfile, mode='r') as csv_file:
            csv_reader = csv.DictReader(csv_file)
            firstLine=next(csv_reader)
            head = [row for row in firstLine]
            line_count = 1
            for row in csv_reader:
                line_count+=1
                send = "({0},{1},{2},{3},{4},{5},{6},{7},{8},{9})".format(row[head[0]],row[head[1]],row[head[2]],row[head[3]],row[head[4]],row[head[5]],row[head[6]],row[head[7]],row[head[8]],row[head[9]])
                device.send_data_broadcast(send)
                #print(line_count, end=",", flush=True)
    finally:
        if device is not None and device.is_open():
            device.close()
            print ("Sent {} lines".format(line_count))
Beispiel #20
0
def main():
    print(" +-------------+")
    print(" | Calculating |")
    print(" +-------------+\n")

    device = XBeeDevice(PORT, BAUD_RATE)
    device1 = XBeeDevice(PORT1, BAUD_RATE)
    device2 = XBeeDevice(PORT2, BAUD_RATE)

    try:
        device.open()
        device1.open()
        device2.open()
        with open('web/data.csv', 'w') as csv_file:
            csv_writer = csv.DictWriter(csv_file, fieldnames=fieldnames)
            csv_writer.writeheader()

        # Obtain the remote XBee device from the XBee network.
        xbee_network = device.get_network()
        xbee_network1 = device1.get_network()
        xbee_network2 = device2.get_network()
        remote_device = xbee_network.discover_device(REMOTE_NODE_ID)
        remote_device1 = xbee_network1.discover_device(REMOTE_NODE_ID)
        remote_device2 = xbee_network2.discover_device(REMOTE_NODE_ID)
        if remote_device and remote_device1 and remote_device2 is None:
            print("Could not find the remote device")
            exit(1)
        while True:
            # Calculating the rssi of each node from DB rigester in the XBee module .
            device.send_data(remote_device, 'a')
            device1.send_data(remote_device1, 'c')
            device2.send_data(remote_device2, 'b')
            rssi = device.get_parameter("DB")
            rssi1 = device1.get_parameter("DB")
            rssi2 = device2.get_parameter("DB")
            res = int.from_bytes(rssi, byteorder='big')
            res1 = int.from_bytes(rssi1, byteorder='big')
            res2 = int.from_bytes(rssi2, byteorder='big')

            R1 = (f"-{res}dbm")
            R2 = (f"-{res1}dbm")
            R3 = (f"-{res2}dbm")
            with open('web/data.csv', 'a') as outfile:
                csv_writer = csv.DictWriter(outfile, fieldnames=fieldnames)

                info = {"R1": res, "R2": res1, "R3": res2}

                csv_writer.writerow(info)
            print([R1, R2, R3])
            time.sleep(1)

    finally:
        if device and device1 and device2 is not None and device.is_open(
        ) and device1.is_open() and device2.is_open():
            device.close() and device1.close() and device2.close()
Beispiel #21
0
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()
Beispiel #22
0
class Simple_controller():
    def __init__(self):
        self.xbee_port = "/dev/tty.usbserial-DN02Z6QY"
        self.local_xbee = XBeeDevice(self.xbee_port, 9600)
        self.local_xbee.open()
        self.local_xbee.serial_port.reset_input_buffer()
        self.boat_xbee = []

        self.hem_lat = 'N/A'
        self.hem_long = 'N/A'
        self.adcp_lat = 'N/A'
        self.velocity = 'N/A'
        self.depth = 'N/A'
        self.roll = 'N/A'
        self.pitch = 'N/A'
        self.yaw = 'N/A'
        self.adcp_lat = 'N/A'
        self.adcp_long = 'N/A'

        self.last_gps_received = datetime.datetime.now()
        self.last_adcp_received = datetime.datetime.now()

    '''
	Discover the boat xbee
	Modify: self.boat_xbee
	'''

    def discover_boat(self):
        print('Discovering device')
        xbee_network = self.local_xbee.get_network()
        xbee_network.start_discovery_process()
        while xbee_network.is_discovery_running():
            time.sleep(0.5)
        self.boat_xbee = xbee_network.discover_device('boat')

    '''
	Call back function whenever a message arrived. Sort out GPS
	and ADCP information

	Input:
		xbee_message: messages from the other xbee
	'''

    def data_received_callback(self, xbee_message):
        data = xbee_message.data.decode()
        parsed_data = data.split(',')

        if parsed_data[0] == '$GPGGA':
            self.last_gps_received = datetime.datetime.now()
            print('Received GPS: ', data)
        elif parsed_data[0] == '$ADCP':
            self.adcp_gps_received = datetime.datetime.now()
            print('Received ADCP: ', data)

    ''' 
	Initialize connection between boat and controller
	'''

    def start_connection(self):
        # setting up xbee communication
        self.local_xbee.add_data_received_callback(self.data_received_callback)
        self.discover_boat()

        if self.boat_xbee == None:
            print('device not found!')
            return False
        else:
            print('device found! Sending start messages')

        # sending start command to the boat
        start_msg = "START".encode()
        self.local_xbee.send_data_async(self.boat_xbee, start_msg)

        return True

    '''
	End connection between boat and controller
	'''

    def end_connection():
        end_msg = "STOP".encode()
        self.local_xbee.send_data_async(self.boat_xbee, end_msg)
        self.local_xbee.close()
Beispiel #23
0
def run():
    global device
    #dev_logger = utils.enable_logger("digi.xbee.devices", logging.DEBUG)
    dev_logger = utils.disable_logger("digi.xbee.devices")
###################################################################################################
#    Look for XBee USB port, to avoid conflicts with other USB devices
###################################################################################################
    rospy.init_node('fleetCoordinator', anonymous=True)

    rospy.loginfo("Looking for XBee...")

    context = pyudev.Context()
    usbPort = 'No XBee found'

    for device in context.list_devices(subsystem='tty'):
        if 'ID_VENDOR' in device and device['ID_VENDOR'] == 'FTDI':
            usbPort = device['DEVNAME']

    device = XBeeDevice(usbPort, 57600)
    #device = XBeeDevice("/dev/ttyUSB0", 57600)
    device.open()
    print("Current timeout: %d seconds" % device.get_sync_ops_timeout())
    device.set_sync_ops_timeout(0.1)

###################################################################################################
#    Get local XBee ID (should be 0, convention for Coordinator)
###################################################################################################
    ID = utils.bytes_to_int(device.get_16bit_addr().address)

    if ID == 0:
        rospy.loginfo("\nHello,\nI am Coordinator " + str(ID)+'\n')
    else:
        raise Exception("This XBee device is not the coordinator of the network,\nlook for the XBee device stamped with 'C'.")


###################################################################################################
#    Initialisation
###################################################################################################
    #Variables storing the data received by the subscribers
    global remote_devices, pubGps, pubEuler, pubLB, pubLE, lastDataStr, lastData
    remote_devices = {}
    lastDataStr = {}
    lastData = {}
    pubGps = []
    pubEuler = []
    pubLB = []
    pubLE = []

    xnet = device.get_network()
    xnet.add_device_discovered_callback(network_callback)
    xnet.add_discovery_process_finished_callback(network_finished)
    device.add_data_received_callback(data_received)

    rate = rospy.Rate(10)

    GPSdata = GPSFix()
    eulerAnglesData = Vector3()
    lineStartData, lineEndData = Pose2D(), Pose2D()

    global chosen, mode, cmd
    mode = 0
    chosen = 0
    cmd = Twist()

    pygame.init()
    screen = pygame.display.set_mode( (640,480) )
    pygame.display.set_caption('Python numbers')


###################################################################################################
# Transmission Loop
###################################################################################################

    while not rospy.is_shutdown():
        if(xnet.is_discovery_running() is False):
            xnet.start_discovery_process()

        display(screen)

        send_command()

        rate.sleep()

    if(xnet.is_discovery_running()):
        xnet.stop_discovery_process()
    device.close()
Beispiel #24
0
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)
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()
        if (io_sample.get_digital_value(x) == IOValue.HIGH):
            IOData[faultMap[x]] = 'true'
            any_fault = 'true'
        else:
            IOData[faultMap[x]] = 'false'
    IOData['any_fault'] = any_fault
    print('IOData: ', IOData)
    #finally, put everything together and publish the data to thingsboard
    turbineName = addr2name[str(remote_xbee.get_64bit_addr(
    ))]  #find the name of the turbine that sent this message
    print(turbineName)
    message = {turbineName: IOData}
    print(message)
    MQTT.publish(topicAttr, json.dumps(message), qos=1, retain=True)


xbee = XBeeDevice(localXBeePort, 9600)
xbee.open()

try:
    xbee.add_data_received_callback(
        data_receive_callback
    )  # Subscribe to data message reception (for power pulse count data).
    xbee.add_io_sample_received_callback(
        io_sample_callback)  # Subscribe to IO samples reception.
    print("Waiting for data...\n")
    input()
finally:
    if xbee is not None and xbee.is_open():
        xbee.close()
Beispiel #27
0
from digi.xbee.devices import XBeeDevice
import sys
import time

# Generate timestamp:
ts = time.gmtime()
ts_string = time.strftime("%Y-%m-%d %H:%M:%S", ts)
'''
Gather data from sys.argv:
    [1]: Lattitude
    [2]: Longitude
    [3]: Azimuth
    
Outgoing json format:
    "{msg_type: 'vor', time: '2019-02-21 00:30:22', lat: float, long: float, azimuth: float}"
'''
lat = sys.argv[1]
long = sys.argv[2]
azimuth = sys.argv[3]
send_string = "{msg_type: 'vor', time: '" + ts_string + \
              "', lat: " + lat + \
              ", long: " + long + \
              ", azimuth: " + azimuth + "}"

device = XBeeDevice("/dev/ttyUSB0", 9600)
device.open()
device.send_data_broadcast(send_string)
device.close()
Beispiel #28
0
class ConnectZigBee:
    def __init__(self, port="/dev/ttyUSB0", baud_rate=9600):
        self.PORT = port
        self.BAUD_RATE = baud_rate
        self.timeout = 0.5
        self.connect()

        self.log = NcapManagerLog()

    def connect(self):
        try:
            self.device = XBeeDevice(self.PORT, self.BAUD_RATE)
            self.log.conn(self.device)
        except Exception:
            self.log.error(self.device)

    def dicovery_node(self, callback):

        try:
            self.device.open()
            xbee_network = self.device.get_network()
            xbee_network.set_discovery_timeout(15)  # 15 seconds.
            xbee_network.clear()
            xbee_network.add_device_discovered_callback(callback)
            xbee_network.start_discovery_process()
            #aplicar um servidor de logs locais print("Discovering remote XBee d
            # ou talvez registar os logs no callback
            while xbee_network.is_discovery_running():
                time.sleep(0.1)

        finally:
            if self.device is not None and self.device.is_open():
                self.device.close()

    def command_env_rec(self, command, mac, device):

        try:
            #talvez aqui aplicar threads
            xbee64 = XBee64BitAddress
            remote = RemoteXBeeDevice(device, xbee64.form_hex_string(mac))
            device.send_data(remote, command)
            time_s = time.time()

            while (xbee_message is None) and time.time() < time_s + timeout:
                xbee_msg = device.read_data()

                if (xbee_message is not None):
                    return xbee_msg.data.decode()

                else:
                    log = (xbee_msg.remote_device.get_64bit_addr(), )
                    error_code
        except:
            error

    def send_command(self, command, mac):

        #talvez aqui tenhamos um probelmas a de se conferires
        #talvez criarmos um método para verificar se o zigbee esta alive
        #self.device = ZigBeeDevice(self.PORT, self.BAUD_RATE)

        try:
            self.device.open()
            response = self.command_env_rec(mac, command, device)
            #Aqui espera-se um retorno para o padrão IEEE 1451
            #Aqui também aplicar logs para registar eventos do servidor
            if response:
                return response
            else:
                return 'Error Code Message format'

        finally:
            if self.device is not None and self.device.is_open():
                self.device.close()
Beispiel #29
0
def main():

    xbee_remote_devices = {}

    device = XBeeDevice(PORT, BAUD_RATE)

    def load_remote_device_info():
        xbee_network = device.get_network()
        xbee_network.start_discovery_process()

        while xbee_network.is_discovery_running():
            sleep(0.5)

        xbee_devices = xbee_network.get_devices()

        for remote_device in xbee_devices:
            try:
                remote_device.read_device_info()
            except:
                continue

            xbee_remote_devices[str(remote_device.get_16bit_addr())] = {
                "node_id": remote_device.get_node_id()
            }

    def data_receive_callback(xbee_message):

        time_zone = datetime.now(timezone.utc).astimezone().tzinfo
        timestamp = datetime.fromtimestamp(xbee_message.timestamp,
                                           tz=time_zone).isoformat()

        addr = xbee_message.remote_device.get_16bit_addr()

        node_id = xbee_remote_devices[str(addr)]["node_id"]

        data = {
            "timestamp": timestamp,
            "device": {
                "node_id": node_id,
                "16bit_addr": utils.hex_to_string(addr.address)
            }
        }

        if xbee_message.data[0]:
            data["error"] = {
                "id": xbee_message.data[1],
                "message": DHT_ERROR_CODES[xbee_message.data[1]]
            }
        else:
            data["observations"] = {
                "temperature": xbee_message.data[2],
                "humidity": xbee_message.data[3]
            }

        print(json.dumps(data))

    try:
        device.open()

        load_remote_device_info()

        device.add_data_received_callback(data_receive_callback)

        print(f"Node {device.get_node_id()} is waiting for data...\n")
        input()

    finally:
        if device is not None and device.is_open():
            print("Closing device")
            device.close()
Beispiel #30
0
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
Beispiel #31
0
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')