summaryrefslogtreecommitdiff
path: root/src/home/mqtt/mqtt.py
diff options
context:
space:
mode:
Diffstat (limited to 'src/home/mqtt/mqtt.py')
-rw-r--r--src/home/mqtt/mqtt.py21
1 files changed, 18 insertions, 3 deletions
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