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()
def main():
    print(" +-----------------------------------------------------+")
    print(" | XBee Python Library Manage Common parameters Sample |")
    print(" +-----------------------------------------------------+\n")

    device = XBeeDevice(PORT, BAUD_RATE)

    try:
        device.open()

        print("Cached parameters\n" + "-" * 50)
        print("64-bit address:   %s" % device.get_64bit_addr())
        print("16-bit address:   %s" % device.get_16bit_addr())
        print("Node Identifier:  %s" % device.get_node_id())
        print("Firmware version: %s" %
              utils.hex_to_string(device.get_firmware_version()))
        print("Hardware version: %s" %
              device.get_hardware_version().description)

        print("")

        # Configure and read non-cached parameters.
        device.set_pan_id(PARAM_VALUE_PAN_ID)
        device.set_dest_address(PARAM_DESTINATION_ADDR)
        device.set_power_level(PARAM_POWER_LEVEL)

        print("Non-Cached parameters\n" + "-" * 50)
        print("PAN ID:           %s" %
              utils.hex_to_string(device.get_pan_id()))
        print("Dest address:     %s" % device.get_dest_address())
        print("Power level:      %s" % device.get_power_level().description)

    finally:
        if device is not None and device.is_open():
            device.close()
Exemplo n.º 3
0
class ModuleSingleton:
    def __init__(self):
        self.device = XBeeDevice(LOCAL_PORT, BAUD_RATE)
        self.device.open()
        self.remote_device = None
        self.queue = None

        try:
            self.remote_device = RemoteXBeeDevice(
                self.device,
                XBee64BitAddress.from_hex_string(REMOTE_NODE_ADDRESS))
            if self.remote_device is None:
                print("Could not find the remote device")
        except XBeeException:
            print("Exception has occurred")

    def send(self, data):
        print("Testing data: " + data)
        try:
            print("Sending data to %s >> %s..." %
                  (self.remote_device.get_64bit_addr(), DATA_TO_SEND))

            logging.basicConfig(stream=sys.stdout,
                                level=logging.DEBUG,
                                format="[root] %(levelname)s - %(message)s")

            logger = logging.getLogger(self.device.get_node_id())

            self.device.send_data(self.remote_device, data)

            print("Success")

        finally:
            if self.device is not None and self.device.is_open():
                # self.device.close()
                print("Commented out close")

    def bind_queue(self, queue):
        self.queue = queue

    def receive(self):
        try:

            def data_receive_callback(msg):
                data = msg.data.decode("utf8")

                json_data = json.loads(data)

                self.queue.put(json_data)

            self.device.add_data_received_callback(data_receive_callback)

            print("Waiting for data...\n")
            input()
        finally:
            if self.device is not None and self.device.is_open():
                #self.device.close()
                print("Commented out close")
def main():

    print(" +---------------------------------+")
    print(" | Get and Set Params Local/Remote |")
    print(" +---------------------------------+\n")

    local_xbee = XBeeDevice(PORT, BAUD_RATE)

    try:
        local_xbee.open()
        remote_xbee = RemoteXBeeDevice(local_xbee,
                                       x64bit_addr=REMOTE_DEVICE_ADDRESS)

        local_xbee.read_device_info()
        print("Read device info of local device successfully")
        remote_xbee.read_device_info()
        print("Read device info of remote device successfully")

        print("\nLocal:")
        print(local_xbee.get_node_id())
        print(local_xbee.get_hardware_version())
        print(hex_to_string(local_xbee.get_firmware_version()))
        print(local_xbee.get_protocol())
        print("\nRemote:")
        print(remote_xbee.get_node_id())
        print(remote_xbee.get_hardware_version())
        print(hex_to_string(remote_xbee.get_firmware_version()))
        print(remote_xbee.get_protocol())

        ni = ''.join(
            random.choice(string.ascii_letters)
            for i in range(random.randint(1, 20)))
        local_xbee.set_parameter("NI", bytearray(ni, "utf8"))
        param = local_xbee.get_parameter("NI")
        assert (param.decode() == ni)

        ni = ''.join(
            random.choice(string.ascii_letters)
            for i in range(random.randint(1, 20)))
        remote_xbee.set_parameter("NI", bytearray(ni, "utf8"))
        param = remote_xbee.get_parameter("NI")
        assert (param.decode() == ni)

        print("\nTest finished successfully")

    finally:
        if local_xbee is not None and local_xbee.is_open():
            local_xbee.close()
