Exemplo n.º 1
0
def dispatch_init(ser):
    """
    Initialize a dispatcher and register rx_data_handler.
    
    Args:
        ser(serial.Serial): a serial interface object.
        
    Returns:
        xbee.helpers.dispatch.Dispatch: an XBee dispatcher object.
    """
    # --------------------------------------------------------------------
    # When a Dispatch is created with a serial port, it will automatically
    # create an XBee object on your behalf for accessing the device.
    # If you wish, you may explicitly provide your own XBee:
    #
    #  xbee = XBee(ser)
    #  dispatch = Dispatch(xbee=xbee)
    #
    # Functionally, these are the same.   --Paul Malmsten
    # --------------------------------------------------------------------
    # Register the packet handlers with the dispatch:
    # The string name allows one to distinguish between mutiple registrations
    # for a single callback function.
    # The second argument is the callback function name.
    # The third argument is a function which determines whether to call its
    # associated callback when a packet arrives. It should return a boolean.
    # --------------------------------------------------------------------
    # Spawn a dispatch instance and associate it with packet id 'rx'
    dispatcher = Dispatch(ser)
    dispatcher.register("rx_data", rx_data_handler,
                        lambda packet: packet['id'] == 'rx')
    return dispatcher
Exemplo n.º 2
0
 def init_comm( self ):
   print( "initialising communication through serial port")
   self.tapped_ser = self.serial
   if self.tapSerial:
     self.tapped_ser = TappedSerial( self.serial )
   self.dispatch = Dispatch( self.tapped_ser )
   self.register_callbacks()
   self.xbee = XBee( self.tapped_ser, callback=self.dispatch.dispatch, escaped=True)
   self.xbee.name = "xbee-thread"
Exemplo n.º 3
0
 def __init__(self, serial_port, baud_rate, dispatcher, serializer):
     self.ser = serial.Serial(serial_port, baud_rate)
     self.zb = xbee.ZigBee(self.ser, escaped=True)
     self.dispatch = Dispatch(xbee=self.zb)
     self.dispatch.register('rx', self.rx_handler,
                            lambda p: p['id'] == 'rx')
     self.dispatch.register('rx_explicit', self.default_handler,
                            lambda p: p['id'] == 'rx_explicit')
     self.dispatch.register('rx_io_data_long_addr', self.default_handler,
                            lambda p: p['id'] == 'rx_io_data_long_addr')
     self.dispatch.register('tx_status', self.default_handler,
                            lambda p: p['id'] == 'tx_status')
     self.dispatch.register('status', self.default_handler,
                            lambda p: p['id'] == 'status')
     self.dispatch.register('at_response', self.at_response_handler,
                            lambda p: p['id'] == 'at_response')
     self.dispatch.register('remote_at_response', self.default_handler,
                            lambda p: p['id'] == 'remote_at_response')
     self.dispatch.register('node_id_indicator', self.default_handler,
                            lambda p: p['id'] == 'node_id_indicator')
     self.dispatcher = dispatcher
     self.serializer = serializer
Exemplo n.º 4
0
 def __init__(self, serial_port, baud_rate, dispatcher, serializer):
     self.ser = serial.Serial(serial_port, baud_rate)
     self.zb = xbee.ZigBee(self.ser, escaped=True)
     self.dispatch = Dispatch(xbee = self.zb)
     self.dispatch.register('rx', self.rx_handler, lambda p: p['id'] == 'rx')
     self.dispatch.register('rx_explicit', self.default_handler, lambda p: p['id'] == 'rx_explicit')
     self.dispatch.register('rx_io_data_long_addr', self.default_handler, lambda p: p['id'] == 'rx_io_data_long_addr')
     self.dispatch.register('tx_status', self.default_handler, lambda p: p['id'] == 'tx_status')
     self.dispatch.register('status', self.default_handler, lambda p: p['id'] == 'status')
     self.dispatch.register('at_response', self.at_response_handler, lambda p: p['id'] == 'at_response')
     self.dispatch.register('remote_at_response', self.default_handler, lambda p: p['id'] == 'remote_at_response')
     self.dispatch.register('node_id_indicator', self.default_handler, lambda p: p['id'] == 'node_id_indicator')
     self.dispatcher = dispatcher
     self.serializer = serializer
Exemplo n.º 5
0
class TestDispatch(unittest.TestCase):
    """
    Tests xbee.helpers.dispatch for expected behavior
    """
    def setUp(self):
        self.xbee = FakeXBee(None)
        self.dispatch = Dispatch(xbee=self.xbee)
        self.callback_check = CallbackCheck()

    def test_callback_is_called_when_registered(self):
        """
        After registerring a callback function with a filter function,
        the callback should be called when data arrives.
        """
        self.dispatch.register("test1", self.callback_check.call,
                               lambda data: True)
        self.dispatch.run(oneshot=True)
        self.assertTrue(self.callback_check.called)

    def test_callback_not_called_when_filter_not_satisfied(self):
        """
        After registerring a callback function with a filter function,
        the callback should not be called if a packet which does not
        satisfy the callback's filter arrives.
        """
        self.dispatch.register("test1", self.callback_check.call,
                               lambda data: False)
        self.dispatch.run(oneshot=True)
        self.assertFalse(self.callback_check.called)

    def test_multiple_callbacks(self):
        """
        Many callbacks should be called on the same packet if each
        callback's filter method is satisfied.
        """
        callbacks = []

        for i in range(0, 10):
            check = CallbackCheck()
            callbacks.append(check)
            self.dispatch.register("test%d" % i, check.call, lambda data: True)

        self.dispatch.run(oneshot=True)

        for callback in callbacks:
            if not callback.called:
                self.fail("All callback methods should be called")

    def test_callback_name_collisions_raise_valueerror(self):
        """
        If a call to register() results in attempting to register a
        callback with the same name as another callback should result
        in a ValueError exception being raised.
        """
        self.dispatch.register("test", None, None)
        self.assertRaises(ValueError, self.dispatch.register, "test", None,
                          None)
