コード例 #1
0
def main():
    print(" +--------------------------------------------------+")
    print(" | XBee Python Library Receive Explicit Data Sample |")
    print(" +--------------------------------------------------+\n")

    device = ZigBeeDevice(PORT, BAUD_RATE)

    try:
        device.open()

        device.set_api_output_mode(APIOutputMode.EXPLICIT)

        def explicit_data_callback(explicit_xbee_message):
            print("From %s >> %s"
                  % (explicit_xbee_message.remote_device.get_64bit_addr(),
                     explicit_xbee_message.data.decode()))
            print(" - Source endpoint:        %s"
                  % utils.hex_to_string(utils.int_to_length(explicit_xbee_message.source_endpoint)))
            print(" - Destination endpoint:   %s"
                  % utils.hex_to_string(utils.int_to_length(explicit_xbee_message.dest_endpoint)))
            print(" - Cluster ID:             %s"
                  % utils.hex_to_string(utils.int_to_length(explicit_xbee_message.cluster_id)))
            print(" - Profile ID:             %s"
                  % utils.hex_to_string(utils.int_to_length(explicit_xbee_message.profile_id)))

        device.flush_queues()
        device.add_expl_data_received_callback(explicit_data_callback)

        print("Waiting for data in explicit format...\n")

        input()

    finally:
        if device is not None and device.is_open():
            device.close()
コード例 #2
0
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()
コード例 #3
0
ファイル: broadcast.py プロジェクト: regisin/erle_rover_nav
def main():
    zigbee = ZigBeeDevice('/dev/ttyUSB0', 9600)

    try:
        zigbee.open()
        data = 'Zigbee node %s sending data' % (zigbee.get_node_id())
        data = data.encode('utf-8')
        rssi_raw = zigbee.get_parameter("DB")
        rssi_val = struct.unpack('=B', rssi_raw)
        print(rssi_val)
        #packet_receive = zigbee.send_data_broadcast(data)
        #data_packet = packets.XBeePacket()
        #packet = data_packet.create_packet(data, OperatingMode.API_MODE)
        #packet_receive = zigbee.send_packet(packet)

        def packet_received_callback(packet):
            packet_dict = packet.to_dict()
            api_data = packet_dict[DictKeys.FRAME_SPEC_DATA][DictKeys.API_DATA]
            print(api_data)
        
        print(packet_receive)
        #zigbee.add_packet_received_callback(packet_received_callback)


    finally:
        if zigbee is not None and zigbee.is_open():
            zigbee.close()
コード例 #4
0
def SendCommand():
    device = ZigBeeDevice(PORT, BAUD_RATE)

    #print(hora_atual[11:19])

    try:

        device.open()
        device.flush_queues()
        cursor.execute("SELECT `MAC` FROM `ESTACAO`")
        resultado = cursor.fetchall()

        #verifica se o MAC já foi inserido no banco de dados
        for linha in resultado:
            res = str(linha)

            res = res[2:18]
            dados = ("\x00\x01\x03\x01\x00\x04")
            leit = SendCommandEnvRec(res, dados, device)
            hora_atual = HoraAtual()
            data_atual = DataAtual()
            print("Tempertura:" + leit)
            if leit != '0':
                cursor.execute(
                    "INSERT INTO `LEITURASENSOR`( `MACROT`, `CODSEN`, `DAT`, `HOR`, `VALO`) VALUES ('"
                    + res + "',1,'" + data_atual + "','" + hora_atual + "','" +
                    leit + "')")
                conexao.commit()
                #time.sleep(1)
            dados = ("\x00\x02\x03\x01\x00\x04")
            leit = SendCommandEnvRec(res, dados, device)
            hora_atual = HoraAtual()
            data_atual = DataAtual()
            if leit != '0':
                leit = "%.3f" % float(leit)
                print("Pressão:" + leit)
                cursor.execute(
                    "INSERT INTO `LEITURASENSOR`( `MACROT`, `CODSEN`, `DAT`, `HOR`, `VALO`) VALUES ('"
                    + res + "',2,'" + data_atual + "','" + hora_atual + "','" +
                    leit + "')")
                conexao.commit()
                #time.sleep(1)
            dados = ("\x00\x03\x03\x01\x00\x04")
            leit = SendCommandEnvRec(res, dados, device)
            print("Umidade:" + leit)
            hora_atual = HoraAtual()
            data_atual = DataAtual()
            if leit != '0':
                cursor.execute(
                    "INSERT INTO `LEITURASENSOR`( `MACROT`, `CODSEN`, `DAT`, `HOR`, `VALO`) VALUES ('"
                    + res + "',3,'" + data_atual + "','" + hora_atual + "','" +
                    leit + "')")
                conexao.commit()
                #time.sleep(1)
            dados = ("\x00\x00\x01\x02\x00\x01\x01")
            leit = SendCommandEnvRec(res, dados, device)

    finally:
        if device is not None and device.is_open():
            device.close()
