#!/usr/bin/env python # -*- coding: utf-8 -*- # """ mqtt (MQTT) =========== **Author:** * Dirk Alders **Description:** This Module supports functionality for mqtt connections **Submodules:** * :mod:`mqtt_client` **Unittest:** See also the :download:`unittest ` documentation. **Module Documentation:** """ __DEPENDENCIES__ = [] import logging import paho.mqtt.client as paho import socket try: from config import APP_NAME as ROOT_LOGGER_NAME except ImportError: ROOT_LOGGER_NAME = 'root' logger = logging.getLogger(ROOT_LOGGER_NAME).getChild(__name__) class mqtt_client(object): def __init__(self, name, host, port=1883, username=None, password=None): logger.info("Initiating mqtt client instance") self.__callbacks__ = {} self.__client__ = paho.Client(name) # create client object if username is not None and password is not None: logger.debug("Configuring authentification") self.__client__.username_pw_set(username, password) # login with credentials self.__client__.on_message = self.__receive__ # attach function to callback self.__client__.on_connect = self.__on_connect__ self.__client__.on_disconnect = self.__on_disconnect__ try: self.__client__.connect(host, port) # establish connection except (socket.timeout, OSError) as e: logger.warning("Can not connect to MQTT-Server") self.__client__.loop_start() # start the loop def add_callback(self, topic, callback): self.__callbacks__[topic] = callback self.__client__.subscribe(topic) def send(self, topic, payload): self.__client__.publish(topic, payload) def __on_connect__(self, client, userdata, flags, rc): logger.debug("Connect with rc=%d", rc) if rc == 0: logger.debug("Registering topics...") for topic in self.__callbacks__: self.__client__.subscribe(topic) def __on_disconnect__(self, client, flags, rc): logger.warning("Disconnect with rc=%d", rc) def __receive__(self, client, userdata, message): logger.debug("Received message with topic %s and payload %s", message.topic, str(message.payload)) for topic in self.__callbacks__: if topic.endswith('#'): if message.topic.startswith(topic[:-1]): self.__callbacks__[topic](client, userdata, message) else: if topic == message.topic: self.__callbacks__[topic](client, userdata, message)