Example #1
0
File: xb.py Project: nkhoa123/XIG
 def get_eui(self, addr=None):
     # read SH and SL and return a EUI-64
     try:
         return ":".join("%02X" % ord(x)
                         for x in xbee.ddo_get_param(addr, 'sh') +
                         xbee.ddo_get_param(addr, 'sl'))
     except:
         return None
Example #2
0
 def work(self):
     sleep(0.5) # makes sure we catch 00 seconds asap 
     time = localtime()
     if time.tm_sec != 0:
       return # wait for 00 seconds(!)
     if time.tm_year < 2000:
       return # wait until time sync   
     s = strftime("[T:%y-%m-%d %H:%M]\r\n", time)
     if s == self._last:
         return # this time was just sent
     self._last = s
     print "xgw: Getting current destination address"
     addr = str2addr(zigbee.ddo_get_param(None, "DH", TIMEOUT) + zigbee.ddo_get_param(None, "DL", TIMEOUT))
     print "xgw: Sending time %s to %s" % (repr(s), addr)
     self._xbee.send(s, addr)
Example #3
0
File: xb.py Project: nkhoa123/XIG
 def __call__(self, request):
     if request.method == 'GET':
         addr = request.GET.get('addr', None)
         at = request.GET.get('at')
         if at:
             if at == "status":
                 status = self.get_status(addr)
                 if addr is None:
                     self.status = status  #store our status for polling
                 return webob.Response(json.dumps(status),
                                       content_type='json')
             elif at == "eui":
                 eui = self.get_eui(addr)
                 if addr is None:
                     self.eui = eui  # store our EUI for polling
                 return webob.Response(json.dumps(eui), content_type='json')
             else:
                 # read AT parameter to return value
                 at_str = xbee.ddo_get_param(addr, at)
                 return webob.Response(json.dumps(binstring_to_int(at_str)),
                                       content_type='json')
         else:
             # invalid request
             return webob.exc.HTTPBadRequest()
     if request.method == 'POST':
         addr = request.POST.get('addr')
         at = request.POST.get('at')
         value = request.POST.get('value')
         if at is not None and value is not None:
             response = xbee.ddo_set_param(addr, at, value)
             return webob.Response(json.dumps(response),
                                   content_type='json')
     else:
         return webob.exc.HTTPMethodNotAllowed()
Example #4
0
File: xb.py Project: Rahuldee/XIG
 def __call__(self, request):
     if request.method == 'GET':
         addr = request.GET.get('addr', None)
         at = request.GET.get('at')
         if at:
             if at == "status":
                 status = self.get_status(addr)
                 if addr is None:
                     self.status = status #store our status for polling
                 return webob.Response(json.dumps(status), content_type='json')
             elif at == "eui":
                 eui = self.get_eui(addr)
                 if addr is None:
                     self.eui = eui # store our EUI for polling
                 return webob.Response(json.dumps(eui), content_type='json')
             else:
                 # read AT parameter to return value
                 at_str = xbee.ddo_get_param(addr, at)
                 return webob.Response(json.dumps(binstring_to_int(at_str)), content_type='json')
         else:
             # invalid request
             return webob.exc.HTTPBadRequest()
     if request.method == 'POST':
         addr = request.POST.get('addr')
         at = request.POST.get('at')
         value = request.POST.get('value')
         if at is not None and value is not None:
             response = xbee.ddo_set_param(addr, at, value)
             return webob.Response(json.dumps(response), content_type='json')
     else:
         return webob.exc.HTTPMethodNotAllowed()
Example #5
0
File: xb.py Project: nkhoa123/XIG
 def get_status(self, addr=None):
     # read AI and return string value
     try:
         ai = ord(xbee.ddo_get_param(addr, 'ai'))
         return self.AI_STATUS.get(ai, '0x%02X - Unknown Status' % ai)
     except Exception, e:
         self.logger.debug("XBee Status: exception '%s'" % repr(e))
         return "XBee Not Connected."
