Allow closing via mqtt

Valentin Ochs 2023-05-17 16:04:53 +02:00
parent 28323ef0ce
commit 2f8edcd223
3 changed files with 19 additions and 7 deletions

View File

@ -1,9 +1,8 @@
#!/usr/bin/python
from . import nfc, socket, door, bell
from . import nfc, socket, door, bell, mqtt
from .util import init_logging
from collections import namedtuple
import paho.mqtt.client as mqcl
import logging
def main():
@ -29,9 +28,7 @@ def main():
config = parser.parse_args()
mqttc = mqcl.Client()
mqttc.connect_async(config.mqtt_host, keepalive=60)
mqttc.loop_start()
mqttc = mqtt.reconnecting_client(config.mqtt_host)
log_host = None
if config.log_host != None:

View File

@ -22,9 +22,15 @@ class Control(util.Loggable):
self._position_task: Thread = None
self._control_task: Thread = None
def handle_target(client, userdata, msg):
self._logger().debug("Incoming MQTT message on %s: %s", msg.topic, msg.payload)
if msg.topic == "door/state/target" and msg.payload == b'closed':
self.close()
self.target = mqtt.Value(mqtt_client, "door/state/target",
persistent=True,
translate=state_names)
translate=state_names,
remote_update_callback = handle_target)
self.state = mqtt.Value(mqtt_client, "door/state/value",
persistent=True,
translate=state_names)

View File

@ -19,7 +19,8 @@ class Value:
typing.Dict[Any, str],
typing.Callable]
= None,
max_update: float = 0.1):
max_update: float = 0.1,
remote_update_callback = None):
self.client = client
self.topic = topic
self.persistent = persistent
@ -39,6 +40,10 @@ class Value:
if start_value is not None:
self.update(start_value)
if remote_update_callback is not None:
self.client.message_callback_add(self.topic, remote_update_callback)
self.client.subscribe(self.topic, 2)
def update(self, value: Any, *,
force: bool = False,
no_update: bool = False) -> None:
@ -73,6 +78,7 @@ class Value:
return self.translate(self.value)
def reconnecting_client(host: str, *, keepalive: int = 60):
_logger.debug("Creating MQTT client with keepalive interval %d", keepalive)
client = Client()
client.on_connect = lambda client, userdata, flags, rc: \
_logger.debug("Connected to mqtt host")
@ -80,5 +86,8 @@ def reconnecting_client(host: str, *, keepalive: int = 60):
_logger.debug("Disconnected from mqtt host")
client.enable_logger(_logger.getChild("paho"))
client.connect_async(host, keepalive=keepalive)
def on_message(client, userdata, msg):
_logger.debug("Unmatched message on %s: %s", msg.topic, msg.payload)
client.on_message = on_message
client.loop_start()
return client