From be2381429fcaf270597de8a9448d7f3d33a5f523 Mon Sep 17 00:00:00 2001 From: "Edgar P. Burkhart" <git@edgarpierre.fr> Date: Sun, 9 Mar 2025 11:40:53 +0100 Subject: [PATCH] Refactor power control logic in MQTT client to use pattern matching for improved readability --- hasspy/mqtt.py | 19 +++++++++++-------- 1 file changed, 11 insertions(+), 8 deletions(-) diff --git a/hasspy/mqtt.py b/hasspy/mqtt.py index 75fec3b..e50a0fc 100644 --- a/hasspy/mqtt.py +++ b/hasspy/mqtt.py @@ -74,14 +74,17 @@ class HassClient(Client): def on_command(self, client: Client, userdata: Any, message: MQTTMessage) -> None: payload = message.payload.decode("utf-8") - if not self.power_on and payload == "POWER_ON": - log.info("Cancelling shutdown…") - self.power_on = True - run(["systemctl", "poweroff", "--when=cancel"]) - elif self.power_on and payload == "POWER_OFF": - log.info("Powering off…") - self.power_on = False - run(["systemctl", "poweroff", "--when=+1m"]) + match payload: + case "POWER_ON": + if not self.power_on: + log.info("Cancelling shutdown…") + self.power_on = True + run(["systemctl", "poweroff", "--when=cancel"]) + case "POWER_OFF": + if self.power_on: + log.info("Powering off…") + self.power_on = False + run(["systemctl", "poweroff", "--when=+1m"]) self.publish_state()