Exemplo n.º 5
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
Exemplo n.º 6
0
from digi.xbee.devices import XBeeDevice
PORT = '/dev/ttyUSB0'
BAUD_RATE = 57600

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

# Get the 64-bit address of the device.
addr_64 = device.get_64bit_addr()
# Get the node identifier of the device.
node_id = device.get_node_id()
# Get the hardware version of the device.
hardware_version = device.get_hardware_version()
# Get the firmware version of the device.
firmware_version = device.get_firmware_version()

print("MAC ADDRESS = ",addr_64)
print("Node ID = ",node_id)
Exemplo n.º 7
0
class XBeeInterfaceNode(Node):
    coordinator: str = '0'
    __platform__: str = platform.system()
    """"

    """
    def __init__(self):
        """
        Creates a ROS2 Node for interfacing with XBee Device
        """
        super().__init__('XBeeInterface')

        # ---> Declare ROS Parameters <--- #
        self.declare_parameter(
            'port', '/dev/ttyUSB0' if self.__platform__ == 'Linux' else 'COM0')
        self.declare_parameter('baud_rate', 115200)
        # ---> Get Xbee Device Object <--- #
        try:
            self.xbee = XBeeDevice(
                self.get_parameter('port').value,
                self.get_parameter('baud_rate').value)
            self.xbee.open()
            self.get_logger().info(
                'Successfully interfaced XBee module with node ID: ' +
                self.xbee.get_node_id())
        except XBeeException as error:
            self.get_logger().info('XBee Exception Occurred, ERROR: ' +
                                   str(error))
        except SerialException as error:
            self.get_logger().info(
                'Cannot establish  connection with the XBee Module,: ' +
                str(error))
        except Exception as error:
            self.get_logger().info('Exception occurred,  Error: ' + str(error))
        finally:
            # self.set_call_back()
            pass

    def transmit(self,
                 data: bytes,
                 recipient_address: str = coordinator) -> TransmitStatusPacket:
        """
        Takes the address of the receiver xbee module and transmit the data to the receiver

        :param data: Data in bytes to be transmitted to the desired xbee module/device
        :type data: bytes
        :param recipient_address: 64 bit xbee address of the recipient module/device
        :type recipient_address: str
        :return: Digi-xbee 'TransmitStatusPacket' object, which gives us the transmit status of the transmitted data
        """
        try:
            if type(data) is not bytes or type(recipient_address) is not str:
                raise TypeError(
                    'Args "data" must be bytes & "recipient_address" must be a str'
                )
            if not self.xbee.is_open():
                self.xbee.open()

                # Instantiate a remote XBee device object
                target = RemoteXBeeDevice(
                    self.xbee,
                    XBee64BitAddress.from_hex_string(recipient_address))

                # Send data using the remote object
                status_packet: TransmitStatusPacket = self.xbee.send_data(
                    target, data)
                return status_packet
        except TypeError as e:
            self.get_logger().info('Bad arg types, ERROR: ', e)
        except TransmitException as e:
            self.get_logger().info('Failed to transmit data, ERROR: ',
                                   e.status)
Exemplo n.º 8
0
from digi.xbee.devices import XBeeDevice, RemoteXBeeDevice, XBee64BitAddress, XBeeMessage
from struct import *
import json
from digi.xbee.io import IOLine, IOMode, IOValue

xbee = XBeeDevice('/dev/tty.usbserial-A505N9YU', 9600)

xbee.open()
print(xbee.get_node_id())

try:

    def data_receive_callback(xbee_message):
        print("pulse count data recieved")
        pulseCount = (256 * xbee_message.data[0] + xbee_message.data[1])
        print("From", xbee_message.remote_device.get_64bit_addr(),
              " >> Pulse count = ", pulseCount)
        print(xbee_message.remote_device.get_node_id())

    def io_sample_callback(io_sample, remote_xbee, send_time):
        print("IO sample:")
        print("IO sample received at time %s." % str(send_time))
        print("IO sample:")
        print(str(io_sample))
        print(str(remote_xbee))
        print(type(remote_xbee))
        print(remote_xbee.get_64bit_addr())
        print(type(remote_xbee.get_64bit_addr()))
        print(remote_xbee.get_node_id())
        b = io_sample.get_digital_value(IOLine.DIO1_AD1)
        print(b)
