Ejemplo n.º 1
0
    def queue_msg(self, channel):
        """ Call back for the channel publisher's __notify function. If the sample
        from the channel evaluates to boolean True, queues message """

        monitored_sample = channel.get()
        notify_cooldown_time = SettingsBase.get_setting(self, 'notify_cooldown_time')

        if not self.started_flag:
            raise Exception("Cannot queue message, presentation is stopped")

        if monitored_sample.value:
            if time.clock()-self.LastNotify > notify_cooldown_time:
                self.LastNotify = time.clock()
                cm = self.__core.get_service("channel_manager")
                cdb = cm.channel_database_get()
                try:
                    status, output = digicli.digicli('show net')
                    if status:
                        for line in output:
                            if line.find('MAC Address') >= 0:
                                l = line.split()
                                #print "".join(l[1:]).strip()
                                gatewayID = l[3]
                                #print "Gateway ID : %s" % gatewayID
                    status, output = digicli.digicli('show system')
                    if status:
                        for line in output:
                            if line.find('description') >= 0:
                                l = line.split(':')
                                descr = l[1]
                                #print "Gateway ID : %s" % gatewayID
                except:
                    print "SMTP Alarm: can't get the Gateway ID..."

                frm    = SettingsBase.get_setting(self, 'from_address')
                to     = SettingsBase.get_setting(self, 'to_address')
                sbj    = SettingsBase.get_setting(self, 'subject')
                msg = "From: %s\r\nTo: %s\r\nSubject: %s from %s - %s\r\n\r\n " % \
                                (frm, to, sbj, gatewayID, descr)
                msg += dump_channel_db_as_text(cdb)
                self.queue.put(msg)
Ejemplo n.º 2
0
def SetTimeUnix(secsSinceEpoch):
    """\
    Like time.time(), but returns int (not float) plus allows spoofing time
    """
    try:
        st = MakeDigiSetTimeString(secsSinceEpoch)
        print "st ", st
        if (sys.platform[:4] == 'digi'):
            success, response = digicli.digicli(st)
            # print 'digicli.success = ', success
            # print 'digicli.response = ', response
        else:
            print st
        return True
    except:
        return False
Ejemplo n.º 3
0
def SetTimeUnix(secsSinceEpoch):
    """\
    Like time.time(), but returns int (not float) plus allows spoofing time
    """
    try:
        st = MakeDigiSetTimeString(secsSinceEpoch)
        print "st ", st
        if( sys.platform[:4] == 'digi'):
            success, response = digicli.digicli(st)
            # print 'digicli.success = ', success
            # print 'digicli.response = ', response
        else:
            print st
        return True
    except:
        return False
Ejemplo n.º 4
0
 def process_gateway_command_pkt(self, gw_command):
     
     GET_VERSION_COMMAND = '\x56'
     CLI_COMMAND_PREFIX = '#cli '
     
     response_str = 'INVALID'
     
     if (gw_command == GET_VERSION_COMMAND):
         self.logger.debug ('Received the GET_VERSION gateway command.')
         response_str = GET_VERSION_COMMAND + VERSION_NUMBER
         
     elif (gw_command.startswith(CLI_COMMAND_PREFIX)):
         self.logger.debug ('Received a CLI gateway command: %s' % gw_command)
         if (on_digi_board()):
             cli_command = gw_command.strip(CLI_COMMAND_PREFIX)
             cli_command_ok, cli_command_output = digicli.digicli(cli_command)
             cli_command_output_str = str(cli_command_output)
             if (not cli_command_ok):
                 self.logger.error ("CLI command \"%s\" return and error: %s" % (cli_command, cli_command_output_str))
             response_str = CLI_COMMAND_PREFIX + cli_command_output_str
             
         else:
             response_str = "CLI command not supported on this platform"
         
     else:
         self.logger.error('Invalid gateway command: %s' % ''.join('%02X ' % ord(x) for x in gw_command))
         response_str = 'unimplemented gateway command'
         
     self.logger.debug ('Command answer is: ' + response_str)
     
     command_answer = '\xFF' + response_str
     
     command_answer_max_len = 255
     sz = len(command_answer)
     if (sz >= command_answer_max_len):
         # invalid answer size
         self.logger.critical('Gateway command answer exceeds max len (strip response): %s' % ''.join('%02X ' % ord(x) for x in command_answer))
         command_answer = command_answer[:command_answer_max_len - 1]
         sz = command_answer_max_len - 1
         
     answer_pkt_len = chr (sz + 1)
     answer_pkt = answer_pkt_len + command_answer
     
     return (answer_pkt)
