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()
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()
Пример #3
0
def main():

    print(" +------------------------+")
    print(" | Read Data Timeout Test |")
    print(" +------------------------+\n")

    local = XBeeDevice(PORT_LOCAL, BAUD_RATE_LOCAL)
    local_remote = XBeeDevice(PORT_REMOTE, BAUD_RATE_REMOTE)

    message = None
    timeout_exception = None

    try:
        local.open()
        local_remote.open()

        message = local_remote.read_data()
        assert (message is None)

        remote = RemoteXBeeDevice(local,
                                  x64bit_addr=local_remote.get_64bit_addr())
        local.send_data(remote, "Test message")

        time.sleep(1)

        message = local_remote.read_data()
        assert (message is not None)
        message = None
        message = local_remote.read_data(3)

    except TimeoutException as e:
        timeout_exception = e

    finally:
        assert (timeout_exception is not None)
        assert (message is None)

        print("Test finished successfully")

        if local is not None and local.is_open():
            local.close()
        if local_remote is not None and local_remote.is_open():
            local_remote.close()
Пример #4
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()
Пример #5
0
def main():
    print("Power Up Timer!  Looking for coordinator XBee on port " + PORT)

    localDevice = XBeeDevice(PORT, BAUD_RATE)
    print("localDevice = %s", localDevice)

    try:
        localDevice.open()
        print("Opened localDevice = ", localDevice)

        # Obtain the remote XBee localDevice from the XBee network.
        xbee_network = localDevice.get_network()
        print("Found network: ", xbee_network)
        print("Looking for remoteDevice named ", REMOTE_NODE_ID)
        remoteDevice = xbee_network.discover_device(REMOTE_NODE_ID)
        if remoteDevice is None:
            print("Could not find the remote device named " + REMOTE_NODE_ID)
            exit(1)
        print("Found remoteDevice = ", remoteDevice)

        # Set the local localDevice as destination address of the remote.
        remoteDevice.set_dest_address(localDevice.get_64bit_addr())

        remoteDevice.set_io_configuration(LEFT, IOMode.DIGITAL_IN)
        remoteDevice.set_io_configuration(RIGHT, IOMode.DIGITAL_IN)

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

        # Enable DIO change detection in the remote device.
        remoteDevice.set_dio_change_detection({LEFT})
        remoteDevice.set_dio_change_detection({RIGHT})

        scaleLeft = Scale()
        scaleRight = Scale()

        # Register a listener to handle the samples received by the local device.
        def io_samples_callback(sample, remote, time):
            try:
                #print("New sample from %s - %s at %s" % (remote.get_node_id(), sample, str(time)))
                newState = sample.get_digital_value(LEFT)
                if (scaleLeft.state == TIMER_STOPPED):
                    # timer is stopped
                    if (sample.get_digital_value(LEFT) == SWITCH_CLOSED):
                        #print("Timer was stopped, switch is now closed.")
                        scaleLeft.start = time
                        scaleLeft.state = TIMER_RUNNING
                else:
                    # timer is running
                    if (sample.get_digital_value(LEFT) == SWITCH_OPEN):
                        #print("Timer was running, switch is now open.")
                        scaleLeft.state = TIMER_STOPPED
                        elapsedSec = time - scaleLeft.start
                        scaleLeft.total += elapsedSec
                        print(
                            "Left side was closed for %.1f, total time is %.1f sec"
                            % (elapsedSec, scaleLeft.total))
                newState = sample.get_digital_value(RIGHT)
                if (scaleRight.state == TIMER_STOPPED):
                    # timer is stopped
                    if (sample.get_digital_value(RIGHT) == SWITCH_CLOSED):
                        #print("Timer was stopped, switch is now closed.")
                        scaleRight.start = time
                        scaleRight.state = TIMER_RUNNING
                else:
                    # timer is running
                    if (sample.get_digital_value(RIGHT) == SWITCH_OPEN):
                        #print("Timer was running, switch is now open.")
                        scaleRight.state = TIMER_STOPPED
                        elapsedSec = time - scaleRight.start
                        scaleRight.total += elapsedSec
                        print(
                            "Right side was closed for %.1f, total time is %.1f sec"
                            % (elapsedSec, scaleRight.total))
            except Exception as ex:
                print("caught in callback: ", ex)
                print("sys.exc_info(): ", sys.exc_info())

        print("Registering callback on ", remoteDevice)
        localDevice.add_io_sample_received_callback(io_samples_callback)

        # Wait for an input line to exit
        print("Press enter to exit")
        input()
    except BaseException as ex:
        print("Caught something: ", ex)

    finally:
        if localDevice is not None and localDevice.is_open():
            localDevice.close()
Пример #6
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('REMOTO_2')
        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(IOLINE_IN_3 , IOMode.ADC)
        remote_device.set_io_configuration(IOLINE_IN_2 , IOMode.ADC)
        remote_device.set_io_configuration(IOLINE_IN_1, IOMode.ADC)
        remote_device.set_io_configuration(IOLINE_IN_0, IOMode.ADC)

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


        def parse_sample(sample):
            for i in range (0,4):
                sample=str(sample).replace('IOLine.DIO'+str(i)+'_AD'+str(i)+':',"")
            sample = sample.replace('[','')
            sample = sample.replace (']','')
            sample = sample.replace('{','')
            sample = sample.replace('}','')
            sample=sample.split(',')
            for i in range (0,len(sample)):
                sample[i]=int(sample[i])
            return sample

        def get_voltaje(remote):
            vcc= remote.get_parameter("%V")
            vcc = int(utils.hex_to_string(vcc).replace(' ', ''), 16)
            return vcc

        # 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))
            vcc = remote.get_parameter("%V")
            vcc = int(utils.hex_to_string(vcc).replace(' ', ''), 16)
            print(vcc)
            raw_values = parse_sample (sample)
            temp_1= ntc10k_calculate_temp(raw_values[0],3300)
            print(temp_1)



        device.add_io_sample_received_callback(io_samples_callback)


        input()

    finally:

        if device is not None and device.is_open():
            device.del_io_sample_received_callback(io_samples_callback)
            device.close()
Пример #7
0
from digi.xbee.devices import XBeeDevice
device = XBeeDevice("/dev/ttyUSB0", 9600)
device.open()

print(device.read_device_info())

protocol = device.get_protocol()
print(protocol)


print("get_64bit_addr {}".format(device.get_64bit_addr()))
print("get_16bit_addr {}".format(device.get_16bit_addr()) )



device.close()
    # If a port found then initialise and run the app
    if portfound:
        root = Tk()
        root.geometry("800x800")
        root.resizable(1, 1)
        root.title("Packet Traffic Visualisation")
        root.protocol("WM_DELETE_WINDOW", ask_quit)

        # Asks the user to enter the baudrate
        BAUD_RATE = input("Enter the baudrate of the device: ")

        gateway = XBeeDevice(PORT, BAUD_RATE)
        gateway.open()
        # Get the 64-bit address of the device.
        GATEWAY = "0x" + str(gateway.get_64bit_addr())
        # Set the ID & NI Parameter
        gateway.set_parameter(PARAM_NODE_ID,
                              bytearray(PARAM_VALUE_NODE_ID, 'utf8'))
        gateway.set_parameter(PARAM_PAN_ID, PARAM_VALUE_PAN_ID)
        # Get parameters.

        print("Node ID:\t%s" % gateway.get_parameter(PARAM_NODE_ID).decode())

        print("PAN ID:\t%s" %
              utils.hex_to_string(gateway.get_parameter(PARAM_PAN_ID)))
        # Assign the data received callback to the gateway
        gateway.add_data_received_callback(packages_received_callback)

        app = Application(master=root)
        app.mainloop()
