### Install Paho MQTT Python Client Source: https://github.com/eclipse-paho/paho.mqtt.python/blob/master/README.rst Instructions for installing the Eclipse Paho MQTT Python client library using pip, virtualenv, or by cloning the Git repository. Includes steps for setting up the testing environment. ```Shell pip install paho-mqtt ``` ```Shell virtualenv paho-mqtt source paho-mqtt/bin/activate pip install paho-mqtt ``` ```Shell git clone https://github.com/eclipse/paho.mqtt.python ``` ```Shell cd paho.mqtt.python pip install -e . ``` ```Shell git clone https://github.com/eclipse/paho.mqtt.testing.git cd paho.mqtt.testing git checkout a4dc694010217b291ee78ee13a6d1db812f9babd ``` -------------------------------- ### Install Python Release Tools and Project Source: https://github.com/eclipse-paho/paho.mqtt.python/blob/master/CONTRIBUTING.md Installs essential Python packages (build, sphinx, twine) required for packaging, documentation, and distribution, and installs the paho.mqtt.python project itself in editable mode for local development and documentation generation. ```bash pip install build sphinx twine pip install -e . ``` -------------------------------- ### Paho MQTT Python Client Subscriber Example with Callbacks Source: https://github.com/eclipse-paho/paho.mqtt.python/blob/master/README.rst This Python example demonstrates how to create an MQTT subscriber using `paho.mqtt.client`, implementing `on_connect`, `on_message`, `on_subscribe`, and `on_unsubscribe` callbacks to handle connection, message reception, and subscription lifecycle. It subscribes to system topics and processes a limited number of messages. ```python import paho.mqtt.client as mqtt def on_subscribe(client, userdata, mid, reason_code_list, properties): # Since we subscribed only for a single channel, reason_code_list contains # a single entry if reason_code_list[0].is_failure: print(f"Broker rejected you subscription: {reason_code_list[0]}") else: print(f"Broker granted the following QoS: {reason_code_list[0].value}") def on_unsubscribe(client, userdata, mid, reason_code_list, properties): # Be careful, the reason_code_list is only present in MQTTv5. # In MQTTv3 it will always be empty if len(reason_code_list) == 0 or not reason_code_list[0].is_failure: print("unsubscribe succeeded (if SUBACK is received in MQTTv3 it success)") else: print(f"Broker replied with failure: {reason_code_list[0]}") client.disconnect() def on_message(client, userdata, message): # userdata is the structure we choose to provide, here it's a list() userdata.append(message.payload) # We only want to process 10 messages if len(userdata) >= 10: client.unsubscribe("$SYS/#") def on_connect(client, userdata, flags, reason_code, properties): if reason_code.is_failure: print(f"Failed to connect: {reason_code}. loop_forever() will retry connection") else: # we should always subscribe from on_connect callback to be sure # our subscribed is persisted across reconnections. client.subscribe("$SYS/#") mqttc = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2) mqttc.on_connect = on_connect mqttc.on_message = on_message mqttc.on_subscribe = on_subscribe mqttc.on_unsubscribe = on_unsubscribe mqttc.user_data_set([]) mqttc.connect("mqtt.eclipseprojects.io") mqttc.loop_forever() print(f"Received the following message: {mqttc.user_data_get()}") ``` -------------------------------- ### Paho MQTT Python Client Publisher Example with on_publish Callback Source: https://github.com/eclipse-paho/paho.mqtt.python/blob/master/README.rst This Python example illustrates how to publish MQTT messages using `paho.mqtt.client`, specifically demonstrating the `on_publish` callback to track message acknowledgments (PUBACK/PUBCOMP) for QoS 1 messages. It includes a mechanism to manage unacknowledged messages and highlights a potential race condition. ```python import time import paho.mqtt.client as mqtt def on_publish(client, userdata, mid, reason_code, properties): # reason_code and properties will only be present in MQTTv5. It's always unset in MQTTv3 try: userdata.remove(mid) except KeyError: print("on_publish() is called with a mid not present in unacked_publish") print("This is due to an unavoidable race-condition:") print("* publish() return the mid of the message sent.") print("* mid from publish() is added to unacked_publish by the main thread") print("* on_publish() is called by the loop_start thread") print("While unlikely (because on_publish() will be called after a network round-trip),") print(" this is a race-condition that COULD happen") print("") print("The best solution to avoid race-condition is using the msg_info from publish()") print("We could also try using a list of acknowledged mid rather than removing from pending list,") print("but remember that mid could be re-used !") unacked_publish = set() mqttc = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2) mqttc.on_publish = on_publish mqttc.user_data_set(unacked_publish) mqttc.connect("mqtt.eclipseprojects.io") mqttc.loop_start() # Our application produce some messages msg_info = mqttc.publish("paho/test/topic", "my message", qos=1) unacked_publish.add(msg_info.mid) msg_info2 = mqttc.publish("paho/test/topic", "my message2", qos=1) unacked_publish.add(msg_info2.mid) # Wait for all message to be published while len(unacked_publish): time.sleep(0.1) ``` -------------------------------- ### Paho MQTT Python Client Basic Setup and Message Handling Source: https://github.com/eclipse-paho/paho.mqtt.python/blob/master/README.rst This snippet demonstrates the fundamental steps for setting up a Paho MQTT client in Python, including subscribing to a system topic, defining a callback for incoming messages (on_message), assigning callbacks, connecting to a broker, and initiating a blocking network loop (loop_forever). It highlights the use of CallbackAPIVersion.VERSION2. ```python # 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)) mqttc = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2) mqttc.on_connect = on_connect mqttc.on_message = on_message mqttc.connect("mqtt.eclipseprojects.io", 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. mqttc.loop_forever() ``` -------------------------------- ### Connect and Subscribe to MQTT Broker with Paho Python Source: https://github.com/eclipse-paho/paho.mqtt.python/blob/master/README.rst A basic Python example demonstrating how to connect to an MQTT broker using the Paho MQTT client library and subscribe to the $SYS topic tree. It includes a callback function for connection status. ```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, reason_code, properties): print(f"Connected with result code {reason_code}") # Subscribing in on_connect() means that if we lose the connection and ``` -------------------------------- ### New paho-mqtt Callback Signature for Unsubscribe Context Source: https://github.com/eclipse-paho/paho.mqtt.python/blob/master/docs/migrations.rst This snippet presents the new unified callback signature for paho-mqtt, as shown in the source under the `on_unsubscribe` section. Although the function is named `on_subscribe` in the example, it demonstrates the new pattern where `reason_codes` is always a list, even if empty for MQTTv3, and includes `properties`. ```Python # NEW code for both version def on_subscribe(client, userdata, mid, reason_codes, properties): # In NEW version, reason_codes is always a list. Empty for MQTTv3 for unsub_result in reason_codes: # Any reason code >= 128 is a failure. if reason_codes[0] >= 128: # error processing ``` -------------------------------- ### Paho MQTT Python Client Class General Usage Flow Source: https://github.com/eclipse-paho/paho.mqtt.python/blob/master/README.rst This section outlines the typical workflow for interacting with the Paho MQTT Python client, from creating an instance and connecting to a broker, to managing network traffic, subscribing, publishing, and disconnecting. It serves as a high-level guide for client operations. ```APIDOC 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 ``` -------------------------------- ### Publish Multiple MQTT Messages with Paho Python Source: https://github.com/eclipse-paho/paho.mqtt.python/blob/master/README.rst Shows how to publish multiple messages to an MQTT broker in a single operation using `paho.mqtt.publish.multiple`, then disconnect cleanly. This example also demonstrates specifying MQTT Protocol Version 5. ```python from paho.mqtt.enums import MQTTProtocolVersion import paho.mqtt.publish as publish msgs = [{'topic':"paho/test/topic", 'payload':"multiple 1"}, ("paho/test/topic", "multiple 2", 0, False)] publish.multiple(msgs, hostname="mqtt.eclipseprojects.io", protocol=MQTTProtocolVersion.MQTTv5) ``` -------------------------------- ### Git Commit Sign-off Format Example Source: https://github.com/eclipse-paho/paho.mqtt.python/blob/master/CONTRIBUTING.md This snippet illustrates the required format for signing off Git commits. Contributors must include this line at the bottom of their commit messages to comply with the Eclipse Foundation IP policy, ensuring proper attribution and legal compliance for their contributions. ```Git Signed-off-by: John Smith ``` -------------------------------- ### Update Version for Post-Release Development Source: https://github.com/eclipse-paho/paho.mqtt.python/blob/master/CONTRIBUTING.md Modifies the version number in 'paho/mqtt/__init__.py' to the next development iteration (e.g., '1.2.3.dev0') immediately after a release, allowing continued development and installation from git clones without conflicting with the released version. ```python # File: paho/mqtt/__init__.py # Update __version__ to next development number, e.g.: # __version__ = "1.2.3.dev0" ``` -------------------------------- ### Old paho-mqtt on_unsubscribe Callback Signatures Source: https://github.com/eclipse-paho/paho.mqtt.python/blob/master/docs/migrations.rst This snippet shows the older `on_unsubscribe` callback signatures for paho-mqtt, differentiating between MQTTv3 and MQTTv5 versions, which had varying parameter lists for handling unsubscribe results, including error processing examples. ```Python # OLD code for MQTTv3 def on_unsubscribe(client, userdata, mid): # ... # OLD code for MQTTv5 def on_unsubscribe(client, userdata, mid, properties, reason_codes): # In OLD version, reason_codes could be a list or a single ReasonCode object if isinstance(reason_codes, list): for unsub_result in reason_codes: # Any reason code >= 128 is a failure. if reason_codes[0] >= 128: # error processing else: # Any reason code >= 128 is a failure. if reason_codes > 128: # error processing ``` -------------------------------- ### Paho MQTT Python: Enable Default Client Logger Source: https://github.com/eclipse-paho/paho.mqtt.python/blob/master/README.rst This example shows how to enable the default logger for the Paho MQTT client. It configures basic logging to DEBUG level and then initializes the MQTT client with logging enabled, useful for troubleshooting. ```python import logging import paho.mqtt.client as mqtt logging.basicConfig(level=logging.DEBUG) mqttc = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2) mqttc.enable_logger() mqttc.connect("mqtt.eclipseprojects.io", 1883, 60) mqttc.loop_start() # Do additional action needed, publish, subscribe, ... [...] ``` -------------------------------- ### Paho MQTT Python Threaded Network Loop (loop_start/loop_stop) Source: https://github.com/eclipse-paho/paho.mqtt.python/blob/master/README.rst This example illustrates how to use loop_start() to run the MQTT network loop in a background thread, allowing the main thread to perform other tasks like reading sensor data and publishing messages. loop_stop() is used to terminate the background thread. ```python mqttc.loop_start() while True: temperature = sensor.blocking_read() mqttc.publish("paho/temperature", temperature) mqttc.loop_stop() ``` -------------------------------- ### Enforce `tls_insecure_set()` Call Order (Breaking Change) Source: https://github.com/eclipse-paho/paho.mqtt.python/blob/master/ChangeLog.txt The `tls_insecure_set()` method must now be invoked strictly after `tls_set()` to ensure correct TLS configuration. This change enforces a specific order of operations for TLS setup. ```Python client.tls_set(ca_certs="ca.crt", certfile="client.crt", keyfile="client.key") client.tls_insecure_set(True) ``` -------------------------------- ### Paho MQTT Python Manual Network Loop (loop) Source: https://github.com/eclipse-paho/paho.mqtt.python/blob/master/README.rst This example demonstrates the manual loop() function, which requires regular calls to process network events. It blocks for a specified timeout and returns a result code, necessitating manual error handling and reconnection strategies by the application. ```python run = True while run: rc = mqttc.loop(timeout=1.0) if rc != 0: # need to handle error, possible reconnecting or stopping the application ``` -------------------------------- ### Build Project Documentation Locally Source: https://github.com/eclipse-paho/paho.mqtt.python/blob/master/CONTRIBUTING.md Navigates to the 'docs' directory and executes the Sphinx build process to generate the HTML documentation, ensuring it is up-to-date and error-free before a release. ```bash cd docs; make clean html ``` -------------------------------- ### Initialize Paho MQTT Client with Callback API Version Source: https://github.com/eclipse-paho/paho.mqtt.python/blob/master/docs/migrations.rst Demonstrates how to initialize the `mqtt.Client` to opt into `CallbackAPIVersion.VERSION1` to maintain compatibility with older callback signatures in paho-mqtt 2.0. This allows existing code to run without immediate changes to callback functions. ```Python # OLD code >>> mqttc = mqtt.Client() ``` ```Python # NEW code >>> mqttc = mqtt.Client(mqtt.CallbackAPIVersion.VERSION1) ``` -------------------------------- ### Publish Documentation to Project Website Source: https://github.com/eclipse-paho/paho.mqtt.python/blob/master/CONTRIBUTING.md Builds the latest documentation locally and outlines the process to copy the generated HTML files to the designated repository for publishing on the paho.mqtt.python project website. ```bash make clean html ``` -------------------------------- ### Run Project Tests with Tox Source: https://github.com/eclipse-paho/paho.mqtt.python/blob/master/CONTRIBUTING.md This command executes all new and existing tests for the project using 'tox'. Running tests is a crucial step before committing changes to ensure that new code does not introduce regressions and that all functionalities continue to work as expected. ```Shell tox ``` -------------------------------- ### Migrate Paho MQTT `on_connect` Callback to Version 2.0 Source: https://github.com/eclipse-paho/paho.mqtt.python/blob/master/docs/migrations.rst Illustrates the changes required for the `on_connect` callback function when migrating to paho-mqtt 2.0. It shows the old signatures for MQTTv3 and MQTTv5, and the new unified signature for both versions, highlighting the change from `rc` to `reason_code` and the use of `flags.session_present`. ```Python # OLD code for MQTTv3 def on_connect(client, userdata, flags, rc): if flags["session present"] == 1: # ... if rc == 0: # success connect if rc > 0: # error processing ``` ```Python # OLD code for MQTTv5 def on_connect(client, userdata, flags, reason_code, properties): if flags["session present"] == 1: # ... if reason_code == 0: # success connect ``` ```Python # NEW code for both version def on_connect(client, userdata, flags, reason_code, properties): if flags.session_present: # ... if reason_code == 0: # success connect if reason_code > 0: # error processing ``` -------------------------------- ### Upload Distribution Archives to PyPI Source: https://github.com/eclipse-paho/paho.mqtt.python/blob/master/CONTRIBUTING.md Uploads the final, built distribution archives (wheel and sdist) from the 'dist/' directory to the official Python Package Index (PyPI), making the new version publicly available. ```bash python -m twine upload dist/* ``` -------------------------------- ### Paho MQTT Python Client Callback Functions Reference Source: https://github.com/eclipse-paho/paho.mqtt.python/blob/master/README.rst Overview of the callback functions provided by the `paho.mqtt.client` class in the Paho MQTT Python library, detailing their purpose and when they are invoked. This section serves as an API reference for understanding the client's event-driven architecture. ```APIDOC on_connect(): Called when the client connects to the broker. - Parameters: client, userdata, flags, reason_code, properties - Purpose: Handle connection success or failure, typically used for initial subscriptions. on_disconnect(): Called when the connection is closed. - Purpose: Handle disconnections, useful for cleanup or retry logic. on_message(): Called when an MQTT message is received from the broker. - Parameters: client, userdata, message - Purpose: Process incoming MQTT messages. on_publish(): Called when an MQTT message was sent to the broker. - Parameters: client, userdata, mid, reason_code, properties - Invocation: - QoS 0: As soon as message is sent over network. - QoS 1: When PUBACK is received from broker. - QoS 2: When PUBCOMP is received from broker. on_subscribe(): Called when the SUBACK is received from the broker. - Parameters: client, userdata, mid, reason_code_list, properties - Purpose: Confirm subscription success or failure. on_unsubscribe(): Called when the UNSUBACK is received from the broker. - Parameters: client, userdata, mid, reason_code_list, properties - Purpose: Confirm unsubscription. on_log(): Called when the library logs a message. on_socket_open(): Callback for external loop support. on_socket_close(): Callback for external loop support. on_socket_register_write(): Callback for external loop support. on_socket_unregister_write(): Callback for external loop support. ``` -------------------------------- ### Introduce `paho.mqtt.subscribe` Module Source: https://github.com/eclipse-paho/paho.mqtt.python/blob/master/ChangeLog.txt A new `paho.mqtt.subscribe` module has been added, offering helper functions like `simple()` and `callback()` to simplify common MQTT subscription patterns. ```Python import paho.mqtt.subscribe as subscribe import paho.mqtt.client as mqtt # Using simple helper msg = subscribe.simple("test/topic", hostname="localhost") print(f"Received: {msg.payload.decode()}") # Using callback helper def on_message_print(client, userdata, message): print(f"Topic: {message.topic}, Payload: {message.payload.decode()}") subscribe.callback(on_message_print, "test/#", hostname="localhost") ``` -------------------------------- ### Configure Arbitrary WebSocket Headers and Path Source: https://github.com/eclipse-paho/paho.mqtt.python/blob/master/ChangeLog.txt Users can now specify arbitrary HTTP headers and a custom path when establishing WebSocket connections, offering greater control over WebSocket behavior. ```Python client.ws_set_options(path="/mqtt", headers={'User-Agent': 'Paho-Python'}) ``` -------------------------------- ### Configure Paho MQTT Client Module API Documentation Generation Source: https://github.com/eclipse-paho/paho.mqtt.python/blob/master/docs/client.rst This reStructuredText directive configures the Sphinx `automodule` extension to generate API documentation for the `paho.mqtt.client` module. It explicitly includes all public members but excludes a specific list of callback methods from the generated documentation, while also including undocumented members. ```reStructuredText .. automodule:: paho.mqtt.client :members: :exclude-members: connect_callback, connect_fail_callback, disconnect_callback, log_callback, message_callback, topic_callback, pre_connect_callback, publish_callback, socket_close_callback, socket_open_callback, socket_register_write_callback, socket_unregister_write_callback, subscribe_callback, unsubscribe_callback :undoc-members: ``` -------------------------------- ### Perform Dry-Run Build and TestPyPI Upload Source: https://github.com/eclipse-paho/paho.mqtt.python/blob/master/CONTRIBUTING.md Executes a dry-run of the release build process, including building distribution archives, checking them for common errors using 'twine check', and attempting an upload to TestPyPI to verify the entire distribution workflow without affecting the production index. ```bash python -m build . python -m twine check dist/* python3 -m twine upload --repository testpypi dist/* ``` -------------------------------- ### Paho MQTT Python: Global Helper Functions Source: https://github.com/eclipse-paho/paho.mqtt.python/blob/master/README.rst This section documents global helper functions available in the Paho MQTT client module. These functions provide utility for common MQTT-related tasks, such as checking topic matches against subscriptions. ```APIDOC Global Helper Functions: - topic_matches_sub(sub: str, topic: str): Checks whether a 'topic' matches a 'subscription'. Example: - The topic 'foo/bar' would match the subscription 'foo/#' or '+/bar'. - The topic 'non/matching' would not match the subscription 'non/+/+'. ``` -------------------------------- ### Paho MQTT Python: One-Shot Publish Helper Functions Source: https://github.com/eclipse-paho/paho.mqtt.python/blob/master/README.rst This section introduces helper functions for straightforward, one-shot message publishing. These functions are designed for scenarios where single or multiple messages need to be published to a broker, followed by a clean disconnect, without requiring a persistent client loop. ```APIDOC One-Shot Publish Functions: - single(): Publishes a single message to a broker, then disconnects cleanly. - multiple(): Publishes multiple messages to a broker, then disconnects cleanly. Note: Both functions support MQTT v5.0 but do not currently allow setting properties on connection or when sending messages. ``` -------------------------------- ### Migrate Paho MQTT `on_subscribe` Callback to Version 2.0 Source: https://github.com/eclipse-paho/paho.mqtt.python/blob/master/docs/migrations.rst Explains the necessary updates for the `on_subscribe` callback function in paho-mqtt 2.0. It shows the previous signatures for MQTTv3 and MQTTv5, and the new unified signature, focusing on the `reason_codes` parameter and handling subscription results. ```Python # OLD code for MQTTv3 def on_subscribe(client, userdata, mid, granted_qos): for sub_result in granted_qos: if sub_result == 1: # process QoS == 1 if sub_result == 0x80: # error processing ``` ```Python # OLD code for MQTTv5 def on_disconnect(client, userdata, mid, reason_codes, properties): for sub_result in reason_codes: if sub_result == 1: # process QoS == 1 # Any reason code >= 128 is a failure. if sub_result >= 128: # error processing ``` ```Python # NEW code for both version def on_subscribe(client, userdata, mid, reason_codes, properties): for sub_result in reason_codes: if sub_result == 1: # process QoS == 1 # Any reason code >= 128 is a failure. if sub_result >= 128: # error processing ``` -------------------------------- ### Publish Single MQTT Message with Paho Python Source: https://github.com/eclipse-paho/paho.mqtt.python/blob/master/README.rst Demonstrates how to publish a single message to an MQTT broker using the `paho.mqtt.publish.single` helper function. It connects, publishes the message, and then disconnects. ```python import paho.mqtt.publish as publish publish.single("paho/test/topic", "payload", hostname="mqtt.eclipseprojects.io") ``` -------------------------------- ### Clone Forked Git Repository Source: https://github.com/eclipse-paho/paho.mqtt.python/blob/master/CONTRIBUTING.md This Git command is used to clone a forked repository from GitHub to your local machine. It's the initial step in setting up your development environment after forking the main project repository. ```Git git clone https://github.com//paho.mqtt.python.git ``` -------------------------------- ### Integrate Standard Python Logging Source: https://github.com/eclipse-paho/paho.mqtt.python/blob/master/ChangeLog.txt The library now supports Python's standard `logging` module, allowing users to configure and manage log output from the MQTT client using familiar logging mechanisms. ```Python import logging client.enable_logger(logging.getLogger(__name__)) ``` -------------------------------- ### paho.mqtt.publish() Raises MQTTException on CONNECT Failure Source: https://github.com/eclipse-paho/paho.mqtt.python/blob/master/ChangeLog.txt The `paho.mqtt.publish()` helper function now raises an `MQTTException` if the connection to the broker fails, providing clearer error handling instead of silently continuing. ```Python import paho.mqtt.publish as publish import paho.mqtt.client as mqtt try: publish.single("topic", "payload", hostname="nonexistent.broker") except mqtt.MQTTException as e: print(f"MQTT connection or publish error: {e}") ``` -------------------------------- ### Paho MQTT Python Module API Documentation References Source: https://github.com/eclipse-paho/paho.mqtt.python/blob/master/docs/types.rst References to automatically generated API documentation for key modules in the paho.mqtt.python library, including enums, properties, and reason codes. The `.. automodule::` directive indicates that Sphinx will generate documentation for all public and undocumented members of these modules. ```APIDOC .. automodule:: paho.mqtt.enums :members: :undoc-members: .. automodule:: paho.mqtt.properties :members: :undoc-members: .. automodule:: paho.mqtt.reasoncodes :members: :undoc-members: ``` -------------------------------- ### Add SSLContext and SNI Support Source: https://github.com/eclipse-paho/paho.mqtt.python/blob/master/ChangeLog.txt The library now includes support for Python's `SSLContext` object, enabling advanced TLS configurations such as Server Name Indication (SNI). ```Python import ssl context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) client.tls_set_context(context) ``` -------------------------------- ### Paho MQTT Python Callback API Versions and Definitions Source: https://github.com/eclipse-paho/paho.mqtt.python/blob/master/README.rst This section details the callback mechanism in Paho MQTT, explaining how user-defined functions are invoked upon specific events. It describes the two supported CallbackAPIVersion's (VERSION1 and VERSION2), highlighting the deprecation of VERSION1 and recommending VERSION2 for its consistency and MQTT 5.x compatibility. It also lists key callbacks like on_connect() and on_connect_fail(). ```APIDOC The interface to interact with paho-mqtt include various callback that are called by the library when some events occur. The callbacks are functions defined in your code, to implement the require action on those events. This could be simply printing received message or much more complex behaviour. Callbacks API is versioned, and the selected version is the `CallbackAPIVersion` you provided to `Client` constructor. Currently two version are supported: * ``CallbackAPIVersion.VERSION1``: it's the historical version used in paho-mqtt before version 2.0. It's the API used before the introduction of `CallbackAPIVersion`. This version is deprecated and will be removed in paho-mqtt version 3.0. * ``CallbackAPIVersion.VERSION2``: This version is more consistent between protocol MQTT 3.x and MQTT 5.x. It's also much more usable with MQTT 5.x since reason code and properties are always provided when available. It's recommended for all user to upgrade to this version. It's highly recommended for MQTT 5.x user. The following callbacks exists: * `on_connect()`: called when the CONNACK from the broker is received. The call could be for a refused connection, check the reason_code to see if the connection is successful or rejected. * `on_connect_fail()`: called by `loop_forever()` and `loop_start()` when the TCP connection failed to establish. This callback is not called when using `connect()` or `reconnect()` directly. It's only called following ``` -------------------------------- ### Allow Zero-Length Username and Password Source: https://github.com/eclipse-paho/paho.mqtt.python/blob/master/ChangeLog.txt The Paho MQTT Python client now supports zero-length usernames and passwords, providing more flexibility compared to the previous requirement for them to be entirely absent if not used. ```Python client.username_pw_set(username="", password="") ``` -------------------------------- ### Migrate Paho MQTT `on_disconnect` Callback to Version 2.0 Source: https://github.com/eclipse-paho/paho.mqtt.python/blob/master/docs/migrations.rst Details the signature changes for the `on_disconnect` callback in paho-mqtt 2.0. It presents the old signatures for MQTTv3 and MQTTv5, and the new unified signature, emphasizing the transition from `rc` to `reason_code` and the addition of `flags` and `properties`. ```Python # OLD code for MQTTv3 def on_disconnect(client, userdata, rc): if rc == 0: # success disconnect if rc > 0: # error processing ``` ```Python # OLD code for MQTTv5 def on_disconnect(client, userdata, reason_code, properties): if reason_code: # error processing ``` ```Python # NEW code for both version def on_disconnect(client, userdata, flags, reason_code, properties): if reason_code == 0: # success disconnect if reason_code > 0: # error processing ``` -------------------------------- ### Simple Blocking MQTT Subscribe with Paho Python Source: https://github.com/eclipse-paho/paho.mqtt.python/blob/master/README.rst Illustrates how to subscribe to a set of topics and return the messages received using `paho.mqtt.subscribe.simple`. This is a blocking function that waits for a message and then prints its topic and payload. ```python import paho.mqtt.subscribe as subscribe msg = subscribe.simple("paho/test/topic", hostname="mqtt.eclipseprojects.io") print("%s %s" % (msg.topic, msg.payload)) ``` -------------------------------- ### Create GPG Signed Git Tag for Release Source: https://github.com/eclipse-paho/paho.mqtt.python/blob/master/CONTRIBUTING.md Generates a cryptographically signed Git tag for the release version (e.g., 'v1.2.3'), which provides authenticity and integrity verification for the release commit. ```bash git tag -s -m "Version 1.2.3" v1.2.3 ``` -------------------------------- ### Update `on_connect` Reason Code Comparisons Source: https://github.com/eclipse-paho/paho.mqtt.python/blob/master/docs/migrations.rst Shows how to update comparisons with `rc` (integer) to `reason_code` (ReasonCode instance) in the `on_connect` callback for paho-mqtt 2.0. It recommends comparing to string values instead of numeric ones for better clarity and compatibility across MQTT versions. ```Python # OLD code for MQTTv3 def on_connect(client, userdata, flags, rc): if rc == 1: # handle bad protocol version if rc == CONNACK_REFUSED_IDENTIFIER_REJECTED: # handle bad identifier ``` ```Python # NEW code def on_connect(client, userdata, flags, reason_code, properties): if reason_code == "Unsupported protocol version": # handle bad protocol version if reason_code == "Client identifier not valid": # handle bad identifier ``` -------------------------------- ### Add Support for Wildcard Certificates Source: https://github.com/eclipse-paho/paho.mqtt.python/blob/master/ChangeLog.txt The library now includes support for wildcard certificates in TLS connections, enhancing flexibility for certificate validation. ```Python # This implies that client.tls_set() or client.tls_set_context() # will now correctly handle wildcard certificates in the CA chain. client.tls_set(ca_certs="ca.crt") ``` -------------------------------- ### Update `on_connect` Callback Signature (Breaking Change) Source: https://github.com/eclipse-paho/paho.mqtt.python/blob/master/ChangeLog.txt The `on_connect` callback in the Paho MQTT Python client now consistently requires 4 arguments (client, userdata, flags, rc). This is a breaking change from previous versions where it could accept 3 or 4 arguments, requiring updates to existing callback implementations. ```Python def on_connect(client, userdata, flags, rc): # client: The client instance # userdata: The user data as set in Client() # flags: Response flags sent by the broker # rc: The connection result code pass ``` -------------------------------- ### Updating on_publish Callback Signature in paho-mqtt Source: https://github.com/eclipse-paho/paho.mqtt.python/blob/master/docs/migrations.rst This snippet shows the updated signature for the `on_publish` callback. The new version includes `reason_codes` and `properties` parameters, providing more detailed information about the publish operation compared to the older signature. ```Python # OLD code def on_publish(client, userdata, mid): # ... ``` ```Python # NEW code def on_publish(client, userdata, mid, reason_codes, properties): # ... ``` -------------------------------- ### Client.subscribe() Accepts Unicode Topics (Python 2) Source: https://github.com/eclipse-paho/paho.mqtt.python/blob/master/ChangeLog.txt On Python 2, the `Client.subscribe()` method now correctly handles unicode type topic inputs, improving compatibility and ease of use for internationalized topics. ```Python # Python 2 specific example client.subscribe(u"topic/unicode_été") ``` -------------------------------- ### Callback-based MQTT Subscribe with Paho Python Source: https://github.com/eclipse-paho/paho.mqtt.python/blob/master/README.rst Demonstrates subscribing to MQTT topics and processing received messages using a user-provided callback function (`on_message_print`). The callback can access client and user data, and can also trigger client disconnection based on conditions. ```python import paho.mqtt.subscribe as subscribe def on_message_print(client, userdata, message): print("%s %s" % (message.topic, message.payload)) userdata["message_count"] += 1 if userdata["message_count"] >= 5: # it's possible to stop the program by disconnecting client.disconnect() subscribe.callback(on_message_print, "paho/test/topic", hostname="mqtt.eclipseprojects.io", userdata={"message_count": 0}) ``` -------------------------------- ### Add WebSocket Protocol Support Source: https://github.com/eclipse-paho/paho.mqtt.python/blob/master/ChangeLog.txt The Paho MQTT Python client now supports connecting to MQTT brokers over WebSocket connections, enabling browser-based or WebSocket-only environments to use the library. ```Python import paho.mqtt.client as mqtt client = mqtt.Client(transport="websockets") client.connect("localhost", 8080, 60) ``` -------------------------------- ### Enhance Unicode Topic and Binary Payload Support Source: https://github.com/eclipse-paho/paho.mqtt.python/blob/master/ChangeLog.txt Improvements have been made to better handle unicode characters in MQTT topics and binary data in message payloads, resolving previous issues with encoding and decoding. ```Python # Python 2: client.publish(u"topic/été", b'binary_data') # Python 3: client.publish("topic/été", b'binary_data') ``` -------------------------------- ### Paho MQTT Python: External Event Loop Pseudo-Code Source: https://github.com/eclipse-paho/paho.mqtt.python/blob/master/README.rst This pseudo-code illustrates the basic structure for integrating the Paho MQTT client with an external event loop. It outlines the calls to `loop_read`, `loop_write`, and `loop_misc` methods to manage socket I/O and periodic tasks. ```python while run: if need_read: mqttc.loop_read() if need_write: mqttc.loop_write() mqttc.loop_misc() if not need_read and not need_write: # But don't wait more than few seconds, loop_misc() need to be called regularly wait_for_change_in_need_read_or_write() updated_need_read_and_write() ``` -------------------------------- ### Client.publish() Returns MQTTMessageInfo Object Source: https://github.com/eclipse-paho/paho.mqtt.python/blob/master/ChangeLog.txt The `Client.publish()` method now returns an `MQTTMessageInfo` object instead of a simple `(rc, mid)` tuple. This new object provides `is_published()` and `wait_for_published()` methods for more robust message delivery tracking without relying on callbacks, while maintaining backward compatibility for tuple unpacking. ```Python msg_info = client.publish("topic", "payload", qos=1) # msg_info behaves like (rc, mid) for backward compatibility # msg_info.rc # msg_info.mid # New methods: # msg_info.is_published() # msg_info.wait_for_published() ``` -------------------------------- ### Paho MQTT Python: External Event Loop Callbacks Source: https://github.com/eclipse-paho/paho.mqtt.python/blob/master/README.rst This section describes the callbacks provided by the Paho MQTT client for event loop integration. These callbacks notify the application about socket state changes and write readiness, enabling dynamic registration/unregistration with event loop mechanisms. ```APIDOC Callbacks for External Event Loop Support: - on_socket_open: Called when the socket is opened. - on_socket_close: Called when the socket is about to be closed. - on_socket_register_write: Called when there is data the client wants to write on the socket. - on_socket_unregister_write: Called when there is no more data to write on the socket. Callback Order: 1. on_socket_open 2. Zero or more times: - on_socket_register_write - on_socket_unregister_write 3. on_socket_close ``` -------------------------------- ### Support Zero-Length Client IDs for MQTT v3.1.1 Source: https://github.com/eclipse-paho/paho.mqtt.python/blob/master/ChangeLog.txt The client now permits the use of zero-length client IDs when connecting with MQTT protocol version 3.1.1, aligning with protocol specifications. ```Python client = mqtt.Client(client_id="", protocol=mqtt.MQTTv311) ``` -------------------------------- ### paho-mqtt Python Version Support Source: https://github.com/eclipse-paho/paho.mqtt.python/blob/master/docs/migrations.rst This section details the updated Python version compatibility for paho-mqtt. Version 2.0 supports Python 3.7 to 3.12, requiring users on older Python versions (including 2.x) to remain on paho-mqtt 1.x. ```APIDOC paho-mqtt support Python 3.7 to 3.12. If you are using an older Python version, including Python 2.x you will need to kept running the 1.x version of paho-mqtt. ``` -------------------------------- ### New Client Class Properties in paho-mqtt Source: https://github.com/eclipse-paho/paho.mqtt.python/blob/master/docs/migrations.rst This section lists new properties added to the `Client` class in paho-mqtt 2.0. Users subclassing `Client` should be aware of potential naming conflicts if they have defined attributes, methods, or properties with the same names as these new additions. ```APIDOC New Client Class Properties: - host - port - keepalive - transport - protocol - connect_timeout - username - password - max_inflight_messages - max_queued_messages - will_topic - will_payload - logger ``` -------------------------------- ### Implement Exponential Reconnection Delay Source: https://github.com/eclipse-paho/paho.mqtt.python/blob/master/ChangeLog.txt The client now incorporates an exponential back-off delay mechanism for reconnection attempts, improving resilience and reducing network strain during transient disconnections. ```Python client.reconnect_delay_set(min_delay=1, max_delay=120, exponential_backoff=True) ``` -------------------------------- ### Automate Git Commit Sign-off Source: https://github.com/eclipse-paho/paho.mqtt.python/blob/master/CONTRIBUTING.md This command demonstrates how to automatically add the required sign-off line to a Git commit message. By using the '-s' flag, contributors can streamline the commit process while adhering to the Eclipse Foundation's legal requirements for contributions. ```Git git commit -s -m "Adding a cool feature" ``` -------------------------------- ### Paho MQTT Python: Logging Level Correspondence Source: https://github.com/eclipse-paho/paho.mqtt.python/blob/master/README.rst This section documents the correspondence between Paho MQTT client's internal logging levels and standard Python `logging` module levels. It helps in mapping Paho's log events to a familiar logging framework. ```APIDOC Paho Logging Levels: - MQTT_LOG_ERR: Corresponds to logging.ERROR - MQTT_LOG_WARNING: Corresponds to logging.WARNING - MQTT_LOG_NOTICE: Corresponds to logging.INFO (no direct equivalent) - MQTT_LOG_INFO: Corresponds to logging.INFO - MQTT_LOG_DEBUG: Corresponds to logging.DEBUG ``` -------------------------------- ### Paho MQTT Python: External Event Loop Methods Source: https://github.com/eclipse-paho/paho.mqtt.python/blob/master/README.rst This section details the methods provided by the Paho MQTT client for integration with external event loops. These methods allow manual control over socket operations and periodic tasks required for MQTT communication. ```APIDOC Methods for External Event Loop Support: - loop_read(): Should be called when the socket is ready for reading. - loop_write(): Should be called when the socket is ready for writing AND the library wants to write data. - loop_misc(): Should be called every few seconds to handle message retrying and pings. - socket(): Returns the socket object when the TCP connection is open. Useful for select-based loops. - want_write(): Returns true if there is data waiting to be written. ``` -------------------------------- ### on_message Callback Signature in paho-mqtt Source: https://github.com/eclipse-paho/paho.mqtt.python/blob/master/docs/migrations.rst This snippet confirms that the `on_message` callback signature remains unchanged across paho-mqtt versions, simplifying migration for this specific handler as no code modifications are required. ```Python # OLD & NEW code def on_message(client, userdata, message): # ... ``` -------------------------------- ### Removed Deprecated Arguments and Methods in paho-mqtt Source: https://github.com/eclipse-paho/paho.mqtt.python/blob/master/docs/migrations.rst This section lists arguments and methods that have been removed in paho-mqtt 2.0. These include `max_packets` from `loop()`, `loop_write()`, and `loop_forever()`, `force` from `loop_stop()`, and the `message_retry_set()` method. Users should remove any references to these from their code. ```APIDOC Removed Arguments: - loop(), loop_write(), loop_forever(): max_packets - loop_stop(): force Removed Methods: - message_retry_set() ``` -------------------------------- ### Fix 'protocol' Not Used in publish.single() Source: https://github.com/eclipse-paho/paho.mqtt.python/blob/master/ChangeLog.txt The `publish.single()` helper function now correctly utilizes the `protocol` argument when specified, ensuring the desired MQTT protocol version is used for single message publications. ```Python import paho.mqtt.publish as publish import paho.mqtt.client as mqtt publish.single("topic", "payload", hostname="localhost", protocol=mqtt.MQTTv311) ``` -------------------------------- ### Revert Default MQTT Protocol to v3.1 Source: https://github.com/eclipse-paho/paho.mqtt.python/blob/master/ChangeLog.txt The default MQTT protocol version for connections has been reverted to v3.1 from v3.1.1 due to insufficient widespread support for v3.1.1 and issues with CONNACK code detection in current implementations. ```Python # Default client initialization now uses MQTT v3.1 client = mqtt.Client() # To explicitly use v3.1.1: # client = mqtt.Client(protocol=mqtt.MQTTv311) ``` -------------------------------- ### Client.publish() Accepts Bytes Payloads (Python 3) Source: https://github.com/eclipse-paho/paho.mqtt.python/blob/master/ChangeLog.txt On Python 3, the `Client.publish()` method now explicitly accepts `bytes()` type payloads, aligning with Python 3's string and bytes handling and improving binary data transmission. ```Python # Python 3 specific example client.publish("topic", b'\x00\x01\x02\xff') ``` -------------------------------- ### Create New Git Branch from Master Source: https://github.com/eclipse-paho/paho.mqtt.python/blob/master/CONTRIBUTING.md This command creates a new local branch based on the latest 'master' branch from the origin. It's a standard practice for isolating new features or bug fixes, ensuring that development work doesn't directly affect the main codebase until ready for integration. ```Git git checkout -b YOUR_BRANCH_NAME origin/master ``` -------------------------------- ### Removed Private Functions and Classes in paho-mqtt Source: https://github.com/eclipse-paho/paho.mqtt.python/blob/master/docs/migrations.rst This section specifies private functions and classes that are no longer exposed in paho-mqtt 2.0. These include the `base62` function, `WebsocketWrapper` class, and `ConnectionState` enum, which were previously accessible. ```APIDOC Removed Private Elements: - function: base62 - class: WebsocketWrapper - enum: ConnectionState ``` -------------------------------- ### Paho MQTT Python: Wait for Publish and Disconnect Source: https://github.com/eclipse-paho/paho.mqtt.python/blob/master/README.rst This snippet demonstrates how to safely wait for all pending MQTT messages to be published before disconnecting the client. It ensures that all messages are sent and acknowledged, preventing race conditions. ```python msg_info.wait_for_publish() msg_info2.wait_for_publish() mqttc.disconnect() mqttc.loop_stop() ``` -------------------------------- ### Handle Unicode Type Payloads on Python 2.7 Source: https://github.com/eclipse-paho/paho.mqtt.python/blob/master/ChangeLog.txt On Python 2.7, the client now correctly handles `unicode` type payloads when publishing messages, improving compatibility for text data. ```Python # ``` -------------------------------- ### Renamed ReasonCodes Class to ReasonCode in paho-mqtt Source: https://github.com/eclipse-paho/paho.mqtt.python/blob/master/docs/migrations.rst This section documents the renaming of the `ReasonCodes` class (plural) to `ReasonCode` (singular) in paho-mqtt 2.0. The old name is still present but deprecated, ensuring backward compatibility during migration. ```APIDOC Class Renamed: - Old Name: ReasonCodes - New Name: ReasonCode Note: ReasonCodes (plural) is still present but deprecated. ``` -------------------------------- ### Paho MQTT Python Blocking Network Loop (loop_forever) Source: https://github.com/eclipse-paho/paho.mqtt.python/blob/master/README.rst This snippet shows the usage of loop_forever(), a blocking network loop function that continuously processes MQTT traffic and handles reconnections until disconnect() is called. The retry_first_connection parameter can be used to control initial connection retries. ```python mqttc.loop_forever(retry_first_connection=False) ``` -------------------------------- ### Paho MQTT Python: Implement Custom on_log Callback Source: https://github.com/eclipse-paho/paho.mqtt.python/blob/master/README.rst This snippet demonstrates how to define a custom `on_log` callback function to receive and process log messages from the Paho MQTT client. It allows for custom handling of log events, such as filtering or redirecting error messages. ```python import paho.mqtt.client as mqtt def on_log(client, userdata, paho_log_level, messages): if paho_log_level == mqtt.LogLevel.MQTT_LOG_ERR: print(message) mqttc = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2) mqttc.on_log = on_log mqttc.connect("mqtt.eclipseprojects.io", 1883, 60) mqttc.loop_start() # Do additional action needed, publish, subscribe, ... [...] ``` -------------------------------- ### Improved Typing and `dup` Attribute Handling in paho-mqtt Source: https://github.com/eclipse-paho/paho.mqtt.python/blob/master/docs/migrations.rst paho-mqtt 2.0 introduces improved typing, which may affect how certain integer attributes are handled. Specifically, the `dup` attribute on `MQTTMessage` is now better typed. Code that checked `if msg.dup == 1:` should be updated to `if msg.dup:` for compatibility with both 1.x and 2.0 versions. ```APIDOC Improved Typing: - MQTTMessage.dup: Now better typed. - Old Usage: if msg.dup == 1: - New Usage: if msg.dup: ``` -------------------------------- ### Fixed connect_srv() Signature in paho-mqtt Source: https://github.com/eclipse-paho/paho.mqtt.python/blob/master/docs/migrations.rst This section describes the fix for the `connect_srv()` method signature in paho-mqtt 2.0. Previously, it did not align with `connect()`. The signature has been changed, but since `connect_srv()` was broken in previous versions, this change should not negatively impact existing code. ```APIDOC Method Signature Change: - Method: connect_srv() - Change: Signature now matches connect(). - Impact: Minimal, as connect_srv() was previously broken. ``` -------------------------------- ### Commit Changes with Git Sign-off Source: https://github.com/eclipse-paho/paho.mqtt.python/blob/master/CONTRIBUTING.md This Git command commits the staged changes to the current branch, automatically adding the sign-off line. It's important to provide a meaningful commit message that accurately describes the changes made, aiding in code review and project history tracking. ```Git git commit -s ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.