{ "info": { "author": "Roger Light", "author_email": "roger@atchoo.org", "bugtrack_url": null, "classifiers": [ "Development Status :: 4 - Beta", "Intended Audience :: Developers", "License :: OSI Approved", "Natural Language :: English", "Operating System :: MacOS :: MacOS X", "Operating System :: Microsoft :: Windows", "Operating System :: POSIX", "Programming Language :: Python", "Programming Language :: Python :: 2", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.4", "Programming Language :: Python :: 3.5", "Programming Language :: Python :: 3.6", "Topic :: Communications", "Topic :: Internet" ], "description": "Eclipse Paho\u2122 MQTT Python Client\n================================\n\nThis document describes the source code for the `Eclipse Paho `_ MQTT Python client library, which implements versions 3.1 and 3.1.1 of the MQTT protocol.\n\nThis code provides a client class which enable applications to connect to an `MQTT `_ broker 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.\n\nIt supports Python 2.7.9+ or 3.4+, with limited support for Python 2.7 before 2.7.9.\n\nThe 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.\n\nPaho is an `Eclipse Foundation `_ project.\n\n\nContents\n--------\n\n* Installation_\n* `Known limitations`_\n* `Usage and API`_\n * `Client`_\n * `Constructor / reinitialise`_\n * `Option functions`_\n * `Connect / reconnect / disconnect`_\n * `Network loop`_\n * `Publishing`_\n * `Subscribe / Unsubscribe`_\n * `Callbacks`_\n * `External event loop support`_\n * `Global helper functions`_\n * `Publish`_\n * `Single`_\n * `Multiple`_\n * `Subscribe`_\n * `Simple`_\n * `Using Callback`_\n* `Reporting bugs`_\n* `More information`_\n\n\nInstallation\n------------\n\nThe latest stable version is available in the Python Package Index (PyPi) and can be installed using\n\n::\n\n pip install paho-mqtt\n\nOr with ``virtualenv``:\n\n::\n\n virtualenv paho-mqtt\n source paho-mqtt/bin/activate\n pip install paho-mqtt\n\nTo obtain the full code, including examples and tests, you can clone the git repository:\n\n::\n\n git clone https://github.com/eclipse/paho.mqtt.python\n\n\nOnce you have the code, it can be installed from your repository as well:\n\n::\n\n cd paho.mqtt.python\n python setup.py install\n\nKnown limitations\n-----------------\n\nThe following are the known unimplemented MQTT feature.\n\nWhen clean_session is False, the session is only stored in memory not persisted. This means that\nwhen client is restarted (not just reconnected, the object is recreated usually because the\nprogram was restarted) the session is lost. This result in possible message lost.\n\nThe following part of client session is lost:\n\n* QoS 2 messages which have been received from the Server, but have not been completely acknowledged.\n\n Since the client will blindly acknowledge any PUBCOMP (last message of a QoS 2 transaction), it\n won't hang but will lost this QoS 2 message.\n\n* QoS 1 and QoS 2 messages which have been sent to the Server, but have not been completely acknowledged.\n\n This means that message passed to publish() may be lost. This could be mitigated by taking care\n that all message passed to publish() has a corresponding on_publish() call.\n\n It also means that the broker may have the Qos2 message in the session. Since the client start\n with an empty session it don't know it and will re-use the mid. This is not yet fixed.\n\nAlso when clean_session is True, this library will republish QoS > 0 message accross network\nreconnection. This means that QoS > 0 message won't be lost. But the standard say that\nif we should discard any message for which the publish packet was sent. Our choice means that\nwe are not compliant with the standard and it's possible for QoS 2 to be received twice.\nYou should you clean_session = False if you need the QoS 2 guarantee of only one delivery.\n\nUsage and API\n-------------\n\nDetailed API documentation is available through **pydoc**. Samples are available in the **examples** directory.\n\nThe package provides two modules, a full client and a helper for simple publishing.\n\nGetting Started\n***************\n\nHere is a very simple example that subscribes to the broker $SYS topic tree and prints out the resulting messages:\n\n.. code:: python\n\n import paho.mqtt.client as mqtt\n\n # The callback for when the client receives a CONNACK response from the server.\n def on_connect(client, userdata, flags, rc):\n print(\"Connected with result code \"+str(rc))\n\n # Subscribing in on_connect() means that if we lose the connection and\n # reconnect then subscriptions will be renewed.\n client.subscribe(\"$SYS/#\")\n\n # The callback for when a PUBLISH message is received from the server.\n def on_message(client, userdata, msg):\n print(msg.topic+\" \"+str(msg.payload))\n\n client = mqtt.Client()\n client.on_connect = on_connect\n client.on_message = on_message\n\n client.connect(\"iot.eclipse.org\", 1883, 60)\n\n # Blocking call that processes network traffic, dispatches callbacks and\n # handles reconnecting.\n # Other loop*() functions are available that give a threaded interface and a\n # manual interface.\n client.loop_forever()\n\nClient\n******\n\nYou can use the client class as an instance, within a class or by subclassing. The general usage flow is as follows:\n\n* Create a client instance\n* Connect to a broker using one of the ``connect*()`` functions\n* Call one of the ``loop*()`` functions to maintain network traffic flow with the broker\n* Use ``subscribe()`` to subscribe to a topic and receive messages\n* Use ``publish()`` to publish messages to the broker\n* Use ``disconnect()`` to disconnect from the broker\n\nCallbacks will be called to allow the application to process events as necessary. These callbacks are described below.\n\nConstructor / reinitialise\n``````````````````````````\n\nClient()\n''''''''\n\n.. code:: python\n\n Client(client_id=\"\", clean_session=True, userdata=None, protocol=MQTTv311, transport=\"tcp\")\n\nThe ``Client()`` constructor takes the following arguments:\n\nclient_id\n the unique client id string used when connecting to the broker. If\n ``client_id`` is zero length or ``None``, then one will be randomly\n generated. In this case the ``clean_session`` parameter must be ``True``.\n\nclean_session\n a boolean that determines the client type. If ``True``, the broker will\n remove all information about this client when it disconnects. If ``False``,\n the client is a durable client and subscription information and queued\n messages will be retained when the client disconnects.\n\n Note that a client will never discard its own outgoing messages on\n disconnect. Calling connect() or reconnect() will cause the messages to be\n resent. Use reinitialise() to reset a client to its original state.\n\nuserdata\n user defined data of any type that is passed as the ``userdata`` parameter\n to callbacks. It may be updated at a later point with the\n ``user_data_set()`` function.\n\nprotocol\n the version of the MQTT protocol to use for this client. Can be either\n ``MQTTv31`` or ``MQTTv311``\n\ntransport\n set to \"websockets\" to send MQTT over WebSockets. Leave at the default of\n \"tcp\" to use raw TCP.\n\n\nConstructor Example\n...................\n\n.. code:: python\n\n import paho.mqtt.client as mqtt\n\n mqttc = mqtt.Client()\n\n\nreinitialise()\n''''''''''''''\n\n.. code:: python\n\n reinitialise(client_id=\"\", clean_session=True, userdata=None)\n\nThe ``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.\n\nReinitialise Example\n....................\n\n.. code:: python\n\n mqttc.reinitialise()\n\nOption functions\n````````````````\n\nThese 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.\n\nmax_inflight_messages_set()\n'''''''''''''''''''''''''''\n\n.. code:: python\n\n max_inflight_messages_set(self, inflight)\n\nSet the maximum number of messages with QoS>0 that can be part way through their network flow at once.\n\nDefaults to 20. Increasing this value will consume more memory but can increase throughput.\n\nmax_queued_messages_set()\n'''''''''''''''''''''''''\n\n.. code:: python\n\n max_queued_messages_set(self, queue_size)\n\nSet the maximum number of outgoing messages with QoS>0 that can be pending in the outgoing message queue.\n\nDefaults to 0. 0 means unlimited. When the queue is full, any further outgoing messages would be dropped.\n\nmessage_retry_set()\n'''''''''''''''''''\n\n.. code:: python\n\n message_retry_set(retry)\n\nSet the time in seconds before a message with QoS>0 is retried, if the broker does not respond.\n\nThis is set to 5 seconds by default and should not normally need changing.\n\nws_set_options()\n''''''''''''''''\n\n.. code:: python\n\n ws_set_options(self, path=\"/mqtt\", headers=None)\n\nSet websocket connection options. These options will only be used if ``transport=\"websockets\"`` was passed into the ``Client()`` constructor.\n\npath\n The mqtt path to use on the broker.\n\nheaders\n Either 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.\n\nMust be called before ``connect*()``. An example of how this can be used with the AWS IoT platform is in the **examples** folder.\n\n\ntls_set()\n'''''''''\n\n.. code:: python\n\n tls_set(ca_certs=None, certfile=None, keyfile=None, cert_reqs=ssl.CERT_REQUIRED,\n tls_version=ssl.PROTOCOL_TLS, ciphers=None)\n\nConfigure network encryption and authentication options. Enables SSL/TLS support.\n\nca_certs\n 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, 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.\n\ncertfile, keyfile\n 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, Python will ask for the password at the command line. It is not currently possible to define a callback to provide the password.\n\ncert_reqs\n defines the certificate requirements that the client imposes on the broker. 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.\n\ntls_version\n specifies 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.\n\nciphers\n a string specifying which encryption ciphers are allowable for this connection, or ``None`` to use the defaults. See the ssl pydoc for more information.\n\nMust be called before ``connect*()``.\n\ntls_set_context()\n'''''''''''''''''\n\n.. code:: python\n\n tls_set_context(context=None)\n\nConfigure network encryption and authentication context. Enables SSL/TLS support.\n\ncontext\n an ssl.SSLContext object. By default, this is given by ``ssl.create_default_context()``, if available (added in Python 3.4).\n\nIf 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.\n\nMust be called before ``connect*()``.\n\ntls_insecure_set()\n''''''''''''''''''\n\n.. code:: python\n\n tls_insecure_set(value)\n\nConfigure verification of the server hostname in the server certificate.\n\nIf ``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.\n\nDo not use this function in a real system. Setting value to True means there is no point using encryption.\n\nMust be called before ``connect*()`` and after ``tls_set()`` or ``tls_set_context()``.\n\nenable_logger()\n'''''''''''''''\n\n.. code:: python\n\n enable_logger(logger=None)\n\nEnable logging using the standard python logging package (See PEP 282). This may be used at the same time as the ``on_log`` callback method.\n\nIf ``logger`` is specified, then that ``logging.Logger`` object will be used, otherwise one will be created automatically.\n\nPaho logging levels are converted to standard ones according to the following mapping:\n\n==================== ===============\nPaho logging\n==================== ===============\n``MQTT_LOG_ERR`` ``logging.ERROR``\n``MQTT_LOG_WARNING`` ``logging.WARNING``\n``MQTT_LOG_NOTICE`` ``logging.INFO`` *(no direct equivalent)*\n``MQTT_LOG_INFO`` ``logging.INFO``\n``MQTT_LOG_DEBUG`` ``logging.DEBUG``\n==================== ===============\n\ndisable_logger()\n''''''''''''''''\n\n.. code:: python\n\n disable_logger()\n\nDisable logging using standard python logging package. This has no effect on the ``on_log`` callback.\n\nusername_pw_set()\n'''''''''''''''''\n\n.. code:: python\n\n username_pw_set(username, password=None)\n\nSet a username and optionally a password for broker authentication. Must be called before ``connect*()``.\n\nuser_data_set()\n'''''''''''''''\n\n.. code:: python\n\n user_data_set(userdata)\n\nSet the private user data that will be passed to callbacks when events are generated. Use this for your own purpose to support your application.\n\nwill_set()\n''''''''''\n\n.. code:: python\n\n will_set(topic, payload=None, qos=0, retain=False)\n\nSet a Will to be sent to the broker. If the client disconnects without calling\n``disconnect()``, the broker will publish the message on its behalf.\n\ntopic\n the topic that the will message should be published on.\n\npayload\n the message to send as a will. If not given, or set to ``None`` a zero\n length message will be used as the will. Passing an int or float will\n result in the payload being converted to a string representing that number.\n If you wish to send a true int/float, use ``struct.pack()`` to create the\n payload you require.\n\nqos\n the quality of service level to use for the will.\n\nretain\n if set to ``True``, the will message will be set as the \"last known\n good\"/retained message for the topic.\n\nRaises a ``ValueError`` if ``qos`` is not 0, 1 or 2, or if ``topic`` is\n``None`` or has zero string length.\n\nreconnect_delay_set\n'''''''''''''''''''\n\n.. code:: python\n\n reconnect_delay_set(min_delay=1, max_delay=120)\n\nThe client will automatically retry connection. Between each attempt\nit will wait a number of seconds between ``min_delay`` and ``max_delay``.\n\nWhen the connection is lost, initially the reconnection attempt is delayed of\n``min_delay`` seconds. It's doubled between subsequent attempt up to ``max_delay``.\n\nThe delay is reset to ``min_delay`` when the connection complete (e.g. the CONNACK is\nreceived, not just the TCP connection is established).\n\n\nConnect / reconnect / disconnect\n````````````````````````````````\n\nconnect()\n'''''''''\n\n.. code:: python\n\n connect(host, port=1883, keepalive=60, bind_address=\"\")\n\nThe ``connect()`` function connects the client to a broker. This is a blocking\nfunction. It takes the following arguments:\n\nhost\n the hostname or IP address of the remote broker\n\nport\n the network port of the server host to connect to. Defaults to 1883. Note\n that the default port for MQTT over SSL/TLS is 8883 so if you are using\n ``tls_set()`` or ``tls_set_context()``, the port may need providing manually\n\nkeepalive\n maximum period in seconds allowed between communications with the broker.\n If no other messages are being exchanged, this controls the rate at which\n the client will send ping messages to the broker\n\nbind_address\n the IP address of a local network interface to bind this client to,\n assuming multiple interfaces exist\n\nCallback\n........\n\nWhen the client receives a CONNACK message from the broker in response to the\nconnect it generates an ``on_connect()`` callback.\n\nConnect Example\n...............\n\n.. code:: python\n\n mqttc.connect(\"iot.eclipse.org\")\n\nconnect_async()\n'''''''''''''''\n\n.. code:: python\n\n connect_async(host, port=1883, keepalive=60, bind_address=\"\")\n\nUse in conjunction with ``loop_start()`` to connect in a non-blocking manner.\nThe connection will not complete until ``loop_start()`` is called.\n\nCallback (connect)\n..................\n\nWhen the client receives a CONNACK message from the broker in response to the\nconnect it generates an ``on_connect()`` callback.\n\nconnect_srv()\n'''''''''''''\n\n.. code:: python\n\n connect_srv(domain, keepalive=60, bind_address=\"\")\n\nConnect to a broker using an SRV DNS lookup to obtain the broker address. Takes\nthe following arguments:\n\ndomain\n the DNS domain to search for SRV records. If ``None``, try to determine the\n local domain name.\n\nSee ``connect()`` for a description of the ``keepalive`` and ``bind_address``\narguments.\n\nCallback (connect_srv)\n......................\n\nWhen the client receives a CONNACK message from the broker in response to the\nconnect it generates an ``on_connect()`` callback.\n\nSRV Connect Example\n...................\n\n.. code:: python\n\n mqttc.connect_srv(\"eclipse.org\")\n\nreconnect()\n'''''''''''\n\n.. code:: python\n\n reconnect()\n\nReconnect to a broker using the previously provided details. You must have\ncalled ``connect*()`` before calling this function.\n\nCallback (reconnect)\n....................\n\nWhen the client receives a CONNACK message from the broker in response to the\nconnect it generates an ``on_connect()`` callback.\n\ndisconnect()\n''''''''''''\n\n.. code:: python\n\n disconnect()\n\nDisconnect from the broker cleanly. Using ``disconnect()`` will not result in a\nwill message being sent by the broker.\n\nDisconnect will not wait for all queued message to be sent, to ensure all messages\nare delivered, ``wait_for_publish()`` from ``MQTTMessageInfo`` should be used.\nSee ``publish()`` for details.\n\nCallback (disconnect)\n.....................\n\nWhen the client has sent the disconnect message it generates an\n``on_disconnect()`` callback.\n\nNetwork loop\n````````````\n\nThese functions are the driving force behind the client. If they are not\ncalled, incoming network data will not be processed and outgoing network data\nmay not be sent in a timely fashion. There are four options for managing the\nnetwork loop. Three are described here, the fourth in \"External event loop\nsupport\" below. Do not mix the different loop functions.\n\nloop()\n''''''\n\n.. code:: python\n\n loop(timeout=1.0, max_packets=1)\n\nCall regularly to process network events. This call waits in ``select()`` until\nthe network socket is available for reading or writing, if appropriate, then\nhandles the incoming/outgoing data. This function blocks for up to ``timeout``\nseconds. ``timeout`` must not exceed the ``keepalive`` value for the client or\nyour client will be regularly disconnected by the broker.\n\nThe ``max_packets`` argument is obsolete and should be left unset.\n\nLoop Example\n............\n\n.. code:: python\n\n run = True\n while run:\n mqttc.loop()\n\nloop_start() / loop_stop()\n''''''''''''''''''''''''''\n\n.. code:: python\n\n loop_start()\n loop_stop(force=False)\n\nThese functions implement a threaded interface to the network loop. Calling\n``loop_start()`` once, before or after ``connect*()``, runs a thread in the\nbackground to call ``loop()`` automatically. This frees up the main thread for\nother work that may be blocking. This call also handles reconnecting to the\nbroker. Call ``loop_stop()`` to stop the background thread. The ``force``\nargument is currently ignored.\n\nLoop Start/Stop Example\n.......................\n\n.. code:: python\n\n mqttc.connect(\"iot.eclipse.org\")\n mqttc.loop_start()\n\n while True:\n temperature = sensor.blocking_read()\n mqttc.publish(\"paho/temperature\", temperature)\n\nloop_forever()\n''''''''''''''\n\n.. code:: python\n\n loop_forever(timeout=1.0, max_packets=1, retry_first_connection=False)\n\nThis is a blocking form of the network loop and will not return until the\nclient calls ``disconnect()``. It automatically handles reconnecting.\n\nExcept for the first connection attempt when using connect_async, use\n``retry_first_connection=True`` to make it retry the first connection.\nWarning: This might lead to situations where the client keeps connecting to an\nnon existing host without failing.\n\nThe ``timeout`` and ``max_packets`` arguments are obsolete and should be left\nunset.\n\nPublishing\n``````````\n\nSend a message from the client to the broker.\n\npublish()\n'''''''''\n\n.. code:: python\n\n publish(topic, payload=None, qos=0, retain=False)\n\nThis causes a message to be sent to the broker and subsequently from the broker\nto any clients subscribing to matching topics. It takes the following\narguments:\n\ntopic\n the topic that the message should be published on\n\npayload\n the actual message to send. If not given, or set to ``None`` a zero length\n message will be used. Passing an int or float will result in the payload\n being converted to a string representing that number. If you wish to send a\n true int/float, use ``struct.pack()`` to create the payload you require\n\nqos\n the quality of service level to use\n\nretain\n if set to ``True``, the message will be set as the \"last known\n good\"/retained message for the topic.\n\nReturns a MQTTMessageInfo which expose the following attributes and methods:\n\n* ``rc``, the result of the publishing. It could be ``MQTT_ERR_SUCCESS`` to\n indicate success, ``MQTT_ERR_NO_CONN`` if the client is not currently connected,\n or ``MQTT_ERR_QUEUE_SIZE`` when ``max_queued_messages_set`` is used to indicate\n that message is neither queued nor sent.\n* ``mid`` is the message ID for the publish request. The mid value can be used to\n track the publish request by checking against the mid argument in the\n ``on_publish()`` callback if it is defined. ``wait_for_publish`` may be easier\n depending on your use-case.\n* ``wait_for_publish()`` will block until the message is published. It will\n raise ValueError if the message is not queued (rc == ``MQTT_ERR_QUEUE_SIZE``).\n* ``is_published`` returns True if the message has been published. It will\n raise ValueError if the message is not queued (rc == ``MQTT_ERR_QUEUE_SIZE``).\n\nA ``ValueError`` will be raised if topic is ``None``, has zero length or is\ninvalid (contains a wildcard), if ``qos`` is not one of 0, 1 or 2, or if the\nlength of the payload is greater than 268435455 bytes.\n\nCallback (publish)\n..................\n\nWhen the message has been sent to the broker an ``on_publish()`` callback will\nbe generated.\n\n\nSubscribe / Unsubscribe\n```````````````````````\n\nsubscribe()\n'''''''''''\n\n.. code:: python\n\n subscribe(topic, qos=0)\n\nSubscribe the client to one or more topics.\n\nThis function may be called in three different ways:\n\nSimple string and integer\n.........................\n\ne.g. ``subscribe(\"my/topic\", 2)``\n\ntopic\n a string specifying the subscription topic to subscribe to.\n\nqos\n the desired quality of service level for the subscription. Defaults to 0.\n\nString and integer tuple\n........................\n\ne.g. ``subscribe((\"my/topic\", 1))``\n\ntopic\n a tuple of ``(topic, qos)``. Both topic and qos must be present in the tuple.\n\nqos\n not used.\n\nList of string and integer tuples\n.................................\n\ne.g. ``subscribe([(\"my/topic\", 0), (\"another/topic\", 2)])``\n\nThis allows multiple topic subscriptions in a single SUBSCRIPTION command,\nwhich is more efficient than using multiple calls to ``subscribe()``.\n\ntopic\n a list of tuple of format ``(topic, qos)``. Both topic and qos must be\n present in all of the tuples.\n\nqos\n not used.\n\nThe function returns a tuple ``(result, mid)``, where ``result`` is\n``MQTT_ERR_SUCCESS`` to indicate success or ``(MQTT_ERR_NO_CONN, None)`` if the\nclient is not currently connected. ``mid`` is the message ID for the subscribe\nrequest. The mid value can be used to track the subscribe request by checking\nagainst the mid argument in the ``on_subscribe()`` callback if it is defined.\n\nRaises a ``ValueError`` if ``qos`` is not 0, 1 or 2, or if topic is ``None`` or\nhas zero string length, or if ``topic`` is not a string, tuple or list.\n\nCallback (subscribe)\n....................\n\nWhen the broker has acknowledged the subscription, an ``on_subscribe()``\ncallback will be generated.\n\nunsubscribe()\n'''''''''''''\n\n.. code:: python\n\n unsubscribe(topic)\n\nUnsubscribe the client from one or more topics.\n\ntopic\n a single string, or list of strings that are the subscription topics to\n unsubscribe from.\n\nReturns a tuple ``(result, mid)``, where ``result`` is ``MQTT_ERR_SUCCESS`` to\nindicate success, or ``(MQTT_ERR_NO_CONN, None)`` if the client is not\ncurrently connected. ``mid`` is the message ID for the unsubscribe request. The\nmid value can be used to track the unsubscribe request by checking against the\nmid argument in the ``on_unsubscribe()`` callback if it is defined.\n\nRaises a ``ValueError`` if ``topic`` is ``None`` or has zero string length, or\nis not a string or list.\n\nCallback (unsubscribe)\n......................\n\nWhen the broker has acknowledged the unsubscribe, an ``on_unsubscribe()``\ncallback will be generated.\n\nCallbacks\n`````````\n\non_connect()\n''''''''''''\n\n.. code:: python\n\n on_connect(client, userdata, flags, rc)\n\nCalled when the broker responds to our connection request.\n\nclient\n the client instance for this callback\n\nuserdata\n the private user data as set in ``Client()`` or ``user_data_set()``\n\nflags\n response flags sent by the broker\nrc\n the connection result\n\n\nflags is a dict that contains response flags from the broker:\n flags['session present'] - this flag is useful for clients that are\n using clean session set to 0 only. If a client with clean\n session=0, that reconnects to a broker that it has previously\n connected to, this flag indicates whether the broker still has the\n session information for the client. If 1, the session still exists.\n\nThe value of rc indicates success or not:\n\n 0: Connection successful\n 1: Connection refused - incorrect protocol version\n 2: Connection refused - invalid client identifier\n 3: Connection refused - server unavailable\n 4: Connection refused - bad username or password\n 5: Connection refused - not authorised\n 6-255: Currently unused.\n\nOn Connect Example\n..................\n\n.. code:: python\n\n def on_connect(client, userdata, flags, rc):\n print(\"Connection returned result: \"+connack_string(rc))\n\n mqttc.on_connect = on_connect\n ...\n\non_disconnect()\n'''''''''''''''\n\n.. code:: python\n\n on_disconnect(client, userdata, rc)\n\nCalled when the client disconnects from the broker.\n\nclient\n the client instance for this callback\n\nuserdata\n the private user data as set in ``Client()`` or ``user_data_set()``\n\nrc\n the disconnection result\n\nThe rc parameter indicates the disconnection state. If ``MQTT_ERR_SUCCESS``\n(0), the callback was called in response to a ``disconnect()`` call. If any\nother value the disconnection was unexpected, such as might be caused by a\nnetwork error.\n\nOn Disconnect Example\n.....................\n\n.. code:: python\n\n def on_disconnect(client, userdata, rc):\n if rc != 0:\n print(\"Unexpected disconnection.\")\n\n mqttc.on_disconnect = on_disconnect\n ...\n\non_message()\n''''''''''''\n\n.. code:: python\n\n on_message(client, userdata, message)\n\nCalled when a message has been received on a topic that the client subscribes\nto and the message does not match an existing topic filter callback.\nUse ``message_callback_add()`` to define a callback that will be called for\nspecific topic filters. ``on_message`` will serve as fallback when none matched.\n\nclient\n the client instance for this callback\n\nuserdata\n the private user data as set in ``Client()`` or ``user_data_set()``\n\nmessage\n an instance of MQTTMessage. This is a class with members ``topic``, ``payload``, ``qos``, ``retain``.\n\nOn Message Example\n..................\n\n.. code:: python\n\n def on_message(client, userdata, message):\n print(\"Received message '\" + str(message.payload) + \"' on topic '\"\n + message.topic + \"' with QoS \" + str(message.qos))\n\n mqttc.on_message = on_message\n ...\n\nmessage_callback_add()\n''''''''''''''''''''''\n\nThis function allows you to define callbacks that handle incoming messages for\nspecific subscription filters, including with wildcards. This lets you, for\nexample, subscribe to ``sensors/#`` and have one callback to handle\n``sensors/temperature`` and another to handle ``sensors/humidity``.\n\n.. code:: python\n\n message_callback_add(sub, callback)\n\nsub\n the subscription filter to match against for this callback. Only one\n callback may be defined per literal sub string\n\ncallback\n the callback to be used. Takes the same form as the ``on_message``\n callback.\n\nIf using ``message_callback_add()`` and ``on_message``, only messages that do\nnot match a subscription specific filter will be passed to the ``on_message``\ncallback.\n\nIf multiple sub match a topic, each callback will be called (e.g. sub ``sensors/#``\nand sub ``+/humidity`` both match a message with a topic ``sensors/humidity``, so both\ncallbacks will handle this message).\n\nmessage_callback_remove()\n'''''''''''''''''''''''''\n\nRemove a topic/subscription specific callback previously registered using\n``message_callback_add()``.\n\n.. code:: python\n\n message_callback_remove(sub)\n\nsub\n the subscription filter to remove\n\non_publish()\n''''''''''''\n\n.. code:: python\n\n on_publish(client, userdata, mid)\n\nCalled when a message that was to be sent using the ``publish()`` call has\ncompleted transmission to the broker. For messages with QoS levels 1 and 2,\nthis means that the appropriate handshakes have completed. For QoS 0, this\nsimply means that the message has left the client. The ``mid`` variable matches\nthe mid variable returned from the corresponding ``publish()`` call, to allow\noutgoing messages to be tracked.\n\nThis callback is important because even if the publish() call returns success,\nit does not always mean that the message has been sent.\n\non_subscribe()\n''''''''''''''\n\n.. code:: python\n\n on_subscribe(client, userdata, mid, granted_qos)\n\nCalled when the broker responds to a subscribe request. The ``mid`` variable\nmatches the mid variable returned from the corresponding ``subscribe()`` call.\nThe ``granted_qos`` variable is a list of integers that give the QoS level the\nbroker has granted for each of the different subscription requests.\n\non_unsubscribe()\n''''''''''''''''\n\n.. code:: python\n\n on_unsubscribe(client, userdata, mid)\n\nCalled when the broker responds to an unsubscribe request. The ``mid`` variable\nmatches the mid variable returned from the corresponding ``unsubscribe()``\ncall.\n\non_log()\n''''''''\n\n.. code:: python\n\n on_log(client, userdata, level, buf)\n\nCalled when the client has log information. Define to allow debugging. The\n``level`` variable gives the severity of the message and will be one of\n``MQTT_LOG_INFO``, ``MQTT_LOG_NOTICE``, ``MQTT_LOG_WARNING``, ``MQTT_LOG_ERR``,\nand ``MQTT_LOG_DEBUG``. The message itself is in ``buf``.\n\nThis may be used at the same time as the standard Python logging, which can be\nenabled via the ``enable_logger`` method.\n\non_socket_open()\n''''''''''''''''\n\n::\n\n on_socket_open(client, userdata, sock)\n\nCalled when the socket has been opened.\nUse this to register the socket with an external event loop for reading.\n\non_socket_close()\n'''''''''''''''''\n\n::\n\n on_socket_close(client, userdata, sock)\n\nCalled when the socket is about to be closed.\nUse this to unregister a socket from an external event loop for reading.\n\non_socket_register_write()\n''''''''''''''''''''''''''\n\n::\n\n on_socket_register_write(client, userdata, sock)\n\nCalled when a write operation to the socket failed because it would have blocked, e.g. output buffer full.\nUse this to register the socket with an external event loop for writing.\n\non_socket_unregister_write()\n''''''''''''''''''''''''''''\n\n::\n\n on_socket_unregister_write(client, userdata, sock)\n\nCalled when a write operation to the socket succeeded after it had previously failed.\nUse this to unregister the socket from an external event loop for writing.\n\nExternal event loop support\n```````````````````````````\n\nloop_read()\n'''''''''''\n\n.. code:: python\n\n loop_read(max_packets=1)\n\nCall when the socket is ready for reading. ``max_packets`` is obsolete and\nshould be left unset.\n\nloop_write()\n''''''''''''\n\n.. code:: python\n\n loop_write(max_packets=1)\n\nCall when the socket is ready for writing. ``max_packets`` is obsolete and\nshould be left unset.\n\nloop_misc()\n'''''''''''\n\n.. code:: python\n\n loop_misc()\n\nCall every few seconds to handle message retrying and pings.\n\nsocket()\n''''''''\n\n.. code:: python\n\n socket()\n\nReturns the socket object in use in the client to allow interfacing with other\nevent loops.\nThis call is particularly useful for select_ based loops. See ``examples/loop_select.py``.\n\n.. _select: https://docs.python.org/3/library/select.html#select.select\n\nwant_write()\n''''''''''''\n\n.. code:: python\n\n want_write()\n\nReturns true if there is data waiting to be written, to allow interfacing the\nclient with other event loops.\nThis call is particularly useful for select_ based loops. See ``examples/loop_select.py``.\n\n.. _select: https://docs.python.org/3/library/select.html#select.select\n\nstate callbacks\n'''''''''''''''\n\n::\n\n on_socket_open\n on_socket_close\n on_socket_register_write\n on_socket_unregister_write\n\nUse these callbacks to get notified about state changes in the socket.\nThis is particularly useful for event loops where you register or unregister a socket\nfor reading+writing. See ``examples/loop_asyncio.py`` for an example.\n\nWhen the socket is opened, ``on_socket_open`` is called.\nRegister the socket with your event loop for reading.\n\nWhen the socket is about to be closed, ``on_socket_close`` is called.\nUnregister the socket from your event loop for reading.\n\nWhen a write to the socket failed because it would have blocked, e.g. output buffer full,\n``on_socket_register_write`` is called.\nRegister the socket with your event loop for writing.\n\nWhen the next write to the socket succeeded, ``on_socket_unregister_write`` is called.\nUnregister the socket from your event loop for writing.\n\nThe callbacks are always called in this order:\n\n- ``on_socket_open``\n- Zero or more times:\n\n - ``on_socket_register_write``\n - ``on_socket_unregister_write``\n\n- ``on_socket_close``\n\nGlobal helper functions\n```````````````````````\n\nThe client module also offers some global helper functions.\n\n``topic_matches_sub(sub, topic)`` can be used to check whether a ``topic``\nmatches a ``subscription``.\n\nFor example:\n\n the topic ``foo/bar`` would match the subscription ``foo/#`` or ``+/bar``\n\n the topic ``non/matching`` would not match the subscription ``non/+/+``\n\n\n``connack_string(connack_code)`` returns the error string associated with a\nCONNACK result.\n\n\n``error_string(mqtt_errno)`` returns the error string associated with a Paho\nMQTT error number.\n\nPublish\n*******\n\nThis module provides some helper functions to allow straightforward publishing\nof messages in a one-shot manner. In other words, they are useful for the\nsituation where you have a single/multiple messages you want to publish to a\nbroker, then disconnect with nothing else required.\n\nThe two functions provided are ``single()`` and ``multiple()``.\n\nSingle\n``````\n\nPublish a single message to a broker, then disconnect cleanly.\n\n.. code:: python\n\n single(topic, payload=None, qos=0, retain=False, hostname=\"localhost\",\n port=1883, client_id=\"\", keepalive=60, will=None, auth=None, tls=None,\n protocol=mqtt.MQTTv311, transport=\"tcp\")\n\n\nPublish Single Function arguments\n'''''''''''''''''''''''''''''''''\n\ntopic\n the only required argument must be the topic string to which the payload\n will be published.\n\npayload\n the payload to be published. If \"\" or None, a zero length payload will be\n published.\n\nqos\n the qos to use when publishing, default to 0.\n\nretain\n set the message to be retained (True) or not (False).\n\nhostname\n a string containing the address of the broker to connect to. Defaults to\n localhost.\n\nport\n the port to connect to the broker on. Defaults to 1883.\n\nclient_id\n the MQTT client id to use. If \"\" or None, the Paho library will\n generate a client id automatically.\n\nkeepalive\n the keepalive timeout value for the client. Defaults to 60 seconds.\n\nwill\n a dict containing will parameters for the client:\n\n will = {'topic': \"\", 'payload':\", 'qos':, 'retain':}.\n\n Topic is required, all other parameters are optional and will default to\n None, 0 and False respectively.\n\n Defaults to None, which indicates no will should be used.\n\nauth\n a dict containing authentication parameters for the client:\n\n auth = {'username':\"\", 'password':\"\"}\n\n Username is required, password is optional and will default to None if not provided.\n\n Defaults to None, which indicates no authentication is to be used.\n\ntls\n a dict containing TLS configuration parameters for the client:\n\n dict = {'ca_certs':\"\", 'certfile':\"\", 'keyfile':\"\", 'tls_version':\"\", 'ciphers':\"}\n\n 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.\n\n Defaults to None, which indicates that TLS should not be used.\n\nprotocol\n choose the version of the MQTT protocol to use. Use either ``MQTTv31`` or ``MQTTv311``.\n\ntransport\n set to \"websockets\" to send MQTT over WebSockets. Leave at the default of\n \"tcp\" to use raw TCP.\n\nPublish Single Example\n''''''''''''''''''''''\n\n.. code:: python\n\n import paho.mqtt.publish as publish\n\n publish.single(\"paho/test/single\", \"payload\", hostname=\"iot.eclipse.org\")\n\nMultiple\n````````\n\nPublish multiple messages to a broker, then disconnect cleanly.\n\n.. code:: python\n\n multiple(msgs, hostname=\"localhost\", port=1883, client_id=\"\", keepalive=60,\n will=None, auth=None, tls=None, protocol=mqtt.MQTTv311, transport=\"tcp\")\n\nPublish Multiple Function arguments\n'''''''''''''''''''''''''''''''''''\n\nmsgs\n a list of messages to publish. Each message is either a dict or a tuple.\n\n If a dict, only the topic must be present. Default values will be\n used for any missing arguments. The dict must be of the form:\n\n msg = {'topic':\"\", 'payload':\"\", 'qos':, 'retain':}\n\n topic must be present and may not be empty.\n 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.\n\n If a tuple, then it must be of the form:\n\n (\"\", \"\", qos, retain)\n\nSee ``single()`` for the description of ``hostname``, ``port``, ``client_id``, ``keepalive``, ``will``, ``auth``, ``tls``, ``protocol``, ``transport``.\n\nPublish Multiple Example\n''''''''''''''''''''''''\n\n.. code:: python\n\n import paho.mqtt.publish as publish\n\n msgs = [{'topic':\"paho/test/multiple\", 'payload':\"multiple 1\"},\n (\"paho/test/multiple\", \"multiple 2\", 0, False)]\n publish.multiple(msgs, hostname=\"iot.eclipse.org\")\n\n\nSubscribe\n*********\n\nThis module provides some helper functions to allow straightforward subscribing\nand processing of messages.\n\nThe two functions provided are ``simple()`` and ``callback()``.\n\nSimple\n``````\n\nSubscribe to a set of topics and return the messages received. This is a\nblocking function.\n\n.. code:: python\n\n simple(topics, qos=0, msg_count=1, retained=False, hostname=\"localhost\",\n port=1883, client_id=\"\", keepalive=60, will=None, auth=None, tls=None,\n protocol=mqtt.MQTTv311)\n\n\nSimple Subscribe Function arguments\n'''''''''''''''''''''''''''''''''''\n\ntopics\n the only required argument is the topic string to which the client will\n subscribe. This can either be a string or a list of strings if multiple\n topics should be subscribed to.\n\nqos\n the qos to use when subscribing, defaults to 0.\n\nmsg_count\n the number of messages to retrieve from the broker. Defaults to 1. If 1, a\n single MQTTMessage object will be returned. If >1, a list of MQTTMessages\n will be returned.\n\nretained\n set to True to consider retained messages, set to False to ignore messages\n with the retained flag set.\n\nhostname\n a string containing the address of the broker to connect to. Defaults to localhost.\n\nport\n the port to connect to the broker on. Defaults to 1883.\n\nclient_id\n the MQTT client id to use. If \"\" or None, the Paho library will\n generate a client id automatically.\n\nkeepalive\n the keepalive timeout value for the client. Defaults to 60 seconds.\n\nwill\n a dict containing will parameters for the client:\n\n will = {'topic': \"\", 'payload':\", 'qos':, 'retain':}.\n\n Topic is required, all other parameters are optional and will default to\n None, 0 and False respectively.\n\n Defaults to None, which indicates no will should be used.\n\nauth\n a dict containing authentication parameters for the client:\n\n auth = {'username':\"\", 'password':\"\"}\n\n Username is required, password is optional and will default to None if not\n provided.\n\n Defaults to None, which indicates no authentication is to be used.\n\ntls\n a dict containing TLS configuration parameters for the client:\n\n dict = {'ca_certs':\"\", 'certfile':\"\", 'keyfile':\"\", 'tls_version':\"\", 'ciphers':\"}\n\n ca_certs is required, all other parameters are optional and will default to\n None if not provided, which results in the client using the default\n behaviour - see the paho.mqtt.client documentation.\n\n Defaults to None, which indicates that TLS should not be used.\n\nprotocol\n choose the version of the MQTT protocol to use. Use either ``MQTTv31`` or ``MQTTv311``.\n\n\nSimple Example\n''''''''''''''\n\n.. code:: python\n\n import paho.mqtt.subscribe as subscribe\n\n msg = subscribe.simple(\"paho/test/simple\", hostname=\"iot.eclipse.org\")\n print(\"%s %s\" % (msg.topic, msg.payload))\n\nUsing Callback\n``````````````\n\nSubscribe to a set of topics and process the messages received using a user\nprovided callback.\n\n.. code:: python\n\n callback(callback, topics, qos=0, userdata=None, hostname=\"localhost\",\n port=1883, client_id=\"\", keepalive=60, will=None, auth=None, tls=None,\n protocol=mqtt.MQTTv311)\n\nCallback Subscribe Function arguments\n'''''''''''''''''''''''''''''''''''''\n\ncallback\n an \"on_message\" callback that will be used for each message received, and\n of the form\n\n .. code:: python\n\n def on_message(client, userdata, message)\n\ntopics\n the topic string to which the client will subscribe. This can either be a\n string or a list of strings if multiple topics should be subscribed to.\n\nqos\n the qos to use when subscribing, defaults to 0.\n\nuserdata\n a user provided object that will be passed to the on_message callback when\n a message is received.\n\nSee ``simple()`` for the description of ``hostname``, ``port``, ``client_id``, ``keepalive``, ``will``, ``auth``, ``tls``, ``protocol``.\n\nCallback Example\n''''''''''''''''\n\n.. code:: python\n\n import paho.mqtt.subscribe as subscribe\n\n def on_message_print(client, userdata, message):\n print(\"%s %s\" % (message.topic, message.payload))\n\n subscribe.callback(on_message_print, \"paho/test/callback\", hostname=\"iot.eclipse.org\")\n\n\nReporting bugs\n--------------\n\nPlease report bugs in the issues tracker at https://github.com/eclipse/paho.mqtt.python/issues.\n\nMore information\n----------------\n\nDiscussion of the Paho clients takes place on the `Eclipse paho-dev mailing list `_.\n\nGeneral questions about the MQTT protocol itself (not this library) are discussed in the `MQTT Google Group `_.\n\nThere is much more information available via the `MQTT community site `_.\n\n\n", "description_content_type": "", "docs_url": null, "download_url": "", "downloads": { "last_day": -1, "last_month": -1, "last_week": -1 }, "home_page": "http://eclipse.org/paho", "keywords": "paho", "license": "Eclipse Public License v1.0 / Eclipse Distribution License v1.0", "maintainer": "", "maintainer_email": "", "name": "iottalk-paho-mqtt", "package_url": "https://pypi.org/project/iottalk-paho-mqtt/", "platform": "", "project_url": "https://pypi.org/project/iottalk-paho-mqtt/", "project_urls": { "Homepage": "http://eclipse.org/paho" }, "release_url": "https://pypi.org/project/iottalk-paho-mqtt/1.4.0.dev2/", "requires_dist": [ "PySocks ; extra == 'proxy'" ], "requires_python": "", "summary": "MQTT version 3.1.1 client class", "version": "1.4.0.dev2" }, "last_serial": 5475557, "releases": { "1.4.0.dev2": [ { "comment_text": "", "digests": { "md5": "787ad94973562fc5eddae52bdc2b9c0f", "sha256": "c5741487bf021f16a6963aa70db66eb1bdd47c294ae9c8ed62b7e974ea8a8f94" }, "downloads": -1, "filename": "iottalk_paho_mqtt-1.4.0.dev2-py3-none-any.whl", "has_sig": false, "md5_digest": "787ad94973562fc5eddae52bdc2b9c0f", "packagetype": "bdist_wheel", "python_version": "py3", "requires_python": null, "size": 49785, "upload_time": "2019-07-02T07:40:51", "url": "https://files.pythonhosted.org/packages/e7/e4/341319a49cf63b6b70c2c99355df1b6bdc711ebf54b3796efe937453dec8/iottalk_paho_mqtt-1.4.0.dev2-py3-none-any.whl" } ] }, "urls": [ { "comment_text": "", "digests": { "md5": "787ad94973562fc5eddae52bdc2b9c0f", "sha256": "c5741487bf021f16a6963aa70db66eb1bdd47c294ae9c8ed62b7e974ea8a8f94" }, "downloads": -1, "filename": "iottalk_paho_mqtt-1.4.0.dev2-py3-none-any.whl", "has_sig": false, "md5_digest": "787ad94973562fc5eddae52bdc2b9c0f", "packagetype": "bdist_wheel", "python_version": "py3", "requires_python": null, "size": 49785, "upload_time": "2019-07-02T07:40:51", "url": "https://files.pythonhosted.org/packages/e7/e4/341319a49cf63b6b70c2c99355df1b6bdc711ebf54b3796efe937453dec8/iottalk_paho_mqtt-1.4.0.dev2-py3-none-any.whl" } ] }