|
3 | 3 |
|
4 | 4 | import argparse |
5 | 5 | import asyncio |
| 6 | +import json |
6 | 7 | import logging |
7 | 8 | import sys |
8 | 9 | import os |
@@ -920,6 +921,62 @@ def _get_params(self): |
920 | 921 | exports["YKUSHPowerPort"] = YKUSHPowerPortExport |
921 | 922 |
|
922 | 923 |
|
| 924 | +@attr.s(eq=False) |
| 925 | +class TasmotaPowerPortExport(ResourceExport): |
| 926 | + """ResourceExport for TasmotaPowerPort devices""" |
| 927 | + |
| 928 | + def __attrs_post_init__(self): |
| 929 | + super().__attrs_post_init__() |
| 930 | + self.data["cls"] = self.cls |
| 931 | + from ..resource import mqtt |
| 932 | + |
| 933 | + local_cls = getattr(mqtt, self.cls) |
| 934 | + self.local = local_cls(target=None, name=None, **self.local_params) |
| 935 | + |
| 936 | + self.status = None |
| 937 | + |
| 938 | + import paho.mqtt.client as mqtt |
| 939 | + self._client = None |
| 940 | + self._client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2) |
| 941 | + self._client.connect(self.local.host) |
| 942 | + self._client.on_message = self._on_message |
| 943 | + self._client.on_connect = self._on_connect |
| 944 | + self._client.loop_start() |
| 945 | + |
| 946 | + def _on_connect(self, client, userdata, flags, reason_code, properties): |
| 947 | + client.subscribe(self.local.status_topic) |
| 948 | + if self.local.tele_topic: |
| 949 | + client.subscribe(self.local.tele_topic) |
| 950 | + client.publish(self.local.power_topic, "") |
| 951 | + |
| 952 | + def _on_message(self, client, userdata, msg): |
| 953 | + if msg.topic == self.local.tele_topic: |
| 954 | + data = json.loads(msg.payload.decode("utf-8")) |
| 955 | + power = self.local.power_topic.split('/')[-1] |
| 956 | + if power in data: |
| 957 | + self.status = data[power] |
| 958 | + else: |
| 959 | + if msg.payload == b'ON': |
| 960 | + self.status = "ON" |
| 961 | + elif msg.payload == b'OFF': |
| 962 | + self.status = "OFF" |
| 963 | + else: |
| 964 | + raise ValueError("unexpected payload in status topic " |
| 965 | + + {msg.payload}) |
| 966 | + |
| 967 | + def _get_params(self): |
| 968 | + """Helper function to return parameters""" |
| 969 | + return { |
| 970 | + **self.local_params, |
| 971 | + "extra": { |
| 972 | + "status": self.status, |
| 973 | + } |
| 974 | + } |
| 975 | + |
| 976 | + |
| 977 | +exports["TasmotaPowerPort"] = TasmotaPowerPortExport |
| 978 | + |
| 979 | + |
923 | 980 | class ExporterSession(ApplicationSession): |
924 | 981 | def onConnect(self): |
925 | 982 | """Set up internal datastructures on successful connection: |
|
0 commit comments