-
Notifications
You must be signed in to change notification settings - Fork 722
/
client.py
5004 lines (4152 loc) · 198 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 v2.0
# and Eclipse Distribution License v1.0 which accompany this distribution.
#
# The Eclipse Public License is available at
# http://www.eclipse.org/legal/epl-v20.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
"""
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.
"""
from __future__ import annotations
import base64
import collections
import errno
import hashlib
import logging
import os
import platform
import select
import socket
import string
import struct
import threading
import time
import urllib.parse
import urllib.request
import uuid
import warnings
from typing import TYPE_CHECKING, Any, Callable, Dict, Iterator, List, NamedTuple, Sequence, Tuple, Union, cast
from paho.mqtt.packettypes import PacketTypes
from .enums import CallbackAPIVersion, ConnackCode, LogLevel, MessageState, MessageType, MQTTErrorCode, MQTTProtocolVersion, PahoClientMode, _ConnectionState
from .matcher import MQTTMatcher
from .properties import Properties
from .reasoncodes import ReasonCode, ReasonCodes
from .subscribeoptions import SubscribeOptions
try:
from typing import Literal
except ImportError:
from typing_extensions import Literal # type: ignore
if TYPE_CHECKING:
try:
from typing import TypedDict # type: ignore
except ImportError:
from typing_extensions import TypedDict
try:
from typing import Protocol # type: ignore
except ImportError:
from typing_extensions import Protocol # type: ignore
class _InPacket(TypedDict):
command: int
have_remaining: int
remaining_count: list[int]
remaining_mult: int
remaining_length: int
packet: bytearray
to_process: int
pos: int
class _OutPacket(TypedDict):
command: int
mid: int
qos: int
pos: int
to_process: int
packet: bytes
info: MQTTMessageInfo | None
class SocketLike(Protocol):
def recv(self, buffer_size: int) -> bytes:
...
def send(self, buffer: bytes) -> int:
...
def close(self) -> None:
...
def fileno(self) -> int:
...
def setblocking(self, flag: bool) -> None:
...
try:
import ssl
except ImportError:
ssl = None # type: ignore[assignment]
try:
import socks # type: ignore[import-untyped]
except ImportError:
socks = None # type: ignore[assignment]
try:
# Use monotonic clock if available
time_func = time.monotonic
except AttributeError:
time_func = time.time
try:
import dns.resolver
HAVE_DNS = True
except ImportError:
HAVE_DNS = False
if platform.system() == 'Windows':
EAGAIN = errno.WSAEWOULDBLOCK # type: ignore[attr-defined]
else:
EAGAIN = errno.EAGAIN
# Avoid linter complain. We kept importing it as ReasonCodes (plural) for compatibility
_ = ReasonCodes
# Keep copy of enums values for compatibility.
CONNECT = MessageType.CONNECT
CONNACK = MessageType.CONNACK
PUBLISH = MessageType.PUBLISH
PUBACK = MessageType.PUBACK
PUBREC = MessageType.PUBREC
PUBREL = MessageType.PUBREL
PUBCOMP = MessageType.PUBCOMP
SUBSCRIBE = MessageType.SUBSCRIBE
SUBACK = MessageType.SUBACK
UNSUBSCRIBE = MessageType.UNSUBSCRIBE
UNSUBACK = MessageType.UNSUBACK
PINGREQ = MessageType.PINGREQ
PINGRESP = MessageType.PINGRESP
DISCONNECT = MessageType.DISCONNECT
AUTH = MessageType.AUTH
# Log levels
MQTT_LOG_INFO = LogLevel.MQTT_LOG_INFO
MQTT_LOG_NOTICE = LogLevel.MQTT_LOG_NOTICE
MQTT_LOG_WARNING = LogLevel.MQTT_LOG_WARNING
MQTT_LOG_ERR = LogLevel.MQTT_LOG_ERR
MQTT_LOG_DEBUG = LogLevel.MQTT_LOG_DEBUG
LOGGING_LEVEL = {
LogLevel.MQTT_LOG_DEBUG: logging.DEBUG,
LogLevel.MQTT_LOG_INFO: logging.INFO,
LogLevel.MQTT_LOG_NOTICE: logging.INFO, # This has no direct equivalent level
LogLevel.MQTT_LOG_WARNING: logging.WARNING,
LogLevel.MQTT_LOG_ERR: logging.ERROR,
}
# CONNACK codes
CONNACK_ACCEPTED = ConnackCode.CONNACK_ACCEPTED
CONNACK_REFUSED_PROTOCOL_VERSION = ConnackCode.CONNACK_REFUSED_PROTOCOL_VERSION
CONNACK_REFUSED_IDENTIFIER_REJECTED = ConnackCode.CONNACK_REFUSED_IDENTIFIER_REJECTED
CONNACK_REFUSED_SERVER_UNAVAILABLE = ConnackCode.CONNACK_REFUSED_SERVER_UNAVAILABLE
CONNACK_REFUSED_BAD_USERNAME_PASSWORD = ConnackCode.CONNACK_REFUSED_BAD_USERNAME_PASSWORD
CONNACK_REFUSED_NOT_AUTHORIZED = ConnackCode.CONNACK_REFUSED_NOT_AUTHORIZED
# Message state
mqtt_ms_invalid = MessageState.MQTT_MS_INVALID
mqtt_ms_publish = MessageState.MQTT_MS_PUBLISH
mqtt_ms_wait_for_puback = MessageState.MQTT_MS_WAIT_FOR_PUBACK
mqtt_ms_wait_for_pubrec = MessageState.MQTT_MS_WAIT_FOR_PUBREC
mqtt_ms_resend_pubrel = MessageState.MQTT_MS_RESEND_PUBREL
mqtt_ms_wait_for_pubrel = MessageState.MQTT_MS_WAIT_FOR_PUBREL
mqtt_ms_resend_pubcomp = MessageState.MQTT_MS_RESEND_PUBCOMP
mqtt_ms_wait_for_pubcomp = MessageState.MQTT_MS_WAIT_FOR_PUBCOMP
mqtt_ms_send_pubrec = MessageState.MQTT_MS_SEND_PUBREC
mqtt_ms_queued = MessageState.MQTT_MS_QUEUED
MQTT_ERR_AGAIN = MQTTErrorCode.MQTT_ERR_AGAIN
MQTT_ERR_SUCCESS = MQTTErrorCode.MQTT_ERR_SUCCESS
MQTT_ERR_NOMEM = MQTTErrorCode.MQTT_ERR_NOMEM
MQTT_ERR_PROTOCOL = MQTTErrorCode.MQTT_ERR_PROTOCOL
MQTT_ERR_INVAL = MQTTErrorCode.MQTT_ERR_INVAL
MQTT_ERR_NO_CONN = MQTTErrorCode.MQTT_ERR_NO_CONN
MQTT_ERR_CONN_REFUSED = MQTTErrorCode.MQTT_ERR_CONN_REFUSED
MQTT_ERR_NOT_FOUND = MQTTErrorCode.MQTT_ERR_NOT_FOUND
MQTT_ERR_CONN_LOST = MQTTErrorCode.MQTT_ERR_CONN_LOST
MQTT_ERR_TLS = MQTTErrorCode.MQTT_ERR_TLS
MQTT_ERR_PAYLOAD_SIZE = MQTTErrorCode.MQTT_ERR_PAYLOAD_SIZE
MQTT_ERR_NOT_SUPPORTED = MQTTErrorCode.MQTT_ERR_NOT_SUPPORTED
MQTT_ERR_AUTH = MQTTErrorCode.MQTT_ERR_AUTH
MQTT_ERR_ACL_DENIED = MQTTErrorCode.MQTT_ERR_ACL_DENIED
MQTT_ERR_UNKNOWN = MQTTErrorCode.MQTT_ERR_UNKNOWN
MQTT_ERR_ERRNO = MQTTErrorCode.MQTT_ERR_ERRNO
MQTT_ERR_QUEUE_SIZE = MQTTErrorCode.MQTT_ERR_QUEUE_SIZE
MQTT_ERR_KEEPALIVE = MQTTErrorCode.MQTT_ERR_KEEPALIVE
MQTTv31 = MQTTProtocolVersion.MQTTv31
MQTTv311 = MQTTProtocolVersion.MQTTv311
MQTTv5 = MQTTProtocolVersion.MQTTv5
MQTT_CLIENT = PahoClientMode.MQTT_CLIENT
MQTT_BRIDGE = PahoClientMode.MQTT_BRIDGE
# For MQTT V5, use the clean start flag only on the first successful connect
MQTT_CLEAN_START_FIRST_ONLY: CleanStartOption = 3
sockpair_data = b"0"
# Payload support all those type and will be converted to bytes:
# * str are utf8 encoded
# * int/float are converted to string and utf8 encoded (e.g. 1 is converted to b"1")
# * None is converted to a zero-length payload (i.e. b"")
PayloadType = Union[str, bytes, bytearray, int, float, None]
HTTPHeader = Dict[str, str]
WebSocketHeaders = Union[Callable[[HTTPHeader], HTTPHeader], HTTPHeader]
CleanStartOption = Union[bool, Literal[3]]
class ConnectFlags(NamedTuple):
"""Contains additional information passed to `on_connect` callback"""
session_present: bool
"""
this flag is useful for clients that are
using clean session set to False only (MQTTv3) or clean_start = False (MQTTv5).
In that case, if client 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 true, the session still exists.
"""
class DisconnectFlags(NamedTuple):
"""Contains additional information passed to `on_disconnect` callback"""
is_disconnect_packet_from_server: bool
"""
tells whether this on_disconnect call is the result
of receiving an DISCONNECT packet from the broker or if the on_disconnect is only
generated by the client library.
When true, the reason code is generated by the broker.
"""
CallbackOnConnect_v1_mqtt3 = Callable[["Client", Any, Dict[str, Any], MQTTErrorCode], None]
CallbackOnConnect_v1_mqtt5 = Callable[["Client", Any, Dict[str, Any], ReasonCode, Union[Properties, None]], None]
CallbackOnConnect_v1 = Union[CallbackOnConnect_v1_mqtt5, CallbackOnConnect_v1_mqtt3]
CallbackOnConnect_v2 = Callable[["Client", Any, ConnectFlags, ReasonCode, Union[Properties, None]], None]
CallbackOnConnect = Union[CallbackOnConnect_v1, CallbackOnConnect_v2]
CallbackOnConnectFail = Callable[["Client", Any], None]
CallbackOnDisconnect_v1_mqtt3 = Callable[["Client", Any, MQTTErrorCode], None]
CallbackOnDisconnect_v1_mqtt5 = Callable[["Client", Any, Union[ReasonCode, int, None], Union[Properties, None]], None]
CallbackOnDisconnect_v1 = Union[CallbackOnDisconnect_v1_mqtt3, CallbackOnDisconnect_v1_mqtt5]
CallbackOnDisconnect_v2 = Callable[["Client", Any, DisconnectFlags, ReasonCode, Union[Properties, None]], None]
CallbackOnDisconnect = Union[CallbackOnDisconnect_v1, CallbackOnDisconnect_v2]
CallbackOnLog = Callable[["Client", Any, int, str], None]
CallbackOnMessage = Callable[["Client", Any, "MQTTMessage"], None]
CallbackOnPreConnect = Callable[["Client", Any], None]
CallbackOnPublish_v1 = Callable[["Client", Any, int], None]
CallbackOnPublish_v2 = Callable[["Client", Any, int, ReasonCode, Properties], None]
CallbackOnPublish = Union[CallbackOnPublish_v1, CallbackOnPublish_v2]
CallbackOnSocket = Callable[["Client", Any, "SocketLike"], None]
CallbackOnSubscribe_v1_mqtt3 = Callable[["Client", Any, int, Tuple[int, ...]], None]
CallbackOnSubscribe_v1_mqtt5 = Callable[["Client", Any, int, List[ReasonCode], Properties], None]
CallbackOnSubscribe_v1 = Union[CallbackOnSubscribe_v1_mqtt3, CallbackOnSubscribe_v1_mqtt5]
CallbackOnSubscribe_v2 = Callable[["Client", Any, int, List[ReasonCode], Union[Properties, None]], None]
CallbackOnSubscribe = Union[CallbackOnSubscribe_v1, CallbackOnSubscribe_v2]
CallbackOnUnsubscribe_v1_mqtt3 = Callable[["Client", Any, int], None]
CallbackOnUnsubscribe_v1_mqtt5 = Callable[["Client", Any, int, Properties, Union[ReasonCode, List[ReasonCode]]], None]
CallbackOnUnsubscribe_v1 = Union[CallbackOnUnsubscribe_v1_mqtt3, CallbackOnUnsubscribe_v1_mqtt5]
CallbackOnUnsubscribe_v2 = Callable[["Client", Any, int, List[ReasonCode], Union[Properties, None]], None]
CallbackOnUnsubscribe = Union[CallbackOnUnsubscribe_v1, CallbackOnUnsubscribe_v2]
# This is needed for typing because class Client redefined the name "socket"
_socket = socket
class WebsocketConnectionError(ConnectionError):
""" WebsocketConnectionError is a subclass of ConnectionError.
It's raised when unable to perform the Websocket handshake.
"""
pass
def error_string(mqtt_errno: MQTTErrorCode | int) -> str:
"""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."
elif mqtt_errno == MQTT_ERR_KEEPALIVE:
return "Client or broker did not communicate in the keepalive interval."
else:
return "Unknown error."
def connack_string(connack_code: int|ReasonCode) -> str:
"""Return the string associated with a CONNACK result or CONNACK reason code."""
if isinstance(connack_code, ReasonCode):
return str(connack_code)
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 convert_connack_rc_to_reason_code(connack_code: ConnackCode) -> ReasonCode:
"""Convert a MQTTv3 / MQTTv3.1.1 connack result to `ReasonCode`.
This is used in `on_connect` callback to have a consistent API.
Be careful that the numeric value isn't the same, for example:
>>> ConnackCode.CONNACK_REFUSED_SERVER_UNAVAILABLE == 3
>>> convert_connack_rc_to_reason_code(ConnackCode.CONNACK_REFUSED_SERVER_UNAVAILABLE) == 136
It's recommended to compare by names
>>> code_to_test = ReasonCode(PacketTypes.CONNACK, "Server unavailable")
>>> convert_connack_rc_to_reason_code(ConnackCode.CONNACK_REFUSED_SERVER_UNAVAILABLE) == code_to_test
"""
if connack_code == ConnackCode.CONNACK_ACCEPTED:
return ReasonCode(PacketTypes.CONNACK, "Success")
if connack_code == ConnackCode.CONNACK_REFUSED_PROTOCOL_VERSION:
return ReasonCode(PacketTypes.CONNACK, "Unsupported protocol version")
if connack_code == ConnackCode.CONNACK_REFUSED_IDENTIFIER_REJECTED:
return ReasonCode(PacketTypes.CONNACK, "Client identifier not valid")
if connack_code == ConnackCode.CONNACK_REFUSED_SERVER_UNAVAILABLE:
return ReasonCode(PacketTypes.CONNACK, "Server unavailable")
if connack_code == ConnackCode.CONNACK_REFUSED_BAD_USERNAME_PASSWORD:
return ReasonCode(PacketTypes.CONNACK, "Bad user name or password")
if connack_code == ConnackCode.CONNACK_REFUSED_NOT_AUTHORIZED:
return ReasonCode(PacketTypes.CONNACK, "Not authorized")
return ReasonCode(PacketTypes.CONNACK, "Unspecified error")
def convert_disconnect_error_code_to_reason_code(rc: MQTTErrorCode) -> ReasonCode:
"""Convert an MQTTErrorCode to Reason code.
This is used in `on_disconnect` callback to have a consistent API.
Be careful that the numeric value isn't the same, for example:
>>> MQTTErrorCode.MQTT_ERR_PROTOCOL == 2
>>> convert_disconnect_error_code_to_reason_code(MQTTErrorCode.MQTT_ERR_PROTOCOL) == 130
It's recommended to compare by names
>>> code_to_test = ReasonCode(PacketTypes.DISCONNECT, "Protocol error")
>>> convert_disconnect_error_code_to_reason_code(MQTTErrorCode.MQTT_ERR_PROTOCOL) == code_to_test
"""
if rc == MQTTErrorCode.MQTT_ERR_SUCCESS:
return ReasonCode(PacketTypes.DISCONNECT, "Success")
if rc == MQTTErrorCode.MQTT_ERR_KEEPALIVE:
return ReasonCode(PacketTypes.DISCONNECT, "Keep alive timeout")
if rc == MQTTErrorCode.MQTT_ERR_CONN_LOST:
return ReasonCode(PacketTypes.DISCONNECT, "Unspecified error")
return ReasonCode(PacketTypes.DISCONNECT, "Unspecified error")
def _base62(
num: int,
base: str = string.digits + string.ascii_letters,
padding: int = 1,
) -> str:
"""Convert a number to base-62 representation."""
if num < 0:
raise ValueError("Number must be positive or zero")
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: str, topic: str) -> bool:
"""Check whether a topic matches a subscription.
For example:
* Topic "foo/bar" would match the subscription "foo/#" or "+/bar"
* Topic "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() -> tuple[socket.socket, socket.socket]:
"""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(False)
try:
sock1.connect(("127.0.0.1", port))
except BlockingIOError:
pass
sock2, address = listensock.accept()
sock2.setblocking(False)
listensock.close()
return (sock1, sock2)
def _force_bytes(s: str | bytes) -> bytes:
if isinstance(s, str):
return s.encode("utf-8")
return s
def _encode_payload(payload: str | bytes | bytearray | int | float | None) -> bytes|bytearray:
if isinstance(payload, str):
return payload.encode("utf-8")
if isinstance(payload, (int, float)):
return str(payload).encode("ascii")
if payload is None:
return b""
if not isinstance(payload, (bytes, bytearray)):
raise TypeError(
"payload must be a string, bytearray, int, float or None."
)
return payload
class MQTTMessageInfo:
"""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: int):
self.mid = mid
""" The message Id (int)"""
self._published = False
self._condition = threading.Condition()
self.rc: MQTTErrorCode = MQTTErrorCode.MQTT_ERR_SUCCESS
""" The `MQTTErrorCode` that give status for this message.
This value could change until the message `is_published`"""
self._iterpos = 0
def __str__(self) -> str:
return str((self.rc, self.mid))
def __iter__(self) -> Iterator[MQTTErrorCode | int]:
self._iterpos = 0
return self
def __next__(self) -> MQTTErrorCode | int:
return self.next()
def next(self) -> MQTTErrorCode | int:
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: int) -> MQTTErrorCode | int:
if index == 0:
return self.rc
elif index == 1:
return self.mid
else:
raise IndexError("index out of range")
def _set_as_published(self) -> None:
with self._condition:
self._published = True
self._condition.notify()
def wait_for_publish(self, timeout: float | None = None) -> None:
"""Block until the message associated with this object is published, or
until the timeout occurs. If timeout is None, this will never time out.
Set timeout to a positive number of seconds, e.g. 1.2, to enable the
timeout.
:raises ValueError: if the message was not queued due to the outgoing
queue being full.
:raises RuntimeError: if the message was not published for another
reason.
"""
if self.rc == MQTT_ERR_QUEUE_SIZE:
raise ValueError('Message is not queued due to ERR_QUEUE_SIZE')
elif self.rc == MQTT_ERR_AGAIN:
pass
elif self.rc > 0:
raise RuntimeError(f'Message publish failed: {error_string(self.rc)}')
timeout_time = None if timeout is None else time_func() + timeout
timeout_tenth = None if timeout is None else timeout / 10.
def timed_out() -> bool:
return False if timeout_time is None else time_func() > timeout_time
with self._condition:
while not self._published and not timed_out():
self._condition.wait(timeout_tenth)
if self.rc > 0:
raise RuntimeError(f'Message publish failed: {error_string(self.rc)}')
def is_published(self) -> bool:
"""Returns True if the message associated with this object has been
published, else returns False.
To wait for this to become true, look at `wait_for_publish`.
"""
if self.rc == MQTTErrorCode.MQTT_ERR_QUEUE_SIZE:
raise ValueError('Message is not queued due to ERR_QUEUE_SIZE')
elif self.rc == MQTTErrorCode.MQTT_ERR_AGAIN:
pass
elif self.rc > 0:
raise RuntimeError(f'Message publish failed: {error_string(self.rc)}')
with self._condition:
return self._published
class MQTTMessage:
""" This is a class that describes an incoming message. It is
passed to the `on_message` callback as the message parameter.
"""
__slots__ = 'timestamp', 'state', 'dup', 'mid', '_topic', 'payload', 'qos', 'retain', 'info', 'properties'
def __init__(self, mid: int = 0, topic: bytes = b""):
self.timestamp = 0.0
self.state = mqtt_ms_invalid
self.dup = False
self.mid = mid
""" The message id (int)."""
self._topic = topic
self.payload = b""
"""the message payload (bytes)"""
self.qos = 0
""" The message Quality of Service (0, 1 or 2)."""
self.retain = False
""" If true, the message is a retained message and not fresh."""
self.info = MQTTMessageInfo(mid)
self.properties: Properties | None = None
""" In MQTT v5.0, the properties associated with the message. (`Properties`)"""
def __eq__(self, other: object) -> bool:
"""Override the default Equals behavior"""
if isinstance(other, self.__class__):
return self.mid == other.mid
return False
def __ne__(self, other: object) -> bool:
"""Define a non-equality test"""
return not self.__eq__(other)
@property
def topic(self) -> str:
"""topic that the message was published on.
This property is read-only.
"""
return self._topic.decode('utf-8')
@topic.setter
def topic(self, value: bytes) -> None:
self._topic = value
class Client:
"""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()` or `connect_srv()` to connect to a broker
* 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.
* Or call `loop()` frequently to maintain network traffic flow with the broker
* 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.
:param CallbackAPIVersion callback_api_version: define the API version for user-callback (on_connect, on_publish,...).
This field is required and it's recommended to use the latest version (CallbackAPIVersion.API_VERSION2).
See each callback for description of API for each version. The file docs/migrations.rst contains details on
how to migrate between version.
:param str client_id: 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.
:param bool clean_session: 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.
:param userdata: 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.
:param int protocol: 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.
:param transport: use "websockets" to use WebSockets as the transport
mechanism. Set to "tcp" to use raw TCP, which is the default.
Use "unix" to use Unix sockets as the transport mechanism; note that
this option is only available on platforms that support Unix sockets,
and the "host" argument is interpreted as the path to the Unix socket
file in this case.
:param bool manual_ack: normally, when a message is received, the library automatically
acknowledges after on_message callback returns. manual_ack=True allows the application to
acknowledge receipt after it has completed processing of a message
using a the ack() method. This addresses vulnerability to message loss
if applications fails while processing a message, or while it pending
locally.
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, reason_code, properties):
print(f"Connected with result code {reason_code}")
client.on_connect = on_connect
Callbacks can also be attached using decorators::
mqttc = paho.mqtt.Client()
@mqttc.connect_callback()
def on_connect(client, userdata, flags, reason_code, properties):
print(f"Connected with result code {reason_code}")
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()`.
If you wish to suppress exceptions within a callback, you should set
``mqttc.suppress_exceptions = True``
The callbacks are listed below, documentation for each of them can be found
at the same function name:
`on_connect`, `on_connect_fail`, `on_disconnect`, `on_message`, `on_publish`,
`on_subscribe`, `on_unsubscribe`, `on_log`, `on_socket_open`, `on_socket_close`,
`on_socket_register_write`, `on_socket_unregister_write`
"""
def __init__(
self,
callback_api_version: CallbackAPIVersion = CallbackAPIVersion.VERSION1,
client_id: str | None = "",
clean_session: bool | None = None,
userdata: Any = None,
protocol: MQTTProtocolVersion = MQTTv311,
transport: Literal["tcp", "websockets", "unix"] = "tcp",
reconnect_on_failure: bool = True,
manual_ack: bool = False,
) -> None:
transport = transport.lower() # type: ignore
if transport == "unix" and not hasattr(socket, "AF_UNIX"):
raise ValueError('"unix" transport not supported')
elif transport not in ("websockets", "tcp", "unix"):
raise ValueError(
f'transport must be "websockets", "tcp" or "unix", not {transport}')
self._manual_ack = manual_ack
self._transport = transport
self._protocol = protocol
self._userdata = userdata
self._sock: SocketLike | None = None
self._sockpairR: socket.socket | None = None
self._sockpairW: socket.socket | None = None
self._keepalive = 60
self._connect_timeout = 5.0
self._client_mode = MQTT_CLIENT
self._callback_api_version = callback_api_version
if self._callback_api_version == CallbackAPIVersion.VERSION1:
warnings.warn(
"Callback API version 1 is deprecated, update to latest version",
category=DeprecationWarning,
stacklevel=2,
)
if isinstance(self._callback_api_version, str):
# Help user to migrate, it probably provided a client id
# as first arguments
raise ValueError(
"Unsupported callback API version: version 2.0 added a callback_api_version, see docs/migrations.rst for details"
)
if self._callback_api_version not in CallbackAPIVersion:
raise ValueError("Unsupported callback API version")
self._clean_start: int = MQTT_CLEAN_START_FIRST_ONLY
if protocol == MQTTv5:
if clean_session is not None:
raise ValueError('Clean session is not used for MQTT 5.0')
else:
if clean_session is 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
# [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).encode("utf8")
else:
self._client_id = b""
else:
self._client_id = _force_bytes(client_id)
self._username: bytes | None = None
self._password: bytes | None = None
self._in_packet: _InPacket = {
"command": 0,
"have_remaining": 0,
"remaining_count": [],
"remaining_mult": 1,
"remaining_length": 0,
"packet": bytearray(b""),
"to_process": 0,
"pos": 0,
}
self._out_packet: collections.deque[_OutPacket] = collections.deque()
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: int | None = None
self._reconnect_on_failure = reconnect_on_failure
self._ping_t = 0.0
self._last_mid = 0
self._state = _ConnectionState.MQTT_CS_NEW
self._out_messages: collections.OrderedDict[
int, MQTTMessage
] = collections.OrderedDict()
self._in_messages: collections.OrderedDict[
int, MQTTMessage
] = collections.OrderedDict()
self._max_inflight_messages = 20
self._inflight_messages = 0
self._max_queued_messages = 0
self._connect_properties: Properties | None = None
self._will_properties: Properties | None = 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: Any = {}
self._in_callback_mutex = threading.Lock()
self._callback_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: threading.Thread | None = None
self._thread_terminate = False
self._ssl = False
self._ssl_context: ssl.SSLContext | None = None
# Only used when SSL context does not have check_hostname attribute
self._tls_insecure = False
self._logger: logging.Logger | None = None
self._registered_write = False
# No default callbacks
self._on_log: CallbackOnLog | None = None
self._on_pre_connect: CallbackOnPreConnect | None = None
self._on_connect: CallbackOnConnect | None = None
self._on_connect_fail: CallbackOnConnectFail | None = None
self._on_subscribe: CallbackOnSubscribe | None = None
self._on_message: CallbackOnMessage | None = None
self._on_publish: CallbackOnPublish | None = None
self._on_unsubscribe: CallbackOnUnsubscribe | None = None
self._on_disconnect: CallbackOnDisconnect | None = None
self._on_socket_open: CallbackOnSocket | None = None
self._on_socket_close: CallbackOnSocket | None = None
self._on_socket_register_write: CallbackOnSocket | None = None
self._on_socket_unregister_write: CallbackOnSocket | None = None
self._websocket_path = "/mqtt"
self._websocket_extra_headers: WebSocketHeaders | None = None
# for clean_start == MQTT_CLEAN_START_FIRST_ONLY
self._mqttv5_first_connect = True
self.suppress_exceptions = False # For callbacks
def __del__(self) -> None:
self._reset_sockets()
@property
def host(self) -> str:
"""
Host to connect to. If `connect()` hasn't been called yet, returns an empty string.
This property may not be changed if the connection is already open.
"""
return self._host
@host.setter
def host(self, value: str) -> None:
if not self._connection_closed():
raise RuntimeError("updating host on established connection is not supported")
if not value:
raise ValueError("Invalid host.")
self._host = value
@property
def port(self) -> int:
"""
Broker TCP port to connect to.
This property may not be changed if the connection is already open.
"""
return self._port
@port.setter
def port(self, value: int) -> None:
if not self._connection_closed():
raise RuntimeError("updating port on established connection is not supported")
if value <= 0:
raise ValueError("Invalid port number.")
self._port = value
@property
def keepalive(self) -> int:
"""
Client keepalive interval (in seconds).
This property may not be changed if the connection is already open.
"""
return self._keepalive
@keepalive.setter
def keepalive(self, value: int) -> None:
if not self._connection_closed():
# The issue here is that the previous value of keepalive matter to possibly
# sent ping packet.
raise RuntimeError("updating keepalive on established connection is not supported")
if value < 0:
raise ValueError("Keepalive must be >=0.")
self._keepalive = value
@property
def transport(self) -> Literal["tcp", "websockets", "unix"]:
"""
Transport method used for the connection ("tcp" or "websockets").
This property may not be changed if the connection is already open.
"""
return self._transport
@transport.setter
def transport(self, value: Literal["tcp", "websockets"]) -> None:
if not self._connection_closed():
raise RuntimeError("updating transport on established connection is not supported")
self._transport = value
@property
def protocol(self) -> MQTTProtocolVersion:
"""
Protocol version used (MQTT v3, MQTT v3.11, MQTTv5)
This property is read-only.
"""
return self._protocol
@property
def connect_timeout(self) -> float:
"""
Connection establishment timeout in seconds.
This property may not be changed if the connection is already open.
"""
return self._connect_timeout
@connect_timeout.setter
def connect_timeout(self, value: float) -> None:
if not self._connection_closed():
raise RuntimeError("updating connect_timeout on established connection is not supported")
if value <= 0.0:
raise ValueError("timeout must be a positive number")
self._connect_timeout = value
@property
def username(self) -> str | None:
"""The username used to connect to the MQTT broker, or None if no username is used.
This property may not be changed if the connection is already open.
"""
if self._username is None:
return None
return self._username.decode("utf-8")
@username.setter
def username(self, value: str | None) -> None:
if not self._connection_closed():
raise RuntimeError("updating username on established connection is not supported")
if value is None:
self._username = None
else: