コード例 #1
0
def main():
    node = Node('temperaturemonitor.py')
    parser = argparse.ArgumentParser(
        description="Get temperature of CPU cores.")
    parser.add_argument(
        "--interval",
        type=int,
        default=2,
        help='Sets time interval between each update on CPU temperature')
    parser.add_argument("--source",
                        choices=["pysensors", "sysfs"],
                        default="sysfs")
    args = parser.parse_args()

    if args.source == "sysfs":
        while True:
            with open('/sys/class/thermal/thermal_zone0/temp') as temp_file:
                temp = int(temp_file.read().strip()) / 1000.0
                node.send(messaging.CPUTemperatureMessage(temp, -1))
                time.sleep(args.interval)
    else:
        import sensors
        sensors.init()
        while True:
            for chip in sensors.iter_detected_chips():
                ##print '%s at %s:' % (chip, chip.adapter_name)
                temperatures = []
                for feature in chip:
                    temperatures.append(feature.get_value())
                node.send(
                    messaging.CPUTemperatureMessage(temperatures[0],
                                                    temperatures[1]))
            time.sleep(args.interval)
        node.stop()
        sensors.cleanup()
コード例 #2
0
def _get_detected_chips():  # pragma: no cover
    sensors.cleanup()
    sensors.init()

    chips_detected = list(sensors.iter_detected_chips())

    return chips_detected
コード例 #3
0
    def get_sensors(self):
        """
        collects the current temperature of CPU
        and each core
        """

        sensors.init()
        added = []
        cpu_temp_c = []
        try:
            for chip in sensors.iter_detected_chips():
                for feature in chip:
                    if feature.name.startswith('temp'):
                        if ((feature.label.startswith('Physical') or
                                feature.label.startswith('CPU')) and
                                feature.label not in added):
                            self._status.add_cpu_temp(feature.get_value())
                        elif (feature.label.startswith('Core')
                                and feature.label not in added):
                            cpu_temp_c.append(feature.get_value())
                        added.append(feature.label)
        except sensors.SensorsError:
            pass
        if cpu_temp_c:
            try:
                self._status.add_cpu_temp_core(cpu_temp_c)
            except IndexError:
                pass
        sensors.cleanup()
コード例 #4
0
def getY():
    sensors.init() # Inicializamos sensores
    temperaturas = [] # Guarda todas las tempereturas
                      #detectadas
    suma_total = 0 # Variable de apoyo
    try:
        # Recorremos todos los sensores detectados
        for chip in sensors.iter_detected_chips():
            a = chip
            b = chip.adapter_name
            if b == "PCI adapter":
                print "Procesador >", a,
                for core in chip:
                    print "",core.get_value(), "C"
                    # Agregamos a la lista
                    temperaturas.append(core.get_value()) 

        total_tempe = len(temperaturas)        
        suma_total = sum(suma for suma in temperaturas)

        prom = int(suma_total) / total_tempe
    finally:
        sensors.cleanup() # Cerramos los sensores
    print "prom =>", prom
    print "--------------------------------------"
    if SERIAL: ser.write(str(prom)) # Enviamos el prom al arduino
    return prom
コード例 #5
0
    def get_sensors(self):
        """
        collects the current temperature of CPU
        and each core
        """

        sensors.init()
        added = []
        cpu_temp_c = []
        try:
            for chip in sensors.iter_detected_chips():
                for feature in chip:
                    if feature.name.startswith('temp'):
                        if ((feature.label.startswith('Physical')
                             or feature.label.startswith('CPU'))
                                and feature.label not in added):
                            self._status.add_cpu_temp(feature.get_value())
                        elif (feature.label.startswith('Core')
                              and feature.label not in added):
                            cpu_temp_c.append(feature.get_value())
                        added.append(feature.label)
        except sensors.SensorsError:
            pass
        if cpu_temp_c:
            try:
                self._status.add_cpu_temp_core(cpu_temp_c)
            except IndexError:
                pass
        sensors.cleanup()
コード例 #6
0
def get_cpu_temp(unit=None):
    """
    Reads and returns the temperature of the CPU if available.
    If unit is F, temperature is returned as Fahrenheit otherwise Celsius.

    Uses pysensors library (0.0.3) - pip install pysensors
    
    @type unit: character
    @param unit: F or C        
    @rtype:   string
    @return:  CPU temperature
    """

    try:
        for chip in sensors.iter_detected_chips():
            for feature in chip:
                temp = feature.get_value()

        if unit == 'F':
            return str(1.8 * temp + 32)
        else:
            return str(temp)

    except Exception:
        return '!!'

    finally:
        sensors.cleanup()
コード例 #7
0
ファイル: __init__.py プロジェクト: felipelerena/voz_cachonda
def process_temp():
    print("-" * 50)
    sensors.init()
    critical = False
    try:
        for chip in sensors.ChipIterator():
            for feature in sensors.FeatureIterator(chip):
                subs = list(sensors.SubFeatureIterator(chip, feature))
                critical = None
                current = None
                for sub in subs:
                    value = sensors.get_value(chip, sub.number)
                    if sub.name.endswith(b"input"):
                        current = value
                    if sub.name.endswith(b"crit"):
                        critical_value = value
                name = sensors.get_label(chip, feature)
                print("Current temp for {}: {} / {}".format(name, current,
                                                            critical_value))
                if current >= critical_value:
                    critical = True
        if critical:
            play_critical()
    finally:
        sensors.cleanup()
コード例 #8
0
ファイル: temperatures.py プロジェクト: Bengt/AL-FanControl
def _get_detected_chips():  # pragma: no cover
    sensors.cleanup()
    sensors.init()

    chips_detected = list(sensors.iter_detected_chips())

    return chips_detected
