Package: iottalk-paho-mqtt
This document describes the source code for theEclipse PahoMQTT Python client library, which implements versions 5.0, 3.1.1, and 3.1 of the MQTT protocol.This code provides a client class which enable applications to connect to anMQTTbroker to publish messages, and to subscribe to topics and receive published messages. It also provides some helper functions to make publishing one off messages to an MQTT server very straightforward.It supports Python 2.7.9+ or 3.5+.The MQTT protocol is a machine-to-machine (M2M)/”Internet of Things” connectivity protocol. Designed as an extremely lightweight publish/subscribe messaging transport, it is useful for connections with remote locations where a small code footprint is required and/or network bandwidth is at a premium.Paho is anEclipse Foundationproject.ContentsInstallationKnown limitationsUsage and APIClientConstructor / reinitialiseOption functionsConnect / reconnect / disconnectNetwork loopPublishingSubscribe / UnsubscribeCallbacksExternal event loop supportGlobal helper functionsPublishSingleMultipleSubscribeSimpleUsing CallbackReporting bugsMore informationInstallationThe latest stable version is available in the Python Package Index (PyPi) and can be installed usingpip install paho-mqttOr withvirtualenv:virtualenv paho-mqtt
source paho-mqtt/bin/activate
pip install paho-mqttTo obtain the full code, including examples and tests, you can clone the git repository:git clone https://github.com/eclipse/paho.mqtt.pythonOnce you have the code, it can be installed from your repository as well:cd paho.mqtt.python
python setup.py installTo perform all test (including MQTT v5 test), you also need to clone paho.mqtt.testing in paho.mqtt.python folder:git clone https://github.com/eclipse/paho.mqtt.testing.gitKnown limitationsThe following are the known unimplemented MQTT feature.When clean_session is False, the session is only stored in memory not persisted. This means that
when client is restarted (not just reconnected, the object is recreated usually because the
program was restarted) the session is lost. This result in possible message lost.The following part of client session is lost:QoS 2 messages which have been received from the Server, but have not been completely acknowledged.Since the client will blindly acknowledge any PUBCOMP (last message of a QoS 2 transaction), it
won’t hang but will lost this QoS 2 message.QoS 1 and QoS 2 messages which have been sent to the Server, but have not been completely acknowledged.This means that message passed to publish() may be lost. This could be mitigated by taking care
that all message passed to publish() has a corresponding on_publish() call.It also means that the broker may have the Qos2 message in the session. Since the client start
with an empty session it don’t know it and will re-use the mid. This is not yet fixed.Also when clean_session is True, this library will republish QoS > 0 message accross network
reconnection. This means that QoS > 0 message won’t be lost. But the standard say that
if we should discard any message for which the publish packet was sent. Our choice means that
we are not compliant with the standard and it’s possible for QoS 2 to be received twice.
You should you clean_session = False if you need the QoS 2 guarantee of only one delivery.Usage and APIDetailed API documentation is available throughpydoc. Samples are available in theexamplesdirectory.The package provides two modules, a full client and a helper for simple publishing.Getting StartedHere is a very simple example that subscribes to the broker $SYS topic tree and prints out the resulting messages:importpaho.mqtt.clientasmqtt# The callback for when the client receives a CONNACK response from the server.defon_connect(client,userdata,flags,rc):print("Connected with result code "+str(rc))# Subscribing in on_connect() means that if we lose the connection and# reconnect then subscriptions will be renewed.client.subscribe("$SYS/#")# The callback for when a PUBLISH message is received from the server.defon_message(client,userdata,msg):print(msg.topic+" "+str(msg.payload))client=mqtt.Client()client.on_connect=on_connectclient.on_message=on_messageclient.connect("mqtt.eclipse.org",1883,60)# Blocking call that processes network traffic, dispatches callbacks and# handles reconnecting.# Other loop*() functions are available that give a threaded interface and a# manual interface.client.loop_forever()ClientYou can use the client class as an instance, within a class or by subclassing. The general usage flow is as follows:Create a client instanceConnect to a broker using one of theconnect*()functionsCall one of theloop*()functions to maintain network traffic flow with the brokerUsesubscribe()to subscribe to a topic and receive messagesUsepublish()to publish messages to the brokerUsedisconnect()to disconnect from the brokerCallbacks will be called to allow the application to process events as necessary. These callbacks are described below.Constructor / reinitialiseClient()Client(client_id="",clean_session=True,userdata=None,protocol=MQTTv311,transport="tcp")TheClient()constructor takes the following arguments:client_idthe unique client id string used when connecting to the broker. Ifclient_idis zero length orNone, then one will be randomly
generated. In this case theclean_sessionparameter must beTrue.clean_sessiona boolean that determines the client type. IfTrue, the broker will
remove all information about this client when it disconnects. IfFalse,
the client is a durable 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.userdatauser defined data of any type that is passed as theuserdataparameter
to callbacks. It may be updated at a later point with theuser_data_set()function.protocolthe version of the MQTT protocol to use for this client. Can be eitherMQTTv31orMQTTv311transportset to “websockets” to send MQTT over WebSockets. Leave at the default of
“tcp” to use raw TCP.Constructor Exampleimportpaho.mqtt.clientasmqttmqttc=mqtt.Client()reinitialise()reinitialise(client_id="",clean_session=True,userdata=None)Thereinitialise()function resets the client to its starting state as if it had just been created. It takes the same arguments as theClient()constructor.Reinitialise Examplemqttc.reinitialise()Option functionsThese functions represent options that can be set on the client to modify its behaviour. In the majority of cases this must be donebeforeconnecting to a broker.max_inflight_messages_set()max_inflight_messages_set(self,inflight)Set the maximum number of messages with QoS>0 that can be part way through their network flow at once.Defaults to 20. Increasing this value will consume more memory but can increase throughput.max_queued_messages_set()max_queued_messages_set(self,queue_size)Set the maximum number of outgoing messages with QoS>0 that can be pending in the outgoing message queue.Defaults to 0. 0 means unlimited. When the queue is full, any further outgoing messages would be dropped.message_retry_set()message_retry_set(retry)Set the time in seconds before a message with QoS>0 is retried, if the broker does not respond.This is set to 5 seconds by default and should not normally need changing.ws_set_options()ws_set_options(self,path="/mqtt",headers=None)Set websocket connection options. These options will only be used iftransport="websockets"was passed into theClient()constructor.pathThe mqtt path to use on the broker.headersEither a dictionary specifying a list of extra headers which should be appended to the standard websocket headers, or a callable that takes the normal websocket headers and returns a new dictionary with a set of headers to connect to the broker.Must be called beforeconnect*(). An example of how this can be used with the AWS IoT platform is in theexamplesfolder.tls_set()tls_set(ca_certs=None,certfile=None,keyfile=None,cert_reqs=ssl.CERT_REQUIRED,tls_version=ssl.PROTOCOL_TLS,ciphers=None)Configure network encryption and authentication options. Enables SSL/TLS support.ca_certsa 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 inca_certsand will communicate using TLS v1, 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, keyfilestrings pointing to the PEM encoded client certificate and private keys respectively. If these arguments are notNonethen 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, Python will ask for the password at the command line. It is not currently possible to define a callback to provide the password.cert_reqsdefines the certificate requirements that the client imposes on the broker. By default this isssl.CERT_REQUIRED, which means that the broker must provide a certificate. See the ssl pydoc for more information on this parameter.tls_versionspecifies the version of the SSL/TLS protocol to be used. By default (if the python version supports it) the highest TLS version is detected. If unavailable, TLS v1 is used. Previous versions (all versions beginning with SSL) are possible but not recommended due to possible security problems.ciphersa string specifying which encryption ciphers are allowable for this connection, orNoneto use the defaults. See the ssl pydoc for more information.Must be called beforeconnect*().tls_set_context()tls_set_context(context=None)Configure network encryption and authentication context. Enables SSL/TLS support.contextan ssl.SSLContext object. By default, this is given byssl.create_default_context(), if available (added in Python 3.4).If you’re unsure about using this method, then either use the default context, or use thetls_setmethod. See the ssl module documentation section aboutsecurity considerationsfor more information.Must be called beforeconnect*().tls_insecure_set()tls_insecure_set(value)Configure verification of the server hostname in the server certificate.Ifvalueis set toTrue, 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 beforeconnect*()and aftertls_set()ortls_set_context().enable_logger()enable_logger(logger=None)Enable logging using the standard python logging package (See PEP 282). This may be used at the same time as theon_logcallback method.Ifloggeris specified, then thatlogging.Loggerobject will be used, otherwise one will be created automatically.Paho logging levels are converted to standard ones according to the following mapping:PahologgingMQTT_LOG_ERRlogging.ERRORMQTT_LOG_WARNINGlogging.WARNINGMQTT_LOG_NOTICElogging.INFO(no direct equivalent)MQTT_LOG_INFOlogging.INFOMQTT_LOG_DEBUGlogging.DEBUGdisable_logger()disable_logger()Disable logging using standard python logging package. This has no effect on theon_logcallback.username_pw_set()username_pw_set(username,password=None)Set a username and optionally a password for broker authentication. Must be called beforeconnect*().user_data_set()user_data_set(userdata)Set the private user data that will be passed to callbacks when events are generated. Use this for your own purpose to support your application.will_set()will_set(topic,payload=None,qos=0,retain=False)Set a Will to be sent to the broker. If the client disconnects without callingdisconnect(), the broker will publish the message on its behalf.topicthe topic that the will message should be published on.payloadthe message to send as a will. If not given, or set toNonea 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, usestruct.pack()to create the
payload you require.qosthe quality of service level to use for the will.retainif set toTrue, the will message will be set as the “last known
good”/retained message for the topic.Raises aValueErrorifqosis not 0, 1 or 2, or iftopicisNoneor has zero string length.reconnect_delay_setreconnect_delay_set(min_delay=1,max_delay=120)The client will automatically retry connection. Between each attempt
it will wait a number of seconds betweenmin_delayandmax_delay.When the connection is lost, initially the reconnection attempt is delayed ofmin_delayseconds. It’s doubled between subsequent attempt up tomax_delay.The delay is reset tomin_delaywhen the connection complete (e.g. the CONNACK is
received, not just the TCP connection is established).Connect / reconnect / disconnectconnect()connect(host,port=1883,keepalive=60,bind_address="")Theconnect()function connects the client to a broker. This is a blocking
function. It takes the following arguments:hostthe hostname or IP address of the remote brokerportthe 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 usingtls_set()ortls_set_context(), the port may need providing manuallykeepalivemaximum period in seconds allowed 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 brokerbind_addressthe IP address of a local network interface to bind this client to,
assuming multiple interfaces existCallbackWhen the client receives a CONNACK message from the broker in response to the
connect it generates anon_connect()callback.Connect Examplemqttc.connect("mqtt.eclipse.org")connect_async()connect_async(host,port=1883,keepalive=60,bind_address="")Use in conjunction withloop_start()to connect in a non-blocking manner.
The connection will not complete untilloop_start()is called.Callback (connect)When the client receives a CONNACK message from the broker in response to the
connect it generates anon_connect()callback.connect_srv()connect_srv(domain,keepalive=60,bind_address="")Connect to a broker using an SRV DNS lookup to obtain the broker address. Takes
the following arguments:domainthe DNS domain to search for SRV records. IfNone, try to determine the
local domain name.Seeconnect()for a description of thekeepaliveandbind_addressarguments.Callback (connect_srv)When the client receives a CONNACK message from the broker in response to the
connect it generates anon_connect()callback.SRV Connect Examplemqttc.connect_srv("eclipse.org")reconnect()reconnect()Reconnect to a broker using the previously provided details. You must have
calledconnect*()before calling this function.Callback (reconnect)When the client receives a CONNACK message from the broker in response to the
connect it generates anon_connect()callback.disconnect()disconnect()Disconnect from the broker cleanly. Usingdisconnect()will not result in a
will message being sent by the broker.Disconnect will not wait for all queued message to be sent, to ensure all messages
are delivered,wait_for_publish()fromMQTTMessageInfoshould be used.
Seepublish()for details.Callback (disconnect)When the client has sent the disconnect message it generates anon_disconnect()callback.Network loopThese functions are the driving force behind the client. If they are not
called, incoming network data will not be processed and outgoing network data
may not be sent in a timely fashion. There are four options for managing the
network loop. Three are described here, the fourth in “External event loop
support” below. Do not mix the different loop functions.loop()loop(timeout=1.0,max_packets=1)Call regularly to process network events. This call waits inselect()until
the network socket is available for reading or writing, if appropriate, then
handles the incoming/outgoing data. This function blocks for up totimeoutseconds.timeoutmust not exceed thekeepalivevalue for the client or
your client will be regularly disconnected by the broker.Themax_packetsargument is obsolete and should be left unset.Loop Examplerun=Truewhilerun:mqttc.loop()loop_start() / loop_stop()loop_start()loop_stop(force=False)These functions implement a threaded interface to the network loop. Callingloop_start()once, before or afterconnect*(), runs a thread in the
background to callloop()automatically. This frees up the main thread for
other work that may be blocking. This call also handles reconnecting to the
broker. Callloop_stop()to stop the background thread. Theforceargument is currently ignored.Loop Start/Stop Examplemqttc.connect("mqtt.eclipse.org")mqttc.loop_start()whileTrue:temperature=sensor.blocking_read()mqttc.publish("paho/temperature",temperature)loop_forever()loop_forever(timeout=1.0,max_packets=1,retry_first_connection=False)This is a blocking form of the network loop and will not return until the
client callsdisconnect(). It automatically handles reconnecting.Except for the first connection attempt when using connect_async, useretry_first_connection=Trueto make it retry the first connection.
Warning: This might lead to situations where the client keeps connecting to an
non existing host without failing.Thetimeoutandmax_packetsarguments are obsolete and should be left
unset.PublishingSend a message from the client to the broker.publish()publish(topic,payload=None,qos=0,retain=False)This causes a message to be sent to the broker and subsequently from the broker
to any clients subscribing to matching topics. It takes the following
arguments:topicthe topic that the message should be published onpayloadthe actual message to send. If not given, or set toNonea 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, usestruct.pack()to create the payload you requireqosthe quality of service level to useretainif set toTrue, the message will be set as the “last known
good”/retained message for the topic.Returns a MQTTMessageInfo which expose the following attributes and methods:rc, the result of the publishing. It could beMQTT_ERR_SUCCESSto
indicate success,MQTT_ERR_NO_CONNif the client is not currently connected,
orMQTT_ERR_QUEUE_SIZEwhenmax_queued_messages_setis used to indicate
that message is neither queued nor sent.midis 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 theon_publish()callback if it is defined.wait_for_publishmay be easier
depending on your use-case.wait_for_publish()will block until the message is published. It will
raise ValueError if the message is not queued (rc ==MQTT_ERR_QUEUE_SIZE).is_publishedreturns True if the message has been published. It will
raise ValueError if the message is not queued (rc ==MQTT_ERR_QUEUE_SIZE).AValueErrorwill be raised if topic isNone, has zero length or is
invalid (contains a wildcard), ifqosis not one of 0, 1 or 2, or if the
length of the payload is greater than 268435455 bytes.Callback (publish)When the message has been sent to the broker anon_publish()callback will
be generated.Subscribe / Unsubscribesubscribe()subscribe(topic,qos=0)Subscribe the client to one or more topics.This function may be called in three different ways:Simple string and integere.g.subscribe("my/topic",2)topica string specifying the subscription topic to subscribe to.qosthe desired quality of service level for the subscription. Defaults to 0.String and integer tuplee.g.subscribe(("my/topic",1))topica tuple of(topic, qos). Both topic and qos must be present in the tuple.qosnot used.List of string and integer tuplese.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 tosubscribe().topica list of tuple of format(topic, qos). Both topic and qos must be
present in all of the tuples.qosnot used.The function returns a tuple(result, mid), whereresultisMQTT_ERR_SUCCESSto indicate success or(MQTT_ERR_NO_CONN, None)if the
client is not currently connected.midis 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 theon_subscribe()callback if it is defined.Raises aValueErrorifqosis not 0, 1 or 2, or if topic isNoneor
has zero string length, or iftopicis not a string, tuple or list.Callback (subscribe)When the broker has acknowledged the subscription, anon_subscribe()callback will be generated.unsubscribe()unsubscribe(topic)Unsubscribe the client from one or more topics.topica single string, or list of strings that are the subscription topics to
unsubscribe from.Returns a tuple(result, mid), whereresultisMQTT_ERR_SUCCESSto
indicate success, or(MQTT_ERR_NO_CONN, None)if the client is not
currently connected.midis 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 theon_unsubscribe()callback if it is defined.Raises aValueErroriftopicisNoneor has zero string length, or
is not a string or list.Callback (unsubscribe)When the broker has acknowledged the unsubscribe, anon_unsubscribe()callback will be generated.Callbackson_connect()on_connect(client,userdata,flags,rc)Called when the broker responds to our connection request.clientthe client instance for this callbackuserdatathe private user data as set inClient()oruser_data_set()flagsresponse flags sent by the brokerrcthe connection resultflags is a dict that contains response flags from the broker:flags[‘session present’] - this flag is useful for clients that areusing 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.On Connect Exampledefon_connect(client,userdata,flags,rc):print("Connection returned result: "+connack_string(rc))mqttc.on_connect=on_connect...on_disconnect()on_disconnect(client,userdata,rc)Called when the client disconnects from the broker.clientthe client instance for this callbackuserdatathe private user data as set inClient()oruser_data_set()rcthe disconnection resultThe rc parameter indicates the disconnection state. IfMQTT_ERR_SUCCESS(0), the callback was called in response to adisconnect()call. If any
other value the disconnection was unexpected, such as might be caused by a
network error.On Disconnect Exampledefon_disconnect(client,userdata,rc):ifrc!=0:print("Unexpected disconnection.")mqttc.on_disconnect=on_disconnect...on_message()on_message(client,userdata,message)Called when a message has been received on a topic that the client subscribes
to and the message does not match an existing topic filter callback.
Usemessage_callback_add()to define a callback that will be called for
specific topic filters.on_messagewill serve as fallback when none matched.clientthe client instance for this callbackuserdatathe private user data as set inClient()oruser_data_set()messagean instance of MQTTMessage. This is a class with memberstopic,payload,qos,retain.On Message Exampledefon_message(client,userdata,message):print("Received message '"+str(message.payload)+"' on topic '"+message.topic+"' with QoS "+str(message.qos))mqttc.on_message=on_message...message_callback_add()This function allows you to define callbacks that handle incoming messages for
specific subscription filters, including with wildcards. This lets you, for
example, subscribe tosensors/#and have one callback to handlesensors/temperatureand another to handlesensors/humidity.message_callback_add(sub,callback)subthe subscription filter to match against for this callback. Only one
callback may be defined per literal sub stringcallbackthe callback to be used. Takes the same form as theon_messagecallback.If usingmessage_callback_add()andon_message, only messages that do
not match a subscription specific filter will be passed to theon_messagecallback.If multiple sub match a topic, each callback will be called (e.g. subsensors/#and sub+/humidityboth match a message with a topicsensors/humidity, so both
callbacks will handle this message).message_callback_remove()Remove a topic/subscription specific callback previously registered usingmessage_callback_add().message_callback_remove(sub)subthe subscription filter to removeon_publish()on_publish(client,userdata,mid)Called when a message that was to be sent using thepublish()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. Themidvariable matches
the mid variable returned from the correspondingpublish()call, to allow
outgoing messages to be tracked.This callback is important because even if the publish() call returns success,
it does not always mean that the message has been sent.on_subscribe()on_subscribe(client,userdata,mid,granted_qos)Called when the broker responds to a subscribe request. Themidvariable
matches the mid variable returned from the correspondingsubscribe()call.
Thegranted_qosvariable is a list of integers that give the QoS level the
broker has granted for each of the different subscription requests.on_unsubscribe()on_unsubscribe(client,userdata,mid)Called when the broker responds to an unsubscribe request. Themidvariable
matches the mid variable returned from the correspondingunsubscribe()call.on_log()on_log(client,userdata,level,buf)Called when the client has log information. Define to allow debugging. Thelevelvariable gives the severity of the message and will be one ofMQTT_LOG_INFO,MQTT_LOG_NOTICE,MQTT_LOG_WARNING,MQTT_LOG_ERR,
andMQTT_LOG_DEBUG. The message itself is inbuf.This may be used at the same time as the standard Python logging, which can be
enabled via theenable_loggermethod.on_socket_open()on_socket_open(client, userdata, sock)Called when the socket has been opened.
Use this to register the socket with an external event loop for reading.on_socket_close()on_socket_close(client, userdata, sock)Called when the socket is about to be closed.
Use this to unregister a socket from an external event loop for reading.on_socket_register_write()on_socket_register_write(client, userdata, sock)Called when a write operation to the socket failed because it would have blocked, e.g. output buffer full.
Use this to register the socket with an external event loop for writing.on_socket_unregister_write()on_socket_unregister_write(client, userdata, sock)Called when a write operation to the socket succeeded after it had previously failed.
Use this to unregister the socket from an external event loop for writing.External event loop supportloop_read()loop_read(max_packets=1)Call when the socket is ready for reading.max_packetsis obsolete and
should be left unset.loop_write()loop_write(max_packets=1)Call when the socket is ready for writing.max_packetsis obsolete and
should be left unset.loop_misc()loop_misc()Call every few seconds to handle message retrying and pings.socket()socket()Returns the socket object in use in the client to allow interfacing with other
event loops.
This call is particularly useful forselectbased loops. Seeexamples/loop_select.py.want_write()want_write()Returns true if there is data waiting to be written, to allow interfacing the
client with other event loops.
This call is particularly useful forselectbased loops. Seeexamples/loop_select.py.state callbackson_socket_open
on_socket_close
on_socket_register_write
on_socket_unregister_writeUse these callbacks to get notified about state changes in the socket.
This is particularly useful for event loops where you register or unregister a socket
for reading+writing. Seeexamples/loop_asyncio.pyfor an example.When the socket is opened,on_socket_openis called.
Register the socket with your event loop for reading.When the socket is about to be closed,on_socket_closeis called.
Unregister the socket from your event loop for reading.When a write to the socket failed because it would have blocked, e.g. output buffer full,on_socket_register_writeis called.
Register the socket with your event loop for writing.When the next write to the socket succeeded,on_socket_unregister_writeis called.
Unregister the socket from your event loop for writing.The callbacks are always called in this order:on_socket_openZero or more times:on_socket_register_writeon_socket_unregister_writeon_socket_closeGlobal helper functionsThe client module also offers some global helper functions.topic_matches_sub(sub, topic)can be used to check whether atopicmatches asubscription.For example:the topicfoo/barwould match the subscriptionfoo/#or+/barthe topicnon/matchingwould not match the subscriptionnon/+/+connack_string(connack_code)returns the error string associated with a
CONNACK result.error_string(mqtt_errno)returns the error string associated with a Paho
MQTT error number.PublishThis module provides some helper functions to allow straightforward publishing
of messages in a one-shot manner. In other words, they are useful for the
situation where you have a single/multiple messages you want to publish to a
broker, then disconnect with nothing else required.The two functions provided aresingle()andmultiple().SinglePublish a single message to a broker, then disconnect cleanly.single(topic,payload=None,qos=0,retain=False,hostname="localhost",port=1883,client_id="",keepalive=60,will=None,auth=None,tls=None,protocol=mqtt.MQTTv311,transport="tcp")Publish Single Function argumentstopicthe only required argument must be the topic string to which the payload
will be published.payloadthe payload to be published. If “” or None, a zero length payload will be
published.qosthe qos to use when publishing,  default to 0.retainset the message to be retained (True) or not (False).hostnamea string containing the address of the broker to connect to. Defaults to
localhost.portthe port to connect to the broker on. Defaults to 1883.client_idthe MQTT client id to use. If “” or None, the Paho library will
generate a client id automatically.keepalivethe keepalive timeout value for the client. Defaults to 60 seconds.willa dict containing will parameters for the client:will = {‘topic’: “<topic>”, ‘payload’:”<payload”>, ‘qos’:<qos>, ‘retain’:<retain>}.Topic is required, all other parameters are optional and will default to
None, 0 and False respectively.Defaults to None, which indicates no will should be used.autha dict containing authentication parameters for the client:auth = {‘username’:”<username>”, ‘password’:”<password>”}Username is required, password is optional and will default to None if not provided.Defaults to None, which indicates no authentication is to be used.tlsa dict containing TLS configuration parameters for the client:dict = {‘ca_certs’:”<ca_certs>”, ‘certfile’:”<certfile>”, ‘keyfile’:”<keyfile>”, ‘tls_version’:”<tls_version>”, ‘ciphers’:”<ciphers”>}ca_certs is required, all other parameters are optional and will default to None if not provided, which results in the client using the default behaviour - see the paho.mqtt.client documentation.Defaults to None, which indicates that TLS should not be used.protocolchoose the version of the MQTT protocol to use. Use eitherMQTTv31orMQTTv311.transportset to “websockets” to send MQTT over WebSockets. Leave at the default of
“tcp” to use raw TCP.Publish Single Exampleimportpaho.mqtt.publishaspublishpublish.single("paho/test/single","payload",hostname="mqtt.eclipse.org")MultiplePublish multiple messages to a broker, then disconnect cleanly.multiple(msgs,hostname="localhost",port=1883,client_id="",keepalive=60,will=None,auth=None,tls=None,protocol=mqtt.MQTTv311,transport="tcp")Publish Multiple Function argumentsmsgsa list of messages to publish. Each message is either a dict or a tuple.If a dict, only the topic must be present. Default values will be
used for any missing arguments. The dict must be of the form:msg = {‘topic’:”<topic>”, ‘payload’:”<payload>”, ‘qos’:<qos>, ‘retain’:<retain>}topic must be present and may not be empty.
If payload is “”, None or not present then a zero length payload will be published. If qos is not present, the default of 0 is used. If retain is not present, the default of False is used.If a tuple, then it must be of the form:(“<topic>”, “<payload>”, qos, retain)Seesingle()for the description ofhostname,port,client_id,keepalive,will,auth,tls,protocol,transport.Publish Multiple Exampleimportpaho.mqtt.publishaspublishmsgs=[{'topic':"paho/test/multiple",'payload':"multiple 1"},("paho/test/multiple","multiple 2",0,False)]publish.multiple(msgs,hostname="mqtt.eclipse.org")SubscribeThis module provides some helper functions to allow straightforward subscribing
and processing of messages.The two functions provided aresimple()andcallback().SimpleSubscribe to a set of topics and return the messages received. This is a
blocking function.simple(topics,qos=0,msg_count=1,retained=False,hostname="localhost",port=1883,client_id="",keepalive=60,will=None,auth=None,tls=None,protocol=mqtt.MQTTv311)Simple Subscribe Function argumentstopicsthe only required argument is the topic string to which the client will
subscribe. This can either be a string or a list of strings if multiple
topics should be subscribed to.qosthe qos to use when subscribing, defaults to 0.msg_countthe number of messages to retrieve from the broker. Defaults to 1. If 1, a
single MQTTMessage object will be returned. If >1, a list of MQTTMessages
will be returned.retainedset to True to consider retained messages, set to False to ignore messages
with the retained flag set.hostnamea string containing the address of the broker to connect to. Defaults to localhost.portthe port to connect to the broker on. Defaults to 1883.client_idthe MQTT client id to use. If “” or None, the Paho library will
generate a client id automatically.keepalivethe keepalive timeout value for the client. Defaults to 60 seconds.willa dict containing will parameters for the client:will = {‘topic’: “<topic>”, ‘payload’:”<payload”>, ‘qos’:<qos>, ‘retain’:<retain>}.Topic is required, all other parameters are optional and will default to
None, 0 and False respectively.Defaults to None, which indicates no will should be used.autha dict containing authentication parameters for the client:auth = {‘username’:”<username>”, ‘password’:”<password>”}Username is required, password is optional and will default to None if not
provided.Defaults to None, which indicates no authentication is to be used.tlsa dict containing TLS configuration parameters for the client:dict = {‘ca_certs’:”<ca_certs>”, ‘certfile’:”<certfile>”, ‘keyfile’:”<keyfile>”, ‘tls_version’:”<tls_version>”, ‘ciphers’:”<ciphers”>}ca_certs is required, all other parameters are optional and will default to
None if not provided, which results in the client using the default
behaviour - see the paho.mqtt.client documentation.Defaults to None, which indicates that TLS should not be used.protocolchoose the version of the MQTT protocol to use. Use eitherMQTTv31orMQTTv311.Simple Exampleimportpaho.mqtt.subscribeassubscribemsg=subscribe.simple("paho/test/simple",hostname="mqtt.eclipse.org")print("%s%s"%(msg.topic,msg.payload))Using CallbackSubscribe to a set of topics and process the messages received using a user
provided callback.callback(callback,topics,qos=0,userdata=None,hostname="localhost",port=1883,client_id="",keepalive=60,will=None,auth=None,tls=None,protocol=mqtt.MQTTv311)Callback Subscribe Function argumentscallbackan “on_message” callback that will be used for each message received, and
of the formdefon_message(client,userdata,message)topicsthe topic string to which the client will subscribe. This can either be a
string or a list of strings if multiple topics should be subscribed to.qosthe qos to use when subscribing, defaults to 0.userdataa user provided object that will be passed to the on_message callback when
a message is received.Seesimple()for the description ofhostname,port,client_id,keepalive,will,auth,tls,protocol.Callback Exampleimportpaho.mqtt.subscribeassubscribedefon_message_print(client,userdata,message):print("%s%s"%(message.topic,message.payload))subscribe.callback(on_message_print,"paho/test/callback",hostname="mqtt.eclipse.org")Reporting bugsPlease report bugs in the issues tracker athttps://github.com/eclipse/paho.mqtt.python/issues.More informationDiscussion of the Paho clients takes place on theEclipse paho-dev mailing list.General questions about the MQTT protocol itself (not this library) are discussed in theMQTT Google Group.There is much more information available via theMQTT community site.Release Process# get in a Python 3 venv
git checkout ib/1.5
python setup.py bdist_wheel
twine upload dist/*

# then get in a Python 2 venv
# and release it