diff options
author | Evgeny Zinoviev <me@ch1p.io> | 2022-12-18 06:31:24 +0300 |
---|---|---|
committer | Evgeny Zinoviev <me@ch1p.io> | 2022-12-24 12:57:55 +0300 |
commit | 0a065f48be99d4ebae49de622a335f23e50c6ca0 (patch) | |
tree | b591d91fac26e5bf7a4dd6d37178b978061ef060 /src/home | |
parent | 022ec129bb8f511a7bf8cf537f165afce2303262 (diff) |
pump-mqtt-bot: wip; relayctl: somewhat stable
Diffstat (limited to 'src/home')
-rw-r--r-- | src/home/api/types/types.py | 1 | ||||
-rw-r--r-- | src/home/api/web_api_client.py | 6 | ||||
-rw-r--r-- | src/home/mqtt/__init__.py | 1 | ||||
-rw-r--r-- | src/home/mqtt/mqtt.py | 21 | ||||
-rw-r--r-- | src/home/mqtt/payload/__init__.py | 1 | ||||
-rw-r--r-- | src/home/mqtt/payload/relay.py | 45 | ||||
-rw-r--r-- | src/home/mqtt/relay.py | 93 | ||||
-rw-r--r-- | src/home/telegram/bot.py | 2 |
8 files changed, 159 insertions, 11 deletions
diff --git a/src/home/api/types/types.py b/src/home/api/types/types.py index 1d5596f..3f77b19 100644 --- a/src/home/api/types/types.py +++ b/src/home/api/types/types.py @@ -8,6 +8,7 @@ class BotType(Enum): ADMIN = auto() SOUND = auto() POLARIS_KETTLE = auto() + PUMP_MQTT = auto() class TemperatureSensorLocation(Enum): diff --git a/src/home/api/web_api_client.py b/src/home/api/web_api_client.py index f74b5a1..ca9a9ee 100644 --- a/src/home/api/web_api_client.py +++ b/src/home/api/web_api_client.py @@ -183,9 +183,9 @@ class WebAPIClient: data = json.loads(r.text) if r.status_code != 200: raise ApiResponseError(r.status_code, - data['error']['type'], - data['error']['message'], - data['error']['stacktrace'] if 'stacktrace' in data['error'] else None) + data['error'], + data['message'], + data['stacktrace'] if 'stacktrace' in data['error'] else None) return data['response'] if 'response' in data else True finally: diff --git a/src/home/mqtt/__init__.py b/src/home/mqtt/__init__.py index c0ef9ba..a6f5f5e 100644 --- a/src/home/mqtt/__init__.py +++ b/src/home/mqtt/__init__.py @@ -1,2 +1,3 @@ from .mqtt import MQTTBase from .util import poll_tick +from .relay import MQTTRelay
\ No newline at end of file diff --git a/src/home/mqtt/mqtt.py b/src/home/mqtt/mqtt.py index b3334b5..9dd973b 100644 --- a/src/home/mqtt/mqtt.py +++ b/src/home/mqtt/mqtt.py @@ -6,8 +6,6 @@ import logging from typing import Tuple from ..config import config -logger = logging.getLogger(__name__) - def username_and_password() -> Tuple[str, str]: username = config['mqtt']['username'] if 'username' in config['mqtt'] else None @@ -23,11 +21,15 @@ class MQTTBase: self._client.on_connect = self.on_connect self._client.on_disconnect = self.on_disconnect self._client.on_message = self.on_message + self._client.on_log = self.on_log + self._client.on_publish = self.on_publish + self._loop_started = False self._logger = logging.getLogger(self.__class__.__name__) username, password = username_and_password() if username and password: + self._logger.debug(f'username={username} password={password}') self._client.username_pw_set(username, password) def configure_tls(self): @@ -50,6 +52,12 @@ class MQTTBase: self._client.loop_forever() else: self._client.loop_start() + self._loop_started = True + + def disconnect(self): + self._client.disconnect() + self._client.loop_write() + self._client.loop_stop() def on_connect(self, client: mqtt.Client, userdata, flags, rc): self._logger.info("Connected with result code " + str(rc)) @@ -57,5 +65,12 @@ class MQTTBase: def on_disconnect(self, client: mqtt.Client, userdata, rc): self._logger.info("Disconnected with result code " + str(rc)) + def on_log(self, client: mqtt.Client, userdata, level, buf): + level = mqtt.LOGGING_LEVEL[level] if level in mqtt.LOGGING_LEVEL else logging.INFO + self._logger.log(level, f'MQTT: {buf}') + def on_message(self, client: mqtt.Client, userdata, msg): - self._logger.info(msg.topic + ": " + str(msg.payload)) + self._logger.debug(msg.topic + ": " + str(msg.payload)) + + def on_publish(self, client: mqtt.Client, userdata, mid): + self._logger.debug(f'publish done, mid={mid}')
\ No newline at end of file diff --git a/src/home/mqtt/payload/__init__.py b/src/home/mqtt/payload/__init__.py index e69de29..9fcaf3e 100644 --- a/src/home/mqtt/payload/__init__.py +++ b/src/home/mqtt/payload/__init__.py @@ -0,0 +1 @@ +from .base_payload import MQTTPayload
\ No newline at end of file diff --git a/src/home/mqtt/payload/relay.py b/src/home/mqtt/payload/relay.py index 2a327ba..debc2c8 100644 --- a/src/home/mqtt/payload/relay.py +++ b/src/home/mqtt/payload/relay.py @@ -1,6 +1,10 @@ +import hashlib + from .base_payload import MQTTPayload, MQTTPayloadCustomField +# _logger = logging.getLogger(__name__) + class StatFlags(MQTTPayloadCustomField): state: bool config_changed_value_present: bool @@ -8,9 +12,11 @@ class StatFlags(MQTTPayloadCustomField): @staticmethod def unpack(flags: int): + # _logger.debug(f'StatFlags.unpack: flags={flags}') state = flags & 0x1 ccvp = (flags >> 1) & 0x1 cc = (flags >> 2) & 0x1 + # _logger.debug(f'StatFlags.unpack: state={state}') return StatFlags(state=(state == 1), config_changed_value_present=(ccvp == 1), config_changed=(cc == 1)) @@ -24,7 +30,7 @@ class StatFlags(MQTTPayloadCustomField): class InitialStatPayload(MQTTPayload): - FORMAT = 'IBbIB' + FORMAT = '=IBbIB' ip: int fw_version: int @@ -34,7 +40,7 @@ class InitialStatPayload(MQTTPayload): class StatPayload(MQTTPayload): - FORMAT = 'bIB' + FORMAT = '=bIB' rssi: int free_heap: int @@ -42,13 +48,42 @@ class StatPayload(MQTTPayload): class PowerPayload(MQTTPayload): - FORMAT = '12sB' + FORMAT = '=12sB' PACKER = { - 'state': lambda n: int(n) + 'state': lambda n: int(n), + 'secret': lambda s: s.encode('utf-8') } UNPACKER = { - 'state': lambda n: bool(n) + 'state': lambda n: bool(n), + 'secret': lambda s: s.decode('utf-8') } secret: str state: bool + + +class OTAPayload(MQTTPayload): + secret: str + filename: str + + # structure of returned data: + # + # uint8_t[len(secret)] secret; + # uint8_t[16] md5; + # *uint8_t data + + def pack(self): + buf = bytearray(self.secret.encode()) + m = hashlib.md5() + with open(self.filename, 'rb') as fd: + content = fd.read() + m.update(content) + buf.extend(m.digest()) + buf.extend(content) + return buf + + def unpack(cls, buf: bytes): + raise RuntimeError(f'{cls.__class__.__name__}.unpack: not implemented') + # secret = buf[:12].decode() + # filename = buf[12:].decode() + # return OTAPayload(secret=secret, filename=filename) diff --git a/src/home/mqtt/relay.py b/src/home/mqtt/relay.py new file mode 100644 index 0000000..0f97b5b --- /dev/null +++ b/src/home/mqtt/relay.py @@ -0,0 +1,93 @@ +import paho.mqtt.client as mqtt +import re + +from .mqtt import MQTTBase +from typing import Optional, Union +from .payload.relay import ( + InitialStatPayload, + StatPayload, + PowerPayload, + OTAPayload +) + + +class MQTTRelay(MQTTBase): + _home_id: Union[str, int] + _secret: str + _message_callback: Optional[callable] + _ota_publish_callback: Optional[callable] + + def __init__(self, + home_id: Union[str, int], + secret: str, + subscribe_to_updates=True): + super().__init__(clean_session=True) + self._home_id = home_id + self._secret = secret + self._message_callback = None + self._ota_publish_callback = None + self._subscribe_to_updates = subscribe_to_updates + self._ota_mid = None + + def on_connect(self, client: mqtt.Client, userdata, flags, rc): + super().on_connect(client, userdata, flags, rc) + + if self._subscribe_to_updates: + topic = f'hk/{self._home_id}/relay/#' + self._logger.info(f"subscribing to {topic}") + + client.subscribe(topic, qos=1) + + def on_publish(self, client: mqtt.Client, userdata, mid): + if self._ota_mid is not None and mid == self._ota_mid and self._ota_publish_callback: + self._ota_publish_callback() + + def set_message_callback(self, callback: callable): + self._message_callback = callback + + def on_message(self, client: mqtt.Client, userdata, msg): + try: + match = re.match(r'^hk/(.*?)/relay/(stat|stat1|power|otares)$', msg.topic) + self._logger.debug(f'topic: {msg.topic}') + if not match: + return + + name = match.group(1) + subtopic = match.group(2) + + if name != self._home_id: + return + + message = None + if subtopic == 'stat': + message = StatPayload.unpack(msg.payload) + elif subtopic == 'stat1': + message = InitialStatPayload.unpack(msg.payload) + elif subtopic == 'power': + message = PowerPayload.unpack(msg.payload) + + if message and self._message_callback: + self._message_callback(message) + + except Exception as e: + self._logger.exception(str(e)) + + def set_power(self, enable: bool): + payload = PowerPayload(secret=self._secret, + state=enable) + self._client.publish(f'hk/{self._home_id}/relay/power', + payload=payload.pack(), + qos=1) + self._client.loop_write() + + def push_ota(self, + filename: str, + publish_callback: callable, + qos: int): + self._ota_publish_callback = publish_callback + payload = OTAPayload(secret=self._secret, filename=filename) + publish_result = self._client.publish(f'hk/{self._home_id}/relay/admin/ota', + payload=payload.pack(), + qos=qos) + self._ota_mid = publish_result.mid + self._client.loop_write() diff --git a/src/home/telegram/bot.py b/src/home/telegram/bot.py index 3c82587..bd09f42 100644 --- a/src/home/telegram/bot.py +++ b/src/home/telegram/bot.py @@ -110,6 +110,8 @@ def _handler_of_handler(*args, **kwargs): ctx.reply_exc(e) else: notify_user(ctx.user_id, exc2text(e)) + else: + _logger.exception(e) def handler(**kwargs): |