Example #6
0
File: xb.py Project: Rahuldee/XIG
 def get_status(self, addr=None):
     # read AI and return string value
     try:
         ai = ord(xbee.ddo_get_param(addr, 'ai'))
         return self.AI_STATUS.get(ai, '0x%02X - Unknown Status' % ai)
     except Exception, e:
         self.logger.debug("XBee Status: exception '%s'" % repr(e))
         return "XBee Not Connected."
Example #7
0
def GetXBeeDeviceNodeIdentifier(address):

    # Attempt the "NI" command a couple times if it fails for some reason.
    for i in range(0, 10):
        try:
            node_name = zigbee.ddo_get_param(address, 'NI')
        except:
            continue
        else:
            return node_name

    return None
Example #8
0
 def XBeeCommandGet(self, command):
     result = None
     # Attempt the command a couple times if it fails for some reason.
     for i in range(0, amount_of_tries):
         try:
             result = zigbee.ddo_get_param(self.addr, command)
         except:
             continue
         else:
             return result
     print "XBeeCommandGet FAILED: %s" % command
     return None
Example #9
0
def GetXBeeDeviceNodeIdentifier(address):

	# Attempt the "NI" command a couple times if it fails for some reason.
	for i in range(0, 10):
		try:
			node_name = zigbee.ddo_get_param(address, 'NI')
		except:
			continue
		else:
			return node_name

	return None
Example #10
0
def to_name(addr, get_device_type=False):
    """Returns a name for a give name or address string, quering it if needed."""
    if not is_addr(addr):
        return addr
    has_name = addr in addr_to_name 
    if has_name and (not get_device_type or type(name_to_addr[addr_to_name[addr]]) == tuple):
        return addr_to_name[addr]
    name = ""
    if has_name:
        name = addr_to_name[addr]
    else:
        for i in range(RETRY):
            print "xgw: Quering name for ", addr, " (", i + 1, " of ", RETRY, ")"
            try:
                name = zigbee.ddo_get_param(addr, "NI", TIMEOUT)
            except Exception, e:
                print "xgw: Query failed ", e
            else:
                break
        if not name:
            return addr
        print "xgw: Found name ", name, " for ", addr
def parseQ():
    pat = "Qr(\d+)g(\d+)b(\d+)s(\d+)"
    pat2 = "2r(\d+)g(\d+)b(\d+)"
    for nodeaddr,text in recvData.items():
        match = re.search(pat, text)
        if match is not None:
            print "found match"
            try:
                nodeName = zigbee.ddo_get_param(nodeaddr, "NI")
                if not nodeData.has_key(nodeaddr):
                    nodeData[nodeaddr] = {
                        "red":0, "green":0, "blue":0, "speed":0,
                        "red2":0, "green2":0, "blue2":0,
                        "nodeaddr":nodeaddr, "nodeId":nodeName
                    }
                else:
                    nodeData[nodeaddr]["nodeId"] = nodeName
            except:
                exctype, value = sys.exc_info()[:2]
                print "failed to add node: "+str(exctype)+", "+str(value)
                continue
            recvData[nodeaddr] = ""
            nodeData[nodeaddr]['red'] = int(match.group(1))
            nodeData[nodeaddr]['green'] = int(match.group(2))
            nodeData[nodeaddr]['blue'] = int(match.group(3))
            nodeData[nodeaddr]['red2'] = int(match.group(1))
            nodeData[nodeaddr]['green2'] = int(match.group(2))
            nodeData[nodeaddr]['blue2'] = int(match.group(3))
            nodeData[nodeaddr]['speed'] = int(match.group(4))
            nodeData[nodeaddr]['active'] = time.time()
        match = re.search(pat2, text)
        if match is not None:
            print "found match2"
            recvData[nodeaddr] = ""
            nodeData[nodeaddr]['red2'] = int(match.group(1))
            nodeData[nodeaddr]['green2'] = int(match.group(2))
            nodeData[nodeaddr]['blue2'] = int(match.group(3))
            nodeData[nodeaddr]['active'] = time.time()
Example #12
0
def GetXBeeDeviceType(address):

    # Attempt the "DD" command a couple times if it fails for some reason.
    for i in xrange(0, 5):
        try:
            device_type, product_type = struct.unpack(
                'HH', zigbee.ddo_get_param(address, 'DD'))
        except:
            continue
        else:
            if (device_type != XBeeUnspecified) and (product_type !=
                                                     XBeeUnspecified):
                return device_type, product_type

# Perhaps we are on some older firmware that doesn't support the
# "DD" command...
# So lets try the older "VR" command instead.

    for i in xrange(0, 5):
        try:
            version = struct.unpack('=H', zigbee.ddo_get_param(address,
                                                               'VR'))[0]
            hardware = struct.unpack('=H', zigbee.ddo_get_param(address,
                                                                'HV'))[0]
        except:
            continue
        else:
            version = version & 0xFF00
            hardware = hardware & 0xFF00

            ## WARNING! This gets a bit sticky.

            ## We need to cross reference the Series of the radio which is determined
            ## from the hardware version, to determine what the firmware version
            ## really means.  Please note that not ALL firmware versions are specified.

            ## Current cross referencing is due to how the 802.15.4 firmware is
            ## versioned.  It does not line up with the versioning on the Series 2 or
            ## ZB firmware.

            ## In addition to the above, we can't be sure what hardware we have.
            ## In the case of a coordinator API firmware, we can't differentiate
            ## between a CPX8, CPX4, or CPX2.  And due to the multiple use of the
            ## 0x1200 (Router AT) firmware, we cannot tell if its a wall router,
            ## rs-232 adapter, rs-485 adapter or XBee smart plug.

            ## The 802.15.4 firmware which covers the gateway, rs-232 adapter, rs-485
            ## adapter, wall router and smartplug is all one firmware version.

            ## In short, if the above identification via the 'DD' parameter fails,
            ## we can only make guesses as to what we really are identifying!

            ## 802.15.4: Regular = 0x1700, PRO = 0x1800
            if hardware == 0x1700 or hardware == 0x1800:
                series = XBeeSeries1

            ## ZB/Znet 2.5 Regular = 0x1900, PRO = 0x1a00
            elif hardware == 0x1900 or hardware == 0x1a00:
                if (version & 0xF000) == 0x1000:
                    series = XBeeSeries2
                elif (version & 0xF000) == 0x2000:
                    series = XBeeZB
                else:
                    return (XBeeUnspecified, XBeeUnspecified)
            else:
                return (XBeeUnspecified, XBeeUnspecified)

            if (version == 0x1200) and (series == XBeeSeries1):
                return (series, XBeeSensorAdapter)

            version = version & 0x0F00

            if (version == 0x0000) and (series == XBeeSeries1):
                return (series, XBeeX8Gateway)
            elif (version == 0x0400) and ((series == XBeeSeries2) or
                                          (series == XBeeZB)):
                return (series, XBeeSensorAdapter)
            elif version == 0x0500:
                return (series, XBeeRS232PowerHarvesterAdapter)
            elif version == 0x0600:
                return (series, XBeeAnalogIOAdapter)
            elif version == 0x0700:
                return (series, XBeeDigitalIOAdapter)
            else:
                return (series, XBeeUnspecified)

    return (XBeeUnspecified, XBeeUnspecified)
Example #13
0
                crc = (crc >> 1) ^ 0x8408
            else:
                crc = (crc >> 1)
    crc = ~crc
    byte = crc
    crc = ((crc << 8) & 0xFF00) | ((byte >> 8) & 0xFF)
    return (crc & 0xFFFF)


# To call ccittcrc16 with a string, use ccittcrc16(map(ord,'string'))

#create a message sequence number that increments with every packet transmitted by the gateway
seqNum = 0

#get the lower 32 bits of the address of radio module in the gateway
gatewayAddress = zigbee.ddo_get_param(None, 'SL')

#setup radio socket
size = 1024
radioSocket = socket.socket(socket.AF_XBEE, socket.SOCK_DGRAM,
                            socket.XBS_PROT_TRANSPORT)
try:
    radioSocket.bind(("", 0xe8, 0, 0))