Ejemplo n.º 5
0
def get_host():
  import digicli
  (flag, response) = digicli.digicli('set host')

  if flag:
    for line in response:
      line = line.strip()
      line = line.lower()

      if line.startswith('name'):
        hostname = line.split(':', 1)[1]
        hostname = hostname.strip()

        ##Special string indicating hostname was not set
        if hostname == '(not set)' or len(hostname) == 0:
          return None

        return hostname
    else:
      raise ValueError("Unable to locate the hostname field in the returned response")
  else:
    raise ValueError("Received error when querying device for hostname")
Ejemplo n.º 6
0
def get_host():
    import digicli
    (flag, response) = digicli.digicli('set host')

    if flag:
        for line in response:
            line = line.strip()
            line = line.lower()

            if line.startswith('name'):
                hostname = line.split(':', 1)[1]
                hostname = hostname.strip()

                ##Special string indicating hostname was not set
                if hostname == '(not set)' or len(hostname) == 0:
                    return None

                return hostname
        else:
            raise ValueError(
                "Unable to locate the hostname field in the returned response")
    else:
        raise ValueError("Received error when querying device for hostname")
    def __do_blink(self):

        blinks = SettingsBase.get_setting(self, "blinks")
        blink_speed = SettingsBase.get_setting(self, "blink_speed")

        self.__logger.debug("Start blinking")
        for _ in range(1, blinks):
            # Turn on user LED's
            self.__logger.info("Led ON")
            if on_digi_board():
                digihw.user_led_set(1, 1)
            digitime.sleep(blink_speed)

            # Turn off the LED's
            self.__logger.info("Led OFF")
            if on_digi_board():
                digihw.user_led_set(0, 1)
            digitime.sleep(blink_speed)

        self.__logger.debug("End blinking")
        # Turn off to prevent any strange behavior
        self.__logger.info("Force led OFF")
        if on_digi_board():
            digihw.user_led_set(0, 1)

        cli_command = SettingsBase.get_setting(self, "cli_command")
        self.__logger.info("Issue the command: %s" % cli_command)
        if (on_digi_board() and len(cli_command) > 0):
            self.__logger.debug('Calling digicli...')
            status, output = digicli.digicli(cli_command)
            if status:
                for line in output:
                    self.__logger.info('Command result: %s' % line)
            else:
                self.__logger.error('Error while executing command: %d, %s' %
                                    (status, output))
Ejemplo n.º 8
0
      <XMLdump>"""

SM_TEMPLATE2 = """</XMLdump>
    </XMLparser>
  </soap:Body>
