METADATA
45.5 KB
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
Metadata-Version: 2.1
Name: paho-mqtt
Version: 1.5.0
Summary: MQTT version 3.1.1 client class
Home-page: http://eclipse.org/paho
Author: Roger Light
Author-email: roger@atchoo.org
License: Eclipse Public License v1.0 / Eclipse Distribution License v1.0
Keywords: paho
Platform: UNKNOWN
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved
Classifier: Operating System :: MacOS :: MacOS X
Classifier: Operating System :: Microsoft :: Windows
Classifier: Operating System :: POSIX
Classifier: Natural Language :: English
Classifier: Programming Language :: Python
Classifier: Programming Language :: Python :: 2
Classifier: Programming Language :: Python :: 2.7
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.4
Classifier: Programming Language :: Python :: 3.5
Classifier: Programming Language :: Python :: 3.6
Classifier: Topic :: Communications
Classifier: Topic :: Internet
Provides-Extra: proxy
Requires-Dist: PySocks ; extra == 'proxy'
Eclipse Paho™ MQTT Python Client
================================
This document describes the source code for the `Eclipse Paho <http://eclipse.org/paho/>`_ MQTT Python client library, which implements versions 3.1 and 3.1.1 of the MQTT protocol.
This code provides a client class which enable applications to connect to an `MQTT <http://mqtt.org/>`_ broker to publish messages, and to subscribe to topics and receive published messages. It also provides some helper functions to make publishing one off messages to an MQTT server very straightforward.
It supports Python 2.7.9+ or 3.4+, with limited support for Python 2.7 before 2.7.9.
The MQTT protocol is a machine-to-machine (M2M)/"Internet of Things" connectivity protocol. Designed as an extremely lightweight publish/subscribe messaging transport, it is useful for connections with remote locations where a small code footprint is required and/or network bandwidth is at a premium.
Paho is an `Eclipse Foundation <https://www.eclipse.org/org/foundation/>`_ project.
Contents
--------
* Installation_
* `Known limitations`_
* `Usage and API`_
* `Client`_
* `Constructor / reinitialise`_
* `Option functions`_
* `Connect / reconnect / disconnect`_
* `Network loop`_
* `Publishing`_
* `Subscribe / Unsubscribe`_
* `Callbacks`_
* `External event loop support`_
* `Global helper functions`_
* `Publish`_
* `Single`_
* `Multiple`_
* `Subscribe`_
* `Simple`_
* `Using Callback`_
* `Reporting bugs`_
* `More information`_
Installation
------------
The latest stable version is available in the Python Package Index (PyPi) and can be installed using
::
pip install paho-mqtt
Or with ``virtualenv``:
::
virtualenv paho-mqtt
source paho-mqtt/bin/activate
pip install paho-mqtt
To obtain the full code, including examples and tests, you can clone the git repository:
::
git clone https://github.com/eclipse/paho.mqtt.python
Once you have the code, it can be installed from your repository as well:
::
cd paho.mqtt.python
python setup.py install
To perform all test (including MQTT v5 test), you also need to clone paho.mqtt.testing in paho.mqtt.python folder::
git clone https://github.com/eclipse/paho.mqtt.testing.git
Known limitations
-----------------
The following are the known unimplemented MQTT feature.
When clean_session is False, the session is only stored in memory not persisted. This means that
when client is restarted (not just reconnected, the object is recreated usually because the
program was restarted) the session is lost. This result in possible message lost.
The following part of client session is lost:
* QoS 2 messages which have been received from the Server, but have not been completely acknowledged.
Since the client will blindly acknowledge any PUBCOMP (last message of a QoS 2 transaction), it
won't hang but will lost this QoS 2 message.
* QoS 1 and QoS 2 messages which have been sent to the Server, but have not been completely acknowledged.
This means that message passed to publish() may be lost. This could be mitigated by taking care
that all message passed to publish() has a corresponding on_publish() call.
It also means that the broker may have the Qos2 message in the session. Since the client start
with an empty session it don't know it and will re-use the mid. This is not yet fixed.
Also when clean_session is True, this library will republish QoS > 0 message accross network
reconnection. This means that QoS > 0 message won't be lost. But the standard say that
if we should discard any message for which the publish packet was sent. Our choice means that
we are not compliant with the standard and it's possible for QoS 2 to be received twice.
You should you clean_session = False if you need the QoS 2 guarantee of only one delivery.
Usage and API
-------------
Detailed API documentation is available through **pydoc**. Samples are available in the **examples** directory.
The package provides two modules, a full client and a helper for simple publishing.
Getting Started
***************
Here is a very simple example that subscribes to the broker $SYS topic tree and prints out the resulting messages:
.. code:: python
import paho.mqtt.client as mqtt
# The callback for when the client receives a CONNACK response from the server.
def on_connect(client, userdata, flags, rc):
print("Connected with result code "+str(rc))
# Subscribing in on_connect() means that if we lose the connection and
# reconnect then subscriptions will be renewed.
client.subscribe("$SYS/#")
# The callback for when a PUBLISH message is received from the server.
def on_message(client, userdata, msg):
print(msg.topic+" "+str(msg.payload))
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.connect("mqtt.eclipse.org", 1883, 60)
# Blocking call that processes network traffic, dispatches callbacks and
# handles reconnecting.
# Other loop*() functions are available that give a threaded interface and a
# manual interface.
client.loop_forever()
Client
******
You can use the client class as an instance, within a class or by subclassing. The general usage flow is as follows:
* Create a client instance
* Connect to a broker using one of the ``connect*()`` functions
* Call one of the ``loop*()`` functions to maintain network traffic flow with the broker
* Use ``subscribe()`` to subscribe to a topic and receive messages
* Use ``publish()`` to publish messages to the broker
* Use ``disconnect()`` to disconnect from the broker
Callbacks will be called to allow the application to process events as necessary. These callbacks are described below.
Constructor / reinitialise
``````````````````````````
Client()
''''''''
.. code:: python
Client(client_id="", clean_session=True, userdata=None, protocol=MQTTv311, transport="tcp")
The ``Client()`` constructor takes the following arguments:
client_id
the unique client id string used when connecting to the broker. If
``client_id`` is zero length or ``None``, then one will be randomly
generated. In this case the ``clean_session`` parameter must be ``True``.
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 durable 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.
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.
protocol
the version of the MQTT protocol to use for this client. Can be either
``MQTTv31`` or ``MQTTv311``
transport
set to "websockets" to send MQTT over WebSockets. Leave at the default of
"tcp" to use raw TCP.
Constructor Example
...................
.. code:: python
import paho.mqtt.client as mqtt
mqttc = mqtt.Client()
reinitialise()
''''''''''''''
.. code:: python
reinitialise(client_id="", clean_session=True, userdata=None)
The ``reinitialise()`` function resets the client to its starting state as if it had just been created. It takes the same arguments as the ``Client()`` constructor.
Reinitialise Example
....................
.. code:: python
mqttc.reinitialise()
Option functions
````````````````
These functions represent options that can be set on the client to modify its behaviour. In the majority of cases this must be done *before* connecting to a broker.
max_inflight_messages_set()
'''''''''''''''''''''''''''
.. code:: python
max_inflight_messages_set(self, inflight)
Set the maximum number of messages with QoS>0 that can be part way through their network flow at once.
Defaults to 20. Increasing this value will consume more memory but can increase throughput.
max_queued_messages_set()
'''''''''''''''''''''''''
.. code:: python
max_queued_messages_set(self, queue_size)
Set the maximum number of outgoing messages with QoS>0 that can be pending in the outgoing message queue.
Defaults to 0. 0 means unlimited. When the queue is full, any further outgoing messages would be dropped.
message_retry_set()
'''''''''''''''''''
.. code:: python
message_retry_set(retry)
Set the time in seconds before a message with QoS>0 is retried, if the broker does not respond.
This is set to 5 seconds by default and should not normally need changing.
ws_set_options()
''''''''''''''''
.. code:: python
ws_set_options(self, path="/mqtt", headers=None)
Set websocket connection options. These options will only be used if ``transport="websockets"`` was passed into the ``Client()`` constructor.
path
The mqtt path to use on the broker.
headers
Either a dictionary specifying a list of extra headers which should be appended to the standard websocket headers, or a callable that takes the normal websocket headers and returns a new dictionary with a set of headers to connect to the broker.
Must be called before ``connect*()``. An example of how this can be used with the AWS IoT platform is in the **examples** folder.
tls_set()
'''''''''
.. code:: python
tls_set(ca_certs=None, certfile=None, keyfile=None, cert_reqs=ssl.CERT_REQUIRED,
tls_version=ssl.PROTOCOL_TLS, 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, keyfile
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
defines the certificate requirements that the client imposes on the broker. 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
specifies the version of the SSL/TLS protocol to be used. By default (if the python version supports it) the highest TLS version is detected. If unavailable, TLS v1 is used. Previous versions (all versions beginning with SSL) are possible but not recommended due to possible security problems.
ciphers
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*()``.
tls_set_context()
'''''''''''''''''
.. code:: python
tls_set_context(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 (added in Python 3.4).
If you're unsure about using this method, then either use the default context, or use the ``tls_set`` method. See the ssl module documentation section about `security considerations <https://docs.python.org/3/library/ssl.html#ssl-security>`_ for more information.
Must be called before ``connect*()``.
tls_insecure_set()
''''''''''''''''''
.. code:: python
tls_insecure_set(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 ``tls_set()`` or ``tls_set_context()``.
enable_logger()
'''''''''''''''
.. code:: python
enable_logger(logger=None)
Enable logging using the standard python logging package (See PEP 282). This may be used at the same time as the ``on_log`` callback method.
If ``logger`` is specified, then that ``logging.Logger`` object will be used, otherwise one will be created automatically.
Paho logging levels are converted to standard ones according to the following mapping:
==================== ===============
Paho logging
==================== ===============
``MQTT_LOG_ERR`` ``logging.ERROR``
``MQTT_LOG_WARNING`` ``logging.WARNING``
``MQTT_LOG_NOTICE`` ``logging.INFO`` *(no direct equivalent)*
``MQTT_LOG_INFO`` ``logging.INFO``
``MQTT_LOG_DEBUG`` ``logging.DEBUG``
==================== ===============
disable_logger()
''''''''''''''''
.. code:: python
disable_logger()
Disable logging using standard python logging package. This has no effect on the ``on_log`` callback.
username_pw_set()
'''''''''''''''''
.. code:: python
username_pw_set(username, password=None)
Set a username and optionally a password for broker authentication. Must be called before ``connect*()``.
user_data_set()
'''''''''''''''
.. code:: python
user_data_set(userdata)
Set the private user data that will be passed to callbacks when events are generated. Use this for your own purpose to support your application.
will_set()
''''''''''
.. code:: python
will_set(topic, payload=None, qos=0, retain=False)
Set a Will to be sent to the broker. If the client disconnects without calling
``disconnect()``, the broker will publish the message on its behalf.
topic
the topic that the will message should be published on.
payload
the message to send as a will. If not given, or set to ``None`` a zero
length message will be used as the will. Passing an int or float will
result in the payload being converted to a string representing that number.
If you wish to send a true int/float, use ``struct.pack()`` to create the
payload you require.
qos
the quality of service level to use for the will.
retain
if set to ``True``, the will message will be set as the "last known
good"/retained message for the topic.
Raises a ``ValueError`` if ``qos`` is not 0, 1 or 2, or if ``topic`` is
``None`` or has zero string length.
reconnect_delay_set
'''''''''''''''''''
.. code:: python
reconnect_delay_set(min_delay=1, max_delay=120)
The client will automatically retry connection. Between each attempt
it will wait a number of seconds between ``min_delay`` and ``max_delay``.
When the connection is lost, initially the reconnection attempt is delayed of
``min_delay`` seconds. It's doubled between subsequent attempt up to ``max_delay``.
The delay is reset to ``min_delay`` when the connection complete (e.g. the CONNACK is
received, not just the TCP connection is established).
Connect / reconnect / disconnect
````````````````````````````````
connect()
'''''''''
.. code:: python
connect(host, port=1883, keepalive=60, bind_address="")
The ``connect()`` function connects the client to a broker. This is a blocking
function. It takes the following arguments:
host
the hostname or IP address of the remote broker
port
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()`` or ``tls_set_context()``, the port may need providing manually
keepalive
maximum period in seconds allowed 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
bind_address
the IP address of a local network interface to bind this client to,
assuming multiple interfaces exist
Callback
........
When the client receives a CONNACK message from the broker in response to the
connect it generates an ``on_connect()`` callback.
Connect Example
...............
.. code:: python
mqttc.connect("mqtt.eclipse.org")
connect_async()
'''''''''''''''
.. code:: python
connect_async(host, port=1883, keepalive=60, bind_address="")
Use in conjunction with ``loop_start()`` to connect in a non-blocking manner.
The connection will not complete until ``loop_start()`` is called.
Callback (connect)
..................
When the client receives a CONNACK message from the broker in response to the
connect it generates an ``on_connect()`` callback.
connect_srv()
'''''''''''''
.. code:: python
connect_srv(domain, keepalive=60, bind_address="")
Connect to a broker using an SRV DNS lookup to obtain the broker address. Takes
the following arguments:
domain
the DNS domain to search for SRV records. If ``None``, try to determine the
local domain name.
See ``connect()`` for a description of the ``keepalive`` and ``bind_address``
arguments.
Callback (connect_srv)
......................
When the client receives a CONNACK message from the broker in response to the
connect it generates an ``on_connect()`` callback.
SRV Connect Example
...................
.. code:: python
mqttc.connect_srv("eclipse.org")
reconnect()
'''''''''''
.. code:: python
reconnect()
Reconnect to a broker using the previously provided details. You must have
called ``connect*()`` before calling this function.
Callback (reconnect)
....................
When the client receives a CONNACK message from the broker in response to the
connect it generates an ``on_connect()`` callback.
disconnect()
''''''''''''
.. code:: python
disconnect()
Disconnect from the broker cleanly. Using ``disconnect()`` will not result in a
will message being sent by the broker.
Disconnect will not wait for all queued message to be sent, to ensure all messages
are delivered, ``wait_for_publish()`` from ``MQTTMessageInfo`` should be used.
See ``publish()`` for details.
Callback (disconnect)
.....................
When the client has sent the disconnect message it generates an
``on_disconnect()`` callback.
Network loop
````````````
These functions are the driving force behind the client. If they are not
called, incoming network data will not be processed and outgoing network data
may not be sent in a timely fashion. There are four options for managing the
network loop. Three are described here, the fourth in "External event loop
support" below. Do not mix the different loop functions.
loop()
''''''
.. code:: python
loop(timeout=1.0, max_packets=1)
Call regularly to process network events. This call waits in ``select()`` until
the network socket is available for reading or writing, if appropriate, then
handles the incoming/outgoing data. This function blocks for up to ``timeout``
seconds. ``timeout`` must not exceed the ``keepalive`` value for the client or
your client will be regularly disconnected by the broker.
The ``max_packets`` argument is obsolete and should be left unset.
Loop Example
............
.. code:: python
run = True
while run:
mqttc.loop()
loop_start() / loop_stop()
''''''''''''''''''''''''''
.. code:: python
loop_start()
loop_stop(force=False)
These functions implement a threaded interface to the network loop. Calling
``loop_start()`` once, before or after ``connect*()``, runs a thread in the
background to call ``loop()`` automatically. This frees up the main thread for
other work that may be blocking. This call also handles reconnecting to the
broker. Call ``loop_stop()`` to stop the background thread. The ``force``
argument is currently ignored.
Loop Start/Stop Example
.......................
.. code:: python
mqttc.connect("mqtt.eclipse.org")
mqttc.loop_start()
while True:
temperature = sensor.blocking_read()
mqttc.publish("paho/temperature", temperature)
loop_forever()
''''''''''''''
.. code:: python
loop_forever(timeout=1.0, max_packets=1, retry_first_connection=False)
This is a blocking form of the network loop and will not return until the
client calls ``disconnect()``. It automatically handles reconnecting.
Except for the first connection attempt when using connect_async, use
``retry_first_connection=True`` to make it retry the first connection.
Warning: This might lead to situations where the client keeps connecting to an
non existing host without failing.
The ``timeout`` and ``max_packets`` arguments are obsolete and should be left
unset.
Publishing
``````````
Send a message from the client to the broker.
publish()
'''''''''
.. code:: python
publish(topic, payload=None, qos=0, retain=False)
This causes a message to be sent to the broker and subsequently from the broker
to any clients subscribing to matching topics. It takes the following
arguments:
topic
the topic that the message should be published on
payload
the actual message to send. If not given, or set to ``None`` a zero length
message will be used. Passing an int or float will result in the payload
being converted to a string representing that number. If you wish to send a
true int/float, use ``struct.pack()`` to create the payload you require
qos
the quality of service level to use
retain
if set to ``True``, the message will be set as the "last known
good"/retained message for the topic.
Returns a MQTTMessageInfo which expose the following attributes and methods:
* ``rc``, the result of the publishing. It could be ``MQTT_ERR_SUCCESS`` to
indicate success, ``MQTT_ERR_NO_CONN`` if the client is not currently connected,
or ``MQTT_ERR_QUEUE_SIZE`` when ``max_queued_messages_set`` is used to indicate
that message is neither queued nor sent.
* ``mid`` is the message ID for the publish request. The mid value can be used to
track the publish request by checking against the mid argument in the
``on_publish()`` callback if it is defined. ``wait_for_publish`` may be easier
depending on your use-case.
* ``wait_for_publish()`` will block until the message is published. It will
raise ValueError if the message is not queued (rc == ``MQTT_ERR_QUEUE_SIZE``).
* ``is_published`` returns True if the message has been published. It will
raise ValueError if the message is not queued (rc == ``MQTT_ERR_QUEUE_SIZE``).
A ``ValueError`` will be raised if topic is ``None``, has zero length or is
invalid (contains a wildcard), if ``qos`` is not one of 0, 1 or 2, or if the
length of the payload is greater than 268435455 bytes.
Callback (publish)
..................
When the message has been sent to the broker an ``on_publish()`` callback will
be generated.
Subscribe / Unsubscribe
```````````````````````
subscribe()
'''''''''''
.. code:: python
subscribe(topic, qos=0)
Subscribe the client to one or more topics.
This function may be called in three different ways:
Simple string and integer
.........................
e.g. ``subscribe("my/topic", 2)``
topic
a string specifying the subscription topic to subscribe to.
qos
the desired quality of service level for the subscription. Defaults to 0.
String and integer tuple
........................
e.g. ``subscribe(("my/topic", 1))``
topic
a tuple of ``(topic, qos)``. Both topic and qos must be present in the tuple.
qos
not used.
List of string and integer tuples
.................................
e.g. ``subscribe([("my/topic", 0), ("another/topic", 2)])``
This allows multiple topic subscriptions in a single SUBSCRIPTION command,
which is more efficient than using multiple calls to ``subscribe()``.
topic
a list of tuple of format ``(topic, qos)``. Both topic and qos must be
present in all of the tuples.
qos
not used.
The function returns a tuple ``(result, mid)``, where ``result`` is
``MQTT_ERR_SUCCESS`` to indicate success or ``(MQTT_ERR_NO_CONN, None)`` if the
client is not currently connected. ``mid`` is the message ID for the subscribe
request. The mid value can be used to track the subscribe request by checking
against the mid argument in the ``on_subscribe()`` callback if it is defined.
Raises a ``ValueError`` if ``qos`` is not 0, 1 or 2, or if topic is ``None`` or
has zero string length, or if ``topic`` is not a string, tuple or list.
Callback (subscribe)
....................
When the broker has acknowledged the subscription, an ``on_subscribe()``
callback will be generated.
unsubscribe()
'''''''''''''
.. code:: python
unsubscribe(topic)
Unsubscribe the client from one or more topics.
topic
a single string, or list of strings that are the subscription topics to
unsubscribe from.
Returns a tuple ``(result, mid)``, where ``result`` is ``MQTT_ERR_SUCCESS`` to
indicate success, or ``(MQTT_ERR_NO_CONN, None)`` if the client is not
currently connected. ``mid`` is the message ID for the unsubscribe request. The
mid value can be used to track the unsubscribe request by checking against the
mid argument in the ``on_unsubscribe()`` callback if it is defined.
Raises a ``ValueError`` if ``topic`` is ``None`` or has zero string length, or
is not a string or list.
Callback (unsubscribe)
......................
When the broker has acknowledged the unsubscribe, an ``on_unsubscribe()``
callback will be generated.
Callbacks
`````````
on_connect()
''''''''''''
.. code:: python
on_connect(client, userdata, flags, rc)
Called when the broker responds to our connection request.
client
the client instance for this callback
userdata
the private user data as set in ``Client()`` or ``user_data_set()``
flags
response flags sent by the broker
rc
the connection result
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 indicates 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 Connect Example
..................
.. code:: python
def on_connect(client, userdata, flags, rc):
print("Connection returned result: "+connack_string(rc))
mqttc.on_connect = on_connect
...
on_disconnect()
'''''''''''''''
.. code:: python
on_disconnect(client, userdata, rc)
Called when the client disconnects from the broker.
client
the client instance for this callback
userdata
the private user data as set in ``Client()`` or ``user_data_set()``
rc
the disconnection result
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 Example
.....................
.. code:: python
def on_disconnect(client, userdata, rc):
if rc != 0:
print("Unexpected disconnection.")
mqttc.on_disconnect = on_disconnect
...
on_message()
''''''''''''
.. code:: python
on_message(client, userdata, message)
Called when a message has been received on a topic that the client subscribes
to and the message does not match an existing topic filter callback.
Use ``message_callback_add()`` to define a callback that will be called for
specific topic filters. ``on_message`` will serve as fallback when none matched.
client
the client instance for this callback
userdata
the private user data as set in ``Client()`` or ``user_data_set()``
message
an instance of MQTTMessage. This is a class with members ``topic``, ``payload``, ``qos``, ``retain``.
On Message Example
..................
.. code:: python
def on_message(client, userdata, message):
print("Received message '" + str(message.payload) + "' on topic '"
+ message.topic + "' with QoS " + str(message.qos))
mqttc.on_message = on_message
...
message_callback_add()
''''''''''''''''''''''
This function allows you to define callbacks that handle incoming messages for
specific subscription filters, including with wildcards. This lets you, for
example, subscribe to ``sensors/#`` and have one callback to handle
``sensors/temperature`` and another to handle ``sensors/humidity``.
.. code:: python
message_callback_add(sub, callback)
sub
the subscription filter to match against for this callback. Only one
callback may be defined per literal sub string
callback
the callback to be used. Takes the same form as the ``on_message``
callback.
If using ``message_callback_add()`` and ``on_message``, only messages that do
not match a subscription specific filter will be passed to the ``on_message``
callback.
If multiple sub match a topic, each callback will be called (e.g. sub ``sensors/#``
and sub ``+/humidity`` both match a message with a topic ``sensors/humidity``, so both
callbacks will handle this message).
message_callback_remove()
'''''''''''''''''''''''''
Remove a topic/subscription specific callback previously registered using
``message_callback_add()``.
.. code:: python
message_callback_remove(sub)
sub
the subscription filter to remove
on_publish()
''''''''''''
.. code:: python
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()
''''''''''''''
.. code:: python
on_subscribe(client, userdata, mid, granted_qos)
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()
''''''''''''''''
.. code:: python
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()
''''''''
.. code:: python
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``.
This may be used at the same time as the standard Python logging, which can be
enabled via the ``enable_logger`` method.
on_socket_open()
''''''''''''''''
::
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()
'''''''''''''''''
::
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()
''''''''''''''''''''''''''
::
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()
''''''''''''''''''''''''''''
::
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.
External event loop support
```````````````````````````
loop_read()
'''''''''''
.. code:: python
loop_read(max_packets=1)
Call when the socket is ready for reading. ``max_packets`` is obsolete and
should be left unset.
loop_write()
''''''''''''
.. code:: python
loop_write(max_packets=1)
Call when the socket is ready for writing. ``max_packets`` is obsolete and
should be left unset.
loop_misc()
'''''''''''
.. code:: python
loop_misc()
Call every few seconds to handle message retrying and pings.
socket()
''''''''
.. code:: python
socket()
Returns the socket object in use in the client to allow interfacing with other
event loops.
This call is particularly useful for select_ based loops. See ``examples/loop_select.py``.
.. _select: https://docs.python.org/3/library/select.html#select.select
want_write()
''''''''''''
.. code:: python
want_write()
Returns true if there is data waiting to be written, to allow interfacing the
client with other event loops.
This call is particularly useful for select_ based loops. See ``examples/loop_select.py``.
.. _select: https://docs.python.org/3/library/select.html#select.select
state callbacks
'''''''''''''''
::
on_socket_open
on_socket_close
on_socket_register_write
on_socket_unregister_write
Use these callbacks to get notified about state changes in the socket.
This is particularly useful for event loops where you register or unregister a socket
for reading+writing. See ``examples/loop_asyncio.py`` for an example.
When the socket is opened, ``on_socket_open`` is called.
Register the socket with your event loop for reading.
When the socket is about to be closed, ``on_socket_close`` is called.
Unregister the socket from your event loop for reading.
When a write to the socket failed because it would have blocked, e.g. output buffer full,
``on_socket_register_write`` is called.
Register the socket with your event loop for writing.
When the next write to the socket succeeded, ``on_socket_unregister_write`` is called.
Unregister the socket from your event loop for writing.
The callbacks are always called in this order:
- ``on_socket_open``
- Zero or more times:
- ``on_socket_register_write``
- ``on_socket_unregister_write``
- ``on_socket_close``
Global helper functions
```````````````````````
The client module also offers some global helper functions.
``topic_matches_sub(sub, topic)`` can be used to check whether a ``topic``
matches a ``subscription``.
For example:
the topic ``foo/bar`` would match the subscription ``foo/#`` or ``+/bar``
the topic ``non/matching`` would not match the subscription ``non/+/+``
``connack_string(connack_code)`` returns the error string associated with a
CONNACK result.
``error_string(mqtt_errno)`` returns the error string associated with a Paho
MQTT error number.
Publish
*******
This module provides some helper functions to allow straightforward publishing
of messages in a one-shot manner. In other words, they are useful for the
situation where you have a single/multiple messages you want to publish to a
broker, then disconnect with nothing else required.
The two functions provided are ``single()`` and ``multiple()``.
Single
``````
Publish a single message to a broker, then disconnect cleanly.
.. code:: python
single(topic, payload=None, qos=0, retain=False, hostname="localhost",
port=1883, client_id="", keepalive=60, will=None, auth=None, tls=None,
protocol=mqtt.MQTTv311, transport="tcp")
Publish Single Function arguments
'''''''''''''''''''''''''''''''''
topic
the only required argument must be the topic string to which the payload
will be published.
payload
the payload to be published. If "" or None, a zero length payload will be
published.
qos
the qos to use when publishing, default to 0.
retain
set the message to be retained (True) or not (False).
hostname
a string containing the address of the broker to connect to. Defaults to
localhost.
port
the port to connect to the broker on. Defaults to 1883.
client_id
the MQTT client id to use. If "" or None, the Paho library will
generate a client id automatically.
keepalive
the keepalive timeout value for the client. Defaults to 60 seconds.
will
a dict containing will parameters for the client:
will = {'topic': "<topic>", 'payload':"<payload">, 'qos':<qos>, 'retain':<retain>}.
Topic is required, all other parameters are optional and will default to
None, 0 and False respectively.
Defaults to None, which indicates no will should be used.
auth
a dict containing authentication parameters for the client:
auth = {'username':"<username>", 'password':"<password>"}
Username is required, password is optional and will default to None if not provided.
Defaults to None, which indicates no authentication is to be used.
tls
a dict containing TLS configuration parameters for the client:
dict = {'ca_certs':"<ca_certs>", 'certfile':"<certfile>", 'keyfile':"<keyfile>", 'tls_version':"<tls_version>", 'ciphers':"<ciphers">}
ca_certs is required, all other parameters are optional and will default to None if not provided, which results in the client using the default behaviour - see the paho.mqtt.client documentation.
Defaults to None, which indicates that TLS should not be used.
protocol
choose the version of the MQTT protocol to use. Use either ``MQTTv31`` or ``MQTTv311``.
transport
set to "websockets" to send MQTT over WebSockets. Leave at the default of
"tcp" to use raw TCP.
Publish Single Example
''''''''''''''''''''''
.. code:: python
import paho.mqtt.publish as publish
publish.single("paho/test/single", "payload", hostname="mqtt.eclipse.org")
Multiple
````````
Publish multiple messages to a broker, then disconnect cleanly.
.. code:: python
multiple(msgs, hostname="localhost", port=1883, client_id="", keepalive=60,
will=None, auth=None, tls=None, protocol=mqtt.MQTTv311, transport="tcp")
Publish Multiple Function arguments
'''''''''''''''''''''''''''''''''''
msgs
a list of messages to publish. Each message is either a dict or a tuple.
If a dict, only the topic must be present. Default values will be
used for any missing arguments. The dict must be of the form:
msg = {'topic':"<topic>", 'payload':"<payload>", 'qos':<qos>, 'retain':<retain>}
topic must be present and may not be empty.
If payload is "", None or not present then a zero length payload will be published. If qos is not present, the default of 0 is used. If retain is not present, the default of False is used.
If a tuple, then it must be of the form:
("<topic>", "<payload>", qos, retain)
See ``single()`` for the description of ``hostname``, ``port``, ``client_id``, ``keepalive``, ``will``, ``auth``, ``tls``, ``protocol``, ``transport``.
Publish Multiple Example
''''''''''''''''''''''''
.. code:: python
import paho.mqtt.publish as publish
msgs = [{'topic':"paho/test/multiple", 'payload':"multiple 1"},
("paho/test/multiple", "multiple 2", 0, False)]
publish.multiple(msgs, hostname="mqtt.eclipse.org")
Subscribe
*********
This module provides some helper functions to allow straightforward subscribing
and processing of messages.
The two functions provided are ``simple()`` and ``callback()``.
Simple
``````
Subscribe to a set of topics and return the messages received. This is a
blocking function.
.. code:: python
simple(topics, qos=0, msg_count=1, retained=False, hostname="localhost",
port=1883, client_id="", keepalive=60, will=None, auth=None, tls=None,
protocol=mqtt.MQTTv311)
Simple Subscribe Function arguments
'''''''''''''''''''''''''''''''''''
topics
the only required argument is the topic string to which the client will
subscribe. This can either be a string or a list of strings if multiple
topics should be subscribed to.
qos
the qos to use when subscribing, defaults to 0.
msg_count
the number of messages to retrieve from the broker. Defaults to 1. If 1, a
single MQTTMessage object will be returned. If >1, a list of MQTTMessages
will be returned.
retained
set to True to consider retained messages, set to False to ignore messages
with the retained flag set.
hostname
a string containing the address of the broker to connect to. Defaults to localhost.
port
the port to connect to the broker on. Defaults to 1883.
client_id
the MQTT client id to use. If "" or None, the Paho library will
generate a client id automatically.
keepalive
the keepalive timeout value for the client. Defaults to 60 seconds.
will
a dict containing will parameters for the client:
will = {'topic': "<topic>", 'payload':"<payload">, 'qos':<qos>, 'retain':<retain>}.
Topic is required, all other parameters are optional and will default to
None, 0 and False respectively.
Defaults to None, which indicates no will should be used.
auth
a dict containing authentication parameters for the client:
auth = {'username':"<username>", 'password':"<password>"}
Username is required, password is optional and will default to None if not
provided.
Defaults to None, which indicates no authentication is to be used.
tls
a dict containing TLS configuration parameters for the client:
dict = {'ca_certs':"<ca_certs>", 'certfile':"<certfile>", 'keyfile':"<keyfile>", 'tls_version':"<tls_version>", 'ciphers':"<ciphers">}
ca_certs is required, all other parameters are optional and will default to
None if not provided, which results in the client using the default
behaviour - see the paho.mqtt.client documentation.
Defaults to None, which indicates that TLS should not be used.
protocol
choose the version of the MQTT protocol to use. Use either ``MQTTv31`` or ``MQTTv311``.
Simple Example
''''''''''''''
.. code:: python
import paho.mqtt.subscribe as subscribe
msg = subscribe.simple("paho/test/simple", hostname="mqtt.eclipse.org")
print("%s %s" % (msg.topic, msg.payload))
Using Callback
``````````````
Subscribe to a set of topics and process the messages received using a user
provided callback.
.. code:: python
callback(callback, topics, qos=0, userdata=None, hostname="localhost",
port=1883, client_id="", keepalive=60, will=None, auth=None, tls=None,
protocol=mqtt.MQTTv311)
Callback Subscribe Function arguments
'''''''''''''''''''''''''''''''''''''
callback
an "on_message" callback that will be used for each message received, and
of the form
.. code:: python
def on_message(client, userdata, message)
topics
the topic string to which the client will subscribe. This can either be a
string or a list of strings if multiple topics should be subscribed to.
qos
the qos to use when subscribing, defaults to 0.
userdata
a user provided object that will be passed to the on_message callback when
a message is received.
See ``simple()`` for the description of ``hostname``, ``port``, ``client_id``, ``keepalive``, ``will``, ``auth``, ``tls``, ``protocol``.
Callback Example
''''''''''''''''
.. code:: python
import paho.mqtt.subscribe as subscribe
def on_message_print(client, userdata, message):
print("%s %s" % (message.topic, message.payload))
subscribe.callback(on_message_print, "paho/test/callback", hostname="mqtt.eclipse.org")
Reporting bugs
--------------
Please report bugs in the issues tracker at https://github.com/eclipse/paho.mqtt.python/issues.
More information
----------------
Discussion of the Paho clients takes place on the `Eclipse paho-dev mailing list <https://dev.eclipse.org/mailman/listinfo/paho-dev>`_.
General questions about the MQTT protocol itself (not this library) are discussed in the `MQTT Google Group <https://groups.google.com/forum/?fromgroups#!forum/mqtt>`_.
There is much more information available via the `MQTT community site <http://mqtt.org/>`_.