Пример #9
0
class TxController:
    """ Class for managing serial connection with XBee Pro S1 """
    def __init__(self, port=None, baud_rate=9600):
        self.port = port
        self.baud_rate = baud_rate
        self.remote = None
        self.xbee = None

    def connect(self):
        try:
            if self.port is None:
                self.port = serial_ports()[0]    # will display text box later for options
                self.xbee = XBeeDevice(port=self.port, baud_rate=self.baud_rate)
                print(self.xbee.get_64bit_addr())
                self.xbee.open()
                return True

            elif self.port is not None:
                self.xbee = XBeeDevice(port=self.port, baud_rate=self.baud_rate)
                self.xbee.open()
                return True

            else:
                if self.is_open():
                    self.xbee.close()
                    print("Disconnected from {}".format(self.port))
                    return False

        except serial.SerialException:
            return False

    def is_open(self):
        return self.xbee.is_open()

    def disconnect(self):
        try:
            if self.is_open():
                self.xbee.close()
                return True
            else:
                return False
        except serial.SerialException:
            return False

    def send_synchronous(self, message):
        self.xbee.send_data(self.remote, message)

    def send_asynchronous(self, message):
        self.xbee.send_data_async(self.remote, message)

    def configure_remote(self):
        if self.xbee.get_64bit_addr() == "0013A2004093DF98":
            self.remote = RemoteXBeeDevice(self.xbee, XBee64BitAddress.from_hex_string('0013A2004093DFA1'))
        else:
            self.remote = RemoteXBeeDevice(self.xbee, XBee64BitAddress.from_hex_string("0013A2004093DF98"))

    @staticmethod
    def list_ports():
        return serial_ports()

    def __del__(self):
        if self.is_open():
            self.disconnect()
        del self
Пример #10
0
class masterXBee:
    '''
    Class for the local XBee device, containing all connected devices and their pins in a dictionary
    port = used COM/tty port
    baud = used baud rate
    callback_handler: function you want to handle callbacks!
        callback_handler should take two arguments:
        sensor(str) = name of sensor
        value(str) = value of sensor (HIGH or LOW)
    '''
    # functional devices dictionary
    devices = {}
    # sensor polling state
    polling = False
    # flask readable device data dictionary
    devicedata = {}
    # flask readable sensor data dictionary
    sensordata = {}

    
    

    def __init__(self, port, baud, callback_handler=None):
        # Semaphore for XBee action, limits acces to single user at a time.
        # This is needed for alternating between polling values from sensors and receiving callbacks
        self.sema = Semaphore()
        # instantiate local XBee device
        print("Opening local device", port, baud)
        self.localXB = XBeeDevice(port,baud)
        self.localXB.open()
        # find devices in network, store in devices dictionary. Keys are device 64bit addresses
        devices = self.getNetworkDevices()
        # write flask readable device dict
        self.devicedata = self.get_device_data()
        # create sensor data dict
        self.sensordata = self.get_sensor_data()
        # set local device to receive IO callbacks
        self.localXB.set_dest_address(self.localXB.get_64bit_addr())
        self.localXB.add_io_sample_received_callback(self.io_sample_callback)
        self.callback_function = callback_handler
        #clear previous monitored IO lines:
        for dev in self.devices:
            self.devices[dev].xbee.set_dio_change_detection(None)

    def getNetworkDevices(self):
        """
        Returns devices in the network of given local xBee device, including the local device:
        devices = dict of all the devices in locals network and their sensors!
        devices : {
            "device ID" : <XBeeDev object>
                sensors = {
                    "NAME/TYPE"  : {
                        "line" : IOLine,
                        "mode" : IOMode,
                    }
                }
        }
        """
        print("Getting a list of network devices...", end="")
        # Get devices in local xbee's network!
        self.localXB.send_data_broadcast("Getting a list of everyone :D")
        network = self.localXB.get_network()
        network.start_discovery_process()
        # wait for network discovery to finish...
        while network.is_discovery_running():
            time.sleep(.5)
            print(".",end="")
        networkDevices = network.get_devices()
        networkDevices.insert(0, self.localXB)
        # loop through found network devices and create a XBeeDev object for each
        # containing device type and connected sensors
        print("\nFound devices and sensors:")
        for device in networkDevices:
            print(device)
            # new xbee device with its pins n stuff
            XBeeDevobj = XBeeDev(device)
            # add it to master class's device dict
            self.devices.update({XBeeDevobj.dvcID : XBeeDevobj})
        return networkDevices
Пример #11
0
from xbee import XBee, ZigBee
from digi.xbee.models.address import XBee64BitAddress, XBee16BitAddress
from digi.xbee.devices import ZigBeeDevice, XBeeDevice, RemoteXBeeDevice, RemoteZigBeeDevice
from digi.xbee.serial import XBeeSerialPort
from digi.xbee.packets.raw import TX64Packet, TX16Packet, RX64Packet, RX16Packet
from digi.xbee.models.message import XBeeMessage
import pymysql
remoto = {}

