This commit is contained in:
Dirk Alders 2022-09-12 21:24:01 +02:00
джерело cf7250c05c
коміт c4ac87f222
6 змінених файлів з 131 додано та 0 видалено

83
__init__.py Normal file

@ -0,0 +1,83 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
"""
mqtt (MQTT)
===========
**Author:**
* Dirk Alders <sudo-dirk@mount-mockery.de>
**Description:**
This Module supports functionality for mqtt connections
**Submodules:**
* :mod:`mqtt_client`
**Unittest:**
See also the :download:`unittest <mqtt/_testresults_/unittest.pdf>` 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)

17
_examples_/.project Normal file

@ -0,0 +1,17 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>mqtt</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.python.pydev.PyDevBuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.python.pydev.pythonNature</nature>
</natures>
</projectDescription>

8
_examples_/.pydevproject Normal file

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

1
_examples_/mqtt Символічне посилання

@ -0,0 +1 @@
..

21
_examples_/test.py Normal file

@ -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)

1
requirements.txt Normal file

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