subscribe.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  1. # Copyright (c) 2016 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 subscribing
  16. to topics and retrieving messages. The two functions are simple(), which
  17. returns one or messages matching a set of topics, and callback() which allows
  18. you to pass a callback for processing of messages.
  19. """
  20. from .. import mqtt
  21. from . import client as paho
  22. def _on_connect(client, userdata, flags, reason_code, properties):
  23. """Internal callback"""
  24. if reason_code != 0:
  25. raise mqtt.MQTTException(paho.connack_string(reason_code))
  26. if isinstance(userdata['topics'], list):
  27. for topic in userdata['topics']:
  28. client.subscribe(topic, userdata['qos'])
  29. else:
  30. client.subscribe(userdata['topics'], userdata['qos'])
  31. def _on_message_callback(client, userdata, message):
  32. """Internal callback"""
  33. userdata['callback'](client, userdata['userdata'], message)
  34. def _on_message_simple(client, userdata, message):
  35. """Internal callback"""
  36. if userdata['msg_count'] == 0:
  37. return
  38. # Don't process stale retained messages if 'retained' was false
  39. if message.retain and not userdata['retained']:
  40. return
  41. userdata['msg_count'] = userdata['msg_count'] - 1
  42. if userdata['messages'] is None and userdata['msg_count'] == 0:
  43. userdata['messages'] = message
  44. client.disconnect()
  45. return
  46. userdata['messages'].append(message)
  47. if userdata['msg_count'] == 0:
  48. client.disconnect()
  49. def callback(callback, topics, qos=0, userdata=None, hostname="localhost",
  50. port=1883, client_id="", keepalive=60, will=None, auth=None,
  51. tls=None, protocol=paho.MQTTv311, transport="tcp",
  52. clean_session=True, proxy_args=None):
  53. """Subscribe to a list of topics and process them in a callback function.
  54. This function creates an MQTT client, connects to a broker and subscribes
  55. to a list of topics. Incoming messages are processed by the user provided
  56. callback. This is a blocking function and will never return.
  57. :param callback: function with the same signature as `on_message` for
  58. processing the messages received.
  59. :param topics: either a string containing a single topic to subscribe to, or a
  60. list of topics to subscribe to.
  61. :param int qos: the qos to use when subscribing. This is applied to all topics.
  62. :param userdata: passed to the callback
  63. :param str hostname: the address of the broker to connect to.
  64. Defaults to localhost.
  65. :param int port: the port to connect to the broker on. Defaults to 1883.
  66. :param str client_id: the MQTT client id to use. If "" or None, the Paho library will
  67. generate a client id automatically.
  68. :param int keepalive: the keepalive timeout value for the client. Defaults to 60
  69. seconds.
  70. :param will: a dict containing will parameters for the client: will = {'topic':
  71. "<topic>", 'payload':"<payload">, 'qos':<qos>, 'retain':<retain>}.
  72. Topic is required, all other parameters are optional and will
  73. default to None, 0 and False respectively.
  74. Defaults to None, which indicates no will should be used.
  75. :param auth: a dict containing authentication parameters for the client:
  76. auth = {'username':"<username>", 'password':"<password>"}
  77. Username is required, password is optional and will default to None
  78. if not provided.
  79. Defaults to None, which indicates no authentication is to be used.
  80. :param tls: a dict containing TLS configuration parameters for the client:
  81. dict = {'ca_certs':"<ca_certs>", 'certfile':"<certfile>",
  82. 'keyfile':"<keyfile>", 'tls_version':"<tls_version>",
  83. 'ciphers':"<ciphers">, 'insecure':"<bool>"}
  84. ca_certs is required, all other parameters are optional and will
  85. default to None if not provided, which results in the client using
  86. the default behaviour - see the paho.mqtt.client documentation.
  87. Alternatively, tls input can be an SSLContext object, which will be
  88. processed using the tls_set_context method.
  89. Defaults to None, which indicates that TLS should not be used.
  90. :param str transport: set to "tcp" to use the default setting of transport which is
  91. raw TCP. Set to "websockets" to use WebSockets as the transport.
  92. :param clean_session: a boolean that determines the client type. If True,
  93. the broker will remove all information about this client
  94. when it disconnects. If False, the client is a persistent
  95. client and subscription information and queued messages
  96. will be retained when the client disconnects.
  97. Defaults to True.
  98. :param proxy_args: a dictionary that will be given to the client.
  99. """
  100. if qos < 0 or qos > 2:
  101. raise ValueError('qos must be in the range 0-2')
  102. callback_userdata = {
  103. 'callback':callback,
  104. 'topics':topics,
  105. 'qos':qos,
  106. 'userdata':userdata}
  107. client = paho.Client(
  108. paho.CallbackAPIVersion.VERSION2,
  109. client_id=client_id,
  110. userdata=callback_userdata,
  111. protocol=protocol,
  112. transport=transport,
  113. clean_session=clean_session,
  114. )
  115. client.enable_logger()
  116. client.on_message = _on_message_callback
  117. client.on_connect = _on_connect
  118. if proxy_args is not None:
  119. client.proxy_set(**proxy_args)
  120. if auth:
  121. username = auth.get('username')
  122. if username:
  123. password = auth.get('password')
  124. client.username_pw_set(username, password)
  125. else:
  126. raise KeyError("The 'username' key was not found, this is "
  127. "required for auth")
  128. if will is not None:
  129. client.will_set(**will)
  130. if tls is not None:
  131. if isinstance(tls, dict):
  132. insecure = tls.pop('insecure', False)
  133. client.tls_set(**tls)
  134. if insecure:
  135. # Must be set *after* the `client.tls_set()` call since it sets
  136. # up the SSL context that `client.tls_insecure_set` alters.
  137. client.tls_insecure_set(insecure)
  138. else:
  139. # Assume input is SSLContext object
  140. client.tls_set_context(tls)
  141. client.connect(hostname, port, keepalive)
  142. client.loop_forever()
  143. def simple(topics, qos=0, msg_count=1, retained=True, hostname="localhost",
  144. port=1883, client_id="", keepalive=60, will=None, auth=None,
  145. tls=None, protocol=paho.MQTTv311, transport="tcp",
  146. clean_session=True, proxy_args=None):
  147. """Subscribe to a list of topics and return msg_count messages.
  148. This function creates an MQTT client, connects to a broker and subscribes
  149. to a list of topics. Once "msg_count" messages have been received, it
  150. disconnects cleanly from the broker and returns the messages.
  151. :param topics: either a string containing a single topic to subscribe to, or a
  152. list of topics to subscribe to.
  153. :param int qos: the qos to use when subscribing. This is applied to all topics.
  154. :param int msg_count: the number of messages to retrieve from the broker.
  155. if msg_count == 1 then a single MQTTMessage will be returned.
  156. if msg_count > 1 then a list of MQTTMessages will be returned.
  157. :param bool retained: If set to True, retained messages will be processed the same as
  158. non-retained messages. If set to False, retained messages will
  159. be ignored. This means that with retained=False and msg_count=1,
  160. the function will return the first message received that does
  161. not have the retained flag set.
  162. :param str hostname: the address of the broker to connect to.
  163. Defaults to localhost.
  164. :param int port: the port to connect to the broker on. Defaults to 1883.
  165. :param str client_id: the MQTT client id to use. If "" or None, the Paho library will
  166. generate a client id automatically.
  167. :param int keepalive: the keepalive timeout value for the client. Defaults to 60
  168. seconds.
  169. :param will: a dict containing will parameters for the client: will = {'topic':
  170. "<topic>", 'payload':"<payload">, 'qos':<qos>, 'retain':<retain>}.
  171. Topic is required, all other parameters are optional and will
  172. default to None, 0 and False respectively.
  173. Defaults to None, which indicates no will should be used.
  174. :param auth: a dict containing authentication parameters for the client:
  175. auth = {'username':"<username>", 'password':"<password>"}
  176. Username is required, password is optional and will default to None
  177. if not provided.
  178. Defaults to None, which indicates no authentication is to be used.
  179. :param tls: a dict containing TLS configuration parameters for the client:
  180. dict = {'ca_certs':"<ca_certs>", 'certfile':"<certfile>",
  181. 'keyfile':"<keyfile>", 'tls_version':"<tls_version>",
  182. 'ciphers':"<ciphers">, 'insecure':"<bool>"}
  183. ca_certs is required, all other parameters are optional and will
  184. default to None if not provided, which results in the client using
  185. the default behaviour - see the paho.mqtt.client documentation.
  186. Alternatively, tls input can be an SSLContext object, which will be
  187. processed using the tls_set_context method.
  188. Defaults to None, which indicates that TLS should not be used.
  189. :param protocol: the MQTT protocol version to use. Defaults to MQTTv311.
  190. :param transport: set to "tcp" to use the default setting of transport which is
  191. raw TCP. Set to "websockets" to use WebSockets as the transport.
  192. :param clean_session: a boolean that determines the client type. If True,
  193. the broker will remove all information about this client
  194. when it disconnects. If False, the client is a persistent
  195. client and subscription information and queued messages
  196. will be retained when the client disconnects.
  197. Defaults to True. If protocol is MQTTv50, clean_session
  198. is ignored.
  199. :param proxy_args: a dictionary that will be given to the client.
  200. """
  201. if msg_count < 1:
  202. raise ValueError('msg_count must be > 0')
  203. # Set ourselves up to return a single message if msg_count == 1, or a list
  204. # if > 1.
  205. if msg_count == 1:
  206. messages = None
  207. else:
  208. messages = []
  209. # Ignore clean_session if protocol is MQTTv50, otherwise Client will raise
  210. if protocol == paho.MQTTv5:
  211. clean_session = None
  212. userdata = {'retained':retained, 'msg_count':msg_count, 'messages':messages}
  213. callback(_on_message_simple, topics, qos, userdata, hostname, port,
  214. client_id, keepalive, will, auth, tls, protocol, transport,
  215. clean_session, proxy_args)
  216. return userdata['messages']