Exemplo n.º 6
0
    print "%s - %s" % (name, packet)

def at_response_handler(name, packet):
    p = ''.join('%02x' % ord(x) for x in packet['parameter'])
    print "AT - %s = %s" % (packet['command'], p)
    
def rx_handler(name, packet):
    print "RX - %s" % packet
    time.sleep(1)
    data = "PONG" if IS_HUB else "PING"
    zb.tx(dest_addr_long=packet['source_addr_long'], dest_addr=packet['source_addr'], data=data)
        

ser = serial.Serial(PORT, BAUD_RATE)
zigbee = ZigBee(ser)
dispatch = Dispatch(xbee = zigbee)
dispatch.register('rx', rx_handler, lambda p: p['id'] == 'rx')
dispatch.register('rx_explicit', default_handler, lambda p: p['id'] == 'rx_explicit')
dispatch.register('rx_io_data_long_addr', default_handler, lambda p: p['id'] == 'rx_io_data_long_addr')
dispatch.register('tx_status', default_handler, lambda p: p['id'] == 'tx_status')
dispatch.register('status', default_handler, lambda p: p['id'] == 'status')
dispatch.register('at_response', at_response_handler, lambda p: p['id'] == 'at_response')
dispatch.register('remote_at_response', default_handler, lambda p: p['id'] == 'remote_at_response')
dispatch.register('node_id_indicator', default_handler, lambda p: p['id'] == 'node_id_indicator')

zb = ZigBee(ser, callback = dispatch.dispatch, escaped = True)

print "run..."
print ""
print "current status:"
zb.send('at', command='ID')
Exemplo n.º 7
0
    print "Status Update - Status is now: ", packet['status']


def io_sample_handler(name, packet):
    print "Samples Received: ", packet['samples']


# When a Dispatch is created with a serial port, it will automatically
# create an XBee object on your behalf for accessing the device.
# If you wish, you may explicitly provide your own XBee:
#
#  xbee = XBee(ser)
#  dispatch = Dispatch(xbee=xbee)
#
# Functionally, these are the same.
dispatch = Dispatch(ser)

# Register the packet handlers with the dispatch:
#  The string name allows one to distinguish between mutiple registrations
#   for a single callback function
#  The second argument is the function to call
#  The third argument is a function which determines whether to call its
#   associated callback when a packet arrives. It should return a boolean.
dispatch.register("status", status_handler,
                  lambda packet: packet['id'] == 'status')

dispatch.register("io_data", io_sample_handler,
                  lambda packet: packet['id'] == 'rx_io_data')

