Пример #1
0
def hiddenNodediscovery():
    
    comPortList = getActiveComPort()
    if comPortList:
        comPort = comPortList[0].get('name')
        timeOut = int(comPortList[0].get('timeout'))
        baudRate = int(comPortList[0].get('baudrate'))
        
    print "Hidden Discovery"
    
    try:
        ser = serial.Serial(comPort, baudRate, timeout=timeOut)
        print "porta e otworen", ser.isOpen() 
        xbee = ZigBee(ser,escaped=True)
        xbee.at(command='ND')
        response = {'':''}
        while response <> {}:
            response = xbee.wait_read_frame()
            if response:
                print response
            else:
                text = "Xbee: Timeout during node discovery operation!"
                response = {}
                print text

    
    except serial.SerialException as ex:
        text = "Exception: " + ex.__str__()
        return text
    else:
        ser.close()
def find_bots():
    #The coordinator broadcasts a "Node Discover" AT command and records the addresses recieved, I suspect
    #Add coordinator first, then add on each bot as it responds.
    #robot id command
    
    global xbee
    
    ser = serial.Serial(DEVICE, 57600)
    xbee = ZigBee(ser)

    try:
        print("Searching for bots...")
        xbee.at(
            dest_addr_long = XBEE_ADDR_LONG,
            dest_addr = XBEE_ADDR_SHORT,
            command = 'ND'
            )
        timeout = time.time() + 30
        num_of_robots = 0
        while timeout > time.time():
            dict = xbee.wait_read_frame()
            if dict == None:
                break
            bot_array.append(parse_ND(dict))
            print "Response: %r " % bot_array[num_of_robots]
            num_of_robots += 1
    except KeyboardInterrupt, SerialException:
        sys.exit(0)
Пример #3
0
def node_discovery():
    comPortList = getActiveComPort()
    if comPortList:
        comPort = comPortList[0].get('name')
        timeOut = int(comPortList[0].get('timeout'))
        baudRate = int(comPortList[0].get('baudrate'))
        count = 0
    
    try:
        ser = serial.Serial(comPort, baudRate, timeout=timeOut)
        xbee = ZigBee(ser,escaped=True)
        node_list=[]        
        xbee.at(command='ND')
        response = {'':''}
        while response <> {}:
            response = xbee.wait_read_frame()
            if response:
                print response
                node_list.append(response)
            else:
                text = "Xbee: Timeout during node discovery operation!"
         
        print "Spisak: ", node_list # return []
        return node_list
    
    except serial.SerialException as ex:
        text = "Exception: " + ex.__str__()
        return text
    else:
        xbee.halt()
        ser.close()
Пример #4
0
def hiddenNodediscovery():

    comPortList = getActiveComPort()
    if comPortList:
        comPort = comPortList[0].get('name')
        timeOut = int(comPortList[0].get('timeout'))
        baudRate = int(comPortList[0].get('baudrate'))

    print "Hidden Discovery"

    try:
        ser = serial.Serial(comPort, baudRate, timeout=timeOut)
        print "porta e otworen", ser.isOpen()
        xbee = ZigBee(ser, escaped=True)
        xbee.at(command='ND')
        response = {'': ''}
        while response <> {}:
            response = xbee.wait_read_frame()
            if response:
                print response
            else:
                text = "Xbee: Timeout during node discovery operation!"
                response = {}
                print text

    except serial.SerialException as ex:
        text = "Exception: " + ex.__str__()
        return text
    else:
        ser.close()
Пример #5
0
def get_RSSI(iteration):
    comm = serial.Serial('/dev/ttyUSB0', 9600)
    xbee_conn = ZigBee(comm)

    rssi = 0

    rssi_list = []
    counter = 0
    while counter < iteration:
        try:
            packet = xbee_conn.wait_read_frame()
            xbee_conn.at(command=b'DB')
            if 'parameter' in packet:
                rssi_list.append(packet['parameter'][0])
                counter += 1
            sleep(0.1)
        except KeyboardInterrupt:
            break
    comm.close()

    if len(rssi_list) > 0:
        rssi = max(set(rssi_list), key=rssi_list.count)

    print(rssi)
    return int(rssi)
Пример #6
0
def node_discovery():
    comPortList = getActiveComPort()
    if comPortList:
        comPort = comPortList[0].get('name')
        timeOut = int(comPortList[0].get('timeout'))
        baudRate = int(comPortList[0].get('baudrate'))
        count = 0

    try:
        ser = serial.Serial(comPort, baudRate, timeout=timeOut)
        xbee = ZigBee(ser, escaped=True)
        node_list = []
        xbee.at(command='ND')
        response = {'': ''}
        while response <> {}:
            response = xbee.wait_read_frame()
            if response:
                print response
                node_list.append(response)
            else:
                text = "Xbee: Timeout during node discovery operation!"

        print "Spisak: ", node_list  # return []
        return node_list

    except serial.SerialException as ex:
        text = "Exception: " + ex.__str__()
        return text
    else:
        xbee.halt()
        ser.close()
Пример #7
0
    def start(self):
        #------------------------------------------------------------------------------- 
        # Open serial port
        ser = serial.Serial('/dev/ttyAMA0', 9600)

        # Create API object
        xbee = ZigBee(ser,callback = self.print_data ,escaped=True)

        # Continuously read and print packets
        print "Starting"
        #print '\n *****************************'
        #print xbee.api_commands
        #print '\n *****************************'
        #print xbee.api_responses
        #print '\n *****************************'

        MY = self.HexToByte('0B41')
        ADR = self.HexToByte('0013A2004092D86A')

        once = 1
        while True:
            try: 
                
                #xbee.tx(dest_addr=pan,dest_addr_long=Destination, data='Hello World')
                #xbee.remote_at(dest_addr=MY,dest_addr_long=ADR, command='MY',parameter=None)
                #time.sleep(5) \x
                #xbee.send("remote_at",frame_id='A', command='MY')
                
                #
                #xbee.tx(dest_addr='\xbf\x0c',dest_addr_long='\x00\x13\xa2\x00\x40\x92\xd8\x6a', data='Hello World')
                    if once == 1:
                        print 'Discovering Nodes'
                        #xbee.at(frame_id='A', command='MY')
                        #xbee.at(frame_id='A', command='ID')
                        xbee.at(frame_id='D', command='ND')
                    
                    #xbee.remote_at(dest_addr='\xbf\x0c',command='IR',parameter='\xff')
                    #xbee.remote_at(dest_addr='\xbf\x0c',command='V+',parameter='\xff')
                    #xbee.remote_at(dest_addr='\xbf\x0c',command='MY',parameter=None)
                    
                        once = 0
                        time.sleep(5)
                        print 'Sending RAT'
                        #xbee.tx(dest_addr=MY2,dest_addr_long=ADR2, data='Hello World')
                        xbee.remote_at(dest_addr=MY,dest_addr_long=ADR,command='IS')
                        #time.sleep(1)
                        xbee.remote_at(dest_addr=MY,dest_addr_long=ADR,command='IR',parameter='\xFF')
                        #time.sleep(1)
                        xbee.remote_at(dest_addr=MY,dest_addr_long=ADR,command='IR',parameter='\x00')
                        print 'Done'
                    time.sleep(3)
            except KeyboardInterrupt:
                break

        xbee.halt()        
        ser.close()
