|
| 1 | +from dataclasses import dataclass, field |
| 2 | +from threading import Condition |
| 3 | +from typing import Literal |
| 4 | + |
| 5 | +import paho.mqtt.client as paho |
| 6 | +from jumpstarter_driver_power.driver import PowerInterface |
| 7 | +from paho.mqtt.enums import CallbackAPIVersion |
| 8 | + |
| 9 | +from jumpstarter.driver import Driver, export |
| 10 | + |
| 11 | + |
| 12 | +@dataclass(kw_only=True) |
| 13 | +class TasmotaPower(PowerInterface, Driver): |
| 14 | + """driver for tasmota compatible power switches""" |
| 15 | + |
| 16 | + client_id: str | None = None |
| 17 | + transport: Literal["tcp", "websockets", "unix"] = "tcp" |
| 18 | + timeout: float | None = None |
| 19 | + |
| 20 | + host: str |
| 21 | + port: int = 1883 |
| 22 | + tls: bool = True |
| 23 | + |
| 24 | + username: str | None = None |
| 25 | + password: str | None = None |
| 26 | + |
| 27 | + cmnd_topic: str |
| 28 | + stat_topic: str |
| 29 | + |
| 30 | + mq: paho.Client = field(init=False) |
| 31 | + state: str | None = field(init=False, default=None) |
| 32 | + cond: Condition = field(init=False, default_factory=Condition) |
| 33 | + |
| 34 | + def __post_init__(self): |
| 35 | + if hasattr(super(), "__post_init__"): |
| 36 | + super().__post_init__() |
| 37 | + |
| 38 | + self.mq = paho.Client( |
| 39 | + callback_api_version=CallbackAPIVersion.VERSION2, |
| 40 | + client_id=self.client_id, |
| 41 | + transport=self.transport, |
| 42 | + ) |
| 43 | + |
| 44 | + def on_message(client, userdata, msg): |
| 45 | + if msg.topic == self.stat_topic: |
| 46 | + self.state = msg.payload.decode() |
| 47 | + with self.cond: |
| 48 | + self.cond.notify_all() |
| 49 | + |
| 50 | + self.mq.on_message = on_message |
| 51 | + |
| 52 | + if self.tls: |
| 53 | + self.mq.tls_set() |
| 54 | + |
| 55 | + self.mq.username_pw_set(self.username, self.password) |
| 56 | + self.mq.connect(self.host, self.port) |
| 57 | + self.mq.loop_start() |
| 58 | + |
| 59 | + self.mq.subscribe(self.stat_topic) |
| 60 | + |
| 61 | + def publish(self, state): |
| 62 | + self.mq.publish( |
| 63 | + self.cmnd_topic, |
| 64 | + payload=state, |
| 65 | + qos=1, |
| 66 | + ).wait_for_publish( |
| 67 | + timeout=self.timeout, |
| 68 | + ) |
| 69 | + with self.cond: |
| 70 | + self.cond.wait_for( |
| 71 | + lambda: self.state == state, |
| 72 | + timeout=self.timeout, |
| 73 | + ) |
| 74 | + |
| 75 | + @export |
| 76 | + def on(self): |
| 77 | + self.publish("ON") |
| 78 | + |
| 79 | + @export |
| 80 | + def off(self): |
| 81 | + self.publish("OFF") |
| 82 | + |
| 83 | + @export |
| 84 | + def read(self): |
| 85 | + pass |
0 commit comments