</soap:Envelope>"""

          # ("infobel", "test")
ADDRESS_A = """&lt;gateway&gt;"""
        
ADDRESS_B = """&lt;/gateway&gt;"""
        
        
        
        
status, output = digicli.digicli('show net')
        
 
if status:
    for line in output:
        if line.find('MAC Address') >= 0:
            l = line.split(':')
            st = "".join(l[1:]).strip()
                    
MAC = st



# constants
ENTITY_MAP = {
    "<": "&lt;",
Ejemplo n.º 9
0
    def _get_ip_address_with_digicli(self):

        cli_output_example = ''' Device Table:
        
         Name     PhysAddr          Status
         mobile0  00:00:00:00:00:00 connected
         vpn4     NA                closed
         vpn3     NA                closed
         vpn2     NA                closed
         vpn1     NA                closed
         vpn0     NA                closed
         eth0     00:40:9D:51:09:35 connected
         vrrp7    NA                closed
         vrrp6    NA                closed
         vrrp5    NA                closed
         vrrp4    NA                closed
         vrrp3    NA                closed
         vrrp2    NA                closed
         vrrp1    NA                closed
         vrrp0    NA                closed
         LOOPBACK NA                connected
        
         Device Entry IP Configuration:
        
         Name     Family mHome Type   Status      IPAddress
         mobile0  IPv4   0     manual configured  90.117.242.26/30
         eth0     IPv4   0     manual configured  192.168.1.1/24
         LOOPBACK IPv4   0     manual configured  127.0.0.1/32
        '''

        interface = SettingsBase.get_setting(self, "interface")

        network_config_cli_command = "display netdevice"

        cli_command_ok, cli_command_output_list = digicli.digicli(
            network_config_cli_command)

        cli_command_output = ''.join(line for line in cli_command_output_list)

        if (not cli_command_ok):
            self._logger.error("Error in CLI command: %s" % cli_command_output)
            return None

        self._logger.debug('CLI command result: %s' % cli_command_output)

        # search for interface number
        split_header = 'Device Entry IP Configuration'
        header_end_index = cli_command_output.find(split_header) + len(
            split_header)
        if header_end_index == -1:
            return None
        device_config_sub_part = cli_command_output[header_end_index:]

        interface_sub_part_index = device_config_sub_part.find(interface)
        if interface_sub_part_index == -1:
            return None
        interface_sub_part = device_config_sub_part[interface_sub_part_index:]

        ip_address_sub_part = interface_sub_part[41:]
        ip_address_end_index = ip_address_sub_part.find('/')
        if ip_address_end_index == -1:
            return None

        computed_ip_address = ip_address_sub_part[:ip_address_end_index]
        self._logger.debug('Got IP address: %s' % computed_ip_address)

        return computed_ip_address
            print "Entering Trace Read Now..."

            while (True):
                rlist, wlist, xlist = select.select([trace_socket], [], [], 5)

                if trace_socket in rlist:
                    payload, src = trace_socket.recvfrom(1024)

                    trace_cache.write(payload)

                if (math.fabs(time.clock() - last_write)) > 60:
                    flush_trace_cache(trace_cache)
                    last_write = time.clock()
        except Exception, e:
            print "Exception during trace read: ", e
    finally:
        trace_socket.close()
        print "Trace thread ending"


if __name__ == "__main__":
    try:
        (status, result) = digicli.digicli(
            "set trace state=on syslog=on mask=sms:*,idigi:*,edp:*,printf:-* loghost=127.0.0.1"
        )
        if not status:
            print "Initial CLI trace set failed"
        else:
            syslog_server()
    except Exception, e:
        print "Initial CLI trace set failed with exception: %s" % e
Ejemplo n.º 11
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
            while True:
                rlist, wlist, xlist = select.select([trace_socket], [], [], 5)

                if trace_socket in rlist:
                    payload, src = trace_socket.recvfrom(1024)

                    trace_cache.write(payload)

                if (math.fabs(time.clock() - last_write)) > 60:
                    flush_trace_cache(trace_cache)
                    last_write = time.clock()
        except Exception, e:
            print "Exception during trace read: ", e
    finally:
        trace_socket.close()
        print "Trace thread ending"


if __name__ == "__main__":
    try:
        (status, result) = digicli.digicli(
            "set trace state=on syslog=on mask=sms:*,idigi:*,edp:*,printf:-* loghost=127.0.0.1"
        )
        if not status:
            print "Initial CLI trace set failed"
        else:
            syslog_server()
    except Exception, e:
        print "Initial CLI trace set failed with exception: %s" % e
Ejemplo n.º 13
0
    def process_gateway_command_pkt(self, gw_command):

        GET_AO_SERVER_IP_ADDRESS = '\x09'
        GET_AO_SERVER_IP_PORT = '\x0A'
        CLI_COMMAND_PREFIX = '#cli '
        ERROR_BYTE_PREFIX = '\x00'

        response_str = 'INVALID'

        if (gw_command == PG_CMD_GET_VERSION):
            self.logger.debug('Received the GET_VERSION gateway command.')
            all_dia_module_software_version = self.get_software_versions()
            response_str = PG_CMD_GET_VERSION + all_dia_module_software_version

        elif (gw_command == GET_AO_SERVER_IP_ADDRESS):
            self.logger.error(
                'Received the AO_SERVER_IP_ADDRESS gateway command.No more implemented.'
            )
            response_str = GET_AO_SERVER_IP_ADDRESS + 'No more implemented: AO server address'

        elif (gw_command == GET_AO_SERVER_IP_PORT):
            self.logger.error(
                'Received the AO_SERVER_IP_PORT gateway command. No more implemented.'
            )
            response_str = GET_AO_SERVER_IP_PORT + 'No more implemented: AO server port'

        elif (gw_command.startswith(CLI_COMMAND_PREFIX)):
            self.logger.debug('Received a CLI gateway command: %s' %
                              gw_command)
            if (on_digi_board()):
                cli_command = gw_command.strip(CLI_COMMAND_PREFIX)
                cli_command_ok, cli_command_output = digicli.digicli(
                    cli_command)
                cli_command_output_str = str(cli_command_output)
                if (not cli_command_ok):
                    self.logger.error(
                        "CLI command \"%s\" return and error: %s" %
                        (cli_command, cli_command_output_str))
                response_str = CLI_COMMAND_PREFIX + cli_command_output_str

            else:
                # FIXME: how to return an error in this case.
                response_str = ERROR_BYTE_PREFIX + "CLI command not supported on this platform"

        else:
            self.logger.error('Invalid gateway command: %s' %
                              ''.join('%02X ' % ord(x) for x in gw_command))
            response_str = ERROR_BYTE_PREFIX + 'unimplemented gateway command'

        self.logger.debug('Command answer is: ' + response_str)

        command_answer = '\xFF' + response_str

        command_answer_max_len = 255
        sz = len(command_answer)
        if (sz >= command_answer_max_len):
            # invalid answer size
            self.logger.critical(
                'Gateway command answer exceeds max len (strip response): %s' %
                ''.join('%02X ' % ord(x) for x in command_answer))
            command_answer = command_answer[:command_answer_max_len - 1]
            sz = command_answer_max_len - 1

        answer_pkt_len = chr(sz + 1)
        answer_pkt = answer_pkt_len + command_answer

        return (answer_pkt)