#Inicio XBee Device
device = XBeeDevice("/dev/serial0", 9600)
device.open()

#MAC de mi dispositivo
print("MAC de mi dispositivo: ")
print(device.get_64bit_addr(), "\n")

#Buscar redes
xnet = device.get_network()
print("Red encontrada:")
print(xnet)
xnet.start_discovery_process()
while xnet.is_discovery_running():
    time.sleep(0.5)

#Busca dispositivos de esa red
devices = xnet.get_devices()
print("Dispositivos en esa red: 0,1,2...")
print(devices, "\n")
# Vision de todos los nodos de la red
for i in range(len(devices)):
Пример #12
0
class Commander:
    def __init__(self, comPort):
        self.device = XBeeDevice(comPort, BAUD_RATE)
        self.network = None
        self.peers = []
        self.lock = Lock()
        self.run = True
        self.device.open()
        self.code = CODE
        self.on_success = None
        self.on_error = None
        logging.info("Commander address: {}".format(
            self.device.get_64bit_addr()))

    def set_on_error(self, callback):
        self.on_error = callback

    def set_on_success(self, callback):
        self.on_success = callback

    @asyncio.coroutine
    def discover_peer(self):
        """
            Search other connected device to the same Zigbee network
        """
        def push_peer(conn):
            peer = Peer(conn)
            if peer not in self.peers:
                logging.info("New peer: {}".format(peer))
                self.lock.acquire()
                self.peers.append(peer)
                self.lock.release()

        if self.network is None:
            self.network = self.device.get_network()
        self.network.set_discovery_timeout(25.5)
        self.network.clear()

        self.network.add_device_discovered_callback(push_peer)
        while self.run:
            logging.info("running network scan...")
            try:
                self.network.start_discovery_process()

                while self.network.is_discovery_running():
                    yield from asyncio.sleep(1)
            except:
                pass
            yield from asyncio.sleep(60)

    def light_red(self):
        self.lock.acquire()
        for peer in self.peers:
            peer.light_red()
        self.lock.release()

    def light_blue(self):
        self.lock.acquire()
        for peer in self.peers:
            peer.light_blue()
        self.lock.release()

    def light_green(self):
        self.lock.acquire()
        for peer in self.peers:
            peer.light_green()
        self.lock.release()

    def listen_remote(self):
        def data_recv_callback(msg):
            logging.info("[{}] {}".format(msg.remote_device.get_64bit_addr(),
                                          msg.data.decode()))

        def samples_recv_callback(sample, remote, time):

            remote = Peer(remote)

            def check(btn):
                if len(self.code) > 0 and self.code[0] == btn:
                    self.code.pop()
                else:
                    self.code = CODE
                    remote.light_red()
                    self.on_error()

            logging.info("[{}] {}".format(remote.get_addr(), sample))

            if sample.get_digital_value(BTN_ONE) == IOValue.HIGH:
                check(BTN_ONE)
            elif sample.get_digital_value(BTN_TWO) == IOValue.HIGH:
                check(BTN_TWO)
            elif sample.get_digital_value(BTN_THREE) == IOValue.HIGH:
                check(BTN_THREE)
            if len(self.code) == 0:
                self.code = CODE
                remote.light_green()
                self.on_success()

        self.device.add_data_received_callback(data_recv_callback)
        self.device.add_io_sample_received_callback(samples_recv_callback)

    def __del__(self):
        for peer in self.peers:
            peer.stop_all_task()
        if self.device.is_open():
            self.device.close()
def run():
    global device, modeV
    modeV = 0

    #dev_logger = utils.enable_logger("digi.xbee.devices", logging.DEBUG)
    dev_logger = utils.disable_logger("digi.xbee.devices")
    ###################################################################################################
    #    Look for XBee USB port, to avoid conflicts with other USB devices
    ###################################################################################################
    rospy.init_node('fleetEndPoint', anonymous=True)

    rospy.loginfo("Looking for XBee...")

    context = pyudev.Context()
    usbPort = 'No XBee found'

    for device in context.list_devices(subsystem='tty'):
        if 'ID_VENDOR' in device and device['ID_VENDOR'] == 'FTDI':
            usbPort = device['DEVNAME']

    device = XBeeDevice(usbPort, 57600)
    #device = XBeeDevice("/dev/ttyUSB1", 57600)
    device.open()
    print("Current timeout: %d seconds" % device.get_sync_ops_timeout())
    device.set_sync_ops_timeout(0.1)

    ###################################################################################################
    #    Get local XBee ID (should be 0, convention for Coordinator)
    ###################################################################################################
    ID = utils.bytes_to_int(device.get_64bit_addr().address)

    if ID == 0:
        raise Exception("\nThis Shouldn't be a Coordinator" + '\n')
    else:
        print("Hello This is " + str(ID))