コード例 #9
0
 def get_lmsensor(self):
     """
     """
     if self._lmsensor_next_run < datetime.now():
         locked = self._lock.acquire(False)
         if locked == True:
             try:
                 _lmsensor = {}
                 pysensors.init(config_filename=self.values["config_filename"].data)
                 try:
                     for chip in pysensors.iter_detected_chips():
                         _lmsensor['%s'%chip] = {}
                         for feature in chip:
                             _lmsensor['%s'%chip][feature.label] = feature.get_value()
                 except Exception:
                     logger.exception("[%s] - Exception in get_lmsensor", self.__class__.__name__)
                 finally:
                     pysensors.cleanup()
                 for val_id in ['temperature', 'voltage']:
                     for config in self.values[val_id].get_index_configs():
                         for chip in _lmsensor:
                             if config in _lmsensor[chip] :
                                 self.values[val_id].set_data_index(config=config, data=_lmsensor[chip][config])
                 self._lmsensor_last = True
             except Exception:
                 logger.exception("[%s] - Exception in get_lmsensor", self.__class__.__name__)
                 self._lmsensor_last = False
             finally:
                 self._lock.release()
                 min_poll=99999
                 for val_id in ['temperature_poll', 'voltage_poll']:
                     if self.values[val_id].data > 0:
                         min_poll=min(min_poll, self.values[val_id].data)
                 self._lmsensor_next_run = datetime.now() + timedelta(seconds=min_poll)
コード例 #10
0
ファイル: cputemp.py プロジェクト: building39/pycoretemp
def metric_init(params):
    global descriptors
    
    sensors.init()
    corelist = []
    
    try:
        for chip in sensors.iter_detected_chips():
            if chip.prefix == CORETEMP:
                for feature in chip:
                    if feature.label.startswith('Core'):
                        corelist.append("%s Temperature" % feature.label)
    except:
        raise
    finally:
        sensors.cleanup()

    for core in corelist:
        print 'name: %s' % core
        descriptors.append({'name': core,
                                'call_back': temp_handler,
                                'time_max': 90,
                                'value_type': 'float',
                                'units': 'Celsius',
                                'slope': 'both',
                                'format': '%.2f',
                                'description': 'Temperature of %s' % core,
                                'groups': 'Node Health'})
    return descriptors
コード例 #11
0
    def check(self, instance):
        ## Capture CPU temperature stats
        dimensions = self._set_dimensions(None, instance)

        sensors.init()
        stats ={}
        try:
          for chip in sensors.iter_detected_chips():
            # Only temps from ISA adpters that are deteced by lm_sensors
            if (chip.adapter_name == "ISA adapter"):
              for feature in chip:
                if "Core" in feature.label:
                  name = feature.label.replace(" ", "_")
                  name = name.lower()
                  stats["cpu."+str(chip)+"."+str(name)+"_temperature"] = feature.get_value()
                elif "Physical id" in feature.label:
                  name = feature.label.replace(" ", "_")
                  name = name.lower()
                  stats["cpu."+str(chip)+".max_temperature"] = feature.get_value()
        finally:
          sensors.cleanup()
        for key, value in stats.iteritems():
          # Writes data to monasca that will go to InfluxDB
          self.gauge(key, value, dimensions)
        log.debug('Collected {0} cpu temp metrics'.format(len(stats)))                                                                                        1,1           Top
コード例 #12
0
    def __exit__(self, *a):
        if self._initSuccess:
            self._initCount -= 1
            if self._initCount == 0:
                # Last one out, get the lights.
                sensors.cleanup()

        return super().__exit__(*a)
コード例 #13
0
ファイル: agent.py プロジェクト: nwlunatic/sensors-agent
def serve(port):
    sensors.init()
    server = Server("localhost", port)
    try:
        server.serve_forever()
    except KeyboardInterrupt:
        server.server_close()
    finally:
        sensors.cleanup()
コード例 #14
0
def getDictTemp():
  result = dict()
  sensors.init()
  try:
      for chip in sensors.iter_detected_chips():
          for feature in chip:
              result[str(feature.label)] = str(feature.get_value())
  finally:
      sensors.cleanup()
  return result
コード例 #15
0
 def check(self, instance):
     sensors.init()
     try:
         for chip in sensors.iter_detected_chips():
             for feature in chip:
                 self.gauge("sensors." + feature.label,
                            feature.get_value(),
                            device_name=('%s' % (chip)))
     finally:
         sensors.cleanup()
コード例 #16
0
ファイル: sensors_log.py プロジェクト: fyhuang/sensors-log
def main():
    try:
        sensors.init()

        log_thread = threading.Thread(target=lambda: run_log(60.0))
        log_thread.daemon = True
        log_thread.start()

        http_viewer.run()
    finally:
        sensors.cleanup()
コード例 #17
0
ファイル: lmsensors.py プロジェクト: kippandrew/Diamond
    def collect(self):
        if sensors is None:
            self.log.error('Unable to import module sensors')
            return {}

        sensors.init()
        try:
            for chip in sensors.iter_detected_chips():
                for feature in chip:
                    self.publish(".".join([str(chip), feature.label]), feature.get_value())
        finally:
            sensors.cleanup()
コード例 #18
0
ファイル: cputemp.py プロジェクト: building39/pycoretemp
def temp_handler(name): 
    sensors.init()
    temp = 0.0
    try:
        for chip in sensors.iter_detected_chips():
            if chip.prefix == CORETEMP:
                for feature in chip:
                    if '%s Temperature' % feature.label == name:
                        temp = feature.get_value()
    finally:
        sensors.cleanup()
    return temp
コード例 #19
0
ファイル: lmsensors.py プロジェクト: richardc/Diamond
    def collect(self):
        if sensors is None:
            self.log.error('Unable to import module sensors')
            return {}

        sensors.init()
        try:
            for chip in sensors.iter_detected_chips():
                for feature in chip:
                    self.publish(".".join([str(chip), feature.label]),
                                 feature.get_value())
        finally:
            sensors.cleanup()
コード例 #20
0
def getTemp(name):
  result = dict()
  sensors.init()
  try:
    for chip in sensors.iter_detected_chips():
        for feature in chip:
          try:
              if feature.label == name:
                return feature.get_value()
          except:
            pass
  finally:
      sensors.cleanup()
コード例 #21
0
 def run(self):
     """
     Main program loop. Keep checking the temperature and set fan speed.
     """
     while True:
         try:
             self.check_temperature()
             time.sleep(self.poll_time)
         except Exception, details:
             self.log.error("Main loop ended with exception: %s", details)
             self.log.error("Daemon is shutting down...")
             sensors.cleanup()
             sys.exit(1)
コード例 #22
0
ファイル: temperature.py プロジェクト: sunzu/vot.ar
def get_temp():
    sensors.init()
    temp = 0
    try:
        for chip in sensors.iter_detected_chips():
            for feature in chip:
                sensor_temp = feature.get_value()
                if sensor_temp > temp:
                    temp = sensor_temp
    finally:
        sensors.cleanup()

    return temp
