2018-10-07 19:59:14 +00:00
|
|
|
import sys
|
|
|
|
from app.celery_builder import task_builder
|
2018-10-08 19:08:50 +00:00
|
|
|
from flask import current_app as app
|
2018-10-07 19:59:14 +00:00
|
|
|
|
|
|
|
|
2018-10-29 21:47:03 +00:00
|
|
|
def connect_and_send_mqtt_message(topic, message):
|
2018-10-07 19:59:14 +00:00
|
|
|
from flask_mqtt import Mqtt, MQTT_ERR_SUCCESS
|
2018-10-08 19:08:50 +00:00
|
|
|
mqtt = Mqtt(app)
|
2018-10-07 19:59:14 +00:00
|
|
|
|
|
|
|
@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("Targeting topic: " + topic)
|
2018-10-29 21:47:03 +00:00
|
|
|
print("Sending message: " + message)
|
2018-10-07 19:59:14 +00:00
|
|
|
try:
|
2018-10-29 21:47:03 +00:00
|
|
|
(result, mid) = mqtt.publish(topic, message, 2)
|
2018-10-07 19:59:14 +00:00
|
|
|
if (result == MQTT_ERR_SUCCESS):
|
2018-10-29 21:47:03 +00:00
|
|
|
print("Successfully sent a message")
|
2018-10-07 19:59:14 +00:00
|
|
|
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
|
2018-10-29 21:47:03 +00:00
|
|
|
|
|
|
|
|
|
|
|
@task_builder.task()
|
|
|
|
def send_config(device_id, config):
|
|
|
|
print("Sending configuration to device: " + str(device_id))
|
|
|
|
print("Configuration: " + str(config))
|
|
|
|
topic = 'device/' + str(device_id) + '/config'
|
|
|
|
connect_and_send_mqtt_message(topic, config)
|