def main():
    print(" +-----------------------------------------------+")
    print(" | XBee Python Library Send Explicit Data Sample |")
    print(" +-----------------------------------------------+\n")

    device = ZigBeeDevice(PORT, BAUD_RATE)

    try:
        device.open()

        # Obtain the remote XBee local_xbee 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 local_xbee")
            exit(1)

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

        device.send_expl_data(remote_device, DATA_TO_SEND, SOURCE_ENDPOINT,
                              DESTINATION_ENDPOINT, CLUSTER_ID, PROFILE_ID)

        print("Success")

    finally:
        if device is not None and device.is_open():
            device.close()
Exemple #2
0
class xbee_write():
    def __init__(self):
        rospy.init_node("xbee_write")
        PORT = rospy.get_param("~device", "/dev/ttyUSB0")
        BAUD_RATE = rospy.get_param("~baud", 115200)
        REMOTE_NODE_ID = rospy.get_param("~destination", "REMOTE")
        self.device = ZigBeeDevice(PORT, BAUD_RATE)
        self.SOURCE_ENDPOINT = 0xA0
        self.DESTINATION_ENDPOINT = 0xA1
        self.CLUSTER_ID = 0x1554
        self.PROFILE_ID = 0x1234
        try:
            self.device.open()
            xbee_network = self.device.get_network()
            self.remote_device = xbee_network.discover_device(REMOTE_NODE_ID)
            if self.remote_device is None:
                rospy.logerr("Could not find the remote local_xbee: {}".format(
                    REMOTE_NODE_ID))
                self.device.close()
            self.run()
        except Exception as exc:
            rospy.logerr(exc)

    def run(self):
        formatspec = 'cc?'
        while not rospy.is_shutdown():
            try:
                cmd = raw_input(
                    "Input commands, press Ctrl+D (linux) or Ctrl+Z+return (Windows) to exit, press h for list of commands:"
                )
                if cmd == 'h':
                    print(
                        "st[X]: start mission X=1, stop mission X=0\nrt[X]: Return home X=1, Resume Mission X=0"
                    )
                    continue
                if len(cmd) == 3:
                    cmd = (cmd[0], cmd[1], str2bool(cmd[2]))
                data = struct.pack(formatspec, *cmd)
                rospy.loginfo("Sending explicit data to {} >> {}".format(
                    self.remote_device.get_64bit_addr(), data))
                self.device.send_expl_data(self.remote_device, data,
                                           self.SOURCE_ENDPOINT,
                                           self.DESTINATION_ENDPOINT,
                                           self.CLUSTER_ID, self.PROFILE_ID)
            except EOFError:
                rospy.loginfo("Exiting")
                rospy.signal_shutdown("User Exit")
            except struct.error:
                rospy.logerr(
                    "Bad command, must contain 2 characters and a binary")
        self.device.close()
Exemple #3
0
def ask_all_sensors(remote_devices_id, status, url, filename, lock):
    lock.acquire()
    local_xbee = ZigBeeDevice(PORT, BAUD_RATE)

    message = {'act': 1}
    data_string = json.dumps(message)

    measures = defaultdict(list)

    try:
        local_xbee.open()
        xbee_network = local_xbee.get_network()

        for xbee_id in remote_devices_id:
            remote_xbee = xbee_network.discover_device(xbee_id)

            if remote_xbee is None:
                print('No se ha podido encontrar el dispositivo remoto')
                continue

            print('Enviando datos asincronamente %s >> %s' %
                  (remote_xbee.get_64bit_addr(), data_string))
            local_xbee.send_data(remote_xbee, data_string)

            xbee_message = local_xbee.read_data(3)
            measure = xbee_message.data.decode()

            print('Received message from %s: %s' %
                  (xbee_message.remote_device.get_64bit_addr(), measure))

            json_measure = json.loads(measure)

            json_measure['timestamp'] = str(datetime.utcnow())

            measures[xbee_id].append(json_measure)

        #if connected sends the file, if not, keeps it
        write_to_file(filename, status, measures, url)

    finally:
        if local_xbee is not None and local_xbee.is_open():
            local_xbee.close()
        lock.release()
Exemple #4
0
def discover_network(remote_devices_id, lock):
    lock.acquire()
    local_xbee = ZigBeeDevice(PORT, BAUD_RATE)

    try:
        local_xbee.open()
        xbee_network = local_xbee.get_network()

        # discovering the xbee network
        xbee_network.start_discovery_process()
        while xbee_network.is_discovery_running():
            time.sleep(0.5)

        remote_devices = xbee_network.get_devices()

        for xbee in remote_devices:
            remote_devices_id.add(xbee.get_node_id())

    finally:
        if local_xbee is not None and local_xbee.is_open():
            local_xbee.close()
        lock.release()
