-
Notifications
You must be signed in to change notification settings - Fork 726
/
client.py
3827 lines (3193 loc) · 147 KB
/
client.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright (c) 2012-2019 Roger Light and others
#
# All rights reserved. This program and the accompanying materials
# are made available under the terms of the Eclipse Public License v1.0
# and Eclipse Distribution License v1.0 which accompany this distribution.
#
# The Eclipse Public License is available at
# http://www.eclipse.org/legal/epl-v10.html
# and the Eclipse Distribution License is available at
# http://www.eclipse.org/org/documents/edl-v10.php.
#
# Contributors:
# Roger Light - initial API and implementation
# Ian Craggs - MQTT V5 support
from .subscribeoptions import SubscribeOptions
from .reasoncodes import ReasonCodes
from .properties import Properties
from .matcher import MQTTMatcher
import logging
import hashlib
import string
import base64
import uuid
import time
import threading
import sys
import struct
"""
This is an MQTT client module. MQTT is a lightweight pub/sub messaging
protocol that is easy to implement and suitable for low powered devices.
"""
import collections
import errno
import os
import platform
import select
import socket
ssl = None
try:
import ssl
except ImportError:
pass
socks = None
try:
import socks
except ImportError:
pass
try:
# Python 3
from urllib import request as urllib_dot_request
from urllib import parse as urllib_dot_parse
except ImportError:
# Python 2
import urllib as urllib_dot_request
import urlparse as urllib_dot_parse
try:
# Use monotonic clock if available
time_func = time.monotonic
except AttributeError:
time_func = time.time
try:
import dns.resolver
except ImportError:
HAVE_DNS = False
else:
HAVE_DNS = True
if platform.system() == 'Windows':
EAGAIN = errno.WSAEWOULDBLOCK
else:
EAGAIN = errno.EAGAIN
MQTTv31 = 3
MQTTv311 = 4
MQTTv5 = 5
if sys.version_info[0] >= 3:
# define some alias for python2 compatibility
unicode = str
basestring = str
# Message types
CONNECT = 0x10
CONNACK = 0x20
PUBLISH = 0x30
PUBACK = 0x40
PUBREC = 0x50
PUBREL = 0x60
PUBCOMP = 0x70
SUBSCRIBE = 0x80
SUBACK = 0x90
UNSUBSCRIBE = 0xA0
UNSUBACK = 0xB0
PINGREQ = 0xC0
PINGRESP = 0xD0
DISCONNECT = 0xE0
AUTH = 0xF0
# Log levels
MQTT_LOG_INFO = 0x01
MQTT_LOG_NOTICE = 0x02
MQTT_LOG_WARNING = 0x04
MQTT_LOG_ERR = 0x08
MQTT_LOG_DEBUG = 0x10
LOGGING_LEVEL = {
MQTT_LOG_DEBUG: logging.DEBUG,
MQTT_LOG_INFO: logging.INFO,
MQTT_LOG_NOTICE: logging.INFO, # This has no direct equivalent level
MQTT_LOG_WARNING: logging.WARNING,
MQTT_LOG_ERR: logging.ERROR,
}
# CONNACK codes
CONNACK_ACCEPTED = 0
CONNACK_REFUSED_PROTOCOL_VERSION = 1
CONNACK_REFUSED_IDENTIFIER_REJECTED = 2
CONNACK_REFUSED_SERVER_UNAVAILABLE = 3
CONNACK_REFUSED_BAD_USERNAME_PASSWORD = 4
CONNACK_REFUSED_NOT_AUTHORIZED = 5
# Connection state
mqtt_cs_new = 0
mqtt_cs_connected = 1
mqtt_cs_disconnecting = 2
mqtt_cs_connect_async = 3
# Message state
mqtt_ms_invalid = 0
mqtt_ms_publish = 1
mqtt_ms_wait_for_puback = 2
mqtt_ms_wait_for_pubrec = 3
mqtt_ms_resend_pubrel = 4
mqtt_ms_wait_for_pubrel = 5
mqtt_ms_resend_pubcomp = 6
mqtt_ms_wait_for_pubcomp = 7
mqtt_ms_send_pubrec = 8
mqtt_ms_queued = 9
# Error values
MQTT_ERR_AGAIN = -1
MQTT_ERR_SUCCESS = 0
MQTT_ERR_NOMEM = 1
MQTT_ERR_PROTOCOL = 2
MQTT_ERR_INVAL = 3
MQTT_ERR_NO_CONN = 4
MQTT_ERR_CONN_REFUSED = 5
MQTT_ERR_NOT_FOUND = 6
MQTT_ERR_CONN_LOST = 7
MQTT_ERR_TLS = 8
MQTT_ERR_PAYLOAD_SIZE = 9
MQTT_ERR_NOT_SUPPORTED = 10
MQTT_ERR_AUTH = 11
MQTT_ERR_ACL_DENIED = 12
MQTT_ERR_UNKNOWN = 13
MQTT_ERR_ERRNO = 14
MQTT_ERR_QUEUE_SIZE = 15
MQTT_CLIENT = 0
MQTT_BRIDGE = 1
# For MQTT V5, use the clean start flag only on the first successful connect
MQTT_CLEAN_START_FIRST_ONLY = 3
sockpair_data = b"0"
class WebsocketConnectionError(ValueError):
pass
class WouldBlockError(Exception):
pass
def error_string(mqtt_errno):
"""Return the error string associated with an mqtt error number."""
if mqtt_errno == MQTT_ERR_SUCCESS:
return "No error."
elif mqtt_errno == MQTT_ERR_NOMEM:
return "Out of memory."
elif mqtt_errno == MQTT_ERR_PROTOCOL:
return "A network protocol error occurred when communicating with the broker."
elif mqtt_errno == MQTT_ERR_INVAL:
return "Invalid function arguments provided."
elif mqtt_errno == MQTT_ERR_NO_CONN:
return "The client is not currently connected."
elif mqtt_errno == MQTT_ERR_CONN_REFUSED:
return "The connection was refused."
elif mqtt_errno == MQTT_ERR_NOT_FOUND:
return "Message not found (internal error)."
elif mqtt_errno == MQTT_ERR_CONN_LOST:
return "The connection was lost."
elif mqtt_errno == MQTT_ERR_TLS:
return "A TLS error occurred."
elif mqtt_errno == MQTT_ERR_PAYLOAD_SIZE:
return "Payload too large."
elif mqtt_errno == MQTT_ERR_NOT_SUPPORTED:
return "This feature is not supported."
elif mqtt_errno == MQTT_ERR_AUTH:
return "Authorisation failed."
elif mqtt_errno == MQTT_ERR_ACL_DENIED:
return "Access denied by ACL."
elif mqtt_errno == MQTT_ERR_UNKNOWN:
return "Unknown error."
elif mqtt_errno == MQTT_ERR_ERRNO:
return "Error defined by errno."
elif mqtt_errno == MQTT_ERR_QUEUE_SIZE:
return "Message queue full."
else:
return "Unknown error."
def connack_string(connack_code):
"""Return the string associated with a CONNACK result."""
if connack_code == CONNACK_ACCEPTED:
return "Connection Accepted."
elif connack_code == CONNACK_REFUSED_PROTOCOL_VERSION:
return "Connection Refused: unacceptable protocol version."
elif connack_code == CONNACK_REFUSED_IDENTIFIER_REJECTED:
return "Connection Refused: identifier rejected."
elif connack_code == CONNACK_REFUSED_SERVER_UNAVAILABLE:
return "Connection Refused: broker unavailable."
elif connack_code == CONNACK_REFUSED_BAD_USERNAME_PASSWORD:
return "Connection Refused: bad user name or password."
elif connack_code == CONNACK_REFUSED_NOT_AUTHORIZED:
return "Connection Refused: not authorised."
else:
return "Connection Refused: unknown reason."
def base62(num, base=string.digits + string.ascii_letters, padding=1):
"""Convert a number to base-62 representation."""
assert num >= 0
digits = []
while num:
num, rest = divmod(num, 62)
digits.append(base[rest])
digits.extend(base[0] for _ in range(len(digits), padding))
return ''.join(reversed(digits))
def topic_matches_sub(sub, topic):
"""Check whether a topic matches a subscription.
For example:
foo/bar would match the subscription foo/# or +/bar
non/matching would not match the subscription non/+/+
"""
matcher = MQTTMatcher()
matcher[sub] = True
try:
next(matcher.iter_match(topic))
return True
except StopIteration:
return False
def _socketpair_compat():
"""TCP/IP socketpair including Windows support"""
listensock = socket.socket(
socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_IP)
listensock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
listensock.bind(("127.0.0.1", 0))
listensock.listen(1)
iface, port = listensock.getsockname()
sock1 = socket.socket(
socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_IP)
sock1.setblocking(0)
try:
sock1.connect(("127.0.0.1", port))
except socket.error as err:
if err.errno != errno.EINPROGRESS and err.errno != errno.EWOULDBLOCK and err.errno != EAGAIN:
raise
sock2, address = listensock.accept()
sock2.setblocking(0)
listensock.close()
return (sock1, sock2)
class MQTTMessageInfo(object):
"""This is a class returned from Client.publish() and can be used to find
out the mid of the message that was published, and to determine whether the
message has been published, and/or wait until it is published.
"""
__slots__ = 'mid', '_published', '_condition', 'rc', '_iterpos'
def __init__(self, mid):
self.mid = mid
self._published = False
self._condition = threading.Condition()
self.rc = 0
self._iterpos = 0
def __str__(self):
return str((self.rc, self.mid))
def __iter__(self):
self._iterpos = 0
return self
def __next__(self):
return self.next()
def next(self):
if self._iterpos == 0:
self._iterpos = 1
return self.rc
elif self._iterpos == 1:
self._iterpos = 2
return self.mid
else:
raise StopIteration
def __getitem__(self, index):
if index == 0:
return self.rc
elif index == 1:
return self.mid
else:
raise IndexError("index out of range")
def _set_as_published(self):
with self._condition:
self._published = True
self._condition.notify()
def wait_for_publish(self):
"""Block until the message associated with this object is published."""
if self.rc == MQTT_ERR_QUEUE_SIZE:
raise ValueError('Message is not queued due to ERR_QUEUE_SIZE')
with self._condition:
while not self._published:
self._condition.wait()
def is_published(self):
"""Returns True if the message associated with this object has been
published, else returns False."""
if self.rc == MQTT_ERR_QUEUE_SIZE:
raise ValueError('Message is not queued due to ERR_QUEUE_SIZE')
with self._condition:
return self._published
class MQTTMessage(object):
""" This is a class that describes an incoming or outgoing message. It is
passed to the on_message callback as the message parameter.
Members:
topic : String/bytes. topic that the message was published on.
payload : String/bytes the message payload.
qos : Integer. The message Quality of Service 0, 1 or 2.
retain : Boolean. If true, the message is a retained message and not fresh.
mid : Integer. The message id.
properties: Properties class. In MQTT v5.0, the properties associated with the message.
On Python 3, topic must be bytes.
"""
__slots__ = 'timestamp', 'state', 'dup', 'mid', '_topic', 'payload', 'qos', 'retain', 'info', 'properties'
def __init__(self, mid=0, topic=b""):
self.timestamp = 0
self.state = mqtt_ms_invalid
self.dup = False
self.mid = mid
self._topic = topic
self.payload = b""
self.qos = 0
self.retain = False
self.info = MQTTMessageInfo(mid)
def __eq__(self, other):
"""Override the default Equals behavior"""
if isinstance(other, self.__class__):
return self.mid == other.mid
return False
def __ne__(self, other):
"""Define a non-equality test"""
return not self.__eq__(other)
@property
def topic(self):
return self._topic.decode('utf-8')
@topic.setter
def topic(self, value):
self._topic = value
class Client(object):
"""MQTT version 3.1/3.1.1/5.0 client class.
This is the main class for use communicating with an MQTT broker.
General usage flow:
* Use connect()/connect_async() to connect to a broker
* Call loop() frequently to maintain network traffic flow with the broker
* Or use loop_start() to set a thread running to call loop() for you.
* Or use loop_forever() to handle calling loop() for you in a blocking
* function.
* Use subscribe() to subscribe to a topic and receive messages
* Use publish() to send messages
* Use disconnect() to disconnect from the broker
Data returned from the broker is made available with the use of callback
functions as described below.
Callbacks
=========
A number of callback functions are available to receive data back from the
broker. To use a callback, define a function and then assign it to the
client:
def on_connect(client, userdata, flags, rc, properties=None):
print("Connection returned " + str(rc))
client.on_connect = on_connect
All of the callbacks as described below have a "client" and an "userdata"
argument. "client" is the Client instance that is calling the callback.
"userdata" is user data of any type and can be set when creating a new client
instance or with user_data_set(userdata).
The callbacks:
on_connect(client, userdata, flags, rc, properties=None): called when the broker responds to our connection
request.
flags is a dict that contains response flags from the broker:
flags['session present'] - this flag is useful for clients that are
using clean session set to 0 only. If a client with clean
session=0, that reconnects to a broker that it has previously
connected to, this flag indicates whether the broker still has the
session information for the client. If 1, the session still exists.
The value of rc determines success or not:
0: Connection successful
1: Connection refused - incorrect protocol version
2: Connection refused - invalid client identifier
3: Connection refused - server unavailable
4: Connection refused - bad username or password
5: Connection refused - not authorised
6-255: Currently unused.
on_disconnect(client, userdata, rc): called when the client disconnects from the broker.
The rc parameter indicates the disconnection state. If MQTT_ERR_SUCCESS
(0), the callback was called in response to a disconnect() call. If any
other value the disconnection was unexpected, such as might be caused by
a network error.
on_disconnect(client, userdata, rc, properties): called when the MQTT V5 client disconnects from the broker.
When using MQTT V5, the broker can send a disconnect message to the client. The
message can contain a reason code and MQTT V5 properties. The properties parameter could be
None if they do not exist in the disconnect message.
on_message(client, userdata, message): called when a message has been received on a
topic that the client subscribes to. The message variable is a
MQTTMessage that describes all of the message parameters.
on_publish(client, userdata, mid): called when a message that was to be sent using the
publish() call has completed transmission to the broker. For messages
with QoS levels 1 and 2, this means that the appropriate handshakes have
completed. For QoS 0, this simply means that the message has left the
client. The mid variable matches the mid variable returned from the
corresponding publish() call, to allow outgoing messages to be tracked.
This callback is important because even if the publish() call returns
success, it does not always mean that the message has been sent.
on_subscribe(client, userdata, mid, granted_qos, properties=None): called when the broker responds to a
subscribe request. The mid variable matches the mid variable returned
from the corresponding subscribe() call. The granted_qos variable is a
list of integers that give the QoS level the broker has granted for each
of the different subscription requests.
on_unsubscribe(client, userdata, mid): called when the broker responds to an unsubscribe
request. The mid variable matches the mid variable returned from the
corresponding unsubscribe() call.
on_log(client, userdata, level, buf): called when the client has log information. Define
to allow debugging. The level variable gives the severity of the message
and will be one of MQTT_LOG_INFO, MQTT_LOG_NOTICE, MQTT_LOG_WARNING,
MQTT_LOG_ERR, and MQTT_LOG_DEBUG. The message itself is in buf.
on_socket_open(client, userdata, sock): Called when the socket has been opened. Use this
to register the socket with an external event loop for reading.
on_socket_close(client, userdata, sock): Called when the socket is about to be closed.
Use this to unregister a socket from an external event loop for reading.
on_socket_register_write(client, userdata, sock): Called when a write operation to the
socket failed because it would have blocked, e.g. output buffer full. Use this to
register the socket with an external event loop for writing.
on_socket_unregister_write(client, userdata, sock): Called when a write operation to the
socket succeeded after it had previously failed. Use this to unregister the socket
from an external event loop for writing.
"""
def __init__(self, client_id="", clean_session=None, userdata=None,
protocol=MQTTv311, transport="tcp"):
"""client_id is the unique client id string used when connecting to the
broker. If client_id is zero length or None, then the behaviour is
defined by which protocol version is in use. If using MQTT v3.1.1, then
a zero length client id will be sent to the broker and the broker will
generate a random for the client. If using MQTT v3.1 then an id will be
randomly generated. In both cases, clean_session must be True. If this
is not the case a ValueError will be raised.
clean_session is a boolean that determines the client type. If True,
the broker will remove all information about this client when it
disconnects. If False, the client is a persistent client and
subscription information and queued messages will be retained when the
client disconnects.
Note that a client will never discard its own outgoing messages on
disconnect. Calling connect() or reconnect() will cause the messages to
be resent. Use reinitialise() to reset a client to its original state.
The clean_session argument only applies to MQTT versions v3.1.1 and v3.1.
It is not accepted if the MQTT version is v5.0 - use the clean_start
argument on connect() instead.
userdata is user defined data of any type that is passed as the "userdata"
parameter to callbacks. It may be updated at a later point with the
user_data_set() function.
The protocol argument allows explicit setting of the MQTT version to
use for this client. Can be paho.mqtt.client.MQTTv311 (v3.1.1),
paho.mqtt.client.MQTTv31 (v3.1) or paho.mqtt.client.MQTTv5 (v5.0),
with the default being v3.1.1.
Set transport to "websockets" to use WebSockets as the transport
mechanism. Set to "tcp" to use raw TCP, which is the default.
"""
if protocol == MQTTv5:
if clean_session != None:
raise ValueError('Clean session is not used for MQTT 5.0')
else:
if clean_session == None:
clean_session = True
if not clean_session and (client_id == "" or client_id is None):
raise ValueError(
'A client id must be provided if clean session is False.')
self._clean_session = clean_session
if transport.lower() not in ('websockets', 'tcp'):
raise ValueError(
'transport must be "websockets" or "tcp", not %s' % transport)
self._transport = transport.lower()
self._protocol = protocol
self._userdata = userdata
self._sock = None
self._sockpairR, self._sockpairW = (None, None,)
self._sockpairR, self._sockpairW = _socketpair_compat()
self._keepalive = 60
self._message_retry = 20
self._last_retry_check = 0
self._client_mode = MQTT_CLIENT
# [MQTT-3.1.3-4] Client Id must be UTF-8 encoded string.
if client_id == "" or client_id is None:
if protocol == MQTTv31:
self._client_id = base62(uuid.uuid4().int, padding=22)
else:
self._client_id = b""
else:
self._client_id = client_id
if isinstance(self._client_id, unicode):
self._client_id = self._client_id.encode('utf-8')
self._username = None
self._password = None
self._in_packet = {
"command": 0,
"have_remaining": 0,
"remaining_count": [],
"remaining_mult": 1,
"remaining_length": 0,
"packet": b"",
"to_process": 0,
"pos": 0}
self._out_packet = collections.deque()
self._current_out_packet = None
self._last_msg_in = time_func()
self._last_msg_out = time_func()
self._reconnect_min_delay = 1
self._reconnect_max_delay = 120
self._reconnect_delay = None
self._ping_t = 0
self._last_mid = 0
self._state = mqtt_cs_new
self._out_messages = collections.OrderedDict()
self._in_messages = collections.OrderedDict()
self._max_inflight_messages = 20
self._inflight_messages = 0
self._max_queued_messages = 0
self._connect_properties = None
self._will_properties = None
self._will = False
self._will_topic = b""
self._will_payload = b""
self._will_qos = 0
self._will_retain = False
self._on_message_filtered = MQTTMatcher()
self._host = ""
self._port = 1883
self._bind_address = ""
self._bind_port = 0
self._proxy = {}
self._in_callback_mutex = threading.Lock()
self._callback_mutex = threading.RLock()
self._out_packet_mutex = threading.Lock()
self._current_out_packet_mutex = threading.RLock()
self._msgtime_mutex = threading.Lock()
self._out_message_mutex = threading.RLock()
self._in_message_mutex = threading.Lock()
self._reconnect_delay_mutex = threading.Lock()
self._mid_generate_mutex = threading.Lock()
self._thread = None
self._thread_terminate = False
self._ssl = False
self._ssl_context = None
# Only used when SSL context does not have check_hostname attribute
self._tls_insecure = False
self._logger = None
self._registered_write = False
# No default callbacks
self._on_log = None
self._on_connect = None
self._on_subscribe = None
self._on_message = None
self._on_publish = None
self._on_unsubscribe = None
self._on_disconnect = None
self._on_socket_open = None
self._on_socket_close = None
self._on_socket_register_write = None
self._on_socket_unregister_write = None
self._websocket_path = "/mqtt"
self._websocket_extra_headers = None
# for clean_start == MQTT_CLEAN_START_FIRST_ONLY
self._mqttv5_first_connect = True
def __del__(self):
self._reset_sockets()
def _sock_recv(self, bufsize):
try:
return self._sock.recv(bufsize)
except socket.error as err:
if self._ssl and err.errno == ssl.SSL_ERROR_WANT_READ:
raise WouldBlockError()
if self._ssl and err.errno == ssl.SSL_ERROR_WANT_WRITE:
self._call_socket_register_write()
raise WouldBlockError()
if err.errno == EAGAIN:
raise WouldBlockError()
raise
def _sock_send(self, buf):
try:
return self._sock.send(buf)
except socket.error as err:
if self._ssl and err.errno == ssl.SSL_ERROR_WANT_READ:
raise WouldBlockError()
if self._ssl and err.errno == ssl.SSL_ERROR_WANT_WRITE:
self._call_socket_register_write()
raise WouldBlockError()
if err.errno == EAGAIN:
self._call_socket_register_write()
raise WouldBlockError()
raise
def _sock_close(self):
"""Close the connection to the server."""
if not self._sock:
return
try:
sock = self._sock
self._sock = None
self._call_socket_unregister_write(sock)
self._call_socket_close(sock)
finally:
# In case a callback fails, still close the socket to avoid leaking the file descriptor.
sock.close()
def _reset_sockets(self):
self._sock_close()
if self._sockpairR:
self._sockpairR.close()
self._sockpairR = None
if self._sockpairW:
self._sockpairW.close()
self._sockpairW = None
def reinitialise(self, client_id="", clean_session=True, userdata=None):
self._reset_sockets()
self.__init__(client_id, clean_session, userdata)
def ws_set_options(self, path="/mqtt", headers=None):
""" Set the path and headers for a websocket connection
path is a string starting with / which should be the endpoint of the
mqtt connection on the remote server
headers can be either a dict or a callable object. If it is a dict then
the extra items in the dict are added to the websocket headers. If it is
a callable, then the default websocket headers are passed into this
function and the result is used as the new headers.
"""
self._websocket_path = path
if headers is not None:
if isinstance(headers, dict) or callable(headers):
self._websocket_extra_headers = headers
else:
raise ValueError(
"'headers' option to ws_set_options has to be either a dictionary or callable")
def tls_set_context(self, context=None):
"""Configure network encryption and authentication context. Enables SSL/TLS support.
context : an ssl.SSLContext object. By default this is given by
`ssl.create_default_context()`, if available.
Must be called before connect() or connect_async()."""
if self._ssl_context is not None:
raise ValueError('SSL/TLS has already been configured.')
# Assume that have SSL support, or at least that context input behaves like ssl.SSLContext
# in current versions of Python
if context is None:
if hasattr(ssl, 'create_default_context'):
context = ssl.create_default_context()
else:
raise ValueError('SSL/TLS context must be specified')
self._ssl = True
self._ssl_context = context
# Ensure _tls_insecure is consistent with check_hostname attribute
if hasattr(context, 'check_hostname'):
self._tls_insecure = not context.check_hostname
def tls_set(self, ca_certs=None, certfile=None, keyfile=None, cert_reqs=None, tls_version=None, ciphers=None):
"""Configure network encryption and authentication options. Enables SSL/TLS support.
ca_certs : a string path to the Certificate Authority certificate files
that are to be treated as trusted by this client. If this is the only
option given then the client will operate in a similar manner to a web
browser. That is to say it will require the broker to have a
certificate signed by the Certificate Authorities in ca_certs and will
communicate using TLS v1, but will not attempt any form of
authentication. This provides basic network encryption but may not be
sufficient depending on how the broker is configured.
By default, on Python 2.7.9+ or 3.4+, the default certification
authority of the system is used. On older Python version this parameter
is mandatory.
certfile and keyfile are strings pointing to the PEM encoded client
certificate and private keys respectively. If these arguments are not
None then they will be used as client information for TLS based
authentication. Support for this feature is broker dependent. Note
that if either of these files in encrypted and needs a password to
decrypt it, Python will ask for the password at the command line. It is
not currently possible to define a callback to provide the password.
cert_reqs allows the certificate requirements that the client imposes
on the broker to be changed. By default this is ssl.CERT_REQUIRED,
which means that the broker must provide a certificate. See the ssl
pydoc for more information on this parameter.
tls_version allows the version of the SSL/TLS protocol used to be
specified. By default TLS v1 is used. Previous versions (all versions
beginning with SSL) are possible but not recommended due to possible
security problems.
ciphers is a string specifying which encryption ciphers are allowable
for this connection, or None to use the defaults. See the ssl pydoc for
more information.
Must be called before connect() or connect_async()."""
if ssl is None:
raise ValueError('This platform has no SSL/TLS.')
if not hasattr(ssl, 'SSLContext'):
# Require Python version that has SSL context support in standard library
raise ValueError(
'Python 2.7.9 and 3.2 are the minimum supported versions for TLS.')
if ca_certs is None and not hasattr(ssl.SSLContext, 'load_default_certs'):
raise ValueError('ca_certs must not be None.')
# Create SSLContext object
if tls_version is None:
tls_version = ssl.PROTOCOL_TLSv1
# If the python version supports it, use highest TLS version automatically
if hasattr(ssl, "PROTOCOL_TLS"):
tls_version = ssl.PROTOCOL_TLS
context = ssl.SSLContext(tls_version)
# Configure context
if certfile is not None:
context.load_cert_chain(certfile, keyfile)
if cert_reqs == ssl.CERT_NONE and hasattr(context, 'check_hostname'):
context.check_hostname = False
context.verify_mode = ssl.CERT_REQUIRED if cert_reqs is None else cert_reqs
if ca_certs is not None:
context.load_verify_locations(ca_certs)
else:
context.load_default_certs()
if ciphers is not None:
context.set_ciphers(ciphers)
self.tls_set_context(context)
if cert_reqs != ssl.CERT_NONE:
# Default to secure, sets context.check_hostname attribute
# if available
self.tls_insecure_set(False)
else:
# But with ssl.CERT_NONE, we can not check_hostname
self.tls_insecure_set(True)
def tls_insecure_set(self, value):
"""Configure verification of the server hostname in the server certificate.
If value is set to true, it is impossible to guarantee that the host
you are connecting to is not impersonating your server. This can be
useful in initial server testing, but makes it possible for a malicious
third party to impersonate your server through DNS spoofing, for
example.
Do not use this function in a real system. Setting value to true means
there is no point using encryption.
Must be called before connect() and after either tls_set() or
tls_set_context()."""
if self._ssl_context is None:
raise ValueError(
'Must configure SSL context before using tls_insecure_set.')
self._tls_insecure = value
# Ensure check_hostname is consistent with _tls_insecure attribute
if hasattr(self._ssl_context, 'check_hostname'):
# Rely on SSLContext to check host name
# If verify_mode is CERT_NONE then the host name will never be checked
self._ssl_context.check_hostname = not value
def proxy_set(self, **proxy_args):
"""Configure proxying of MQTT connection. Enables support for SOCKS or
HTTP proxies.
Proxying is done through the PySocks library. Brief descriptions of the
proxy_args parameters are below; see the PySocks docs for more info.
(Required)
proxy_type: One of {socks.HTTP, socks.SOCKS4, or socks.SOCKS5}
proxy_addr: IP address or DNS name of proxy server
(Optional)
proxy_rdns: boolean indicating whether proxy lookup should be performed
remotely (True, default) or locally (False)
proxy_username: username for SOCKS5 proxy, or userid for SOCKS4 proxy
proxy_password: password for SOCKS5 proxy
Must be called before connect() or connect_async()."""
if socks is None:
raise ValueError("PySocks must be installed for proxy support.")
elif not self._proxy_is_valid(proxy_args):
raise ValueError("proxy_type and/or proxy_addr are invalid.")
else:
self._proxy = proxy_args
def enable_logger(self, logger=None):
""" Enables a logger to send log messages to """
if logger is None:
if self._logger is not None:
# Do not replace existing logger
return
logger = logging.getLogger(__name__)
self._logger = logger
def disable_logger(self):
self._logger = None
def connect(self, host, port=1883, keepalive=60, bind_address="", bind_port=0,
clean_start=MQTT_CLEAN_START_FIRST_ONLY, properties=None):
"""Connect to a remote broker.
host is the hostname or IP address of the remote broker.
port is the network port of the server host to connect to. Defaults to
1883. Note that the default port for MQTT over SSL/TLS is 8883 so if you
are using tls_set() the port may need providing.
keepalive: Maximum period in seconds between communications with the
broker. If no other messages are being exchanged, this controls the
rate at which the client will send ping messages to the broker.
clean_start: (MQTT v5.0 only) True, False or MQTT_CLEAN_START_FIRST_ONLY.
Sets the MQTT v5.0 clean_start flag always, never or on the first successful connect only,
respectively. MQTT session data (such as outstanding messages and subscriptions)
is cleared on successful connect when the clean_start flag is set.
properties: (MQTT v5.0 only) the MQTT v5.0 properties to be sent in the
MQTT connect packet.
"""
if self._protocol == MQTTv5:
self._mqttv5_first_connect = True
else:
if clean_start != MQTT_CLEAN_START_FIRST_ONLY:
raise ValueError("Clean start only applies to MQTT V5")
if properties != None:
raise ValueError("Properties only apply to MQTT V5")
self.connect_async(host, port, keepalive,
bind_address, bind_port, clean_start, properties)
return self.reconnect()
def connect_srv(self, domain=None, keepalive=60, bind_address="",
clean_start=MQTT_CLEAN_START_FIRST_ONLY, properties=None):
"""Connect to a remote broker.
domain is the DNS domain to search for SRV records; if None,
try to determine local domain name.
keepalive, bind_address, clean_start and properties are as for connect()
"""
if HAVE_DNS is False:
raise ValueError(
'No DNS resolver library found, try "pip install dnspython" or "pip3 install dnspython3".')
if domain is None:
domain = socket.getfqdn()
domain = domain[domain.find('.') + 1:]
try:
rr = '_mqtt._tcp.%s' % domain
if self._ssl:
# IANA specifies secure-mqtt (not mqtts) for port 8883
rr = '_secure-mqtt._tcp.%s' % domain
answers = []
for answer in dns.resolver.query(rr, dns.rdatatype.SRV):
addr = answer.target.to_text()[:-1]
answers.append(
(addr, answer.port, answer.priority, answer.weight))
except (dns.resolver.NXDOMAIN, dns.resolver.NoAnswer, dns.resolver.NoNameservers):
raise ValueError("No answer/NXDOMAIN for SRV in %s" % (domain))
# FIXME: doesn't account for weight
for answer in answers:
host, port, prio, weight = answer
try:
return self.connect(host, port, keepalive, bind_address, clean_start, properties)
except Exception:
pass
raise ValueError("No SRV hosts responded")
def connect_async(self, host, port=1883, keepalive=60, bind_address="", bind_port=0,
clean_start=MQTT_CLEAN_START_FIRST_ONLY, properties=None):
"""Connect to a remote broker asynchronously. This is a non-blocking
connect call that can be used with loop_start() to provide very quick
start.
host is the hostname or IP address of the remote broker.
port is the network port of the server host to connect to. Defaults to
1883. Note that the default port for MQTT over SSL/TLS is 8883 so if you
are using tls_set() the port may need providing.
keepalive: Maximum period in seconds between communications with the
broker. If no other messages are being exchanged, this controls the
rate at which the client will send ping messages to the broker.
clean_start: (MQTT v5.0 only) True, False or MQTT_CLEAN_START_FIRST_ONLY.
Sets the MQTT v5.0 clean_start flag always, never or on the first successful connect only,
respectively. MQTT session data (such as outstanding messages and subscriptions)
is cleared on successful connect when the clean_start flag is set.
properties: (MQTT v5.0 only) the MQTT v5.0 properties to be sent in the
MQTT connect packet. Use the Properties class.
"""
if host is None or len(host) == 0: