Move main config to config.toml

This commit is contained in:
Edgar P. Burkhart 2024-12-08 11:17:25 +01:00
parent 477cc99247
commit 119feee5e5
Signed by: edpibu
GPG key ID: 9833D3C5A25BD227
3 changed files with 42 additions and 12 deletions

View file

@ -1,4 +1,14 @@
[mqtt]
[logging]
level = "DEBUG"
[homeassistant]
entity = "climate.chaudiere"
secondary_entities = [
"sensor.esptic_tempo",
"sensor.rte_tempo_prochaine_couleur",
]
[homeassistant.mqtt]
username = "oin"
password = "n+Bi58l7LxbH5nEJ"
host = "homeassistant.local"

View file

@ -1,20 +1,35 @@
import logging
import sys
import tomllib
from .mqtt import HAClient
if __name__ == "__main__":
with open("config.toml", "rb") as config_file:
logger = logging.getLogger(__name__)
config_path = "config.toml"
def main():
with open(config_path, "rb") as config_file:
config = tomllib.load(config_file)
logging.basicConfig(level=logging.DEBUG)
logging.basicConfig(**config.get("logging", dict()))
ha_config = config.get("homeassistant")
if ha_config is None:
logger.error(f"Missing home assistant config in <{config_path}>")
logger.error(f"\t{config}")
sys.exit(1)
client = HAClient(
"climate.chaudiere",
["sensor.esptic_tempo", "sensor.rte_tempo_prochaine_couleur"],
config.get("mqtt", dict()),
ha_config.get("entity"),
ha_config.get("secondary_entities"),
mqtt_config=ha_config.get("mqtt"),
)
client.connect()
client.loop()
if __name__ == "__main__":
main()

View file

@ -14,18 +14,20 @@ class HAClient:
self,
entity: str,
secondary_entities: list[str] = [],
config: dict = dict(),
mqtt_config: dict = dict(),
) -> None:
self.entity = entity
self.secondary_entities = secondary_entities
self.config = config
self.config = mqtt_config
self.state_topic = "oin/state"
self.availability_topic = "oin/availability"
self.client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2)
username = self.config.get("username", None)
logger.debug(f"Setting up MQTT with user <{username}>")
self.client.username_pw_set(
username=self.config.get("username", None),
username=username,
password=self.config.get("password", None),
)
@ -48,9 +50,12 @@ class HAClient:
}
def connect(self) -> None:
logger.debug("Connecting to HA...")
self.client.will_set(self.availability_topic, "offline", retain=True)
self.client.connect(self.config.get("host"), self.config.get("port", 1883))
host = self.config.get("host")
port = self.config.get("port", 1883)
logger.debug(f"Connecting to <{host}> on port <{port}>")
self.client.connect(host, port)
self.subscribe(entity_topic(self.entity), self.state_update)
for entity in self.secondary_entities: