Refactor power control logic in MQTT client to use pattern matching for improved readability

This commit is contained in:
Edgar P. Burkhart 2025-03-09 11:40:53 +01:00
parent 98e1e970c1
commit be2381429f
Signed by: edpibu
GPG key ID: 9833D3C5A25BD227

View file

@ -74,14 +74,17 @@ class HassClient(Client):
def on_command(self, client: Client, userdata: Any, message: MQTTMessage) -> None: def on_command(self, client: Client, userdata: Any, message: MQTTMessage) -> None:
payload = message.payload.decode("utf-8") payload = message.payload.decode("utf-8")
if not self.power_on and payload == "POWER_ON": match payload:
log.info("Cancelling shutdown…") case "POWER_ON":
self.power_on = True if not self.power_on:
run(["systemctl", "poweroff", "--when=cancel"]) log.info("Cancelling shutdown…")
elif self.power_on and payload == "POWER_OFF": self.power_on = True
log.info("Powering off…") run(["systemctl", "poweroff", "--when=cancel"])
self.power_on = False case "POWER_OFF":
run(["systemctl", "poweroff", "--when=+1m"]) if self.power_on:
log.info("Powering off…")
self.power_on = False
run(["systemctl", "poweroff", "--when=+1m"])
self.publish_state() self.publish_state()