mqtt

mqtt

class platypush.backend.mqtt.MqttBackend(host: Optional[str] = None, port: int = 1883, topic='platypush_bus_mq', subscribe_default_topic: bool = True, tls_cafile: Optional[str] = None, tls_certfile: Optional[str] = None, tls_keyfile: Optional[str] = None, tls_version: Optional[str] = None, tls_ciphers: Optional[str] = None, tls_insecure: bool = False, username: Optional[str] = None, password: Optional[str] = None, client_id: Optional[str] = None, listeners=None, *args, **kwargs)[source]

Backend that reads messages from a configured MQTT topic (default: platypush_bus_mq/<device_id>) and posts them to the application bus.

Triggers:

Requires:

  • paho-mqtt (pip install paho-mqtt)

__init__(host: Optional[str] = None, port: int = 1883, topic='platypush_bus_mq', subscribe_default_topic: bool = True, tls_cafile: Optional[str] = None, tls_certfile: Optional[str] = None, tls_keyfile: Optional[str] = None, tls_version: Optional[str] = None, tls_ciphers: Optional[str] = None, tls_insecure: bool = False, username: Optional[str] = None, password: Optional[str] = None, client_id: Optional[str] = None, listeners=None, *args, **kwargs)[source]
Parameters:
  • host – MQTT broker host. If no host configuration is specified then the backend will use the host configuration specified on the mqtt plugin if it’s available.

  • port – MQTT broker port (default: 1883)

  • topic – Topic to read messages from (default: platypush_bus_mq/<device_id>)

  • subscribe_default_topic – Whether the backend should subscribe the default topic (default: platypush_bus_mq/<device_id>) and execute the messages received there as action requests (default: True).

  • tls_cafile – If TLS/SSL is enabled on the MQTT server and the certificate requires a certificate authority to authenticate it, ssl_cafile will point to the provided ca.crt file (default: None)

  • tls_certfile – If TLS/SSL is enabled on the MQTT server and a client certificate it required, specify it here (default: None)

  • tls_keyfile – If TLS/SSL is enabled on the MQTT server and a client certificate key it required, specify it here (default: None) :type tls_keyfile: str

  • tls_version – If TLS/SSL is enabled on the MQTT server and it requires a certain TLS version, specify it here (default: None). Supported versions: tls (automatic), tlsv1, tlsv1.1, tlsv1.2.

  • tls_ciphers – If TLS/SSL is enabled on the MQTT server and an explicit list of supported ciphers is required, specify it here (default: None)

  • tls_insecure – Set to True to ignore TLS insecure warnings (default: False).

  • username – Specify it if the MQTT server requires authentication (default: None)

  • password – Specify it if the MQTT server requires authentication (default: None)

  • client_id – ID used to identify the client on the MQTT server (default: None). If None is specified then Config.get('device_id') will be used.

  • listeners

    If specified then the MQTT backend will also listen for messages on the additional configured message queues. This parameter is a list of maps where each item supports the same arguments passed to the main backend configuration (host, port, topic, password etc.). Note that the message queue configured on the main configuration will expect valid Platypush messages that then can execute, while message queues registered to the listeners will accept any message. Example:

    listeners:
        - host: localhost
          topics:
              - topic1
              - topic2
              - topic3
        - host: sensors
          topics:
              - topic4
              - topic5
    

property daemon

A boolean value indicating whether this thread is a daemon thread.

This must be set before start() is called, otherwise RuntimeError is raised. Its initial value is inherited from the creating thread; the main thread is not a daemon thread and therefore all threads created in the main thread default to daemon = False.

The entire Python program exits when only daemon threads are left.

getName()

Return a string used for identification purposes only.

This method is deprecated, use the name attribute instead.

property ident

Thread identifier of this thread or None if it has not been started.

This is a nonzero integer. See the get_ident() function. Thread identifiers may be recycled when a thread exits and another thread is created. The identifier is available even after the thread has exited.

