feat: enhance MQTT controller to prevent duplicate command sends and update documentation for delay parameter
This commit is contained in:
1 parent
df0213b004
commit
50851c0cfe
5 files changed
+49
-6
No files matched your search
@@ -1,3 +1,4 @@
|
||||
import asyncio
|
||||
from abc import ABC, abstractmethod
|
||||
from base64 import b64encode
|
||||
import binascii
|
||||
@@ -27,6 +28,8 @@ MQTT_COMMANDS_ENCODING = [ENC_RAW]
|
||||
LOOKIN_COMMANDS_ENCODING = [ENC_PRONTO, ENC_RAW]
|
||||
ESPHOME_COMMANDS_ENCODING = [ENC_RAW]
|
||||
|
||||
MQTT_SEND_STATES_KEY = 'infrarize_mqtt_send_states'
|
||||
|
||||
|
||||
def get_controller(hass, controller, encoding, controller_data, delay):
|
||||
"""Return a controller compatible with the specification provided."""
|
||||
@@ -135,6 +138,12 @@ class XiaomiController(AbstractController):
|
||||
class MQTTController(AbstractController):
|
||||
"""Controls a MQTT device."""
|
||||
|
||||
def __init__(self, hass, controller, encoding, controller_data, delay):
|
||||
super().__init__(hass, controller, encoding, controller_data, delay)
|
||||
states = self.hass.data.setdefault(MQTT_SEND_STATES_KEY, {})
|
||||
self._send_state = states.setdefault(controller_data, MQTTTopicSendState())
|
||||
self._send_delay = float(delay)
|
||||
|
||||
def check_encoding(self, encoding):
|
||||
"""Check if the encoding is supported by the controller."""
|
||||
if encoding not in MQTT_COMMANDS_ENCODING:
|
||||
@@ -148,8 +157,42 @@ class MQTTController(AbstractController):
|
||||
'payload': command
|
||||
}
|
||||
|
||||
await self.hass.services.async_call(
|
||||
'mqtt', 'publish', service_data)
|
||||
async with self._send_state.lock:
|
||||
loop = asyncio.get_running_loop()
|
||||
now = loop.time()
|
||||
|
||||
if (
|
||||
self._send_state.last_payload == command
|
||||
and self._send_state.last_sent_at is not None
|
||||
and now - self._send_state.last_sent_at < self._send_delay
|
||||
):
|
||||
_LOGGER.debug(
|
||||
"Skipping duplicate MQTT command for topic %s within %.3fs",
|
||||
self._controller_data,
|
||||
self._send_delay,
|
||||
)
|
||||
return
|
||||
|
||||
if self._send_state.last_sent_at is not None:
|
||||
wait = self._send_delay - (
|
||||
now - self._send_state.last_sent_at
|
||||
)
|
||||
if wait > 0:
|
||||
await asyncio.sleep(wait)
|
||||
|
||||
await self.hass.services.async_call(
|
||||
'mqtt', 'publish', service_data)
|
||||
self._send_state.last_payload = command
|
||||
self._send_state.last_sent_at = loop.time()
|
||||
|
||||
|
||||
class MQTTTopicSendState:
|
||||
"""Shared send state for controllers publishing to the same topic."""
|
||||
|
||||
def __init__(self):
|
||||
self.lock = asyncio.Lock()
|
||||
self.last_payload = None
|
||||
self.last_sent_at = None
|
||||
|
||||
|
||||
class LookinController(AbstractController):
|
||||
|
||||
Reference in new issue
Block a user