MQTT Interface
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

__init__.py 2.7KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. #
  4. """
  5. mqtt (MQTT)
  6. ===========
  7. **Author:**
  8. * Dirk Alders <sudo-dirk@mount-mockery.de>
  9. **Description:**
  10. This Module supports functionality for mqtt connections
  11. **Submodules:**
  12. * :mod:`mqtt_client`
  13. **Unittest:**
  14. See also the :download:`unittest <mqtt/_testresults_/unittest.pdf>` documentation.
  15. **Module Documentation:**
  16. """
  17. __DEPENDENCIES__ = []
  18. import logging
  19. import paho.mqtt.client as paho
  20. import socket
  21. try:
  22. from config import APP_NAME as ROOT_LOGGER_NAME
  23. except ImportError:
  24. ROOT_LOGGER_NAME = 'root'
  25. logger = logging.getLogger(ROOT_LOGGER_NAME).getChild(__name__)
  26. class mqtt_client(object):
  27. def __init__(self, name, host, port=1883, username=None, password=None):
  28. logger.info("Initiating mqtt client instance")
  29. self.__callbacks__ = {}
  30. self.__client__ = paho.Client(name) # create client object
  31. if username is not None and password is not None:
  32. logger.debug("Configuring authentification")
  33. self.__client__.username_pw_set(username, password) # login with credentials
  34. self.__client__.on_message = self.__receive__ # attach function to callback
  35. self.__client__.on_connect = self.__on_connect__
  36. self.__client__.on_disconnect = self.__on_disconnect__
  37. try:
  38. self.__client__.connect(host, port) # establish connection
  39. except (socket.timeout, OSError) as e:
  40. logger.warning("Can not connect to MQTT-Server")
  41. self.__client__.loop_start() # start the loop
  42. def add_callback(self, topic, callback):
  43. self.__callbacks__[topic] = callback
  44. self.__client__.subscribe(topic)
  45. def send(self, topic, payload):
  46. self.__client__.publish(topic, payload)
  47. def __on_connect__(self, client, userdata, flags, rc):
  48. logger.debug("Connect with rc=%d", rc)
  49. if rc == 0:
  50. logger.debug("Registering topics...")
  51. for topic in self.__callbacks__:
  52. self.__client__.subscribe(topic)
  53. def __on_disconnect__(self, client, flags, rc):
  54. logger.warning("Disconnect with rc=%d", rc)
  55. def __receive__(self, client, userdata, message):
  56. logger.debug("Received message with topic %s and payload %s", message.topic, str(message.payload))
  57. for topic in self.__callbacks__:
  58. if topic.endswith('#'):
  59. if message.topic.startswith(topic[:-1]):
  60. self.__callbacks__[topic](client, userdata, message)
  61. else:
  62. if topic == message.topic:
  63. self.__callbacks__[topic](client, userdata, message)