示例#1
0
def main():
    print(" +-----------------------------------------------------+")
    print(" | XBee Python Library Send Data Asynchronously Sample |")
    print(" +-----------------------------------------------------+\n")

    device = XBeeDevice(PORT, BAUD_RATE)

    try:
        device.open()

        # Obtain the remote XBee device from the XBee network.
        xbee_network = device.get_network()
        remote_device = xbee_network.discover_device(REMOTE_NODE_ID)
        if remote_device is None:
            print("Could not find the remote device")
            exit(1)

        print("Sending data asynchronously to %s >> %s..." %
              (remote_device.get_64bit_addr(), DATA_TO_SEND))

        device.send_data_async(remote_device, DATA_TO_SEND)

        print("Success")

    finally:
        if device is not None and device.is_open():
            device.close()
def main():
    print(" +---------------------------------------------------+")
    print(" | XBee Python Library Remote Firmware Update Sample |")
    print(" +---------------------------------------------------+\n")

    device = XBeeDevice(PORT, BAUD_RATE)
    try:
        device.open()

        # Obtain the remote XBee device from the XBee network.
        xbee_network = device.get_network()
        remote_device = xbee_network.discover_device(REMOTE_NODE_ID)
        if remote_device is None:
            print("Could not find the remote device")
            exit(1)

        print("Starting firmware update process...")
        remote_device.update_firmware(
            XML_FIRMWARE_FILE,
            xbee_firmware_file=OTA_FIRMWARE_FILE,
            bootloader_firmware_file=OTB_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()
示例#3
0
    def find_coordinator(self, xbee: XBeeDevice):
        """
        Finds the coordinator XBee radio for targeting MAVLink data transmission

        :param xbee: Local XBee device object
        :return: Remote XBee coordinator device object
        """
        # Discover network.  Repeat until GCS has been found.
        network = xbee.get_network()
        network.add_device_discovered_callback(logging.debug)
        network.set_discovery_timeout(5)

        logging.debug('Beginning Coordinator Discovery loop.')
        while True:
            network.start_discovery_process()

            # Block until discovery is finished TODO is blocking required?
            while network.is_discovery_running():
                time.sleep(0.1)

            # Check devices on the network by Node ID
            for device in network.get_devices():
                if device not in self.known_endpoints or device not in self.old_coordinators:
                    check = self.check_coordinator(xbee, device)
                    if check is True:
                        return device
示例#4
0
def main():
    print(" +------------------------------------------------------+")
    print(" | XBee Python Library Apply XBee Profile Remote Sample |")
    print(" +------------------------------------------------------+\n")

    device = XBeeDevice(PORT, BAUD_RATE)
    try:
        device.open()

        # Obtain the remote XBee device from the XBee network.
        xbee_network = device.get_network()
        remote_device = xbee_network.discover_device(REMOTE_NODE_ID)
        if remote_device is None:
            print("Could not find the remote device")
            exit(1)

        print("Updating profile '%s'...\n" % PROFILE_PATH)
        remote_device.apply_profile(PROFILE_PATH,
                                    progress_callback=progress_callback)
        print("\nProfile updated successfully!")
    except Exception as e:
        print(str(e))
        exit(1)
    finally:
        if device.is_open():
            device.close()
示例#5
0
def main():
    print(" +--------------------------------------+")
    print(" |           Sender (Station)           |")
    print(" +--------------------------------------+\n")

    device = XBeeDevice(PORT, BAUD_RATE)
    try:
        device.open()
        # Obtain the remote XBee device from the XBee network.
        xbee_network = device.get_network()
        remote_device = xbee_network.discover_device(REMOTE_NODE_ID)

        commActive = True
        if remote_device is None:
            print("Could not find the remote device")
            exit(1)

        while commActive:
            print(remote_device)
            action = input("action: ")
            device.send_data_async(remote_device, action)
            print("Success")
            if action == "exit":
                commActive = False

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

    device = XBeeDevice(PORT, BAUD_RATE)

    try:
        device.open()
        print("open device")
        
        # Obtain the remote XBee device from the XBee network.
        xbee_network = device.get_network()
        remote_device = xbee_network.discover_device(REMOTE_NODE_ID)
        if remote_device is None:
            print("Could not find the remote device. We will try 5 second")
            time.sleep(5)
            #exit(1)
        numero = 300
        count = 0
        #numero = int(input("Escriba un número positivo: "))
        while (count < numero):
            DATA_TO_SEND = "Fecha: " + dt.datetime.now().strftime('%Y-%m-%d  Hora: %H:%M:%S') + " Temperatura: 24.7 Humedad: 33% Presion 44mb Co2: 674.5" + "\n"
            time.sleep(2)
            count = count + 1
            print("Sending data to %s >> %s..." % (remote_device.get_64bit_addr(), DATA_TO_SEND))
            device.send_data(remote_device, DATA_TO_SEND)
            print("Success")

    finally:
        if device is not None and device.is_open():
            device.close()
示例#7
0
def main():

    print(" +-----------------------+")
    print(" | Discover Network Test |")
    print(" +-----------------------+\n")

    device = XBeeDevice(PORT, BAUD_RATE)

    try:
        device.open()

        network = device.get_network()

        devices_callback = []

        def device_discovered_callback(remote):
            devices_callback.append(remote)

        network.add_device_discovered_callback(device_discovered_callback)

        network.start_discovery_process()

        while network.is_discovery_running():
            time.sleep(0.1)

        assert(devices_callback == network.get_devices())

        print("Test finished successfully")

    finally:
        if device is not None and device.is_open():
            device.close()
示例#8
0
文件: zigbee.py 项目: ayebayley/uctrl
def connect():
    zigbee_device = XBeeDevice('/dev/ttyUSB0', 230400)
    REMOTE_NODE_ID = "Sender"
    zigbee_device.open()
    xbee_network = zigbee_device.get_network()
    remote_device = xbee_network.discover_device(REMOTE_NODE_ID)
    return remote_device, zigbee_device
示例#9
0
def main():

    #Define your xbee device with the defined port and baudrate
    device = XBeeDevice(PORT, BAUD_RATE)

    try:
        #open the xbee device
        device.open()
        #set the io pins on the xbee board itself
        #in this example, we are using the DIO_AD0 pin on the board
        #refrence the datasheet for other availible pins
        device.set_io_configuration(IOLine.DIO0_AD0, IOMode.ADC)
        # Obtain the remote XBee device from the XBee network.
        xbee_network = device.get_network()
        remote_device = xbee_network.discover_device(REMOTE_NODE_ID)
        if remote_device is None:
            print("Could not find the remote device")
            exit(1)

        # a simple while loop to read the adc sample, convert it and send to the main reciever
        while True:
            raw_val = device.get_adc_value(IOLine.DIO0_AD0)
            voltage = ((raw_val / 1024)) * 2.5
            p = ((voltage - .3333) / 1.32000) - 1.00
            string = str(p)
            print(string)
            time.sleep(0.05)
            device.send_data(remote_device, string)

    # close the device if any error occurs
    finally:
        if device is not None and device.is_open():
            device.close()
示例#10
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()
示例#11
0
def main():
    print(" +-------------+")
    print(" | Calculating ..! |")
    print(" +-------------+\n")

    device = XBeeDevice(PORT, BAUD_RATE)

    try:
        device.open()
        # Obtain the remote XBee device from the XBee network.
        xbee_network = device.get_network()
        remote_device = xbee_network.discover_device(REMOTE_NODE_ID)
        if remote_device is None:
            print("Could not find the remote device")
            exit(1)
        while True:
            device.send_data(remote_device, 'a')
            rssi = device.get_parameter("DB")
            r = int.from_bytes(rssi, byteorder='big')
            res = (f"-{r}dbm")
            with open('web/data.csv', 'a') as outfile:
                writer = csv.writer(outfile)
                writer.writerow([res])
            print(res)

            time.sleep(0.2)

    finally:
        if device is not None and device.is_open():
            device.close()
def main():
    print(" +-------------------------------------------+")
    print(" | XBee Python Library List Directory 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()

        path_to_list = PATH_TO_LIST
        if not path_to_list:
            path_to_list = "/flash"
        files = filesystem_manager.list_directory(path_to_list)
        print("Contents of '%s' (%s):\n" %
              (path_to_list, fs_xbee if fs_xbee.is_remote() else "local"))
        for file in files:
            print(file)
    except (XBeeException, FileSystemException) as e:
        print("ERROR: %s" % str(e))
        exit(1)
    finally:
        if local_xbee and local_xbee.is_open():
            local_xbee.close()
示例#13
0
def main():
    print(" +--------------------------------------+")
    print(" | XBee Python Library Send Data Sample |")
    print(" +--------------------------------------+\n")

    device = XBeeDevice(PORT, BAUD_RATE)

    # 这部分可选,传输Timeout
    # Retrieving the configured timeout for synchronous operations.
    print("Current timeout: %d seconds" % device.get_sync_ops_timeout())
    # 默认是4s
    # Configuring the new timeout (in seconds) for synchronous operations.
    device.set_sync_ops_timeout(NEW_TIMEOUT_FOR_SYNC_OPERATIONS)

    try:
        device.open()

        # Obtain the remote XBee device from the XBee network.
        xbee_network = device.get_network()
        remote_device = xbee_network.discover_device(REMOTE_NODE_ID)
        if remote_device is None:
            print("Could not find the remote device")
            exit(1)

        print("Sending data to %s >> %s..." % (remote_device.get_64bit_addr(), DATA_TO_SEND))

        device.send_data(remote_device, DATA_TO_SEND)

        print("Success")

    finally:
        if device is not None and device.is_open():
            device.close()
示例#14
0
def main():

    print(" +---------------------------------+")
    print(" | Add Devices to the Network Test |")
    print(" +---------------------------------+\n")

    device = XBeeDevice(PORT, BAUD_RATE)

    try:
        device.open()

        network = device.get_network()

        # Add "Remote A" device with 64-bit address.
        remote_a = RemoteXBeeDevice(device, x64bit_addr=ADDR_64_REMOTE_A)
        network.add_remote(remote_a)
        assert (len(network.get_devices()) == 1)
        assert (network.get_device_by_64(ADDR_64_REMOTE_A) == remote_a)

        # Add "Remote B" device with 64-bit address.
        remote_b = RemoteXBeeDevice(device, x64bit_addr=ADDR_64_REMOTE_B)
        network.add_remote(remote_b)
        assert (len(network.get_devices()) == 2)
        assert (network.get_device_by_64(ADDR_64_REMOTE_B) == remote_b)

        # Construct again "Remote A" with 16-bit address and add it to the network.
        remote_a = RemoteXBeeDevice(device,
                                    x64bit_addr=ADDR_64_REMOTE_A,
                                    x16bit_addr=ADDR_16_REMOTE_A)
        network.add_remote(remote_a)
        assert (len(network.get_devices()) == 2)
        assert (network.get_device_by_64(ADDR_64_REMOTE_A) == remote_a)
        assert (network.get_device_by_16(ADDR_16_REMOTE_A) == remote_a)

        # Construct again "Remote A" with a different 16-bit address and add it to the network.
        remote_a = RemoteXBeeDevice(device,
                                    x64bit_addr=ADDR_64_REMOTE_A,
                                    x16bit_addr=ADDR_16_REMOTE_A_2)
        network.add_remote(remote_a)
        assert (len(network.get_devices()) == 2)
        assert (network.get_device_by_64(ADDR_64_REMOTE_A) == remote_a)
        assert (network.get_device_by_16(ADDR_16_REMOTE_A) is None)
        assert (network.get_device_by_16(ADDR_16_REMOTE_A_2) == remote_a)

        # Set the node ID to "Remote A" and add it again to the network.
        remote_a = RemoteXBeeDevice(device,
                                    x64bit_addr=ADDR_64_REMOTE_A,
                                    x16bit_addr=ADDR_16_REMOTE_A_2,
                                    node_id=NODE_ID_REMOTE_A)
        network.add_remote(remote_a)
        assert (len(network.get_devices()) == 2)
        assert (network.get_device_by_node_id(NODE_ID_REMOTE_A) == remote_a)

        print("Test finished successfully")

    finally:
        if device is not None and device.is_open():
            device.close()
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
def main():

    print(" +-----------------------------+")
    print(" | Add Remote Device by Reader |")
    print(" +-----------------------------+\n")

    device_a = XBeeDevice(PORT_A, BAUD_RATE_A)
    device_b = XBeeDevice(PORT_B, BAUD_RATE_B)

    try:
        device_a.open()
        device_b.open()

        network = device_a.get_network()

        remote = RemoteXBeeDevice(device_b, device_a.get_64bit_addr())

        # Send a message from B to A.
        device_b.send_data(remote, "Test")

        # Give some time to device A to receive the packet.
        time.sleep(1)

        # Check that B is in the network of A.
        assert (len(network.get_devices()) == 1)
        try:
            assert (network.get_device_by_64(
                device_b.get_64bit_addr()) == device_b)
        except AssertionError:
            assert (network.get_device_by_16(
                device_b.get_16bit_addr()).get_16bit_addr() ==
                    device_b.get_16bit_addr())

        # Send another message from B to A.
        device_b.send_data(remote, "Test")

        # Check that B is not duplicated.
        assert (len(network.get_devices()) == 1)
        try:
            assert (network.get_device_by_64(
                device_b.get_64bit_addr()) == device_b)
        except AssertionError:
            assert (network.get_device_by_16(
                device_b.get_16bit_addr()).get_16bit_addr() ==
                    device_b.get_16bit_addr())

        print("Test finished successfully")

    finally:
        if device_a is not None and device_a.is_open():
            device_a.close()
        if device_b is not None and device_b.is_open():
            device_b.close()
示例#17
0
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()
示例#18
0
def main():
    print(" +-----------------------------------------+")
    print(" |         XBee Sending Data         |")
    print(" +-----------------------------------------+\n")

    device = XBeeDevice(PORT, BAUD_RATE)

    try:
        # Now wake the 6050 up as it starts in sleep mode
        bus.write_byte_data(int(address, base=16), int(power_mgmt_1, base=16),
                            0)
        # Wake up XBee
        device.open()
        # Obtain the remote XBee device from the XBee network.
        xbee_network = device.get_network()
        remote_device = xbee_network.discover_device(REMOTE_NODE_ID)
        if remote_device is None:
            print("Could not find the remote device")
            exit(1)
        while True:
            time.sleep(5)  # pauses your Python program for 5seconds
            gyro_xout = read_word_2c(0x43)  #anuglar velocity in x-axis
            gyro_yout = read_word_2c(0x45)  #angular velocity in y-axis
            gyro_zout = read_word_2c(0x47)  #angular velocity in z-axis

            # Pick DATA_TO_SEND
            x_threshold = int(get_gyroData_from_config_file('x_threshold'))
            y_threshold = int(get_gyroData_from_config_file('y_threshold'))
            z_threshold = int(get_gyroData_from_config_file('z_threshold'))

            if (gyro_xout > x_threshold and gyro_yout > y_threshold
                    and gyro_zout > z_threshold):
                #use config file here to set threshold values through config
                DATA_TO_SEND = "OK"
            else:
                DATA_TO_SEND = "ERROR"

            print("Sending data to %s >> %s..." %
                  (remote_device.get_64bit_addr(), DATA_TO_SEND))

            device.send_data(remote_device, DATA_TO_SEND)

            print("Success")

            time.sleep(5)  # pauses your Python program for 5seconds

    finally:
        if device is not None and device.is_open():
            device.close()
示例#19
0
def main():
    print(" +-----------------------------------------------+")
    print(" | XBee Python Library Get/Set Remote DIO Sample |")
    print(" +-----------------------------------------------+\n")

    stop = False
    th = None

    local_device = XBeeDevice(PORT, BAUD_RATE)

    try:
        local_device.open()

        # Obtain the remote XBee device from the XBee network.
        xbee_network = local_device.get_network()
        remote_device = xbee_network.discover_device(REMOTE_NODE_ID)
        if remote_device is None:
            print("Could not find the remote device")
            exit(1)

        def io_detection_callback():
            while not stop:
                # Read the digital value from the input line.
                io_value = remote_device.get_dio_value(IOLINE_IN)
                print("%s: %s" % (IOLINE_IN, io_value))

                # Set the previous value to the local output line.
                #local_device.set_dio_value(IOLINE_OUT, io_value)
                remote_device.set_dio_value(IOLINE_OUT, io_value)

                time.sleep(0.2)

        th = threading.Thread(target=io_detection_callback)

        remote_device.set_io_configuration(IOLINE_IN, IOMode.DIGITAL_IN)

        local_device.set_io_configuration(IOLINE_OUT, IOMode.DIGITAL_OUT_LOW)

        time.sleep(0.5)
        th.start()

        input()

    finally:
        stop = True
        if th is not None and th.is_alive():
            th.join()
        if local_device is not None and local_device.is_open():
            local_device.close()
def main():

    print(" +--------------------------------+")
    print(" | Discover Specific Devices Test |")
    print(" +--------------------------------+\n")

    device = XBeeDevice(PORT, BAUD_RATE)

    try:
        device.open()

        network = device.get_network()

        # Discover a valid remote device.
        remote = network.discover_device(REMOTE_NODE_ID)
        assert (remote is not None)
        assert (remote.get_node_id() == REMOTE_NODE_ID)

        # Discover an invalid remote device.
        remote = network.discover_device("!inv4lid_1d!")
        assert (remote is None)

        # Discover myself.
        network.set_discovery_options({DiscoveryOptions.DISCOVER_MYSELF})
        if device.get_protocol() == XBeeProtocol.RAW_802_15_4:
            assert (network.get_discovery_options()[0] == 1)
        else:
            assert (network.get_discovery_options()[0] == 2)
        remote = network.discover_device(device.get_node_id())
        assert (remote == device)

        network.clear()

        # Discover the remote device and myself.
        devices_list = network.discover_devices(
            [REMOTE_NODE_ID, device.get_node_id()])
        assert (len(devices_list) == 2)
        assert (network.get_device_by_node_id(device.get_node_id()) == device)

        # Restore the discovery options.
        network.set_discovery_options({})
        assert (network.get_discovery_options()[0] == 0)

        print("Test finished successfully")

    finally:
        if device is not None and device.is_open():
            device.close()
示例#21
0
def main():
    Number = 0
    while 1:
        try:
            Port = "COM" + str(Number)
            device = XBeeDevice(Port, Baud_Rate)
            device.open()

            # Obtain the remote XBee device from the XBee network.
            xbee_network = device.get_network()
            remote_device = xbee_network.discover_device(REMOTE_NODE_ID)
            if remote_device is None:
                print("Could not find the remote device")
                exit(1)
            device.send_data(remote_device, "1/100")
            sleep(1)
            device.send_data(remote_device, "2/100")

            sleep(1)

            device.send_data(remote_device, "1/70")
            sleep(1)
            device.send_data(remote_device, "2/60")

            sleep(1)

            device.send_data(remote_device, "1/50")
            sleep(1)
            device.send_data(remote_device, "2/40")

            sleep(1)

            device.send_data(remote_device, "1/30")
            sleep(1)
            device.send_data(remote_device, "2/20")

            sleep(1)

            device.send_data(remote_device, "1/0")
            sleep(1)
            device.send_data(remote_device, "2/0")
            sleep(7)
        except:
            Number = Number + 1
        finally:
            if device is not None and device.is_open():
                device.close()
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
示例#23
0
def main():
    device = connect()
    initData(device)
    zigbee_device = XBeeDevice('/dev/ttyUSB0', 230400)
    REMOTE_NODE_ID = "Sender"
    zigbee_device.open()
    xbee_network = zigbee_device.get_network()
    remote_device = xbee_network.discover_device(REMOTE_NODE_ID)

    while True:
        values = getData(device)
        if len(values) <= 1:  # only got the currtime
            device = handleTimeout(device)
        else:
            # do something with data (printing for now)
            output = printData(values)
            zigbee_device.send_data(remote_device, output)
示例#24
0
def main():
    print(" +---------------------------------------------+")
    print(" | XBee Python Library Discover Devices Sample |")
    print(" +---------------------------------------------+\n")

    device = XBeeDevice(PORT, BAUD_RATE)

    try:
        device.open()

        xbee_network = device.get_network()

        xbee_network.set_discovery_timeout(15)  # 15 seconds.

        xbee_network.clear()

        # Callback for discovered devices.
        def callback_device_discovered(remote):
            print("Device discovered: %s" % remote)
            print(type(remote))

        # Callback for discovery finished.
        def callback_discovery_finished(status):
            if status == NetworkDiscoveryStatus.SUCCESS:
                print("Discovery process finished successfully.")
            else:
                print("There was an error discovering devices: %s" %
                      status.description)

        xbee_network.add_device_discovered_callback(callback_device_discovered)

        xbee_network.add_discovery_process_finished_callback(
            callback_discovery_finished)

        xbee_network.start_discovery_process()

        print("Discovering remote XBee devices...")

        while xbee_network.is_discovery_running():
            time.sleep(0.1)

    finally:
        if device is not None and device.is_open():
            device.close()
示例#25
0
def main():
    print(" +--------------------------------------------+")
    print(" | XBee Python Library Read Remote ADC Sample |")
    print(" +--------------------------------------------+\n")

    stop = False
    th = None

    local_device = XBeeDevice(PORT, BAUD_RATE)

    try:
        local_device.open()

        # Obtain the remote XBee device from the XBee network.
        xbee_network = local_device.get_network()
        remote_device = xbee_network.discover_device(REMOTE_NODE_ID)
        if remote_device is None:
            print("Could not find the remote device")
            exit(1)

        remote_device.set_io_configuration(IOLINE_IN, IOMode.ADC)

        def read_adc_task():
            while not stop:
                # Read the analog value from the remote input line.
                value = remote_device.get_adc_value(IOLINE_IN)
                value = (value / 1023) * 1200
                print("%s: %d" % (IOLINE_IN, value))

                time.sleep(0.2)

        th = threading.Thread(target=read_adc_task)

        time.sleep(0.5)
        th.start()

        input()

    finally:
        stop = True
        if th is not None and th.isAlive():
            th.join()
        if local_device is not None and local_device.is_open():
            local_device.close()
示例#26
0
def initXBee(port, baud):
    global CONTROLLER_ADDR
    print("Init XBee at {0}, {1:d}".format(port, baud))
    #device = ZigBeeDevice(port, baud)
    device = XBeeDevice(port, baud)
    device.open()
    device.add_modem_status_received_callback(xbee_status_callback)
    device.add_data_received_callback(xbee_received_callback)
    xnet = device.get_network()
    xnet.set_discovery_timeout(5)
    xnet.start_discovery_process()
    while xnet.is_discovery_running():
        time.sleep(0.5)
    controller16Addr = XBee16BitAddress.COORDINATOR_ADDRESS
    remote_device = xnet.get_device_by_16(controller16Addr)
    if remote_device is None:
        print("Could not find the remote device {0}".format(controller16Addr))
    print("init, nodeId= {0}".format(device.get_node_id()))
    return device, remote_device
示例#27
0
def main():
    print(" +-------------------------------------------------+")
    print(" | XBee Python Library Upload/Download File 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()

        xb_upload_path = os.path.join(XBEE_UPLOAD_DIR_PATH,
                                      os.path.basename(FILE_TO_UPLOAD_PATH))
        filesystem_manager.put_file(FILE_TO_UPLOAD_PATH, xb_upload_path,
                                    overwrite=True, progress_cb=progress_upload_callback)

        download_path = os.path.join(LOCAL_DOWNLOAD_DIR_PATH,
                                     os.path.basename(FILE_TO_UPLOAD_PATH))
        filesystem_manager.get_file(xb_upload_path, download_path,
                                    progress_cb=progress_download_callback)

        print("\nFile hash summary\n-----------------------")
        print("%s %s" % ("Local:".ljust(15), get_sha256_hash(FILE_TO_UPLOAD_PATH).upper()))
        print("%s %s" % ("Uploaded:".ljust(15),
                         utils.hex_to_string(filesystem_manager.get_file_hash(xb_upload_path), pretty=False)))
        print("%s %s\n" % ("Downloaded:".ljust(15), get_sha256_hash(download_path).upper()))
    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():
    device = XBeeDevice(PORT, BAUD_RATE)
    try:
        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 the remote device")
            exit(1)
        latitude, longitude = getLocation()
        data = "Latitude: " + str(latitude) + " Longitude: " + str(longitude)
        #modify this
        print("Sending data to %s >> %s..." %
              (remote_device.get_64bit_addr(), data))

        device.send_data(remote_device, data)

    finally:
        if device is not None and device.is_open():
            device.close()
示例#29
0
def main():
    print(" +----------------------------------------------+")
    print(" | XBee Python Library Handle IO Samples Sample |")
    print(" +----------------------------------------------+\n")

    device = XBeeDevice(PORT, BAUD_RATE)

    try:
        device.open()

        # Obtain the remote XBee device from the XBee network.
        xbee_network = device.get_network()
        remote_device = xbee_network.discover_device(REMOTE_NODE_ID)
        if remote_device is None:
            print("Could not find the remote device")
            exit(1)

        # Set the local device as destination address of the remote.
        remote_device.set_dest_address(device.get_64bit_addr())

        remote_device.set_io_configuration(DIGITAL_LINE, IOMode.DIGITAL_IN)
        remote_device.set_io_configuration(ANALOG_LINE, IOMode.ADC)

        # Enable periodic sampling every IO_SAMPLING_RATE seconds in the remote device.
        remote_device.set_io_sampling_rate(IO_SAMPLING_RATE)

        # Enable DIO change detection in the remote device.
        remote_device.set_dio_change_detection({DIGITAL_LINE})

        # Register a listener to handle the samples received by the local device.
        def io_samples_callback(sample, remote, time):
            print("New sample received from %s - %s" %
                  (remote.get_64bit_addr(), sample))

        device.add_io_sample_received_callback(io_samples_callback)

        input()

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

    device = XBeeDevice(PORT, BAUD_RATE)

    try:
        device.open()

        def data_receive_callback(xbee_message):
            print("From {} >> {}".format(
                xbee_message.remote_device.get_64bit_addr(),
                xbee_message.data.decode()))

        device.add_data_received_callback(data_receive_callback)

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

        # Obtain the remote XBee device from the XBee network.
        xbee_network = device.get_network()
        remote_device = xbee_network.discover_device(REMOTE_NODE_ID)
        if remote_device is None:
            print("Could not find the remote device")
            exit(1)

        print("Sending data to {} >> {}...".format(
            remote_device.get_64bit_addr(), DATA_TO_SEND))

        device.send_data(remote_device, DATA_TO_SEND)

        print("Success")

        input("Press any key to quit...\n")

    finally:
        if device is not None and device.is_open():
            device.close()
示例#31
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()