### Start hbmqtt Broker with Default Configuration Source: https://github.com/njouanin/hbmqtt/blob/master/docs/references/broker.rst This example demonstrates how to initialize and start the hbmqtt Broker using its default settings. It requires asyncio and logging setup. ```python import logging import asyncio import os from hbmqtt.broker import Broker @asyncio.coroutine def broker_coro(): broker = Broker() yield from broker.start() if __name__ == '__main__': formatter = "[%(asctime)s] :: %(levelname)s :: %(name)s :: %(message)s" logging.basicConfig(level=logging.INFO, format=formatter) asyncio.get_event_loop().run_until_complete(broker_coro()) asyncio.get_event_loop().run_forever() ``` -------------------------------- ### Broker Usage Example Source: https://github.com/njouanin/hbmqtt/blob/master/docs/references/broker.rst This example demonstrates how to start an HBMQTT broker with default configuration. ```APIDOC ## Broker Usage Example ### Description This example shows how to start a broker using the default configuration. ### Method N/A (Python script) ### Endpoint N/A (In-process broker) ### Request Body N/A ### Response N/A ### Code Example ```python import logging import asyncio import os from hbmqtt.broker import Broker @asyncio.coroutine def broker_coro(): broker = Broker() yield from broker.start() if __name__ == '__main__': formatter = "[%(asctime)s] :: %(levelname)s :: %(name)s :: %(message)s" logging.basicConfig(level=logging.INFO, format=formatter) asyncio.get_event_loop().run_until_complete(broker_coro()) asyncio.get_event_loop().run_forever() ``` ``` -------------------------------- ### Install HBMQTT using pip Source: https://github.com/njouanin/hbmqtt/blob/master/readme.rst Install HBMQTT using pip. This is the recommended way to get started with the library. ```bash $ pip install hbmqtt ``` -------------------------------- ### Start HBMQTT Broker from Command Line Source: https://context7.com/njouanin/hbmqtt/llms.txt Starts an HBMQTT broker with default configuration using the command-line tool. ```bash # Start a broker with default configuration $ hbmqtt [2023-01-01 12:00:00] :: INFO - Listener 'default' bind to 0.0.0.0:1883 ``` -------------------------------- ### Start an MQTT Broker Source: https://context7.com/njouanin/hbmqtt/llms.txt Provides the necessary import for starting an MQTT broker using the `Broker` class. The `start` method is used to initiate the broker's listening services. ```python import asyncio import logging from hbmqtt.broker import Broker ``` -------------------------------- ### Complete Publisher/Subscriber Example in Python Source: https://context7.com/njouanin/hbmqtt/llms.txt A comprehensive asyncio example demonstrating a publisher and subscriber client interacting with an MQTT broker. Includes connection handling, message publishing with QoS, message subscription, and error handling. ```python import asyncio import logging from hbmqtt.client import MQTTClient, ClientException, ConnectException from hbmqtt.mqtt.constants import QOS_1 logger = logging.getLogger(__name__) async def publisher(): client = MQTTClient(client_id='publisher-1') try: await client.connect('mqtt://localhost:1883/') for i in range(10): message = f'Message {i}'.encode() await client.publish('demo/messages', message, qos=QOS_1) logger.info(f"Published: {message}") await asyncio.sleep(1) except ConnectException as e: logger.error(f"Connection failed: {e}") finally: await client.disconnect() async def subscriber(): client = MQTTClient(client_id='subscriber-1') try: await client.connect('mqtt://localhost:1883/') await client.subscribe([('demo/messages', QOS_1)]) while True: try: message = await client.deliver_message(timeout=30) packet = message.publish_packet payload = packet.payload.data.decode() logger.info(f"Received: {payload}") except asyncio.TimeoutError: logger.info("No message received, continuing...") except ClientException as e: logger.error(f"Client error: {e}") finally: await client.disconnect() async def main(): # Run publisher and subscriber concurrently await asyncio.gather( publisher(), subscriber() ) if __name__ == '__main__': logging.basicConfig( level=logging.INFO, format='[%(asctime)s] %(name)s - %(message)s' ) asyncio.get_event_loop().run_until_complete(main()) ``` -------------------------------- ### HBMQTT Configuration Example Source: https://github.com/njouanin/hbmqtt/blob/master/docs/references/hbmqtt.rst An extensive YAML configuration example demonstrating various listener types (TCP, SSL, WebSocket), connection limits, and authentication methods. ```yaml listeners: default: max-connections: 50000 type: tcp my-tcp-1: bind: 127.0.0.1:1883 my-tcp-2: bind: 1.2.3.4:1883 max-connections: 1000 my-tcp-ssl-1: bind: 127.0.0.1:8883 ssl: on cafile: /some/cafile capath: /some/folder capath: certificate data certfile: /some/certfile keyfile: /some/key my-ws-1: bind: 0.0.0.0:8080 type: ws timeout-disconnect-delay: 2 auth: plugins: ['auth.anonymous'] allow-anonymous: true password-file: /some/passwd_file ``` -------------------------------- ### Broker.start Source: https://context7.com/njouanin/hbmqtt/llms.txt Starts the MQTT broker instance. ```APIDOC ## Broker.start ### Description The `start` method opens network sockets and begins listening for incoming connections. The broker supports multiple listeners (TCP and WebSocket), SSL/TLS encryption, and pluggable authentication and topic access control. ``` -------------------------------- ### Install HBMQTT Source: https://github.com/njouanin/hbmqtt/blob/master/docs/index.rst Install HBMQTT and its dependencies within a virtual environment using pip. ```bash (venv) $ pip install hbmqtt ``` -------------------------------- ### MQTT URL examples Source: https://github.com/njouanin/hbmqtt/blob/master/docs/quickstart.rst Examples of valid MQTT URL schemes for connecting to brokers. These demonstrate different protocols (mqtt, ws, wss), authentication, and port specifications. ```text mqtt://localhost mqtt://localhost:1884 mqtt://user:password@localhost ws://test.mosquitto.org wss://user:password@localhost ``` -------------------------------- ### Publish MQTT messages via command line Source: https://github.com/njouanin/hbmqtt/blob/master/docs/references/hbmqtt_pub.rst Examples of publishing messages to an MQTT broker using different configurations. ```bash hbmqtt_pub --url mqtt://localhost -t sensors/temperature -m 32 -q 1 ``` ```bash hbmqtt_pub --url mqtt://192.168.1.1:1885 -t sensors/temperature -m "1266193804 32" ``` ```bash hbmqtt_pub --url mqtt://localhost -r -t switches/kitchen_lights/status -m "on" ``` -------------------------------- ### Configure Basic HBMQTT Broker Source: https://context7.com/njouanin/hbmqtt/llms.txt Defines a basic broker configuration with TCP and WebSocket listeners and starts the broker instance. ```python config = { 'listeners': { 'default': { 'type': 'tcp', 'bind': '0.0.0.0:1883', 'max_connections': 50000, }, 'ws-mqtt': { 'type': 'ws', 'bind': '0.0.0.0:8080', 'max_connections': 1000, }, }, 'sys_interval': 10, # $SYS topic update interval 'auth': { 'allow-anonymous': True, }, 'topic-check': { 'enabled': False, } } async def start_broker(): broker = Broker(config) await broker.start() print("Broker started on port 1883 (TCP) and 8080 (WebSocket)") if __name__ == '__main__': logging.basicConfig(level=logging.INFO) asyncio.get_event_loop().run_until_complete(start_broker()) asyncio.get_event_loop().run_forever() ``` -------------------------------- ### Run HBMQTT broker Source: https://github.com/njouanin/hbmqtt/blob/master/docs/quickstart.rst Start a standalone MQTT broker using the `hbmqtt` command-line tool. This command will bind to all available network interfaces on the default MQTT port (1883). ```bash $ hbmqtt [2015-11-06 22:45:16,470] :: INFO - Listener 'default' bind to 0.0.0.0:1883 (max_connections=-1) ``` -------------------------------- ### Publish a message using hbmqtt_pub Source: https://github.com/njouanin/hbmqtt/blob/master/docs/quickstart.rst Publish a simple message to a topic on an external MQTT broker using the `hbmqtt_pub` command-line tool. This example uses an insecure TCP connection. ```bash $ hbmqtt_pub --url mqtt://test.mosquitto.org -t /test -m some_data [2015-11-06 22:21:55,108] :: INFO - hbmqtt_pub/5135-MacBook-Pro.local Connecting to broker [2015-11-06 22:21:55,333] :: INFO - hbmqtt_pub/5135-MacBook-Pro.local Publishing to '/test' [2015-11-06 22:21:55,336] :: INFO - hbmqtt_pub/5135-MacBook-Pro.local Disconnected from broker ``` -------------------------------- ### HBMQTT Password File Format Source: https://github.com/njouanin/hbmqtt/blob/master/docs/references/hbmqtt.rst Example format for the HBMQTT password file, showing username and encrypted password pairs. Passwords should be generated using `mkpasswd -m sha-512`. ```text # Test user with 'test' password encrypted with sha-512 test:$6$l4zQEHEcowc1Pnv4$HHrh8xnsZoLItQ8BmpFHM4r6q5UqK3DnXp2GaTm5zp5buQ7NheY3Xt9f6godVKbEtA.hOC7IEDwnok3pbAOip. ``` -------------------------------- ### Receive MQTT Messages with Timeout Source: https://context7.com/njouanin/hbmqtt/llms.txt Demonstrates receiving messages from subscribed topics using `deliver_message`. Includes an example of handling a timeout. ```python import asyncio from hbmqtt.client import MQTTClient, ClientException from hbmqtt.mqtt.constants import QOS_1 async def receive_messages(): client = MQTTClient() await client.connect('mqtt://test.mosquitto.org/') await client.subscribe([ ('$SYS/broker/uptime', QOS_1), ('$SYS/broker/load/#', QOS_1), ]) try: # Receive 10 messages for i in range(10): message = await client.deliver_message() packet = message.publish_packet topic = packet.variable_header.topic_name payload = packet.payload.data.decode('utf-8') print(f"{i+1}: {topic} => {payload}") # With timeout (raises asyncio.TimeoutError if exceeded) try: message = await client.deliver_message(timeout=5) print(f"Received: {message.topic}") except asyncio.TimeoutError: print("No message received within 5 seconds") except ClientException as e: print(f"Client error: {e}") finally: await client.unsubscribe(['$SYS/broker/uptime', '$SYS/broker/load/#']) await client.disconnect() if __name__ == '__main__': asyncio.get_event_loop().run_until_complete(receive_messages()) ``` -------------------------------- ### Gracefully Shutdown HBMQTT Broker Source: https://context7.com/njouanin/hbmqtt/llms.txt Demonstrates how to gracefully stop the HBMQTT broker by handling SIGINT and SIGTERM signals. Ensure the broker is started before attempting to shut it down. ```python import asyncio import signal from hbmqtt.broker import Broker broker = Broker() async def start_broker(): await broker.start() print("Broker started") async def shutdown_broker(): await broker.shutdown() print("Broker stopped") def signal_handler(): asyncio.ensure_future(shutdown_broker()) if __name__ == '__main__': loop = asyncio.get_event_loop() loop.add_signal_handler(signal.SIGINT, signal_handler) loop.add_signal_handler(signal.SIGTERM, signal_handler) loop.run_until_complete(start_broker()) loop.run_forever() ``` -------------------------------- ### Subscribe to MQTT topics with Python Source: https://github.com/njouanin/hbmqtt/blob/master/docs/references/mqttclient.rst Demonstrates connecting to a broker, subscribing to multiple topics with specific QOS levels, and processing incoming messages. ```python import logging import asyncio from hbmqtt.client import MQTTClient, ClientException from hbmqtt.mqtt.constants import QOS_1, QOS_2 logger = logging.getLogger(__name__) @asyncio.coroutine def uptime_coro(): C = MQTTClient() yield from C.connect('mqtt://test.mosquitto.org/') # Subscribe to '$SYS/broker/uptime' with QOS=1 # Subscribe to '$SYS/broker/load/#' with QOS=2 yield from C.subscribe([ ('$SYS/broker/uptime', QOS_1), ('$SYS/broker/load/#', QOS_2), ]) try: for i in range(1, 100): message = yield from C.deliver_message() packet = message.publish_packet print("%d: %s => %s" % (i, packet.variable_header.topic_name, str(packet.payload.data))) yield from C.unsubscribe(['$SYS/broker/uptime', '$SYS/broker/load/#']) yield from C.disconnect() except ClientException as ce: logger.error("Client exception: %s" % ce) if __name__ == '__main__': formatter = "[%(asctime)s] %(name)s {%(filename)s:%(lineno)d} %(levelname)s - %(message)s" logging.basicConfig(level=logging.DEBUG, format=formatter) asyncio.get_event_loop().run_until_complete(uptime_coro()) ``` -------------------------------- ### HBMQTT Command-Line Usage Source: https://github.com/njouanin/hbmqtt/blob/master/docs/references/hbmqtt.rst Basic command-line arguments for running the HBMQTT broker, including version check, help, and configuration file specification. ```bash hbmqtt --version ``` ```bash hbmqtt (-h | --help) ``` ```bash hbmqtt [-c ] [-d] ``` -------------------------------- ### hbmqtt_sub Help Usage Source: https://github.com/njouanin/hbmqtt/blob/master/docs/references/hbmqtt_sub.rst Displays the help message for the hbmqtt_sub client, outlining available options. ```bash hbmqtt_sub -h ``` ```bash hbmqtt_sub --help ``` -------------------------------- ### Display hbmqtt_pub usage Source: https://github.com/njouanin/hbmqtt/blob/master/docs/references/hbmqtt_pub.rst Shows the command line syntax and available arguments for the hbmqtt_pub tool. ```bash hbmqtt_pub --version hbmqtt_pub (-h | --help) hbmqtt_pub --url BROKER_URL -t TOPIC (-f FILE | -l | -m MESSAGE | -n | -s) [-c CONFIG_FILE] [-i CLIENT_ID] [-d] [-q | --qos QOS] [-d] [-k KEEP_ALIVE] [--clean-session] [--ca-file CAFILE] [--ca-path CAPATH] [--ca-data CADATA] [ --will-topic WILL_TOPIC [--will-message WILL_MESSAGE] [--will-qos WILL_QOS] [--will-retain] ] [--extra-headers HEADER] ``` -------------------------------- ### MQTTClient Configuration Source: https://github.com/njouanin/hbmqtt/blob/master/docs/references/mqttclient.rst Configuration parameters for the MQTTClient initialization. ```APIDOC ## MQTTClient Configuration ### Description The MQTTClient constructor accepts a configuration dictionary to define client behavior. ### Configuration Parameters - **keep_alive** (int): Keep alive interval in seconds (default: 10). - **ping_delay** (int): Auto-ping delay before timeout (default: 1). - **default_qos** (int): Default QoS level for publishing (default: 0). - **default_retain** (bool): Default retain flag for publishing (default: False). - **auto_reconnect** (bool): Enable/disable auto-reconnect (default: True). - **reconnect_max_interval** (int): Max interval between connection retries (default: 10). - **reconnect_retries** (int): Max number of connection retries (default: 2). ``` -------------------------------- ### Configure MQTTClient with Custom Settings Source: https://context7.com/njouanin/hbmqtt/llms.txt Illustrates configuring an `MQTTClient` with various options like keep-alive, auto-reconnect, LWT messages, and topic-specific QoS/retain settings. ```python import asyncio from hbmqtt.client import MQTTClient from hbmqtt.mqtt.constants import QOS_1 config = { 'keep_alive': 10, 'ping_delay': 1, 'default_qos': 0, 'default_retain': False, 'auto_reconnect': True, 'reconnect_max_interval': 10, 'reconnect_retries': 5, 'will': { 'topic': '/status/client1', 'message': b'Client disconnected unexpectedly', 'qos': QOS_1, 'retain': True }, 'topics': { '/important/data': {'qos': 2, 'retain': True}, '/logs': {'qos': 0}, } } async def configured_client(): client = MQTTClient(client_id='my-custom-client-id', config=config) await client.connect('mqtt://localhost:1883/') await client.publish('/important/data', b'critical value') await client.publish('/logs', b'log entry') await client.disconnect() if __name__ == '__main__': asyncio.get_event_loop().run_until_complete(configured_client()) ``` -------------------------------- ### hbmqtt_sub Basic Usage Source: https://github.com/njouanin/hbmqtt/blob/master/docs/references/hbmqtt_sub.rst Displays the version information for the hbmqtt_sub client. ```bash hbmqtt_sub --version ``` -------------------------------- ### Broker Configuration Source: https://github.com/njouanin/hbmqtt/blob/master/docs/references/broker.rst Details on configuring the HBMQTT broker using a dictionary. ```APIDOC ## Broker Configuration ### Description The `hbmqtt.broker.Broker` `__init__` method accepts a `config` parameter, which must be a Python dictionary, to set up broker behavior and default settings. ### Configuration Structure (YAML Example) ```yaml listeners: default: max-connections: 50000 type: tcp my-tcp-1: bind: 127.0.0.1:1883 my-tcp-2: bind: 1.2.3.4:1884 max-connections: 1000 my-tcp-ssl-1: bind: 127.0.0.1:8885 ssl: on cafile: /some/cafile capath: /some/folder certfile: /some/certfile keyfile: /some/key my-ws-1: bind: 0.0.0.0:8080 type: ws timeout-disconnect-delay: 2 auth: plugins: ['auth.anonymous'] allow-anonymous: true / false password-file: /some/passwd_file topic-check: enabled: true / false plugins: ['topic_acl'] acl: username1: ['repositories/+/master', 'calendar/#', 'data/memes'] username2: [] anonymous: [] ``` ### Configuration Sections #### `listeners` Defines network listeners for the broker. * `default`: Common attributes for all listeners. * `max-connections` (integer): Maximum active connections for a listener. `0` means no limit. * `type` (string): Transport protocol (`tcp` or `ws`). * Each listener subsection can have: * `bind` (string): IP address and port binding (e.g., `127.0.0.1:1883`). * `max-connections` (integer): Maximum connections for this specific listener. * `type` (string): Transport protocol (`tcp` or `ws`). * `ssl` (string): Enable (`on`) or disable SSL. * `cafile` (string): Path to CA certificate file (for SSL). * `cadata` (string): CA certificate data (for SSL). * `certfile` (string): Path to certificate file (for SSL). * `keyfile` (string): Path to key file (for SSL). #### `timeout-disconnect-delay` * (integer): Delay in seconds before disconnecting clients due to timeout. #### `auth` Sets up authentication behavior. * `plugins` (list of strings): List of activated authentication plugins. * `allow-anonymous` (boolean): Enables or disables anonymous connections. * `password-file` (string): Path to the password file for file-based authentication. #### `topic-check` Sets up access control policies for topic publishing and subscribing. * `enabled` (boolean): Enables or disables topic access control. * `plugins` (list of strings): List of activated topic access control plugins. * `acl` (dict): Defines access control lists for specific usernames. Keys are usernames, and values are lists of allowed topics. ``` -------------------------------- ### Subscribe to 10 messages from /# with QoS 2 Source: https://github.com/njouanin/hbmqtt/blob/master/docs/references/hbmqtt_sub.rst Subscribes to a maximum of 10 messages published under any topic (/#) with a Quality of Service level of 2. ```bash hbmqtt_sub --url mqtt://localhost -t /# -q 2 -n 10 ``` -------------------------------- ### MQTTClient.connect Source: https://context7.com/njouanin/hbmqtt/llms.txt Establishes a connection to an MQTT broker. Supports various protocols (TCP, WebSocket) and security options (SSL). ```APIDOC ## MQTTClient.connect ### Description Establishes a connection to an MQTT broker using the specified URI. Supports multiple protocols including `mqtt://` (TCP), `mqtts://` (TCP with SSL), `ws://` (WebSocket), and `wss://` (WebSocket with SSL). The URI can include username and password for authentication, and the method returns the CONNACK return code upon successful connection. ### Method `connect` ### Endpoint N/A (This is a client method, not a server endpoint) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python import asyncio from hbmqtt.client import MQTTClient, ConnectException async def connect_example(): # Basic TCP connection client = MQTTClient() await client.connect('mqtt://test.mosquitto.org/') # Connection with authentication client_auth = MQTTClient() await client_auth.connect('mqtt://user:password@localhost:1883/') # WebSocket connection client_ws = MQTTClient() await client_ws.connect('ws://test.mosquitto.org:8080/') # Secure connection with SSL certificate client_ssl = MQTTClient() await client_ssl.connect( 'mqtts://test.mosquitto.org/', cafile='mosquitto.org.crt' ) # Secure WebSocket connection client_wss = MQTTClient() await client_wss.connect( 'wss://test.mosquitto.org:8081/', cafile='mosquitto.org.crt' ) await client.disconnect() if __name__ == '__main__': asyncio.get_event_loop().run_until_complete(connect_example()) ``` ### Response #### Success Response (CONNACK return code) - **return_code** (int) - The CONNACK return code from the broker. #### Response Example (CONNACK return codes are integers, e.g., 0 for success) ``` -------------------------------- ### Subscribe to $SYS/# with QoS 0 Source: https://github.com/njouanin/hbmqtt/blob/master/docs/references/hbmqtt_sub.rst Subscribes to all messages published under the $SYS/ topic with a Quality of Service level of 0. ```bash hbmqtt_sub --url mqtt://localhost -t '$SYS/#' -q 0 ``` -------------------------------- ### Publish file contents via hbmqtt_pub Source: https://github.com/njouanin/hbmqtt/blob/master/docs/references/hbmqtt_pub.rst Use these commands to send file data to an MQTT topic using either a file path argument or standard input redirection. ```bash hbmqtt_pub --url mqtt://localhost -t my/topic -f ./data ``` ```bash hbmqtt_pub --url mqtt://localhost -t my/topic -s < ./data ``` -------------------------------- ### Connect to MQTT Broker Source: https://context7.com/njouanin/hbmqtt/llms.txt Establishes a connection to an MQTT broker using various protocols (TCP, WebSocket, SSL/TLS). Supports authentication via URI. ```python import asyncio from hbmqtt.client import MQTTClient, ConnectException async def connect_example(): # Basic TCP connection client = MQTTClient() await client.connect('mqtt://test.mosquitto.org/') # Connection with authentication client_auth = MQTTClient() await client_auth.connect('mqtt://user:password@localhost:1883/') # WebSocket connection client_ws = MQTTClient() await client_ws.connect('ws://test.mosquitto.org:8080/') # Secure connection with SSL certificate client_ssl = MQTTClient() await client_ssl.connect( 'mqtts://test.mosquitto.org/', cafile='mosquitto.org.crt' ) # Secure WebSocket connection client_wss = MQTTClient() await client_wss.connect( 'wss://test.mosquitto.org:8081/', cafile='mosquitto.org.crt' ) await client.disconnect() if __name__ == '__main__': asyncio.get_event_loop().run_until_complete(connect_example()) ``` -------------------------------- ### Publish MQTT messages with Python Source: https://github.com/njouanin/hbmqtt/blob/master/docs/references/mqttclient.rst Shows two methods for publishing messages: using asyncio tasks for concurrent publishing and sequential publishing using yield from. ```python import logging import asyncio from hbmqtt.client import MQTTClient from hbmqtt.mqtt.constants import QOS_0, QOS_1, QOS_2 logger = logging.getLogger(__name__) @asyncio.coroutine def test_coro(): C = MQTTClient() yield from C.connect('mqtt://test.mosquitto.org/') tasks = [ asyncio.ensure_future(C.publish('a/b', b'TEST MESSAGE WITH QOS_0')), asyncio.ensure_future(C.publish('a/b', b'TEST MESSAGE WITH QOS_1', qos=QOS_1)), asyncio.ensure_future(C.publish('a/b', b'TEST MESSAGE WITH QOS_2', qos=QOS_2)), ] yield from asyncio.wait(tasks) logger.info("messages published") yield from C.disconnect() @asyncio.coroutine def test_coro2(): try: C = MQTTClient() ret = yield from C.connect('mqtt://test.mosquitto.org:1883/') message = yield from C.publish('a/b', b'TEST MESSAGE WITH QOS_0', qos=QOS_0) message = yield from C.publish('a/b', b'TEST MESSAGE WITH QOS_1', qos=QOS_1) message = yield from C.publish('a/b', b'TEST MESSAGE WITH QOS_2', qos=QOS_2) #print(message) logger.info("messages published") yield from C.disconnect() except ConnectException as ce: logger.error("Connection failed: %s" % ce) asyncio.get_event_loop().stop() if __name__ == '__main__': formatter = "[%(asctime)s] %(name)s {%(filename)s:%(lineno)d} %(levelname)s - %(message)s" logging.basicConfig(level=logging.DEBUG, format=formatter) asyncio.get_event_loop().run_until_complete(test_coro()) asyncio.get_event_loop().run_until_complete(test_coro2()) ``` -------------------------------- ### hbmqtt_sub General Usage Source: https://github.com/njouanin/hbmqtt/blob/master/docs/references/hbmqtt_sub.rst General usage syntax for hbmqtt_sub, specifying broker URL, topics, and various optional parameters for connection and message handling. ```bash hbmqtt_sub --url BROKER_URL -t TOPIC... [-n COUNT] [-c CONFIG_FILE] [-i CLIENT_ID] [-q | --qos QOS] [-d] [-k KEEP_ALIVE] [--clean-session] [--ca-file CAFILE] [--ca-path CAPATH] [--ca-data CADATA] [ --will-topic WILL_TOPIC [--will-message WILL_MESSAGE] [--will-qos WILL_QOS] [--will-retain] ] [--extra-headers HEADER] ``` -------------------------------- ### Configure Broker with SSL/TLS Source: https://context7.com/njouanin/hbmqtt/llms.txt Enables secure connections by specifying certificate and key files for TCP and WebSocket listeners. ```python import asyncio import logging from hbmqtt.broker import Broker ssl_config = { 'listeners': { 'default': { 'type': 'tcp', 'bind': '0.0.0.0:1883', }, 'ssl-mqtt': { 'type': 'tcp', 'bind': '0.0.0.0:8883', 'ssl': 'on', 'certfile': '/path/to/server.crt', 'keyfile': '/path/to/server.key', 'cafile': '/path/to/ca.crt', }, 'wss-mqtt': { 'type': 'ws', 'bind': '0.0.0.0:8443', 'ssl': 'on', 'certfile': '/path/to/server.crt', 'keyfile': '/path/to/server.key', }, }, 'auth': { 'allow-anonymous': True, }, } async def start_secure_broker(): broker = Broker(ssl_config) await broker.start() if __name__ == '__main__': logging.basicConfig(level=logging.INFO) asyncio.get_event_loop().run_until_complete(start_secure_broker()) asyncio.get_event_loop().run_forever() ``` -------------------------------- ### Publish a message using websockets Source: https://github.com/njouanin/hbmqtt/blob/master/docs/quickstart.rst Publish a message to a topic using `hbmqtt_pub` over a websocket connection. This demonstrates connecting to a broker via `ws://`. ```bash $ hbmqtt_pub --url ws://test.mosquitto.org:8080 -t /test -m some_data [2015-11-06 22:22:42,542] :: INFO - hbmqtt_pub/5157-MacBook-Pro.local Connecting to broker [2015-11-06 22:22:42,924] :: INFO - hbmqtt_pub/5157-MacBook-Pro.local Publishing to '/test' [2015-11-06 22:22:52,926] :: INFO - hbmqtt_pub/5157-MacBook-Pro.local Disconnected from broker ``` -------------------------------- ### Configure Broker Authentication Source: https://context7.com/njouanin/hbmqtt/llms.txt Implements file-based password authentication using passlib hashes. ```python import asyncio import logging import os from hbmqtt.broker import Broker # passwd file format (one per line): # username:$6$rounds=656000$hash... # Create hashes with: python -c "from passlib.apps import custom_app_context; print(custom_app_context.hash('password'))" auth_config = { 'listeners': { 'default': { 'type': 'tcp', 'bind': '0.0.0.0:1883', }, }, 'auth': { 'allow-anonymous': False, 'password-file': '/path/to/passwd', 'plugins': ['auth_file', 'auth_anonymous'], }, } async def start_authenticated_broker(): broker = Broker(auth_config) await broker.start() if __name__ == '__main__': logging.basicConfig(level=logging.INFO) asyncio.get_event_loop().run_until_complete(start_authenticated_broker()) asyncio.get_event_loop().run_forever() ``` -------------------------------- ### Subscribe via WebSocket with Extra Headers Source: https://github.com/njouanin/hbmqtt/blob/master/docs/references/hbmqtt_sub.rst Subscribes to $SYS/# with QoS 0, using a WebSocket connection and including custom authorization headers. ```bash hbmqtt_sub --url wss://localhost -t '$SYS/#' -q 0 --extra-headers '{"Authorization": "Bearer "}' ``` -------------------------------- ### Subscribe to MQTT Topics Source: https://context7.com/njouanin/hbmqtt/llms.txt Subscribes to topic patterns with specified QoS levels, supporting single-level (+) and multi-level (#) wildcards. ```python import asyncio from hbmqtt.client import MQTTClient from hbmqtt.mqtt.constants import QOS_1, QOS_2 async def subscribe_example(): client = MQTTClient() await client.connect('mqtt://test.mosquitto.org/') # Subscribe to multiple topics with different QoS levels await client.subscribe([ ('$SYS/broker/uptime', QOS_1), # Broker uptime ('$SYS/broker/load/#', QOS_2), # All load metrics (wildcard) ('sensors/+/temperature', QOS_1), # Temperature from any sensor ]) print("Subscribed to topics") await client.disconnect() if __name__ == '__main__': asyncio.get_event_loop().run_until_complete(subscribe_example()) ``` -------------------------------- ### hbmqtt Broker Configuration Options Source: https://github.com/njouanin/hbmqtt/blob/master/docs/references/broker.rst This snippet outlines the configuration structure for the hbmqtt Broker, including listener settings, authentication plugins, and topic access control policies. It is presented in YAML format. ```yaml listeners: default: max-connections: 50000 type: tcp my-tcp-1: bind: 127.0.0.1:1883 my-tcp-2: bind: 1.2.3.4:1884 max-connections: 1000 my-tcp-ssl-1: bind: 127.0.0.1:8885 ssl: on cafile: /some/cafile capath: /some/folder capath: certificate data certfile: /some/certfile keyfile: /some/key my-ws-1: bind: 0.0.0.0:8080 type: ws timeout-disconnect-delay: 2 auth: plugins: ['auth.anonymous'] #List of plugins to activate for authentication among all registered plugins allow-anonymous: true / false password-file: /some/passwd_file topic-check: enabled: true / false # Set to False if topic filtering is not needed plugins: ['topic_acl'] #List of plugins to activate for topic filtering among all registered plugins acl: # username: [list of allowed topics] username1: ['repositories/+/master', 'calendar/#', 'data/memes'] # List of topics on which client1 can publish and subscribe username2: ... anonymous: [] # List of topics on which an anonymous client can publish and subscribe ``` -------------------------------- ### Define HBMQTT configuration dictionary Source: https://github.com/njouanin/hbmqtt/blob/master/docs/references/mqttclient.rst Configures global MQTT client behavior and topic-specific QoS/retain settings. Values passed directly to the publish method will override these defaults. ```python config = { 'keep_alive': 10, 'ping_delay': 1, 'default_qos': 0, 'default_retain': False, 'auto_reconnect': True, 'reconnect_max_interval': 5, 'reconnect_retries': 10, 'topics': { '/test': { 'qos': 1 }, '/some_topic': { 'qos': 2, 'retain': True } } } ``` -------------------------------- ### Subscribe to Topic with hbmqtt_sub Source: https://context7.com/njouanin/hbmqtt/llms.txt Subscribes to MQTT topics using the hbmqtt_sub command-line tool. Supports topic patterns, limiting the number of messages received, and secure connections. ```bash # Subscribe to a topic pattern $ hbmqtt_sub --url mqtt://localhost -t /test/# # Subscribe with limit on messages received $ hbmqtt_sub --url mqtt://localhost -t /sensors/+ -n 10 ``` -------------------------------- ### MQTTClient.publish Source: https://context7.com/njouanin/hbmqtt/llms.txt Sends a message to a specified topic on the broker with configurable QoS levels and retain flag. ```APIDOC ## MQTTClient.publish ### Description Sends a message to a specified topic on the broker. It supports QoS levels 0 (at most once), 1 (at least once), and 2 (exactly once), as well as the retain flag to have the broker store the message for future subscribers. The method waits for acknowledgment based on the QoS level. ### Method `publish` ### Endpoint N/A (This is a client method, not a server endpoint) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python import asyncio from hbmqtt.client import MQTTClient from hbmqtt.mqtt.constants import QOS_0, QOS_1, QOS_2 async def publish_example(): client = MQTTClient() await client.connect('mqtt://test.mosquitto.org/') # Publish with QoS 0 (fire and forget) await client.publish('sensors/temperature', b'23.5') # Publish with QoS 1 (at least once delivery) await client.publish('sensors/humidity', b'65', qos=QOS_1) # Publish with QoS 2 (exactly once delivery) await client.publish('sensors/pressure', b'1013.25', qos=QOS_2) # Publish with retain flag await client.publish('status/device1', b'online', qos=QOS_1, retain=True) # Publish multiple messages concurrently tasks = [ asyncio.ensure_future(client.publish('a/b', b'MESSAGE_QOS_0')), asyncio.ensure_future(client.publish('a/b', b'MESSAGE_QOS_1', qos=QOS_1)), asyncio.ensure_future(client.publish('a/b', b'MESSAGE_QOS_2', qos=QOS_2)), ] await asyncio.wait(tasks) await client.disconnect() if __name__ == '__main__': asyncio.get_event_loop().run_until_complete(publish_example()) ``` ### Response #### Success Response (PUBACK, PUBREC, PUBCOMP) - **acknowledgment** (dict) - A dictionary containing details of the acknowledgment, specific to the QoS level. #### Response Example (Responses depend on QoS level; for QoS 1, a PUBACK is received. For QoS 2, PUBREC and PUBCOMP are involved.) ``` -------------------------------- ### Subscribe to a topic pattern Source: https://github.com/njouanin/hbmqtt/blob/master/docs/quickstart.rst Subscribe to messages on a topic pattern using `hbmqtt_sub`. This command will run indefinitely, printing all received messages to standard output. ```bash $ hbmqtt_sub --url mqtt://localhost -t /test/# ``` -------------------------------- ### Unsubscribe from MQTT Topics Source: https://context7.com/njouanin/hbmqtt/llms.txt Shows how to unsubscribe from previously subscribed topics using the `unsubscribe` method. ```python import asyncio from hbmqtt.client import MQTTClient from hbmqtt.mqtt.constants import QOS_1 async def unsubscribe_example(): client = MQTTClient() await client.connect('mqtt://test.mosquitto.org/') # Subscribe to topics await client.subscribe([ ('topic/one', QOS_1), ('topic/two', QOS_1), ('topic/three/#', QOS_1), ]) # Process some messages... # Unsubscribe from specific topics await client.unsubscribe(['topic/one', 'topic/two', 'topic/three/#']) await client.disconnect() if __name__ == '__main__': asyncio.get_event_loop().run_until_complete(unsubscribe_example()) ``` -------------------------------- ### Publish Message with hbmqtt_pub Source: https://context7.com/njouanin/hbmqtt/llms.txt Publishes a message to a specified topic using the hbmqtt_pub command-line tool. Supports various options for URL, topic, message content, and Quality of Service (QoS). ```bash # Publish a message to a topic $ hbmqtt_pub --url mqtt://localhost -t /test -m "Hello World" # Publish with QoS 1 $ hbmqtt_pub --url mqtt://localhost -t /test -m "Important message" -q 1 # Publish from stdin $ echo "data from pipe" | hbmqtt_pub --url mqtt://localhost -t /test -l # Publish via WebSocket $ hbmqtt_pub --url ws://localhost:8080 -t /test -m "WebSocket message" # Secure connection $ hbmqtt_pub --url mqtts://localhost:8883 -t /test -m "Secure" --cafile ca.crt ``` -------------------------------- ### Publish via secure websocket with headers Source: https://github.com/njouanin/hbmqtt/blob/master/docs/references/hbmqtt_pub.rst Sends a message to a specific topic over a WSS connection, including QoS level and authorization headers. ```bash hbmqtt_pub --url wss://localhost -t sensors/temperature -m 32 -q 1 --extra-headers '{"Authorization": "Bearer "}' ``` -------------------------------- ### MQTTClient Methods Source: https://github.com/njouanin/hbmqtt/blob/master/docs/references/mqttclient.rst Core methods available in the hbmqtt.client.MQTTClient class for managing MQTT connections and message flow. ```APIDOC ## MQTTClient Methods ### Description The MQTTClient class provides methods to interact with an MQTT broker, including connection management, publishing, and subscription handling. ### Methods - **connect**: Establishes a connection to the MQTT broker. - **disconnect**: Closes the connection to the MQTT broker. - **reconnect**: Attempts to re-establish a connection to the broker. - **ping**: Sends a PINGREQ packet to the broker. - **publish**: Publishes a message to a specific topic. - **subscribe**: Subscribes to one or more topics. - **unsubscribe**: Unsubscribes from one or more topics. - **deliver_message**: Handles the delivery of incoming messages. ``` -------------------------------- ### Publish message from stdin Source: https://github.com/njouanin/hbmqtt/blob/master/docs/quickstart.rst Use `hbmqtt_pub` to publish messages where the payload is read from standard input. The `-l` flag indicates that the message payload should be read from stdin. ```bash $ some_command | hbmqtt_pub --url mqtt://localhost -t /test -l ``` -------------------------------- ### Publish MQTT Messages Source: https://context7.com/njouanin/hbmqtt/llms.txt Sends messages to a topic with specified QoS levels (0, 1, 2) and the retain flag. Supports concurrent publishing. ```python import asyncio from hbmqtt.client import MQTTClient from hbmqtt.mqtt.constants import QOS_0, QOS_1, QOS_2 async def publish_example(): client = MQTTClient() await client.connect('mqtt://test.mosquitto.org/') # Publish with QoS 0 (fire and forget) await client.publish('sensors/temperature', b'23.5') # Publish with QoS 1 (at least once delivery) await client.publish('sensors/humidity', b'65', qos=QOS_1) # Publish with QoS 2 (exactly once delivery) await client.publish('sensors/pressure', b'1013.25', qos=QOS_2) # Publish with retain flag await client.publish('status/device1', b'online', qos=QOS_1, retain=True) # Publish multiple messages concurrently tasks = [ asyncio.ensure_future(client.publish('a/b', b'MESSAGE_QOS_0')), asyncio.ensure_future(client.publish('a/b', b'MESSAGE_QOS_1', qos=QOS_1)), asyncio.ensure_future(client.publish('a/b', b'MESSAGE_QOS_2', qos=QOS_2)), ] await asyncio.wait(tasks) await client.disconnect() if __name__ == '__main__': asyncio.get_event_loop().run_until_complete(publish_example()) ``` -------------------------------- ### MQTTClient.subscribe Source: https://context7.com/njouanin/hbmqtt/llms.txt Subscribes to one or more topic patterns with specified QoS levels. ```APIDOC ## MQTTClient.subscribe ### Description Subscribes to one or more topic patterns with specified QoS levels. Topic patterns can include wildcards: `+` for single-level matching and `#` for multi-level matching. The method returns the SUBACK return codes indicating the granted QoS for each subscription. ### Method `subscribe` ### Endpoint N/A (This is a client method, not a server endpoint) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python import asyncio from hbmqtt.client import MQTTClient from hbmqtt.mqtt.constants import QOS_1, QOS_2 async def subscribe_example(): client = MQTTClient() await client.connect('mqtt://test.mosquitto.org/') # Subscribe to multiple topics with different QoS levels await client.subscribe([ ('$SYS/broker/uptime', QOS_1), # Broker uptime ('$SYS/broker/load/#', QOS_2), # All load metrics (wildcard) ('sensors/+/temperature', QOS_1), # Temperature from any sensor ]) print("Subscribed to topics") await client.disconnect() if __name__ == '__main__': asyncio.get_event_loop().run_until_complete(subscribe_example()) ``` ### Response #### Success Response (SUBACK) - **granted_qos_levels** (list) - A list of integers representing the granted QoS level for each subscribed topic. #### Response Example (Example: `[1, 2, 1]` corresponding to the QoS levels requested in the subscription.) ``` -------------------------------- ### ApplicationMessage Classes Source: https://github.com/njouanin/hbmqtt/blob/master/docs/references/common.rst Details on the ApplicationMessage, IncomingApplicationMessage, and OutgoingApplicationMessage classes used within HBMQTT. ```APIDOC ## ApplicationMessage API ### Description Provides details on the base `ApplicationMessage` class and its derived classes for handling MQTT messages. ### Classes #### `ApplicationMessage` This is the base class for all application messages. **Members:** - `topic` (string): The topic of the message. - `payload` (bytes): The message payload. - `qos` (int): The Quality of Service level. - `retain` (bool): The retain flag. #### `IncomingApplicationMessage` Represents a message received by the broker or client. **Inheritance:** Inherits from `ApplicationMessage`. #### `OutgoingApplicationMessage` Represents a message to be sent by the broker or client. **Inheritance:** Inherits from `ApplicationMessage`. ``` -------------------------------- ### Integrate Piwik Tracking in Jinja2 Footer Source: https://github.com/njouanin/hbmqtt/blob/master/docs/_templates/layout.html Overrides the footer block in the documentation layout to inject Piwik tracking code. Requires the Piwik server URL and site ID to be configured correctly. ```jinja2 {% extends "!layout.html" %} {% block footer %} {{ super() }} var _paq = _paq || []; _paq.push(['trackPageView']); _paq.push(['enableLinkTracking']); (function() { var u="//piwik.beerfactory.org/"; _paq.push(['setTrackerUrl', u+'piwik.php']); _paq.push(['setSiteId', 6]); var d=document, g=d.createElement('script'), s=d.getElementsByTagName('script')[0]; g.type='text/javascript'; g.async=true; g.defer=true; g.src=u+'piwik.js'; s.parentNode.insertBefore(g,s); })(); {% endblock %} ``` -------------------------------- ### Broker API Reference Source: https://github.com/njouanin/hbmqtt/blob/master/docs/references/broker.rst Reference for the Broker class methods. ```APIDOC ## Broker API ### Description Reference for the `hbmqtt.broker.Broker` class and its methods. ### Methods #### `Broker.start()` ##### Description Starts the MQTT broker. ##### Method N/A (Internal method called by the broker instance) ##### Endpoint N/A #### `Broker.shutdown()` ##### Description Shuts down the MQTT broker gracefully. ##### Method N/A (Internal method called by the broker instance) ##### Endpoint N/A ```