コード例 #23
0
ファイル: fanfare.py プロジェクト: eduardok/fanfare
 def run(self):
     """
     Main program loop. Keep checking the temperature and set fan speed.
     """
     while True:
         try:
             self.check_temperature()
             time.sleep(self.poll_time)
         except Exception, details:
             self.log.error("Main loop ended with exception: %s", details)
             self.log.error("Daemon is shutting down...")
             sensors.cleanup()
             sys.exit(1)
コード例 #24
0
def pysensors():
    """use python sensors package to collect sensor data"""
    #print(f"Using sensors library {sensors.VERSION} ({sensors.LIB_FILENAME})")
    #print()

    html = '<pre>'
    #print(dir(sensors))
    sensors.init()
    try:
        #print(config)
        for chip in sensors.iter_detected_chips():
            if str(chip) in pysensorconfig:
                #print(chip)
                html += str(chip) + '<br>'
                #print('Adapter:', chip.adapter_name)
                #print(repr(config[str(chip)]))
                for feature in chip:
                    #print(config[chip])
                    if feature.name in pysensorconfig[str(chip)]:
                        if 'label' in pysensorconfig[str(chip)]:
                            label = pysensorconfig[str(chip)]['label']
                        else:
                            label = feature.label
                        #print(feature.name)
                        if feature.name.startswith('fan'):
                            #print("%-25s %4d RPM" % (label+':', feature.get_value()))
                            html += "%-25s %4d RPM " % (label + ':',
                                                        feature.get_value())
                            html += "<meter max=2000 min=0 value=%d high=1250 low=750 optimum=100></meter> <br>" % feature.get_value(
                            )
                        if feature.name.startswith('temp'):
                            #print("%-27s %4.1f C" % (label+':', feature.get_value()))
                            html += "%-27s %4.1f&deg;C " % (
                                label + ':', feature.get_value())
                            html += "<meter max=110.0 min=0.0 value=%f high=70.0 low=40.0 optimum=10.0></meter> </br>" % feature.get_value(
                            )
                            #f"{label!r}:"
                            #f" {feature.get_value():.1f}"
                        #)
                        for subfeature in feature:
                            if str(subfeature.name) in pysensorconfig[str(
                                    chip)][feature.name]:
                                #print(f"  {subfeature.name}: {subfeature.get_value():.1f}")
                                #print("     (%s: %4.1f C)" % (subfeature.name, subfeature.get_value()))
                                html += "     (%s: %4.1f&deg;C) <br>" % (
                                    subfeature.name, subfeature.get_value())
                #print()
                html += '<br>'
    finally:
        sensors.cleanup()
    return html
コード例 #25
0
ファイル: cli.py プロジェクト: tedder/pysensors3
def main():
    sensors.init()
    try:
        for chip in sensors.iter_detected_chips():
            print(chip)
            print('Adapter:', chip.adapter_name)
            for feature in chip:
                print('%s (%r): %.1f' %
                      (feature.name, feature.label, feature.get_value()))
                for subfeature in feature:
                    print('  %s: %.1f' %
                          (subfeature.name, subfeature.get_value()))
            print()
    finally:
        sensors.cleanup()
コード例 #26
0
ファイル: coretemp.py プロジェクト: building39/pycoretemp
def coretemp_handler(name):
    
    sensors.init()
    value = 0
    try:
        for chip in sensors.iter_detected_chips():
            if chip.prefix.startswith('coretemp'):
                for feature in chip:
                    if feature.label == name:
                        value = feature.get_value()
                        break
    except:
        print "WTF?!?"
    finally:
        sensors.cleanup()
    return value
コード例 #27
0
ファイル: lm.py プロジェクト: bmcorser/lm-graphs
def create_models():
    sensors.init()
    S = sqla.session()
    try:
        for chip_struct in sensors.iter_detected_chips():
            chip = sqla.create(S, models.Chip, ['addr', 'bus', 'path', 'prefix'], chip_struct)
            S.add(chip)
            S.flush()
            for sensor_struct in chip_struct:
                sensor = sqla.create(S, models.Sensor, ['chip', 'label'], sensor_struct)
                sensor.chip_id = chip.id
                S.add(sensor)
                S.flush()
        S.commit()
    finally:
        sensors.cleanup()
コード例 #28
0
 def __set_chip_read(self):
     """ 
   Queries the chip applies result 
   to the 'read' dict. Then, collects the 
   recommended threshold values 
   """
     r.init()
     try:
         for x in r.iter_detected_chips(CHIP):
             for f in x:
                 if "Core" in f.label:
                     self.read[f.label] = f.get_value()
                     for sub in f:
                         self.__collect_recommended(sub)
     finally:
         r.cleanup()
コード例 #29
0
def main():
    monitor = Monitor()

    updateThread = Thread(target=monitor.update)
    sendThread = Thread(target=monitor.send)

    updateThread.daemon = True
    sendThread.daemon = True

    updateThread.start()
    sendThread.start()

    while (1):
        sleep(1000)

    sensors.cleanup()
コード例 #30
0
def main():
    print(f"Using sensors library {sensors.VERSION} ({sensors.LIB_FILENAME})")
    print()
    sensors.init()
    try:
        for chip in sensors.iter_detected_chips():
            print(chip)
            print('Adapter:', chip.adapter_name)
            for feature in chip:
                print(f"{feature.name} ({feature.label!r}):"
                      f" {feature.get_value():.1f}")
                for subfeature in feature:
                    print(f"  {subfeature.name}: {subfeature.get_value():.1f}")
            print()
    finally:
        sensors.cleanup()
コード例 #31
0
 def getTemperature(self):
     try:
         for chip in sensors.iter_detected_chips():
             for feature in chip:
                 label = feature.label.replace(' ', '-')
                 value = None
                 try:
                     value = feature.get_value()
                 except Exception:
                     value = 0
         if value is not None:
             #print '%s  %s: %.2f' % (chip, feature.label, value)
             return value
         else:
             return 00.0
     finally:
         sensors.cleanup()