# Create API object, which spawns a new thread
# Point the asyncronous callback at Dispatch.dispatch()
Exemplo n.º 8
0
class HiveSerialAPI(object):
  def __init__(self, serial_port, baudrate = 57600 ):
    #self.init_with_serial( mid, serial, libv, revision, caps)
    #self.serialOpened = False
    #self.hive = hive
    #self.serialport = serial_port
    #self.serialbaudrate = baudrate
    self.serial = serial.Serial()  # open first serial port
    self.serial.baudrate = baudrate
    self.serial.port = serial_port
    
    self.ack_cnt = 0
    self.framecnt = 1
    self.hiveMsgId = 1
    self.logAction = None
    self.verbose = False
    self.tapSerial = False
    self.open_serial_port()
    
  def init_comm( self ):
    print( "initialising communication through serial port")
    self.tapped_ser = self.serial
    if self.tapSerial:
      self.tapped_ser = TappedSerial( self.serial )
    self.dispatch = Dispatch( self.tapped_ser )
    self.register_callbacks()
    self.xbee = XBee( self.tapped_ser, callback=self.dispatch.dispatch, escaped=True)
    self.xbee.name = "xbee-thread"
    self.read_settings()
    self.coordinator_settings()
    self.read_settings()
    print( "--------------------------------" )

  #def start( self ):
    #self.xbee.start()

  def halt( self ):
    self.xbee.halt()
    self.xbee.join(1) # 1 second timeout to join thread

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

  def isRunning( self ):
    return self.xbee.is_alive()

  def isOpen( self ):
    return self.serial.isOpen()

  def open_serial_port( self ):
    print( "trying to open serial port" )
    try:
      self.serial.open()      
      #self.serial = serial.Serial( self.serialport, self.serialbaudrate )  # open first serial port
      #self.serialOpened = self.serial.isOpen()
      print( "Opening serial port", self.serial.port, self.serial.isOpen() )
    except:
      #self.serialOpened = False
      print( "could not open serial port", self.serial.port )
      print( "Please make sure your coordinator node is connected to the computer and pass in the right serial port location upon startup, e.g. \'python swpydonhive.py -s /dev/ttyUSB1\'" )
      #os._exit(1)
      #raise SystemExit
      #sys.exit()
      #raise KeyboardInterrupt

  def register_callbacks( self ):
    self.dispatch.register(
      "rfdata", 
      self.rfdata_handler,
      lambda packet: packet['id']=='rx'
    )

    self.dispatch.register(
      "status",
      self.generic_handler, 
      lambda packet: packet['id']=='status'
    )

    self.dispatch.register(
      "tx_status",
      self.txstatus_handler, 
      lambda packet: packet['id']=='tx_status'
    )

    self.dispatch.register(
      "remote_at_response", 
      self.generic_handler, 
      lambda packet: packet['id']=='remote_at_response'
    )

    self.dispatch.register(
      "at_response", 
      self.at_handler, 
      lambda packet: packet['id']=='at_response'
    )

    self.dispatch.register(
      "rx_io_data", 
      self.generic_handler,
      lambda packet: packet['id']=='rx_io_data'
    )

    self.dispatch.register(
      "rx_io_data_long", 
      self.generic_handler,
      lambda packet: packet['id']=='rx_io_data_long_addr'
    )

    self.dispatch.register(
      "rfdata_long", 
      self.generic_handler,
      lambda packet: packet['id']=='rx_long_addr'
    )

  def generic_handler( self, name, packet ):
    if self.verbose:
      print( name, packet )

  def at_handler( self, name, packet ):    
    #print( name, packet )
    if 'parameter' in packet:
        if packet['command'] == 'CH':
            print( "XBEE setting: channel", packet[ 'parameter'] )
        elif packet['command'] == 'ID':
            print( "XBEE setting: panid", packet[ 'parameter'] )
        elif packet['command'] == 'CE':
            print( "XBEE setting: coordinator enable", packet[ 'parameter'] )
        elif packet['command'] == 'AP':
            print( "XBEE setting: api mode", packet[ 'parameter'] )
        elif packet['command'] == 'MY':
            print( "XBEE setting: my address", packet[ 'parameter'] )
        elif packet['command'] == 'DH':
            print( "XBEE setting: destination high address", packet[ 'parameter'] )
        elif packet['command'] == 'DL':
            print( "XBEE setting: destination low address", packet[ 'parameter'] )
    else:
        if packet['status'] == '\x00':
            print( "XBEE setting changed", packet['command'] )
        else:
            print( "XBEE setting not changed!", packet['command'] )

  def txstatus_handler( self, name, packet ):
    if self.verbose:
      print "TXStatus Received: ", packet
    if packet['status'] == 0:
      self.ack_cnt = self.ack_cnt - 1
    elif self.verbose:
      if packet['status'] == 1:
	print( "TX, No ACK (Acknowledgement) received" )
      elif packet['status'] == 2:
	print( "TX, CCA failure" )
      elif packet['status'] == 3:
	print( "TX, Purged" )
      #0 = Success
      #1 = No ACK (Acknowledgement) received
      #2 = CCA failure
      #3 = Purged


  def rfdata_handler(self, name, packet):
    if self.verbose:
      print "RFData Received: ", packet
    if packet['rf_data'][0] == 'd' and len( packet[ 'rf_data' ] ) > 1: # minibee sending data
      self.recv_data( packet[ 'rf_data' ][1:], packet[ 'source_addr'], packet['rssi'] )
    elif packet['rf_data'][0] == 't' and len( packet[ 'rf_data' ] ) > 1: # minibee sending trigger data
      self.recv_triggerdata( packet[ 'rf_data' ][1:], packet[ 'source_addr'], packet['rssi'] )      
    elif packet['rf_data'][0] == 'e' and len( packet[ 'rf_data' ] ) > 1: # minibee sending private data
      self.recv_privatedata( packet[ 'rf_data' ][1:], packet[ 'source_addr'], packet['rssi'] )      
    elif packet['rf_data'][0] == 's' and len( packet[ 'rf_data' ] ) > 12:
      if len( packet[ 'rf_data' ] ) > 13 :
	self.parse_serial( packet[ 'rf_data' ][2:10], ord( packet[ 'rf_data' ][10] ), packet[ 'rf_data' ][11], ord( packet[ 'rf_data' ][12] ), ord( packet[ 'rf_data' ][13] ) )
      else:
	self.parse_serial( packet[ 'rf_data' ][2:10], ord( packet[ 'rf_data' ][10] ), packet[ 'rf_data' ][11], ord( packet[ 'rf_data' ][12] ), 1 )
    elif packet['rf_data'][0] == 'w' and len( packet[ 'rf_data' ] ) > 3:
        if self.verbose:
          print( "wait config", packet[ 'rf_data' ][2], packet[ 'rf_data' ][3] )
        #print( "rf - calling wait_config" )
        self.hive.wait_config( ord(packet[ 'rf_data' ][2]), ord(packet[ 'rf_data' ][3]) )
    elif packet['rf_data'][0] == 'c' and len( packet[ 'rf_data' ] ) > 6: # configuration confirmation
        #print( "rf - calling check_config" )
        self.hive.check_config( ord(packet[ 'rf_data' ][2]), ord(packet[ 'rf_data' ][3] ), [ ord(x) for x in packet[ 'rf_data' ][4:] ] )
    elif packet['rf_data'][0] == 'i' and len( packet[ 'rf_data' ] ) > 2: # info message
      nid = int( ByteToHex( packet[ 'source_addr'] ), 16 )
      self.hive.loopback( nid , [ ord(x) for x in packet[ 'rf_data' ][2:] ] )
      print( "info message",  packet, [ ord(x) for x in packet[ 'rf_data' ][2:] ] )
    elif packet['rf_data'][0] == 'p' and len( packet[ 'rf_data' ] ) > 1: # minibee sending pause message
      self.recv_paused( packet['rf_data'][1], packet[ 'source_addr'], packet['rssi'] )      
    elif packet['rf_data'][0] == 'a' and len( packet[ 'rf_data' ] ) > 1: # minibee sending active message
      self.recv_active( packet['rf_data'][1], packet[ 'source_addr'], packet['rssi'] )      
    self.hive.gotData()
    self.log_data( packet )
    
  def set_verbose( self, onoff ):
    self.verbose = onoff
    if onoff:
      print( self.serial )
      print( self.serial.portstr )       # check which port was really used

    
  def set_hive( self, hive ):
    self.hive = hive
    
  def announce( self, nodeid = 0xFFFF ):
    self.send_msg_inc( nodeid, 'A', [] );

  def closePort( self ):
    self.serial.close()

  def quit( self ):
    self.send_msg_inc( 0xFFFF, 'Q', [] );
    self.xbee.halt()
    self.xbee.join() # no timeout to join thread
    self.serial.close()
    
  def incMsgID( self ):
    self.hiveMsgId = self.hiveMsgId + 1
    if self.hiveMsgId > 255:
      self.hiveMsgId = 1

  def read_settings( self ):
    print( "querying settings" )
    if self.serial.isOpen():
        self.xbee.send('at', frame_id='0', command='CH')        
        self.xbee.send('at', frame_id='1', command='ID')        
        self.xbee.send('at', frame_id='2', command='CE')        
        self.xbee.send('at', frame_id='3', command='AP')        
        self.xbee.send('at', frame_id='4', command='MY')        
        self.xbee.send('at', frame_id='5', command='DH')        
        self.xbee.send('at', frame_id='6', command='DL')        

  def coordinator_settings( self ):
    print( "setting coordinator settings" )
    if self.serial.isOpen():
        self.xbee.send('at', frame_id='2', command='CE', parameter='\x01')
        self.xbee.send('at', frame_id='3', command='AP', parameter='\x02')        
        self.xbee.send('at', frame_id='4', command='MY', parameter='\x00')        
        self.xbee.send('at', frame_id='5', command='DH', parameter='\x00\x00\x00\x00')        
        self.xbee.send('at', frame_id='6', command='DL', parameter='\x00\x00\xff\xfa')        

  def send_me( self, ser, onoff ):
    if self.verbose:
      print( "sending bee me", ser, onoff )
    self.send_msg64( ser, 'M', [ chr(onoff) ] )

  def send_id( self, ser, nodeid, configid = 0 ):
    #print ser
    if self.verbose:
      print( "sending bee id", ser, nodeid, configid )
    self.assign_remote_my( ser, nodeid )
    if configid > 0:
      time.sleep(.02)

      datalist = []
      datalist.append( HexToByte( ser ) )
      #datalist.append( ser )
      datalist.append( chr( nodeid ) )
      datalist.append( chr( configid ) )
      self.send_msg_inc( nodeid, 'I', datalist )
    
  def send_config( self, nodeid, configuration ):
    if self.verbose:
      print( "sending configuration", configuration )
    config = [ chr(x) for x in configuration ]
    self.send_msg_inc( nodeid, 'C', config )

  def set_digital_out3( self, serial, rmmy ):
    if self.serial.isOpen():
      rfser = HexToByte( serial )
      #rfser = serial
      destaddr = ''.join( rfser )
      hrm = struct.pack('>H', rmmy)
      self.xbee.send('remote_at', 
	    frame_id='B',
	    dest_addr_long=destaddr,
	    options='\x02',
	    command='D3',
	    parameter=hrm
	    )
    #FIXME: this should be a setting or a separate osc message or something
    #self.store_remote_at64( serial )

  def set_digital_out3_short( self, beeid, rmmy ):
    if self.serial.isOpen():
      hrm = struct.pack('>H', rmmy)
      destaddr = struct.pack('>H', beeid)
      self.xbee.send('remote_at', 
	    frame_id='B',
	    dest_addr=destaddr,
	    options='\x02',
	    command='D3',
	    parameter=hrm
	    )

  def reset_minibee( self, serial ):
    if self.serial.isOpen():
      rfser = HexToByte( serial )
      #rfser = serial
      destaddr = ''.join( rfser )
      hrm = struct.pack('>H', 8 )
      self.xbee.send('remote_at', 
	    frame_id='C',
	    dest_addr_long=destaddr,
	    options='\x02',
	    command='IO',
	    parameter=hrm
	    )

  def reset_minibee_short( self, beeid ):
    if self.serial.isOpen():
      destaddr = struct.pack('>H', beeid)
      hrm = struct.pack('>H', 8 )
      self.xbee.send('remote_at', 
	    frame_id='C',
	    dest_addr=destaddr,
	    options='\x02',
	    command='IO',
	    parameter=hrm
	    )

  def restart_minibee( self, serial ):
    if self.serial.isOpen():
      rfser = HexToByte( serial )
      #rfser = serial
      destaddr = ''.join( rfser )
      hrm = struct.pack('>H', 0 )
      self.xbee.send('remote_at', 
	    frame_id='D',
	    dest_addr_long=destaddr,
	    options='\x02',
	    command='IO',
	    parameter=hrm
	    )

  def restart_minibee_short( self, beeid ):
    if self.serial.isOpen():
      destaddr = struct.pack('>H', beeid)
      hrm = struct.pack('>H', 0 )
      self.xbee.send('remote_at', 
	    frame_id='D',
	    dest_addr=destaddr,
	    options='\x02',
	    command='IO',
	    parameter=hrm
	    )

  def assign_remote_my( self, serial, rmmy ):
    if self.serial.isOpen():
      rfser = HexToByte( serial )
      #rfser = serial
      destaddr = ''.join( rfser )
      hrm = struct.pack('>H', rmmy)
      self.xbee.send('remote_at', 
	    frame_id='A',
	    dest_addr_long=destaddr,
	    options='\x02',
	    command='MY',
	    parameter=hrm
	    )
    #FIXME: this should be a setting or a separate osc message or something
    #self.store_remote_at64( serial )

  def store_remote_at64( self, serial ):
    if self.serial.isOpen():
      rfser = HexToByte( serial )
      #rfser = serial
      destaddr = ''.join( rfser )
      #hrm = struct.pack('>H', rmmy)
      self.xbee.send('remote_at', 
	    frame_id='8',
	    dest_addr_long=destaddr,
	    options='\x02',
	    command='WR'
	    #parameter=hrm
	    )

  def store_remote_at16( self, nodeid ):
    if self.serial.isOpen():
      #rfser = HexToByte( serial )
      #rfser = serial
      #destaddr = ''.join( rfser )
      hrm = struct.pack('>H', nodeid)
      self.xbee.send('remote_at', 
	    frame_id='9',
	    dest_addr=hrm,
	    options='\x02',
	    command='WR'
	    #parameter=hrm
	    )

  def create_beemsg( self, msgtype, msgid, msgdata, mid ):
    datalist = [ msgtype ]
    datalist.append( chr(msgid) )
    datalist.extend( [ chr(int(x)) for x in msgdata ] )
    return datalist

  def send_msg( self, datalistin, rmmy ):
    if self.serial.isOpen():
      self.framecnt = self.framecnt + 1
      if self.framecnt == 16:
	self.framecnt = 1
      msgid = chr( self.framecnt )
      self.ack_cnt = self.ack_cnt + 1
      datalist = []
      datalist.extend( datalistin )
      data = ''.join( datalist )
      hrm = struct.pack('>H', rmmy)
      self.xbee.send('tx',
          dest_addr=hrm,
          data=data,
          frame_id=msgid,
          options='\x02'
          )
      if self.verbose:
	print( "sending message to minibee", rmmy, hrm, data, self.ack_cnt )
    
  def send_msg_inc( self, rmmy, msgtype, datalistin ):
    if self.serial.isOpen():
      self.framecnt = self.framecnt + 1
      if self.framecnt == 16:
	self.framecnt = 1
      msgid = chr( self.framecnt )
      self.ack_cnt = self.ack_cnt + 1
      self.incMsgID()
      datalist = [ msgtype ]
      datalist.append( chr( self.hiveMsgId ) )
      datalist.extend( datalistin )
      data = ''.join( datalist )
      hrm = struct.pack('>H', rmmy)
      self.xbee.send('tx',
          dest_addr=hrm,
          options='\x02',
          frame_id=msgid,
          data=data
          )
      if self.verbose:
	print( "sending message to minibee", rmmy, hrm, data, self.ack_cnt )

  def send_msg64( self, ser, msgtype, datalistin ):
    if self.serial.isOpen():
      self.framecnt = self.framecnt + 1
      if self.framecnt == 16:
	self.framecnt = 1
      msgid = chr( self.framecnt )
      self.ack_cnt = self.ack_cnt + 1
      self.incMsgID()
      rfser = HexToByte( ser )
      destaddr = ''.join( rfser )
      datalist = [ msgtype ]
      datalist.append( chr( self.hiveMsgId) )
      datalist.extend( datalistin )
      data = ''.join( datalist )
      self.xbee.send('tx_long_addr',
	    dest_addr=destaddr,
	    data=data,
	    frame_id=msgid,
	    options='\x02'
	    )
      if self.verbose:
	print( "sending message to minibee with long addr", ser, rfser, data, self.ack_cnt )

  def send_run( self, mid, run ):
    if self.verbose:
      print( "sending bee run", mid, run )
    self.send_msg_inc( mid, 'R', [ chr(run) ] )

  def send_loop( self, mid, loop ):
    if self.verbose:
      print( "sending bee loop", mid, loop )
    self.send_msg_inc( mid, 'L', [ chr(loop) ] )

  def parse_serial( self, rfser, libv, rev, caps, remConf ): # later also libv, rev, caps
    sser = ByteToHex( rfser )
    if self.verbose:
      print( sser, libv, rev, caps, remConf )
    #self.hive.new_bee_no_config( sser )
    self.hive.new_bee( sser, libv, rev, caps, remConf )

  def recv_data( self, rfdata, source, rfrssi ):
    data = []
    for x in rfdata[1:]:
      data.append( int( ByteToHex( x ), 16 ) )    
    nid = int( ByteToHex( source ), 16 )
    rssi = int( ByteToHex( rfrssi ), 16 )
    msgid = int( ByteToHex( rfdata[0] ), 16 )
    if self.verbose:
      print( "receiving data from minibee", nid, msgid, data, rssi )
    self.hive.new_data( nid, msgid, data, rssi )

  def recv_triggerdata( self, rfdata, source, rfrssi ):
    data = []
    for x in rfdata[1:]:
      data.append( int( ByteToHex( x ), 16 ) )    
    nid = int( ByteToHex( source ), 16 )
    rssi = int( ByteToHex( rfrssi ), 16 )
    msgid = int( ByteToHex( rfdata[0] ), 16 )
    if self.verbose:
      print( "receiving trigger data from minibee", nid, msgid, data, rssi )
    self.hive.new_trigger_data( nid, msgid, data, rssi )

  def recv_privatedata( self, rfdata, source, rfrssi ):
    data = []
    for x in rfdata[1:]:
      data.append( int( ByteToHex( x ), 16 ) )    
    nid = int( ByteToHex( source ), 16 )
    rssi = int( ByteToHex( rfrssi ), 16 )
    msgid = int( ByteToHex( rfdata[0] ), 16 )
    if self.verbose:
      print( "receiving private data from minibee", nid, msgid, data, rssi )
    self.hive.new_private_data( nid, msgid, data, rssi )

  def recv_paused( self, msgid, source, rfrssi ):
    nid = int( ByteToHex( source ), 16 )
    rssi = int( ByteToHex( rfrssi ), 16 )
    msgid = int( ByteToHex( msgid ), 16 )
    if self.verbose:
      print( "receiving paused data from minibee", nid, msgid, rssi )
    self.hive.new_paused( nid, msgid, rssi )

  def recv_active( self, msgid, source, rfrssi ):
    nid = int( ByteToHex( source ), 16 )
    rssi = int( ByteToHex( rfrssi ), 16 )
    msgid = int( ByteToHex( msgid ), 16 )
    if self.verbose:
      print( "receiving active data from minibee", nid, msgid, rssi )
    self.hive.new_active( nid, msgid, rssi )

  def set_log_action( self, action ):
    self.logAction = action

  def log_data( self, packet ):
    nid = int( ByteToHex( packet[ 'source_addr' ] ), 16 )
    rssi = int( ByteToHex( packet[ 'rssi' ] ), 16 )
    #msgid = int( ByteToHex( packet[ 'rfdata' ][1] ), 16 )    
    data = []
    data.append( nid )
    data.append( rssi )
    data.append( packet[ 'rf_data' ][0] )
    for x in packet[ 'rf_data' ][1:]:
      data.append( int( ByteToHex( x ), 16 ) )    
    #print "receiving data"
    if self.logAction != None :
      self.logAction( data )
