From 2967e6ad6bade72b8949db43189678f1209a50bd Mon Sep 17 00:00:00 2001 From: esensar Date: Thu, 20 Sep 2018 00:50:26 +0200 Subject: [PATCH] Add mqtt notification when configuration changes --- app/devices/__init__.py | 2 ++ app/mqtt/mqtt_client.py | 26 +++++++++++++++++++++++++- 2 files changed, 27 insertions(+), 1 deletion(-) diff --git a/app/devices/__init__.py b/app/devices/__init__.py index da6f647..95ceab5 100644 --- a/app/devices/__init__.py +++ b/app/devices/__init__.py @@ -2,6 +2,7 @@ import sys from flask import Blueprint from .models import Device, Recording, DeviceAssociation, DeviceType from app import app +from app.mqtt.mqtt_client import MqttClient devices_bp = Blueprint('devices', __name__) @@ -51,6 +52,7 @@ def set_device_configuration(device_id, configuration_json): device = Device.get(id=device_id) device.configuration = configuration_json device.save() + MqttClient.send_config(device_id, str(configuration_json)) def get_device_configuration(device_id): diff --git a/app/mqtt/mqtt_client.py b/app/mqtt/mqtt_client.py index fbf9682..cc5c408 100644 --- a/app/mqtt/mqtt_client.py +++ b/app/mqtt/mqtt_client.py @@ -1,6 +1,6 @@ import sys import json -from flask_mqtt import Mqtt +from flask_mqtt import Mqtt, MQTT_ERR_SUCCESS import app.devices as devices @@ -15,6 +15,7 @@ class MqttClient: MqttClient.mqtt.init_app(app) MqttClient.mqtt.client.on_message = MqttClient.handle_mqtt_message MqttClient.mqtt.client.on_subscribe = MqttClient.handle_subscribe + MqttClient.mqtt.client.on_publish = MqttClient.handle_publish MqttClient.__initialized = True @MqttClient.mqtt.on_connect() @@ -58,6 +59,10 @@ class MqttClient: print("Instance: " + str(error_instance)) return + @staticmethod + def handle_publish(client, userdata, mid): + print("Published message! (" + str(mid) + ")") + @staticmethod def get_device_id(topic): device_token, device_id = topic.split("/") @@ -65,3 +70,22 @@ class MqttClient: return int(device_id) else: raise ValueError("Topic is in invalid format") + + @staticmethod + def send_config(device_id, config): + print("Sending configuration to device: " + str(device_id)) + print("Configuration: " + str(config)) + topic = 'device/' + str(device_id) + '/config' + print("Targeting topic: " + topic) + try: + (result, mid) = MqttClient.mqtt.publish(topic, config, 2) + if (result == MQTT_ERR_SUCCESS): + print("Success!!!") + print("Result: " + str(result)) + print("Message id: " + str(mid)) + except Exception: + print("ERROR!") + error_type, error_instance, traceback = sys.exc_info() + print("Type: " + str(error_type)) + print("Instance: " + str(error_instance)) + return