Add mqtt notification when configuration changes

master
esensar 2018-09-20 00:50:26 +02:00
parent 446778e445
commit 2967e6ad6b
2 changed files with 27 additions and 1 deletions

View File

@ -2,6 +2,7 @@ import sys
from flask import Blueprint from flask import Blueprint
from .models import Device, Recording, DeviceAssociation, DeviceType from .models import Device, Recording, DeviceAssociation, DeviceType
from app import app from app import app
from app.mqtt.mqtt_client import MqttClient
devices_bp = Blueprint('devices', __name__) devices_bp = Blueprint('devices', __name__)
@ -51,6 +52,7 @@ def set_device_configuration(device_id, configuration_json):
device = Device.get(id=device_id) device = Device.get(id=device_id)
device.configuration = configuration_json device.configuration = configuration_json
device.save() device.save()
MqttClient.send_config(device_id, str(configuration_json))
def get_device_configuration(device_id): def get_device_configuration(device_id):

View File

@ -1,6 +1,6 @@
import sys import sys
import json import json
from flask_mqtt import Mqtt from flask_mqtt import Mqtt, MQTT_ERR_SUCCESS
import app.devices as devices import app.devices as devices
@ -15,6 +15,7 @@ class MqttClient:
MqttClient.mqtt.init_app(app) MqttClient.mqtt.init_app(app)
MqttClient.mqtt.client.on_message = MqttClient.handle_mqtt_message MqttClient.mqtt.client.on_message = MqttClient.handle_mqtt_message
MqttClient.mqtt.client.on_subscribe = MqttClient.handle_subscribe MqttClient.mqtt.client.on_subscribe = MqttClient.handle_subscribe
MqttClient.mqtt.client.on_publish = MqttClient.handle_publish
MqttClient.__initialized = True MqttClient.__initialized = True
@MqttClient.mqtt.on_connect() @MqttClient.mqtt.on_connect()
@ -58,6 +59,10 @@ class MqttClient:
print("Instance: " + str(error_instance)) print("Instance: " + str(error_instance))
return return
@staticmethod
def handle_publish(client, userdata, mid):
print("Published message! (" + str(mid) + ")")
@staticmethod @staticmethod
def get_device_id(topic): def get_device_id(topic):
device_token, device_id = topic.split("/") device_token, device_id = topic.split("/")
@ -65,3 +70,22 @@ class MqttClient:
return int(device_id) return int(device_id)
else: else:
raise ValueError("Topic is in invalid format") 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