11import paho .mqtt .client as mqtt
2+ import json
3+ import logging
4+ import time
5+
6+ logger = logging .getLogger (__name__ )
27
38class MQTTWriter :
4- def __init__ (self , broker_address :str , broker_port :int , topic :str , username :str , password :str ):
5- self .client = mqtt .Client ()
9+ def __init__ (self , broker_address :str , broker_port :int , topic :str , username :str , password :str , client_id :str = "Arduino_MQTTWriter" ):
10+ self .topic = topic
11+ self .client = mqtt .Client (client_id )
612 self .client .username_pw_set (username , password )
13+
14+ def on_connect (client , userdata , flags , rc ):
15+ if rc != 0 :
16+ logger .error ("Failed to connect, return code %d\n " , rc )
17+
18+ FIRST_RECONNECT_DELAY = 1
19+ RECONNECT_RATE = 2
20+ MAX_RECONNECT_COUNT = 12
21+ MAX_RECONNECT_DELAY = 60
22+
23+ def on_disconnect (client , userdata , rc ):
24+ logging .warning ("Disconnected with result code: %s" , rc )
25+ reconnect_count , reconnect_delay = 0 , FIRST_RECONNECT_DELAY
26+ while reconnect_count < MAX_RECONNECT_COUNT :
27+ logging .info ("Reconnecting in %d seconds..." , reconnect_delay )
28+ time .sleep (reconnect_delay )
29+
30+ try :
31+ client .reconnect ()
32+ logging .info ("Reconnected successfully!" )
33+ return
34+ except Exception as err :
35+ logging .error ("%s. Reconnect failed. Retrying..." , err )
36+
37+ reconnect_delay *= RECONNECT_RATE
38+ reconnect_delay = min (reconnect_delay , MAX_RECONNECT_DELAY )
39+ reconnect_count += 1
40+ logging .info ("Reconnect failed after %s attempts. Exiting..." , reconnect_count )
41+
42+ self .client .on_connect = on_connect
43+ self .client .on_disconnect = on_disconnect
44+
745 self .client .connect (broker_address , broker_port , 60 )
8- self .topic = topic
46+ self .client . loop_start ()
947
1048 def close (self ):
49+ self .client .loop_stop ()
1150 self .client .disconnect ()
1251
1352 def write (self , message :str ):
1453 if message and message != "" :
1554 self .client .publish (self .topic , message )
1655
1756 def consume (self , item ):
57+ if item == None :
58+ return None
59+
1860 if isinstance (item , str ):
1961 self .write (item )
62+ elif isinstance (item , dict ) and len (item ) > 0 :
63+ self .write (json .dumps (item ))
64+
2065 return item
0 commit comments