except socket.error, msg:
    print 'Failed to bind radio socket. Exception: ' + str(
        msg[0]) + ' - ' + msg[1]
    sys.exit()
radioSocket.setblocking(0)
#radioSocket.listen(5)
#radioClients = [radioSocket]
print 'Radio socket: ' + str(radioSocket.getsockname())
Example #14
0
    def poll_stats(self):
        """rci and cli requests for digi device stats"""
        print "SystemStatus:  Polling system stats"
        #find cpu utilization percent and free memory
        try:
            msg = "<rci_request version=\"1.1\"><query_state><device_stats/></query_state></rci_request>"
            resp = rci.process_request(msg)
            cpuPercent = re.search("<cpu>(\S+)</cpu>", resp).group(1)
            self.property_set("cpu_utilization", Sample(0, int(cpuPercent), "%"))
            freeMemory = re.search("<freemem>(\S+)</freemem>", resp).group(1)
            self.property_set("free_memory", Sample(0, int(freeMemory), "bytes"))
            self.schedule_polling()
        except: pass

        if not SettingsBase.get_setting(self,"no_zigbee"):
          try:
          # look for configure and read from all active XBee nodes
              node_list = []
              print 'Device discovery in progress. Please wait ...'
              nodes = zigbee.getnodelist(True)
              print '\nActive node list of extended addresses'
              for node in nodes:
                  print node.addr_short, ' ', node.addr_extended, ' ', node.label

              # now for each node try to retrieve a sample
              for node in nodes:
                  if node.type != "router":
                     xtn_addr = node.addr_extended
                     # store the active node extended addr for later use
                     node_list.append(xtn_addr)
                     # print the attributes of each active node
#                     print '\naddr_extended: %s' % node.addr_extended
#                     print 'addr_short: %s' % node.addr_short
#                     print 'addr_parent: %s' % node.addr_parent
#                     print 'profile_id: %s' % node.profile_id
#                     print 'manufacturer_id: %s' % node.manufacturer_id
#                     print 'label: %s' % node.label
#                     print 'type: %s' % node.type
#                      try:
#                          module_type, product_type = GetXBeeDeviceType(xtn_addr)
#                          print 'module_type: %s' % module_type
#                          print 'product_type: %s' % product_type
#                      except Exception, e:
#                          print 'GetXBeeDeviceType error: %s' % e
#
                      # get some node configuration info using ddo_get
                     try:
                         rssi_raw = zigbee.ddo_get_param(xtn_addr,'DB')
                         zb_rssi = 0-struct.unpack('=B',rssi_raw)[0]
                         print 'Zigbee Coordinator rssi : %s ' % zb_rssi
                         self.property_set("zigbee_coord_rssi", Sample(0, zb_rssi))
                         vr_raw = zigbee.ddo_get_param(xtn_addr,'VR')
                         #print 'firmware version: %s' % hex(struct.unpack('>H',vr_raw)[0])
                     except Exception, e:
                          print 'ddo_get error: %s' % e
          except: pass

        #find mobile connectivity status
        if not SettingsBase.get_setting(self,"no_mobile"):
            try:
                msg = "<rci_request version=\"1.1\"><query_state><mobile_stats/></query_state></rci_request>"
                resp = rci.process_request(msg)
                rssi = re.search("<rssi>(\S+)</rssi>", resp).group(1)
                try:
                    i_rssi = int(rssi)
                except ValueError:
                    i_rssi = 0
                self.property_set("mobile_rssi", Sample(0, i_rssi))
                statsIndex = re.search("<stats_index>(\S+)</stats_index>", resp).group(1)
                msg = "<rci_request version=\"1.1\"><query_state><ppp_stats index=\""+statsIndex+"\"/></query_state></rci_request>"
                resp = rci.process_request(msg)
                mobileStatus = re.search("<ppp_stats index=\""+statsIndex+"\"><state>(\S+)</state>", resp).group(1)
                self.property_set("mobile_status", Sample(0, mobileStatus))
            except: pass

        #find idigi connectivity status
        try:
            msg = "who"
            status, response = digicli.digicli(msg)
            if status:
                #response is a list of strings for each line.  Convert into single string.
                responseStr = string.join(response, "")
                #responseStr = ""
                #for line in response:
                #    responseStr += line
                if ((responseStr.find("connectware") == -1) and (responseStr.find("idigi") == -1)):
                    self.property_set("idigi_status", Sample(0, "disconnected"))
                else:
                    self.property_set("idigi_status", Sample(0, "connected"))
        except: pass
