Exemplo n.º 1
0
    def test_equals(self):
        chip_name = sensors.ChipName()
        self.assertEqual(chip_name, chip_name)
        self.assertEqual(sensors.ChipName(), sensors.ChipName())
        self.assertEqual(sensors.ChipName('prefix', 10, 2, 15, 'path'),
                         sensors.ChipName('prefix', 10, 2, 15, 'path'))

        for chip_name in sensors.get_detected_chips():
            self.assertEqual(chip_name, chip_name)

        for c1, c2 in zip(sensors.get_detected_chips(),
                          sensors.get_detected_chips()):
            self.assertEqual(c1, c2)
Exemplo n.º 2
0
def get_sensors():
    """ Detect and return a list of Sensor objects """
    import sensors
    found_sensors = list()

    def get_subfeature_value(feature, subfeature_type):
        subfeature = chip.get_subfeature(feature, subfeature_type)
        if subfeature:
            return chip.get_value(subfeature.number)

    for chip in sensors.get_detected_chips():
        for feature in chip.get_features():
            if feature.type == sensors.FEATURE_TEMP:
                try:
                    name = chip.get_label(feature)
                    max = get_subfeature_value(feature,
                                               sensors.SUBFEATURE_TEMP_MAX)
                    current = get_subfeature_value(
                        feature, sensors.SUBFEATURE_TEMP_INPUT)
                    critical = get_subfeature_value(
                        feature, sensors.SUBFEATURE_TEMP_CRIT)
                    if critical:
                        found_sensors.append(
                            Sensor(name=name,
                                   current=current,
                                   maximum=max,
                                   critical=critical))
                except sensors.SensorsException:
                    continue
    return found_sensors
Exemplo n.º 3
0
    def test_equals(self):
        subfeature = sensors.Subfeature()
        self.assertEqual(subfeature, subfeature)
        self.assertEqual(sensors.Subfeature(), sensors.Subfeature())

        c = sensors.get_detected_chips()[0]
        subfeatures = c.get_all_subfeatures(c.get_features()[0])

        for s1, s2 in zip(subfeatures, list(subfeatures)):
            self.assertEqual(s1, s2)
Exemplo n.º 4
0
def print_stuff():
    for chip in sensors.get_detected_chips():
        print chip

        for feature in chip.get_features():
            print ' ', chip.get_label(feature)

            for subfeature in chip.get_all_subfeatures(feature):
                print '   ', subfeature, chip.get_value(subfeature.number)

            print
Exemplo n.º 5
0
def print_stuff():
    for chip in sensors.get_detected_chips():
        print chip

        for feature in chip.get_features():
            print ' ', chip.get_label(feature)

            for subfeature in chip.get_all_subfeatures(feature):
                print '   ', subfeature, chip.get_value(subfeature.number)

            print
Exemplo n.º 6
0
    def test_equals(self):
        feature = sensors.Feature()
        self.assertEqual(feature, feature)
        self.assertEqual(sensors.Feature(), sensors.Feature())
        c = sensors.get_detected_chips()[0]

        for feature in c.get_features():
            self.assertEqual(feature, feature)

        for f1, f2 in zip(c.get_features(), c.get_features()):
            self.assertEqual(f1, f2)
Exemplo n.º 7
0
def print_stuff():
    for chip in sensors.get_detected_chips():
        print(chip)

        for feature in chip.get_features():
            print('  {0}'.format(chip.get_label(feature)))

            for subfeature in chip.get_all_subfeatures(feature):
                print('    {0}'.format(subfeature,
                                       chip.get_value(subfeature.number)))

            print()
Exemplo n.º 8
0
def main():
    global config
    global state

    print("Starting fan control script.")
    for host in config['hosts']:
        print(
            "[{}] Thresholds of {}°C ({}%), {}°C ({}%) and {}°C ({}%)".format(
                host['name'],
                host['temperatures'][0],
                host['speeds'][0],
                host['temperatures'][1],
                host['speeds'][1],
                host['temperatures'][2],
                host['speeds'][2],
            ))

    while True:
        for host in config['hosts']:
            temps = []

            if not state[host['name']]['is_remote']:
                cores = []
                for sensor in sensors.get_detected_chips():
                    if sensor.prefix == "coretemp":
                        cores.append(sensor)
                for core in cores:
                    for feature in core.get_features():
                        for subfeature in core.get_all_subfeatures(feature):
                            if subfeature.name.endswith("_input"):
                                temps.append(core.get_value(subfeature.number))
            else:
                cmd = os.popen(host['remote_temperature_command'])
                temps = list(
                    map(lambda n: float(n),
                        cmd.read().strip().split('\n')))
                cmd.close()

            temp_average = round(sum(temps) / len(temps))
            compute_fan_speed(temp_average, host)

        time.sleep(config['general']['interval'])
