• Home
  • History
  • Annotate
Name Date Size #Lines LOC

..03-May-2022-

examples/H03-May-2022-1,285673

src/H30-Oct-2019-6,6675,047

CONTRIBUTING.mdH A D30-Oct-20193.9 KiB8560

MANIFEST.inH A D30-Oct-2019203 119

PKG-INFOH A D30-Oct-201956.9 KiB1,494974

README.rstH A D30-Oct-201944.4 KiB1,466947

edl-v10H A D30-Oct-20191.5 KiB3223

epl-v10H A D30-Oct-201911.4 KiB222172

setup.cfgH A D30-Oct-2019183 1712

setup.pyH A D30-Oct-20191.9 KiB6051

README.rst

1Eclipse Paho™ MQTT Python Client
2================================
3
4This 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.
5
6This 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.
7
8It supports Python 2.7.9+ or 3.4+, with limited support for Python 2.7 before 2.7.9.
9
10The 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.
11
12Paho is an `Eclipse Foundation <https://www.eclipse.org/org/foundation/>`_ project.
13
14
15Contents
16--------
17
18* Installation_
19* `Known limitations`_
20* `Usage and API`_
21    * `Client`_
22        * `Constructor / reinitialise`_
23        * `Option functions`_
24        * `Connect / reconnect / disconnect`_
25        * `Network loop`_
26        * `Publishing`_
27        * `Subscribe / Unsubscribe`_
28        * `Callbacks`_
29        * `External event loop support`_
30        * `Global helper functions`_
31    * `Publish`_
32        * `Single`_
33        * `Multiple`_
34    * `Subscribe`_
35        * `Simple`_
36        * `Using Callback`_
37* `Reporting bugs`_
38* `More information`_
39
40
41Installation
42------------
43
44The latest stable version is available in the Python Package Index (PyPi) and can be installed using
45
46::
47
48    pip install paho-mqtt
49
50Or with ``virtualenv``:
51
52::
53
54    virtualenv paho-mqtt
55    source paho-mqtt/bin/activate
56    pip install paho-mqtt
57
58To obtain the full code, including examples and tests, you can clone the git repository:
59
60::
61
62    git clone https://github.com/eclipse/paho.mqtt.python
63
64
65Once you have the code, it can be installed from your repository as well:
66
67::
68
69    cd paho.mqtt.python
70    python setup.py install
71
72To perform all test (including MQTT v5 test), you also need to clone paho.mqtt.testing in paho.mqtt.python folder::
73
74    git clone https://github.com/eclipse/paho.mqtt.testing.git
75
76Known limitations
77-----------------
78
79The following are the known unimplemented MQTT feature.
80
81When clean_session is False, the session is only stored in memory not persisted. This means that
82when client is restarted (not just reconnected, the object is recreated usually because the
83program was restarted) the session is lost. This result in possible message lost.
84
85The following part of client session is lost:
86
87* QoS 2 messages which have been received from the Server, but have not been completely acknowledged.
88
89  Since the client will blindly acknowledge any PUBCOMP (last message of a QoS 2 transaction), it
90  won't hang but will lost this QoS 2 message.
91
92* QoS 1 and QoS 2 messages which have been sent to the Server, but have not been completely acknowledged.
93
94  This means that message passed to publish() may be lost. This could be mitigated by taking care
95  that all message passed to publish() has a corresponding on_publish() call.
96
97  It also means that the broker may have the Qos2 message in the session. Since the client start
98  with an empty session it don't know it and will re-use the mid. This is not yet fixed.
99
100Also when clean_session is True, this library will republish QoS > 0 message accross network
101reconnection. This means that QoS > 0 message won't be lost. But the standard say that
102if we should discard any message for which the publish packet was sent. Our choice means that
103we are not compliant with the standard and it's possible for QoS 2 to be received twice.
104You should you clean_session = False if you need the QoS 2 guarantee of only one delivery.
105
106Usage and API
107-------------
108
109Detailed API documentation is available through **pydoc**. Samples are available in the **examples** directory.
110
111The package provides two modules, a full client and a helper for simple publishing.
112
113Getting Started
114***************
115
116Here is a very simple example that subscribes to the broker $SYS topic tree and prints out the resulting messages:
117
118.. code:: python
119
120    import paho.mqtt.client as mqtt
121
122    # The callback for when the client receives a CONNACK response from the server.
123    def on_connect(client, userdata, flags, rc):
124        print("Connected with result code "+str(rc))
125
126        # Subscribing in on_connect() means that if we lose the connection and
127        # reconnect then subscriptions will be renewed.
128        client.subscribe("$SYS/#")
129
130    # The callback for when a PUBLISH message is received from the server.
131    def on_message(client, userdata, msg):
132        print(msg.topic+" "+str(msg.payload))
133
134    client = mqtt.Client()
135    client.on_connect = on_connect
136    client.on_message = on_message
137
138    client.connect("mqtt.eclipse.org", 1883, 60)
139
140    # Blocking call that processes network traffic, dispatches callbacks and
141    # handles reconnecting.
142    # Other loop*() functions are available that give a threaded interface and a
143    # manual interface.
144    client.loop_forever()
145
146Client
147******
148
149You can use the client class as an instance, within a class or by subclassing. The general usage flow is as follows:
150
151* Create a client instance
152* Connect to a broker using one of the ``connect*()`` functions
153* Call one of the ``loop*()`` functions to maintain network traffic flow with the broker
154* Use ``subscribe()`` to subscribe to a topic and receive messages
155* Use ``publish()`` to publish messages to the broker
156* Use ``disconnect()`` to disconnect from the broker
157
158Callbacks will be called to allow the application to process events as necessary. These callbacks are described below.
159
160Constructor / reinitialise
161``````````````````````````
162
163Client()
164''''''''
165
166.. code:: python
167
168    Client(client_id="", clean_session=True, userdata=None, protocol=MQTTv311, transport="tcp")
169
170The ``Client()`` constructor takes the following arguments:
171
172client_id
173    the unique client id string used when connecting to the broker. If
174    ``client_id`` is zero length or ``None``, then one will be randomly
175    generated. In this case the ``clean_session`` parameter must be ``True``.
176
177clean_session
178    a boolean that determines the client type. If ``True``, the broker will
179    remove all information about this client when it disconnects. If ``False``,
180    the client is a durable client and subscription information and queued
181    messages will be retained when the client disconnects.
182
183    Note that a client will never discard its own outgoing messages on
184    disconnect. Calling connect() or reconnect() will cause the messages to be
185    resent. Use reinitialise() to reset a client to its original state.
186
187userdata
188    user defined data of any type that is passed as the ``userdata`` parameter
189    to callbacks. It may be updated at a later point with the
190    ``user_data_set()`` function.
191
192protocol
193    the version of the MQTT protocol to use for this client. Can be either
194    ``MQTTv31`` or ``MQTTv311``
195
196transport
197    set to "websockets" to send MQTT over WebSockets. Leave at the default of
198    "tcp" to use raw TCP.
199
200
201Constructor Example
202...................
203
204.. code:: python
205
206    import paho.mqtt.client as mqtt
207
208    mqttc = mqtt.Client()
209
210
211reinitialise()
212''''''''''''''
213
214.. code:: python
215
216    reinitialise(client_id="", clean_session=True, userdata=None)
217
218The ``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.
219
220Reinitialise Example
221....................
222
223.. code:: python
224
225    mqttc.reinitialise()
226
227Option functions
228````````````````
229
230These 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.
231
232max_inflight_messages_set()
233'''''''''''''''''''''''''''
234
235.. code:: python
236
237    max_inflight_messages_set(self, inflight)
238
239Set the maximum number of messages with QoS>0 that can be part way through their network flow at once.
240
241Defaults to 20. Increasing this value will consume more memory but can increase throughput.
242
243max_queued_messages_set()
244'''''''''''''''''''''''''
245
246.. code:: python
247
248    max_queued_messages_set(self, queue_size)
249
250Set the maximum number of outgoing messages with QoS>0 that can be pending in the outgoing message queue.
251
252Defaults to 0. 0 means unlimited. When the queue is full, any further outgoing messages would be dropped.
253
254message_retry_set()
255'''''''''''''''''''
256
257.. code:: python
258
259    message_retry_set(retry)
260
261Set the time in seconds before a message with QoS>0 is retried, if the broker does not respond.
262
263This is set to 5 seconds by default and should not normally need changing.
264
265ws_set_options()
266''''''''''''''''
267
268.. code:: python
269
270    ws_set_options(self, path="/mqtt", headers=None)
271
272Set websocket connection options. These options will only be used if ``transport="websockets"`` was passed into the ``Client()`` constructor.
273
274path
275    The mqtt path to use on the broker.
276
277headers
278    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.
279
280Must be called before ``connect*()``. An example of how this can be used with the AWS IoT platform is in the **examples** folder.
281
282
283tls_set()
284'''''''''
285
286.. code:: python
287
288    tls_set(ca_certs=None, certfile=None, keyfile=None, cert_reqs=ssl.CERT_REQUIRED,
289        tls_version=ssl.PROTOCOL_TLS, ciphers=None)
290
291Configure network encryption and authentication options. Enables SSL/TLS support.
292
293ca_certs
294    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.
295
296certfile, keyfile
297    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.
298
299cert_reqs
300    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.
301
302tls_version
303    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.
304
305ciphers
306    a string specifying which encryption ciphers are allowable for this connection, or ``None`` to use the defaults. See the ssl pydoc for more information.
307
308Must be called before ``connect*()``.
309
310tls_set_context()
311'''''''''''''''''
312
313.. code:: python
314
315    tls_set_context(context=None)
316
317Configure network encryption and authentication context. Enables SSL/TLS support.
318
319context
320    an ssl.SSLContext object. By default, this is given by ``ssl.create_default_context()``, if available (added in Python 3.4).
321
322If 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.
323
324Must be called before ``connect*()``.
325
326tls_insecure_set()
327''''''''''''''''''
328
329.. code:: python
330
331    tls_insecure_set(value)
332
333Configure verification of the server hostname in the server certificate.
334
335If ``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.
336
337Do not use this function in a real system. Setting value to True means there is no point using encryption.
338
339Must be called before ``connect*()`` and after ``tls_set()`` or ``tls_set_context()``.
340
341enable_logger()
342'''''''''''''''
343
344.. code:: python
345
346    enable_logger(logger=None)
347
348Enable logging using the standard python logging package (See PEP 282). This may be used at the same time as the ``on_log`` callback method.
349
350If ``logger`` is specified, then that ``logging.Logger`` object will be used, otherwise one will be created automatically.
351
352Paho logging levels are converted to standard ones according to the following mapping:
353
354====================  ===============
355Paho                  logging
356====================  ===============
357``MQTT_LOG_ERR``      ``logging.ERROR``
358``MQTT_LOG_WARNING``  ``logging.WARNING``
359``MQTT_LOG_NOTICE``   ``logging.INFO`` *(no direct equivalent)*
360``MQTT_LOG_INFO``     ``logging.INFO``
361``MQTT_LOG_DEBUG``    ``logging.DEBUG``
362====================  ===============
363
364disable_logger()
365''''''''''''''''
366
367.. code:: python
368
369    disable_logger()
370
371Disable logging using standard python logging package. This has no effect on the ``on_log`` callback.
372
373username_pw_set()
374'''''''''''''''''
375
376.. code:: python
377
378    username_pw_set(username, password=None)
379
380Set a username and optionally a password for broker authentication. Must be called before ``connect*()``.
381
382user_data_set()
383'''''''''''''''
384
385.. code:: python
386
387    user_data_set(userdata)
388
389Set the private user data that will be passed to callbacks when events are generated. Use this for your own purpose to support your application.
390
391will_set()
392''''''''''
393
394.. code:: python
395
396    will_set(topic, payload=None, qos=0, retain=False)
397
398Set a Will to be sent to the broker. If the client disconnects without calling
399``disconnect()``, the broker will publish the message on its behalf.
400
401topic
402    the topic that the will message should be published on.
403
404payload
405    the message to send as a will. If not given, or set to ``None`` a zero
406    length message will be used as the will. Passing an int or float will
407    result in the payload being converted to a string representing that number.
408    If you wish to send a true int/float, use ``struct.pack()`` to create the
409    payload you require.
410
411qos
412    the quality of service level to use for the will.
413
414retain
415    if set to ``True``, the will message will be set as the "last known
416    good"/retained message for the topic.
417
418Raises a ``ValueError`` if ``qos`` is not 0, 1 or 2, or if ``topic`` is
419``None`` or has zero string length.
420
421reconnect_delay_set
422'''''''''''''''''''
423
424.. code:: python
425
426    reconnect_delay_set(min_delay=1, max_delay=120)
427
428The client will automatically retry connection. Between each attempt
429it will wait a number of seconds between ``min_delay`` and ``max_delay``.
430
431When the connection is lost, initially the reconnection attempt is delayed of
432``min_delay`` seconds. It's doubled between subsequent attempt up to ``max_delay``.
433
434The delay is reset to ``min_delay`` when the connection complete (e.g. the CONNACK is
435received, not just the TCP connection is established).
436
437
438Connect / reconnect / disconnect
439````````````````````````````````
440
441connect()
442'''''''''
443
444.. code:: python
445
446    connect(host, port=1883, keepalive=60, bind_address="")
447
448The ``connect()`` function connects the client to a broker. This is a blocking
449function. It takes the following arguments:
450
451host
452    the hostname or IP address of the remote broker
453
454port
455    the network port of the server host to connect to. Defaults to 1883. Note
456    that the default port for MQTT over SSL/TLS is 8883 so if you are using
457    ``tls_set()`` or ``tls_set_context()``, the port may need providing manually
458
459keepalive
460    maximum period in seconds allowed between communications with the broker.
461    If no other messages are being exchanged, this controls the rate at which
462    the client will send ping messages to the broker
463
464bind_address
465    the IP address of a local network interface to bind this client to,
466    assuming multiple interfaces exist
467
468Callback
469........
470
471When the client receives a CONNACK message from the broker in response to the
472connect it generates an ``on_connect()`` callback.
473
474Connect Example
475...............
476
477.. code:: python
478
479    mqttc.connect("mqtt.eclipse.org")
480
481connect_async()
482'''''''''''''''
483
484.. code:: python
485
486    connect_async(host, port=1883, keepalive=60, bind_address="")
487
488Use in conjunction with ``loop_start()`` to connect in a non-blocking manner.
489The connection will not complete until ``loop_start()`` is called.
490
491Callback (connect)
492..................
493
494When the client receives a CONNACK message from the broker in response to the
495connect it generates an ``on_connect()`` callback.
496
497connect_srv()
498'''''''''''''
499
500.. code:: python
501
502    connect_srv(domain, keepalive=60, bind_address="")
503
504Connect to a broker using an SRV DNS lookup to obtain the broker address. Takes
505the following arguments:
506
507domain
508    the DNS domain to search for SRV records. If ``None``, try to determine the
509    local domain name.
510
511See ``connect()`` for a description of the ``keepalive`` and ``bind_address``
512arguments.
513
514Callback (connect_srv)
515......................
516
517When the client receives a CONNACK message from the broker in response to the
518connect it generates an ``on_connect()`` callback.
519
520SRV Connect Example
521...................
522
523.. code:: python
524
525    mqttc.connect_srv("eclipse.org")
526
527reconnect()
528'''''''''''
529
530.. code:: python
531
532    reconnect()
533
534Reconnect to a broker using the previously provided details. You must have
535called ``connect*()`` before calling this function.
536
537Callback (reconnect)
538....................
539
540When the client receives a CONNACK message from the broker in response to the
541connect it generates an ``on_connect()`` callback.
542
543disconnect()
544''''''''''''
545
546.. code:: python
547
548    disconnect()
549
550Disconnect from the broker cleanly. Using ``disconnect()`` will not result in a
551will message being sent by the broker.
552
553Disconnect will not wait for all queued message to be sent, to ensure all messages
554are delivered, ``wait_for_publish()`` from ``MQTTMessageInfo`` should be used.
555See ``publish()`` for details.
556
557Callback (disconnect)
558.....................
559
560When the client has sent the disconnect message it generates an
561``on_disconnect()`` callback.
562
563Network loop
564````````````
565
566These functions are the driving force behind the client. If they are not
567called, incoming network data will not be processed and outgoing network data
568may not be sent in a timely fashion. There are four options for managing the
569network loop. Three are described here, the fourth in "External event loop
570support" below. Do not mix the different loop functions.
571
572loop()
573''''''
574
575.. code:: python
576
577    loop(timeout=1.0, max_packets=1)
578
579Call regularly to process network events. This call waits in ``select()`` until
580the network socket is available for reading or writing, if appropriate, then
581handles the incoming/outgoing data. This function blocks for up to ``timeout``
582seconds. ``timeout`` must not exceed the ``keepalive`` value for the client or
583your client will be regularly disconnected by the broker.
584
585The ``max_packets`` argument is obsolete and should be left unset.
586
587Loop Example
588............
589
590.. code:: python
591
592    run = True
593    while run:
594        mqttc.loop()
595
596loop_start() / loop_stop()
597''''''''''''''''''''''''''
598
599.. code:: python
600
601    loop_start()
602    loop_stop(force=False)
603
604These functions implement a threaded interface to the network loop. Calling
605``loop_start()`` once, before or after ``connect*()``, runs a thread in the
606background to call ``loop()`` automatically. This frees up the main thread for
607other work that may be blocking. This call also handles reconnecting to the
608broker. Call ``loop_stop()`` to stop the background thread. The ``force``
609argument is currently ignored.
610
611Loop Start/Stop Example
612.......................
613
614.. code:: python
615
616    mqttc.connect("mqtt.eclipse.org")
617    mqttc.loop_start()
618
619    while True:
620        temperature = sensor.blocking_read()
621        mqttc.publish("paho/temperature", temperature)
622
623loop_forever()
624''''''''''''''
625
626.. code:: python
627
628    loop_forever(timeout=1.0, max_packets=1, retry_first_connection=False)
629
630This is a blocking form of the network loop and will not return until the
631client calls ``disconnect()``. It automatically handles reconnecting.
632
633Except for the first connection attempt when using connect_async, use
634``retry_first_connection=True`` to make it retry the first connection.
635Warning: This might lead to situations where the client keeps connecting to an
636non existing host without failing.
637
638The ``timeout`` and ``max_packets`` arguments are obsolete and should be left
639unset.
640
641Publishing
642``````````
643
644Send a message from the client to the broker.
645
646publish()
647'''''''''
648
649.. code:: python
650
651    publish(topic, payload=None, qos=0, retain=False)
652
653This causes a message to be sent to the broker and subsequently from the broker
654to any clients subscribing to matching topics. It takes the following
655arguments:
656
657topic
658    the topic that the message should be published on
659
660payload
661    the actual message to send. If not given, or set to ``None`` a zero length
662    message will be used. Passing an int or float will result in the payload
663    being converted to a string representing that number. If you wish to send a
664    true int/float, use ``struct.pack()`` to create the payload you require
665
666qos
667    the quality of service level to use
668
669retain
670    if set to ``True``, the message will be set as the "last known
671    good"/retained message for the topic.
672
673Returns a MQTTMessageInfo which expose the following attributes and methods:
674
675* ``rc``, the result of the publishing. It could be ``MQTT_ERR_SUCCESS`` to
676  indicate success, ``MQTT_ERR_NO_CONN`` if the client is not currently connected,
677  or ``MQTT_ERR_QUEUE_SIZE`` when ``max_queued_messages_set`` is used to indicate
678  that message is neither queued nor sent.
679* ``mid`` is the message ID for the publish request. The mid value can be used to
680  track the publish request by checking against the mid argument in the
681  ``on_publish()`` callback if it is defined. ``wait_for_publish`` may be easier
682  depending on your use-case.
683* ``wait_for_publish()`` will block until the message is published. It will
684  raise ValueError if the message is not queued (rc == ``MQTT_ERR_QUEUE_SIZE``).
685* ``is_published`` returns True if the message has been published. It will
686  raise ValueError if the message is not queued (rc == ``MQTT_ERR_QUEUE_SIZE``).
687
688A ``ValueError`` will be raised if topic is ``None``, has zero length or is
689invalid (contains a wildcard), if ``qos`` is not one of 0, 1 or 2, or if the
690length of the payload is greater than 268435455 bytes.
691
692Callback (publish)
693..................
694
695When the message has been sent to the broker an ``on_publish()`` callback will
696be generated.
697
698
699Subscribe / Unsubscribe
700```````````````````````
701
702subscribe()
703'''''''''''
704
705.. code:: python
706
707    subscribe(topic, qos=0)
708
709Subscribe the client to one or more topics.
710
711This function may be called in three different ways:
712
713Simple string and integer
714.........................
715
716e.g. ``subscribe("my/topic", 2)``
717
718topic
719    a string specifying the subscription topic to subscribe to.
720
721qos
722    the desired quality of service level for the subscription. Defaults to 0.
723
724String and integer tuple
725........................
726
727e.g. ``subscribe(("my/topic", 1))``
728
729topic
730    a tuple of ``(topic, qos)``. Both topic and qos must be present in the tuple.
731
732qos
733    not used.
734
735List of string and integer tuples
736.................................
737
738e.g. ``subscribe([("my/topic", 0), ("another/topic", 2)])``
739
740This allows multiple topic subscriptions in a single SUBSCRIPTION command,
741which is more efficient than using multiple calls to ``subscribe()``.
742
743topic
744    a list of tuple of format ``(topic, qos)``. Both topic and qos must be
745    present in all of the tuples.
746
747qos
748    not used.
749
750The function returns a tuple ``(result, mid)``, where ``result`` is
751``MQTT_ERR_SUCCESS`` to indicate success or ``(MQTT_ERR_NO_CONN, None)`` if the
752client is not currently connected.  ``mid`` is the message ID for the subscribe
753request. The mid value can be used to track the subscribe request by checking
754against the mid argument in the ``on_subscribe()`` callback if it is defined.
755
756Raises a ``ValueError`` if ``qos`` is not 0, 1 or 2, or if topic is ``None`` or
757has zero string length, or if ``topic`` is not a string, tuple or list.
758
759Callback (subscribe)
760....................
761
762When the broker has acknowledged the subscription, an ``on_subscribe()``
763callback will be generated.
764
765unsubscribe()
766'''''''''''''
767
768.. code:: python
769
770    unsubscribe(topic)
771
772Unsubscribe the client from one or more topics.
773
774topic
775    a single string, or list of strings that are the subscription topics to
776    unsubscribe from.
777
778Returns a tuple ``(result, mid)``, where ``result`` is ``MQTT_ERR_SUCCESS`` to
779indicate success, or ``(MQTT_ERR_NO_CONN, None)`` if the client is not
780currently connected. ``mid`` is the message ID for the unsubscribe request. The
781mid value can be used to track the unsubscribe request by checking against the
782mid argument in the ``on_unsubscribe()`` callback if it is defined.
783
784Raises a ``ValueError`` if ``topic`` is ``None`` or has zero string length, or
785is not a string or list.
786
787Callback (unsubscribe)
788......................
789
790When the broker has acknowledged the unsubscribe, an ``on_unsubscribe()``
791callback will be generated.
792
793Callbacks
794`````````
795
796on_connect()
797''''''''''''
798
799.. code:: python
800
801    on_connect(client, userdata, flags, rc)
802
803Called when the broker responds to our connection request.
804
805client
806    the client instance for this callback
807
808userdata
809    the private user data as set in ``Client()`` or ``user_data_set()``
810
811flags
812    response flags sent by the broker
813rc
814    the connection result
815
816
817flags is a dict that contains response flags from the broker:
818    flags['session present'] - this flag is useful for clients that are
819        using clean session set to 0 only. If a client with clean
820        session=0, that reconnects to a broker that it has previously
821        connected to, this flag indicates whether the broker still has the
822        session information for the client. If 1, the session still exists.
823
824The value of rc indicates success or not:
825
826    0: Connection successful
827    1: Connection refused - incorrect protocol version
828    2: Connection refused - invalid client identifier
829    3: Connection refused - server unavailable
830    4: Connection refused - bad username or password
831    5: Connection refused - not authorised
832    6-255: Currently unused.
833
834On Connect Example
835..................
836
837.. code:: python
838
839    def on_connect(client, userdata, flags, rc):
840        print("Connection returned result: "+connack_string(rc))
841
842    mqttc.on_connect = on_connect
843    ...
844
845on_disconnect()
846'''''''''''''''
847
848.. code:: python
849
850    on_disconnect(client, userdata, rc)
851
852Called when the client disconnects from the broker.
853
854client
855    the client instance for this callback
856
857userdata
858    the private user data as set in ``Client()`` or ``user_data_set()``
859
860rc
861    the disconnection result
862
863The rc parameter indicates the disconnection state. If ``MQTT_ERR_SUCCESS``
864(0), the callback was called in response to a ``disconnect()`` call. If any
865other value the disconnection was unexpected, such as might be caused by a
866network error.
867
868On Disconnect Example
869.....................
870
871.. code:: python
872
873    def on_disconnect(client, userdata, rc):
874        if rc != 0:
875            print("Unexpected disconnection.")
876
877    mqttc.on_disconnect = on_disconnect
878    ...
879
880on_message()
881''''''''''''
882
883.. code:: python
884
885    on_message(client, userdata, message)
886
887Called when a message has been received on a topic that the client subscribes
888to and the message does not match an existing topic filter callback.
889Use ``message_callback_add()`` to define a callback that will be called for
890specific topic filters. ``on_message`` will serve as fallback when none matched.
891
892client
893    the client instance for this callback
894
895userdata
896    the private user data as set in ``Client()`` or ``user_data_set()``
897
898message
899    an instance of MQTTMessage. This is a class with members ``topic``, ``payload``, ``qos``, ``retain``.
900
901On Message Example
902..................
903
904.. code:: python
905
906    def on_message(client, userdata, message):
907        print("Received message '" + str(message.payload) + "' on topic '"
908            + message.topic + "' with QoS " + str(message.qos))
909
910    mqttc.on_message = on_message
911    ...
912
913message_callback_add()
914''''''''''''''''''''''
915
916This function allows you to define callbacks that handle incoming messages for
917specific subscription filters, including with wildcards. This lets you, for
918example, subscribe to ``sensors/#`` and have one callback to handle
919``sensors/temperature`` and another to handle ``sensors/humidity``.
920
921.. code:: python
922
923    message_callback_add(sub, callback)
924
925sub
926    the subscription filter to match against for this callback. Only one
927    callback may be defined per literal sub string
928
929callback
930    the callback to be used. Takes the same form as the ``on_message``
931    callback.
932
933If using ``message_callback_add()`` and ``on_message``, only messages that do
934not match a subscription specific filter will be passed to the ``on_message``
935callback.
936
937If multiple sub match a topic, each callback will be called (e.g. sub ``sensors/#``
938and sub ``+/humidity`` both match a message with a topic ``sensors/humidity``, so both
939callbacks will handle this message).
940
941message_callback_remove()
942'''''''''''''''''''''''''
943
944Remove a topic/subscription specific callback previously registered using
945``message_callback_add()``.
946
947.. code:: python
948
949    message_callback_remove(sub)
950
951sub
952    the subscription filter to remove
953
954on_publish()
955''''''''''''
956
957.. code:: python
958
959    on_publish(client, userdata, mid)
960
961Called when a message that was to be sent using the ``publish()`` call has
962completed transmission to the broker. For messages with QoS levels 1 and 2,
963this means that the appropriate handshakes have completed. For QoS 0, this
964simply means that the message has left the client. The ``mid`` variable matches
965the mid variable returned from the corresponding ``publish()`` call, to allow
966outgoing messages to be tracked.
967
968This callback is important because even if the publish() call returns success,
969it does not always mean that the message has been sent.
970
971on_subscribe()
972''''''''''''''
973
974.. code:: python
975
976    on_subscribe(client, userdata, mid, granted_qos)
977
978Called when the broker responds to a subscribe request. The ``mid`` variable
979matches the mid variable returned from the corresponding ``subscribe()`` call.
980The ``granted_qos`` variable is a list of integers that give the QoS level the
981broker has granted for each of the different subscription requests.
982
983on_unsubscribe()
984''''''''''''''''
985
986.. code:: python
987
988    on_unsubscribe(client, userdata, mid)
989
990Called when the broker responds to an unsubscribe request. The ``mid`` variable
991matches the mid variable returned from the corresponding ``unsubscribe()``
992call.
993
994on_log()
995''''''''
996
997.. code:: python
998
999    on_log(client, userdata, level, buf)
1000
1001Called when the client has log information. Define to allow debugging. The
1002``level`` variable gives the severity of the message and will be one of
1003``MQTT_LOG_INFO``, ``MQTT_LOG_NOTICE``, ``MQTT_LOG_WARNING``, ``MQTT_LOG_ERR``,
1004and ``MQTT_LOG_DEBUG``. The message itself is in ``buf``.
1005
1006This may be used at the same time as the standard Python logging, which can be
1007enabled via the ``enable_logger`` method.
1008
1009on_socket_open()
1010''''''''''''''''
1011
1012::
1013
1014    on_socket_open(client, userdata, sock)
1015
1016Called when the socket has been opened.
1017Use this to register the socket with an external event loop for reading.
1018
1019on_socket_close()
1020'''''''''''''''''
1021
1022::
1023
1024    on_socket_close(client, userdata, sock)
1025
1026Called when the socket is about to be closed.
1027Use this to unregister a socket from an external event loop for reading.
1028
1029on_socket_register_write()
1030''''''''''''''''''''''''''
1031
1032::
1033
1034    on_socket_register_write(client, userdata, sock)
1035
1036Called when a write operation to the socket failed because it would have blocked, e.g. output buffer full.
1037Use this to register the socket with an external event loop for writing.
1038
1039on_socket_unregister_write()
1040''''''''''''''''''''''''''''
1041
1042::
1043
1044    on_socket_unregister_write(client, userdata, sock)
1045
1046Called when a write operation to the socket succeeded after it had previously failed.
1047Use this to unregister the socket from an external event loop for writing.
1048
1049External event loop support
1050```````````````````````````
1051
1052loop_read()
1053'''''''''''
1054
1055.. code:: python
1056
1057    loop_read(max_packets=1)
1058
1059Call when the socket is ready for reading. ``max_packets`` is obsolete and
1060should be left unset.
1061
1062loop_write()
1063''''''''''''
1064
1065.. code:: python
1066
1067    loop_write(max_packets=1)
1068
1069Call when the socket is ready for writing. ``max_packets`` is obsolete and
1070should be left unset.
1071
1072loop_misc()
1073'''''''''''
1074
1075.. code:: python
1076
1077    loop_misc()
1078
1079Call every few seconds to handle message retrying and pings.
1080
1081socket()
1082''''''''
1083
1084.. code:: python
1085
1086    socket()
1087
1088Returns the socket object in use in the client to allow interfacing with other
1089event loops.
1090This call is particularly useful for select_ based loops. See ``examples/loop_select.py``.
1091
1092.. _select: https://docs.python.org/3/library/select.html#select.select
1093
1094want_write()
1095''''''''''''
1096
1097.. code:: python
1098
1099    want_write()
1100
1101Returns true if there is data waiting to be written, to allow interfacing the
1102client with other event loops.
1103This call is particularly useful for select_ based loops. See ``examples/loop_select.py``.
1104
1105.. _select: https://docs.python.org/3/library/select.html#select.select
1106
1107state callbacks
1108'''''''''''''''
1109
1110::
1111
1112    on_socket_open
1113    on_socket_close
1114    on_socket_register_write
1115    on_socket_unregister_write
1116
1117Use these callbacks to get notified about state changes in the socket.
1118This is particularly useful for event loops where you register or unregister a socket
1119for reading+writing. See ``examples/loop_asyncio.py`` for an example.
1120
1121When the socket is opened, ``on_socket_open`` is called.
1122Register the socket with your event loop for reading.
1123
1124When the socket is about to be closed, ``on_socket_close`` is called.
1125Unregister the socket from your event loop for reading.
1126
1127When a write to the socket failed because it would have blocked, e.g. output buffer full,
1128``on_socket_register_write`` is called.
1129Register the socket with your event loop for writing.
1130
1131When the next write to the socket succeeded, ``on_socket_unregister_write`` is called.
1132Unregister the socket from your event loop for writing.
1133
1134The callbacks are always called in this order:
1135
1136- ``on_socket_open``
1137- Zero or more times:
1138
1139  - ``on_socket_register_write``
1140  - ``on_socket_unregister_write``
1141
1142- ``on_socket_close``
1143
1144Global helper functions
1145```````````````````````
1146
1147The client module also offers some global helper functions.
1148
1149``topic_matches_sub(sub, topic)`` can be used to check whether a ``topic``
1150matches a ``subscription``.
1151
1152For example:
1153
1154    the topic ``foo/bar`` would match the subscription ``foo/#`` or ``+/bar``
1155
1156    the topic ``non/matching`` would not match the subscription ``non/+/+``
1157
1158
1159``connack_string(connack_code)`` returns the error string associated with a
1160CONNACK result.
1161
1162
1163``error_string(mqtt_errno)`` returns the error string associated with a Paho
1164MQTT error number.
1165
1166Publish
1167*******
1168
1169This module provides some helper functions to allow straightforward publishing
1170of messages in a one-shot manner. In other words, they are useful for the
1171situation where you have a single/multiple messages you want to publish to a
1172broker, then disconnect with nothing else required.
1173
1174The two functions provided are ``single()`` and ``multiple()``.
1175
1176Single
1177``````
1178
1179Publish a single message to a broker, then disconnect cleanly.
1180
1181.. code:: python
1182
1183    single(topic, payload=None, qos=0, retain=False, hostname="localhost",
1184        port=1883, client_id="", keepalive=60, will=None, auth=None, tls=None,
1185        protocol=mqtt.MQTTv311, transport="tcp")
1186
1187
1188Publish Single Function arguments
1189'''''''''''''''''''''''''''''''''
1190
1191topic
1192    the only required argument must be the topic string to which the payload
1193    will be published.
1194
1195payload
1196    the payload to be published. If "" or None, a zero length payload will be
1197    published.
1198
1199qos
1200    the qos to use when publishing,  default to 0.
1201
1202retain
1203    set the message to be retained (True) or not (False).
1204
1205hostname
1206    a string containing the address of the broker to connect to. Defaults to
1207    localhost.
1208
1209port
1210    the port to connect to the broker on. Defaults to 1883.
1211
1212client_id
1213    the MQTT client id to use. If "" or None, the Paho library will
1214    generate a client id automatically.
1215
1216keepalive
1217    the keepalive timeout value for the client. Defaults to 60 seconds.
1218
1219will
1220    a dict containing will parameters for the client:
1221
1222    will = {'topic': "<topic>", 'payload':"<payload">, 'qos':<qos>, 'retain':<retain>}.
1223
1224    Topic is required, all other parameters are optional and will default to
1225    None, 0 and False respectively.
1226
1227    Defaults to None, which indicates no will should be used.
1228
1229auth
1230    a dict containing authentication parameters for the client:
1231
1232    auth = {'username':"<username>", 'password':"<password>"}
1233
1234    Username is required, password is optional and will default to None if not provided.
1235
1236    Defaults to None, which indicates no authentication is to be used.
1237
1238tls
1239    a dict containing TLS configuration parameters for the client:
1240
1241    dict = {'ca_certs':"<ca_certs>", 'certfile':"<certfile>", 'keyfile':"<keyfile>", 'tls_version':"<tls_version>", 'ciphers':"<ciphers">}
1242
1243    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.
1244
1245    Defaults to None, which indicates that TLS should not be used.
1246
1247protocol
1248    choose the version of the MQTT protocol to use. Use either ``MQTTv31`` or ``MQTTv311``.
1249
1250transport
1251    set to "websockets" to send MQTT over WebSockets. Leave at the default of
1252    "tcp" to use raw TCP.
1253
1254Publish Single Example
1255''''''''''''''''''''''
1256
1257.. code:: python
1258
1259    import paho.mqtt.publish as publish
1260
1261    publish.single("paho/test/single", "payload", hostname="mqtt.eclipse.org")
1262
1263Multiple
1264````````
1265
1266Publish multiple messages to a broker, then disconnect cleanly.
1267
1268.. code:: python
1269
1270    multiple(msgs, hostname="localhost", port=1883, client_id="", keepalive=60,
1271        will=None, auth=None, tls=None, protocol=mqtt.MQTTv311, transport="tcp")
1272
1273Publish Multiple Function arguments
1274'''''''''''''''''''''''''''''''''''
1275
1276msgs
1277    a list of messages to publish. Each message is either a dict or a tuple.
1278
1279    If a dict, only the topic must be present. Default values will be
1280    used for any missing arguments. The dict must be of the form:
1281
1282    msg = {'topic':"<topic>", 'payload':"<payload>", 'qos':<qos>, 'retain':<retain>}
1283
1284    topic must be present and may not be empty.
1285    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.
1286
1287    If a tuple, then it must be of the form:
1288
1289    ("<topic>", "<payload>", qos, retain)
1290
1291See ``single()`` for the description of ``hostname``, ``port``, ``client_id``, ``keepalive``, ``will``, ``auth``, ``tls``, ``protocol``, ``transport``.
1292
1293Publish Multiple Example
1294''''''''''''''''''''''''
1295
1296.. code:: python
1297
1298    import paho.mqtt.publish as publish
1299
1300    msgs = [{'topic':"paho/test/multiple", 'payload':"multiple 1"},
1301        ("paho/test/multiple", "multiple 2", 0, False)]
1302    publish.multiple(msgs, hostname="mqtt.eclipse.org")
1303
1304
1305Subscribe
1306*********
1307
1308This module provides some helper functions to allow straightforward subscribing
1309and processing of messages.
1310
1311The two functions provided are ``simple()`` and ``callback()``.
1312
1313Simple
1314``````
1315
1316Subscribe to a set of topics and return the messages received. This is a
1317blocking function.
1318
1319.. code:: python
1320
1321    simple(topics, qos=0, msg_count=1, retained=False, hostname="localhost",
1322        port=1883, client_id="", keepalive=60, will=None, auth=None, tls=None,
1323        protocol=mqtt.MQTTv311)
1324
1325
1326Simple Subscribe Function arguments
1327'''''''''''''''''''''''''''''''''''
1328
1329topics
1330    the only required argument is the topic string to which the client will
1331    subscribe. This can either be a string or a list of strings if multiple
1332    topics should be subscribed to.
1333
1334qos
1335    the qos to use when subscribing, defaults to 0.
1336
1337msg_count
1338    the number of messages to retrieve from the broker. Defaults to 1. If 1, a
1339    single MQTTMessage object will be returned. If >1, a list of MQTTMessages
1340    will be returned.
1341
1342retained
1343    set to True to consider retained messages, set to False to ignore messages
1344    with the retained flag set.
1345
1346hostname
1347    a string containing the address of the broker to connect to. Defaults to localhost.
1348
1349port
1350    the port to connect to the broker on. Defaults to 1883.
1351
1352client_id
1353    the MQTT client id to use. If "" or None, the Paho library will
1354    generate a client id automatically.
1355
1356keepalive
1357    the keepalive timeout value for the client. Defaults to 60 seconds.
1358
1359will
1360    a dict containing will parameters for the client:
1361
1362    will = {'topic': "<topic>", 'payload':"<payload">, 'qos':<qos>, 'retain':<retain>}.
1363
1364    Topic is required, all other parameters are optional and will default to
1365    None, 0 and False respectively.
1366
1367    Defaults to None, which indicates no will should be used.
1368
1369auth
1370    a dict containing authentication parameters for the client:
1371
1372    auth = {'username':"<username>", 'password':"<password>"}
1373
1374    Username is required, password is optional and will default to None if not
1375    provided.
1376
1377    Defaults to None, which indicates no authentication is to be used.
1378
1379tls
1380    a dict containing TLS configuration parameters for the client:
1381
1382    dict = {'ca_certs':"<ca_certs>", 'certfile':"<certfile>", 'keyfile':"<keyfile>", 'tls_version':"<tls_version>", 'ciphers':"<ciphers">}
1383
1384    ca_certs is required, all other parameters are optional and will default to
1385    None if not provided, which results in the client using the default
1386    behaviour - see the paho.mqtt.client documentation.
1387
1388    Defaults to None, which indicates that TLS should not be used.
1389
1390protocol
1391    choose the version of the MQTT protocol to use. Use either ``MQTTv31`` or ``MQTTv311``.
1392
1393
1394Simple Example
1395''''''''''''''
1396
1397.. code:: python
1398
1399    import paho.mqtt.subscribe as subscribe
1400
1401    msg = subscribe.simple("paho/test/simple", hostname="mqtt.eclipse.org")
1402    print("%s %s" % (msg.topic, msg.payload))
1403
1404Using Callback
1405``````````````
1406
1407Subscribe to a set of topics and process the messages received using a user
1408provided callback.
1409
1410.. code:: python
1411
1412    callback(callback, topics, qos=0, userdata=None, hostname="localhost",
1413        port=1883, client_id="", keepalive=60, will=None, auth=None, tls=None,
1414        protocol=mqtt.MQTTv311)
1415
1416Callback Subscribe Function arguments
1417'''''''''''''''''''''''''''''''''''''
1418
1419callback
1420    an "on_message" callback that will be used for each message received, and
1421    of the form
1422
1423    .. code:: python
1424
1425        def on_message(client, userdata, message)
1426
1427topics
1428    the topic string to which the client will subscribe. This can either be a
1429    string or a list of strings if multiple topics should be subscribed to.
1430
1431qos
1432    the qos to use when subscribing, defaults to 0.
1433
1434userdata
1435    a user provided object that will be passed to the on_message callback when
1436    a message is received.
1437
1438See ``simple()`` for the description of ``hostname``, ``port``, ``client_id``, ``keepalive``, ``will``, ``auth``, ``tls``, ``protocol``.
1439
1440Callback Example
1441''''''''''''''''
1442
1443.. code:: python
1444
1445    import paho.mqtt.subscribe as subscribe
1446
1447    def on_message_print(client, userdata, message):
1448        print("%s %s" % (message.topic, message.payload))
1449
1450    subscribe.callback(on_message_print, "paho/test/callback", hostname="mqtt.eclipse.org")
1451
1452
1453Reporting bugs
1454--------------
1455
1456Please report bugs in the issues tracker at https://github.com/eclipse/paho.mqtt.python/issues.
1457
1458More information
1459----------------
1460
1461Discussion of the Paho clients takes place on the `Eclipse paho-dev mailing list <https://dev.eclipse.org/mailman/listinfo/paho-dev>`_.
1462
1463General questions about the MQTT protocol itself (not this library) are discussed in the `MQTT Google Group <https://groups.google.com/forum/?fromgroups#!forum/mqtt>`_.
1464
1465There is much more information available via the `MQTT community site <http://mqtt.org/>`_.
1466