Пример #8
0
def find_bots():
    global xbee

    ser = serial.Serial(DEVICE, 57600)
    xbee = ZigBee(ser)

    try:
        print("Searching for bots. This may take a moment.")
        xbee.at(dest_addr_long=XBEE_ADDR_LONG,
                dest_addr=XBEE_ADDR_SHORT,
                command='ND')
        timeout = time.time() + 30
        num_of_robots = 0
        while timeout > time.time():
            dictl = xbee.wait_read_frame()
            if dictl == None:
                break
            bot_array.append(parse_ND(dictl))
            num_of_robots += 1
    except KeyboardInterrupt:
        sys.exit(0)
Пример #9
0
class SensorNetwork:
    def __init__(self,
                 serial_device,
                 baud=9600,
                 escaped=True):  # Use escaped for XBees in API mode 2
        self._ser = serial.Serial(serial_device, baud)
        self._xbee = ZigBee(self._ser,
                            callback=self._handle_data,
                            escaped=escaped)
        self._slave_nodes = {}  # Slave nodes found using self.discover()
        self._message_queue = []  # Queued data messages incoming

    def discover(self, timeout=0):
        """Initiate a node discovery.

        Args:
            timeout (int): Seconds before function returns.
        """
        logger.debug('Starting node discovery...')
        self._xbee.at(command='ND')
        if timeout > 0:
            time.sleep(timeout)

    def get_node_ids(self):
        """Get IDs of all slave nodes.

        Returns:
            list of addr: List of slave node IDs.
        """
        return self._slave_nodes.keys()

    def get_nodes(self):
        """Get all slave nodes.

        Returns:
            list of Node: List of slave nodes.
        """
        return self._slave_nodes.values()

    def get_node_by_id(self, id):
        """Get a node by it's ID.

        Args:
            id: Node ID.

        Returns:
            Node: Node represented by ID.
        """
        return self._slave_nodes.get(id)

    def node_exists(self, id):
        """Test if a node exists in the slave nodes.

        Args:
            id: Node ID.

        Returns:
            bool: True if node ID exists in slave nodes, else False.
        """
        return id in self._slave_nodes

    def _handle_data(self, data):
        """Internal function to handle data responses from XBee API."""
        if 'rf_data' in data.keys():
            if data['rf_data'][0] == Packet.IO_RESPONSE.value:
                self._message_queue.append(data)
                logger.debug('Received IO_RESPONSE, added to queue.')
            elif data['rf_data'][0] == Packet.INFO_RESPONSE.value:
                self._message_queue.append(data)
                logger.debug('Received INFO_RESPONSE, added to queue.')
            elif data['rf_data'][0] == Packet.DATA_RESPONSE.value:
                self._message_queue.append(data)
                logger.debug('Received DATA_RESPONSE, added to queue.')
            elif data['rf_data'][0] == Packet.CTRL_ACK.value:
                self._message_queue.append(data)
                logger.debug('Received ACK, added to queue.')
            elif data['rf_data'][0] == Packet.CTRL_NACK.value:
                self._message_queue.append(data)
                logger.debug('Received NACK, added to queue.')
            else:
                print('Unknown data: {}'.format(data['rf_data']))
        elif 'id' in data.keys() and data[
                'id'] == 'tx_status':  # Every transmission returns a tx_status packet
            if data['deliver_status'] != b'\x00':
                logger.error('Transmission was not delivered!')
                logger.error(data)
        elif 'command' in data.keys():
            command = data['command'].decode('utf-8')
            if command == 'ND':  # XBee node discovery AT command
                params = data['parameter']
                node = Node(params['source_addr_long'],
                            params['node_identifier'])
                logging.debug("Found node at {}".format(node.addr))
                self._slave_nodes[node.addr] = node
            else:
                logger.error('Unsupported command: {}'.format(command))
        else:
            logger.error('Received unknown packet:')
            logger.error(data)

    def stop(self):
        """Stop radio listener & handler."""
        logger.info('Stopping...')
        self._xbee.halt()
        self._ser.close()

    def _wait_for_response(self,
                           node,
                           type_,
                           fail_type,
                           following=None,
                           count=None,
                           timeout=None):
        """Internal function to wait until data arrives meeting specific constraints.

        Args:
            node (Node): Node to wait for data from (using long_addr).
            type_ (Packet): Packet type required
            fail_type (Packet): Packet type transimitted before wait called.
            following (bytes): Byte sequence required following type_ byte.
            count (int): Total number of bytes in packet required (including type byte).

        Returns:
            bytes: Data bytes after type byte.
        """
        if timeout is None:
            timeout = 0
        timer = time.time() + timeout
        while True:
            for msg in self._message_queue:
                if 'source_addr_long' in msg.keys(
                ) and msg['source_addr_long'] == node.long_addr:
                    # Message is from target node
                    if len(msg['rf_data']
                           ) > 0 and msg['rf_data'][0] == type_.value:
                        if following is None and count is None:
                            self._message_queue.remove(msg)
                            return msg['rf_data'][1:]
                        # Just following
                        elif count is None and len(
                                msg['rf_data']) > len(following) and msg[
                                    'rf_data'][1:len(following) +
                                               1] == following:
                            self._message_queue.remove(msg)
                            return msg['rf_data'][1:]
                        # Just count
                        elif following is None and len(
                                msg['rf_data']) == count:
                            self._message_queue.remove(msg)
                            return msg['rf_data'][1:]
                        # Following AND count
                        elif len(msg['rf_data']) == count and len(
                                msg['rf_data']) > 1 + len(following) and msg[
                                    'rf_data'][1:len(following) +
                                               1] == following:
                            self._message_queue.remove(msg)
                            return msg['rf_data'][1:]
                    # Check for NACK of same type
                    if len(msg['rf_data']) == 2 and msg['rf_data'][
                            0] == Packet.CTRL_NACK.value and msg['rf_data'][
                                1] == fail_type.value:
                        self._message_queue.remove(msg)
                        raise ProtocolError(
                            "Node returned NACK, did you ask for something which doesn't exist?"
                        )
            if timeout > 0 and time.time() > timer:
                raise ProtocolError('Did not recieve any data from node.')

    def get_node_io(self, node, timeout=None):
        """Get IO presented by node.

        Args:
            node (Node): Node to inspect.

        Returns:
            dict of Packet to int: Packet IO type mapped to quantity.
        """
        if type(node) != Node:  # Check node is a Node
            raise TypeError('Invalid node.')
        self._xbee.tx(dest_addr_long=node.long_addr,
                      data=bytes([Packet.IO_REQUEST.value]))
        logger.info('Waiting for IO_RESPONSE')
        out = {}
        # Loop over each byte as each represents a device
        for b in self._wait_for_response(node,
                                         Packet.IO_RESPONSE,
                                         Packet.IO_REQUEST,
                                         timeout=timeout):
            out[Node.Payload(
                b >> 4)] = (b & 15) + 1  # +1 to 1-index number of devices
        return out

    def get_payload_info(self, node, payload, index=0, timeout=None):
        """Get information about payload presented by node.

        Args:
            node (Node): Node to inspect.
            payload (Node.Payload): Payload type to inspect.
            index (int): Address of payload if node presents multiple.

        Returns:
            bytes: Raw bytes sent from node upon querying for information about payload
        """
        if type(node) != Node:  # Check node is a valid Node
            raise TypeError('Invalid node.')
        if type(payload
                ) != Node.Payload:  # Check payload is a valid Node.Payload
            raise TypeError('Invalid IO payload.')
        if type(index) != int:
            raise TypeError('Invalid index.')
        if index < 0 or index > 15:
            raise ValueError('Index out of bounds (0-15).')
        self._xbee.tx(dest_addr_long=node.long_addr,
                      data=bytes([
                          Packet.INFO_REQUEST.value,
                          (payload.value << 4) + index
                      ]))
        logger.info('Waiting for INFO_RESPONSE')
        data = self._wait_for_response(node,
                                       Packet.INFO_RESPONSE,
                                       Packet.INFO_REQUEST,
                                       following=bytes([
                                           (payload.value << 4) + index
                                       ]),
                                       timeout=timeout)
        return data[1:]

    def get_data(self, node, payload, index=0, timeout=None):
        """Get data from node supporting data sourcing.

        Args:
            node (Node): Node to retrieve data from.
            payload (Node.Payload): Payload type to retrieve data for.
            index (int): Address of payload if node presents multiple.

        Returns:
            bytes or int or list of bool:
                If requesting an analog value, returns int of value.
                If requesting a digital output, returns list of bool containing 8 values.
                Otherwise, bytes of raw data.
        """
        if type(node) != Node:  # Check node is a valid Node
            raise TypeError('Invalid node.')
        if type(payload
                ) != Node.Payload:  # Check payload is a valid Node.Payload
            raise TypeError('Invalid IO payload.')
        if type(index) != int:
            raise TypeError('Invalid index.')
        if payload in (Node.Payload.DIGITAL_INPUT, Node.Payload.BYTE_INPUT):
            raise ValueError('Cannot get data out of a sink node.')
        if index < 0 or index > 15:
            raise ValueError('Index out of bounds (0-15).')
        self._xbee.tx(dest_addr_long=node.long_addr,
                      data=bytes([
                          Packet.DATA_REQUEST.value,
                          (payload.value << 4) + index
                      ]))
        logger.info('Waiting for DATA_RESPONSE')
        if payload == Node.Payload.DIGITAL_OUTPUT:  # Return tuple of True/False values representing data
            data = self._wait_for_response(node,
                                           Packet.DATA_RESPONSE,
                                           Packet.DATA_REQUEST,
                                           following=bytes([
                                               (payload.value << 4) + index
                                           ]),
                                           count=3,
                                           timeout=timeout)[1:]
            return [(int(data[0]) & 1 << i) >> i == 1
                    for i in reversed(range(0, 8))]
        elif payload == Node.Payload.INT_1B_OUTPUT:  # Return number represented by byte data
            data = self._wait_for_response(node,
                                           Packet.DATA_RESPONSE,
                                           Packet.DATA_REQUEST,
                                           following=bytes([
                                               (payload.value << 4) + index
                                           ]),
                                           count=3,
                                           timeout=timeout)[1:]
            return int(data[0])
        elif payload == Node.Payload.INT_2B_OUTPUT:  # Return number represented by byte data
            data = self._wait_for_response(node,
                                           Packet.DATA_RESPONSE,
                                           Packet.DATA_REQUEST,
                                           following=bytes([
                                               (payload.value << 4) + index
                                           ]),
                                           count=4,
                                           timeout=timeout)[1:]
            return int((data[0] << 8) + data[1])
        elif payload == Node.Payload.BYTE_OUTPUT:  # Return raw bytes
            return self._wait_for_response(node,
                                           Packet.DATA_RESPONSE,
                                           Packet.DATA_REQUEST,
                                           following=bytes([
                                               (payload.value << 4) + index
                                           ]),
                                           timeout=timeout)[1:]

    def send_data(self, node, payload, data, index=0, timeout=None):
        """Send data to a node supporting data sinking.

        Args:
            node (Node): Node to send data to.
            payload (Node.Payload): Payload type of data to send.
            data: Data to be sent to device, type dependant on payload.
            index (int): Address of payload on node if multiple available.
        """
        if type(node) != Node:  # Check node is a valid Node
            raise TypeError('Invalid node.')
        if type(payload
                ) != Node.Payload:  # Check payload is a valid Node.Payload
            raise TypeError('Invalid IO payload.')
        if type(index) != int:
            raise TypeError('Invalid index.')
        if payload not in (Node.Payload.DIGITAL_INPUT, Node.Payload.BYTE_INPUT,
                           Node.Payload.INT_1B_INPUT,
                           Node.Payload.INT_2B_INPUT):
            raise ValueError('Cannot send data to a source node.')
        if index < 0 or index > 15:
            raise ValueError('Index out of bounds (0-15).')
        if payload == Node.Payload.BYTE_INPUT:
            self._xbee.tx(
                dest_addr_long=node.long_addr,
                data=bytes(
                    [Packet.SET_REQUEST.value,
                     (payload.value << 4) + index]) + data)
        elif payload == Node.Payload.INT_1B_INPUT:
            if type(data) != int:
                raise TypeError('Invalid data type for INT_1B_Input.')
            if data < 0 or data > 255:
                raise ValueError('Data out of bounds (0-255).')
            self._xbee.tx(dest_addr_long=node.long_addr,
                          data=bytes([
                              Packet.SET_REQUEST.value,
                              (payload.value << 4) + index, data
                          ]))
        elif payload == Node.Payload.INT_2B_INPUT:
            if type(data) != int:
                raise TypeError('Invalid data type for INT_2B_Input.')
            if data < 0 or data > 65535:
                raise ValueError('Data out of bounds (0-65535).')
            self._xbee.tx(dest_addr_long=node.long_addr,
                          data=bytes([
                              Packet.SET_REQUEST.value,
                              (payload.value << 4) + index, data >> 8,
                              data & 255
                          ]))
        elif payload == Node.Payload.DIGITAL_INPUT:
            if type(data) not in (list, tuple) or len(data) != 8:
                raise ValueError(
                    "Data is not in correct format for specified payload type."
                )
            out = 0
            for i in reversed(range(0, 8)):
                if type(data[i]) != bool:
                    raise ValueError(
                        "Data is not in correct format for specified payload type."
                    )
                if data[i] == True:
                    out += 1 << i
            print(out)
            self._xbee.tx(dest_addr_long=node.long_addr,
                          data=bytes([
                              Packet.SET_REQUEST.value,
                              (payload.value << 4) + index, out
                          ]))
        logger.info('Waiting for ACK after having sent data')
        self._wait_for_response(node,
                                Packet.CTRL_ACK,
                                Packet.SET_REQUEST,
                                following=bytes([Packet.SET_REQUEST.value]),
                                timeout=timeout)

    @staticmethod
    def convert_payload(payload, data):
        if payload == Node.Payload.BYTE_INPUT:
            return bytes([data])
