MqttMonitor/MqttClient.py

changeset 10
7e0e921dc7ea
parent 9
f75a385e9127
child 11
90d3ebed4cc0
--- a/MqttMonitor/MqttClient.py	Fri Aug 31 19:28:28 2018 +0200
+++ b/MqttMonitor/MqttClient.py	Sat Sep 01 20:18:11 2018 +0200
@@ -79,6 +79,77 @@
         self.__mqttClient.on_unsubscribe = \
             lambda client, userdata, mid: self.onUnsubscribe.emit(mid)
     
+    def reinitialise(self, clientId="", cleanSession=True, userdata=None):
+        """
+        Public method to reinitialize the client with given data.
+        
+        @param clientId ID to be used for the client
+        @type str
+        @param cleanSession flag indicating to start a clean session
+        @type bool
+        @param userdata user data
+        @type any
+        """
+        self.__mqttClient.reinitialise(
+            client_id=clientId, clean_session=cleanSession, userdata=userdata)
+    
+    def setMaxInflightMessages(self, inflight=20):
+        """
+        Public method to set the maximum number of messages with QoS > 0 that
+        can be part way through their network flow at once.
+        
+        @param inflight maximum number of messages in flight
+        @type int
+        """
+        self.__mqttClient.max_inflight_messages_set(inflight)
+    
+    def setMaxQueuedMessages(self, queueSize=0):
+        """
+        Public method to set the maximum number of messages with QoS > 0 that
+        can be pending in the outgoing message queue.
+        
+        @param queueSize maximum number of queued messages (0 = unlimited)
+        @type int
+        """
+        self.__mqttClient.max_queued_messages_set(queueSize)
+    
+    def setUserCredentials(self, username, password=None):
+        """
+        Public method to set the user name and optionally the password.
+        
+        @param username user name to be set
+        @type str
+        @param password optional password
+        @type str
+        """
+        self.__mqttClient.username_pw_set(username, password=password)
+    
+    def setUserData(self, userdata):
+        """
+        Public method to set the user data.
+        
+        @param userdata user data
+        @type any
+        """
+        self.__mqttClient.user_data_set(userdata)
+    
+    def setLastWill(self, topic, payload=None, qos=0, retain=False):
+        """
+        Public method to set the last will of the client.
+        
+        @param topic topic the will message should be published on
+        @type str
+        @param payload message to send as a will
+        @type str, bytes, int or float
+        @param qos quality of service level to use for the will
+        @type int, one of 0, 1 or 2
+        @param retain flag indicating to set as the "last known good"/retained
+            message for the will topic
+        @type bool
+        """
+        self.__mqttClient.will_set(topic, payload=payload, qos=qos,
+                                   retain=retain)
+    
     def startLoop(self):
         """
         Public method to start the MQTT client loop.
@@ -115,6 +186,85 @@
         if not self.__loopStarted:
             self.startLoop()
     
+    def connectToServerWithOptions(self, host, port=1883, bindAddress="",
+                                   options=None):
+        """
+        Public method to connect to a remote MQTT broker.
+        
+        @param host host name or IP address of the remote broker
+        @type str
+        @param port network port of the server host to connect to (default:
+            1883, using TLS: 8883)
+        @type int
+        @param bindAddress IP address of a local network interface to bind
+            this client to
+        @type str
+        @param options dictionary containing the connection options. This
+            dictionary should contain the keys "ClientId", "Keepalive",
+            "CleanSession", "Username", "Password", "WillTopic", "WillMessage",
+            "WillQos", "WillRetain"
+        @type dict
+        """
+        if options:
+            parametersDict = self.defaultConnectionOptions()
+            parametersDict.update(options)
+            
+            # step 1: reinitialize to set the client ID and clean session flag
+            self.reinitialise(
+                clientId=parametersDict["ClientId"],
+                cleanSession=parametersDict["CleanSession"]
+            )
+            
+            # step 2: set username and password
+            if parametersDict["Username"]:
+                if parametersDict["Password"]:
+                    self.setUserCredentials(parametersDict["Username"],
+                                            parametersDict["Password"])
+                else:
+                    self.setUserCredentials(parametersDict["Username"])
+            
+            # step 3: set last will data
+            if parametersDict["WillTopic"]:
+                if parametersDict["WillMessage"]:
+                    willMessage = parametersDict["WillMessage"]
+                else:
+                    # empty message to clear the will
+                    willMessage = None
+                self.setLastWill(parametersDict["WillTopic"],
+                                 willMessage,
+                                 parametersDict["WillQos"],
+                                 parametersDict["WillRetain"])
+            
+            # step 4: connect to server
+            self.connectToServer(host, port=port,
+                                 keepalive=parametersDict["Keepalive"])
+        else:
+            keepalive = self.defaultConnectionOptions["Keepalive"]
+            self.connectToServer(host, port=port, keepalive=keepalive,
+                                 bindAddress=bindAddress)
+    
+    def defaultConnectionOptions(self):
+        """
+        Public method to get a connection options dictionary with default
+        values.
+        
+        @return dictionary containing the default connection options. It has
+            the keys "ClientId", "Keepalive", "CleanSession", "Username",
+            "Password", "WillTopic", "WillMessage", "WillQos", "WillRetain"
+        @rtype dict
+        """
+        return {
+            "ClientId": "ERIC6_MQTT_MONITOR_CLIENT",
+            "Keepalive": 60,
+            "CleanSession": True,
+            "Username": "",
+            "Password": "",
+            "WillTopic": "",
+            "WillMessage": "",
+            "WillQos": 0,
+            "WillRetain": False,
+        }
+    
     def reconnectToServer(self):
         """
         Public method to reconnect the client with the same parameters.

eric ide

mercurial