Add celery task for config update

master
esensar 2018-09-20 22:21:50 +02:00
parent d3a5854454
commit 3beae5b0d5
3 changed files with 36 additions and 22 deletions

View File

@ -1,4 +1,5 @@
# App initialization
import sys
from flask import Flask
from .tasks import celery as celery_configurator
@ -7,3 +8,35 @@ app.config.from_object('config')
app.config.from_pyfile('config.py', silent=True)
app.config['MQTT_CLIENT_ID'] = 'final-iot-backend-server-worker'
celery = celery_configurator.make_celery(app)
@celery.task()
def send_config(device_id, config):
from flask_mqtt import Mqtt, MQTT_ERR_SUCCESS
mqtt = Mqtt(app)
@mqtt.on_log()
def handle_logging(client, userdata, level, buf):
print(level, buf)
@mqtt.on_connect()
def handle_connect(client, userdata, flags, rc):
print('MQTT worker client connected')
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) = mqtt.publish(topic, config, 2)
if (result == MQTT_ERR_SUCCESS):
print("Success!!!")
print("Result: " + str(result))
print("Message id: " + str(mid))
mqtt.client.disconnect()
except Exception:
print("ERROR!")
error_type, error_instance, traceback = sys.exc_info()
print("Type: " + str(error_type))
print("Instance: " + str(error_instance))
mqtt.client.disconnect()
return

View File

@ -48,11 +48,11 @@ def set_device_configuration(device_id, configuration_json):
:type configuration_json: JSON
:rtype: Boolean
"""
from app.mqtt.mqtt_client import MqttClient
from app.celery_builder import send_config
device = Device.get(id=device_id)
device.configuration = configuration_json
device.save()
MqttClient.send_config(device_id, str(configuration_json))
send_config.delay(device_id, str(configuration_json))
def get_device_configuration(device_id):

View File

@ -1,6 +1,6 @@
import sys
import json
from flask_mqtt import Mqtt, MQTT_ERR_SUCCESS
from flask_mqtt import Mqtt
import app.devices as devices
@ -74,22 +74,3 @@ 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