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
DEBUG = False
is_connected = False
def delay(self, i):
time.sleep(self.DELAY)
def log(self, in_reconnect, e):
def log(self, in_reconnect, err):
"""Log error if DEBUG is True"""
if self.DEBUG:
if in_reconnect:
print("mqtt reconnect: %r" % e)
print("mqtt reconnect: %r" % err)
else:
print("mqtt: %r" % e)
print("mqtt: %r" % err)
def reconnect(self):
"""Try to connect or reconnect to MQTT broker"""
i = 0
while 1:
try:
self.is_connected = True
return super().connect(False)
except OSError as e:
self.log(True, e)
except OSError as err:
self.is_connected = False
self.log(True, err)
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):
"""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")
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")

Binary file not shown.