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
def updateLmSensors(self): for chip in sensors.iter_detected_chips(): if chip.prefix == b'w83627dhg': for f in chip: if f.label.startswith('temp'): # print(f.label) self.readings[self.aliases[f.label]] = f.get_value()
def update(_): indicator.set_label(prefix + str(tempconvert(int(selected.get_value()))) + deg, '00°C') global chips chips = [] for chip in sensors.iter_detected_chips(): chips.append(chip) return True
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)
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()
def __init__(self): """Initialize""" print("Initialize") if os.name == "posix": sensors.init() self.ser = serial.Serial() self.ser.baudrate = 9600 self.ser.port = PORT try: self.ser.open() except: print("no serial port") if os.name == "posix": self.chips = [[0 for feature in chip] for chip in sensors.iter_detected_chips()] self.cores = psutil.cpu_count() self.cpuTotal = psutil.cpu_percent() self.cpu = [0 for cores in range(self.cores)] self.mem = psutil.virtual_memory() self.disk = psutil.disk_usage('/') self.netio = psutil.net_io_counters() self.netup = 0 self.netdw = 0 self.lastnetup = 0 self.lastnetdw = 0 self.interval = 1
def _get_detected_chips(): # pragma: no cover sensors.cleanup() sensors.init() chips_detected = list(sensors.iter_detected_chips()) return chips_detected
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
def __update__(self): """Update the stats.""" # Reset the list self.reset() if self.initok: for chip in sensors.iter_detected_chips(): for feature in chip: sensors_current = {} if feature.name.startswith(b'temp'): # Temperature sensor sensors_current['unit'] = SENSOR_TEMP_UNIT elif feature.name.startswith(b'fan'): # Fan speed sensor sensors_current['unit'] = SENSOR_FAN_UNIT if sensors_current: try: sensors_current['label'] = feature.label sensors_current['value'] = int(feature.get_value()) except SensorsError as e: logger.debug("Cannot grab sensor stat(%s)" % e) else: self.sensors_list.append(sensors_current) return self.sensors_list
def update_sensors(self): # Temperature sensors for chip in pysensors.iter_detected_chips(): for feature in chip: if feature.type == self.__FEATURE_TEMP: self.append_sensor( chip.prefix + '_' + feature.name, feature.label, '%.1f ºC', feature.get_value(), 100.0) # Cpu usage self.append_sensor( 'cpu', 'CPU usage', '%.1f %%', psutil.cpu_percent(interval=1), 95.0) # Memory usage vmem = psutil.virtual_memory() self.append_sensor( 'memory', 'Memory usage', '%.1f %%', vmem.percent, 95.0) # Swap usage vswap = psutil.swap_memory() self.append_sensor( 'swap', 'Swap usage', '%.1f %%', vswap.percent, 95.0)
def get_sensors(self): sensor_objects = [] sensor_names = [] for chip in sensors.iter_detected_chips(): logger.debug("Found chip %s, adapter %s", chip, chip.adapter_name) for feature in chip: sensor_name = feature.label # Prevent name conflicts across chips if not sensor_name in sensor_names: sensor_names.append(sensor_name) else: o = sensor_name idx = 1 while sensor_name in sensor_names: idx += 1 sensor_name = "%s-%d" % (o, idx) sensor_names.append(sensor_name) logger.debug("' %s: %.2f", sensor_name, feature.get_value()) sensor = Sensor(feature.type, sensor_name, float(feature.get_value())) sensor_objects.append(sensor) for subfeature in feature: name = subfeature.name if name.endswith("_crit"): sensor.critical = float(subfeature.get_value()) elif name.endswith("_input"): sensor.value = float(subfeature.get_value()) return sensor_objects
def fetch_sensor_data(): try: sensors.init() data = {} for chip in sensors.iter_detected_chips(): for feature in chip: # log stuff we care about if feature.label not in IGNORE_READINGS: data[feature.label] = round(feature.get_value(), 3) sorted_data = collections.OrderedDict(sorted(data.items())) write_data_file(sorted_data) if USE_REDIS: import redis REDIS_CONNECTION = redis.StrictRedis(host='localhost', port=6379, db=0) write_data_redis(sorted_data) if USE_INFLUX: from influxdb import InfluxDBClient INFLUX_CLIENT = InfluxDBClient('localhost', 8086, 'root', 'root', 'jarvis') write_data_influx(sorted_data, INFLUX_CLIENT) for name, reading in sorted_data.iteritems(): print "{0}: {1}".format(name, reading) except Exception as exception: print_exc() print "Failed to get sensor data: {0}".format(exception.message)
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
def update(_): indicator.set_label( prefix + str(tempconvert(int(selected.get_value()))) + deg, '00°C') global chips chips = [] for chip in sensors.iter_detected_chips(): chips.append(chip) return True
def updateInfoPerSecond(self): self.cpuPercent = psutil.cpu_percent(interval=1, percpu=True) self.ramInfo = psutil.virtual_memory() self.swapInfo = psutil.swap_memory() self.diskParts = psutil.disk_partitions() self.diskPartsUsage = {} for disk in self.diskParts: mnt = disk.mountpoint usage = psutil.disk_usage(mnt) self.diskPartsUsage.update({mnt: usage}) self.oldNetCounters = self.netCounters self.netCounters = psutil.net_io_counters(pernic=True) self.netNicStats = psutil.net_if_stats() self.netStats = {} for nic in self.netCounters.iterkeys(): m = self.netNicStats[nic].speed sent = self.netCounters[nic].bytes_sent recv = self.netCounters[nic].bytes_recv oSent = self.oldNetCounters[nic].bytes_sent oRecv = self.oldNetCounters[nic].bytes_recv sent = (sent - oSent) * 8 recv = (recv - oRecv) * 8 try: pr = recv / (m * 1000.0) except ZeroDivisionError: pr = 0 try: ps = sent / (m * 1000.0) except ZeroDivisionError: ps = 0 self.netStats.update( {nic: { 'sent': sent, 'recv': recv, 's_per': ps, 'r_per': pr }}) self.sensors = [] for c in sensors.iter_detected_chips(): for f in c: self.sensors.append(f.get_value()) self.raid = {} self.raid = readRaid() #fetches the data from hddtemp #self.hdd = {} try: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect(('localhost', 7634)) data = s.recv(4096) s.close() parts = data.split('|') for i in range(1, len(parts), 5): self.hdd[parts[i].split('/dev/')[1]] = int(parts[i + 2]) except: pass
def collect_sensor_data(): data = {} for chip in sensors.iter_detected_chips(): for feature in chip: try: data[f'{chip}.{feature.label}'] = feature.get_value() except: # noqa: E722 pass return data
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()
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
def _get_temp(self): import sensors sensors.init() for chip in sensors.iter_detected_chips(): if not 'temp' in str(chip): continue tot = 0 for i, feature in enumerate(chip): tot += feature.get_value() return float(tot) / (i + 1) return None
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
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()
def get_temp(self,sensor_name): """ doc """ data_list = list() for chip in sensors.iter_detected_chips(): if str(chip) == sensor_name: for feature in chip: sensor_data = dict() sensor_data['label'] = feature.label sensor_data['value'] = feature.get_value() data_list.append(sensor_data) return data_list
def get_sensors_temp(): temp = {} chips = sensors.iter_detected_chips() for chip in chips: features = {} for feature in chip: # temperature type is 2 if feature.type == 2: features[feature.label] = feature.get_value() if features: temp[str(chip)] = features return temp
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
def get_cpu_temperature() -> float: """ Returns CPU temperature in degrees celsius read from sensors based on constants specified in file header. :return: CPU temperature in degrees celsius. """ # Iter sensors. for chip in sensors.iter_detected_chips(): if chip.addr == SENSOR_ADDR and chip.prefix.decode( 'utf-8') == SENSOR_PREFIX: # Sensor matches, try reading features. for feature in chip: if feature.label == SENSOR_FEATURE_LABEL: return feature.get_value()
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()
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°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°C) <br>" % ( subfeature.name, subfeature.get_value()) #print() html += '<br>' finally: sensors.cleanup() return html
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()
def update(self): while True: """Update Data""" if os.name == "posix": i = 0 for chip in sensors.iter_detected_chips(): j = 0 for feature in chip: self.chips[i][j] = feature.get_value() j += 1 i += 1 cpuTotal = psutil.cpu_percent() self.cpuTotal = str(cpuTotal) cpu = psutil.cpu_percent(percpu=True) for i in range(self.cores): cpu[i] = str(cpu[i]) if len(cpu[i]) == 3: cpu[i] = cpu[i] + "0 " elif len(cpu[i]) == 4: cpu[i] = cpu[i] + " " self.cpu[i] = cpu[i] self.mem = psutil.virtual_memory() self.disk = psutil.disk_usage('/') self.netio = psutil.net_io_counters() self.netup = self.netio.bytes_sent - self.lastnetup self.netdw = self.netio.bytes_recv - self.lastnetdw self.lastnetup = self.netio.bytes_sent self.lastnetdw = self.netio.bytes_recv self.netup = str(self.netup / 1000) self.netdw = str(self.netdw / 1000) if len(self.netup) == 1: self.netup = self.netup + " " if len(self.netup) == 2: self.netup = self.netup + " " if len(self.netdw) == 1: self.netdw = self.netdw + " " if len(self.netdw) == 2: self.netdw = self.netdw + " " if len(self.netdw) == 3: self.netdw = self.netdw + " " sleep(1)
def updateInfoPerSecond(self): self.cpuPercent = psutil.cpu_percent(interval=1, percpu=True) self.ramInfo = psutil.virtual_memory() self.swapInfo = psutil.swap_memory() self.diskParts = psutil.disk_partitions() self.diskPartsUsage = {} for disk in self.diskParts: mnt = disk.mountpoint usage = psutil.disk_usage(mnt) self.diskPartsUsage.update({mnt:usage}) self.oldNetCounters = self.netCounters self.netCounters = psutil.net_io_counters(pernic=True) self.netNicStats = psutil.net_if_stats() self.netStats = {} for nic in self.netCounters.iterkeys(): m = self.netNicStats[nic].speed sent = self.netCounters[nic].bytes_sent recv = self.netCounters[nic].bytes_recv oSent = self.oldNetCounters[nic].bytes_sent oRecv = self.oldNetCounters[nic].bytes_recv sent = (sent-oSent)*8 recv = (recv-oRecv)*8 try: pr = recv/(m*1000.0) except ZeroDivisionError: pr = 0 try: ps = sent/(m*1000.0) except ZeroDivisionError: ps = 0 self.netStats.update({nic:{'sent':sent, 'recv':recv, 's_per':ps, 'r_per':pr}}) self.sensors = [] for c in sensors.iter_detected_chips(): for f in c: self.sensors.append(f.get_value()) self.raid = {} self.raid = readRaid() #fetches the data from hddtemp #self.hdd = {} try: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect(('localhost',7634)) data = s.recv(4096) s.close() parts = data.split('|') for i in range(1,len(parts),5): self.hdd[parts[i].split('/dev/')[1]] = int(parts[i+2]) except: pass
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()
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()
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()
def __update__(self): """Update the stats.""" # Reset the list self.reset() # grab only temperature stats if self.initok: for chip in sensors.iter_detected_chips(): for feature in chip: sensors_current = {} if feature.name.startswith(b'temp'): sensors_current['label'] = feature.label sensors_current['value'] = int(feature.get_value()) self.sensors_list.append(sensors_current) return self.sensors_list
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
def collect_metrics(self): """ Starts the AMD GPU and CPU-core temperature data collection """ amdgpu_count = 0 json_body = [] for chip in sensors.iter_detected_chips(): if chip.prefix == 'amdgpu': json_body.append( self._collect_amd_gpu_metrics(chip, amdgpu_count)) amdgpu_count += 1 elif chip.prefix == 'coretemp': json_body.append(self._collect_cpu_metrics(chip)) time.sleep(_PERIOD_SECONDS) return json_body
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()
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()
def log_one_iter(): with log_lock: time_id = data.add_time(datetime.datetime.now()) for chip in sensors.iter_detected_chips(): chip_name = str(chip) features = chip_features(chip_name) if not features: continue print(chip_name) for feature in chip: if not feature_enabled(features, feature.label): continue print(' {}: {}'.format(feature.label, feature.get_value())) # Add to the log data.add_feature_value(time_id, chip_name, feature)
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()
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()
def load_sensors(self): # build a temp hashmap to collect sensors id & address sensors.init() for chip in sensors.iter_detected_chips(): for feature in chip: if feature.label in self.cfg['sensors'].keys(): dev = xaal.lib.Device("thermometer.basic") dev.address = self.cfg['sensors'][feature.label]['addr'] dev.vendor_id = "IHSEV" dev.product_id = "LM_SENSOR" dev.url = "https://wiki.archlinux.org/index.php/Lm_sensors" dev.info = "%s/%s/%s" % (platform.node(),chip.adapter_name,feature.label) dev.version = 0.2 temp = dev.new_attribute("temperature") name = "%s:%s" % (chip,feature.label) self.data.update({name:temp}) self.engine.add_device(dev) dev.dump()
def update(self): self.data = {} for chip in sensors.iter_detected_chips(): chip_name = str(chip).lower() adapter_name = chip.adapter_name.lower() for atype in ('acpi', 'isa'): if atype in chip_name + adapter_name: adapter = {} if atype not in self.data: self.data[atype] = [] for feature in chip: label = self._clean_name(feature.label) value = feature.get_value() if value: adapter[label] = value if label == 'temp1': adapter['mb_temperature'] = value if label == 'temp2': adapter['cpu_temperature'] = value self.data[atype].append(adapter) super(Plugin, self).update()
def __init__(self): if not 'FONT' in globals(): raise Exception('Config not loaded, missing \'from config import *\'?') sensors.init() for chip in sensors.iter_detected_chips(): for feature in chip: self.cpusensor = feature break self.lastsent = 0 self.lastrecv = 0 self.lasttimestamp = None self.blink_batt = True self.refresh_batt_left_in = 0 self.time_batt_remaining = 0 self.re_cpufreq = re.compile('^cpu .*(?P<tst> \d+\.\d*)$', re.M|re.I)
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()
def system_status(self): msg = SystemStatus() msg.cpu_usage_average = psutil.cpu_percent(interval=0.0) msg.cpu_usage_detail = psutil.cpu_percent(interval=0.0, percpu=True) msg.mem_usage = psutil.phymem_usage()[3] temps = [] #print "sys 1 sensors" #res = os.popen("sensors | grep Core") #print "sys after sensors" for chip in sensors.iter_detected_chips(): for feature in chip: if "Core " in feature.label: temps.append(feature.get_value()) #for line in res.readlines(): # print "lines" # print line # temps.append(float(re.search('\+(.*?)\W\WC', line).group(1))) #print temps msg.cpu_temp_detail = temps msg.cpu_temp_average = numpy.mean(temps) self.stat_system = DiagnosticStatus(name="computer: System", level=DiagnosticStatus.OK, message="OK") self.stat_system.values = [ KeyValue("CPU usage", str(msg.cpu_usage_average)), KeyValue("CPU temp (C)", str(msg.cpu_temp_average)), KeyValue("Memory usage", str(msg.mem_usage)) ] if msg.cpu_temp_average > SystemInfo.CPU_TEMP_ERROR: self.stat_system.level = DiagnosticStatus.ERROR self.stat_system.message = "CPU overheating" elif msg.cpu_temp_average > SystemInfo.CPU_TEMP_WARN: self.stat_system.level = DiagnosticStatus.WARNING self.stat_system.message = "CPU overheating" elif msg.cpu_usage_average > SystemInfo.CPU_USAGE_ERROR: self.stat_system.level = DiagnosticStatus.ERROR self.stat_system.message = "High CPU load" elif msg.cpu_usage_average > SystemInfo.CPU_USAGE_WARN: self.stat_system.level = DiagnosticStatus.WARN self.stat_system.message = "High CPU load" return msg
def __init__(self): if not 'FONT' in globals(): raise Exception( 'Config not loaded, missing \'from config import *\'?') sensors.init() for chip in sensors.iter_detected_chips(): for feature in chip: self.cpusensor = feature break self.lastsent = 0 self.lastrecv = 0 self.lasttimestamp = None self.blink_batt = True self.refresh_batt_left_in = 0 self.time_batt_remaining = 0 self.re_cpufreq = re.compile('^cpu .*(?P<tst> \d+\.\d*)$', re.M | re.I)
def hwmon_get_values(): volts = [] power = [] temperatures = [] for chip in sensors.iter_detected_chips(): # read voltage and power values for feature in chip: if str(chip) in sensor: if feature.label == "in1": if feature.label in sensor[str( chip)] and 'compute' in sensor[str(chip)][ feature.label]: # print(str(chip) + ' : ' + str(eval(str(feature.get_value()) + str(sensor[str(chip)][feature.label][compute])))) volts.append( eval( str(feature.get_value()) + str(sensor[str( chip)][feature.label]['compute']))) else: volts.append(feature.get_value()) if feature.label == "power1": if feature.label in sensor[str( chip)] and 'compute' in sensor[str(chip)][ feature.label]: # print(str(chip) + ' : ' + str(eval(str(feature.get_value()) + str(sensor[str(chip)][feature.label][compute])))) power.append( eval( str(feature.get_value()) + str(sensor[str( chip)][feature.label]['compute']))) else: power.append(feature.get_value()) if 'temp' in feature.label: if feature.label in sensor[str( chip)] and 'compute' in sensor[str(chip)][ feature.label]: # print(feature.label + ' : ' + str(eval(str(feature.get_value()) + str(sensor[str(chip)][feature.label]['compute']))))) temperatures.append( eval( str(feature.get_value()) + str(sensor[str( chip)][feature.label]['compute']))) else: temperatures.append(feature.get_value()) return volts, power, temperatures
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()
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]
def check_temperature(self): """ Check label value, if it exceeds treshold, set fan to full speed. """ for chip in sensors.iter_detected_chips(): for feature in chip: if feature.label == self.target_label: if feature.get_value() >= self.temp_treshold: if not self.full_speed_on: self.log.info('%s: %.2f exceeds the treshold %.2f', feature.label, feature.get_value(), self.temp_treshold) self.set_fan_speed('full-speed') self.full_speed_on = True else: if self.full_speed_on: self.log.info('%s: %.2f back below %.2f', feature.label, feature.get_value(), self.temp_treshold) self.set_fan_speed('auto') self.full_speed_on = False
def __update__(self): """Update the stats.""" # Reset the list self.reset() if self.initok: for chip in sensors.iter_detected_chips(): for feature in chip: sensors_current = {} if feature.name.startswith(b'temp'): # Temperature sensor sensors_current['unit'] = SENSOR_TEMP_UNIT elif feature.name.startswith(b'fan'): # Fan speed sensor sensors_current['unit'] = SENSOR_FAN_UNIT if sensors_current: sensors_current['label'] = feature.label sensors_current['value'] = int(feature.get_value()) self.sensors_list.append(sensors_current) return self.sensors_list
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()
def __init__(self, callback): threading.Thread.__init__(self) self.name = "TempMonThread" self.callback = callback self.error = None sensors.init() for chip in sensors.iter_detected_chips(): if "acpi" in str(chip): break else: self.die = True self.error = "Could not read acpi bus: Temperature monitoring disabled" return self.chip = chip for feature in chip: if 'MB Temperature' in feature.label: break else: self.die = True return self.feature = feature self.die = False
def update(self): print("Reading sensors") cpu_counter = 0 fan_count = 0 for chip in sensors.iter_detected_chips(): for feature in chip: if feature.get_value() > 0 and feature.label != 'CPUTIN': if 'cpu' in feature.label.lower( ) or 'core' in feature.label.lower( ) and cpu_counter < self.cpus: self.data['CPU{}'.format(cpu_counter)] = Data( feature.label, feature.get_value()) cpu_counter += 1 elif 'fan' in feature.label.lower(): self.data['FAN{}'.format(fan_count)] = Data( feature.label, feature.get_value()) fan_count += 1 elif 'sys' in feature.label.lower(): self.data['SYSTEM'] = Data(feature.label, feature.get_value())