Пример #10
0
class ZigbeeSerial:
    def __init__(self,
                 rx_queue: Queue,
                 tx_queue: Queue,
                 port='/dev/ttyS0',
                 baudrate=9600):
        self.ser = serial.Serial(port=port, baudrate=baudrate)

        # And begin listening for packets
        self.xbee = ZigBee(self.ser,
                           escaped=True,
                           callback=self.zigbee_callback)

        # Store the reference to the queues
        self.rx_queue = rx_queue
        self.tx_queue = tx_queue

        # After the serial port has been opened then configure the ZigBee module
        self.set_api_mode()
        self.set_as_coordinator()

    def __del__(self):
        print("Closing serial")

        if hasattr(self, 'ser'):
            self.ser.close()

    def set_api_mode(self):
        """
        Set the attached zigbee module to API mode so that it will work with the ZigBee module
        """

        # Enter AT command mode
        print("+++")
        self.ser.write(b"+++")
        # self.print_serial(3)
        # Reset the module
        print("Reset Module")
        self.ser.write(b"ATRE\r\n")
        # self.print_serial(3)
        # Set the module into API mode with escaping
        print("Set API mode to 2")
        self.ser.write(b"ATAP 2\r\n")
        # self.print_serial(3)
        # Write the settings to the module
        print("Write settings")
        self.ser.write(b"ATWR\r\n")
        # self.print_serial(3)
        print("Drop out of command mode")
        self.ser.write(b"ATCN\r\n")
        # self.print_serial(3)

    def set_as_coordinator(self):
        """
        Since this code is to be run on the base station only we can assume that
        this zigbee module will be the coordinator and we can set it as such
        """

        # Set the module network ID
        print("Setting network ID")
        self.xbee.at(command=b'ID', parameter=b'\xbe\xef')
        # print(self.xbee.wait_read_frame())
        print("Network ID set to")
        self.xbee.at(command=b'ID')
        # print(self.xbee.wait_read_frame())

        # Set this module as the Non-Routing Coordinator
        print("Setting module type")
        self.xbee.at(command=b'CE', parameter=b'3')
        # print(self.xbee.wait_read_frame())
        print("Module set as ")
        self.xbee.at(command=b'CE')
        # print(self.xbee.wait_read_frame())

    def zigbee_callback(self, data):
        """
        We will need two things from the data every time. First is the long address and the second is the rf_data.
        Anything that was received over the serial connection will be slightly parsed and then sent to the queue.
        """

        print('zigbee_callback')

        # The data will only contain source_addr_long when it comes from an external zigbee, and not a setup command.
        if 'source_addr_long' in data:
            # Decode the source address
            source_address = binascii.hexlify(
                data['source_addr_long']).decode()
            print(source_address)

            # Take the received rf data, decode it as UTF-8, remove the \n from the end of the string and split on tabs.
            print(data['rf_data'])
            print(data['rf_data'].decode())
            parsed_data = data['rf_data'].decode()[:-1].split("\t")
            print(parsed_data)

            self.rx_queue.put({
                'address': source_address,
                'data': parsed_data,
            })
        else:
            # If this is a setup command then just print the data.
            print(data)

    def send_packet(self, address, body):
        self.xbee.send('tx',
                       dest_addr_long=bytearray.fromhex(address),
                       data=body.encode('UTF-8'))
