publish.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  1. # Copyright (c) 2014 Roger Light <roger@atchoo.org>
  2. #
  3. # All rights reserved. This program and the accompanying materials
  4. # are made available under the terms of the Eclipse Public License v2.0
  5. # and Eclipse Distribution License v1.0 which accompany this distribution.
  6. #
  7. # The Eclipse Public License is available at
  8. # http://www.eclipse.org/legal/epl-v20.html
  9. # and the Eclipse Distribution License is available at
  10. # http://www.eclipse.org/org/documents/edl-v10.php.
  11. #
  12. # Contributors:
  13. # Roger Light - initial API and implementation
  14. """
  15. This module provides some helper functions to allow straightforward publishing
  16. of messages in a one-shot manner. In other words, they are useful for the
  17. situation where you have a single/multiple messages you want to publish to a
  18. broker, then disconnect and nothing else is required.
  19. """
  20. from __future__ import annotations
  21. import collections
  22. from collections.abc import Iterable
  23. from typing import TYPE_CHECKING, Any, Union
  24. from paho.mqtt.enums import CallbackAPIVersion, MQTTProtocolVersion
  25. from paho.mqtt.properties import Properties
  26. from paho.mqtt.reasoncodes import ReasonCode
  27. from .. import mqtt
  28. from . import client as paho
  29. if TYPE_CHECKING:
  30. try:
  31. from typing import NotRequired, Required, TypedDict # type: ignore
  32. except ImportError:
  33. from typing_extensions import NotRequired, Required, TypedDict
  34. try:
  35. from typing import Literal
  36. except ImportError:
  37. from typing_extensions import Literal # type: ignore
  38. class AuthParameter(TypedDict, total=False):
  39. username: Required[str]
  40. password: NotRequired[str]
  41. class TLSParameter(TypedDict, total=False):
  42. ca_certs: Required[str]
  43. certfile: NotRequired[str]
  44. keyfile: NotRequired[str]
  45. tls_version: NotRequired[int]
  46. ciphers: NotRequired[str]
  47. insecure: NotRequired[bool]
  48. class MessageDict(TypedDict, total=False):
  49. topic: Required[str]
  50. payload: NotRequired[paho.PayloadType]
  51. qos: NotRequired[int]
  52. retain: NotRequired[bool]
  53. MessageTuple = tuple[str, paho.PayloadType, int, bool]
  54. MessagesList = list[Union[MessageDict, MessageTuple]]
  55. def _do_publish(client: paho.Client):
  56. """Internal function"""
  57. message = client._userdata.popleft()
  58. if isinstance(message, dict):
  59. client.publish(**message)
  60. elif isinstance(message, (tuple, list)):
  61. client.publish(*message)
  62. else:
  63. raise TypeError('message must be a dict, tuple, or list')
  64. def _on_connect(client: paho.Client, userdata: MessagesList, flags, reason_code, properties):
  65. """Internal v5 callback"""
  66. if reason_code == 0:
  67. if len(userdata) > 0:
  68. _do_publish(client)
  69. else:
  70. raise mqtt.MQTTException(paho.connack_string(reason_code))
  71. def _on_publish(
  72. client: paho.Client, userdata: collections.deque[MessagesList], mid: int, reason_codes: ReasonCode, properties: Properties,
  73. ) -> None:
  74. """Internal callback"""
  75. #pylint: disable=unused-argument
  76. if len(userdata) == 0:
  77. client.disconnect()
  78. else:
  79. _do_publish(client)
  80. def multiple(
  81. msgs: MessagesList,
  82. hostname: str = "localhost",
  83. port: int = 1883,
  84. client_id: str = "",
  85. keepalive: int = 60,
  86. will: MessageDict | None = None,
  87. auth: AuthParameter | None = None,
  88. tls: TLSParameter | None = None,
  89. protocol: MQTTProtocolVersion = paho.MQTTv311,
  90. transport: Literal["tcp", "websockets"] = "tcp",
  91. proxy_args: Any | None = None,
  92. ) -> None:
  93. """Publish multiple messages to a broker, then disconnect cleanly.
  94. This function creates an MQTT client, connects to a broker and publishes a
  95. list of messages. Once the messages have been delivered, it disconnects
  96. cleanly from the broker.
  97. :param msgs: a list of messages to publish. Each message is either a dict or a
  98. tuple.
  99. If a dict, only the topic must be present. Default values will be
  100. used for any missing arguments. The dict must be of the form:
  101. msg = {'topic':"<topic>", 'payload':"<payload>", 'qos':<qos>,
  102. 'retain':<retain>}
  103. topic must be present and may not be empty.
  104. If payload is "", None or not present then a zero length payload
  105. will be published.
  106. If qos is not present, the default of 0 is used.
  107. If retain is not present, the default of False is used.
  108. If a tuple, then it must be of the form:
  109. ("<topic>", "<payload>", qos, retain)
  110. :param str hostname: the address of the broker to connect to.
  111. Defaults to localhost.
  112. :param int port: the port to connect to the broker on. Defaults to 1883.
  113. :param str client_id: the MQTT client id to use. If "" or None, the Paho library will
  114. generate a client id automatically.
  115. :param int keepalive: the keepalive timeout value for the client. Defaults to 60
  116. seconds.
  117. :param will: a dict containing will parameters for the client: will = {'topic':
  118. "<topic>", 'payload':"<payload">, 'qos':<qos>, 'retain':<retain>}.
  119. Topic is required, all other parameters are optional and will
  120. default to None, 0 and False respectively.
  121. Defaults to None, which indicates no will should be used.
  122. :param auth: a dict containing authentication parameters for the client:
  123. auth = {'username':"<username>", 'password':"<password>"}
  124. Username is required, password is optional and will default to None
  125. if not provided.
  126. Defaults to None, which indicates no authentication is to be used.
  127. :param tls: a dict containing TLS configuration parameters for the client:
  128. dict = {'ca_certs':"<ca_certs>", 'certfile':"<certfile>",
  129. 'keyfile':"<keyfile>", 'tls_version':"<tls_version>",
  130. 'ciphers':"<ciphers">, 'insecure':"<bool>"}
  131. ca_certs is required, all other parameters are optional and will
  132. default to None if not provided, which results in the client using
  133. the default behaviour - see the paho.mqtt.client documentation.
  134. Alternatively, tls input can be an SSLContext object, which will be
  135. processed using the tls_set_context method.
  136. Defaults to None, which indicates that TLS should not be used.
  137. :param str transport: set to "tcp" to use the default setting of transport which is
  138. raw TCP. Set to "websockets" to use WebSockets as the transport.
  139. :param proxy_args: a dictionary that will be given to the client.
  140. """
  141. if not isinstance(msgs, Iterable):
  142. raise TypeError('msgs must be an iterable')
  143. if len(msgs) == 0:
  144. raise ValueError('msgs is empty')
  145. client = paho.Client(
  146. CallbackAPIVersion.VERSION2,
  147. client_id=client_id,
  148. userdata=collections.deque(msgs),
  149. protocol=protocol,
  150. transport=transport,
  151. )
  152. client.enable_logger()
  153. client.on_publish = _on_publish
  154. client.on_connect = _on_connect # type: ignore
  155. if proxy_args is not None:
  156. client.proxy_set(**proxy_args)
  157. if auth:
  158. username = auth.get('username')
  159. if username:
  160. password = auth.get('password')
  161. client.username_pw_set(username, password)
  162. else:
  163. raise KeyError("The 'username' key was not found, this is "
  164. "required for auth")
  165. if will is not None:
  166. client.will_set(**will)
  167. if tls is not None:
  168. if isinstance(tls, dict):
  169. insecure = tls.pop('insecure', False)
  170. # mypy don't get that tls no longer contains the key insecure
  171. client.tls_set(**tls) # type: ignore[misc]
  172. if insecure:
  173. # Must be set *after* the `client.tls_set()` call since it sets
  174. # up the SSL context that `client.tls_insecure_set` alters.
  175. client.tls_insecure_set(insecure)
  176. else:
  177. # Assume input is SSLContext object
  178. client.tls_set_context(tls)
  179. client.connect(hostname, port, keepalive)
  180. client.loop_forever()
  181. def single(
  182. topic: str,
  183. payload: paho.PayloadType = None,
  184. qos: int = 0,
  185. retain: bool = False,
  186. hostname: str = "localhost",
  187. port: int = 1883,
  188. client_id: str = "",
  189. keepalive: int = 60,
  190. will: MessageDict | None = None,
  191. auth: AuthParameter | None = None,
  192. tls: TLSParameter | None = None,
  193. protocol: MQTTProtocolVersion = paho.MQTTv311,
  194. transport: Literal["tcp", "websockets"] = "tcp",
  195. proxy_args: Any | None = None,
  196. ) -> None:
  197. """Publish a single message to a broker, then disconnect cleanly.
  198. This function creates an MQTT client, connects to a broker and publishes a
  199. single message. Once the message has been delivered, it disconnects cleanly
  200. from the broker.
  201. :param str topic: the only required argument must be the topic string to which the
  202. payload will be published.
  203. :param payload: the payload to be published. If "" or None, a zero length payload
  204. will be published.
  205. :param int qos: the qos to use when publishing, default to 0.
  206. :param bool retain: set the message to be retained (True) or not (False).
  207. :param str hostname: the address of the broker to connect to.
  208. Defaults to localhost.
  209. :param int port: the port to connect to the broker on. Defaults to 1883.
  210. :param str client_id: the MQTT client id to use. If "" or None, the Paho library will
  211. generate a client id automatically.
  212. :param int keepalive: the keepalive timeout value for the client. Defaults to 60
  213. seconds.
  214. :param will: a dict containing will parameters for the client: will = {'topic':
  215. "<topic>", 'payload':"<payload">, 'qos':<qos>, 'retain':<retain>}.
  216. Topic is required, all other parameters are optional and will
  217. default to None, 0 and False respectively.
  218. Defaults to None, which indicates no will should be used.
  219. :param auth: a dict containing authentication parameters for the client:
  220. Username is required, password is optional and will default to None
  221. auth = {'username':"<username>", 'password':"<password>"}
  222. if not provided.
  223. Defaults to None, which indicates no authentication is to be used.
  224. :param tls: a dict containing TLS configuration parameters for the client:
  225. dict = {'ca_certs':"<ca_certs>", 'certfile':"<certfile>",
  226. 'keyfile':"<keyfile>", 'tls_version':"<tls_version>",
  227. 'ciphers':"<ciphers">, 'insecure':"<bool>"}
  228. ca_certs is required, all other parameters are optional and will
  229. default to None if not provided, which results in the client using
  230. the default behaviour - see the paho.mqtt.client documentation.
  231. Defaults to None, which indicates that TLS should not be used.
  232. Alternatively, tls input can be an SSLContext object, which will be
  233. processed using the tls_set_context method.
  234. :param transport: set to "tcp" to use the default setting of transport which is
  235. raw TCP. Set to "websockets" to use WebSockets as the transport.
  236. :param proxy_args: a dictionary that will be given to the client.
  237. """
  238. msg: MessageDict = {'topic':topic, 'payload':payload, 'qos':qos, 'retain':retain}
  239. multiple([msg], hostname, port, client_id, keepalive, will, auth, tls,
  240. protocol, transport, proxy_args)