Juice/mqtt.py

35 lines
862 B
Python
Raw Permalink Normal View History

2019-11-18 13:05:37 -05:00
#!/usr/bin/env python3
"""
Contains MQTT funtionality.
"""
import paho.mqtt.client as mqtt
from models import network
def on_connect(client, userdata, flags, rc):
"""Called when the client successfully connects to the broker."""
client.subscribe("juice/#")
for device in network:
if device.mqtt_root:
client.subscribe(device.mqtt_root + '/#')
def on_message(client, userdata, msg):
"""Called when the client receives a message."""
root = msg.topic.partition('/')[0]
devices = [device for device in network if root == device.mqtt_root]
for device in devices:
2020-05-15 19:06:31 -04:00
device.mqtt_callback(client.app, msg)
2019-11-18 13:05:37 -05:00
def init_client(app):
"""Initializes the MQTT client."""
client = mqtt.Client()
client.app = app
client.on_connect = on_connect
client.on_message = on_message
client.connect_async("localhost", 1883, 60)
client.loop_start()
return client