Пример #11
0
#! /usr/bin/python

# Import and init an XBee device
from model import *
from xbee import ZigBee



if __name__ == '__main__':
    srlc = serial.Serial('COM7', 9600)
    xbc = ZigBee(srlc)
    # srle = serial.Serial('COM5', 9600)
    # xbe = XBee(srle)
    a = b'ND'
    xbc.at(command=bytes('ND', encoding='utf-8'))

    resc1 = xbc.wait_read_frame()
    print(resc1)
    resc2 = xbc.wait_read_frame()
    print(resc2)
    xbc.remote_at(
        dest_addr=b'\x56\x78',
        command=b'D2',
        parameter=b'\x04')

    xbc.remote_at(
        dest_addr=b'\x56\x78',
        command=b'WR')

    # Use an XBee 802.15.4 device
    # To use with an XBee ZigBee device, replace with:
Пример #12
0
class XBeeInterface(object):
    """
    Interfaces between an XBee connected through a serial port and messages
    passed through stdin/stdout. Uses a simple JSON protocol to encode message
    parameters.
    """
    def __init__(self, port, baud, escaped):

        self.serial_port = Serial(port, baud)
        self.xbee = ZigBee(self.serial_port, escaped=escaped)

        # Reopen stdin/stdout in line-buffered mode
        self.stdin = os.fdopen(sys.stdin.fileno(), 'r', 1)
        self.stdout = os.fdopen(sys.stdout.fileno(), 'w', 1)

        # Associate each file descriptor with handler methods
        self.handlers = {
            self.serial_port.fileno(): (self.read_frame, self.on_frame),
            self.stdin.fileno(): (self.read_message, self.on_message)
        }

        # Turn on non-blocking IO
        for fd in self.handlers.keys():
            fcntl.fcntl(fd, fcntl.F_SETFL, os.O_NONBLOCK)

    def run(self):
        # Send an AT command to trigger a response from the module
        self.xbee.at(command='NI')
        response = self.xbee.wait_read_frame()
        log.info('Network identifier is "%s"', response['parameter'])

        while True:
            # do non-blocking reading from stdin and serial port
            r, w, x = select.select(self.handlers.keys(), [], [])

            for fd in r:
                read_handler, data_handler = self.handlers[fd]
                data = read_handler()

                # read handlers return None if message is gimped
                if data is not None:
                    data_handler(data)


    def read_frame(self):
        """ Read an entire frame from the serial connection and return it """
        try:
            return self.xbee.wait_read_frame()
        except ValueError as e:
            log.warning('error in packet data: %s', e)
            return None
        except SerialException as e:
            log.error('error reading serial frame: %s', e)
            raise IOError("Error reading from serial port")

    def read_message(self):
        """ Read a line from stdin and parse it as JSON """
        try:
            line = self.stdin.readline()
            return json.loads(line)
        except ValueError as e:
            log.error('error decoding message: %s', e)
            return None

    def json_message(self, data):
        """ Write a JSON string to stdout, using latin1 encoding to keep binary
        data intact """
        json_str = json.dumps(data, encoding='latin1')
        self.stdout.write(json_str + '\n')

    def on_message(self, message):
        log.info('Message received from stdin: %s', message)

        try:
            # delegate to another method specified by action
            action = '_'.join(('do', message['action']))
            if not hasattr(self, action):
                return log.error('Unknown action "%s"', message['action'])
            getattr(self, action)(message)
        except KeyError as e:
            return log.error('Message is missing "%s"', e.message)


    def do_send(self, message):
        """ Sends a transmit request to the module """
        # encode as latin1 to get back byte string
        address, data, frame_id = (
                message['address'].encode('latin1'),
                message['data'].encode('latin1'), 
                message.get('frame_id', u'\x01').encode('latin1'))

        try:
            self.xbee.tx(data=data, frame_id=frame_id,
                    dest_addr_long=address, dest_addr='\xFF\xFE')
        except Exception as e:
            return log.error('Failed to send transmit request: %s', e)


    def do_discover(self, message):
        frame_id = message.get('frame_id', u'\x01').encode('latin1')
        self.xbee.at(command='ND', frame_id=frame_id)
            

    def on_frame(self, frame):
        log.debug('Frame received from device: %s', frame)
        try:
            event = '_'.join(('on_frame', frame['id']))
            getattr(self, event)(frame)
        except (AttributeError, KeyError):
            log.warning('unhandled frame: %s', frame)

    def on_frame_rx(self, frame):
        log.info('Received message from %s/%s', hexify(frame['source_addr_long']),
                hexify(frame['source_addr']))
        self.json_message(frame)

    def on_frame_tx_status(self, frame):
        log.info('Transmit status for frame %s: %s', frame['frame_id'],
                'success' if frame['deliver_status'] == '\x00' else 'failure')
        self.json_message(frame)

    def on_frame_at_response(self, frame):
        log.info('AT response for frame %s: "%s"', 
                frame['frame_id'], frame['parameter'])
        self.json_message(frame)