isDaemon()

Return whether this thread is a daemon.

This method is deprecated, use the daemon attribute instead.

is_alive()

Return whether the thread is alive.

This method returns True just before the run() method starts until just after the run() method terminates. See also the module function enumerate().

join(timeout=None)

Wait until the thread terminates.

This blocks the calling thread until the thread whose join() method is called terminates – either normally or through an unhandled exception or until the optional timeout occurs.

When the timeout argument is present and not None, it should be a floating point number specifying a timeout for the operation in seconds (or fractions thereof). As join() always returns None, you must call is_alive() after join() to decide whether a timeout happened – if the thread is still alive, the join() call timed out.

When the timeout argument is not present or None, the operation will block until the thread terminates.

A thread can be join()ed many times.

join() raises a RuntimeError if an attempt is made to join the current thread as that would cause a deadlock. It is also an error to join() a thread before it has been started and attempts to do so raises the same exception.

property name

A string used for identification purposes only.

It has no semantics. Multiple threads may be given the same name. The initial name is set by the constructor.

property native_id

Native integral thread ID of this thread, or None if it has not been started.

This is a non-negative integer. See the get_native_id() function. This represents the Thread ID as reported by the kernel.

on_message(msg)

Callback when a message is received on the backend. It parses and posts the message on the main bus. It should be called by the derived classes whenever a new message should be processed.

Parameters:

msg – Received message. It can be either a key-value dictionary, a platypush.message.Message object, or a string/byte UTF-8 encoded string

on_stop()[source]

Callback invoked when the process stops

register_service(port: Optional[int] = None, name: Optional[str] = None, srv_type: Optional[str] = None, srv_name: Optional[str] = None, udp: bool = False, properties: Optional[Dict] = None)

Initialize the Zeroconf service configuration for this backend.

Parameters:
  • port – Service listen port (default: the backend port attribute if available, or None).

  • name – Service short name (default: backend name).

  • srv_type – Service type (default: _platypush-{name}._{proto}.local.).

  • srv_name – Full service name (default: {hostname or device_id}.{type}).

  • udp – Set to True if this is a UDP service.

  • properties

    Extra properties to be passed on the service. Default:

    {
        "name": "Platypush",
        "vendor": "Platypush",
        "version": "{platypush_version}"
    }
    

run()[source]

Starts the backend thread. To be implemented in the derived classes if the loop method isn’t defined.

send_event(event, **kwargs)

Send an event message on the backend.

Parameters:

event – Event to send. It can be a dict, a string/bytes UTF-8 JSON, or a platypush.message.event.Event object.

send_message(msg, topic: Optional[str] = None, **kwargs)[source]

Sends a platypush.message.Message to a node. To be implemented in the derived classes. By default, if the Redis backend is configured then it will try to deliver the message to other consumers through the configured Redis main queue.

Parameters:
  • msg – The message to send

  • queue_name – Send the message on a specific queue (default: the queue_name configured on the Redis backend)

send_request(request, on_response=None, response_timeout=5, **kwargs)

Send a request message on the backend.

Parameters:
  • request – The request, either a dict, a string/bytes UTF-8 JSON, or a platypush.message.request.Request object.

  • on_response (function) – Optional callback that will be called when a response is received. If set, this method will synchronously wait for a response before exiting.

  • response_timeout (float) – If on_response is set, the backend will raise an exception if the response isn’t received within this number of seconds (default: None)

send_response(response, request, **kwargs)

Send a response message on the backend.

Parameters:
  • response – The response, either a dict, a string/bytes UTF-8 JSON, or a platypush.message.response.Response object.

  • request – Associated request, used to set the response parameters that will link them

setDaemon(daemonic)

Set whether this thread is a daemon.

This method is deprecated, use the .daemon property instead.

setName(name)

Set the name string for this thread.

This method is deprecated, use the name attribute instead.