コード例 #32
0
ファイル: cli.py プロジェクト: akaIDIOT/python-sensors
def main():
    sensors.init()
    try:
        for chip in sensors.iter_detected_chips():
            print(chip)
            print('Adapter:', chip.adapter_name)
            for feature in chip:
                print('%s (%r): %.1f' % (
                    feature.name, feature.label, feature.get_value()
                ))
                for subfeature in feature:
                    print('  %s: %.1f' % (
                        subfeature.name, subfeature.get_value()
                    ))
            print()
    finally:
        sensors.cleanup()
コード例 #33
0
ファイル: monitor.py プロジェクト: helium876/System-Monitor
def getTemp():
    sensors.init()
    avg = 0
    try:
        for chip in sensors.iter_detected_chips():
            print HEADER + '%s at %s' % (chip, chip.adapter_name) + ENDC
            for feature in chip:
                _system = feature.label
                _system_temp = feature.get_value()
                print BLUE + '\tSystem: %s ' % (_system) + ENDC
                print WARNING + '\tTemp: %.2f°C ' % (_system_temp) + ENDC
                if _system_temp > 60:
                    print FAIL + '\tSystem Overheating' + ENDC
                else:
                    print GREEN + BOLD + '\tSystem OK' + ENDC
                print '\n'
    finally:
        sensors.cleanup()
コード例 #34
0
    def get_core_temp(self):
        if self.os_name == "ubuntu":
            sensors.init()
            max_temp = 0
            sensors.init()
            for chip in sensors.iter_detected_chips():
                for feature in chip:
                    if "temp" in feature.label:
                        core_temp = int(feature.get_value())
                        if core_temp > max_temp:
                            max_temp = core_temp
            sensors.cleanup()
            return max_temp

        if self.os_name == "raspbian":
            process = subprocess.run("/opt/vc/bin/vcgencmd measure_temp",
                                     shell=True,
                                     check=True,
                                     stdout=subprocess.PIPE,
                                     universal_newlines=True)
            return process.stdout[1][5:-2]
コード例 #35
0
def main(argv):
    global serial_com
    comList = []
    # print command line arguments
    if len(argv) < 1:
        comList = [
            '/dev/ttyUSB0', '/dev/ttyUSB1', '/dev/ttyUSB2', '/dev/ttyUSB3'
        ]
    else:
        comList = [argv[0]]
    sensors.init()
    get_sensors()
    #    start('/dev/ttyUSB0')
    while 1:
        for com in comList:
            try:
                start(com)
            except:
                sleep(5)

    sensors.cleanup()
コード例 #36
0
ファイル: lmsensors.py プロジェクト: Logan2211/Diamond
    def collect(self):
        if sensors is None:
            self.log.error('Unable to import module sensors')
            return {}

        sensors.init()
        try:
            for chip in sensors.iter_detected_chips():
                for feature in chip:
                    label = feature.label.replace(' ', '-')
                    value = None
                    try:
                        value = feature.get_value()
                    except Exception:
                        if str_to_bool(self.config['send_zero']):
                            value = 0

                    if value is not None:
                        self.publish(".".join([str(chip), label]), value)
        finally:
            sensors.cleanup()
コード例 #37
0
ファイル: lmsensors.py プロジェクト: isabella232/Diamond-1
    def collect(self):
        if sensors is None:
            self.log.error('Unable to import module sensors')
            return {}

        sensors.init()
        try:
            for chip in sensors.iter_detected_chips():
                for feature in chip:
                    label = feature.label.replace(' ', '-')
                    value = None
                    try:
                        value = feature.get_value()
                    except Exception:
                        if self.config['send_zero']:
                            value = 0

                    if value is not None:
                        self.publish(".".join([str(chip), label]), value)
        finally:
            sensors.cleanup()
コード例 #38
0
ファイル: coretemp.py プロジェクト: building39/pycoretemp
def metric_init(params):
    global descriptors
    
    metric_group = params.get('metric_group', 'coretemp')
    sensors.init()

    for chip in sensors.iter_detected_chips():
        for feature in chip:
            if chip.prefix.startswith('coretemp'):
                descriptors.append({
                    'name': feature.label,
                    'call_back' : coretemp_handler,
                    'time_max' : 60,
                    'units': 'C',
                    'format' : '%.2f',
                    'slope' : 'both',
                    'description' : 'CPU Core Temperature',
                    'groups' : metric_group,
                }) 
    sensors.cleanup()

    return descriptors
コード例 #39
0
    def collectTemperatureMetrics(self):
        gmetric_obj = gmetric.Gmetric(self.gconf.host, self.gconf.port, self.gconf.protocol)

        while not self._stopevent.isSet():
            try:
                sensors.init()
                list_metrics = {}
                for chip in sensors.iter_detected_chips():
                    for feature in chip:
                        fname = str(chip) + "-" + feature.label
                        feature_id = fname.replace(" ", "_")
                        # print '%s: %.2f' % (feature_id, feature.get_value())
                        list_metrics[feature_id] = feature.get_value()

                # send metrics

                # IPMI TOOL FOR mb TEMPERATURE
                # get system wide counters metrics
                p = subprocess.Popen(
                    "sudo ipmitool sdr | grep \"MB Temperature\" | awk '{print $4}'",
                    shell=True,
                    stdout=subprocess.PIPE,
                    stderr=subprocess.PIPE,
                )
                try:
                    ipmi_value = float(p.stdout.readline().strip())
                    list_metrics["MB_Temperature"] = ipmi_value
                except ValueError:
                    pass

                self.sendTemperatureMetrics(list_metrics, gmetric_obj)
                # print list_metrics
            finally:
                sensors.cleanup()

            sleep(self.temperature_interval)

        logger.info("Terminating %s", threading.currentThread().name)
コード例 #40
0
ファイル: temperature.py プロジェクト: bauna/vot.ar
def get_temp():
    sensors.init()
    temp = 0
    try:
        for chip in sensors.ChipIterator():
            for feature in sensors.FeatureIterator(chip):
                subs = list(sensors.SubFeatureIterator(chip, feature))
                try:
                    sensor_temp = sensors.get_value(chip, subs[0].number)
                    # el 200 es por que en las maquinas de desarrollo devuelve
                    # los RPM de los ventiladores como features. Esta es la
                    # solucion menos compleja para descartar ese valor.
                    if sensor_temp < 200 and sensor_temp > temp:
                        temp = sensor_temp
                except Exception:
                    # alguno de los sensores no se pudo leer. en circunstancias
                    # normales no pasa pero atajamoe el error para que siga con
                    # el resto de las featuras
                    pass
    finally:
        sensors.cleanup()

    return temp
