Add retry limits and "is_connected" property

This commit is contained in:
arofarn 2020-05-16 09:10:06 +02:00
parent 22e2506dfa
commit b7a3387c5f
2 changed files with 50 additions and 21 deletions

View File

@ -6,39 +6,68 @@ class MQTTClient(simple.MQTTClient):
DELAY = 2 DELAY = 2
DEBUG = False DEBUG = False
is_connected = False
def delay(self, i): def log(self, in_reconnect, err):
time.sleep(self.DELAY) """Log error if DEBUG is True"""
def log(self, in_reconnect, e):
if self.DEBUG: if self.DEBUG:
if in_reconnect: if in_reconnect:
print("mqtt reconnect: %r" % e) print("mqtt reconnect: %r" % err)
else: else:
print("mqtt: %r" % e) print("mqtt: %r" % err)
def reconnect(self): def reconnect(self):
"""Try to connect or reconnect to MQTT broker"""
i = 0 i = 0
while 1: while 1:
try: try:
self.is_connected = True
return super().connect(False) return super().connect(False)
except OSError as e: except OSError as err:
self.log(True, e) self.is_connected = False
self.log(True, err)
i += 1 i += 1
self.delay(i) time.sleep(self.DELAY)
if i >= 5:
print("Mqtt reconnect : too much retry")
self.is_connected = False
break
def publish(self, topic, msg, retain=False, qos=0): 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: while 1:
try: try:
return super().publish(topic, msg, retain, qos) return super().publish(topic, msg, retain, qos)
except OSError as e: except OSError as e:
i += 1
self.log(False, e) self.log(False, e)
if i >= 5:
print("Mqtt publish : too much retry")
self.is_connected = False
break
else:
self.reconnect() self.reconnect()
else:
print("Mqtt publish: not connected")
def wait_msg(self): def wait_msg(self):
"""Check if any subscribed messages is available"""
if self.is_connected:
i = 0
while 1: while 1:
try: try:
return super().wait_msg() return super().wait_msg()
except OSError as e: except OSError as e:
i += 1
self.log(False, e) self.log(False, e)
if i >= 5:
print("Mqtt wait_msg : too much retry")
self.is_connected = False
break
else:
self.reconnect() self.reconnect()
else:
print("Mqtt wait_msg: not connected")

Binary file not shown.