Exemplo n.º 9
0
def at_response_handler(name, packet):
    print(packet)


def rx_handler(name, packet):
    print("RX - %s" % packet)
    time.sleep(1)
    data = "PONG" if IS_HUB else "PING"
    xbee.tx(dest_addr_long=packet['source_addr_long'],
            dest_addr=packet['source_addr'],
            data=data)


ser = serial.Serial('/dev/ttyS0', 9600)
dispatch = Dispatch()
dispatch.register('rx', rx_handler, lambda p: p['id'] == 'rx')
dispatch.register('rx_explicit', default_handler,
                  lambda p: p['id'] == 'rx_explicit')
dispatch.register('rx_io_data_long_addr', default_handler,
                  lambda p: p['id'] == 'rx_io_data_long_addr')
dispatch.register('rx_io_data', default_handler,
                  lambda p: p['id'] == 'rx_io_data')
dispatch.register('tx_status', default_handler,
                  lambda p: p['id'] == 'tx_status')
dispatch.register('status', default_handler, lambda p: p['id'] == 'status')
dispatch.register('at_response', at_response_handler,
                  lambda p: p['id'] == 'at_response')
dispatch.register('remote_at_response', default_handler,
                  lambda p: p['id'] == 'remote_at_response')
dispatch.register('node_id_indicator', default_handler,
Exemplo n.º 10
0
class ZigBee(object):
    def __init__(self, serial_port, baud_rate, dispatcher, serializer):
        self.ser = serial.Serial(serial_port, baud_rate)
        self.zb = xbee.ZigBee(self.ser, escaped=True)
        self.dispatch = Dispatch(xbee = self.zb)
        self.dispatch.register('rx', self.rx_handler, lambda p: p['id'] == 'rx')
        self.dispatch.register('rx_explicit', self.default_handler, lambda p: p['id'] == 'rx_explicit')
        self.dispatch.register('rx_io_data_long_addr', self.default_handler, lambda p: p['id'] == 'rx_io_data_long_addr')
        self.dispatch.register('tx_status', self.default_handler, lambda p: p['id'] == 'tx_status')
        self.dispatch.register('status', self.default_handler, lambda p: p['id'] == 'status')
        self.dispatch.register('at_response', self.at_response_handler, lambda p: p['id'] == 'at_response')
        self.dispatch.register('remote_at_response', self.default_handler, lambda p: p['id'] == 'remote_at_response')
        self.dispatch.register('node_id_indicator', self.default_handler, lambda p: p['id'] == 'node_id_indicator')
        self.dispatcher = dispatcher
        self.serializer = serializer

    def default_handler(self, name, packet):
        print "%s - %s" % (name, packet)

    def at_response_handler(self, name, packet):
        p = ''.join('%02x' % ord(x) for x in packet['parameter'])
        print "AT - %s = %s" % (packet['command'], p)

    def rx_handler(self, name, packet):
        req = self.serializer.deserialize_request(packet['rf_data'])
        if not req:
            print "Ignoring garbage request"
            return
        
        rsp = self.dispatcher.dispatch(req)
        data = self.serializer.serialize_response(rsp)
        dst_long = packet['source_addr_long']
        dst_addr = packet['source_addr']
        print packet
        self.zb.tx(dest_addr_long=dst_long, dest_addr=dst_addr, data=data)

    def run(self):
        try:
            print "Run!"
            self.dispatch.run()
        except KeyboardInterrupt:
            pass

        print "Bye!"
        self.ser.close()
Exemplo n.º 11
0
        addr1.extend(packet['parameter'][2:10])
        global addrAll
        addrAll += [addr1]

    def remote_at_response_handler(name, packet):
        print packet

    def node_id_indicator_handler(name, packet):
        print packet

    # When a Dispatch is created with a serial port, it will automatically
    # create an XBee object on your behalf for accessing the device.
    # If you wish, you may explicitly provide your own XBee:
    #
    xbee = ZigBee(ser)
    dispatch = Dispatch(
        xbee=xbee)  #We need a Zigbee object, so only this works

    #
    # Functionally, these are the same.
    #dispatch = Dispatch(ser) #Will not work for senior project.


    def tx_packet(source, data, packet=0, status=False):
        #Get the address of our sender
        send_addr_long = source['source_addr_long']
        send_addr = source['source_addr']

        xbee.tx(
            dest_addr=send_addr,  #reply to sender
            dest_addr_long=send_addr_long,
            data=data,
Exemplo n.º 12
0
            'Missing "nodefile" in DEFAULT group of the configuration file.')
    nodefilename = config['DEFAULT']['nodefile']

    logging.info('Reading nodes configuration "%s"', nodefilename)
    nodeconfig = configparser.ConfigParser()
    try:
        nodeconfig.read(nodefilename)
    except:
        logging.critical('Could not read the node configuration file "%s".',
                         nodefilename)
        raise

    # Open serial port
    with serial.Serial(args.port, args.rate) as ser:
        # Create an xbee ZigBee communication object
        dispatch = Dispatch(ser)
        logging.debug('Creating xbee object.')
        xbee = ZigBee(ser, callback=dispatch.dispatch)

        try:
            if args.command == 'listen':
                listen(xbee, dispatch, config, nodeconfig)
            elif args.command == 'configure':
                config_client(xbee, dispatch, config, nodeconfig)
            else:
                logging.critical('Unknown command "%s", terminating.',
                                 args.command)
        finally:
            # halt() must be called before closing the serial port in order to ensure proper thread shutdown
            logging.info('Halting xbee.')
            xbee.halt()
Exemplo n.º 13
0
 def setUp(self):
     self.xbee = FakeXBee(None)
     self.dispatch = Dispatch(xbee=self.xbee)
     self.callback_check = CallbackCheck()
Exemplo n.º 14
0
class TestDispatch(unittest.TestCase):
    """
    Tests xbee.helpers.dispatch for expected behavior
    """

    def setUp(self):
        self.xbee = FakeXBee(None)
        self.dispatch = Dispatch(xbee=self.xbee)
        self.callback_check = CallbackCheck()

    def test_callback_is_called_when_registered(self):
        """
        After registerring a callback function with a filter function,
        the callback should be called when data arrives.
        """
        self.dispatch.register("test1", self.callback_check.call,
                               lambda data: True)
        self.dispatch.run(oneshot=True)
        self.assertTrue(self.callback_check.called)

    def test_callback_not_called_when_filter_not_satisfied(self):
        """
        After registerring a callback function with a filter function,
        the callback should not be called if a packet which does not
        satisfy the callback's filter arrives.
        """
        self.dispatch.register("test1", self.callback_check.call,
                               lambda data: False)
        self.dispatch.run(oneshot=True)
        self.assertFalse(self.callback_check.called)

    def test_multiple_callbacks(self):
        """
        Many callbacks should be called on the same packet if each
        callback's filter method is satisfied.
        """
        callbacks = []

        for i in range(0, 10):
            check = CallbackCheck()
            callbacks.append(check)
            self.dispatch.register("test%d" % i, check.call, lambda data: True)

        self.dispatch.run(oneshot=True)

        for callback in callbacks:
            if not callback.called:
                self.fail("All callback methods should be called")

    def test_callback_name_collisions_raise_valueerror(self):
        """
        If a call to register() results in attempting to register a
        callback with the same name as another callback should result
        in a ValueError exception being raised.
        """
        self.dispatch.register("test", None, None)
        self.assertRaises(ValueError, self.dispatch.register,
                          "test", None, None)
Exemplo n.º 15
0
 def setUp(self):
     self.xbee = FakeXBee(None)
     self.dispatch = Dispatch(xbee=self.xbee)
     self.callback_check = CallbackCheck()
Exemplo n.º 16
0
 def setUp(self):
     self.headless = Dispatch()
Exemplo n.º 17
0
	#print( "TX, Purged" )
      ##0 = Success
      ##1 = No ACK (Acknowledgement) received
      ##2 = CCA failure
      ##3 = Purged


# When a Dispatch is created with a serial port, it will automatically
# create an XBee object on your behalf for accessing the device.
# If you wish, you may explicitly provide your own XBee:
#
#  xbee = XBee(ser)
#  dispatch = Dispatch(xbee=xbee)
#
# Functionally, these are the same.
dispatch = Dispatch(ser)

# Register the packet handlers with the dispatch:
#  The string name allows one to distinguish between mutiple registrations
#   for a single callback function
#  The second argument is the function to call
#  The third argument is a function which determines whether to call its
#   associated callback when a packet arrives. It should return a boolean.
dispatch.register(
    "status", 
    status_handler, 
    lambda packet: packet['id']=='status'
)

dispatch.register(
    "rfdata", 
Exemplo n.º 18
0
# Create handlers for various packet types
def status_handler(name, packet):
    print "Status Update - Status is now: ", packet['status']

def io_sample_handler(name, packet):
    print "Samples Received: ", packet['samples']

# When a Dispatch is created with a serial port, it will automatically
# create an XBee object on your behalf for accessing the device.
# If you wish, you may explicitly provide your own XBee:
#
#  xbee = XBee(ser)
#  dispatch = Dispatch(xbee=xbee)
#
# Functionally, these are the same.
dispatch = Dispatch(ser)

# Register the packet handlers with the dispatch:
#  The string name allows one to distinguish between mutiple registrations
#   for a single callback function
#  The second argument is the function to call
#  The third argument is a function which determines whether to call its
#   associated callback when a packet arrives. It should return a boolean.
dispatch.register(
    "status", 
    status_handler, 
    lambda packet: packet['id']=='status'
)

dispatch.register(
    "io_data", 
Exemplo n.º 19
0
class ZigBee(object):
    def __init__(self, serial_port, baud_rate, dispatcher, serializer):
        self.ser = serial.Serial(serial_port, baud_rate)
        self.zb = xbee.ZigBee(self.ser, escaped=True)
        self.dispatch = Dispatch(xbee=self.zb)
        self.dispatch.register('rx', self.rx_handler,
                               lambda p: p['id'] == 'rx')
        self.dispatch.register('rx_explicit', self.default_handler,
                               lambda p: p['id'] == 'rx_explicit')
        self.dispatch.register('rx_io_data_long_addr', self.default_handler,
                               lambda p: p['id'] == 'rx_io_data_long_addr')
        self.dispatch.register('tx_status', self.default_handler,
                               lambda p: p['id'] == 'tx_status')
        self.dispatch.register('status', self.default_handler,
                               lambda p: p['id'] == 'status')
        self.dispatch.register('at_response', self.at_response_handler,
                               lambda p: p['id'] == 'at_response')
        self.dispatch.register('remote_at_response', self.default_handler,
                               lambda p: p['id'] == 'remote_at_response')
        self.dispatch.register('node_id_indicator', self.default_handler,
                               lambda p: p['id'] == 'node_id_indicator')
        self.dispatcher = dispatcher
        self.serializer = serializer

    def default_handler(self, name, packet):
        print "%s - %s" % (name, packet)

    def at_response_handler(self, name, packet):
        p = ''.join('%02x' % ord(x) for x in packet['parameter'])
        print "AT - %s = %s" % (packet['command'], p)

    def rx_handler(self, name, packet):
        req = self.serializer.deserialize_request(packet['rf_data'])
        if not req:
            print "Ignoring garbage request"
            return

        rsp = self.dispatcher.dispatch(req)
        data = self.serializer.serialize_response(rsp)
        dst_long = packet['source_addr_long']
        dst_addr = packet['source_addr']
        print packet
        self.zb.tx(dest_addr_long=dst_long, dest_addr=dst_addr, data=data)

    def run(self):
        try:
            print "Run!"
            self.dispatch.run()
        except KeyboardInterrupt:
            pass

        print "Bye!"
        self.ser.close()