コード例 #41
0
def get_temp():
    sensors.init()
    temp = 0
    try:
        for chip in sensors.ChipIterator():
            for feature in sensors.FeatureIterator(chip):
                subs = list(sensors.SubFeatureIterator(chip, feature))
                try:
                    sensor_temp = sensors.get_value(chip, subs[0].number)
                    # el 200 es por que en las maquinas de desarrollo devuelve
                    # los RPM de los ventiladores como features. Esta es la
                    # solucion menos compleja para descartar ese valor.
                    if sensor_temp < 200 and sensor_temp > temp:
                        temp = sensor_temp
                except Exception:
                    # alguno de los sensores no se pudo leer. en circunstancias
                    # normales no pasa pero atajamoe el error para que siga con
                    # el resto de las featuras
                    pass
    finally:
        sensors.cleanup()

    return temp
コード例 #42
0
ファイル: acpi.py プロジェクト: rrader/pySmartHouse
def acpi():
    """
    ACPI sensors (e.g., computer internal temperature)
    """
    sensors.init()
    print "ACPI Sensors found: %s" % list(sensors.iter_detected_chips())

    db = dict((sensor.prefix, sqlite.open(LOG_PATH_FORMAT % sensor.prefix)) for sensor 
                                in sensors.iter_detected_chips() )

    try:
        while True:
            for sensor in sensors.iter_detected_chips():
                #MONGO?
                for feature in sensor:
                    print "%s: %s=%s" % (sensor.prefix, feature.name, feature.get_value())

                db[sensor.prefix][int(time())] = \
                    [(feature.name, feature.get_value()) for feature in sensor]

            sleep(2)
    finally:
        sensors.cleanup()
コード例 #43
0
def overview(request, host_id):
    """
    Overview page.
    """
    if not request.user.is_authenticated():
        return HttpResponseRedirect(reverse('login'))

    errors = []
    time_refresh = TIME_JS_REFRESH

    compute = Compute.objects.get(id=host_id)

    try:
        conn = wvmHostDetails(compute.hostname, compute.login,
                              compute.password, compute.type)
        hostname, host_arch, host_memory, logical_cpu, model_cpu, uri_conn = conn.get_node_info(
        )
        hypervisor = conn.hypervisor_type()
        mem_usage = conn.get_memory_usage()
        conn.close()
    except libvirtError as err:
        errors.append(err)

    sensors.init()
    sensor_output = ""
    try:
        for chip in sensors.iter_detected_chips():
            for feature in chip:
                sensor_output += '%s: %.0fC' % (feature.label,
                                                feature.get_value()) + '\n'
    finally:
        sensors.cleanup()
    sensor_output = sensor_output.strip()

    return render_to_response('hostdetail.html',
                              locals(),
                              context_instance=RequestContext(request))
コード例 #44
0
ファイル: lm.py プロジェクト: bmcorser/lm-graphs
def record():
    sensors.init()
    S = sqla.session()
    sensors_dict = {}
    for chip_struct in sensors.iter_detected_chips():
        for sensor_struct in chip_struct:
            key = "{0}{1}".format(sensor_struct.chip, sensor_struct.label)
            sensors_dict[key] = sqla.get(S, models.Sensor, ['chip', 'label'], sensor_struct).id
    try:
        while True:
            for chip_struct in sensors.iter_detected_chips():
                for sensor_struct in chip_struct:
                    key = "{0}{1}".format(sensor_struct.chip, sensor_struct.label)
                    sensor_id = sensors_dict[key]
                    reading = models.Reading()
                    reading.datetime = datetime.datetime.now()
                    reading_value = sensor_struct.get_value()
                    reading.value = reading_value
                    reading.sensor_id = sensor_id
                    S.add(reading)
                    S.commit()
            time.sleep(1)
    finally:
        sensors.cleanup()
コード例 #45
0
 def makeLCDLines(self):
     global LCDlines
     LCDlines = []
     host_name = socket.gethostname()
     myIP = socket.gethostbyname(host_name + ".local")
     print myIP
     LCDlines.append(myIP)
     #LCDlines.append("some text1")
     #LCDlines.append("some text2")
     sensors.init()
     #print sensors
     #mylist=sensors.iter_detected_chips()
     #print mylist
     try:
         for chip in sensors.iter_detected_chips():
             #print '%s at %s' % (chip, chip.adapter_name)
             for feature in chip:
                 if 'temp1' in feature.label:
                     templine = 'Temp %.2fC' % (feature.get_value())
                     print 'Temp %.2fC' % (feature.get_value())
                     #print ' %s: %.2f' % (feature.label, feature.get_value())
     finally:
         sensors.cleanup()
     LCDlines.append(templine)
コード例 #46
0
# Подключаемся к серверу
client_sensor.connect("ks-cube.tk")

# Запускаем цикл работы с сетевым траффиком
client_sensor.loop_start()

# Запускаем вечный цикл, обрываемый исключением
try:
    sensors.init()

    # Получаем объект для считвания значения температуры
    chip, nr = sensors.get_detected_chips(sensors.parse_chip_name("dell_smm-virtual-0"), 0)

    while True:
        # Получаем текущую температуру 2-го эелемента чипа dell_smm-virtual-0 (CPU)
        payload = sensors.get_value(chip, 2)

        # Публикуем текущую температура, печатаем результат передачи номер сообщения в сессии
        print("temp: {0}".format(payload))
        print(client_sensor.publish("/sensors/book1/cpu", payload=payload, qos=0, retain=False))

        # ...раз в 10 секунд
        time.sleep(10)
finally:  # Если выброшено исключение...
    print("disconnecting")
    client_sensor.loop_stop()  # Останавливаем сетевой цикл, Иначе получим аварийный обрыв соединения
    # и брокер вышлет last will всем подписавшимся клиентам
    client_sensor.disconnect()  # Отключаемся

    sensors.cleanup()  # Чистим после себя
コード例 #47
0
 def quit(self):
     """End of connection."""
     if self.initok:
         sensors.cleanup()
