timofurrer / w1thermsensor

A Python package and CLI tool to work with w1 temperature sensors like DS1822, DS18S20 & DS18B20 on the Raspberry Pi, Beagle Bone and other devices.
MIT License
493 stars 113 forks source link

How to return name of sensor? #78

Closed mplinuxgeek closed 4 years ago

mplinuxgeek commented 4 years ago

Is there a better way to get the sensor name?

I'm not very well versed in Python, I'm able to put together examples to build scripts to do what I want but that's about it...

I'm using the w1thermsensor library to publish all DS sensors on the 1wire bus to Home Assistant and would also like to include the sensor type in the discovery config, I currently do this by taking some of you code, namely the sensor definitions to convert the sensor type to a name, surely theres a better way but I don't know how I would do it with your library, could you point me in the right direction?

THERM_SENSOR_DS18S20 = 0x10
THERM_SENSOR_DS1822 = 0x22
THERM_SENSOR_DS18B20 = 0x28
THERM_SENSOR_DS1825 = 0x3B
THERM_SENSOR_DS28EA00 = 0x42
THERM_SENSOR_MAX31850K = 0x3B
TYPE_NAMES = {
    THERM_SENSOR_DS18S20: "DS18S20",
    THERM_SENSOR_DS1822: "DS1822",
    THERM_SENSOR_DS18B20: "DS18B20",
    THERM_SENSOR_DS1825: "DS1825",
    THERM_SENSOR_DS28EA00: "DS28EA00",
    THERM_SENSOR_MAX31850K: "MAX31850K",
}

while True:
    for sensor in W1ThermSensor.get_available_sensors():
        sensor_type_name = TYPE_NAMES.get(sensor.type, hex(sensor.type))
        temperature = sensor.get_temperature()
        sensor_id = sensor.id
        print("%s %s %.2f" % (sensor_type_name, sensor_id, temperature))
timofurrer commented 4 years ago

There is a type_name property on any W1ThermSensor which does exactly that for you:

while True:
    for sensor in W1ThermSensor.get_available_sensors():
        sensor_type_name = sensor.type_name
        temperature = sensor.get_temperature()
        sensor_id = sensor.id
        print("%s %s %.2f" % (sensor_type_name, sensor_id, temperature))

Have fun :tada:

mplinuxgeek commented 4 years ago

Thank you, I was sure I tried that... I feel silly now!

timofurrer commented 4 years ago

No worries! Happens to everyone once in a while! :tada:

sailoog commented 3 years ago

this attribute no longer exists in 2.0.0, is this intentional?