Source code for festivalgrid.device_templates.mqtt_device

import uuid
import socket

from django.conf import settings
import paho.mqtt.client as paho

from .device import DeviceTemplate

[docs]def init_mqtt(client_id=None, on_message=False, on_connect=False, on_disconnect=False): """This will open a connection to the mqtt broker and register any callbacks you pass in as parameters. :param client_id: The name this connection should register as with the broker. :type client_id: str. :param on_message: Callback function that gets called when a new message is received. :type on_message: function. :param on_connect: Callback function that gets called when the connection to the broker is successful. :type on_connect: function. :param on_disconnect: Callback function that gets called when the broker disconnects. :type on_disconnect: function. :returns: paho.Client -- the paho Client object instance """ if client_id is None: client_id = 'festivalgrid-%s' % uuid.uuid4() client = paho.Client(client_id, clean_session=False) if on_message: client.on_message = on_message if on_connect: client.on_connect = on_connect if on_disconnect: client.on_disconnect = on_disconnect if settings.MQTT_USERNAME: client.username_pw_set(settings.MQTT_USERNAME, settings.MQTT_PASSWORD) if settings.MQTT_TLS: client.tls_set() # wait for mqtt host socket.socket(socket.AF_INET, socket.SOCK_STREAM).connect_ex((settings.MQTT_HOST, int(settings.MQTT_PORT))) client.connect(settings.MQTT_HOST, settings.MQTT_PORT, 5) return client
[docs]class MQTTDevice(DeviceTemplate): """The base class for MQTT based devices. .. note:: :class:`.Tasmota` is a good reference for implementing new MQTT based device templates. """ _client = None
[docs] def send_mqtt_message(self, topic, message): """Use this to send a message to the mqtt broker. :param topic: The topic this message should be published under. :type topic: str. :param message: The message that should be published. :type message: str. """ if not self._client: self._client = init_mqtt('festivalgrid-device-template-%d' % topic = "festivalgrid/" + self.device.mqtt_topic + "/" + topic self._client.publish(topic, message)
[docs] def notify_setup_change(self, model): """Pings both the worker and mqtt_broker services that they should reload the setup.""" self.send_mqtt_message("setup_changed", model)