###################################################################################################
#    Initialisation
###################################################################################################
#Variables storing the data received by the subscribers
    global windForceString, windDirectionString, gpsString, eulerAnglesString, posString, beginString, endString, lastData, lastDataStr, pub_send_u_rudder_sail, pub_send_control_mode
    windForceData, windDirectionData, GPSdata, eulerAnglesData, lineStartData, lineEndData = Float32(
    ), Float32(), String(), Vector3(), Pose2D(), Pose2D()

    remote_devices = {}
    lastDataStr = ''
    lastData = {}
    lastData["NMEA"] = ''
    lastData["windF"] = 0.0
    lastData["windT"] = 0.0
    lastData["eulerx"] = 0.0
    lastData["eulery"] = 0.0
    lastData["eulerz"] = 0.0

    #xnet = device.get_network()
    #xnet.add_device_discovered_callback(network_callback)
    #xnet.add_discovery_process_finished_callback(network_finished)
    device.add_data_received_callback(data_received)

    rate = rospy.Rate(10)

    rospy.Subscriber('/sailboat/GPS/NMEA', String, sub_GPS)
    rospy.Subscriber('/sailboat/wind', Pose2D, sub_WIND)
    rospy.Subscriber('/sailboat/IMU', Imu, sub_IMU)
    rospy.Subscriber('regulator_send_lineBegin', Pose2D, sub_lineBegin)
    rospy.Subscriber('regulator_send_lineEnd', Pose2D, sub_lineEnd)

    pub_send_u_rudder_sail = rospy.Publisher('xbee/sailboat_cmd',
                                             Twist,
                                             queue_size=2)
    pub_send_control_mode = rospy.Publisher('xbee/mode', Float32, queue_size=2)

    ###################################################################################################
    # Transmission Loop
    ###################################################################################################

    while not rospy.is_shutdown():
        #if(xnet.is_discovery_running() is False):
        #    xnet.start_discovery_process()
        try:
            device.send_data(
                RemoteXBeeDevice(device,
                                 XBee64BitAddress.from_hex_string("00")),
                data_to_bytearray(lastData))
        except TimeoutException:
            #print("timeout")
            pass
        except XBeeException:
            pass

        if (modeV == 1):
            pub_send_u_rudder_sail.publish(rudder_sail)

        mode = Float32(data=0.)
        mode.data = modeV
        pub_send_control_mode.publish(mode)

        rate.sleep()

    #if(xnet.is_discovery_running()):
    #    xnet.stop_discovery_process()
    device.close()
