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()
 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()
Exemple #3
0
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()
Exemple #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()
Exemple #5
0
    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)
Exemple #6
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.')
Exemple #7
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 #8
0
 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)
Exemple #9
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()
Exemple #10
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()
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 #12
0
import serial
import time
from digi.xbee.devices import ZigBeeDevice
from digi.xbee.models.mode import OperatingMode

arduino = ZigBeeDevice('/dev/ttyS6', 9600)
arduino.open()
print('done')
print(arduino.get_64bit_addr())
Exemple #13
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()
Exemple #14
0
from flask import Blueprint
from digi.xbee.devices import ZigBeeDevice
import serial
import time
import json

CONFIG_FILE = 'ucuapi/protocols/zigbee/config.json'
zigbee = Blueprint('zigbee', __name__)

with open(CONFIG_FILE) as json_file:
    config = json.load(json_file)['config'][0]

# need to figure out how to change operating mode of the device

device = ZigBeeDevice(config['devicePort'], config['deviceBaudRate'])


@zigbee.route('/device_info')
def zigbee_device_info():
    return device.read_device_info()


@zigbee.route('/broadcast')
def zigbee_broadcast():
    device.open()
    device.send_data_broadcast("Hello XBee World!")
    device.close()
    return "TEST_BROADCAST_OK"


@zigbee.route('/test')
Exemple #15
0
#   _____ _____ _____
#  |   | |__   |   | | EmbeddedAF/src/master/xbeeTesting.py
#  | | | |   __| | | | Nikolai Nymo
#  |_|___|_____|_|___| 19-04-18
from digi.xbee.devices import ZigBeeDevice
import sys
if sys.version_info[0] < 3: raise "Must be using Python 3"
from time import sleep

#   Instantiate device:
XBee_zig = ZigBeeDevice('/dev/tty.SLAB_USBtoUART', 9600)  # ('port', baud)
XBee_zig.open()  # Opens serial interface to device


# Define callback.
def xbRxCallback(xbee_message):
    address = xbee_message.remote_device.get_64bit_addr()
    data = xbee_message.data.decode("utf8")
    print("Received data from %s: %s" % (address, data))


# Add the callback.
XBee_zig.add_data_received_callback(xbRxCallback)

#   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')
Exemple #16
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()
Exemple #17
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_value(
            APIOutputModeBit.calculate_api_output_mode_value(
                device.get_protocol(), {APIOutputModeBit.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()
Exemple #18
0
from digi.xbee.devices import XBeeDevice
from digi.xbee.devices import ZigBeeDevice
from digi.xbee.devices import RemoteZigBeeDevice
from digi.xbee.devices import XBee64BitAddress
from digi.xbee.models.mode import APIOutputModeBit
from digi.xbee.util import utils

device = ZigBeeDevice("COM11", 9600)

switch_endpoint = 0x11

device_switch_controller_id = 0x0840
switch_cluster_id = {
    "Identify": 0x00,
    "Groups": 0x01,
    "Scenes": 0x02,
    "On/Off": 0x03,
    "Level control": 0x04,
    "Color control": 0x05
}

light_endpoint = 0x11

device_light_id = 0x0000
light_cluster_id = {
    "Identify": 0x00,
    "Groups": 0x01,
    "Scenes": 0x02,
    "On/Off": 0x03
}
light_commands = {"Off": "0x00", "On": "0x01", "Toggle": "0x02"}
Exemple #19
0
    warn_led = LED(warn_led_pin, pin_factory=factory)
    error_led = LED(error_led_pin, pin_factory=factory)
    monitor_led = LED(monitor_led_pin, pin_factory=factory)
else:
    # Test para local
    # Seteamos el pin de datos del servo  un puerto PWM
    servo = Servo(servo_pin)
    # Seteo de los pines
    ok_led = LED(ok_led_pin)
    warn_led = LED(warn_led_pin)
    error_led = LED(error_led_pin)
    monitor_led = LED(monitor_led_pin)
# Configuramos la antena Xbee
# Comando para escanear puertos {dmesg | grep tty}
# se accede a traves de RS232 masterport
xbee = ZigBeeDevice("/dev/ttyAMA0", 9600)
remote_xbee = RemoteZigBeeDevice(
    xbee, XBee64BitAddress.from_hex_string("0013A20041513615"))

print("Empezamos")

for x in range(5):
    ok_led.blink(1, 1, 5)
    warn_led.blink(1, 1, 5)
    error_led.blink(1, 1, 5)
    monitor_led.blink(1, 1, 5)
    print(servo.value)
    servo.min()
    print(servo.value)
    sleep(5)
    servo.mid()
Exemple #20
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 #21
0
    print("Key : %s" % (key))
    print("Received data from %s : %s, %f" % (address, key, target_Speed))


PORT = '/dev/ttyUSB0'
BAUD_RATE = 9600

REMOTE_NODE_ID = "MAIN"

SOURCE_ENDPOINT = 0xE9
DESTINATION_ENDPOINT = 0xE8
CLUSTER_ID = 0xC
PROFILE_ID = 0x3332

device = ZigBeeDevice(PORT, BAUD_RATE)

input = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]
output = [
    0, 2.11, 2.6, 3.11, 3.65, 4.21, 4.75, 5.45, 6.37, 7.4, 8.7, 10.3, 12.4,
    16.5, 22.1, 34.5, 99
]

pin_servo = 18
pin_dc = 12
pin_dir = 26
pin_encA = 23
pin_encB = 24
freq = 50

GPIO.setmode(GPIO.BCM)
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(APIOutputMode.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()
import os

from mavros_msgs.msg import OverrideRCIn, BatteryStatus
from mavros_msgs.srv import SetMode, CommandBool, CommandTOL
#from msg import NodeStatus
from digi.xbee.models.address import XBee64BitAddress
from digi.xbee.devices import ZigBeeDevice
from digi.xbee.packets.base import DictKeys
from digi.xbee.exception import XBeeException, ConnectionException, ATCommandException, InvalidOperatingModeException
from digi.xbee.util import utils
from digi.xbee.io import IOLine, IOMode

system_nodes = {}
rssi_table = []

xbee = ZigBeeDevice("/dev/ttyUSB0", 9600)
power_level = 2
api_mode = 2
hierarchy = 0
node_id = ''
address = ''
received_packet = None
battery = 1
nodes = []
node_rely = None
node_send = None
rssi_rely = 0
current_rssi = 0
data = []
rssi_avg = 0
rssi_hist = []
Exemple #24
0
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))
Exemple #25
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()
        print("from: {}, RSSI: {}, Data: {}".format(addr, rssi, bytes(data).decode()))
    return packet_received_callback


#
# def do_discovery(device):
#     network = device.get_network()
#     network.start_discovery_process()
#
#     while network.is_discovery_running():
#         time.sleep(0.5)
#
#     print("Discovery complete!")
#     devices = network.get_devices()
#     for d in devices:
#         name = d.get_parameter("NI").decode("utf-8")
#         print("Name is: " + name)
#         if name == "jeremy":
#             d.set_parameter("NI", "NEWNAME".encode())
#             d.execute_command("WR")
#             print("renamed!")


if __name__ == "__main__":
    my_device = ZigBeeDevice("COM5", 9600)
    my_device.open()
    set_node_and_pan(my_device, "test_device", "1234")
    my_device.add_packet_received_callback(generate_packet_callback(my_device))

    print("At startup, last received packet strength: -" + str(ord(my_device.get_parameter("DB"))) + "dB")