Пример #13
0
from serial import Serial
from xbee import ZigBee

if __name__ == "__main__":
    port = Serial("COM5", 9600, timeout=3)
    print("Port set up")
    my_device = ZigBee(port)
    print("Device created")
    while True:
        print("In loop")
        dat = my_device.wait_read_frame()
        dat = my_device.at(command=b'DB')
        print("After wait")
        print(dat)


Пример #14
0
			accesslock.release()
			print "device added to list...."
			print DeviceList
	elif data['id']=="rx":
		rx_data = data['rf_data']
		NetworkInfo[data['source_addr_long']].insert(2,rx_data)
		print NetworkInfo[data['source_addr_long']][0] + " sent to co-ordinator: " + NetworkInfo[data['source_addr_long']][2]
	elif DEBUG:
		print data
	return 0

zb = ZigBee(ser,callback=msg_pack)

#---Zigbee Node ping----------
print "Acquiring Node addresses..."
zb.at(command="ND")

def plotwaypoints():
	writehtml = open('plot_waypoints_gmaps.html','w')
	node_num = 0
	for key in NetworkInfo.keys():
		plot_data = NetworkInfo[key][2].split(",")
		nodes.append([NetworkInfo[key][0],plot_data[0],plot_data[1],node_num])
		node_num+=1
	print str(nodes)
	message = """
<!DOCTYPE html>
	<html> 
	<head> 
		<meta http-equiv="content-type" content="text/html; charset=UTF-8" /> 
  		<title>Google Maps Multiple Markers</title> 
Пример #15
0
class XBeeSerial:
    def __init__(self, port='/dev/ttyS0', baudrate=9600):
        self.ser = serial.Serial(port=port, baudrate=baudrate)
        self.xbee = ZigBee(self.ser, escaped=True)

        self.set_api_mode()
        self.set_as_coordinator()

    def __del__(self):
        print("Closing serial")

        if hasattr(self, 'ser'):
            self.ser.close()

    def set_api_mode(self):
        # Enter AT command mode
        self.ser.write(b"+++")
        self.print_serial(3)
        # Reset the module
        print("Reset Module")
        self.ser.write(b"ATRE\r\n")
        self.print_serial(3)
        # Set the module into API mode with escaping
        print("Set API mode to 2")
        self.ser.write(b"ATAP 2\r\n")
        self.print_serial(3)
        # Write the settings to the module
        print("Write settings")
        self.ser.write(b"ATWR\r\n")
        self.print_serial(3)
        print("Drop out of command mode")
        self.ser.write(b"ATCN\r\n")
        self.print_serial(3)

    def set_as_coordinator(self):
        # Set the module network ID
        print("Setting network ID")
        self.xbee.at(command=b'ID', parameter=b'\xbe\xef')
        print(self.xbee.wait_read_frame())
        print("Network ID set to")
        self.xbee.at(command=b'ID')
        print(self.xbee.wait_read_frame())

        # Set this module as the Non-Routing Coordinator
        print("Setting module type")
        self.xbee.at(command=b'CE', parameter=b'3')
        print(self.xbee.wait_read_frame())
        print("Module set as ")
        self.xbee.at(command=b'CE')
        print(self.xbee.wait_read_frame())

    def print_serial(self, bytes):
        self.ser.flush()
        time.sleep(.1)
        buffer_bytes = self.ser.in_waiting
        if buffer_bytes == 0:
            print(self.ser.read(bytes))
        else:
            print(self.ser.read(buffer_bytes))

    def wait_poll_frame(self):
        data = self.xbee.wait_read_frame()
        decoded_data = data['rf_data'].decode("utf-8")
        parsed_data = decoded_data.replace('\n', '').split('\t')
        if parsed_data[0] == '0':
            return RegistrationRequest(parsed_data)
Пример #16
0
import serial.tools.list_ports


#PORT = '/dev/ttyUSB0'
BAUD_RATE = 9600

ports = list(serial.tools.list_ports.comports())
for p in ports:
    # The SparkFun XBee Explorer USB board uses an FTDI chip as USB interface
    if "FTDIBUS" in p[2]:
        print "Found possible XBee on " + p[0]
        if not portfound:
            portfound = True
            portname = p[0]
            print "Using " + p[0] + " as XBee COM port."
        else:
            print "Ignoring this port, using the first one that was found."
 
if portfound:
    ser = serial.Serial(portname, 9600)
else:
    sys.exit("No serial port seems to have an XBee connected.")

ser = serial.Serial(PORT, BAUD_RATE)
xbee = ZigBee(ser=ser, escaped=True)



xbee.at(command="AT")

print xbee.wait_read_frame()
Пример #17
0
        current_file.write(current_data)
        current_file.write('\n')
        current_file.close()
    reads = reads+1
    print ("Recieved data: {0}".format(reads))

#-----Scheduler----------
SchedDataCollect = Scheduler()
#------------------------

if __name__ == '__main__':
    # Code to be executed when the script is called directly
    while packets.qsize() > 0:
        newPacket = packets.get_nowait()
    # Send ND command - responses will create a list of addresses
    xbee.at(command=b'ND')

    numReaders = int(raw_input("How many readers?"))
    while len(XBeeID) != numReaders:
        try:
            if packets.qsize() > 0:
                newPacket = packets.get_nowait()
                handlePacket(newPacket)
        except KeyboardInterrupt:
            break
    
    # Ask for specific file names for each XBee ID:
    for x in range(0,len(XBeeID)):
        XBeeFilenames.append(raw_input("Identifier {0} filename:".format(XBeeID[x])))
        # Change save_file to the file destination for your server
        save_file = '/media/usbhdd/'
Пример #18
0

#sends data to xbee address
def sendData(address, datatosend):
    zb.send('tx', dest_addr_long=address, dest_addr=UNKNOWN, data=datatosend)


def recvData(data):
    print data


zb = ZigBee(ser)

#test data sending method
ack = '0013A2004098DA02'
while True:
    try:
        sendData(WHERE, dataString)
        time.sleep(0)

    except KeyboardInterrupt:
        break

    zb.at(frame_id='A', command='MY')
    reply = zb.wait_read_frame()
    print(reply)

    # print(zb.wait_read_frame())

zb.halt()
ser.close()
Пример #19
0
import glob
import signal
import serial
from xbee import ZigBee


def signal_shutdown(signum, frame):
    xbee.halt()
    ser.close()

# Halt XBee and closer serial upon SIGINT (Ctrl-C)
signal.signal(signal.SIGINT, signal_shutdown)

SERIALPORT = glob.glob('/dev/tty.usbserial*')[0]
ser = serial.Serial(SERIALPORT, 9600)
xbee = ZigBee(ser)

# Set `Node Discovery Timeout` to X * 100ms
xbee.send('at', frame='A', command='NT', parameter='\xFF')
xbee.at(command='ND')

while True:
    response = xbee.wait_read_frame()
    if ('command' in response) and (response['command'] == 'ND'):
        print response
        print response['parameter']['node_identifier']
        break


signal_shutdown(0, None)
Пример #20
0
short_int = eval(config.get('node','short_addr'))
short_daddr = pack(">H", short_int)
long_daddr = pack('>Q',eval(config.get('node','long_addr'))) # set 64-bit address here

print "parsed short_daddr=%s\n" % repr(short_daddr)
print "parsed long_daddr=%s\n" % repr(long_daddr)


ser = serial.Serial(config.get('modem', 'port'), 57600)
xb = ZigBee(ser,callback=cb,escaped=True,start_callback=scb)
xb.start()



print xb.at(command='ND')

if 0:
    while True:
        print "one"
        for x in range(0xFF):
            data = pack('BBBB', 0, x,x,x)
            xb.tx( dest_addr = short_daddr , dest_addr_long = long_daddr, data = data )
            time.sleep(0.1)

if 0:
    print "foo"
    data = pack('BBBB', 0, 0xff,0xff,0xff)
    xb.tx( dest_addr = short_daddr, dest_addr_long = long_daddr, data = data )

Пример #21
0
xb.remote_at(command='D2', parameter=byte(0x02), dest_addr_long=dest)
wait()

xb.remote_at(command='D3', parameter=byte(0x02), dest_addr_long=dest)
wait()

# wiki says to enable digital input on the battery monitoring pin
xb.remote_at(command='P1', parameter=byte(0x03), dest_addr_long=dest)
wait()


# set up sleep

# set child timeout on local router (3*SP*SN)
xb.at(command='SP', parameter=short(0x03e8))
wait()
xb.at(command='SN', parameter=short(0x60))
wait()

# set power level (0 -8dBm,  1 -4 dBm, 2 -2 dBm, 3 -0 dBm, 4 +2 dBm)
xb.remote_at(command='PL', parameter=byte(0x04), dest_addr_long=dest)
wait()

# in units of 10ms
# range of 0x20 - 0xAF0
#xb.remote_at(command='SP', parameter=short(0x03e8), dest_addr_long=dest)
xb.remote_at(command='SP', parameter=short(0x03e8), dest_addr_long=dest)
#xb.remote_at(command='SP', parameter=b'\x07\xd0', dest_addr_long=dest)
wait()
# number of sleep periods (sleep = SP * SN)
Пример #22
0
import serial
from xbee import XBee, ZigBee

serial_port = serial.Serial('/dev/ttyUSB0', 9600)
xbee = ZigBee(serial_port)

while True:
    try:
        xbee.at(command='ab')
        xbee.at(command='bc')
        xbee.at(command='cd')
        xbee.at(command='c1')
        xbee.at(command='!$')
        xbee.at(command=' d')
        xbee.at(command='|d')
        xbee.at(command=bytes([0x13, 0x8F]))
        # xbee.send('at', frame_id='B', command='DL')

    except KeyboardInterrupt:
        break

serial_port.close()
Пример #23
0
class handler(LoggerMixin, object):
    port = None
    nodes_by_identifier = {}
    nodes_by_shortaddr = {}
    xb = None
    new_node_callbacks = []
    last_discovery = 0

    def __init__(self, port, *args, **kwargs):
        self.port = port
        self.xb = ZigBee(self.port,
                         callback=self.xbee_callback,
                         error_callback=self.error_callback,
                         escaped=False)
        super().__init__(*args, **kwargs)
        self.discover_nodes()

    @log_exceptions
    def xbee_callback(self, *args, **kwargs):
        self.logger.debug("args: {} kwargs: {}".format(args, kwargs))
        packet = args[0]

        node_discovery_info = None
        if (packet['id'] == 'at_response' and packet['command'] == b'ND'):
            node_discovery_info = packet['parameter']

        if (packet['id'] == 'node_id_indicator'):
            node_discovery_info = packet
            node_discovery_info['node_identifier'] = packet['node_id']

        if (node_discovery_info and 'node_identifier' in node_discovery_info
                and 'source_addr' in node_discovery_info
                and 'source_addr_long' in node_discovery_info):
            # Node discovery packet
            node = XbeeNode(
                self.xb,
                short_addr=node_discovery_info['source_addr'],
                long_addr=node_discovery_info['source_addr_long'],
                node_identifier=node_discovery_info['node_identifier'],
                logger_name=self.logger_name)
            self.nodes_by_identifier[node.node_identifier] = node
            sa_hex = binascii.hexlify(node.short_addr)
            self.nodes_by_shortaddr[sa_hex] = node

            self.logger.info("New node {} at 0x{}".format(
                node.node_identifier, sa_hex))
            # Trigger callbacks registered for new nodes
            for cb in self.new_node_callbacks:
                cb(node)

        if packet['id'] == 'rx':
            # Trigger node rx callbacks
            sa_hex = binascii.hexlify(packet['source_addr'])
            if sa_hex not in self.nodes_by_shortaddr:
                self.logger.info(
                    "Got message from unkown node {}".format(sa_hex))
                if time.time() - self.last_discovery > 5:
                    self.logger.debug("Triggering new node discovery")
                    self.discover_nodes()
            else:
                self.nodes_by_shortaddr[sa_hex].rx(packet)

    @log_exceptions
    def error_callback(self, *args):
        self.logger.error("Got error args: {}".format(args))
        try:
            raise args[0]
        except Exception:
            self.logger.exception("Raised exception via callback")

    @log_exceptions
    def quit(self, *args, **kwargs):
        self.xb.halt()
        self.port.close()

    @log_exceptions
    def discover_nodes(self):
        self.last_discovery = time.time()
        self.xb.at(command=b'ND')

    @log_exceptions
    def ping_nodes(self):
        """Ping each known node to make sure it's still alive, if not mark it dead and remove from our list"""
        # TODO: Implement
        pass

    @log_exceptions
    def tx_all(self, *args):
        for nodeid in self.nodes_by_identifier.keys():
            self.logger.debug("Sending to {}".format(nodeid))
            self.nodes_by_identifier[nodeid].tx(*args)
        self.logger.debug("All sent")

    @log_exceptions
    def tx_string_all(self, *args):
        for nodeid in self.nodes_by_identifier.keys():
            self.logger.debug("Sending to {}".format(nodeid))
            self.nodes_by_identifier[nodeid].tx_string(*args)
        self.logger.debug("All sent")