コード例 #5
0
class XBeeHandler(Thread):
    def __init__(self, inQ, outQ, XBeePort):
        super(XBeeHandler, self).__init__()
        self.daemon = True
        self.name = 'XBH'
        self.inQ = inQ
        self.outQ = outQ

        # Initialize XBee device:
        self.device = ZigBeeDevice(XBeePort, 9600)
        self.device.open()
        self.device.add_data_received_callback(self.receiveCB)

    def run(self):
        while (True):
            msg = self.outQ.get()  # Blocking call
            self.device.send_data(msg.sender, msg.data)
            if DEBUG:
                print('XBH - Sent %s bytes to %s' %
                      (len(msg.data), msg.sender.get_64bit_addr()))

    def receiveCB(self, xbee_message):
        sender = xbee_message.remote_device
        data = xbee_message.data
        msg = MSG(sender, data)
        self.inQ.put(msg)
        if DEBUG:
            print('XBH - Received %s bytes from %s' %
                  (len(msg.data), sender.get_64bit_addr()))

    def terminate(self):
        self.device.close()
        if DEBUG: print('XBH - Closed connection with RF device.')
コード例 #6
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()
コード例 #7
0
ファイル: xbee.py プロジェクト: Borjis131/snail
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()
コード例 #8
0
def main():
    print(" +---------------------------------------------------------+")
    print(" | XBee Python Library Send Broadcast Explicit Data Sample |")
    print(" +---------------------------------------------------------+\n")

    device = ZigBeeDevice(PORT, BAUD_RATE)

    try:
        device.open()

        print("Sending explicit broadcast data: %s..." % DATA_TO_SEND)

        device.send_expl_data_broadcast(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()
コード例 #9
0
ファイル: xbee.py プロジェクト: Borjis131/snail
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()
コード例 #10
0
ファイル: xbee.py プロジェクト: Borjis131/snail
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()
コード例 #11
0
def main():
    print(" +--------------------------------------------------+")
    print(" | XBee Python Library Explicit Data Polling Sample |")
    print(" +--------------------------------------------------+\n")

    device = ZigBeeDevice(PORT, BAUD_RATE)

    try:
        device.open()

        device.set_api_output_mode_value(
            APIOutputModeBit.calculate_api_output_mode_value(
                device.get_protocol(), {APIOutputModeBit.EXPLICIT}))

        device.flush_queues()

        print("Waiting for data in explicit format...\n")

        while True:
            explicit_xbee_message = device.read_expl_data(None)
            if explicit_xbee_message is not None:
                print("From %s >> %s" %
                      (explicit_xbee_message.remote_device.get_64bit_addr(),
                       explicit_xbee_message.data.decode()))
                print(" - Source endpoint:        %s" % utils.hex_to_string(
                    utils.int_to_length(
                        explicit_xbee_message.source_endpoint)))
                print(" - Destination endpoint:   %s" % utils.hex_to_string(
                    utils.int_to_length(explicit_xbee_message.dest_endpoint)))
                print(" - Cluster ID:             %s" % utils.hex_to_string(
                    utils.int_to_length(explicit_xbee_message.cluster_id)))
                print(" - Profile ID:             %s" % utils.hex_to_string(
                    utils.int_to_length(explicit_xbee_message.profile_id)))

    finally:
        if device is not None and device.is_open():
            device.close()
コード例 #12
0
def main():
    global SPACE_CONFIGURATION

    # read  in our space configuration
    with open(os.path.join(ROOT_DIR, 'config', 'garage_a_v2.json')) as f:
        SPACE_CONFIGURATION = json.load(f)

    # create and open a serial connection to the device
    device = ZigBeeDevice(PORT, BAUD_RATE)
    device.open()

    try:
        device.flush_queues()
        print("Waiting for data...\n")

        # add a callback for the io sample
        device.add_io_sample_received_callback(on_io_sample_received)

        while True:
            time.sleep(1)

    finally:
        if device is not None and device.is_open():
            device.close()
コード例 #13
0
            if key == "c":
                t = 1
            elif key == "`":
                target_Speed = 0
            elif key == "1":
                target_Speed = 5
            elif key == "2":
                target_Speed = 10
            elif key == "3":
                target_Speed = 15
            elif key == "4":
                target_Speed = 15.99
            elif key == "a":  #Left
                angle = angle + 0.1
                k = 1
            elif key == "d":  #Right
                angle = angle - 0.1
                k = 1
            elif key == "q":
                angle = standard
                k = 1
            elif key == "s":
                Driving_Time = 0

finally:

    if device is not None and device.is_open():
        print("f**k")
        device.close()
        data_set.close()
コード例 #14
0
ファイル: long_test.py プロジェクト: asamland/xbee-python
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()
コード例 #15
0
#   Read device information (more getters are availiable):
addr_64 = XBee_zig.get_64bit_addr()
node_id = XBee_zig.get_node_id()
pan_id = XBee_zig.get_pan_id()
print('Opened device with addr')
print(addr_64)
print('and node ID')
print(node_id)
print('on PAN ID')
print(pan_id)
print('listening for messages...')

#msg = XBee_zig.read_data(120);

#data = msg.data.decode("utf8")
#print(data)

while (True):
    sleep(10)

#   Reset device:
#XBee_zig.reset()

#   Close serial interface with device:
XBee_zig.close()

print(addr_64)
print('')
print(node_id)
print('')
print(pan_id)
コード例 #16
0
ファイル: xbee_read.py プロジェクト: FletcherFT/asv_framework
class xbee_read():
    def __init__(self):
        rospy.init_node("xbee_read")
        PORT = rospy.get_param("~device", "/dev/ttyUSB1")
        BAUD_RATE = rospy.get_param("~baud", 115200)
        self.joy_msg = Joy()
        self.device = ZigBeeDevice(PORT, BAUD_RATE)
        hz = rospy.Rate(10)
        self.pub = rospy.Publisher("joy", Joy, queue_size=10)
        try:
            self.device.open()
        except Exception as exc:
            rospy.logerr(exc)
            if self.device.is_open:
                self.device.close()
            return
        self.device.flush_queues()
        self.device.set_api_output_mode(APIOutputMode.EXPLICIT)
        rospy.sleep(rospy.Duration.from_sec(2.0))
        rospy.on_shutdown(self.shutdown_handle)
        while not rospy.is_shutdown():
            try:
                data_msg = self.device.read_expl_data()
            except TimeoutException:
                rospy.logerr("Timeout!")
            except InvalidPacketException:
                rospy.logerr("Bad Checksum")
            except XBeeException as exc:
                rospy.logerr("XBee Error!: {}".format(exc))
            else:
                if data_msg:
                    self.handle_data(data_msg)
            hz.sleep()

    def shutdown_handle(self):
        if self.device._is_open:
            self.device.close()

    def handle_data(self, data_msg):
        if len(data_msg.data) == 16:
            formatspec = '>cchhhhh????'
            self.parse_joystick(struct.unpack(formatspec, data_msg.data))
        elif len(data_msg.data) == 3:
            formatspec = 'cc?'
            self.parse_commands(struct.unpack(formatspec, data_msg.data))

    def parse_joystick(self, data):
        rospy.loginfo(data[2:7])
        self.joy_msg.axes = data[2:7]
        self.joy_msg.buttons = data[7:]
        rospy.logdebug(data)
        self.joy_msg.header.stamp = rospy.Time.now()
        self.joy_msg.header.frame_id = "override"
        self.pub.publish(self.joy_msg)

    def parse_commands(self, data):
        cmd = data[0] + data[1]
        if cmd == 'st':
            if data[2]:
                rospy.loginfo("Start Mission Request")
                try:
                    rospy.wait_for_service("supervisor/start", 2.0)
                except:
                    rospy.logerr("No supervisor/start service available.")
                else:
                    service_handle = rospy.ServiceProxy(
                        "supervisor/start", Trigger)
                    response = service_handle()
                    if response.success:
                        rospy.loginfo(
                            "Successful start mission request (xbee)")
                    else:
                        rospy.logerr(response.message)
            else:
                rospy.loginfo("Stop Mission Request")
                try:
                    rospy.wait_for_service("supervisor/pause", 2.0)
                except:
                    rospy.logerr("No supervisor/pause service available.")
                else:
                    service_handle = rospy.ServiceProxy(
                        "supervisor/pause", SetBool)
                    response = service_handle(True)
                    if response.success:
                        rospy.loginfo(
                            "Successful pause mission request (xbee)")
                    else:
                        rospy.logerr(response.message)
        elif cmd == 'rt':
            if data[2]:
                rospy.loginfo("Return Home Request")
            else:
                rospy.loginfo("Resume Mission Request")
                try:
                    rospy.wait_for_service("supervisor/pause", 2.0)
                except:
                    rospy.logerr("No supervisor/pause service available.")
                else:
                    service_handle = rospy.ServiceProxy(
                        "supervisor/pause", SetBool)
                    response = service_handle(False)
                    if response.success:
                        rospy.loginfo(
                            "Successful resume mission request (xbee)")
                    else:
                        rospy.logerr(response.message)
        else:
            rospy.logwarn("Unknown Command: {}".format(cmd))