The latest stable version is available in the Python Package Index (PyPi) and can be installed usinghtml
pip install paho-mqtt
示例:
import paho.mqtt.client as mqtt # The callback for when the client receives a CONNACK response from the server. def on_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. def on_message(client, userdata, msg): print(msg.topic+" "+str(msg.payload)) client = mqtt.Client() client.on_connect = on_connect client.on_message = on_message client.connect("iot.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()
You can use the client class as an instance, within a class or by subclassing. The general usage flow is as follows:python
Callbacks will be called to allow the application to process events as necessary. These callbacks are described below.git
Client(client_id="", clean_session=True, userdata=None, protocol=MQTTv311, transport="tcp")
The Client() constructor takes the following arguments:github
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 durable client and subscription information and queued messages will be retained when the client disconnects.web
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.api
Constructor Examplewebsocket
import paho.mqtt.client as mqtt mqttc = mqtt.Client()
Reinitialise Examplesession
reinitialise(client_id="", clean_session=True, userdata=None)
The reinitialise() function resets the client to its starting state as if it had just been created. It takes the same arguments as the Client() constructor.app
mqttc.reinitialise()
These functions represent options that can be set on the client to modify its behaviour. In the majority of cases this must be done before connecting to a broker.dom
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(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(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(self, path="/mqtt", headers=None)
Set websocket connection options. These options will only be used if transport="websockets" was passed into the Client() constructor.
Must be called before connect*(). An example of how this can be used with the AWS IoT platform is in the examples folder.
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.
Must be called before connect*().
tls_set_context(context=None)
Configure network encryption and authentication context. Enables SSL/TLS support.
contextan ssl.SSLContext object. By default, this is given by ssl.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 the tls_set method. See the ssl module documentation section about security considerations for more information.
Must be called before connect*().
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 tls_set() or tls_set_context().
enable_logger(logger=None)
Enable logging using the standard python logging package (See PEP 282). This may be used at the same time as the on_log callback method.
If logger is specified, then that logging.Logger object will be used, otherwise one will be created automatically.
Paho logging levels are converted to standard ones according to the following mapping:
username_pw_set(username, password=None)
Set a username and optionally a password for broker authentication. Must be called before connect*().
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(topic, payload=None, qos=0, retain=False)
Set a Will to be sent to the broker. If the client disconnects without calling disconnect(), the broker will publish the message on its behalf.
Raises a ValueError if qos is not 0, 1 or 2, or if topic is None or has zero string length.
reconnect_delay_set(min_delay=1, max_delay=120)
The client will automatically retry connection. Between each attempt it will wait a number of seconds between min_delay and max_delay.
When the connection is lost, initially the reconnection attempt is delayed of min_delay seconds. It’s doubled between subsequent attempt up to max_delay.
The delay is reset to min_delay when the connection complete (e.g. the CONNACK is received, not just the TCP connection is established).
connect(host, port=1883, keepalive=60, bind_address="")
The connect() function connects the client to a broker. This is a blocking function. It takes the following arguments:
When the client receives a CONNACK message from the broker in response to the connect it generates an on_connect() callback.
mqttc.connect("iot.eclipse.org")
connect_async(host, port=1883, keepalive=60, bind_address="")
Use in conjunction with loop_start() to connect in a non-blocking manner. The connection will not complete until loop_start() is called.
When the client receives a CONNACK message from the broker in response to the connect it generates an on_connect() callback.
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:
See connect() for a description of the keepalive and bind_address arguments.
When the client receives a CONNACK message from the broker in response to the connect it generates an on_connect() callback.
mqttc.connect_srv("eclipse.org")
reconnect()
Reconnect to a broker using the previously provided details. You must have called connect*() before calling this function.
When the client receives a CONNACK message from the broker in response to the connect it generates an on_connect() callback.
disconnect()
Disconnect from the broker cleanly. Using disconnect() 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() from MQTTMessageInfo should be used. See publish() for details.
When the client has sent the disconnect message it generates an on_disconnect() callback.
These 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(timeout=1.0, max_packets=1)
Call regularly to process network events. This call waits in select() until the network socket is available for reading or writing, if appropriate, then handles the incoming/outgoing data. This function blocks for up to timeout seconds. timeout must not exceed the keepalive value for the client or your client will be regularly disconnected by the broker.
The max_packets argument is obsolete and should be left unset.
run = True while run: mqttc.loop()
loop_start() loop_stop(force=False)
These functions implement a threaded interface to the network loop. Calling loop_start() once, before or after connect*(), runs a thread in the background to call loop() automatically. This frees up the main thread for other work that may be blocking. This call also handles reconnecting to the broker. Call loop_stop() to stop the background thread. The force argument is currently ignored.
mqttc.connect("iot.eclipse.org") mqttc.loop_start() while True: temperature = sensor.blocking_read() mqttc.publish("paho/temperature", temperature)
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 calls disconnect(). It automatically handles reconnecting.
Except for the first connection attempt when using connect_async, use retry_first_connection=True to make it retry the first connection. Warning: This might lead to situations where the client keeps connecting to an non existing host without failing.
The timeout and max_packets arguments are obsolete and should be left unset.
Send a message from the client to the broker.
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:
Returns a MQTTMessageInfo which expose the following attributes and methods:
A ValueError will be raised if topic is None, has zero length or is invalid (contains a wildcard), if qos is not one of 0, 1 or 2, or if the length of the payload is greater than 268435455 bytes.
When the message has been sent to the broker an on_publish() callback will be generated.
subscribe(topic, qos=0)
Subscribe the client to one or more topics.
This function may be called in three different ways:
e.g. subscribe("my/topic", 2)
e.g. subscribe(("my/topic", 1))
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().
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.
When the broker has acknowledged the subscription, an on_subscribe() callback will be generated.
unsubscribe(topic)
Unsubscribe the client from one or more topics.
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 a ValueError if topic is None or has zero string length, or is not a string or list.
When the broker has acknowledged the unsubscribe, an on_unsubscribe() callback will be generated.
on_connect(client, userdata, flags, rc)
Called when the broker responds to our connection request.
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.
def on_connect(client, userdata, flags, rc): print("Connection returned result: "+connack_string(rc)) mqttc.on_connect = on_connect ...
on_disconnect(client, userdata, rc)
Called when the client disconnects from the broker.
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.
def on_disconnect(client, userdata, rc): if rc != 0: print("Unexpected disconnection.") mqttc.on_disconnect = on_disconnect ...
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. Use message_callback_add() to define a callback that will be called for specific topic filters. on_message will serve as fallback when none matched.
def on_message(client, userdata, message): print("Received message '" + str(message.payload) + "' on topic '" + message.topic + "' with QoS " + str(message.qos)) mqttc.on_message = on_message ...
This function allows you to define callbacks that handle incoming messages for specific subscription filters, including with wildcards. This lets you, for example, subscribe to sensors/# and have one callback to handlesensors/temperature and another to handle sensors/humidity.
message_callback_add(sub, callback)
If using message_callback_add() and on_message, only messages that do not match a subscription specific filter will be passed to the on_message callback.
If multiple sub match a topic, each callback will be called (e.g. sub sensors/# and sub +/humidity both match a message with a topic sensors/humidity, so both callbacks will handle this message).
Remove a topic/subscription specific callback previously registered using message_callback_add().
message_callback_remove(sub)
on_publish(client, userdata, mid)
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. The mid variable matches the mid variable returned from the corresponding publish() 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(client, userdata, mid, granted_qos)
Called when the broker responds to a subscribe request. The mid variable matches the mid variable returned from the corresponding subscribe() call. The granted_qos variable is a list of integers that give the QoS level the broker has granted for each of the different subscription requests.
on_unsubscribe(client, userdata, mid)
Called when the broker responds to an unsubscribe request. The mid variable matches the mid variable returned from the corresponding unsubscribe() call.
on_log(client, userdata, level, buf)
Called when the client has log information. Define to allow debugging. The level variable 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. The message itself is in buf.
This may be used at the same time as the standard Python logging, which can be enabled via the enable_logger method.
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(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(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(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.
loop_read(max_packets=1)
Call when the socket is ready for reading. max_packets is obsolete and should be left unset.
loop_write(max_packets=1)
Call when the socket is ready for writing. max_packets is obsolete and should be left unset.
loop_misc()
Call every few seconds to handle message retrying and pings.
socket()
Returns the socket object in use in the client to allow interfacing with other event loops. This call is particularly useful for select based loops. See examples/loop_select.py.
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 for select based loops. See examples/loop_select.py.
on_socket_open on_socket_close on_socket_register_write on_socket_unregister_write
Use 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. See examples/loop_asyncio.py for an example.
When the socket is opened, on_socket_open is called. Register the socket with your event loop for reading.
When the socket is about to be closed, on_socket_close is 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_write is called. Register the socket with your event loop for writing.
When the next write to the socket succeeded, on_socket_unregister_write is called. Unregister the socket from your event loop for writing.
The callbacks are always called in this order:
The client module also offers some global helper functions.
topic_matches_sub(sub, topic) can be used to check whether a topic matches a subscription.
For example:
the topic foo/bar would match the subscription foo/# or +/bar
the topic non/matching would not match the subscription non/+/+
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.
This 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 are single() and multiple().
Publish 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")
a 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.
a 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.
a 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.
import paho.mqtt.publish as publish publish.single("paho/test/single", "payload", hostname="iot.eclipse.org")
Publish 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")
a 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)
See single() for the description of hostname, port, client_id, keepalive, will, auth, tls, protocol, transport.
import paho.mqtt.publish as publish msgs = [{'topic':"paho/test/multiple", 'payload':"multiple 1"}, ("paho/test/multiple", "multiple 2", 0, False)] publish.multiple(msgs, hostname="iot.eclipse.org")
This module provides some helper functions to allow straightforward subscribing and processing of messages.
The two functions provided are simple() and callback().
Subscribe 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)
a 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.
a 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.
a 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.
import paho.mqtt.subscribe as subscribe msg = subscribe.simple("paho/test/simple", hostname="iot.eclipse.org") print("%s %s" % (msg.topic, msg.payload))
Subscribe 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)
an 「on_message」 callback that will be used for each message received, and of the form
def on_message(client, userdata, message)
See simple() for the description of hostname, port, client_id, keepalive, will, auth, tls, protocol.
import paho.mqtt.subscribe as subscribe def on_message_print(client, userdata, message): print("%s %s" % (message.topic, message.payload)) subscribe.callback(on_message_print, "paho/test/callback", hostname="iot.eclipse.org")
Please report bugs in the issues tracker at https://github.com/eclipse/paho.mqtt.python/issues.
Discussion of the Paho clients takes place on the Eclipse paho-dev mailing list.
General questions about the MQTT protocol are discussed in the MQTT Google Group.
There is much more information available via the MQTT community site.