From d827788da172a4110b3c1a376bc1aea2bb36651d Mon Sep 17 00:00:00 2001
From: "Edgar P. Burkhart" <git@edgarpierre.fr>
Date: Sat, 8 Mar 2025 23:50:43 +0100
Subject: [PATCH] Add logging to MQTT client and main application; create
 systemd service file

---
 hasspy.service | 12 ++++++++++++
 hasspy/mqtt.py |  8 ++++++--
 main.py        |  3 +++
 3 files changed, 21 insertions(+), 2 deletions(-)
 create mode 100644 hasspy.service

diff --git a/hasspy.service b/hasspy.service
new file mode 100644
index 0000000..7358d01
--- /dev/null
+++ b/hasspy.service
@@ -0,0 +1,12 @@
+[Unit]
+Description=Hasspy
+After=network.target
+
+[Service]
+Type=simple
+WorkingDirectory=/home/edpibu/Code/hasspy
+ExecStart=/usr/bin/uv run main.py
+Restart=always
+
+[Install]
+WantedBy=multi-user.target
diff --git a/hasspy/mqtt.py b/hasspy/mqtt.py
index 5f1201d..75fec3b 100644
--- a/hasspy/mqtt.py
+++ b/hasspy/mqtt.py
@@ -1,10 +1,13 @@
 import json
+import logging
 from subprocess import run
 from typing import Any, Mapping
 
 from paho.mqtt.client import Client, MQTTMessage, MQTTMessageInfo
 from paho.mqtt.enums import CallbackAPIVersion, MQTTErrorCode
 
+log = logging.getLogger(__name__)
+
 
 class HassClient(Client):
     def __init__(self, node_id: str, config: Mapping[str, Any]) -> None:
@@ -61,6 +64,7 @@ class HassClient(Client):
         )
 
     def on_connect(self, *args: Any, **kwargs: Any) -> None:
+        log.info("Connected to MQTT broker")
         self.publish_discovery()
         self.publish_availability()
         self.init_subs()
@@ -71,11 +75,11 @@ class HassClient(Client):
         payload = message.payload.decode("utf-8")
 
         if not self.power_on and payload == "POWER_ON":
-            print("Cancelling shutdown…")
+            log.info("Cancelling shutdown…")
             self.power_on = True
             run(["systemctl", "poweroff", "--when=cancel"])
         elif self.power_on and payload == "POWER_OFF":
-            print("Powering off…")
+            log.info("Powering off…")
             self.power_on = False
             run(["systemctl", "poweroff", "--when=+1m"])
 
diff --git a/main.py b/main.py
index 582d4f5..c5a8785 100644
--- a/main.py
+++ b/main.py
@@ -1,9 +1,12 @@
+import logging
 import tomllib
 
 from hasspy.mqtt import HassClient
 
 
 def main() -> None:
+    logging.basicConfig(level=logging.INFO)
+
     with open("config.toml", "rb") as file:
         config = tomllib.load(file)