Add logging to MQTT client and main application; create systemd service file

This commit is contained in:
Edgar P. Burkhart 2025-03-08 23:50:43 +01:00
parent fa8bb1d8a9
commit d827788da1
Signed by: edpibu
GPG key ID: 9833D3C5A25BD227
3 changed files with 21 additions and 2 deletions

12
hasspy.service Normal file
View file

@ -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

View file

@ -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"])

View file

@ -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)