From e0422f066b5a4c862698694dcb30792e542ba282 Mon Sep 17 00:00:00 2001 From: marisa Date: Sun, 29 Oct 2023 20:56:03 -0300 Subject: [PATCH] Add Service and MqttSubscriber classes - Create utils dir and move utils.py there --- motor_passo/utils/__init__.py | 0 motor_passo/utils/mqtt_subscriber.py | 51 ++++++++++++++++++++++++++++ motor_passo/utils/service.py | 17 ++++++++++ motor_passo/{ => utils}/utils.py | 0 poetry.lock | 16 ++++++++- pyproject.toml | 1 + 6 files changed, 84 insertions(+), 1 deletion(-) create mode 100644 motor_passo/utils/__init__.py create mode 100644 motor_passo/utils/mqtt_subscriber.py create mode 100644 motor_passo/utils/service.py rename motor_passo/{ => utils}/utils.py (100%) diff --git a/motor_passo/utils/__init__.py b/motor_passo/utils/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/motor_passo/utils/mqtt_subscriber.py b/motor_passo/utils/mqtt_subscriber.py new file mode 100644 index 0000000..6b8db3e --- /dev/null +++ b/motor_passo/utils/mqtt_subscriber.py @@ -0,0 +1,51 @@ +import paho.mqtt.client as mqtt + +from motor_passo.utils.service import Service + + +class MqttSubscriber(Service): + + def __init__(self, broker_host, broker_port): + super().__init__(name="mqtt_listener") + self.broker_host = broker_host + self.broker_port = broker_port + self._client = mqtt.Client() + self._client.on_connect = self._on_connect + self._client.on_message = self._on_message + self._client.on_disconnect = self._on_disconnect + self._cbs: dict[str, callable] = {} + + def run(self) -> None: + self.client.connect(self.broker_host, self.broker_port, 60) + self.client.loop_start() + + def subscribe(self, topic: str, cb: callable) -> None: + self._cbs[topic] = cb + + if self._client.is_connected(): + self._client.subscribe(topic) + + def _on_connect(self, client, userdata, flags, rc) -> None: + self._l.debug(f"Conectado com resultado {str(rc)}") + + for topic in self._cbs.keys(): + client.subscribe(topic) + + def _on_disconnect(self, client, userdata, rc) -> None: + self._l.debug(f"Desconectado, código {str(rc)}") + # Start the loop again in case of an unexpected disconnection + client.loop_start() + + def _on_message(self, client, userdata, message) -> None: + payload = message.payload.decode("utf-8") + self._l.debug(f"Mensagem recebida no tópico: {message.topic}") + + if message.topic not in self._cbs: + self._l.debug(f"Mensagem no tópico {message.topic} não tratada") + return + + try: + self._cbs[message.topic](message.topic, payload) + except Exception: + self._l.exception( + f"Falha ao processar mensagem no tópico {message.topic}") diff --git a/motor_passo/utils/service.py b/motor_passo/utils/service.py new file mode 100644 index 0000000..3972ddf --- /dev/null +++ b/motor_passo/utils/service.py @@ -0,0 +1,17 @@ +import threading +import logging + + +class Service(threading.Thread): + + def __init__(self, name: str = "(sem nome)"): + super().__init__() + log = logging.getLogger(__name__).getChild(self.__class__.__name__) + + self.daemon = True + self.name = name + self._l = log.getChild(self.name) + + def start(self) -> None: + self._l.debug(f"Iniciando serviço {self.name}") + super().start() diff --git a/motor_passo/utils.py b/motor_passo/utils/utils.py similarity index 100% rename from motor_passo/utils.py rename to motor_passo/utils/utils.py diff --git a/poetry.lock b/poetry.lock index 4444796..c3a62fa 100644 --- a/poetry.lock +++ b/poetry.lock @@ -29,6 +29,20 @@ files = [ {file = "mccabe-0.7.0.tar.gz", hash = "sha256:348e0240c33b60bbdf4e523192ef919f28cb2c3d7d5c7794f74009290f236325"}, ] +[[package]] +name = "paho-mqtt" +version = "1.6.1" +description = "MQTT version 5.0/3.1.1 client class" +category = "main" +optional = false +python-versions = "*" +files = [ + {file = "paho-mqtt-1.6.1.tar.gz", hash = "sha256:2a8291c81623aec00372b5a85558a372c747cbca8e9934dfe218638b8eefc26f"}, +] + +[package.extras] +proxy = ["PySocks"] + [[package]] name = "pycodestyle" version = "2.10.0" @@ -99,4 +113,4 @@ tomli = ">=2.0.1" [metadata] lock-version = "2.0" python-versions = "^3.9" -content-hash = "ada48f840d3939f59714a8dc9b66ea1363582c6f658da3b771f9d89c8371e200" +content-hash = "88cff2fd871e1c4248abedb8ef45af99e90ac4ef620fe4ed32fb752b63fc6502" diff --git a/pyproject.toml b/pyproject.toml index 9ebed09..1515bfc 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -9,6 +9,7 @@ packages = [{include = "motor_passo"}] [tool.poetry.dependencies] python = "^3.9" rpi-gpio = "^0.7.1" +paho-mqtt = "^1.6.1" [tool.poetry.group.dev.dependencies]