コード例 #48
0
def main():
    while True:
        #read config file
        config = json.load(
            open(os.path.join(os.path.dirname(__file__), u'settings.json'),
                 'r'))

        #get cpu_psutil temperature (depending on platform)
        sensor_temperatures = []
        if platform == u"win32":
            #this is old code using standard wmi provided by windows

            #             try:
            #                 w = wmi.WMI(namespace="root\wmi",privileges=["Security"])
            #
            #                 temperature_infos = w.MSAcpi_ThermalZoneTemperature()
            #                 for idx,temp_cpu_psutil in enumerate(temperature_infos):
            #                     temp = {"Sensor":idx,"Temperature":temp_cpu_psutil.CurrentTemperature/10-273}
            #                     sensor_temperatures.append(temp)
            #             except wmi.x_access_denied:
            #                 print 'Cannot get cpu_psutil temperature, please run as admin!'
            #             except wmi.x_wmi:
            #                 print 'Error grabbing cpu_psutil temperature. Your machine might not be supported.'

            try:
                w = wmi.WMI(namespace="root\OpenHardwareMonitor")
                temperature_infos = w.Sensor()
                for sensor in temperature_infos:
                    if sensor.SensorType == u'Temperature':
                        temp = {
                            u"Sensor": sensor.Name,
                            u"Temperature": sensor.Value
                        }
                        sensor_temperatures.append(temp)
            except wmi.x_wmi, x:
                print u'WMI Exception. Is Open Hardware Monitor running?'
                print u'Exception number', x.com_error.hresult

        if platform == u"linux" or platform == u"linux2":
            try:
                for chip in sensors.iter_detected_chips():
                    #print '%s at %s' % (chip, chip.adapter_name)
                    for feature in chip:
                        #print '  %s: %.2f' % (feature.label, feature.get_value())
                        if feature.label.find(u'Temp'):
                            temp = {
                                u"Sensor": str(chip) + " " + feature.label,
                                u"Temperature": feature.get_value()
                            }
                            sensor_temperatures.append(temp)
            finally:
                sensors.cleanup()
        #print json.dumps(sensor_temperatures)

        #get cpu_psutil time
        cpu_psutil = psutil.cpu_times_percent()
        cpu = {
            u"User": int(cpu_psutil.user),
            u"System": int(cpu_psutil.system),
            u"Idle": int(cpu_psutil.idle)
        }
        #print json.dumps(cpu)

        #get disk information
        hard_drives = []
        for part in psutil.disk_partitions(all=False):
            if not (os.name == u'nt' and
                    (u'cdrom' in part.opts or u'removable' in part.opts)):
                usage = psutil.disk_usage(part.mountpoint)
                hd = {
                    u"Mount": part.mountpoint,
                    u"Free": bytes2human(usage.free),
                    u"Used": bytes2human(usage.used),
                    u"Total": bytes2human(usage.total)
                }
                hard_drives.append(hd)
        #print json.dumps(hard_drives)

        #get memory usage
        physmem_psutil = psutil.virtual_memory()
        physmem = {
            u"Available": bytes2human(physmem_psutil.available),
            u"Used": bytes2human(physmem_psutil.used),
            u"Free": bytes2human(physmem_psutil.free),
            u"Total": bytes2human(physmem_psutil.total)
        }
        #print json.dumps(physmem)

        #get network usage
        nw_psutil = psutil.net_io_counters()
        nw = {
            u"Sent": bytes2human(nw_psutil.bytes_sent),
            u"Recv": bytes2human(nw_psutil.bytes_recv),
            u"PacketsSent": bytes2human(nw_psutil.packets_sent),
            u"PacketsRecv": bytes2human(nw_psutil.packets_recv)
        }
        #print json.dumps(nw)

        #get disk throughput
        disk_tp_psutil = psutil.disk_io_counters()
        disk_tp = {
            u"TimesRead": disk_tp_psutil.read_count,
            u"TimesWrite": disk_tp_psutil.write_count,
            u"BytesRead": bytes2human(disk_tp_psutil.read_bytes),
            u"BytesWrite": bytes2human(disk_tp_psutil.write_bytes)
        }
        #print json.dumps(disk_tpdict)

        #combine all info in a dict
        allinfo = {
            u"Temp": sensor_temperatures,
            u"CPU": cpu,
            u"HDD": hard_drives,
            u"Memory": physmem,
            u"Network": nw,
            u"DiskThroughput": disk_tp
        }

        #dump it into JSON
        data = json.dumps(allinfo,
                          sort_keys=True,
                          indent=4,
                          separators=(',', ': '))
        #send data to URL configured in configuration file
        #important: set correct content type!
        req = urllib2.Request(config[u"url"], data,
                              {u'Content-Type': u'application/json'})
        #get and print response
        with contextlib.closing(urllib2.urlopen(req)) as f:
            response = f.read()
            print response

        #wait delay time before entering next loop
        time.sleep(config[u"delay"])