start()

Start the thread’s activity.

It must be called at most once per thread object. It arranges for the object’s run() method to be invoked in a separate thread of control.

This method will raise a RuntimeError if called more than once on the same thread object.

stop()

Stops the backend thread by sending a STOP event on its bus

unregister_service()

Unregister the Zeroconf service configuration if available.

class platypush.backend.mqtt.MqttClient(*args, host: str, port: int, topics: Optional[List[str]] = None, on_message: Optional[Callable] = None, username: Optional[str] = None, password: Optional[str] = None, client_id: Optional[str] = None, tls_cafile: Optional[str] = None, tls_certfile: Optional[str] = None, tls_keyfile: Optional[str] = None, tls_version: Optional = None, tls_ciphers: Optional = None, tls_insecure: bool = False, keepalive: Optional[int] = 60, **kwargs)[source]
__init__(*args, host: str, port: int, topics: Optional[List[str]] = None, on_message: Optional[Callable] = None, username: Optional[str] = None, password: Optional[str] = None, client_id: Optional[str] = None, tls_cafile: Optional[str] = None, tls_certfile: Optional[str] = None, tls_keyfile: Optional[str] = None, tls_version: Optional = None, tls_ciphers: Optional = None, tls_insecure: bool = False, keepalive: Optional[int] = 60, **kwargs)[source]

client_id is the unique client id string used when connecting to the broker. If client_id is zero length or None, then the behaviour is defined by which protocol version is in use. If using MQTT v3.1.1, then a zero length client id will be sent to the broker and the broker will generate a random for the client. If using MQTT v3.1 then an id will be randomly generated. In both cases, clean_session must be True. If this is not the case a ValueError will be raised.

clean_session is a boolean that determines the client type. If True, the broker will remove all information about this client when it disconnects. If False, the client is a persistent client and subscription information and queued messages will be retained when the client disconnects. Note that a client will never discard its own outgoing messages on disconnect. Calling connect() or reconnect() will cause the messages to be resent. Use reinitialise() to reset a client to its original state. The clean_session argument only applies to MQTT versions v3.1.1 and v3.1. It is not accepted if the MQTT version is v5.0 - use the clean_start argument on connect() instead.

userdata is user defined data of any type that is passed as the “userdata” parameter to callbacks. It may be updated at a later point with the user_data_set() function.

The protocol argument allows explicit setting of the MQTT version to use for this client. Can be paho.mqtt.client.MQTTv311 (v3.1.1), paho.mqtt.client.MQTTv31 (v3.1) or paho.mqtt.client.MQTTv5 (v5.0), with the default being v3.1.1.

Set transport to “websockets” to use WebSockets as the transport mechanism. Set to “tcp” to use raw TCP, which is the default.

connect(host, port=1883, keepalive=60, bind_address='', bind_port=0, clean_start=3, properties=None)

Connect to a remote broker.