Exemple #5
0
def ask_sensor(data, message_callback, lock):
    message = data['message']
    data_string = json.dumps(message)
    REMOTE_NODE_ID = data['sensor']

    lock.acquire()
    local_xbee = ZigBeeDevice(PORT, BAUD_RATE)

    try:
        local_xbee.open()
        xbee_network = local_xbee.get_network()
        remote_xbee = xbee_network.discover_device(REMOTE_NODE_ID)

        if remote_xbee is None:
            print('No se ha podido encontrar el dispositivo remoto')
            exit(1)

        print('Enviando datos asincronamente %s >> %s' %
              (remote_xbee.get_64bit_addr(), data_string))

        local_xbee.send_data(remote_xbee, data_string)

        xbee_message = local_xbee.read_data(3)

        print('Received message from %s: %s' %
              (xbee_message.remote_device.get_64bit_addr(),
               xbee_message.data.decode()))

        sensor_data = {
            'sender': 'section 2',
            'receiver': data['sender'],
            'message': json.loads(xbee_message.data.decode())
        }
        message_callback(sensor_data)

    finally:
        if local_xbee is not None and local_xbee.is_open():
            local_xbee.close()
        lock.release()
def main():
    ser = serial.Serial('/dev/ttyAMA0', 9600)
    port = '/dev/ttyAMA0'
    baud = 9600
    print('Port Opened')
    data = 'Hello'
    remote_node_id = bytearray.fromhex('00 21 2E FF FF 02 45 01')

    #zigbee = ZigBee(ser)
    zigbee = ZigBeeDevice(port, baud)

    zigbee.open()
    print('Device open')
    zigbee_net = zigbee.get_network()
    #remote = zigbee_net.discover_device(remote_node_id)

    print('Network open...sending data')
    while True:
        #zigbee.send('at', frame_id='A', command='DH')
        #zigbee.write('1')
        zigbee.send_data(remote_node_id, data)
        print('...')
    response = zigbee.wait_read_frame()
    print(response)
Exemple #7
0
Driving_Time = 50

Kp = 1
Ki = 0.5
Kd = 0

servo.ChangeDutyCycle(standard)
servo.ChangeDutyCycle(0)
dc.ChangeDutyCycle(0)

data_set = open("Data_PID.txt", 'a')

try:
    device.open()

    xbee_network = device.get_network()
    remote_device = xbee_network.discover_device(REMOTE_NODE_ID)
    xbee_network.set_discovery_timeout(10)
    xbee_network.clear()
    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)

    if remote_device is None:
        print("Could not find the remote device")
Exemple #8
0
def main(argv):

    if len(argv) != 3:
        print("Usage: long_test.py <port> <baud_rate> <duration_in_seconds>")
        return

    print(" +-------------------------------+")
    print(" | Long duration and stress test |")
    print(" +-------------------------------+\n")

    port = argv[0]
    baud_rate = int(argv[1])
    duration = int(argv[2])

    device = ZigBeeDevice(port, baud_rate)

    try:
        device.open()

        # Discover the network.
        network = device.get_network()
        network.start_discovery_process()

        print("Discovering network...")

        # Wait until the discovery process has finished.
        while network.is_discovery_running():
            time.sleep(0.1)

        if not network.has_devices():
            print("No remote modules in the network")
            return

        # Get the first device of the network that is not an end device.
        remote = None
        for dev in network.get_devices():
            if utils.bytes_to_int(dev.get_parameter("SM")) == 0:
                remote = dev
                break

        if remote is None:
            print("No routers in the network")
            return

        print("Selected remote device: %s" % remote)

        # Add a data received callback.
        def data_callback(message):
            if message.remote_device.get_64bit_addr() == remote.get_64bit_addr(
            ):
                print("%s - [C] - %s" %
                      (datetime.datetime.now(), message.data.decode()))
                # Ensure that the sent and received messages are equal.
                assert (data == message.data.decode())

        device.add_data_received_callback(data_callback)

        print("Sending data...\n")

        dead_line = time.time() + duration

        while dead_line > time.time():
            retries = MAX_RETRIES
            data_received = False
            while not data_received:
                try:
                    data = ''.join(
                        random.choice(string.ascii_letters)
                        for i in range(random.randint(1, 84)))
                    print("%s - [S] - %s" % (datetime.datetime.now(), data))
                    # Send explicit data to the loopback cluster.
                    device.send_expl_data(remote, data, SOURCE_ENDPOINT,
                                          DEST_ENDPOINT, CLUSTER_ID,
                                          PROFILE_ID)
                    # Read new data from the remote device.
                    msg = device.read_data_from(remote, 10)
                    print("%s - [P] - %s" %
                          (datetime.datetime.now(), msg.data.decode()))
                    data_received = True
                    # Ensure that the sent and received messages are equal.
                    assert (data == msg.data.decode())
                except TimeoutException as ex:
                    retries -= 1
                    if retries == 0:
                        raise ex

                # Wait some time between 1 and 5 seconds.
                time.sleep(random.randint(1, 5))

        print("\nTest finished successfully")

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