From 337e2a0384045e2ed8fdb6846c04f8f9f8073f1b Mon Sep 17 00:00:00 2001 From: obnjed <71677354+obnjed@users.noreply.github.com> Date: Tue, 22 Sep 2020 08:58:05 +0800 Subject: [PATCH] Update MQTTKeywords.py suites to repair a messages abandoning deficiency MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This code (self._messages[topic] = []) in "subscribe" and "listen" will abandon some messages that would not return to scripts when multiple messages received and multiple “subscribe” or “listen” called in very short time. This modification suites to repair the deficiency above. --- src/MQTTLibrary/MQTTKeywords.py | 22 ++++++++++++++++++---- 1 file changed, 18 insertions(+), 4 deletions(-) diff --git a/src/MQTTLibrary/MQTTKeywords.py b/src/MQTTLibrary/MQTTKeywords.py index 63934b5..fbee2c4 100644 --- a/src/MQTTLibrary/MQTTKeywords.py +++ b/src/MQTTLibrary/MQTTKeywords.py @@ -36,7 +36,8 @@ def __init__(self, loop_timeout=LOOP_TIMEOUT): self._username = None self._password = None #self._mqttc = mqtt.Client() - + self.msg_tmp = {} + def set_username_and_password(self, username, password=None): self._username = username self._password = password @@ -149,7 +150,10 @@ def subscribe(self, topic, qos, timeout=1, limit=1): """ seconds = convert_time(timeout) - self._messages[topic] = [] + try: + self._messages[topic] = [i for i in self._messages[topic] if i not in self.msg_tmp[topic]] + except KeyError: + self._messages[topic] = [] limit = int(limit) self._subscribed = False @@ -163,6 +167,7 @@ def subscribe(self, topic, qos, timeout=1, limit=1): logger.info('Starting background loop') self._background_mqttc = self._mqttc self._background_mqttc.loop_start() + self.msg_tmp = self._messages return self._messages[topic] timer_start = time.time() @@ -176,6 +181,7 @@ def subscribe(self, topic, qos, timeout=1, limit=1): # next connect. time.sleep(1) break + self.msg_tmp = self._messages return self._messages[topic] def listen(self, topic, timeout=1, limit=1): @@ -215,7 +221,11 @@ def listen(self, topic, timeout=1, limit=1): # If enough messages have already been gathered, return them if limit != 0 and len(self._messages[topic]) >= limit: messages = self._messages[topic][:] # Copy the list's contents - self._messages[topic] = [] + try: + self._messages[topic] = [i for i in self._messages[topic] if i not in self.msg_tmp[topic]] + except KeyError: + self._messages[topic] = [] + self.msg_tmp = self._messages return messages[-limit:] seconds = convert_time(timeout) @@ -241,7 +251,11 @@ def listen(self, topic, timeout=1, limit=1): break messages = self._messages[topic][:] # Copy the list's contents - self._messages[topic] = [] + try: + self._messages[topic] = [i for i in self._messages[topic] if i not in self.msg_tmp[topic]] + except KeyError: + self._messages[topic] = [] + self.msg_tmp = self._messages return messages[-limit:] if limit != 0 else messages def subscribe_and_validate(self, topic, qos, payload, timeout=1):