A more robust way to handle JSON serialization/deserialization on MQTT backend

This commit is contained in:
Fabio Manganiello 2018-06-12 10:33:30 +02:00
parent b329580ff0
commit 464ff1ff57
2 changed files with 12 additions and 16 deletions

View file

@ -5,7 +5,6 @@ import paho.mqtt.publish as publisher
from platypush.backend import Backend from platypush.backend import Backend
from platypush.message import Message from platypush.message import Message
from platypush.context import get_backend
class MqttBackend(Backend): class MqttBackend(Backend):
@ -27,15 +26,10 @@ class MqttBackend(Backend):
self.port = port self.port = port
self.topic = '{}/{}'.format(topic, self.device_id) self.topic = '{}/{}'.format(topic, self.device_id)
try:
self.redis = get_backend('redis')
except:
self.redis = None
def send_message(self, msg): def send_message(self, msg):
try: try:
msg = json.loads(msg) msg = Message.build(json.loads(msg))
except: except:
pass pass
@ -48,17 +42,11 @@ class MqttBackend(Backend):
def on_message(client, userdata, msg): def on_message(client, userdata, msg):
msg = msg.payload.decode('utf-8') msg = msg.payload.decode('utf-8')
try: try: msg = Message.build(json.loads(msg))
msg = Message.build(json.loads(msg)) except: pass
except:
pass
self.logger.info('Received message on the MQTT backend: {}'.format(msg)) self.logger.info('Received message on the MQTT backend: {}'.format(msg))
self.bus.post(msg)
if self.redis:
self.redis.send_message(msg)
else:
self.bus.post(msg)
super().run() super().run()
client = mqtt.Client() client = mqtt.Client()

View file

@ -1,11 +1,19 @@
import json
import paho.mqtt.publish as publisher import paho.mqtt.publish as publisher
from platypush.message import Message
from platypush.message.response import Response from platypush.message.response import Response
from platypush.plugins import Plugin from platypush.plugins import Plugin
class MqttPlugin(Plugin): class MqttPlugin(Plugin):
def send_message(self, topic, msg, host, port=1883, *args, **kwargs): 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) publisher.single(topic, str(msg), hostname=host, port=port)
return Response(output={'state': 'ok'}) return Response(output={'state': 'ok'})