MQTT¶
- class nirahmq.mqtt.MQTTClient[source]¶
Bases:
objectNirahMQ MQTT client class
This class is responsible for establishing a connection to the MQTT broker, handles authentication, callback registration and subscription, as well as publishing arbitrary payloads to any MQTT topic.
- __init__(hostname: str, port: int = 1883, username: str | None = None, password: str | None = None, client_id: str = 'nirahmq')[source]¶
Initialize the MQTT client.
Caution
Currently there is no TLS support! Authentication details and messages are sent on plaintext!
- add_callback(topic: str, callback: Callable[[bytes | bytearray], None]) None[source]¶
Register a callback to an MQTT topic.
Subscribes to the specified MQTT topic and registers a user supplied callback to it. See
remove_callback()for how to remove a callback.
- connect() bool[source]¶
Connect to the MQTT broker.
Attempt to connect to the MQTT broker with the configured settings. If the connection was successful, returns True. If the connection failed or the instance is already connected, returns False.
- Returns:
True if the connection was successful
- Return type:
- Raises:
RuntimeError – If the connection was not successful
- disconnect() None[source]¶
Disconnect from the MQTT broker.
Disconnect from the connected MQTT broker. Does nothing if the instance is already disconnected.
- Raises:
RuntimeError – If the connection was not successfully terminated
- publish(topic: str, payload: str | bytes | bytearray | int | float | None, qos: QoS = QoS.MOST, retain: bool = True) None[source]¶
Publish an arbitrary payload to the specified MQTT topic.
Publish an arbitrary payload to the specified MQTT topic. Optionally, set the Quality of Service (QoS) and retain flag for the message.
Does nothing if the instance is not connected to an MQTT broker.
- remove_callback(topic: str) None[source]¶
Unregister a callback to an MQTT topic.
Removes a previously registered callback with
add_callback()and unsubscribes from the associated MQTT topic. Seeadd_callback()for how to add a callback.Note
The instance must be connected to take effect. Does nothing otherwise.
- Parameters:
topic (str) – The topic to remove the callback from
- set_will(topic: str, payload: str) None[source]¶
Set the MQTT Last Will and Testament (LWT) payload and topic.
Set the MQTT topic and payload that the MQTT broker will publish to when the client disconnects unexpectedly.
Note
Must be called before connection. Does nothing otherwise.
- property client_id: str¶
The configured MQTT client ID (read-only).
- Returns:
The configured client ID
- Return type:
- class nirahmq.mqtt.QoS[source]¶
Bases:
IntEnumMQTT Quality of Service (QoS) enumeration class.
- EXACTLY = 2¶
Message is delivered exactly once.
- LEAST = 1¶
Message is delivered at least once.
- MOST = 0¶
Message is delivered at most once.
- mqtt.Topic = Topic¶
A custom type alias used by
nirahmqto validate a string is a valid MQTT topic.