Пример #14
0
def main():
    def publish_callback(result, status):
        pass

    pubnub.publish().channel('myocarta_ui').message(
        ["> Launching myocarta Beta Version"]). async (publish_callback)
    time.sleep(0.7)
    all_connected = True
    device = XBeeDevice(PORT, BAUD_RATE)

    try:
        pubnub.publish().channel('myocarta_ui').message(
            [">> Launching home receiver module..."]). async (publish_callback)
        time.sleep(0.7)
        device.open()

        pubnub.publish().channel('myocarta_ui').message(
            [">>> Connecting to sensors..."]). async (publish_callback)
        time.sleep(0.7)
        xbee_network = device.get_network()

        for device_id in REMOTE_NODE_IDS:
            remote_device = xbee_network.discover_device(device_id)
            if remote_device is None:
                print("ERROR: Could not find remote devices with ID " +
                      device_id)
                all_connected = False
            else:
                REMOTE_DEVICES.append(remote_device)

        while (not all_connected):
            response_1 = input(
                "Not all selected remote devices were connected; enter 'proceed' or 'abort' to continue."
            )
            if response_1 == "proceed":
                print("Proceeding with connected devices.")
                all_connected = True
            if response_1 == "abort":
                print("ERROR: Aborting")
                exit(1)
            else:
                print("Input unrecognized. Please enter proceed or abort.")

        pubnub.publish().channel('myocarta_ui').message(
            [">>>> Configuring remote sensors..."]). async (publish_callback)

        i = 0
        for rem in REMOTE_DEVICES:
            rem.set_dest_address(device.get_64bit_addr())
            rem.set_io_configuration(ANALOG_LINES[i], IOMode.ADC)
            rem.set_io_sampling_rate(IO_SAMPLING_RATE)
            i += 1
            MOVING_AVERAGES.append([])

        print("Home module " + str(device.get_64bit_addr()) +
              " is connected to the following addresses:")
        for rem in REMOTE_DEVICES:
            print(str(rem.get_64bit_addr()) + " ")

        pubnub.publish().channel('myocarta_ui').message([
            ">>>>> Launch successful. Starting data collection."
        ]). async (publish_callback)
        time.sleep(0.7)
        pubnub.publish().channel('myocarta_ui').message(
            ["| myocarta |"]). async (publish_callback)
        device.add_io_sample_received_callback(io_samples_callback)
        input()
        print(" | Closing MyoCarta V2 07/25/18 |")

    finally:
        if device is not None and device.is_open():
            device.close()
Пример #15
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)
Пример #16
0
class RxController:
    """ Class for managing serial connection with XBee Pro S1 """
    def __init__(self, port=None, baud_rate=9600):
        self.port = port
        self.baud_rate = baud_rate
        self.remote = None
        self.xbee: XBeeDevice = None
        self.timeout = 100
        self.packet = None
        self.dataframe = pd.DataFrame()

    def connect(self):
        try:
            if self.port is None:
                self.port = serial_ports()[
                    0]  # will display text box later for options
                self.xbee = XBeeDevice(port=self.port,
                                       baud_rate=self.baud_rate)
                self.xbee.open()
                return True

            elif self.port is not None:
                self.xbee = XBeeDevice(port=self.port,
                                       baud_rate=self.baud_rate)
                self.xbee.open()
                return True

            else:
                if self.is_open():
                    self.xbee.close()
                    print("Disconnected from {}".format(self.port))
                    return False

        except serial.SerialException:
            return False

    def is_open(self):
        return self.xbee.is_open()

    def disconnect(self):
        try:
            if self.is_open():
                self.xbee.close()
                return True
            else:
                return False
        except serial.SerialException:
            return False

    def receive(self):
        self.packet = XBeePacket(self.xbee.read_data())
        print(self.packet.data.decode("utf8"))

    def receive_from(self):
        self.packet = XBeePacket(
            self.xbee.read_data_from(self.remote, self.timeout))
        data = self.packet.data.decode("utf8").split(' ')
        if float(data[0]) == 0:
            print('No data, but still connected. Try # ', data[-1])
        else:
            image = g_img.get_image(float(data[1]))
            kml.kml_gen(i=float(data[0]),
                        lon=data[3],
                        lat=data[2],
                        alt=(float(data[4]) - 117),
                        icon=image)

    def configure_remote(self):
        if self.xbee.get_64bit_addr() == "0013A2004093DF98":
            self.remote = RemoteXBeeDevice(
                self.xbee,
                XBee64BitAddress.from_hex_string('0013A2004093DFA1'))
        else:
            self.remote = RemoteXBeeDevice(
                self.xbee,
                XBee64BitAddress.from_hex_string("0013A2004093DF98"))

    def to_csv(self):
        a = pd.ExcelWriter('../RxData.xlsx', engine='xlsxwriter')
        self.dataframe.to_excel(a, sheet_name='Sheet1')
        a.save()

    @staticmethod
    def list_ports():
        return serial_ports()

    def __del__(self):
        if self.is_open():
            self.disconnect()
        del self
