diff --git a/__init__.py b/__init__.py new file mode 100644 index 0000000..8b4013c --- /dev/null +++ b/__init__.py @@ -0,0 +1,83 @@ +#!/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) diff --git a/_examples_/.project b/_examples_/.project new file mode 100644 index 0000000..258cac5 --- /dev/null +++ b/_examples_/.project @@ -0,0 +1,17 @@ + + + mqtt + + + + + + org.python.pydev.PyDevBuilder + + + + + + org.python.pydev.pythonNature + + diff --git a/_examples_/.pydevproject b/_examples_/.pydevproject new file mode 100644 index 0000000..aa7a29a --- /dev/null +++ b/_examples_/.pydevproject @@ -0,0 +1,8 @@ + + + + /${PROJECT_DIR_NAME} + + python interpreter + Default + diff --git a/_examples_/mqtt b/_examples_/mqtt new file mode 120000 index 0000000..a96aa0e --- /dev/null +++ b/_examples_/mqtt @@ -0,0 +1 @@ +.. \ No newline at end of file diff --git a/_examples_/test.py b/_examples_/test.py new file mode 100644 index 0000000..f912db1 --- /dev/null +++ b/_examples_/test.py @@ -0,0 +1,21 @@ +import mqtt +import time +import logging +import sys + +root = logging.getLogger('root') +root.setLevel(logging.DEBUG) + +handler = logging.StreamHandler(sys.stdout) +handler.setLevel(logging.DEBUG) +formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') +handler.setFormatter(formatter) +root.addHandler(handler) + +def print_msg(client, userdata, message): + print("Received ", message.topic, ": ", str(message.payload)) + +c = mqtt.mqtt_client('test', '192.168.0.2', username='', password='') +c.add_callback('ambient/#', print_msg) +while True: + time.sleep(1) \ No newline at end of file diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..8579e8b --- /dev/null +++ b/requirements.txt @@ -0,0 +1 @@ +paho-mqtt