Example #15
0
File: xb.py Project: Rahuldee/XIG
 def get_eui(self, addr=None):
     # read SH and SL and return a EUI-64
     try:
         return ":".join("%02X"%ord(x) for x in xbee.ddo_get_param(addr, 'sh') + xbee.ddo_get_param(addr, 'sl'))
     except:
         return None
Example #16
0
def GetXBeeDeviceType(address):
  
	# Attempt the "DD" command a couple times if it fails for some reason.
  for i in xrange(0, 5):
    try:
			device_type, product_type = struct.unpack('HH', zigbee.ddo_get_param(address, 'DD'))
    except:
			continue
    else:
      if (device_type != XBeeUnspecified) and (product_type != XBeeUnspecified):
        return device_type, product_type      

	# Perhaps we are on some older firmware that doesn't support the
	# "DD" command...
	# So lets try the older "VR" command instead.	
	
  for i in xrange(0, 5):
		try:
			version = struct.unpack('=H', zigbee.ddo_get_param(address, 'VR'))[0]
			hardware = struct.unpack('=H', zigbee.ddo_get_param(address, 'HV'))[0]			
		except:
			continue
		else:
			version = version & 0xFF00
			hardware = hardware & 0xFF00
			
			## WARNING! This gets a bit sticky.
			
			## We need to cross reference the Series of the radio which is determined
			## from the hardware version, to determine what the firmware version 
			## really means.  Please note that not ALL firmware versions are specified.  
			
			## Current cross referencing is due to how the 802.15.4 firmware is 
			## versioned.  It does not line up with the versioning on the Series 2 or
			## ZB firmware.  
			
			## In addition to the above, we can't be sure what hardware we have.
			## In the case of a coordinator API firmware, we can't differentiate
			## between a CPX8, CPX4, or CPX2.  And due to the multiple use of the
			## 0x1200 (Router AT) firmware, we cannot tell if its a wall router, 
			## rs-232 adapter, rs-485 adapter or XBee smart plug.
			
			## The 802.15.4 firmware which covers the gateway, rs-232 adapter, rs-485
			## adapter, wall router and smartplug is all one firmware version.  
			
			## In short, if the above identification via the 'DD' parameter fails,
			## we can only make guesses as to what we really are identifying!  			
			
			## 802.15.4: Regular = 0x1700, PRO = 0x1800
			if hardware == 0x1700 or hardware == 0x1800:
				series = XBeeSeries1
			
			## ZB/Znet 2.5 Regular = 0x1900, PRO = 0x1a00
			elif hardware == 0x1900 or hardware == 0x1a00:
				if (version & 0xF000) == 0x1000:
					series = XBeeSeries2
				elif (version & 0xF000) == 0x2000:
					series = XBeeZB
				else:
					return (XBeeUnspecified, XBeeUnspecified)
			else:
				return (XBeeUnspecified, XBeeUnspecified)
						
			if (version == 0x1200) and (series == XBeeSeries1):
				return (series, XBeeSensorAdapter)
			
			version = version & 0x0F00			
			
			if (version == 0x0000) and (series == XBeeSeries1):				
				return (series, XBeeX8Gateway) 
			elif (version == 0x0400) and ((series == XBeeSeries2) or (series == XBeeZB)):				
				return (series, XBeeSensorAdapter)
			elif version == 0x0500:				
				return (series, XBeeRS232PowerHarvesterAdapter)
			elif version == 0x0600:
				return (series, XBeeAnalogIOAdapter)
			elif version == 0x0700:
				return (series, XBeeDigitalIOAdapter)			
			else:
				return (series, XBeeUnspecified)
	
  return (XBeeUnspecified, XBeeUnspecified)