Sfoglia il codice sorgente

Initial implementation

master
Dirk Alders 2 anni fa
parent
commit
c4ac87f222
6 ha cambiato i file con 131 aggiunte e 0 eliminazioni
  1. 83
    0
      __init__.py
  2. 17
    0
      _examples_/.project
  3. 8
    0
      _examples_/.pydevproject
  4. 1
    0
      _examples_/mqtt
  5. 21
    0
      _examples_/test.py
  6. 1
    0
      requirements.txt

+ 83
- 0
__init__.py Vedi File

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

+ 17
- 0
_examples_/.project Vedi File

@@ -0,0 +1,17 @@
1
+<?xml version="1.0" encoding="UTF-8"?>
2
+<projectDescription>
3
+	<name>mqtt</name>
4
+	<comment></comment>
5
+	<projects>
6
+	</projects>
7
+	<buildSpec>
8
+		<buildCommand>
9
+			<name>org.python.pydev.PyDevBuilder</name>
10
+			<arguments>
11
+			</arguments>
12
+		</buildCommand>
13
+	</buildSpec>
14
+	<natures>
15
+		<nature>org.python.pydev.pythonNature</nature>
16
+	</natures>
17
+</projectDescription>

+ 8
- 0
_examples_/.pydevproject Vedi File

@@ -0,0 +1,8 @@
1
+<?xml version="1.0" encoding="UTF-8" standalone="no"?>
2
+<?eclipse-pydev version="1.0"?><pydev_project>
3
+    <pydev_pathproperty name="org.python.pydev.PROJECT_SOURCE_PATH">
4
+        <path>/${PROJECT_DIR_NAME}</path>
5
+    </pydev_pathproperty>
6
+    <pydev_property name="org.python.pydev.PYTHON_PROJECT_VERSION">python interpreter</pydev_property>
7
+    <pydev_property name="org.python.pydev.PYTHON_PROJECT_INTERPRETER">Default</pydev_property>
8
+</pydev_project>

+ 1
- 0
_examples_/mqtt Vedi File

@@ -0,0 +1 @@
1
+..

+ 21
- 0
_examples_/test.py Vedi File

@@ -0,0 +1,21 @@
1
+import mqtt
2
+import time
3
+import logging
4
+import sys
5
+
6
+root = logging.getLogger('root')
7
+root.setLevel(logging.DEBUG)
8
+
9
+handler = logging.StreamHandler(sys.stdout)
10
+handler.setLevel(logging.DEBUG)
11
+formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
12
+handler.setFormatter(formatter)
13
+root.addHandler(handler)
14
+
15
+def print_msg(client, userdata, message):
16
+    print("Received ", message.topic, ": ", str(message.payload))
17
+
18
+c = mqtt.mqtt_client('test', '192.168.0.2', username='', password='')
19
+c.add_callback('ambient/#', print_msg)
20
+while True:
21
+    time.sleep(1)

+ 1
- 0
requirements.txt Vedi File

@@ -0,0 +1 @@
1
+paho-mqtt

Loading…
Annulla
Salva