22import json
33import logging
44import time
5+ import uuid
56
67logger = logging .getLogger (__name__ )
78
8- class MQTTWriter :
9- def __init__ (self , broker_address :str , broker_port :int , topic :str , username :str , password :str , client_id :str = "Arduino_MQTTWriter" ):
9+ def generate_client_id ():
10+ return "Arduino_MQTTSink-" + str (uuid .uuid4 ())
11+
12+ class MQTTSink :
13+ def __init__ (self , broker_address :str , broker_port :int , topic :str , username :str , password :str , client_id :str = "" ):
1014 self .topic = topic
11- self .client = mqtt .Client (client_id )
12- self .client .username_pw_set (username , password )
15+ if not client_id or client_id == "" :
16+ client_id = generate_client_id ()
17+ self .client = mqtt .Client (callback_api_version = mqtt .CallbackAPIVersion .VERSION2 , client_id = client_id )
18+ if username and password :
19+ self .client .username_pw_set (username , password )
1320
14- def on_connect (client , userdata , flags , rc ):
15- if rc != 0 :
16- logger .error ("Failed to connect, return code %d\n " , rc )
21+ def on_connect (client , userdata , flags , reason_code , properties ):
22+ if reason_code != 0 :
23+ logger .error ("Failed to connect, return code %d\n " , reason_code )
1724
1825 FIRST_RECONNECT_DELAY = 1
1926 RECONNECT_RATE = 2
2027 MAX_RECONNECT_COUNT = 12
2128 MAX_RECONNECT_DELAY = 60
2229
23- def on_disconnect (client , userdata , rc ):
24- logging .warning ("Disconnected with result code: %s" , rc )
30+ def on_disconnect (client , userdata , flags , reason_code , properties ):
31+ logging .info ("Disconnected with result code: %s" , reason_code )
2532 reconnect_count , reconnect_delay = 0 , FIRST_RECONNECT_DELAY
2633 while reconnect_count < MAX_RECONNECT_COUNT :
2734 logging .info ("Reconnecting in %d seconds..." , reconnect_delay )
@@ -51,7 +58,8 @@ def close(self):
5158
5259 def write (self , message :str ):
5360 if message and message != "" :
54- self .client .publish (self .topic , message )
61+ return self .client .publish (self .topic , message )
62+ return None
5563
5664 def consume (self , item ):
5765 if item == None :
@@ -60,6 +68,4 @@ def consume(self, item):
6068 if isinstance (item , str ):
6169 self .write (item )
6270 elif isinstance (item , dict ) and len (item ) > 0 :
63- self .write (json .dumps (item ))
64-
65- return item
71+ self .write (json .dumps (item ))
0 commit comments