Exemplo n.º 9
0
def get_sensors():
    """ Detect and return a list of Sensor objects """
    import sensors
    found_sensors = list()

    def get_subfeature_value(feature, subfeature_type):
        subfeature = chip.get_subfeature(feature, subfeature_type)
        if subfeature:
            return chip.get_value(subfeature.number)

    for chip in sensors.get_detected_chips():
        for feature in chip.get_features():
            if feature.type == sensors.FEATURE_TEMP:
                name = chip.get_label(feature)
                max = get_subfeature_value(feature, sensors.SUBFEATURE_TEMP_MAX)
                current = get_subfeature_value(feature, sensors.SUBFEATURE_TEMP_INPUT)
                critical = get_subfeature_value(feature, sensors.SUBFEATURE_TEMP_CRIT)
                if critical:
                    found_sensors.append(Sensor(name=name, current=current, maximum=max, critical=critical))
    return found_sensors
Exemplo n.º 10
0
    def __init__(self):
        gtk.Window.__init__(self,
                            title='Sensors information',
                            default_width=800,
                            default_height=500)
        self.connect('destroy', gtk.main_quit)
        self.store = gtk.TreeStore(str, str, str)

        for chip in sensors.get_detected_chips():
            chip_parent = self.store.append(None, [str(chip), '', repr(chip)])

            for feature in chip.get_features():
                feature_parent = self.store.append(
                    chip_parent, [chip.get_label(feature), '',
                                  repr(feature)])

                for subfeature in chip.get_all_subfeatures(feature):
                    self.store.append(feature_parent, [
                        subfeature.name, '{0:.2f}'.format(
                            chip.get_value(subfeature.number)),
                        repr(subfeature)
                    ])

        self.tree = gtk.TreeView(self.store)
        self.tree.set_search_column(0)
        self.tree.expand_all()
        renderer = gtk.CellRendererText()
        name_column = gtk.TreeViewColumn('Name', renderer, text=0)
        self.tree.append_column(name_column)
        name_column.set_resizable(True)
        value_column = gtk.TreeViewColumn('Value', renderer, text=1)
        self.tree.append_column(value_column)
        value_column.set_resizable(True)
        info_column = gtk.TreeViewColumn('Additional info', renderer, text=2)
        self.tree.append_column(info_column)
        s = gtk.ScrolledWindow()
        self.add(s)
        s.add(self.tree)
        self.show_all()
Exemplo n.º 11
0
    def __init__(self):
        gtk.Window.__init__(self, title='Sensors information',
                            default_width=800, default_height=500)
        self.connect('destroy', gtk.main_quit)
        self.store = gtk.TreeStore(str, str, str)

        for chip in sensors.get_detected_chips():
            chip_parent = self.store.append(None, [str(chip), '', repr(chip)])

            for feature in chip.get_features():
                feature_parent = self.store.append(
                    chip_parent, [chip.get_label(feature), '', repr(feature)])

                for subfeature in chip.get_all_subfeatures(feature):
                    self.store.append(
                        feature_parent,
                        [subfeature.name,
                         '{0:.2f}'.format(chip.get_value(subfeature.number)),
                                       repr(subfeature)])

        self.tree = gtk.TreeView(self.store)
        self.tree.set_search_column(0)
        self.tree.expand_all()
        renderer = gtk.CellRendererText()
        name_column = gtk.TreeViewColumn('Name', renderer, text=0)
        self.tree.append_column(name_column)
        name_column.set_resizable(True)
        value_column = gtk.TreeViewColumn('Value', renderer, text=1)
        self.tree.append_column(value_column)
        value_column.set_resizable(True)
        info_column = gtk.TreeViewColumn('Additional info', renderer, text=2)
        self.tree.append_column(info_column)
        s = gtk.ScrolledWindow()
        self.add(s)
        s.add(self.tree)
        self.show_all()
Exemplo n.º 12
0
# Инициализируем объект-клиент
client_sensor = mqtt.Client(client_id="BookPublisher", clean_session=False, userdata=None, protocol=mqtt.MQTTv311)

# Подключаемся к серверу
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 всем подписавшимся клиентам