コード例 #49
0
def main():
    while True:
        # read config file
        config = json.load(open(os.path.join(os.path.dirname(__file__), u"settings.json"), "r"))

        # get cpu_psutil temperature (depending on platform)
        sensor_temperatures = []
        if platform == u"win32":
            # this is old code using standard wmi provided by windows

            #             try:
            #                 w = wmi.WMI(namespace="root\wmi",privileges=["Security"])
            #
            #                 temperature_infos = w.MSAcpi_ThermalZoneTemperature()
            #                 for idx,temp_cpu_psutil in enumerate(temperature_infos):
            #                     temp = {"Sensor":idx,"Temperature":temp_cpu_psutil.CurrentTemperature/10-273}
            #                     sensor_temperatures.append(temp)
            #             except wmi.x_access_denied:
            #                 print 'Cannot get cpu_psutil temperature, please run as admin!'
            #             except wmi.x_wmi:
            #                 print 'Error grabbing cpu_psutil temperature. Your machine might not be supported.'

            try:
                w = wmi.WMI(namespace="root\OpenHardwareMonitor")
                temperature_infos = w.Sensor()
                for sensor in temperature_infos:
                    if sensor.SensorType == u"Temperature":
                        temp = {u"Sensor": sensor.Name, u"Temperature": sensor.Value}
                        sensor_temperatures.append(temp)
            except wmi.x_wmi, x:
                print u"WMI Exception. Is Open Hardware Monitor running?"
                print u"Exception number", x.com_error.hresult

        if platform == u"linux" or platform == u"linux2":
            try:
                for chip in sensors.iter_detected_chips():
                    # print '%s at %s' % (chip, chip.adapter_name)
                    for feature in chip:
                        # print '  %s: %.2f' % (feature.label, feature.get_value())
                        if feature.label.find(u"Temp"):
                            temp = {u"Sensor": str(chip) + " " + feature.label, u"Temperature": feature.get_value()}
                            sensor_temperatures.append(temp)
            finally:
                sensors.cleanup()
        # print json.dumps(sensor_temperatures)

        # get cpu_psutil time
        cpu_psutil = psutil.cpu_times_percent()
        cpu = {u"User": int(cpu_psutil.user), u"System": int(cpu_psutil.system), u"Idle": int(cpu_psutil.idle)}
        # print json.dumps(cpu)

        # get disk information
        hard_drives = []
        for part in psutil.disk_partitions(all=False):
            if not (os.name == u"nt" and (u"cdrom" in part.opts or u"removable" in part.opts)):
                usage = psutil.disk_usage(part.mountpoint)
                hd = {
                    u"Mount": part.mountpoint,
                    u"Free": bytes2human(usage.free),
                    u"Used": bytes2human(usage.used),
                    u"Total": bytes2human(usage.total),
                }
                hard_drives.append(hd)
        # print json.dumps(hard_drives)

        # get memory usage
        physmem_psutil = psutil.virtual_memory()
        physmem = {
            u"Available": bytes2human(physmem_psutil.available),
            u"Used": bytes2human(physmem_psutil.used),
            u"Free": bytes2human(physmem_psutil.free),
            u"Total": bytes2human(physmem_psutil.total),
        }
        # print json.dumps(physmem)

        # get network usage
        nw_psutil = psutil.net_io_counters()
        nw = {
            u"Sent": bytes2human(nw_psutil.bytes_sent),
            u"Recv": bytes2human(nw_psutil.bytes_recv),
            u"PacketsSent": bytes2human(nw_psutil.packets_sent),
            u"PacketsRecv": bytes2human(nw_psutil.packets_recv),
        }
        # print json.dumps(nw)

        # get disk throughput
        disk_tp_psutil = psutil.disk_io_counters()
        disk_tp = {
            u"TimesRead": disk_tp_psutil.read_count,
            u"TimesWrite": disk_tp_psutil.write_count,
            u"BytesRead": bytes2human(disk_tp_psutil.read_bytes),
            u"BytesWrite": bytes2human(disk_tp_psutil.write_bytes),
        }
        # print json.dumps(disk_tpdict)

        # combine all info in a dict
        allinfo = {
            u"Temp": sensor_temperatures,
            u"CPU": cpu,
            u"HDD": hard_drives,
            u"Memory": physmem,
            u"Network": nw,
            u"DiskThroughput": disk_tp,
        }

        # dump it into JSON
        data = json.dumps(allinfo, sort_keys=True, indent=4, separators=(",", ": "))
        # send data to URL configured in configuration file
        # important: set correct content type!
        req = urllib2.Request(config[u"url"], data, {u"Content-Type": u"application/json"})
        # get and print response
        with contextlib.closing(urllib2.urlopen(req)) as f:
            response = f.read()
            print response

        # wait delay time before entering next loop
        time.sleep(config[u"delay"])
コード例 #50
0
ファイル: sensormonman.py プロジェクト: GabMus/gSensorMon
 def stop(self):
     sensors.cleanup()
     self.chips=[]
     self.chipsVal=[]
