micropy-light/code/lib-src/umqtt/robust.py

74 lines
2.1 KiB
Python
Raw Permalink Normal View History

2020-04-22 11:10:41 +02:00
import time
from . import simple
class MQTTClient(simple.MQTTClient):
DELAY = 2
DEBUG = False
is_connected = False
2020-04-22 11:10:41 +02:00
def log(self, in_reconnect, err):
"""Log error if DEBUG is True"""
2020-04-22 11:10:41 +02:00
if self.DEBUG:
if in_reconnect:
print("mqtt reconnect: %r" % err)
2020-04-22 11:10:41 +02:00
else:
print("mqtt: %r" % err)
2020-04-22 11:10:41 +02:00
def reconnect(self):
"""Try to connect or reconnect to MQTT broker"""
2020-04-22 11:10:41 +02:00
i = 0
while 1:
try:
self.is_connected = True
2020-04-22 11:10:41 +02:00
return super().connect(False)
except OSError as err:
self.is_connected = False
self.log(True, err)
2020-04-22 11:10:41 +02:00
i += 1
time.sleep(self.DELAY)
if i >= 5:
print("Mqtt reconnect : too much retry")
self.is_connected = False
break
2020-04-22 11:10:41 +02:00
def publish(self, topic, msg, retain=False, qos=0):
"""Try to publish if connected to MQTT broker"""
if self.is_connected:
i = 0
while 1:
try:
return super().publish(topic, msg, retain, qos)
except OSError as e:
i += 1
self.log(False, e)
if i >= 5:
print("Mqtt publish : too much retry")
self.is_connected = False
break
else:
self.reconnect()
else:
print("Mqtt publish: not connected")
2020-04-22 11:10:41 +02:00
def wait_msg(self):
"""Check if any subscribed messages is available"""
if self.is_connected:
i = 0
while 1:
try:
return super().wait_msg()
except OSError as e:
i += 1
self.log(False, e)
if i >= 5:
print("Mqtt wait_msg : too much retry")
self.is_connected = False
break
else:
self.reconnect()
else:
print("Mqtt wait_msg: not connected")