Exemplo n.º 9
0
class XBeeConnect(QObject):

    successful_connection_signal = pyqtSignal()
    error_connection_signal = pyqtSignal()

    def __init__(self, parent=None):

        super(XBeeConnect, self).__init__(parent)

        self.local_device = None
        self.com = ''
        self.speed = ''
        self.connected = False
        self.parent = parent

        self.parent.signal_start_connect.connect(self.start_connection)
        self.parent.signal_read_info.connect(self.read_info)
        self.parent.signal_write_info.connect(self.write_info)
        self.parent.signal_disconnect_module.connect(self.close_port)
        self.parent.signal_info_type_s2c_dev.connect(self.info_type_s2c_dev)
        self.parent.signal_update_info_id.connect(self.update_info_id)
        self.parent.signal_apply_change_id.connect(self.apply_change_id)
        self.parent.signal_update_info_ni.connect(self.update_info_ni)
        self.parent.signal_apply_change_ni.connect(self.apply_change_ni)
        self.parent.signal_update_info_ce.connect(self.update_info_ce)
        self.parent.signal_apply_change_ce.connect(self.apply_change_ce)
        self.parent.signal_update_info_jv.connect(self.update_info_jv)
        self.parent.signal_apply_change_jv.connect(self.apply_change_jv)
        self.parent.signal_update_info_sm.connect(self.update_info_sm)
        self.parent.signal_apply_change_sm.connect(self.apply_change_sm)

    @pyqtSlot()
    def start_connection(self):

        self.local_device = XBeeDevice(self.com, self.speed)

        try:
            self.local_device.open()
            self.connected = True

            # делаем для теста print
            print('ПОРТ ОТКРЫТ. Устройство готово к работе')

            self.type_device = hex_to_string(
                self.local_device.get_firmware_version())

            print("Firmware version: %s" % self.type_device)

            self.successful_connection_signal.emit()

        except Exception as e:
            self.connected = False
            print(e)
            self.error_connection_signal.emit()
            self.local_device.close()

    def read_info(self):

        self.pan_id = self.local_device.get_parameter('ID')
        self.node_id = self.local_device.get_node_id()

    def write_info(self, parameters):

        self.local_device.set_pan_id(hex_string_to_bytes(str(parameters[0])))
        self.local_device.set_parameter('NI',
                                        bytearray(str(parameters[1]), 'utf8'))

        time.sleep(1)
        self.local_device.apply_changes()
        time.sleep(1)
        self.local_device.write_changes()
        time.sleep(1)
        self.new_pan_id = self.local_device.get_parameter('ID')
        self.new_node_id = self.local_device.get_node_id()

        print('ПАРАМЕТРЫ ОБНОВЛЕНЫ')

    def close_port(self):

        self.local_device.close()
        print('ПОРТ ЗАКРЫТ')

    def info_type_s2c_dev(self):

        self.coordinator_enabled = self.local_device.get_parameter('CE')
        self.sleep_mode = self.local_device.get_parameter('SM')

    def update_info_id(self):

        self.info_id = self.local_device.get_parameter('ID')

    def apply_change_id(self, id):

        self.local_device.set_pan_id(hex_string_to_bytes(str(id)))
        self.local_device.apply_changes()
        self.local_device.write_changes()
        self.new_id = self.local_device.get_parameter('ID')

    def update_info_ni(self):

        self.info_ni = self.local_device.get_node_id()

    def apply_change_ni(self, ni):

        self.local_device.set_parameter('NI', bytearray(str(ni), 'utf8'))
        self.local_device.apply_changes()
        self.local_device.write_changes()
        self.new_ni = self.local_device.get_node_id()

    def update_info_ce(self):

        self.info_ce = self.local_device.get_parameter('CE')

    def apply_change_ce(self, ce):

        self.local_device.set_parameter('CE', hex_string_to_bytes(str(ce)))
        self.local_device.apply_changes()
        self.local_device.write_changes()
        self.new_ce = self.local_device.get_parameter('CE')

    def update_info_jv(self):

        self.info_jv = self.local_device.get_parameter('JV')

    def apply_change_jv(self, jv):

        self.local_device.set_parameter('JV', hex_string_to_bytes(str(jv)))
        self.local_device.apply_changes()
        self.local_device.write_changes()
        self.new_jv = self.local_device.get_parameter('JV')

    def update_info_sm(self):

        self.info_sm = self.local_device.get_parameter('SM')

    def apply_change_sm(self, sm):

        self.local_device.set_parameter('SM', hex_string_to_bytes(str(sm)))
        self.local_device.apply_changes()
        self.local_device.write_changes()
        self.new_sm = self.local_device.get_parameter('SM')