Add suspend command support and improve power state handling

This commit is contained in:
Edgar P. Burkhart 2025-03-09 20:26:34 +01:00
parent 1f5da172d6
commit 8a67a0b674
Signed by: edpibu
GPG key ID: 9833D3C5A25BD227

View file

@ -2,6 +2,7 @@ import io
import json import json
import logging import logging
import re import re
from pathlib import Path
from subprocess import run from subprocess import run
from threading import Thread, Timer from threading import Thread, Timer
from typing import Any, Mapping, Tuple from typing import Any, Mapping, Tuple
@ -25,7 +26,6 @@ class HassClient(Client):
self.username_pw_set(username, self.config.get("password")) self.username_pw_set(username, self.config.get("password"))
self.interval = self.config.get("interval", 60) self.interval = self.config.get("interval", 60)
self.power_on = True
self.timer = Timer(0, self.publish_state) self.timer = Timer(0, self.publish_state)
self.cover = "" self.cover = ""
@ -140,6 +140,7 @@ class HassSystemClient(HassClient):
"POWER_ON": ["systemctl", "poweroff", "--when=cancel"], "POWER_ON": ["systemctl", "poweroff", "--when=cancel"],
"POWER_OFF": ["systemctl", "poweroff", "--when=+1m"], "POWER_OFF": ["systemctl", "poweroff", "--when=+1m"],
"LOCK": ["loginctl", "lock-sessions"], "LOCK": ["loginctl", "lock-sessions"],
"SUSPEND": ["systemctl", "suspend"],
} }
def do_command(self, cmd: str, value: str = "") -> None: def do_command(self, cmd: str, value: str = "") -> None:
@ -149,11 +150,6 @@ class HassSystemClient(HassClient):
if code != 0: if code != 0:
log.error(f"Failed to execute command: {cmd}") log.error(f"Failed to execute command: {cmd}")
if cmd == "POWER_ON":
self.power_on = True
elif cmd == "POWER_OFF":
self.power_on = False
@property @property
def components(self) -> dict[str, dict[str, Any]]: def components(self) -> dict[str, dict[str, Any]]:
return { return {
@ -173,12 +169,21 @@ class HassSystemClient(HassClient):
"icon": "mdi:account-lock", "icon": "mdi:account-lock",
"payload_press": "LOCK", "payload_press": "LOCK",
}, },
"suspend": {
"unique_id": f"{self.node_id}_suspend",
"p": "button",
"name": "Suspend",
"icon": "mdi:sleep",
"payload_press": "SUSPEND",
},
} }
@property @property
def state_payload(self) -> dict[str, Any]: def state_payload(self) -> dict[str, Any]:
return { return {
"power": "POWER_ON" if self.power_on else "POWER_OFF", "power": "POWER_OFF"
if Path("/run/systemd/shutdown/scheduled").exists()
else "POWER_ON",
} }