juham.mqtt¶
Description¶
Classes implementing MQTT publish/subscriber network for Juham.
- class juham.mqtt.JPaho(name='paho')[source]¶
Bases:
JMqtt
MQTT broker implementation based on paho.mqtt.
Creates a paho mosquitto client running on localhost and port 1883.
- app_name = 'juham'¶
- classmethod classattrs_from_dict(attributes)¶
Set class attributes from a dictionary.
- classmethod classattrs_to_dict()¶
Convert class attributes to a dictionary.
- config_folder = 'config'¶
- connect_to_server(host='locahost', port=1883, keepalive=60, bind_address='', clean_start=True, properties=None)[source]¶
Connects the client to the mqtt broker.
- copy()¶
Create and return a copy of the current object.
This method serializes the current object to a dictionary using the to_dict method, creates a new instance of the object’s class, and populates it with the serialized data using the from_dict method.
This method uses class identifier based instantiation (see factory method pattern) to create a new instance of the object, and ‘to_dict’ and ‘from_dict’ methods to initialize object’s state.
- Returns:
A new instance of the object’s class with the same state as the original object.
Example:
john = Human("john") john.height = 1.8 john.age = 62 clone_of_john = john.copy()
- debug(msg, details='')¶
Logs the given debug message to the application log.
- Parameters:
msg (str) – The information message to be logged.
details (str) – Additional detailed information for the message to be logged
- Return type:
None
- deserialize_from_json(f)¶
Load attributes from a JSON file.
- disconnect_from_server()[source]¶
Disconnect from the MQTT broker.
It is up to the sub classes to implement the method.
- error(msg, details='')¶
Logs the given error message to the application log.
- Parameters:
msg (str) – The message to be logged.
details (str) – Additional detailed information for the message to be logged
- Return type:
None
- classmethod find_class(class_id)¶
Given class identifier find the registered class. If no class with the give identifier exists return None.
- Parameters:
class_id (int) – class identifier
- Returns:
class or null if not registered
- Return type:
obj (obj)
- from_dict(data)¶
Update instance attributes from a dictionary.
- classmethod get_class_id()¶
Return the class id of the class. Each class has an unique identifier that can be used for instantiating the class via
Object.instantiate()
method.- Parameters:
cls (class) – class
- Return type:
str
- Returns:
id (int) unique class identifier through which the class can be instantiated by factory method pattern.
- classmethod get_json_file()¶
Generate the JSON file name based on the class name.
The file is created into users home folder.
- info(msg, details='')¶
Logs the given information message to the application log.
- Parameters:
msg (str) – The information message to be logged.
details (str) – Additional detailed information for the message to be logged
- Return type:
None
- classmethod initialize_class()¶
Initialize the class for instantiation, if not initialized already. This method initializes the class identifier and deserializes the public attributes from the specified configuration folder.
- Returns:
returns true if the class was initialized, false implies the class is already initialized in which case the method call has no effect.
- Return type:
bool
- classmethod instantiate(class_id)¶
Given class identifier create the corresponding object. This method implements so called factory method pattern.
- Parameters:
class_id (int) – class identifier
- Returns:
instance of the given class.
- Return type:
obj (obj)
- classmethod instantiate_with_param(class_id, param)¶
Given class identifier and one constructor argument create the corresponding object.
- Parameters:
class_id (
str
|None
) – class identifierparam (
Any
) – class specific constructor parameter
- Returns:
instance of the given class.
- Return type:
obj
- classmethod is_abstract()¶
Check whether the class is abstract or real. Override in the derived sub-classes. The default is False.
- Return type:
bool
- Returns:
True (bool) if abstract
- classmethod load_from_json()¶
Load class attributes from a JSON file.
- on_message(mth)[source]¶
Set the message handler, a method to be called when new messages are published.
- Parameters:
mth (meth) – python method to be called on arrival messages.
- paho_api_version = 1¶
- classmethod parse_args()¶
Parse the startup arguments defined by this class.
- Return type:
None
- publish(topic, msg=None, qos=0, retain=False)[source]¶
Publishes an MQTT message.
This method sends a message to the MQTT broker and publish it to the given topic.
Parameters: msg (str): The topic the message is published to. msg (str): The message to be published.
Raises: ValueError: If the message is not a string or is empty. ConnectionError: If there is a problem connecting to the MQTT broker. MQTTException: If there is an error during the publish operation.
- classmethod register()[source]¶
Register the class to the class database.
Once registered the class can be instantiated by its class identifier. Note that this method is called automatically by the system when the python loads the class. In this method sub classes should prepare themselves for instantiation by initializing their class attributes, for example.
- classmethod register_class(class_id, ctor)¶
Register the given class identifier for identifier based instantiation . This, factory method pattern, as it is called, decouples the actual implementation from the interface. For more information see
instantiate()
method.- Parameters:
class_id (str) – class identifier
ctor (function) – constructor
- classmethod save_to_json()¶
Create class configuration file, if the file does not exist yet.
- serialize_to_json(f)¶
Serialize.
- classmethod set_log(l)¶
Set logger.
- Parameters:
l (logger) – logger object
- Return type:
None
- to_dict()¶
Convert instance attributes to a dictionary.
- warning(msg, details='')¶
Logs the given warning message to the application log.
- Parameters:
msg (str) – The message to be logged.
details (str) – Additional detailed information for the message to be logged
- Return type:
None
- class juham.mqtt.JPaho2(name='paho')[source]¶
Bases:
Client
,JMqtt
MQTT broker implementation based on paho.mqtt Python package. Uses multi-inheritance by subclassing paho.CLient and JMqtt super classes.
- ack(mid, qos)¶
send an acknowledgement for a given message id (stored in
message.mid
). only useful in QoS>=1 andmanual_ack=True
(option of Client)- Return type:
MQTTErrorCode
- app_name = 'juham'¶
- property callback_api_version: CallbackAPIVersion¶
Return the callback API version used for user-callback. See docstring for each user-callback (on_connect, on_publish, …) for details.
This property is read-only.
- classmethod classattrs_from_dict(attributes)¶
Set class attributes from a dictionary.
- classmethod classattrs_to_dict()¶
Convert class attributes to a dictionary.
- config_folder = 'config'¶
- configured = False¶
- connect(host, port=1883, keepalive=60, bind_address='', bind_port=0, clean_start=3, properties=None)¶
Connect to a remote broker. This is a blocking call that establishes the underlying connection and transmits a CONNECT packet. Note that the connection status will not be updated until a CONNACK is received and processed (this requires a running network loop, see loop_start, loop_forever, loop…).
- Parameters:
host (str) – the hostname or IP address of the remote broker.
port (int) – the network port of the server host to connect to. Defaults to 1883. Note that the default port for MQTT over SSL/TLS is 8883 so if you are using tls_set() the port may need providing.
keepalive (int) – Maximum period in seconds between communications with the broker. If no other messages are being exchanged, this controls the rate at which the client will send ping messages to the broker.
clean_start (bool) – (MQTT v5.0 only) True, False or MQTT_CLEAN_START_FIRST_ONLY. Sets the MQTT v5.0 clean_start flag always, never or on the first successful connect only, respectively. MQTT session data (such as outstanding messages and subscriptions) is cleared on successful connect when the clean_start flag is set. For MQTT v3.1.1, the
clean_session
argument of Client should be used for similar result.properties (Properties) – (MQTT v5.0 only) the MQTT v5.0 properties to be sent in the MQTT connect packet.
- Return type:
MQTTErrorCode
- connect_async(host, port=1883, keepalive=60, bind_address='', bind_port=0, clean_start=3, properties=None)¶
Connect to a remote broker asynchronously. This is a non-blocking connect call that can be used with loop_start() to provide very quick start.
Any already established connection will be terminated immediately.
- Parameters:
host (str) – the hostname or IP address of the remote broker.
port (int) – the network port of the server host to connect to. Defaults to 1883. Note that the default port for MQTT over SSL/TLS is 8883 so if you are using tls_set() the port may need providing.
keepalive (int) – Maximum period in seconds between communications with the broker. If no other messages are being exchanged, this controls the rate at which the client will send ping messages to the broker.
clean_start (bool) – (MQTT v5.0 only) True, False or MQTT_CLEAN_START_FIRST_ONLY. Sets the MQTT v5.0 clean_start flag always, never or on the first successful connect only, respectively. MQTT session data (such as outstanding messages and subscriptions) is cleared on successful connect when the clean_start flag is set. For MQTT v3.1.1, the
clean_session
argument of Client should be used for similar result.properties (Properties) – (MQTT v5.0 only) the MQTT v5.0 properties to be sent in the MQTT connect packet.
- Return type:
None
- connect_callback()¶
- Return type:
Callable
[[Union
[Callable
[[Client
,Any
,Dict
[str
,Any
],ReasonCode
,Optional
[Properties
]],None
],Callable
[[Client
,Any
,Dict
[str
,Any
],MQTTErrorCode
],None
],Callable
[[Client
,Any
,ConnectFlags
,ReasonCode
,Optional
[Properties
]],None
]]],Union
[Callable
[[Client
,Any
,Dict
[str
,Any
],ReasonCode
,Optional
[Properties
]],None
],Callable
[[Client
,Any
,Dict
[str
,Any
],MQTTErrorCode
],None
],Callable
[[Client
,Any
,ConnectFlags
,ReasonCode
,Optional
[Properties
]],None
]]]
- connect_fail_callback()¶
- Return type:
Callable
[[Callable
[[Client
,Any
],None
]],Callable
[[Client
,Any
],None
]]
- connect_srv(domain=None, keepalive=60, bind_address='', bind_port=0, clean_start=3, properties=None)¶
Connect to a remote broker.
- Parameters:
domain (str) – the DNS domain to search for SRV records; if None, try to determine local domain name.
properties (keepalive, bind_address, clean_start and) – see connect()
- Return type:
MQTTErrorCode
- property connect_timeout: float¶
Connection establishment timeout in seconds.
This property may not be changed if the connection is already open.
- connect_to_server(host='localhost', port=1883, keepalive=60)[source]¶
Connect to MQTT server
- Parameters:
host (str, optional) – host. Defaults to “localhost”.
port (int, optional) – port. Defaults to 1883.
keepalive (int, optional) – keep alive, in seconds. Defaults to 60.
- copy()¶
Create and return a copy of the current object.
This method serializes the current object to a dictionary using the to_dict method, creates a new instance of the object’s class, and populates it with the serialized data using the from_dict method.
This method uses class identifier based instantiation (see factory method pattern) to create a new instance of the object, and ‘to_dict’ and ‘from_dict’ methods to initialize object’s state.
- Returns:
A new instance of the object’s class with the same state as the original object.
Example:
john = Human("john") john.height = 1.8 john.age = 62 clone_of_john = john.copy()
- debug(msg, details='')¶
Logs the given debug message to the application log.
- Parameters:
msg (str) – The information message to be logged.
details (str) – Additional detailed information for the message to be logged
- Return type:
None
- deserialize_from_json(f)¶
Load attributes from a JSON file.
- disable_logger()¶
Disable logging using standard python logging package. This has no effect on the on_log callback.
- Return type:
None
- disconnect(reasoncode=None, properties=None)¶
Disconnect a connected client from the broker.
- Parameters:
reasoncode (ReasonCode) – (MQTT v5.0 only) a ReasonCode instance setting the MQTT v5.0 reasoncode to be sent with the disconnect packet. It is optional, the receiver then assuming that 0 (success) is the value.
properties (Properties) – (MQTT v5.0 only) a Properties instance setting the MQTT v5.0 properties to be included. Optional - if not set, no properties are sent.
- Return type:
MQTTErrorCode
- disconnect_callback()¶
- Return type:
Callable
[[Union
[Callable
[[Client
,Any
,MQTTErrorCode
],None
],Callable
[[Client
,Any
,Union
[ReasonCode
,int
,None
],Optional
[Properties
]],None
],Callable
[[Client
,Any
,DisconnectFlags
,ReasonCode
,Optional
[Properties
]],None
]]],Union
[Callable
[[Client
,Any
,MQTTErrorCode
],None
],Callable
[[Client
,Any
,Union
[ReasonCode
,int
,None
],Optional
[Properties
]],None
],Callable
[[Client
,Any
,DisconnectFlags
,ReasonCode
,Optional
[Properties
]],None
]]]
- disconnect_from_server()¶
Disconnect from the MQTT broker.
It is up to the sub classes to implement the method.
- enable_bridge_mode()¶
Sets the client in a bridge mode instead of client mode.
Must be called before connect() to have any effect. Requires brokers that support bridge mode.
Under bridge mode, the broker will identify the client as a bridge and not send it’s own messages back to it. Hence a subsciption of # is possible without message loops. This feature also correctly propagates the retain flag on the messages.
Currently Mosquitto and RSMB support this feature. This feature can be used to create a bridge between multiple broker.
- Return type:
None
- enable_logger(logger=None)¶
Enables a logger to send log messages to
- Parameters:
logger (logging.Logger) – if specified, that
logging.Logger
object will be used, otherwise one will be created automatically.- Return type:
None
See disable_logger to undo this action.
- error(msg, details='')¶
Logs the given error message to the application log.
- Parameters:
msg (str) – The message to be logged.
details (str) – Additional detailed information for the message to be logged
- Return type:
None
- classmethod find_class(class_id)¶
Given class identifier find the registered class. If no class with the give identifier exists return None.
- Parameters:
class_id (int) – class identifier
- Returns:
class or null if not registered
- Return type:
obj (obj)
- from_dict(data)¶
Update instance attributes from a dictionary.
- classmethod get_class_id()¶
Return the class id of the class. Each class has an unique identifier that can be used for instantiating the class via
Object.instantiate()
method.- Parameters:
cls (class) – class
- Return type:
str
- Returns:
id (int) unique class identifier through which the class can be instantiated by factory method pattern.
- classmethod get_json_file()¶
Generate the JSON file name based on the class name.
The file is created into users home folder.
- host = 'localhost'¶
- info(msg, details='')¶
Logs the given information message to the application log.
- Parameters:
msg (str) – The information message to be logged.
details (str) – Additional detailed information for the message to be logged
- Return type:
None
- classmethod initialize_class()¶
Initialize the class for instantiation, if not initialized already. This method initializes the class identifier and deserializes the public attributes from the specified configuration folder.
- Returns:
returns true if the class was initialized, false implies the class is already initialized in which case the method call has no effect.
- Return type:
bool
- classmethod instantiate(class_id)¶
Given class identifier create the corresponding object. This method implements so called factory method pattern.
- Parameters:
class_id (int) – class identifier
- Returns:
instance of the given class.
- Return type:
obj (obj)
- classmethod instantiate_with_param(class_id, param)¶
Given class identifier and one constructor argument create the corresponding object.
- Parameters:
class_id (
str
|None
) – class identifierparam (
Any
) – class specific constructor parameter
- Returns:
instance of the given class.
- Return type:
obj
- classmethod is_abstract()¶
Check whether the class is abstract or real. Override in the derived sub-classes. The default is False.
- Return type:
bool
- Returns:
True (bool) if abstract
- is_connected()¶
Returns the current status of the connection
True if connection exists False if connection is closed
- Return type:
bool
- property keepalive: int¶
Client keepalive interval (in seconds).
This property may not be changed if the connection is already open.
- classmethod load_from_json()¶
Load class attributes from a JSON file.
- log_callback()¶
- Return type:
Callable
[[Callable
[[Client
,Any
,int
,str
],None
]],Callable
[[Client
,Any
,int
,str
],None
]]
- property logger: Logger | None¶
- loop(timeout=1.0)¶
Process network events.
It is strongly recommended that you use loop_start(), or loop_forever(), or if you are using an external event loop using loop_read(), loop_write(), and loop_misc(). Using loop() on it’s own is no longer recommended.
This function must be called regularly to ensure communication with the broker is carried out. It calls select() on the network socket to wait for network events. If incoming data is present it will then be processed. Outgoing commands, from e.g. publish(), are normally sent immediately that their function is called, but this is not always possible. loop() will also attempt to send any remaining outgoing messages, which also includes commands that are part of the flow for messages with QoS>0.
- Parameters:
timeout (int) – The time in seconds to wait for incoming/outgoing network traffic before timing out and returning.
- Return type:
MQTTErrorCode
Returns MQTT_ERR_SUCCESS on success. Returns >0 on error.
A ValueError will be raised if timeout < 0
- loop_forever(timeout=1.0, retry_first_connection=False)¶
This function calls the network loop functions for you in an infinite blocking loop. It is useful for the case where you only want to run the MQTT client loop in your program.
loop_forever() will handle reconnecting for you if reconnect_on_failure is true (this is the default behavior). If you call disconnect() in a callback it will return.
- Parameters:
timeout (int) – The time in seconds to wait for incoming/outgoing network traffic before timing out and returning.
retry_first_connection (bool) – Should the first connection attempt be retried on failure. This is independent of the reconnect_on_failure setting.
- Raises:
OSError – if the first connection fail unless retry_first_connection=True
- Return type:
MQTTErrorCode
- loop_misc()¶
Process miscellaneous network events. Use in place of calling loop() if you wish to call select() or equivalent on.
Do not use if you are using loop_start() or loop_forever().
- Return type:
MQTTErrorCode
- loop_read(max_packets=1)¶
Process read network events. Use in place of calling loop() if you wish to handle your client reads as part of your own application.
Use socket() to obtain the client socket to call select() or equivalent on.
Do not use if you are using loop_start() or loop_forever().
- Return type:
MQTTErrorCode
- loop_start()¶
This is part of the threaded client interface. Call this once to start a new thread to process network traffic. This provides an alternative to repeatedly calling loop() yourself.
Under the hood, this will call loop_forever in a thread, which means that the thread will terminate if you call disconnect()
- Return type:
MQTTErrorCode
- loop_stop()¶
This is part of the threaded client interface. Call this once to stop the network thread previously created with loop_start(). This call will block until the network thread finishes.
This don’t guarantee that publish packet are sent, use wait_for_publish or on_publish to ensure publish are sent.
- Return type:
MQTTErrorCode
- loop_write()¶
Process write network events. Use in place of calling loop() if you wish to handle your client writes as part of your own application.
Use socket() to obtain the client socket to call select() or equivalent on.
Use want_write() to determine if there is data waiting to be written.
Do not use if you are using loop_start() or loop_forever().
- Return type:
MQTTErrorCode
- manual_ack_set(on)¶
The paho library normally acknowledges messages as soon as they are delivered to the caller. If manual_ack is turned on, then the caller MUST manually acknowledge every message once application processing is complete using ack()
- Return type:
None
- property max_inflight_messages: int¶
Maximum number of messages with QoS > 0 that can be partway through the network flow at once
This property may not be changed if the connection is already open.
- max_inflight_messages_set(inflight)¶
Set the maximum number of messages with QoS>0 that can be part way through their network flow at once. Defaults to 20.
- Return type:
None
- property max_queued_messages: int¶
Maximum number of message in the outgoing message queue, 0 means unlimited
This property may not be changed if the connection is already open.
- max_queued_messages_set(queue_size)¶
Set the maximum number of messages in the outgoing message queue. 0 means unlimited.
- Return type:
Client
- message_callback()¶
- Return type:
Callable
[[Callable
[[Client
,Any
,MQTTMessage
],None
]],Callable
[[Client
,Any
,MQTTMessage
],None
]]
- message_callback_add(sub, callback)¶
Register a message callback for a specific topic. Messages that match ‘sub’ will be passed to ‘callback’. Any non-matching messages will be passed to the default on_message callback.
Call multiple times with different ‘sub’ to define multiple topic specific callbacks.
Topic specific callbacks may be removed with message_callback_remove().
See on_message for the expected signature of the callback.
- Return type:
None
- Decorator: @client.topic_callback(sub) (
client
is the name of the instance which this callback is being attached to)
Example:
@client.topic_callback("mytopic/#") def handle_mytopic(client, userdata, message): ...
- message_callback_remove(sub)¶
Remove a message callback previously registered with message_callback_add().
- Return type:
None
- property on_connect: Callable[[Client, Any, Dict[str, Any], ReasonCode, Properties | None], None] | Callable[[Client, Any, Dict[str, Any], MQTTErrorCode], None] | Callable[[Client, Any, ConnectFlags, ReasonCode, Properties | None], None] | None¶
The callback called when the broker reponds to our connection request.
Expected signature for callback API version 2:
connect_callback(client, userdata, connect_flags, reason_code, properties)
- Expected signature for callback API version 1 change with MQTT protocol version:
For MQTT v3.1 and v3.1.1 it’s:
connect_callback(client, userdata, flags, rc)
For MQTT v5.0 it’s:
connect_callback(client, userdata, flags, reason_code, properties)
- Parameters:
client (Client) – the client instance for this callback
userdata – the private user data as set in Client() or user_data_set()
connect_flags (ConnectFlags) – the flags for this connection
reason_code (ReasonCode) – the connection reason code received from the broken. In MQTT v5.0 it’s the reason code defined by the standard. In MQTT v3, we convert return code to a reason code, see convert_connack_rc_to_reason_code(). ReasonCode may be compared to integer.
properties (Properties) – the MQTT v5.0 properties received from the broker. For MQTT v3.1 and v3.1.1 properties is not provided and an empty Properties object is always used.
flags (dict) – response flags sent by the broker
rc (int) – the connection result, should have a value of ConnackCode
- flags is a dict that contains response flags from the broker:
- flags[‘session present’] - this flag is useful for clients that are
using clean session set to 0 only. If a client with clean session=0, that reconnects to a broker that it has previously connected to, this flag indicates whether the broker still has the session information for the client. If 1, the session still exists.
- The value of rc indicates success or not:
0: Connection successful
1: Connection refused - incorrect protocol version
2: Connection refused - invalid client identifier
3: Connection refused - server unavailable
4: Connection refused - bad username or password
5: Connection refused - not authorised
6-255: Currently unused.
- Decorator: @client.connect_callback() (
client
is the name of the instance which this callback is being attached to)
- property on_connect_fail: Callable[[Client, Any], None] | None¶
The callback called when the client failed to connect to the broker.
Expected signature is (for all callback_api_version):
connect_fail_callback(client, userdata)
- Parameters:
client (Client) – the client instance for this callback
- Parama userdata:
the private user data as set in Client() or user_data_set()
- Decorator: @client.connect_fail_callback() (
client
is the name of the instance which this callback is being attached to)
- property on_disconnect: Callable[[Client, Any, MQTTErrorCode], None] | Callable[[Client, Any, ReasonCode | int | None, Properties | None], None] | Callable[[Client, Any, DisconnectFlags, ReasonCode, Properties | None], None] | None¶
The callback called when the client disconnects from the broker.
Expected signature for callback API version 2:
disconnect_callback(client, userdata, disconnect_flags, reason_code, properties)
- Expected signature for callback API version 1 change with MQTT protocol version:
For MQTT v3.1 and v3.1.1 it’s:
disconnect_callback(client, userdata, rc)
For MQTT v5.0 it’s:
disconnect_callback(client, userdata, reason_code, properties)
- Parameters:
client (Client) – the client instance for this callback
userdata – the private user data as set in Client() or user_data_set()
disconnect_flags (DisconnectFlag) – the flags for this disconnection.
reason_code (ReasonCode) – the disconnection reason code possibly received from the broker (see disconnect_flags). In MQTT v5.0 it’s the reason code defined by the standard. In MQTT v3 it’s never received from the broker, we convert an MQTTErrorCode, see convert_disconnect_error_code_to_reason_code(). ReasonCode may be compared to integer.
properties (Properties) – the MQTT v5.0 properties received from the broker. For MQTT v3.1 and v3.1.1 properties is not provided and an empty Properties object is always used.
rc (int) – the disconnection result The rc parameter indicates the disconnection state. If MQTT_ERR_SUCCESS (0), the callback was called in response to a disconnect() call. If any other value the disconnection was unexpected, such as might be caused by a network error.
- Decorator: @client.disconnect_callback() (
client
is the name of the instance which this callback is being attached to)
- property on_log: Callable[[Client, Any, int, str], None] | None¶
The callback called when the client has log information. Defined to allow debugging.
Expected signature is:
log_callback(client, userdata, level, buf)
- Parameters:
client (Client) – the client instance for this callback
userdata – the private user data as set in Client() or user_data_set()
level (int) – gives the severity of the message and will be one of MQTT_LOG_INFO, MQTT_LOG_NOTICE, MQTT_LOG_WARNING, MQTT_LOG_ERR, and MQTT_LOG_DEBUG.
buf (str) – the message itself
- Decorator: @client.log_callback() (
client
is the name of the instance which this callback is being attached to)
- property on_message: Callable[[Client, Any, MQTTMessage], None] | None¶
The callback called when a message has been received on a topic that the client subscribes to.
This callback will be called for every message received unless a message_callback_add() matched the message.
- Expected signature is (for all callback API version):
message_callback(client, userdata, message)
- Parameters:
client (Client) – the client instance for this callback
userdata – the private user data as set in Client() or user_data_set()
message (MQTTMessage) – the received message. This is a class with members topic, payload, qos, retain.
- Decorator: @client.message_callback() (
client
is the name of the instance which this callback is being attached to)
- property on_pre_connect: Callable[[Client, Any], None] | None¶
The callback called immediately prior to the connection is made request.
Expected signature (for all callback API version):
connect_callback(client, userdata)
- Parama Client client:
the client instance for this callback
- Parama userdata:
the private user data as set in Client() or user_data_set()
- Decorator: @client.pre_connect_callback() (
client
is the name of the instance which this callback is being attached to)
- property on_publish: Callable[[Client, Any, int], None] | Callable[[Client, Any, int, ReasonCode, Properties], None] | None¶
The callback called when a message that was to be sent using the publish() call has completed transmission to the broker.
For messages with QoS levels 1 and 2, this means that the appropriate handshakes have completed. For QoS 0, this simply means that the message has left the client. This callback is important because even if the publish() call returns success, it does not always mean that the message has been sent.
See also wait_for_publish which could be simpler to use.
Expected signature for callback API version 2:
publish_callback(client, userdata, mid, reason_code, properties)
Expected signature for callback API version 1:
publish_callback(client, userdata, mid)
- Parameters:
client (Client) – the client instance for this callback
userdata – the private user data as set in Client() or user_data_set()
mid (int) – matches the mid variable returned from the corresponding publish() call, to allow outgoing messages to be tracked.
reason_code (ReasonCode) – the connection reason code received from the broken. In MQTT v5.0 it’s the reason code defined by the standard. In MQTT v3 it’s always the reason code Success
- Parama Properties properties:
the MQTT v5.0 properties received from the broker. For MQTT v3.1 and v3.1.1 properties is not provided and an empty Properties object is always used.
Note: for QoS = 0, the reason_code and the properties don’t really exist, it’s the client library that generate them. It’s always an empty properties and a success reason code. Because the (MQTTv5) standard don’t have reason code for PUBLISH packet, the library create them at PUBACK packet, as if the message was sent with QoS = 1.
- Decorator: @client.publish_callback() (
client
is the name of the instance which this callback is being attached to)
- property on_socket_close: Callable[[Client, Any, SocketLike], None] | None¶
The callback called just before the socket is closed.
This should be used to unregister the socket from an external event loop for reading.
Expected signature is (for all callback API version):
socket_close_callback(client, userdata, socket)
- Parameters:
client (Client) – the client instance for this callback
userdata – the private user data as set in Client() or user_data_set()
sock (SocketLike) – the socket which is about to be closed.
- Decorator: @client.socket_close_callback() (
client
is the name of the instance which this callback is being attached to)
- property on_socket_open: Callable[[Client, Any, SocketLike], None] | None¶
The callback called just after the socket was opend.
This should be used to register the socket to an external event loop for reading.
Expected signature is (for all callback API version):
socket_open_callback(client, userdata, socket)
- Parameters:
client (Client) – the client instance for this callback
userdata – the private user data as set in Client() or user_data_set()
sock (SocketLike) – the socket which was just opened.
- Decorator: @client.socket_open_callback() (
client
is the name of the instance which this callback is being attached to)
- property on_socket_register_write: Callable[[Client, Any, SocketLike], None] | None¶
The callback called when the socket needs writing but can’t.
This should be used to register the socket with an external event loop for writing.
Expected signature is (for all callback API version):
socket_register_write_callback(client, userdata, socket)
- Parameters:
client (Client) – the client instance for this callback
userdata – the private user data as set in Client() or user_data_set()
sock (SocketLike) – the socket which should be registered for writing
- Decorator: @client.socket_register_write_callback() (
client
is the name of the instance which this callback is being attached to)
- property on_socket_unregister_write: Callable[[Client, Any, SocketLike], None] | None¶
The callback called when the socket doesn’t need writing anymore.
This should be used to unregister the socket from an external event loop for writing.
Expected signature is (for all callback API version):
socket_unregister_write_callback(client, userdata, socket)
- Parameters:
client (Client) – the client instance for this callback
userdata – the private user data as set in Client() or user_data_set()
sock (SocketLike) – the socket which should be unregistered for writing
- Decorator: @client.socket_unregister_write_callback() (
client
is the name of the instance which this callback is being attached to)
- property on_subscribe: Callable[[Client, Any, int, Tuple[int, ...]], None] | Callable[[Client, Any, int, List[ReasonCode], Properties], None] | Callable[[Client, Any, int, List[ReasonCode], Properties | None], None] | None¶
The callback called when the broker responds to a subscribe request.
Expected signature for callback API version 2:
subscribe_callback(client, userdata, mid, reason_code_list, properties)
- Expected signature for callback API version 1 change with MQTT protocol version:
For MQTT v3.1 and v3.1.1 it’s:
subscribe_callback(client, userdata, mid, granted_qos)
For MQTT v5.0 it’s:
subscribe_callback(client, userdata, mid, reason_code_list, properties)
- Parameters:
client (Client) – the client instance for this callback
userdata – the private user data as set in Client() or user_data_set()
mid (int) – matches the mid variable returned from the corresponding subscribe() call.
reason_code_list (list[ReasonCode]) – reason codes received from the broker for each subscription. In MQTT v5.0 it’s the reason code defined by the standard. In MQTT v3, we convert granted QoS to a reason code. It’s a list of ReasonCode instances.
properties (Properties) – the MQTT v5.0 properties received from the broker. For MQTT v3.1 and v3.1.1 properties is not provided and an empty Properties object is always used.
granted_qos (list[int]) – list of integers that give the QoS level the broker has granted for each of the different subscription requests.
- Decorator: @client.subscribe_callback() (
client
is the name of the instance which this callback is being attached to)
- property on_unsubscribe: Callable[[Client, Any, int], None] | Callable[[Client, Any, int, Properties, ReasonCode | List[ReasonCode]], None] | Callable[[Client, Any, int, List[ReasonCode], Properties | None], None] | None¶
The callback called when the broker responds to an unsubscribe request.
Expected signature for callback API version 2:
unsubscribe_callback(client, userdata, mid, reason_code_list, properties)
- Expected signature for callback API version 1 change with MQTT protocol version:
For MQTT v3.1 and v3.1.1 it’s:
unsubscribe_callback(client, userdata, mid)
For MQTT v5.0 it’s:
unsubscribe_callback(client, userdata, mid, properties, v1_reason_codes)
- Parameters:
client (Client) – the client instance for this callback
userdata – the private user data as set in Client() or user_data_set()
mid – matches the mid variable returned from the corresponding unsubscribe() call.
reason_code_list (list[ReasonCode]) – reason codes received from the broker for each unsubscription. In MQTT v5.0 it’s the reason code defined by the standard. In MQTT v3, there is not equivalent from broken and empty list is always used.
properties (Properties) – the MQTT v5.0 properties received from the broker. For MQTT v3.1 and v3.1.1 properties is not provided and an empty Properties object is always used.
v1_reason_codes – the MQTT v5.0 reason codes received from the broker for each unsubscribe topic. A list of ReasonCode instances OR a single ReasonCode when we unsubscribe from a single topic.
- Decorator: @client.unsubscribe_callback() (
client
is the name of the instance which this callback is being attached to)
- paho_version = 2¶
- classmethod parse_args()¶
Parse the startup arguments defined by this class.
- Return type:
None
- property password: str | None¶
The password used to connect to the MQTT broker, or None if no password is used.
This property may not be changed if the connection is already open.
- port = 1883¶
- pre_connect_callback()¶
- Return type:
Callable
[[Callable
[[Client
,Any
],None
]],Callable
[[Client
,Any
],None
]]
- property protocol: MQTTProtocolVersion¶
Protocol version used (MQTT v3, MQTT v3.11, MQTTv5)
This property is read-only.
- proxy_set(**proxy_args)¶
Configure proxying of MQTT connection. Enables support for SOCKS or HTTP proxies.
Proxying is done through the PySocks library. Brief descriptions of the proxy_args parameters are below; see the PySocks docs for more info.
(Required)
- Parameters:
proxy_type – One of {socks.HTTP, socks.SOCKS4, or socks.SOCKS5}
proxy_addr – IP address or DNS name of proxy server
- Return type:
None
(Optional)
- Parameters:
proxy_port – (int) port number of the proxy server. If not provided, the PySocks package default value will be utilized, which differs by proxy_type.
proxy_rdns – boolean indicating whether proxy lookup should be performed remotely (True, default) or locally (False)
proxy_username – username for SOCKS5 proxy, or userid for SOCKS4 proxy
proxy_password – password for SOCKS5 proxy
Example:
mqttc.proxy_set(proxy_type=socks.HTTP, proxy_addr='1.2.3.4', proxy_port=4231)
- publish(topic, payload=None, qos=0, retain=False, properties=None)¶
Publish a message on a topic.
This causes a message to be sent to the broker and subsequently from the broker to any clients subscribing to matching topics.
- Parameters:
topic (str) – The topic that the message should be published on.
payload (
Union
[str
,bytes
,bytearray
,int
,float
,None
]) – The actual message to send. If not given, or set to None a zero length message will be used. Passing an int or float will result in the payload being converted to a string representing that number. If you wish to send a true int/float, use struct.pack() to create the payload you require.qos (int) – The quality of service level to use.
retain (bool) – If set to true, the message will be set as the “last known good”/retained message for the topic.
properties (Properties) – (MQTT v5.0 only) the MQTT v5.0 properties to be included.
- Return type:
MQTTMessageInfo
Returns a MQTTMessageInfo class, which can be used to determine whether the message has been delivered (using is_published()) or to block waiting for the message to be delivered (wait_for_publish()). The message ID and return code of the publish() call can be found at
info.mid
andinfo.rc
.For backwards compatibility, the MQTTMessageInfo class is iterable so the old construct of
(rc, mid) = client.publish(...)
is still valid.rc is MQTT_ERR_SUCCESS to indicate success or MQTT_ERR_NO_CONN if the client is not currently connected. mid is the message ID for the publish request. The mid value can be used to track the publish request by checking against the mid argument in the on_publish() callback if it is defined.
- Raises:
ValueError – if topic is None, has zero length or is invalid (contains a wildcard), except if the MQTT version used is v5.0. For v5.0, a zero length topic can be used when a Topic Alias has been set.
ValueError – if qos is not one of 0, 1 or 2
ValueError – if the length of the payload is greater than 268435455 bytes.
- publish_callback()¶
- Return type:
Callable
[[Union
[Callable
[[Client
,Any
,int
],None
],Callable
[[Client
,Any
,int
,ReasonCode
,Properties
],None
]]],Union
[Callable
[[Client
,Any
,int
],None
],Callable
[[Client
,Any
,int
,ReasonCode
,Properties
],None
]]]
- reconnect()¶
Reconnect the client after a disconnect. Can only be called after connect()/connect_async().
- Return type:
MQTTErrorCode
- reconnect_delay_set(min_delay=1, max_delay=120)¶
Configure the exponential reconnect delay
When connection is lost, wait initially min_delay seconds and double this time every attempt. The wait is capped at max_delay. Once the client is fully connected (e.g. not only TCP socket, but received a success CONNACK), the wait timer is reset to min_delay.
- Return type:
None
- classmethod register()[source]¶
Register the class to the class database.
Once registered the class can be instantiated by its class identifier. Note that this method is called automatically by the system when the python loads the class. In this method sub classes should prepare themselves for instantiation by initializing their class attributes, for example.
- classmethod register_class(class_id, ctor)¶
Register the given class identifier for identifier based instantiation . This, factory method pattern, as it is called, decouples the actual implementation from the interface. For more information see
instantiate()
method.- Parameters:
class_id (str) – class identifier
ctor (function) – constructor
- reinitialise(client_id='', clean_session=True, userdata=None)¶
- Return type:
None
- classmethod save_to_json()¶
Create class configuration file, if the file does not exist yet.
- serialize_to_json(f)¶
Serialize.
- classmethod set_log(l)¶
Set logger.
- Parameters:
l (logger) – logger object
- Return type:
None
- socket()¶
Return the socket or ssl object for this client.
- Return type:
SocketLike
|None
- socket_close_callback()¶
- Return type:
Callable
[[Callable
[[Client
,Any
,SocketLike
],None
]],Callable
[[Client
,Any
,SocketLike
],None
]]
- socket_open_callback()¶
- Return type:
Callable
[[Callable
[[Client
,Any
,SocketLike
],None
]],Callable
[[Client
,Any
,SocketLike
],None
]]
- socket_register_write_callback()¶
- Return type:
Callable
[[Callable
[[Client
,Any
,SocketLike
],None
]],Callable
[[Client
,Any
,SocketLike
],None
]]
- socket_unregister_write_callback()¶
- Return type:
Callable
[[Callable
[[Client
,Any
,SocketLike
],None
]],Callable
[[Client
,Any
,SocketLike
],None
]]
- subscribe(topic, qos=0, options=None, properties=None)¶
Subscribe the client to one or more topics.
This function may be called in three different ways (and a further three for MQTT v5.0):
- Return type:
tuple
[MQTTErrorCode
,int
|None
]
Simple string and integer¶
e.g. subscribe(“my/topic”, 2)
- topic:
A string specifying the subscription topic to subscribe to.
- qos:
The desired quality of service level for the subscription. Defaults to 0.
- options and properties:
Not used.
Simple string and subscribe options (MQTT v5.0 only)¶
e.g. subscribe(“my/topic”, options=SubscribeOptions(qos=2))
- topic:
A string specifying the subscription topic to subscribe to.
- qos:
Not used.
- options:
The MQTT v5.0 subscribe options.
- properties:
a Properties instance setting the MQTT v5.0 properties to be included. Optional - if not set, no properties are sent.
String and integer tuple¶
e.g. subscribe((“my/topic”, 1))
- topic:
A tuple of (topic, qos). Both topic and qos must be present in the tuple.
- qos and options:
Not used.
- properties:
Only used for MQTT v5.0. A Properties instance setting the MQTT v5.0 properties. Optional - if not set, no properties are sent.
String and subscribe options tuple (MQTT v5.0 only)¶
e.g. subscribe((“my/topic”, SubscribeOptions(qos=1)))
- topic:
A tuple of (topic, SubscribeOptions). Both topic and subscribe options must be present in the tuple.
- qos and options:
Not used.
- properties:
a Properties instance setting the MQTT v5.0 properties to be included. Optional - if not set, no properties are sent.
List of string and integer tuples¶
e.g. subscribe([(“my/topic”, 0), (“another/topic”, 2)])
This allows multiple topic subscriptions in a single SUBSCRIPTION command, which is more efficient than using multiple calls to subscribe().
- topic:
A list of tuple of format (topic, qos). Both topic and qos must be present in all of the tuples.
- qos, options and properties:
Not used.
List of string and subscribe option tuples (MQTT v5.0 only)¶
e.g. subscribe([(“my/topic”, SubscribeOptions(qos=0), (“another/topic”, SubscribeOptions(qos=2)])
This allows multiple topic subscriptions in a single SUBSCRIPTION command, which is more efficient than using multiple calls to subscribe().
- topic:
A list of tuple of format (topic, SubscribeOptions). Both topic and subscribe options must be present in all of the tuples.
- qos and options:
Not used.
- properties:
a Properties instance setting the MQTT v5.0 properties to be included. Optional - if not set, no properties are sent.
The function returns a tuple (result, mid), where result is MQTT_ERR_SUCCESS to indicate success or (MQTT_ERR_NO_CONN, None) if the client is not currently connected. mid is the message ID for the subscribe request. The mid value can be used to track the subscribe request by checking against the mid argument in the on_subscribe() callback if it is defined.
Raises a ValueError if qos is not 0, 1 or 2, or if topic is None or has zero string length, or if topic is not a string, tuple or list.
- subscribe_callback()¶
- Return type:
Callable
[[Union
[Callable
[[Client
,Any
,int
,Tuple
[int
,...
]],None
],Callable
[[Client
,Any
,int
,List
[ReasonCode
],Properties
],None
],Callable
[[Client
,Any
,int
,List
[ReasonCode
],Optional
[Properties
]],None
]]],Union
[Callable
[[Client
,Any
,int
,Tuple
[int
,...
]],None
],Callable
[[Client
,Any
,int
,List
[ReasonCode
],Properties
],None
],Callable
[[Client
,Any
,int
,List
[ReasonCode
],Optional
[Properties
]],None
]]]
- tls_insecure_set(value)¶
Configure verification of the server hostname in the server certificate.
If value is set to true, it is impossible to guarantee that the host you are connecting to is not impersonating your server. This can be useful in initial server testing, but makes it possible for a malicious third party to impersonate your server through DNS spoofing, for example.
Do not use this function in a real system. Setting value to true means there is no point using encryption.
Must be called before connect() and after either tls_set() or tls_set_context().
- Return type:
None
- tls_set(ca_certs=None, certfile=None, keyfile=None, cert_reqs=None, tls_version=None, ciphers=None, keyfile_password=None, alpn_protocols=None)¶
Configure network encryption and authentication options. Enables SSL/TLS support.
- Parameters:
ca_certs (str) –
a string path to the Certificate Authority certificate files that are to be treated as trusted by this client. If this is the only option given then the client will operate in a similar manner to a web browser. That is to say it will require the broker to have a certificate signed by the Certificate Authorities in ca_certs and will communicate using TLS v1,2, but will not attempt any form of authentication. This provides basic network encryption but may not be sufficient depending on how the broker is configured.
By default, on Python 2.7.9+ or 3.4+, the default certification authority of the system is used. On older Python version this parameter is mandatory.
certfile (str) – PEM encoded client certificate filename. Used with keyfile for client TLS based authentication. Support for this feature is broker dependent. Note that if the files in encrypted and needs a password to decrypt it, then this can be passed using the keyfile_password argument - you should take precautions to ensure that your password is not hard coded into your program by loading the password from a file for example. If you do not provide keyfile_password, the password will be requested to be typed in at a terminal window.
keyfile (str) – PEM encoded client private keys filename. Used with certfile for client TLS based authentication. Support for this feature is broker dependent. Note that if the files in encrypted and needs a password to decrypt it, then this can be passed using the keyfile_password argument - you should take precautions to ensure that your password is not hard coded into your program by loading the password from a file for example. If you do not provide keyfile_password, the password will be requested to be typed in at a terminal window.
cert_reqs (
VerifyMode
|None
) – the certificate requirements that the client imposes on the broker to be changed. By default this is ssl.CERT_REQUIRED, which means that the broker must provide a certificate. See the ssl pydoc for more information on this parameter.tls_version (
int
|None
) – the version of the SSL/TLS protocol used to be specified. By default TLS v1.2 is used. Previous versions are allowed but not recommended due to possible security problems.ciphers (str) – encryption ciphers that are allowed for this connection, or None to use the defaults. See the ssl pydoc for more information.
- Return type:
None
Must be called before connect(), connect_async() or connect_srv().
- tls_set_context(context=None)¶
Configure network encryption and authentication context. Enables SSL/TLS support.
- Parameters:
context (
SSLContext
|None
) – an ssl.SSLContext object. By default this is given byssl.create_default_context()
, if available.- Return type:
None
Must be called before connect(), connect_async() or connect_srv().
- to_dict()¶
Convert instance attributes to a dictionary.
- topic_callback(sub)¶
- Return type:
Callable
[[Callable
[[Client
,Any
,MQTTMessage
],None
]],Callable
[[Client
,Any
,MQTTMessage
],None
]]
- property transport: Literal['tcp', 'websockets', 'unix']¶
Transport method used for the connection (“tcp” or “websockets”).
This property may not be changed if the connection is already open.
- unsubscribe(topic, properties=None)¶
Unsubscribe the client from one or more topics.
- Parameters:
topic (
str
|list
[str
]) – A single string, or list of strings that are the subscription topics to unsubscribe from.properties (
Properties
|None
) – (MQTT v5.0 only) a Properties instance setting the MQTT v5.0 properties to be included. Optional - if not set, no properties are sent.
- Return type:
tuple
[MQTTErrorCode
,int
|None
]
Returns a tuple (result, mid), where result is MQTT_ERR_SUCCESS to indicate success or (MQTT_ERR_NO_CONN, None) if the client is not currently connected. mid is the message ID for the unsubscribe request. The mid value can be used to track the unsubscribe request by checking against the mid argument in the on_unsubscribe() callback if it is defined.
- Raises:
ValueError – if topic is None or has zero string length, or is not a string or list.
- unsubscribe_callback()¶
- Return type:
Callable
[[Union
[Callable
[[Client
,Any
,int
],None
],Callable
[[Client
,Any
,int
,Properties
,Union
[ReasonCode
,List
[ReasonCode
]]],None
],Callable
[[Client
,Any
,int
,List
[ReasonCode
],Optional
[Properties
]],None
]]],Union
[Callable
[[Client
,Any
,int
],None
],Callable
[[Client
,Any
,int
,Properties
,Union
[ReasonCode
,List
[ReasonCode
]]],None
],Callable
[[Client
,Any
,int
,List
[ReasonCode
],Optional
[Properties
]],None
]]]
- user_data_get()¶
Get the user data variable passed to callbacks. May be any data type.
- Return type:
Any
- user_data_set(userdata)¶
Set the user data variable passed to callbacks. May be any data type.
- Return type:
None
- property username: str | None¶
The username used to connect to the MQTT broker, or None if no username is used.
This property may not be changed if the connection is already open.
- username_pw_set(username, password=None)¶
Set a username and optionally a password for broker authentication.
Must be called before connect() to have any effect. Requires a broker that supports MQTT v3.1 or more.
- Parameters:
username (str) – The username to authenticate with. Need have no relationship to the client id. Must be str [MQTT-3.1.3-11]. Set to None to reset client back to not using username/password for broker authentication.
password (str) – The password to authenticate with. Optional, set to None if not required. If it is str, then it will be encoded as UTF-8.
- Return type:
None
- want_write()¶
Call to determine if there is network data waiting to be written. Useful if you are calling select() yourself rather than using loop(), loop_start() or loop_forever().
- Return type:
bool
- warning(msg, details='')¶
Logs the given warning message to the application log.
- Parameters:
msg (str) – The message to be logged.
details (str) – Additional detailed information for the message to be logged
- Return type:
None
- will_clear()¶
Removes a will that was previously configured with will_set().
Must be called before connect() to have any effect.
- Return type:
None
- property will_payload: bytes | None¶
The payload for the will message that is sent when disconnecting unexpectedly. None if a will shall not be sent.
This property is read-only. Use will_set() to change its value.
- will_set(topic, payload=None, qos=0, retain=False, properties=None)¶
Set a Will to be sent by the broker in case the client disconnects unexpectedly.
This must be called before connect() to have any effect.
- Parameters:
topic (str) – The topic that the will message should be published on.
payload (
Union
[str
,bytes
,bytearray
,int
,float
,None
]) – The message to send as a will. If not given, or set to None a zero length message will be used as the will. Passing an int or float will result in the payload being converted to a string representing that number. If you wish to send a true int/float, use struct.pack() to create the payload you require.qos (int) – The quality of service level to use for the will.
retain (bool) – If set to true, the will message will be set as the “last known good”/retained message for the topic.
properties (Properties) – (MQTT v5.0 only) the MQTT v5.0 properties to be included with the will message. Optional - if not set, no properties are sent.
- Raises:
ValueError – if qos is not 0, 1 or 2, or if topic is None or has zero string length.
- Return type:
None
See will_clear to clear will. Note that will are NOT send if the client disconnect cleanly for example by calling disconnect().
- property will_topic: str | None¶
The topic name a will message is sent to when disconnecting unexpectedly. None if a will shall not be sent.
This property is read-only. Use will_set() to change its value.
- ws_set_options(path='/mqtt', headers=None)¶
Set the path and headers for a websocket connection
- Parameters:
path (str) – a string starting with / which should be the endpoint of the mqtt connection on the remote server
headers (
Union
[Callable
[[Dict
[str
,str
]],Dict
[str
,str
]],Dict
[str
,str
],None
]) – can be either a dict or a callable object. If it is a dict then the extra items in the dict are added to the websocket headers. If it is a callable, then the default websocket headers are passed into this function and the result is used as the new headers.
- Return type:
None