Пример #24
0
            'command': 'AO',
            'parameter': b'\x03'
        }
    },
}

if len(sys.argv) < 2:
    print "Missing command argument {}".format(commands.keys())

else:
    action = sys.argv[1]
    if action in commands:
        XBEE_PORT = '/dev/tty.usbserial-A1014P7W'
        XBEE_BAUD = 9600
        ser = serial.Serial(XBEE_PORT, XBEE_BAUD)
        zb = ZigBee(ser=ser,
                    callback=receive_message,
                    error_callback=xbee_error,
                    escaped=True)

        print "Running", action, "...."
        for name, command in commands[action].iteritems():
            print "Sending", name
            zb.at(**command)
            time.sleep(3)

        zb.halt()
        ser.close()
    else:
        print "Invalid command '{}'".format(action)
Пример #25
0
class handler(object):
    port = None
    nodes_by_identifier = {}
    nodes_by_shortaddr = {}
    xb = None

    def xbee_callback(self, x):
        print "DEBUG: x=%s" % repr(x)
        
        node_discovery_info = None
        
        if (    x['id'] == 'at_response'
            and x['command'] == 'ND'):
            # Node discovery response
            node_discovery_info = x['parameter']

        if (x['id'] == 'node_id_indicator'):
            node_discovery_info = x
            node_discovery_info['node_identifier'] = x['node_id']

        if (    node_discovery_info
            and node_discovery_info.has_key('node_identifier')
            and node_discovery_info.has_key('source_addr')
            and node_discovery_info.has_key('source_addr_long')):
            # Node discovery packet
            node = XbeeNode(self.xb, short_addr=node_discovery_info['source_addr'], long_addr=node_discovery_info['source_addr_long'], node_identifier=node_discovery_info['node_identifier'])
            self.nodes_by_identifier[node.node_identifier] = node
            sa_hex = binascii.hexlify(node.short_addr)
            self.nodes_by_shortaddr[sa_hex] = node
            print "New node %s at 0x%s" % (node.node_identifier, sa_hex)

    def start_callback(self, x):
        print "DEBUG: start_callback, x=%s" % repr(x)
        pass

    def __init__(self, port):
        self.xb = ZigBee(port,callback=self.xbee_callback,escaped=True,start_callback=self.start_callback)
        try:
            self.xb.start()
        except Exception:
            # TODO: check the real exception threading throws up
            pass
        self.discover_nodes()

    def discover_nodes(self):
        self.xb.at(command='ND')

    def ping_nodes(self):
        """Ping each known node to make sure it's still alive, if not remove from node list (or maybe just mark dead somehow)"""
        pass        

    def tx_all(self, *args):
        for nodeid in self.nodes_by_identifier.keys():
            print "Sending to %s" % nodeid
            self.nodes_by_identifier[nodeid].tx(*args)
        print "All sent"

    def tx_string_all(self, *args):
        for nodeid in self.nodes_by_identifier.keys():
            print "Sending to %s" % nodeid
            self.nodes_by_identifier[nodeid].tx_string(*args)
        print "All sent"