Пример #17
0
class XBeeTalks:
    def __init__(self, port, baudrate=BAUDRATE):
        self.device = XBeeDevice(port, baudrate)

        self.instructions = dict()
        self.listener = XBeeListener(self)

        self.queues_dict = dict()
        self.queues_lock = RLock()

    def open(self):
        if (self.device.is_open()):
            raise AlreadyOpenedError("Device already in use")
        else:
            self.device.open()
        self.listener.start()

    def bind(self, opcode, instruction):
        if not opcode in self.instructions:
            self.instructions[opcode] = instruction
        else:
            raise KeyError(
                'opcode {} is already bound to another instruction'.format(
                    opcode))

    def get_address(self):
        return self.device.get_64bit_addr()

    def send(self, address, opcode, *args, **kwargs):
        retcode = random.randint(0, 0xFFFFFFFF)
        content = (opcode, retcode, args, kwargs)
        prefix = (MASTER_BYTE, )
        self.rawsend(address, pickle.dumps(prefix + content))
        return retcode

    def sendback(self, address, retcode, *args):
        content = (retcode, args)
        prefix = (SLAVE_BYTE, )
        self.rawsend(address, pickle.dumps(prefix + content))

    def get_queue(self, retcode):
        self.queues_lock.acquire()
        try:
            queue = self.queues_dict[retcode]
        except KeyError:
            queue = self.queues_dict[retcode] = Queue()
        finally:
            self.queues_lock.release()
        return queue

    def delete_queue(self, retcode):
        self.queues_lock.acquire()
        try:
            del self.queues_dict[retcode]
        finally:
            self.queues_lock.release()

    def reset_queues(self):
        self.queues_lock.acquire()
        self.queues_dict = dict()
        self.queues_lock.release()

    def process(self, sender, message):
        role = message[0]
        if (role == MASTER_BYTE):
            opcode, retcode, args, kwargs = message[1:]
            self.execinstruction(sender, opcode, retcode, *args, **kwargs)
        elif (role == SLAVE_BYTE):
            retcode, args = message[1:]
            queue = self.get_queue(retcode)
            queue.put(args)

    def execinstruction(self, sender, opcode, retcode, *args, **kwargs):
        try:
            # # Make sure that the authentification was well performed
            # if not self.is_authentificated:
            # raise AuthentificationError('you are not authentificated')
            # # AJOUT
            # self.parent.disconnect()

            # Get the function or method associated with the received opcode
            try:
                instruction = self.instructions[opcode]
            except KeyError:
                raise KeyError(
                    'opcode {} is not bound to any instruction'.format(
                        opcode)) from None

            # Execute the instruction
            output = instruction(*args, **kwargs)

        except Exception:
            etype, value, tb = sys.exc_info()
            output = (etype, value, traceback.extract_tb(tb))

        # Send back the output
        self.sendback(sender, retcode, output)

    def poll(self, retcode, timeout=0):
        queue = self.get_queue(retcode)
        block = (timeout is None or timeout > 0)
        try:
            assert (current_thread() is not self.listener)
            output = queue.get(block, timeout)
        except Empty:
            if block:
                raise TimeoutError('timeout exceeded') from None
            else:
                return None
        if queue.qsize() == 0:
            self.delete_queue(retcode)
        if len(output) > 1:
            return output  # Return as a tuple
        else:
            return output[0]  # Return as a single variable

    def flush(self, retcode):
        while self.poll(retcode) is not None:
            pass

    def execute(self, address, opcode, *args, timeout=5, **kwargs):
        retcode = self.send(address, opcode, *args, **kwargs)
        output = self.poll(retcode, timeout=timeout)
        if isinstance(output, tuple) and isinstance(
                output[0], type) and issubclass(output[0], Exception):
            etype, value, tb = output
            output = (
                '{2}\n' +
                '\nThe above exception was first raised by the distant TCPTalks instance:\n\n'
                + 'Distant traceback (most recent call last):\n' + '{0}' +
                '{1}: {2}'
                '').format(''.join(traceback.format_list(tb)), etype.__name__,
                           str(value))
            raise etype(output)
        else:
            return output

    def sleep_until_disconnected(self):
        if self.listener is not current_thread():
            self.listener.join()
        else:
            raise RuntimeError(
                'cannot call the \'sleep_until_disconnected\' method from within the listening thread'
            )

    def rawsend(self, adr, data):
        try:
            remote = RemoteXBeeDevice(self.device, adr)
            self.device.send_data_async(remote, data)
        except XBeeException:
            pass