host is the hostname or IP address of the remote broker. port is 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: 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: (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. properties: (MQTT v5.0 only) the MQTT v5.0 properties to be sent in the MQTT connect packet.

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.

host is the hostname or IP address of the remote broker. port is 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: 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: (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. properties: (MQTT v5.0 only) the MQTT v5.0 properties to be sent in the MQTT connect packet. Use the Properties class.

connect_srv(domain=None, keepalive=60, bind_address='', clean_start=3, properties=None)

Connect to a remote broker.

domain is the DNS domain to search for SRV records; if None, try to determine local domain name. keepalive, bind_address, clean_start and properties are as for connect()

property daemon

A boolean value indicating whether this thread is a daemon thread.

This must be set before start() is called, otherwise RuntimeError is raised. Its initial value is inherited from the creating thread; the main thread is not a daemon thread and therefore all threads created in the main thread default to daemon = False.

The entire Python program exits when only daemon threads are left.

disconnect(reasoncode=None, properties=None)

Disconnect a connected client from the broker. reasoncode: (MQTT v5.0 only) a ReasonCodes instance setting the MQTT v5.0 reasoncode to be sent with the disconnect. It is optional, the receiver then assuming that 0 (success) is the value. 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.

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.

enable_logger(logger=None)

Enables a logger to send log messages to

getName()

Return a string used for identification purposes only.

This method is deprecated, use the name attribute instead.

property ident

Thread identifier of this thread or None if it has not been started.

This is a nonzero integer. See the get_ident() function. Thread identifiers may be recycled when a thread exits and another thread is created. The identifier is available even after the thread has exited.

isDaemon()

Return whether this thread is a daemon.

This method is deprecated, use the daemon attribute instead.

is_alive()

Return whether the thread is alive.

This method returns True just before the run() method starts until just after the run() method terminates. See also the module function enumerate().

is_connected()

Returns the current status of the connection

True if connection exists False if connection is closed

join(timeout=None)

Wait until the thread terminates.

This blocks the calling thread until the thread whose join() method is called terminates – either normally or through an unhandled exception or until the optional timeout occurs.

When the timeout argument is present and not None, it should be a floating point number specifying a timeout for the operation in seconds (or fractions thereof). As join() always returns None, you must call is_alive() after join() to decide whether a timeout happened – if the thread is still alive, the join() call timed out.

When the timeout argument is not present or None, the operation will block until the thread terminates.

A thread can be join()ed many times.

join() raises a RuntimeError if an attempt is made to join the current thread as that would cause a deadlock. It is also an error to join() a thread before it has been started and attempts to do so raises the same exception.

loop(timeout=1.0, max_packets=1)

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.

timeout: The time in seconds to wait for incoming/outgoing network

traffic before timing out and returning.

max_packets: Not currently used.

Returns MQTT_ERR_SUCCESS on success. Returns >0 on error.

A ValueError will be raised if timeout < 0

loop_forever(timeout=1.0, max_packets=1, 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.

timeout: The time in seconds to wait for incoming/outgoing network

traffic before timing out and returning.

max_packets: Not currently used. retry_first_connection: Should the first connection attempt be retried on failure.

This is independent of the reconnect_on_failure setting.

Raises OSError/WebsocketConnectionError on first connection failures unless retry_first_connection=True

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 the threaded interface loop_start().

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 the threaded interface loop_start().

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.

loop_stop(force=False)

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.

The force parameter is currently ignored.

loop_write(max_packets=1)

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 the threaded interface loop_start().

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.

max_queued_messages_set(queue_size)

Set the maximum number of messages in the outgoing message queue. 0 means unlimited.

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().

message_callback_remove(sub)

Remove a message callback previously registered with message_callback_add().

message_retry_set(retry)

No longer used, remove in version 2.0

property name

A string used for identification purposes only.

It has no semantics. Multiple threads may be given the same name. The initial name is set by the constructor.

property native_id

Native integral thread ID of this thread, or None if it has not been started.

This is a non-negative integer. See the get_native_id() function. This represents the Thread ID as reported by the kernel.

property on_connect

If implemented, called when the broker responds to our connection request.

property on_connect_fail

If implemented, called when the client failed to connect to the broker.

property on_disconnect

If implemented, called when the client disconnects from the broker.

property on_log

If implemented, called when the client has log information. Defined to allow debugging.

property on_message

If implemented, called when a message has been received on a topic that the client subscribes to.

This callback will be called for every message received. Use message_callback_add() to define multiple callbacks that will be called for specific topic filters.

property on_publish

If implemented, 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.

property on_socket_close

If implemented, called just before the socket is closed.

property on_socket_open

If implemented, called just after the socket was opend.

property on_socket_register_write

If implemented, called when the socket needs writing but can’t.

property on_socket_unregister_write

If implemented, called when the socket doesn’t need writing anymore.

property on_subscribe

If implemented, called when the broker responds to a subscribe request.

property on_unsubscribe

If implemented, called when the broker responds to an unsubscribe request.

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) proxy_type: One of {socks.HTTP, socks.SOCKS4, or socks.SOCKS5} proxy_addr: IP address or DNS name of proxy server

(Optional) 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

Must be called before connect() or connect_async().

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.

topic: The topic that the message should be published on. payload: 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: The quality of service level to use. retain: If set to true, the message will be set as the “last known good”/retained message for the topic. properties: (MQTT v5.0 only) the MQTT v5.0 properties to be included. Use the Properties class.

Returns a MQTTMessageInfo class, which can be used to determine whether the message has been delivered (using info.is_published()) or to block waiting for the message to be delivered (info.wait_for_publish()). The message ID and return code of the publish() call can be found at info.mid and info.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.

A ValueError will be raised 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.

A ValueError will be raised if qos is not one of 0, 1 or 2, or if the length of the payload is greater than 268435455 bytes.

reconnect()

Reconnect the client after a disconnect. Can only be called after connect()/connect_async().

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.

run()[source]

Method representing the thread’s activity.

You may override this method in a subclass. The standard run() method invokes the callable object passed to the object’s constructor as the target argument, if any, with sequential and keyword arguments taken from the args and kwargs arguments, respectively.

setDaemon(daemonic)

Set whether this thread is a daemon.

This method is deprecated, use the .daemon property instead.

setName(name)

Set the name string for this thread.

This method is deprecated, use the name attribute instead.

socket()

Return the socket or ssl object for this client.

start()

Start the thread’s activity.

It must be called at most once per thread object. It arranges for the object’s run() method to be invoked in a separate thread of control.

This method will raise a RuntimeError if called more than once on the same thread object.

subscribe(*topics, **kwargs)[source]

Client subscription handler.

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().

tls_set(ca_certs=None, certfile=None, keyfile=None, cert_reqs=None, tls_version=None, ciphers=None, keyfile_password=None)

Configure network encryption and authentication options. Enables SSL/TLS support.

ca_certs : 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 and keyfile are strings pointing to the PEM encoded client certificate and private keys respectively. If these arguments are not None then they will be used as client information for TLS based authentication. Support for this feature is broker dependent. Note that if either of these files in encrypted and needs a password to decrypt it, 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 allows 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 allows 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 is a string specifying which encryption ciphers are allowable for this connection, or None to use the defaults. See the ssl pydoc for more information.

Must be called before connect() or connect_async().

tls_set_context(context=None)

Configure network encryption and authentication context. Enables SSL/TLS support.

context : an ssl.SSLContext object. By default this is given by ssl.create_default_context(), if available.

Must be called before connect() or connect_async().

unsubscribe(*topics, **kwargs)[source]

Client unsubscription handler.

user_data_set(userdata)

Set the user data variable passed to callbacks. May be any data type.

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.

username: The username to authenticate with. Need have no relationship to the client id. Must be unicode

[MQTT-3.1.3-11]. Set to None to reset client back to not using username/password for broker authentication.

password: The password to authenticate with. Optional, set to None if not required. If it is unicode, then it

will be encoded as UTF-8.

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().

will_clear()

Removes a will that was previously configured with will_set().

Must be called before connect() to have any effect.

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.

topic: The topic that the will message should be published on. payload: 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: The quality of service level to use for the will. retain: If set to true, the will message will be set as the “last known good”/retained message for the topic. properties: (MQTT v5.0 only) a Properties instance setting the MQTT v5.0 properties to be included with the will message. Optional - if not set, no properties are sent.

Raises a ValueError if qos is not 0, 1 or 2, or if topic is None or has zero string length.

ws_set_options(path='/mqtt', headers=None)

Set the path and headers for a websocket connection

path is a string starting with / which should be the endpoint of the mqtt connection on the remote server

headers 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.