From 464ff1ff5754397cb577e042e34c41ebe59254c2 Mon Sep 17 00:00:00 2001 From: Fabio Manganiello Date: Tue, 12 Jun 2018 10:33:30 +0200 Subject: [PATCH] A more robust way to handle JSON serialization/deserialization on MQTT backend --- platypush/backend/mqtt.py | 20 ++++---------------- platypush/plugins/mqtt.py | 8 ++++++++ 2 files changed, 12 insertions(+), 16 deletions(-) diff --git a/platypush/backend/mqtt.py b/platypush/backend/mqtt.py index c0d250307..e875e5e5f 100644 --- a/platypush/backend/mqtt.py +++ b/platypush/backend/mqtt.py @@ -5,7 +5,6 @@ import paho.mqtt.publish as publisher from platypush.backend import Backend from platypush.message import Message -from platypush.context import get_backend class MqttBackend(Backend): @@ -27,15 +26,10 @@ class MqttBackend(Backend): self.port = port self.topic = '{}/{}'.format(topic, self.device_id) - try: - self.redis = get_backend('redis') - except: - self.redis = None - def send_message(self, msg): try: - msg = json.loads(msg) + msg = Message.build(json.loads(msg)) except: pass @@ -48,17 +42,11 @@ class MqttBackend(Backend): def on_message(client, userdata, msg): msg = msg.payload.decode('utf-8') - try: - msg = Message.build(json.loads(msg)) - except: - pass + try: msg = Message.build(json.loads(msg)) + except: pass self.logger.info('Received message on the MQTT backend: {}'.format(msg)) - - if self.redis: - self.redis.send_message(msg) - else: - self.bus.post(msg) + self.bus.post(msg) super().run() client = mqtt.Client() diff --git a/platypush/plugins/mqtt.py b/platypush/plugins/mqtt.py index 8ce0079a5..b1e3c22b5 100644 --- a/platypush/plugins/mqtt.py +++ b/platypush/plugins/mqtt.py @@ -1,11 +1,19 @@ +import json import paho.mqtt.publish as publisher +from platypush.message import Message from platypush.message.response import Response from platypush.plugins import Plugin class MqttPlugin(Plugin): def send_message(self, topic, msg, host, port=1883, *args, **kwargs): + try: msg = json.dumps(msg) + except: pass + + try: msg = Message.build(json.loads(msg)) + except: pass + publisher.single(topic, str(msg), hostname=host, port=port) return Response(output={'state': 'ok'})