MqttMonitor/MqttClient.py

branch
eric7
changeset 123
3d7e63ed4fd1
parent 114
8c0e9e602124
child 127
8982ef7b7d67
equal deleted inserted replaced
122:28d69b9e1b6a 123:3d7e63ed4fd1
5 5
6 """ 6 """
7 Module implementing a PyQt wrapper around the paho MQTT client. 7 Module implementing a PyQt wrapper around the paho MQTT client.
8 """ 8 """
9 9
10 from PyQt6.QtCore import ( 10 from PyQt6.QtCore import pyqtSignal, pyqtSlot, QObject, QCoreApplication, QTimer
11 pyqtSignal, pyqtSlot, QObject, QCoreApplication, QTimer
12 )
13 11
14 import paho.mqtt.client as mqtt 12 import paho.mqtt.client as mqtt
15 from paho.mqtt.packettypes import PacketTypes 13 from paho.mqtt.packettypes import PacketTypes
16 from paho.mqtt.properties import Properties 14 from paho.mqtt.properties import Properties
17 15
21 19
22 20
23 class MqttClient(QObject): 21 class MqttClient(QObject):
24 """ 22 """
25 Class implementing a PyQt wrapper around the paho MQTT client. 23 Class implementing a PyQt wrapper around the paho MQTT client.
26 24
27 @signal onConnectV3(flags, rc) emitted after the client has connected to 25 @signal onConnectV3(flags, rc) emitted after the client has connected to
28 the broker (MQTT v3) 26 the broker (MQTT v3)
29 @signal onConnectV5(flags, rc, packetType, properties emitted after the 27 @signal onConnectV5(flags, rc, packetType, properties emitted after the
30 client has connected to the broker (MQTT v5) 28 client has connected to the broker (MQTT v5)
31 @signal onDisconnectedV3(rc) emitted after the client has disconnected from 29 @signal onDisconnectedV3(rc) emitted after the client has disconnected from
47 @signal onUnsubscribeV5(mid, rc, packetType, properties) emitted after the 45 @signal onUnsubscribeV5(mid, rc, packetType, properties) emitted after the
48 client has unsubscribed from some topics (MQTT v5) 46 client has unsubscribed from some topics (MQTT v5)
49 @signal connectTimeout() emitted to indicate, that a connection attempt 47 @signal connectTimeout() emitted to indicate, that a connection attempt
50 timed out 48 timed out
51 """ 49 """
50
52 onConnectV3 = pyqtSignal(dict, int) 51 onConnectV3 = pyqtSignal(dict, int)
53 onConnectV5 = pyqtSignal(dict, int, int, dict) 52 onConnectV5 = pyqtSignal(dict, int, int, dict)
54 onDisconnectedV3 = pyqtSignal(int) 53 onDisconnectedV3 = pyqtSignal(int)
55 onDisconnectedV5 = pyqtSignal(int, int) 54 onDisconnectedV5 = pyqtSignal(int, int)
56 onLog = pyqtSignal(int, str) 55 onLog = pyqtSignal(int, str)
59 onPublish = pyqtSignal(int) 58 onPublish = pyqtSignal(int)
60 onSubscribeV3 = pyqtSignal(int, tuple) 59 onSubscribeV3 = pyqtSignal(int, tuple)
61 onSubscribeV5 = pyqtSignal(int, list, dict) 60 onSubscribeV5 = pyqtSignal(int, list, dict)
62 onUnsubscribeV3 = pyqtSignal(int) 61 onUnsubscribeV3 = pyqtSignal(int)
63 onUnsubscribeV5 = pyqtSignal(int, int, int, dict) 62 onUnsubscribeV5 = pyqtSignal(int, int, int, dict)
64 63
65 connectTimeout = pyqtSignal() 64 connectTimeout = pyqtSignal()
66 65
67 DefaultConnectTimeout = 15 # connect timeout in seconds 66 DefaultConnectTimeout = 15 # connect timeout in seconds
68 67
69 LogDebug = 0x01 68 LogDebug = 0x01
70 LogInfo = 0x02 69 LogInfo = 0x02
71 LogNotice = 0x04 70 LogNotice = 0x04
72 LogWarning = 0x08 71 LogWarning = 0x08
73 LogError = 0x10 72 LogError = 0x10
74 LogDisabled = 0xff 73 LogDisabled = 0xFF
75 LogLevelMap = { 74 LogLevelMap = {
76 mqtt.MQTT_LOG_DEBUG: LogDebug, 75 mqtt.MQTT_LOG_DEBUG: LogDebug,
77 mqtt.MQTT_LOG_INFO: LogInfo, 76 mqtt.MQTT_LOG_INFO: LogInfo,
78 mqtt.MQTT_LOG_NOTICE: LogNotice, 77 mqtt.MQTT_LOG_NOTICE: LogNotice,
79 mqtt.MQTT_LOG_WARNING: LogWarning, # __NO-TASK__ 78 mqtt.MQTT_LOG_WARNING: LogWarning, # __NO-TASK__
80 mqtt.MQTT_LOG_ERR: LogError, 79 mqtt.MQTT_LOG_ERR: LogError,
81 } 80 }
82 81
83 def __init__(self, clientId="", cleanSession=True, userdata=None, 82 def __init__(
84 protocol=mqtt.MQTTv311, transport="tcp", parent=None): 83 self,
84 clientId="",
85 cleanSession=True,
86 userdata=None,
87 protocol=mqtt.MQTTv311,
88 transport="tcp",
89 parent=None,
90 ):
85 """ 91 """
86 Constructor 92 Constructor
87 93
88 @param clientId ID to be used for the client 94 @param clientId ID to be used for the client
89 @type str 95 @type str
90 @param cleanSession flag indicating to start a clean session 96 @param cleanSession flag indicating to start a clean session
91 @type bool 97 @type bool
92 @param userdata user data 98 @param userdata user data
97 @type str, one of "tcp" or "websockets" 103 @type str, one of "tcp" or "websockets"
98 @param parent reference to the parent object 104 @param parent reference to the parent object
99 @type QObject 105 @type QObject
100 """ 106 """
101 QObject.__init__(self, parent=parent) 107 QObject.__init__(self, parent=parent)
102 108
103 self.__loopStarted = False 109 self.__loopStarted = False
104 110
105 self.__connectTimeoutTimer = QTimer(self) 111 self.__connectTimeoutTimer = QTimer(self)
106 self.__connectTimeoutTimer.setSingleShot(True) 112 self.__connectTimeoutTimer.setSingleShot(True)
107 self.__connectTimeoutTimer.setInterval( 113 self.__connectTimeoutTimer.setInterval(MqttClient.DefaultConnectTimeout * 1000)
108 MqttClient.DefaultConnectTimeout * 1000)
109 self.__connectTimeoutTimer.timeout.connect(self.__connectTimeout) 114 self.__connectTimeoutTimer.timeout.connect(self.__connectTimeout)
110 115
111 self.onConnectV3.connect(self.__connectTimeoutTimer.stop) 116 self.onConnectV3.connect(self.__connectTimeoutTimer.stop)
112 self.onConnectV5.connect(self.__connectTimeoutTimer.stop) 117 self.onConnectV5.connect(self.__connectTimeoutTimer.stop)
113 118
114 self.__cleanSession = cleanSession 119 self.__cleanSession = cleanSession
115 self.__protocol = protocol 120 self.__protocol = protocol
116 self.__disconnectUserProperties = [] 121 self.__disconnectUserProperties = []
117 122
118 if protocol == MqttProtocols.MQTTv5: 123 if protocol == MqttProtocols.MQTTv5:
119 cleanSession = None 124 cleanSession = None
120 125
121 self.__mqttClient = mqtt.Client( 126 self.__mqttClient = mqtt.Client(
122 client_id=clientId, clean_session=cleanSession, userdata=userdata, 127 client_id=clientId,
123 protocol=int(protocol), transport=transport) 128 clean_session=cleanSession,
124 129 userdata=userdata,
130 protocol=int(protocol),
131 transport=transport,
132 )
133
125 self.__initCallbacks(protocol) 134 self.__initCallbacks(protocol)
126 135
127 def __initCallbacks(self, protocol): 136 def __initCallbacks(self, protocol):
128 """ 137 """
129 Private method to initialize the MQTT callback methods. 138 Private method to initialize the MQTT callback methods.
130 139
131 @param protocol MQTT protocol version 140 @param protocol MQTT protocol version
132 @type MqttProtocols 141 @type MqttProtocols
133 """ 142 """
134 if protocol in (MqttProtocols.MQTTv31, MqttProtocols.MQTTv311): 143 if protocol in (MqttProtocols.MQTTv31, MqttProtocols.MQTTv311):
135 self.__mqttClient.on_connect = ( 144 self.__mqttClient.on_connect = self.__onConnectV3
136 lambda client, userdata, flags, rc, properties=None: 145 self.__mqttClient.on_disconnect = self.__onDisconnectedV3
137 self.onConnectV3.emit(flags, rc) 146 self.__mqttClient.on_subscribe = self.__onSubscribeV3
138 ) 147 self.__mqttClient.on_unsubscribe = self.__onUnsubscribeV3
139 self.__mqttClient.on_disconnect = ( 148 self.__mqttClient.on_message = self.__onMessageV3
140 lambda client, userdata, rc:
141 self.onDisconnectedV3.emit(rc)
142 )
143 self.__mqttClient.on_subscribe = (
144 lambda client, userdata, mid, grantedQos, properties=None:
145 self.onSubscribeV3.emit(mid, grantedQos)
146 )
147 self.__mqttClient.on_unsubscribe = (
148 lambda client, userdata, mid:
149 self.onUnsubscribeV3.emit(mid)
150 )
151 self.__mqttClient.on_message = (
152 lambda client, userdata, message:
153 self.onMessageV3.emit(message.topic, message.payload,
154 message.qos, message.retain)
155 )
156 else: 149 else:
157 self.__mqttClient.on_connect = ( 150 self.__mqttClient.on_connect = self.__onConnectV5
158 lambda client, userdata, flags, rc, properties=None:
159 self.onConnectV5.emit(
160 flags, rc.value, rc.packetType,
161 properties.json() if properties is not None else {}
162 )
163 )
164 self.__mqttClient.on_disconnect = self.__onDisconnectedV5 151 self.__mqttClient.on_disconnect = self.__onDisconnectedV5
165 self.__mqttClient.on_subscribe = ( 152 self.__mqttClient.on_subscribe = self.__onSubscribeV5
166 lambda client, userdata, mid, reasonCodes, properties=None: 153 self.__mqttClient.on_unsubscribe = self.__onUnsubscribeV5
167 self.onSubscribeV5.emit( 154 self.__mqttClient.on_message = self.__onMessageV5
168 mid, reasonCodes, 155
169 properties.json() if properties is not None else {} 156 self.__mqttClient.on_log = self.__onLog
170 ) 157 self.__mqttClient.on_publish = self.__onPublish
171 ) 158
172 self.__mqttClient.on_unsubscribe = ( 159 def __onConnectV3(self, client, userdata, flags, rc, properties=None):
173 lambda client, userdata, mid, properties, rc: 160 """
174 self.onUnsubscribeV5.emit( 161 Private method to handle the connect to the broker (MQTT v3.1 and v3.1.1).
175 mid, rc.value, rc.packetType, 162
176 properties.json() if properties is not None else {} 163 @param client reference to the client object
177 ) 164 @type paho.mqtt.Client
178 ) 165 @param userdata user data
179 self.__mqttClient.on_message = ( 166 @type Any
180 lambda client, userdata, message: 167 @param flags dictionary containing the response flags sent by the broker
181 self.onMessageV5.emit( 168 @type dict
182 message.topic, message.payload, message.qos, 169 @param rc result code
183 message.retain, message.properties.json() 170 @type int
184 ) 171 @param properties optional properties (defaults to None)
185 ) 172 @type dict (optional)
186 self.__mqttClient.on_log = ( 173 """
187 lambda client, userdata, level, buf: 174 self.onConnectV3.emit(flags, rc)
188 self.onLog.emit(level, buf) 175
189 ) 176 def __onDisconnectedV3(self, client, userdata, rc):
190 self.__mqttClient.on_publish = ( 177 """
191 lambda client, userdata, mid: 178 Private method to handle the disconnect from the broker (MQTT v3.1 and v3.1.1).
192 self.onPublish.emit(mid) 179
193 ) 180 @param client reference to the client object
194 181 @type paho.mqtt.Client
182 @param userdata user data
183 @type Any
184 @param rc result code
185 @type int
186 """
187 self.onDisconnectedV3.emit(rc)
188
189 def __onSubscribeV3(self, client, userdata, mid, grantedQos):
190 """
191 Private method to handle a subscribe event (MQTT v3.1 and v3.1.1).
192
193 @param client reference to the client object
194 @type paho.mqtt.Client
195 @param userdata user data
196 @type Any
197 @param mid message ID
198 @type int
199 @param grantedQos list of granted QoS for each subscription request
200 @type list of int
201 """
202 self.onSubscribeV3.emit(mid, grantedQos)
203
204 def __onUnsubscribeV3(self, client, userdata, mid):
205 """
206 Private method to handle an unsubscribe event (MQTT v3.1 and v3.1.1).
207
208 @param client reference to the client object
209 @type paho.mqtt.Client
210 @param userdata user data
211 @type Any
212 @param mid message ID
213 @type int
214 """
215 self.onUnsubscribeV3.emit(mid)
216
217 def __onMessageV3(self, client, userdata, message):
218 """
219 Private method to handle a new message received from the broker (MQTT v3.1
220 and v3.1.1).
221
222 @param client reference to the client object
223 @type paho.mqtt.Client
224 @param userdata user data
225 @type Any
226 @param message received message object
227 @type paho.mqtt.MQTTMessage
228 """
229 self.onMessageV3.emit(
230 message.topic, message.payload, message.qos, message.retain
231 )
232
233 def __onConnectV5(self, client, userdata, flags, rc, properties=None):
234 """
235 Private method to handle the connect to the broker (MQTT v5.0).
236
237 @param client reference to the client object
238 @type paho.mqtt.Client
239 @param userdata user data
240 @type Any
241 @param flags dictionary containing the response flags sent by the broker
242 @type dict
243 @param rc reason code
244 @type paho.mqtt.ReasonCodes
245 @param properties optional properties (defaults to None)
246 @type dict (optional)
247 """
248 self.onConnectV5.emit(
249 flags,
250 rc.value,
251 rc.packetType,
252 properties.json() if properties is not None else {},
253 )
254
195 def __onDisconnectedV5(self, client, userdata, rc, properties=None): 255 def __onDisconnectedV5(self, client, userdata, rc, properties=None):
196 """ 256 """
197 Private method to handle the disconnect from the broker. 257 Private method to handle the disconnect from the broker (MQTT v5.0).
198 258
199 @param client reference to the client object 259 @param client reference to the client object
200 @type paho.mqtt.Client 260 @type paho.mqtt.Client
201 @param userdata user data 261 @param userdata user data
202 @type Any 262 @type Any
203 @param rc result code or reason code 263 @param rc result code or reason code
204 @type int or ReasonCodes 264 @type int or paho.mqtt.ReasonCodes
205 @param properties optional properties (defaults to None) 265 @param properties optional properties (defaults to None)
206 @type dict (optional) 266 @type dict (optional)
207 """ 267 """
208 if isinstance(rc, int): 268 if isinstance(rc, int):
209 packetType = PacketTypes.DISCONNECT 269 packetType = PacketTypes.DISCONNECT
210 resultCode = rc 270 resultCode = rc
211 else: 271 else:
212 packetType = rc.packetType 272 packetType = rc.packetType
213 resultCode = rc.value 273 resultCode = rc.value
214 self.onDisconnectedV5.emit(resultCode, packetType) 274 self.onDisconnectedV5.emit(resultCode, packetType)
215 275
276 def __onSubscribeV5(self, client, userdata, mid, reasonCodes, properties=None):
277 """
278 Private method to handle a subscribe event (MQTT v5.0).
279
280 @param client reference to the client object
281 @type paho.mqtt.Client
282 @param userdata user data
283 @type Any
284 @param mid message ID
285 @type int
286 @param reasonCodes list of reason code for each subscribed topic
287 @type list of paho.mqtt.ReasonCodes
288 @param properties optional properties (defaults to None)
289 @type dict (optional)
290 """
291 self.onSubscribeV5.emit(
292 mid,
293 reasonCodes,
294 properties.json() if properties is not None else {},
295 )
296
297 def __onUnsubscribeV5(self, client, userdata, mid, properties, reasonCodes):
298 """
299 Private method to handle an unsubscribe event (MQTT v5.0).
300
301 @param client reference to the client object
302 @type paho.mqtt.Client
303 @param userdata user data
304 @type Any
305 @param mid message ID
306 @type int
307 @param properties optional properties (defaults to None)
308 @type dict (optional)
309 @param reasonCodes list of reason code for each unsubscribed topic
310 @type list of paho.mqtt.ReasonCodes
311 """
312 self.onUnsubscribeV5.emit(
313 mid,
314 reasonCodes.value,
315 reasonCodes.packetType,
316 properties.json() if properties is not None else {},
317 )
318
319 def __onMessageV5(self, client, userdata, message):
320 """
321 Private method to handle a new message received from the broker (MQTT v5.0).
322
323 @param client reference to the client object
324 @type paho.mqtt.Client
325 @param userdata user data
326 @type Any
327 @param message received message object
328 @type paho.mqtt.MQTTMessage
329 """
330 self.onMessageV5.emit(
331 message.topic,
332 message.payload,
333 message.qos,
334 message.retain,
335 message.properties.json(),
336 )
337
338 def __onLog(self, client, userdata, level, buf):
339 """
340 Private method to handle a log event (MQTT v3.1, v3.1.1 and v5.0).
341
342 @param client reference to the client object
343 @type paho.mqtt.Client
344 @param userdata user data
345 @type Any
346 @param level severity of the log message
347 @type int
348 @param buf log message
349 @type str
350 """
351 self.onLog.emit(level, buf)
352
353 def __onPublish(self, client, userdata, mid):
354 """
355 Private method to handle the publishing of a message (MQTT v3.1, v3.1.1
356 and v5.0).
357
358 @param client reference to the client object
359 @type paho.mqtt.Client
360 @param userdata user data
361 @type Any
362 @param mid message ID
363 @type int
364 """
365 self.onPublish.emit(mid)
366
216 @pyqtSlot() 367 @pyqtSlot()
217 def __connectTimeout(self): 368 def __connectTimeout(self):
218 """ 369 """
219 Private slot handling a failed connection attempt. 370 Private slot handling a failed connection attempt.
220 """ 371 """
221 self.stopLoop() 372 self.stopLoop()
222 self.connectTimeout.emit() 373 self.connectTimeout.emit()
223 374
224 def setConnectionTimeout(self, timeout): 375 def setConnectionTimeout(self, timeout):
225 """ 376 """
226 Public method to set the connection timeout value. 377 Public method to set the connection timeout value.
227 378
228 @param timeout timeout value to be set in seconds 379 @param timeout timeout value to be set in seconds
229 @type int 380 @type int
230 """ 381 """
231 self.__connectTimeoutTimer.setInterval(timeout * 1000) 382 self.__connectTimeoutTimer.setInterval(timeout * 1000)
232 383
233 def setMaxInflightMessages(self, inflight=20): 384 def setMaxInflightMessages(self, inflight=20):
234 """ 385 """
235 Public method to set the maximum number of messages with QoS > 0 that 386 Public method to set the maximum number of messages with QoS > 0 that
236 can be part way through their network flow at once. 387 can be part way through their network flow at once.
237 388
238 @param inflight maximum number of messages in flight 389 @param inflight maximum number of messages in flight
239 @type int 390 @type int
240 """ 391 """
241 self.__mqttClient.max_inflight_messages_set(inflight) 392 self.__mqttClient.max_inflight_messages_set(inflight)
242 393
243 def setMaxQueuedMessages(self, queueSize=0): 394 def setMaxQueuedMessages(self, queueSize=0):
244 """ 395 """
245 Public method to set the maximum number of messages with QoS > 0 that 396 Public method to set the maximum number of messages with QoS > 0 that
246 can be pending in the outgoing message queue. 397 can be pending in the outgoing message queue.
247 398
248 @param queueSize maximum number of queued messages (0 = unlimited) 399 @param queueSize maximum number of queued messages (0 = unlimited)
249 @type int 400 @type int
250 """ 401 """
251 self.__mqttClient.max_queued_messages_set(queueSize) 402 self.__mqttClient.max_queued_messages_set(queueSize)
252 403
253 def setUserCredentials(self, username, password=None): 404 def setUserCredentials(self, username, password=None):
254 """ 405 """
255 Public method to set the user name and optionally the password. 406 Public method to set the user name and optionally the password.
256 407
257 @param username user name to be set 408 @param username user name to be set
258 @type str 409 @type str
259 @param password optional password 410 @param password optional password
260 @type str 411 @type str
261 """ 412 """
262 self.__mqttClient.username_pw_set(username, password=password) 413 self.__mqttClient.username_pw_set(username, password=password)
263 414
264 def setUserData(self, userdata): 415 def setUserData(self, userdata):
265 """ 416 """
266 Public method to set the user data. 417 Public method to set the user data.
267 418
268 @param userdata user data 419 @param userdata user data
269 @type any 420 @type any
270 """ 421 """
271 self.__mqttClient.user_data_set(userdata) 422 self.__mqttClient.user_data_set(userdata)
272 423
273 def setLastWill(self, topic, payload=None, qos=0, retain=False, 424 def setLastWill(self, topic, payload=None, qos=0, retain=False, properties=None):
274 properties=None):
275 """ 425 """
276 Public method to set the last will of the client. 426 Public method to set the last will of the client.
277 427
278 @param topic topic the will message should be published on 428 @param topic topic the will message should be published on
279 @type str 429 @type str
280 @param payload message to send as a will 430 @param payload message to send as a will
281 @type str, bytes, int or float 431 @type str, bytes, int or float
282 @param qos quality of service level to use for the will 432 @param qos quality of service level to use for the will
286 @type bool 436 @type bool
287 @param properties list of user properties to be sent with the 437 @param properties list of user properties to be sent with the
288 last will message 438 last will message
289 @type list of tuple of (str, str) 439 @type list of tuple of (str, str)
290 """ 440 """
291 self.__mqttClient.will_set(topic, payload=payload, qos=qos, 441 self.__mqttClient.will_set(
292 retain=retain, properties=properties) 442 topic, payload=payload, qos=qos, retain=retain, properties=properties
293 443 )
444
294 def clearLastWill(self): 445 def clearLastWill(self):
295 """ 446 """
296 Public method to remove a will that was previously configured with 447 Public method to remove a will that was previously configured with
297 setLastWill(). 448 setLastWill().
298 """ 449 """
299 self.__mqttClient.will_clear() 450 self.__mqttClient.will_clear()
300 451
301 def setTLS(self, caCerts=None, certFile=None, keyFile=None): 452 def setTLS(self, caCerts=None, certFile=None, keyFile=None):
302 """ 453 """
303 Public method to enable secure connections and set the TLS parameters. 454 Public method to enable secure connections and set the TLS parameters.
304 455
305 @param caCerts path to the Certificate Authority certificates file 456 @param caCerts path to the Certificate Authority certificates file
306 @type str 457 @type str
307 @param certFile PEM encoded client certificate file 458 @param certFile PEM encoded client certificate file
308 @type str 459 @type str
309 @param keyFile PEM encoded private key file 460 @param keyFile PEM encoded private key file
311 @return tuple containing a success flag and the error string of the 462 @return tuple containing a success flag and the error string of the
312 paho-mqtt library 463 paho-mqtt library
313 @rtype tuple of (bool, str) 464 @rtype tuple of (bool, str)
314 """ 465 """
315 try: 466 try:
316 self.__mqttClient.tls_set(ca_certs=caCerts, certfile=certFile, 467 self.__mqttClient.tls_set(
317 keyfile=keyFile) 468 ca_certs=caCerts, certfile=certFile, keyfile=keyFile
469 )
318 return True, "" 470 return True, ""
319 except (ValueError, FileNotFoundError) as err: 471 except (ValueError, FileNotFoundError) as err:
320 return False, str(err) 472 return False, str(err)
321 473
322 return False, "unspecific error occurred" 474 return False, "unspecific error occurred"
323 475
324 def getProtocol(self): 476 def getProtocol(self):
325 """ 477 """
326 Public method to get the MQTT protocol version. 478 Public method to get the MQTT protocol version.
327 479
328 @return MQTT protocol version in use 480 @return MQTT protocol version in use
329 @rtype int 481 @rtype int
330 """ 482 """
331 return self.__protocol 483 return self.__protocol
332 484
333 def startLoop(self): 485 def startLoop(self):
334 """ 486 """
335 Public method to start the MQTT client loop. 487 Public method to start the MQTT client loop.
336 """ 488 """
337 self.__mqttClient.loop_start() 489 self.__mqttClient.loop_start()
338 self.__loopStarted = True 490 self.__loopStarted = True
339 491
340 def stopLoop(self): 492 def stopLoop(self):
341 """ 493 """
342 Public method to stop the MQTT client loop. 494 Public method to stop the MQTT client loop.
343 """ 495 """
344 self.__mqttClient.loop_stop() 496 self.__mqttClient.loop_stop()
345 self.__loopStarted = False 497 self.__loopStarted = False
346 498
347 def connectToServer(self, host, port=1883, keepalive=60, bindAddress="", 499 def connectToServer(
348 properties=None, clearWill=False): 500 self,
501 host,
502 port=1883,
503 keepalive=60,
504 bindAddress="",
505 properties=None,
506 clearWill=False,
507 ):
349 """ 508 """
350 Public method to connect to a remote MQTT broker. 509 Public method to connect to a remote MQTT broker.
351 510
352 @param host host name or IP address of the remote broker 511 @param host host name or IP address of the remote broker
353 @type str 512 @type str
354 @param port network port of the server host to connect to (default: 513 @param port network port of the server host to connect to (default:
355 1883, using TLS: 8883) 514 1883, using TLS: 8883)
356 @type int 515 @type int
366 @param clearWill flag indicating to clear the last will previously set 525 @param clearWill flag indicating to clear the last will previously set
367 @type bool 526 @type bool
368 """ 527 """
369 if clearWill: 528 if clearWill:
370 self.clearLastWill() 529 self.clearLastWill()
371 530
372 props = ( 531 props = (
373 self.__createPropertiesObject(PacketTypes.CONNECT, properties) 532 self.__createPropertiesObject(PacketTypes.CONNECT, properties)
374 if properties else 533 if properties
375 None 534 else None
376 ) 535 )
377 self.__mqttClient.connect_async( 536 self.__mqttClient.connect_async(
378 host, port=port, keepalive=keepalive, bind_address=bindAddress, 537 host,
379 clean_start=self.__cleanSession, properties=props) 538 port=port,
380 539 keepalive=keepalive,
540 bind_address=bindAddress,
541 clean_start=self.__cleanSession,
542 properties=props,
543 )
544
381 self.__connectTimeoutTimer.start() 545 self.__connectTimeoutTimer.start()
382 546
383 if not self.__loopStarted: 547 if not self.__loopStarted:
384 self.startLoop() 548 self.startLoop()
385 549
386 def connectToServerWithOptions(self, host, port=1883, bindAddress="", 550 def connectToServerWithOptions(
387 options=None, clearWill=False): 551 self, host, port=1883, bindAddress="", options=None, clearWill=False
552 ):
388 """ 553 """
389 Public method to connect to a remote MQTT broker. 554 Public method to connect to a remote MQTT broker.
390 555
391 @param host host name or IP address of the remote broker 556 @param host host name or IP address of the remote broker
392 @type str 557 @type str
393 @param port network port of the server host to connect to (default: 558 @param port network port of the server host to connect to (default:
394 1883, using TLS: 8883) 559 1883, using TLS: 8883)
395 @type int 560 @type int
407 @type bool 572 @type bool
408 """ 573 """
409 if options: 574 if options:
410 parametersDict = self.defaultConnectionOptions() 575 parametersDict = self.defaultConnectionOptions()
411 parametersDict.update(options) 576 parametersDict.update(options)
412 577
413 self.setConnectionTimeout(parametersDict["ConnectionTimeout"]) 578 self.setConnectionTimeout(parametersDict["ConnectionTimeout"])
414 579
415 # step 1: set username and password 580 # step 1: set username and password
416 if parametersDict["Username"]: 581 if parametersDict["Username"]:
417 if parametersDict["Password"]: 582 if parametersDict["Password"]:
418 self.setUserCredentials( 583 self.setUserCredentials(
419 parametersDict["Username"], 584 parametersDict["Username"],
420 pwConvert(parametersDict["Password"], encode=False)) 585 pwConvert(parametersDict["Password"], encode=False),
586 )
421 else: 587 else:
422 self.setUserCredentials(parametersDict["Username"]) 588 self.setUserCredentials(parametersDict["Username"])
423 589
424 # step 2: set last will data 590 # step 2: set last will data
425 if not clearWill and parametersDict["WillTopic"]: 591 if not clearWill and parametersDict["WillTopic"]:
426 if parametersDict["WillMessage"]: 592 if parametersDict["WillMessage"]:
427 willMessage = parametersDict["WillMessage"] 593 willMessage = parametersDict["WillMessage"]
428 else: 594 else:
429 # empty message to clear the will 595 # empty message to clear the will
430 willMessage = None 596 willMessage = None
431 props = ( 597 props = (
432 self.__createPropertiesObject( 598 self.__createPropertiesObject(
433 PacketTypes.WILLMESSAGE, 599 PacketTypes.WILLMESSAGE, parametersDict["WillProperties"]
434 parametersDict["WillProperties"]) 600 )
435 if (parametersDict["WillProperties"] and 601 if (
436 self.__protocol == MqttProtocols.MQTTv5) else 602 parametersDict["WillProperties"]
437 None 603 and self.__protocol == MqttProtocols.MQTTv5
604 )
605 else None
438 ) 606 )
439 self.setLastWill(parametersDict["WillTopic"], 607 self.setLastWill(
440 payload=willMessage, 608 parametersDict["WillTopic"],
441 qos=parametersDict["WillQos"], 609 payload=willMessage,
442 retain=parametersDict["WillRetain"], 610 qos=parametersDict["WillQos"],
443 properties=props) 611 retain=parametersDict["WillRetain"],
444 612 properties=props,
613 )
614
445 # step 3: set TLS parameters 615 # step 3: set TLS parameters
446 if parametersDict["TlsEnable"]: 616 if parametersDict["TlsEnable"]:
447 if ( 617 if parametersDict["TlsCaCert"] and parametersDict["TlsClientCert"]:
448 parametersDict["TlsCaCert"] and
449 parametersDict["TlsClientCert"]
450 ):
451 # use self signed client certificate 618 # use self signed client certificate
452 self.setTLS(caCerts=parametersDict["TlsCaCert"], 619 self.setTLS(
453 certFile=parametersDict["TlsClientCert"], 620 caCerts=parametersDict["TlsCaCert"],
454 keyFile=parametersDict["TlsClientKey"]) 621 certFile=parametersDict["TlsClientCert"],
622 keyFile=parametersDict["TlsClientKey"],
623 )
455 elif parametersDict["TlsCaCert"]: 624 elif parametersDict["TlsCaCert"]:
456 # use CA certificate file 625 # use CA certificate file
457 self.setTLS(caCerts=parametersDict["TlsCaCert"]) 626 self.setTLS(caCerts=parametersDict["TlsCaCert"])
458 else: 627 else:
459 # use default TLS configuration 628 # use default TLS configuration
460 self.setTLS() 629 self.setTLS()
461 630
462 # step 4: get the connect user properties 631 # step 4: get the connect user properties
463 if self.__protocol == MqttProtocols.MQTTv5: 632 if self.__protocol == MqttProtocols.MQTTv5:
464 try: 633 try:
465 userProperties = parametersDict["UserProperties"] 634 userProperties = parametersDict["UserProperties"]
466 properties = userProperties["connect"][:] 635 properties = userProperties["connect"][:]
467 self.__disconnectUserProperties = ( 636 self.__disconnectUserProperties = (
468 userProperties["connect"][:] 637 userProperties["connect"][:]
469 if userProperties["use_connect"] else 638 if userProperties["use_connect"]
470 userProperties["disconnect"][:] 639 else userProperties["disconnect"][:]
471 ) 640 )
472 except KeyError: 641 except KeyError:
473 properties = None 642 properties = None
474 else: 643 else:
475 properties = None 644 properties = None
476 # step 4: connect to server 645 # step 4: connect to server
477 self.__cleanSession = parametersDict["CleanSession"] 646 self.__cleanSession = parametersDict["CleanSession"]
478 self.connectToServer(host, port=port, 647 self.connectToServer(
479 keepalive=parametersDict["Keepalive"], 648 host,
480 properties=properties, 649 port=port,
481 clearWill=clearWill) 650 keepalive=parametersDict["Keepalive"],
651 properties=properties,
652 clearWill=clearWill,
653 )
482 else: 654 else:
483 keepalive = self.defaultConnectionOptions()["Keepalive"] 655 keepalive = self.defaultConnectionOptions()["Keepalive"]
484 self.connectToServer(host, port=port, keepalive=keepalive, 656 self.connectToServer(
485 bindAddress=bindAddress, 657 host,
486 clearWill=clearWill) 658 port=port,
487 659 keepalive=keepalive,
660 bindAddress=bindAddress,
661 clearWill=clearWill,
662 )
663
488 @classmethod 664 @classmethod
489 def defaultConnectionOptions(cls): 665 def defaultConnectionOptions(cls):
490 """ 666 """
491 Class method to get a connection options dictionary with default 667 Class method to get a connection options dictionary with default
492 values. 668 values.
493 669
494 @return dictionary containing the default connection options. It has 670 @return dictionary containing the default connection options. It has
495 the keys "ClientId", "Protocol", "ConnectionTimeout", "Keepalive", 671 the keys "ClientId", "Protocol", "ConnectionTimeout", "Keepalive",
496 "CleanSession", "Username", "Password", "WillTopic", "WillMessage", 672 "CleanSession", "Username", "Password", "WillTopic", "WillMessage",
497 "WillQos", "WillRetain", "WillProperties", "TlsEnable", 673 "WillQos", "WillRetain", "WillProperties", "TlsEnable",
498 "TlsCaCert", "TlsClientCert", "TlsClientKey", "UserProperties". 674 "TlsCaCert", "TlsClientCert", "TlsClientKey", "UserProperties".
499 @rtype dict 675 @rtype dict
500 """ 676 """
501 from PluginMqttMonitor import mqttPluginObject 677 from PluginMqttMonitor import mqttPluginObject
502 678
503 return { 679 return {
504 "ClientId": "ERIC7_MQTT_MONITOR_CLIENT", 680 "ClientId": "ERIC7_MQTT_MONITOR_CLIENT",
505 "Protocol": mqttPluginObject.getPreferences("DefaultProtocol"), 681 "Protocol": mqttPluginObject.getPreferences("DefaultProtocol"),
506 "ConnectionTimeout": MqttClient.DefaultConnectTimeout, 682 "ConnectionTimeout": MqttClient.DefaultConnectTimeout,
507 "Keepalive": 60, 683 "Keepalive": 60,
521 "connect": [], 697 "connect": [],
522 "disconnect": [], 698 "disconnect": [],
523 "use_connect": True, 699 "use_connect": True,
524 }, 700 },
525 } 701 }
526 702
527 def reconnectToServer(self): 703 def reconnectToServer(self):
528 """ 704 """
529 Public method to reconnect the client with the same parameters. 705 Public method to reconnect the client with the same parameters.
530 """ 706 """
531 self.__connectTimeoutTimer.start() 707 self.__connectTimeoutTimer.start()
532 708
533 self.__mqttClient.reconnect() 709 self.__mqttClient.reconnect()
534 710
535 if not self.__loopStarted: 711 if not self.__loopStarted:
536 self.startLoop() 712 self.startLoop()
537 713
538 def disconnectFromServer(self): 714 def disconnectFromServer(self):
539 """ 715 """
540 Public method to disconnect the client from the remote broker. 716 Public method to disconnect the client from the remote broker.
541 """ 717 """
542 self.__connectTimeoutTimer.stop() 718 self.__connectTimeoutTimer.stop()
543 719
544 props = ( 720 props = (
545 self.__createPropertiesObject( 721 self.__createPropertiesObject(
546 PacketTypes.DISCONNECT, self.__disconnectUserProperties) 722 PacketTypes.DISCONNECT, self.__disconnectUserProperties
547 if self.__disconnectUserProperties else 723 )
548 None 724 if self.__disconnectUserProperties
725 else None
549 ) 726 )
550 self.__mqttClient.disconnect(properties=props) 727 self.__mqttClient.disconnect(properties=props)
551 728
552 def subscribe(self, topic, qos=0, properties=None): 729 def subscribe(self, topic, qos=0, properties=None):
553 """ 730 """
554 Public method to subscribe to topics with quality of service. 731 Public method to subscribe to topics with quality of service.
555 732
556 @param topic single topic to subscribe to or a tuple with a topic 733 @param topic single topic to subscribe to or a tuple with a topic
557 and a QoS or a list of tuples with a topic and a QoS each 734 and a QoS or a list of tuples with a topic and a QoS each
558 @type str or tuple of (str, int) or list of tuple of (str, int) 735 @type str or tuple of (str, int) or list of tuple of (str, int)
559 @param qos quality of service 736 @param qos quality of service
560 @type int, one of 0, 1 or 2 737 @type int, one of 0, 1 or 2
564 @return tuple containing the result code and the message ID 741 @return tuple containing the result code and the message ID
565 @rtype tuple of (int, int) 742 @rtype tuple of (int, int)
566 """ 743 """
567 props = ( 744 props = (
568 self.__createPropertiesObject(PacketTypes.SUBSCRIBE, properties) 745 self.__createPropertiesObject(PacketTypes.SUBSCRIBE, properties)
569 if properties else 746 if properties
570 None 747 else None
571 ) 748 )
572 return self.__mqttClient.subscribe(topic, qos=qos, properties=props) 749 return self.__mqttClient.subscribe(topic, qos=qos, properties=props)
573 750
574 def unsubscribe(self, topic, properties=None): 751 def unsubscribe(self, topic, properties=None):
575 """ 752 """
576 Public method to unsubscribe topics. 753 Public method to unsubscribe topics.
577 754
578 @param topic topic or list of topics to unsubscribe 755 @param topic topic or list of topics to unsubscribe
579 @type str or list of str 756 @type str or list of str
580 @param properties list of user properties to be sent with the 757 @param properties list of user properties to be sent with the
581 subscription 758 subscription
582 @type list of tuple of (str, str) 759 @type list of tuple of (str, str)
583 @return tuple containing the result code and the message ID 760 @return tuple containing the result code and the message ID
584 @rtype tuple of (int, int) 761 @rtype tuple of (int, int)
585 """ 762 """
586 props = ( 763 props = (
587 self.__createPropertiesObject(PacketTypes.UNSUBSCRIBE, properties) 764 self.__createPropertiesObject(PacketTypes.UNSUBSCRIBE, properties)
588 if properties else 765 if properties
589 None 766 else None
590 ) 767 )
591 return self.__mqttClient.unsubscribe(topic, properties=props) 768 return self.__mqttClient.unsubscribe(topic, properties=props)
592 769
593 def publish(self, topic, payload=None, qos=0, retain=False, 770 def publish(self, topic, payload=None, qos=0, retain=False, properties=None):
594 properties=None):
595 """ 771 """
596 Public method to publish to a topic. 772 Public method to publish to a topic.
597 773
598 @param topic topic to publish to 774 @param topic topic to publish to
599 @type str 775 @type str
600 @param payload data to be published 776 @param payload data to be published
601 @type str, bytes, int or float 777 @type str, bytes, int or float
602 @param qos quality of service 778 @param qos quality of service
610 @return message info object 786 @return message info object
611 @rtype mqtt.MQTTMessageInfo 787 @rtype mqtt.MQTTMessageInfo
612 """ 788 """
613 props = ( 789 props = (
614 self.__createPropertiesObject(PacketTypes.PUBLISH, properties) 790 self.__createPropertiesObject(PacketTypes.PUBLISH, properties)
615 if properties else 791 if properties
616 None 792 else None
617 ) 793 )
618 return self.__mqttClient.publish(topic, payload=payload, qos=qos, 794 return self.__mqttClient.publish(
619 retain=retain, properties=props) 795 topic, payload=payload, qos=qos, retain=retain, properties=props
620 796 )
797
621 def __createPropertiesObject(self, packetType, properties): 798 def __createPropertiesObject(self, packetType, properties):
622 """ 799 """
623 Private method to assemble the MQTT v5 properties object. 800 Private method to assemble the MQTT v5 properties object.
624 801
625 @param packetType type of the MQTT packet 802 @param packetType type of the MQTT packet
626 @type PacketTypes (= int) 803 @type PacketTypes (= int)
627 @param properties list of user properties 804 @param properties list of user properties
628 @type list of tuple of (str, str) 805 @type list of tuple of (str, str)
629 @return MQTT v5 properties object 806 @return MQTT v5 properties object
635 812
636 813
637 def mqttConnackMessage(connackCode): 814 def mqttConnackMessage(connackCode):
638 """ 815 """
639 Module function to get the string associated with a CONNACK result. 816 Module function to get the string associated with a CONNACK result.
640 817
641 @param connackCode result code of the connection request 818 @param connackCode result code of the connection request
642 @type int 819 @type int
643 @return textual representation for the result code 820 @return textual representation for the result code
644 @rtype str 821 @rtype str
645 """ 822 """
646 if connackCode == mqtt.CONNACK_ACCEPTED: 823 if connackCode == mqtt.CONNACK_ACCEPTED:
647 return QCoreApplication.translate( 824 return QCoreApplication.translate("MqttConnackMessage", "Connection Accepted.")
648 "MqttConnackMessage",
649 "Connection Accepted.")
650 elif connackCode == mqtt.CONNACK_REFUSED_PROTOCOL_VERSION: 825 elif connackCode == mqtt.CONNACK_REFUSED_PROTOCOL_VERSION:
651 return QCoreApplication.translate( 826 return QCoreApplication.translate(
652 "MqttConnackMessage", 827 "MqttConnackMessage", "Connection Refused: unacceptable protocol version."
653 "Connection Refused: unacceptable protocol version.") 828 )
654 elif connackCode == mqtt.CONNACK_REFUSED_IDENTIFIER_REJECTED: 829 elif connackCode == mqtt.CONNACK_REFUSED_IDENTIFIER_REJECTED:
655 return QCoreApplication.translate( 830 return QCoreApplication.translate(
656 "MqttConnackMessage", 831 "MqttConnackMessage", "Connection Refused: identifier rejected."
657 "Connection Refused: identifier rejected.") 832 )
658 elif connackCode == mqtt.CONNACK_REFUSED_SERVER_UNAVAILABLE: 833 elif connackCode == mqtt.CONNACK_REFUSED_SERVER_UNAVAILABLE:
659 return QCoreApplication.translate( 834 return QCoreApplication.translate(
660 "MqttConnackMessage", 835 "MqttConnackMessage", "Connection Refused: broker unavailable."
661 "Connection Refused: broker unavailable.") 836 )
662 elif connackCode == mqtt.CONNACK_REFUSED_BAD_USERNAME_PASSWORD: 837 elif connackCode == mqtt.CONNACK_REFUSED_BAD_USERNAME_PASSWORD:
663 return QCoreApplication.translate( 838 return QCoreApplication.translate(
664 "MqttConnackMessage", 839 "MqttConnackMessage", "Connection Refused: bad user name or password."
665 "Connection Refused: bad user name or password.") 840 )
666 elif connackCode == mqtt.CONNACK_REFUSED_NOT_AUTHORIZED: 841 elif connackCode == mqtt.CONNACK_REFUSED_NOT_AUTHORIZED:
667 return QCoreApplication.translate( 842 return QCoreApplication.translate(
668 "MqttConnackMessage", 843 "MqttConnackMessage", "Connection Refused: not authorised."
669 "Connection Refused: not authorised.") 844 )
670 else: 845 else:
671 return QCoreApplication.translate( 846 return QCoreApplication.translate(
672 "MqttConnackMessage", 847 "MqttConnackMessage", "Connection Refused: unknown reason."
673 "Connection Refused: unknown reason.") 848 )
674 849
675 850
676 def mqttErrorMessage(mqttErrno): 851 def mqttErrorMessage(mqttErrno):
677 """ 852 """
678 Module function to get the error string associated with an MQTT error 853 Module function to get the error string associated with an MQTT error
679 number. 854 number.
680 855
681 @param mqttErrno result code of a MQTT request 856 @param mqttErrno result code of a MQTT request
682 @type int 857 @type int
683 @return textual representation of the result code 858 @return textual representation of the result code
684 @rtype str 859 @rtype str
685 """ 860 """
686 if mqttErrno == mqtt.MQTT_ERR_SUCCESS: 861 if mqttErrno == mqtt.MQTT_ERR_SUCCESS:
862 return QCoreApplication.translate("MqttErrorMessage", "No error.")
863 elif mqttErrno == mqtt.MQTT_ERR_NOMEM:
864 return QCoreApplication.translate("MqttErrorMessage", "Out of memory.")
865 elif mqttErrno == mqtt.MQTT_ERR_PROTOCOL:
687 return QCoreApplication.translate( 866 return QCoreApplication.translate(
688 "MqttErrorMessage", 867 "MqttErrorMessage",
689 "No error.") 868 "A network protocol error occurred when communicating with" " the broker.",
690 elif mqttErrno == mqtt.MQTT_ERR_NOMEM: 869 )
691 return QCoreApplication.translate(
692 "MqttErrorMessage",
693 "Out of memory.")
694 elif mqttErrno == mqtt.MQTT_ERR_PROTOCOL:
695 return QCoreApplication.translate(
696 "MqttErrorMessage",
697 "A network protocol error occurred when communicating with"
698 " the broker.")
699 elif mqttErrno == mqtt.MQTT_ERR_INVAL: 870 elif mqttErrno == mqtt.MQTT_ERR_INVAL:
700 return QCoreApplication.translate( 871 return QCoreApplication.translate(
701 "MqttErrorMessage", 872 "MqttErrorMessage", "Invalid function arguments provided."
702 "Invalid function arguments provided.") 873 )
703 elif mqttErrno == mqtt.MQTT_ERR_NO_CONN: 874 elif mqttErrno == mqtt.MQTT_ERR_NO_CONN:
704 return QCoreApplication.translate( 875 return QCoreApplication.translate(
705 "MqttErrorMessage", 876 "MqttErrorMessage", "The client is not currently connected."
706 "The client is not currently connected.") 877 )
707 elif mqttErrno == mqtt.MQTT_ERR_CONN_REFUSED: 878 elif mqttErrno == mqtt.MQTT_ERR_CONN_REFUSED:
708 return QCoreApplication.translate( 879 return QCoreApplication.translate(
709 "MqttErrorMessage", 880 "MqttErrorMessage", "The connection was refused."
710 "The connection was refused.") 881 )
711 elif mqttErrno == mqtt.MQTT_ERR_NOT_FOUND: 882 elif mqttErrno == mqtt.MQTT_ERR_NOT_FOUND:
712 return QCoreApplication.translate( 883 return QCoreApplication.translate(
713 "MqttErrorMessage", 884 "MqttErrorMessage", "Message not found (internal error)."
714 "Message not found (internal error).") 885 )
715 elif mqttErrno == mqtt.MQTT_ERR_CONN_LOST: 886 elif mqttErrno == mqtt.MQTT_ERR_CONN_LOST:
716 return QCoreApplication.translate( 887 return QCoreApplication.translate(
717 "MqttErrorMessage", 888 "MqttErrorMessage", "The connection was lost."
718 "The connection was lost.") 889 )
719 elif mqttErrno == mqtt.MQTT_ERR_TLS: 890 elif mqttErrno == mqtt.MQTT_ERR_TLS:
720 return QCoreApplication.translate( 891 return QCoreApplication.translate("MqttErrorMessage", "A TLS error occurred.")
721 "MqttErrorMessage",
722 "A TLS error occurred.")
723 elif mqttErrno == mqtt.MQTT_ERR_PAYLOAD_SIZE: 892 elif mqttErrno == mqtt.MQTT_ERR_PAYLOAD_SIZE:
724 return QCoreApplication.translate( 893 return QCoreApplication.translate("MqttErrorMessage", "Payload too large.")
725 "MqttErrorMessage",
726 "Payload too large.")
727 elif mqttErrno == mqtt.MQTT_ERR_NOT_SUPPORTED: 894 elif mqttErrno == mqtt.MQTT_ERR_NOT_SUPPORTED:
728 return QCoreApplication.translate( 895 return QCoreApplication.translate(
729 "MqttErrorMessage", 896 "MqttErrorMessage", "This feature is not supported."
730 "This feature is not supported.") 897 )
731 elif mqttErrno == mqtt.MQTT_ERR_AUTH: 898 elif mqttErrno == mqtt.MQTT_ERR_AUTH:
732 return QCoreApplication.translate( 899 return QCoreApplication.translate("MqttErrorMessage", "Authorisation failed.")
733 "MqttErrorMessage",
734 "Authorisation failed.")
735 elif mqttErrno == mqtt.MQTT_ERR_ACL_DENIED: 900 elif mqttErrno == mqtt.MQTT_ERR_ACL_DENIED:
736 return QCoreApplication.translate( 901 return QCoreApplication.translate("MqttErrorMessage", "Access denied by ACL.")
737 "MqttErrorMessage",
738 "Access denied by ACL.")
739 elif mqttErrno == mqtt.MQTT_ERR_UNKNOWN: 902 elif mqttErrno == mqtt.MQTT_ERR_UNKNOWN:
740 return QCoreApplication.translate( 903 return QCoreApplication.translate("MqttErrorMessage", "Unknown error.")
741 "MqttErrorMessage",
742 "Unknown error.")
743 elif mqttErrno == mqtt.MQTT_ERR_ERRNO: 904 elif mqttErrno == mqtt.MQTT_ERR_ERRNO:
744 return QCoreApplication.translate( 905 return QCoreApplication.translate("MqttErrorMessage", "Error defined by errno.")
745 "MqttErrorMessage",
746 "Error defined by errno.")
747 elif mqttErrno == mqtt.MQTT_ERR_QUEUE_SIZE: 906 elif mqttErrno == mqtt.MQTT_ERR_QUEUE_SIZE:
748 return QCoreApplication.translate( 907 return QCoreApplication.translate("MqttErrorMessage", "Message queue full.")
749 "MqttErrorMessage",
750 "Message queue full.")
751 else: 908 else:
752 return QCoreApplication.translate( 909 return QCoreApplication.translate("MqttErrorMessage", "Unknown error.")
753 "MqttErrorMessage",
754 "Unknown error.")
755 910
756 911
757 def mqttLogLevelString(mqttLogLevel, isMqttLogLevel=True): 912 def mqttLogLevelString(mqttLogLevel, isMqttLogLevel=True):
758 """ 913 """
759 Module function to get the log level string associated with a log level. 914 Module function to get the log level string associated with a log level.
760 915
761 @param mqttLogLevel log level of the paho-mqtt client 916 @param mqttLogLevel log level of the paho-mqtt client
762 @type int 917 @type int
763 @param isMqttLogLevel flag indicating a MQTT log level is given (if 918 @param isMqttLogLevel flag indicating a MQTT log level is given (if
764 False it is the MqttClient variant, i.e. Debug being lowest) 919 False it is the MqttClient variant, i.e. Debug being lowest)
765 @type bool 920 @type bool
771 logLevel = MqttClient.LogLevelMap[mqttLogLevel] 926 logLevel = MqttClient.LogLevelMap[mqttLogLevel]
772 except KeyError: 927 except KeyError:
773 return QCoreApplication.translate("MqttLogLevelString", "Unknown") 928 return QCoreApplication.translate("MqttLogLevelString", "Unknown")
774 else: 929 else:
775 logLevel = mqttLogLevel 930 logLevel = mqttLogLevel
776 931
777 if logLevel == MqttClient.LogInfo: 932 if logLevel == MqttClient.LogInfo:
778 return QCoreApplication.translate("MqttLogLevelString", "Info") 933 return QCoreApplication.translate("MqttLogLevelString", "Info")
779 elif logLevel == MqttClient.LogNotice: 934 elif logLevel == MqttClient.LogNotice:
780 return QCoreApplication.translate("MqttLogLevelString", "Notice") 935 return QCoreApplication.translate("MqttLogLevelString", "Notice")
781 elif logLevel == MqttClient.LogWarning: 936 elif logLevel == MqttClient.LogWarning:
783 elif logLevel == MqttClient.LogError: 938 elif logLevel == MqttClient.LogError:
784 return QCoreApplication.translate("MqttLogLevelString", "Error") 939 return QCoreApplication.translate("MqttLogLevelString", "Error")
785 elif logLevel == MqttClient.LogDebug: 940 elif logLevel == MqttClient.LogDebug:
786 return QCoreApplication.translate("MqttLogLevelString", "Debug") 941 return QCoreApplication.translate("MqttLogLevelString", "Debug")
787 elif logLevel == MqttClient.LogDisabled: 942 elif logLevel == MqttClient.LogDisabled:
788 return QCoreApplication.translate("MqttLogLevelString", 943 return QCoreApplication.translate("MqttLogLevelString", "Logging Disabled")
789 "Logging Disabled")
790 else: 944 else:
791 return QCoreApplication.translate("MqttLogLevelString", "Unknown") 945 return QCoreApplication.translate("MqttLogLevelString", "Unknown")

eric ide

mercurial