Пример #26
0
once = 1
while True:
    try:

        # xbee.tx(dest_addr=pan,dest_addr_long=Destination, data='Hello World')
        # xbee.remote_at(dest_addr=MY,dest_addr_long=ADR, command='MY',parameter=None)
        # time.sleep(5) \x
        # xbee.send("remote_at",frame_id='A', command='MY')

        #
        # xbee.tx(dest_addr='\xbf\x0c',dest_addr_long='\x00\x13\xa2\x00\x40\x92\xd8\x6a', data='Hello World')
        if once == 1:
            print "Discovering Nodes"
            # xbee.at(frame_id='A', command='MY')
            # xbee.at(frame_id='A', command='ID')
            xbee.at(frame_id="D", command="ND")

            # xbee.remote_at(dest_addr='\xbf\x0c',command='IR',parameter='\xff')
            # xbee.remote_at(dest_addr='\xbf\x0c',command='V+',parameter='\xff')
            # xbee.remote_at(dest_addr='\xbf\x0c',command='MY',parameter=None)

            once = 0
            time.sleep(5)
            print "Sending RAT"
            # xbee.tx(dest_addr=MY2,dest_addr_long=ADR2, data='Hello World')
            xbee.remote_at(dest_addr=MY, dest_addr_long=ADR, command="IS")
            # time.sleep(1)
            xbee.remote_at(dest_addr=MY, dest_addr_long=ADR, command="IR", parameter="\xFF")
            # time.sleep(1)
            xbee.remote_at(dest_addr=MY, dest_addr_long=ADR, command="IR", parameter="\x00")
            print "Done"
Пример #27
0
#set serial communication with xbee
ser = serial.Serial('/dev/cu.usbserial-AD025EOA', 9600)

#python xbee api doesn't implmenet timeout on read
#to work around this, set signal alarm to trigger timout

#set signal for timeout
signal.signal(signal.SIGALRM, exceptionHandler)

#create instance of zigbee
xbee = ZigBee(ser)

hb = 0x00
lb = 0x00

xbee.at(command='ID')
ret = xbee.wait_read_frame()
print "Current ID"
print ret
exit()
fd = open("scanlog.txt", "w+")

while 1:
    if hb > 0xFF:
        break
    rb = lb << 8 | hb
    fd.write("[*] pan id 0x%02x%02x\n" % (hb,lb))
    try:    
        #change pan id and query id command with argument 
        arg = struct.pack('h', rb)
        xbee.at(command='ID', parameter=arg)
