Enable reset saving

This commit is contained in:
KenwoodFox
2026-07-06 17:00:39 -04:00
parent c61fe1a5c4
commit 8a133c9d62

View File

@@ -1,10 +1,12 @@
from __future__ import annotations
import argparse
import json
import logging
import os
import signal
import sys
from pathlib import Path
import paho.mqtt.client as mqtt
from usb.core import USBError
@@ -13,6 +15,34 @@ from patlite_mqtt.channels import Mode, PatliteController
from patlite_mqtt.device import PatliteDevice
LOG = logging.getLogger("patlite_mqtt")
STATE_FILE = Path.home() / ".local" / "state" / "patlite-mqtt" / "channels.json"
def _load_state(controller: PatliteController) -> None:
if not STATE_FILE.is_file():
return
try:
data = json.loads(STATE_FILE.read_text(encoding="utf-8"))
except (OSError, json.JSONDecodeError):
LOG.warning("Could not read %s", STATE_FILE)
return
for name, value in data.items():
channel = controller.channels.get(name)
if channel is None:
continue
try:
channel.set_mode(Mode.parse(value))
except ValueError:
LOG.warning("Ignoring saved mode for %s: %r", name, value)
def _save_state(controller: PatliteController) -> None:
data = {name: ch.mode.value for name, ch in controller.channels.items()}
try:
STATE_FILE.parent.mkdir(parents=True, exist_ok=True)
STATE_FILE.write_text(json.dumps(data) + "\n", encoding="utf-8")
except OSError as exc:
LOG.warning("Could not write %s: %s", STATE_FILE, exc)
def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
@@ -111,6 +141,7 @@ class PatliteMqttDaemon:
LOG.info("%s -> %s", message.topic, mode.value)
channel.set_mode(mode)
_save_state(self._controller)
def run(self):
self._client.connect(
@@ -150,6 +181,7 @@ def main(argv: list[str] | None = None) -> int:
fast_delay=args.fast_delay,
slow_delay=args.slow_delay,
)
_load_state(controller)
daemon = PatliteMqttDaemon(args, controller)
def handle_signal(signum, frame):