コード例 #51
0
ファイル: __init__.py プロジェクト: dermatty/GUCK3
def get_status(state_data):
    osversion = os.popen("cat /etc/os-release").read().split("\n")[2].split(
        "=")[1].replace('"', '')

    # os & version
    ret = "------- General -------"
    ret += "\nOS: " + osversion
    ret += "\nVersion: " + os.environ["GUCK3_VERSION"]
    ret += "\nAlarm System Active: "
    ret += "YES" if state_data.PD_ACTIVE else "NO"
    '''ret += "\nRecording: "
    ret += "YES" if recording else "NO"
    ret += "\nPaused: "
    ret += "YES" if not alarmrunning else "NO"
    ret += "\nTelegram Mode: " + TG_MODE
    ret += "\nAI Mode: " + AIMODE.upper()
    ret += "\nAI Sens.: " + str(AISENS)
    ret += "\nHCLIMIT: " + str(HCLIMIT)
    ret += "\nNIGHTMODE: "
    ret += "YES" if NIGHTMODE else "NO"'''
    ret += "\n------- System -------"

    # memory
    overall_mem = round(psutil.virtual_memory()[0] / float(2**20) / 1024, 2)
    free_mem = round(psutil.virtual_memory()[1] / float(2**20) / 1024, 2)
    used_mem = round(overall_mem - free_mem, 2)
    perc_used = round((used_mem / overall_mem) * 100, 2)
    mem_crit = False
    if perc_used > 85:
        mem_crit = True

    # cpu
    cpu_perc0 = psutil.cpu_percent(interval=0.25, percpu=True)
    cpu_avg = sum(cpu_perc0) / float(len(cpu_perc0))
    cpu_perc = (max(cpu_perc0) * 0.6 + cpu_avg * 0.4) / 2
    cpu_crit = False
    if cpu_perc > 0.8:
        cpu_crit = True
    ret += "\nRAM: " + str(perc_used) + "% ( =" + str(used_mem) + " GB) of overall " + str(overall_mem) + \
           " GB used"
    ret += "\nCPU: " + str(round(cpu_avg, 1)) + "% ("
    for cpu0 in cpu_perc0:
        ret += str(cpu0) + " "
    ret += ")"

    # sensors / cpu temp
    sensors.init()
    cpu_temp = []
    for chip in sensors.iter_detected_chips():
        for feature in chip:
            if feature.label[0:4] == "Core":
                temp0 = feature.get_value()
                cpu_temp.append(temp0)
                ret += "\nCPU " + feature.label + " temp.: " + str(
                    round(temp0, 2)) + "°"
    sensors.cleanup()
    if len(cpu_temp) > 0:
        avg_cpu_temp = sum(c for c in cpu_temp) / len(cpu_temp)
    else:
        avg_cpu_temp = 0
    if avg_cpu_temp > 52.0:
        cpu_crit = True
    else:
        cpu_crit = False

    # gpu
    if osversion == "Gentoo/Linux":
        smifn = "/opt/bin/nvidia-smi"
    else:
        smifn = "/usr/bin/nvidia-smi"
    try:
        gputemp = subprocess.Popen(
            [smifn, "--query-gpu=temperature.gpu", "--format=csv"],
            stdout=subprocess.PIPE).stdout.readlines()[1]
        gpuutil = subprocess.Popen(
            [smifn, "--query-gpu=utilization.gpu", "--format=csv"],
            stdout=subprocess.PIPE).stdout.readlines()[1]
        gputemp_str = gputemp.decode("utf-8").rstrip()
        gpuutil_str = gpuutil.decode("utf-8").rstrip()
    except Exception:
        gputemp_str = "0.0"
        gpuutil_str = "0.0%"
    ret += "\nGPU: " + gputemp_str + "°C" + " / " + gpuutil_str + " util."
    if float(gputemp_str) > 70.0:
        gpu_crit = True
    else:
        gpu_crit = False

    cam_crit = False
    if state_data.PD_ACTIVE:
        ret += "\n------- Cameras -------"
        for c in state_data.CAMERADATA:
            cname, cframe, cfps, cisok, cactive, ctx = c
            if not cactive:
                ctstatus0 = "DISABLED"
                ret += "\n" + cname + " " + ctstatus0
            else:
                try:
                    dt = time.time() - ctx
                except Exception:
                    dt = 31
                if dt > 30 or not cisok:
                    ctstatus0 = "DOWN"
                elif dt > 3:
                    ctstatus0 = "DELAYED"
                else:
                    ctstatus0 = "running"
                    if ctstatus0 in ["DOWN", "DELAYED"]:
                        cam_crit = True
                    else:
                        cam_crit = False
                ret += "\n" + cname + " " + ctstatus0 + " @ %3.1f fps" % cfps + ", (%.2f" % dt + " sec. ago)"

    ret += "\n" + get_net_status(state_data)

    temp, hum = get_sens_temp()
    ret += "\n------- Sensors -------"
    ret += "\nTemperature:  " + "%.1f" % temp + "C"
    ret += "\nHumidity: " + "%.1f" % hum + "%"
    ret += "\n------- System Summary -------"
    ret += "\nRAM: "
    ret += "CRITICAL!" if mem_crit else "OK!"
    ret += "\nCPU: "
    ret += "CRITICAL!" if cpu_crit else "OK!"
    ret += "\nGPU: "
    ret += "CRITICAL!" if gpu_crit else "OK!"
    ret += "\nCAMs: "
    if state_data.PD_ACTIVE:
        ret += "CRITICAL!" if cam_crit else "OK!"
    else:
        ret += "NOT RUNNING!"
    return ret, mem_crit, cpu_crit, gpu_crit, cam_crit
コード例 #52
0
 def __del__(self):
     LOG.info('Shutting down AMD + CPU metrics collection....')
     sensors.cleanup()
コード例 #53
0
ファイル: pysense.py プロジェクト: BruceJohnJennerLawso/scrap
import sensors



if(__name__ == "__main__"):
	sensors.init()
	try:
		for chip in sensors.iter_detected_chips():
			print '%s at %s' % (chip, chip.adapter_name)
			for feature in chip:
				print '  %s: %.2f' % (feature.label, feature.get_value())
	finally:
		sensors.cleanup()
コード例 #54
0
ファイル: sensors-trayicon.py プロジェクト: abbarrasa/openbox
            u"This program is distributed in the hope that it will be useful, "
            u"but WITHOUT ANY WARRANTY; without even the implied warranty of "
            u"MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the "
            u"GNU General Public License for more details.\n"
            u"\n"
            u"You should have received a copy of the GNU General Public "
            u"License along with this program. If not, see "
            u"<http://www.gnu.org/licenses/>."
        )
        about_dialog.set_wrap_license(True)
        about_dialog.run()
        about_dialog.destroy()

    def update_menu(self):
        mysensors = self.sensors.get_sensors()
        for sensor in mysensors:
            label = '{0}: {1}'.format(
                mysensors[sensor]['label'], mysensors[sensor]['format'])
            setlabel = label % mysensors[sensor]['value']
            self.items[sensor].set_label(setlabel)

        return True

if __name__ == "__main__":
    pysensors.init()
    try:
        SystrayIcon()
        gtk.main()
    finally:
        pysensors.cleanup()
コード例 #55
0
def quit(_):
    gtk.main_quit()
    sensors.cleanup()
コード例 #56
0
ファイル: sense.py プロジェクト: FPar/gnome15
 def stop(self):
     if self.started:
         sensors.cleanup()
コード例 #57
0
dicMotherboardReadings = {}
try:
    if bDebugPrint == 1:
        print('List of Detected Sensors:')
    for chip in sensors.iter_detected_chips(
    ):  # Loop through the chips on the motherboard
        if bDebugPrint == 1:
            print '%s at %s' % (chip, chip.adapter_name)
        for feature in chip:  # Loop though the sensors in each chip
            dicMotherboardReadings[
                chip.adapter_name + ' ' + feature.label] = feature.get_value(
                )  #Add chip name and feature name as key and feature as value
            if bDebugPrint == 1:
                print '  %s: %.2f' % (feature.label, feature.get_value())
finally:
    sensors.cleanup()
if bDebugPrint == 1:
    print('Motherboard Readings Dictionary:')
    print(dicMotherboardReadings)
# Add the motherboard data that I am interested in to the emoncms dictionary
dicEmoncmsData['ISA_adapter_temp1'] = dicMotherboardReadings[
    'ISA adapter temp1']
dicEmoncmsData['ISA_adapter_temp2'] = dicMotherboardReadings[
    'ISA adapter temp2']
dicEmoncmsData['ISA_adapter_temp3'] = dicMotherboardReadings[
    'ISA adapter temp3']

# Get hard drive temperatures
lsHardDriveIDs = Get_Device_Ids()  # Get list of hard drives
if bDebugPrint == 1:
    if ([] == lsHardDriveIDs): print "No devices found."