Пример #28
0
class handler(object):
    port = None
    nodes_by_identifier = {}
    nodes_by_shortaddr = {}
    xb = None

    def xbee_callback(self, x):
        print "DEBUG: x=%s" % repr(x)

        node_discovery_info = None

        if (x['id'] == 'at_response' and x['command'] == 'ND'):
            # Node discovery response
            node_discovery_info = x['parameter']

        if (x['id'] == 'node_id_indicator'):
            node_discovery_info = x
            node_discovery_info['node_identifier'] = x['node_id']

        if (node_discovery_info
                and node_discovery_info.has_key('node_identifier')
                and node_discovery_info.has_key('source_addr')
                and node_discovery_info.has_key('source_addr_long')):
            # Node discovery packet
            node = XbeeNode(
                self.xb,
                short_addr=node_discovery_info['source_addr'],
                long_addr=node_discovery_info['source_addr_long'],
                node_identifier=node_discovery_info['node_identifier'])
            self.nodes_by_identifier[node.node_identifier] = node
            sa_hex = binascii.hexlify(node.short_addr)
            self.nodes_by_shortaddr[sa_hex] = node
            print "New node %s at 0x%s" % (node.node_identifier, sa_hex)

    def start_callback(self, x):
        print "DEBUG: start_callback, x=%s" % repr(x)
        pass

    def __init__(self, port):
        self.xb = ZigBee(port,
                         callback=self.xbee_callback,
                         escaped=True,
                         start_callback=self.start_callback)
        try:
            self.xb.start()
        except Exception:
            # TODO: check the real exception threading throws up
            pass
        self.discover_nodes()

    def discover_nodes(self):
        self.xb.at(command='ND')

    def ping_nodes(self):
        """Ping each known node to make sure it's still alive, if not remove from node list (or maybe just mark dead somehow)"""
        pass

    def tx_all(self, *args):
        for nodeid in self.nodes_by_identifier.keys():
            print "Sending to %s" % nodeid
            self.nodes_by_identifier[nodeid].tx(*args)
        print "All sent"

    def tx_string_all(self, *args):
        for nodeid in self.nodes_by_identifier.keys():
            print "Sending to %s" % nodeid
            self.nodes_by_identifier[nodeid].tx_string(*args)
        print "All sent"
Пример #29
0
class XbeeSerial:
	XbeeModules = OrderedDict()
	#Cues = {}
	#fireQueue = Queue.Queue(1)
	ModulesLock = threading.Lock()
	#CuesLock = threading.Lock()
	#txEvent = threading.Event()
	def __init__(self, ser):
		#self.txEvent.set()
		#f = open(cueFile, 'r')
		#for line in f:
			#line = line.strip().split(',')
			#if len(line) == 2:
				#self.Cues[int(line[1])] = {'name': line[0], 'adc': 0}

		#f = open(XbeeFile, 'r')
		#for line in f:
			#line = line.strip().split(',')
			#if len(line) == 2:
				#line[0] = struct.pack('>Q', int(line[0], 16))
				#line[1] = struct.pack('>H', int(line[1], 16))
				#self.XbeeModules.append((line[0], line[1]))
		self.xbee = ZigBee(ser, callback=self.callback_data)
		#t = threading.Thread(target = self.loop)
		#t.start()

	#def loop(self):
		#moduleStatus = 0
		#while True:
			#self.txEvent.wait(3)
			#try:
				#fireCue = self.fireQueue.get(False)
			#except Queue.Empty:
				#fireCue = -1
			#if fireCue < 0:
				#pass
				#if moduleStatus >= len(self.XbeeModules):
				#	moduleStatus = 0
				#self.updateStatus(moduleStatus)
				#moduleStatus += 1
			#else:
				#self.fire(fireCue)

	def initialize(self):
		with self.ModulesLock:
			self.XbeeModules = OrderedDict()
		self.xbee.at(command = 'ND')
		return {'message': 'Initializing...'}

	def getBoardInfo(self, addr_long, addr):
		#print('Getting board info {0} {1}'.format(addr_long, addr))
		self.tx_addr(addr_long, addr, 'i')

	#def addFire(self, cue):
	#	self.fireQueue.put(cue)

	def fire(self, cue):
		with self.ModulesLock:
			for i, (board_id, (addr_long, addr, num_cues)) in enumerate(self.XbeeModules.iteritems()):
				if cue < num_cues:
					board = board_id
					break
				else:
					cue -= num_cues
			else:
				return

		print('%s - Fireing cue: %d on board: %d' % (datetime.now(), cue, board))
		self.tx_board(board, 'f%c' % cue)

	#def getStatus(self):
		#with self.CuesLock:
			#return self.Cues

	def getStatus(self):
		cues=[]
		with self.ModulesLock:
			for i, (board_id, (addr_long, addr, num_cues)) in enumerate(self.XbeeModules.iteritems()):
				for cue in range(0, num_cues):
					cues.append({'name': 'Board: %d, Cue: %d' % (board_id, cue), 'adc': 500});
		return cues

	def tx_board(self, board, data):
		with self.ModulesLock:
			self.tx_addr(self.XbeeModules[board][0], self.XbeeModules[board][1], data)

	def tx_addr(self, addr_long, addr, data):
		#self.txEvent.clear()
		self.xbee.tx(dest_addr_long = addr_long, dest_addr = addr, data = data)

	def callback_data(self, data):
		if data['id'] == 'rx':
			if len(data['rf_data']) > 0:
				if data['rf_data'][0] == 'I' and len(data['rf_data']) == 3:
					#print('board_id: {0} 64: {1} 16: {2} cues: {3}'.format(ord(data['rf_data'][1]), data['source_addr_long'], data['source_addr'], ord(data['rf_data'][2])))
					with self.ModulesLock:
						self.XbeeModules[ord(data['rf_data'][1])] = (data['source_addr_long'], data['source_addr'], ord(data['rf_data'][2]))
						self.XbeeModules = OrderedDict(sorted(self.XbeeModules.items()))
					#print(self.XbeeModules)
				#else:
					#print(data)
			#self.txEvent.set()
			#for (i, module) in enumerate(self.XbeeModules):
				#if data['source_addr_long'] == module[0] and data['source_addr'] == module[1]:
					#moduleNum = i
					#break;
			#else:
				#print('%s - unknown module' % datetime.today())
				#return
			#if data['rf_data'][0] != '[':
				#status = data['rf_data'].split(',')
				#with self.CuesLock:
					#for i in range(0, len(status), 2):
						#cue = int(status[i]) + 20 * moduleNum
						#if cue in self.Cues:
							#self.Cues[cue]['adc'] = status[i + 1]
				#print('%s - status from module %d' % (datetime.now(), moduleNum))
			#else:
				#print('%s - response from module %d' % (datetime.now(), moduleNum))
		elif data['id'] == 'at_response' and data['command'] == 'ND':
			#print(data)
			if data['parameter']['device_type'] == '\x01':
				self.getBoardInfo(data['parameter']['source_addr_long'], data['parameter']['source_addr'])