import json from sense_hat import SenseHat class Sensors: def __init__(self, mqttc, uid, name): self.mqttc = mqttc self.sense = SenseHat() self.uid = uid self.name = name self.init_sensors() self.mqttc.will_set(self.availability_topic, "offline", retain=True) @property def device(self): return { "identifiers": [self.uid], "name": self.name, } @property def availability_topic(self): return f"{self.uid}/availability" @property def state_topic(self): return f"{self.uid}/state" def init_sensors(self): options = { "device": self.device, "availability_topic": self.availability_topic, "state_topic": self.state_topic, "entity_category": "diagnostic", } self.sensors = [ TemperatureSensor( "Température", self.uid, "temperature", self.sense.get_temperature, **options, ), HumiditySensor( "Humidité", self.uid, "humidity", self.sense.get_humidity, **options ), PressureSensor( "Pression", self.uid, "pressure", self.sense.get_pressure, **options ), ] def publish_discovery(self): for sensor in self.sensors: sensor.publish_discovery(self.mqttc) def publish_online(self): self.mqttc.publish(self.availability_topic, "online", retain=True) def publish_state(self): self.mqttc.publish( self.state_topic, json.dumps({sensor.slug: sensor.get_value() for sensor in self.sensors}), ) class SingleSensor: def __init__(self, name, parent_uid, slug, get_value, **kwargs): self.name = name self.parent_uid = parent_uid self.slug = slug self.get_value = get_value self.options = kwargs def publish_discovery(self, mqttc): mqttc.publish( self.discovery_topic, json.dumps( { "name": self.name, "state_class": "MEASUREMENT", "unique_id": self.uid, "value_template": self.value_template, } | self.options ), retain=True, ) @property def uid(self): return f"{self.parent_uid}_{self.slug}" @property def discovery_topic(self): return f"homeassistant/sensor/{self.uid}/config" @property def value_template(self): return "{{" + f"value_json.{self.slug}" + "}}" class TemperatureSensor(SingleSensor): def __init__(self, name, parent_uid, slug, get_value, **kwargs): super().__init__(name, parent_uid, slug, get_value, **kwargs) self.options["device_class"] = "temperature" self.options["icon"] = "mdi:thermometer" self.options["suggested_display_precision"] = 1 self.options["unit_of_measurement"] = "°C" class HumiditySensor(SingleSensor): def __init__(self, name, parent_uid, slug, get_value, **kwargs): super().__init__(name, parent_uid, slug, get_value, **kwargs) self.options["device_class"] = "humidity" self.options["icon"] = "mdi:water-percent" self.options["suggested_display_precision"] = 0 self.options["unit_of_measurement"] = "%" class PressureSensor(SingleSensor): def __init__(self, name, parent_uid, slug, get_value, **kwargs): super().__init__(name, parent_uid, slug, get_value, **kwargs) self.options["device_class"] = "pressure" self.options["icon"] = "mdi:gauge" self.options["suggested_display_precision"] = 0 self.options["unit_of_measurement"] = "mbar"