Exemplo n.º 1
0
    def _on_disconnect(
        self,
        client: mqtt.Client | None,
        userdata: Any | None,
        rc: int | None,
        properties: Any | None = None,  # pylint: disable=unused-argument,invalid-name
    ) -> None:
        """MQTT callback method."""
        logger = self._log.getChild("mqtt.disconnected")
        if rc > 0:
            if rc == 7:
                if not self.mqtt.connected:
                    raise MQTTException(
                        "Unexpected MQTT disconnect - were you perhaps banned?"
                    )

            if self.mqtt.connected:
                logger.debug("MQTT connection was lost! (%s)", error_string(rc))

            logger.debug("Setting MQTT connected flag FALSE")
            self.mqtt.connected = False
            self._events.call(LandroidEvent.MQTT_CONNECTION, state=self.mqtt.connected)
            for name, topics in self.mqtt.topics.items():
                topic = topics["out"]
                logger.debug(
                    "MQTT for %s disconnected, unsubscribing from topic '%s'",
                    name,
                    topic,
                )
                client.unsubscribe(topic)
Exemplo n.º 2
0
    def _on_connect(
        self,
        client: mqtt.Client | None,
        userdata: Any | None,
        flags: Any | None,
        rc: int | None,
        properties: Any | None = None,  # pylint: disable=unused-argument,invalid-name
    ) -> None:
        """MQTT callback method."""
        logger = self._log.getChild("mqtt.connected")
        logger.debug(connack_string(rc))
        if rc == 0:
            for name, topics in self.mqtt.topics.items():
                topic = topics["out"]
                logger.debug(
                    "MQTT for %s connected, subscribing to topic '%s'", name, topic
                )
                client.subscribe(topic)

            for name, device in self.devices.items():
                device.mqtt = self.mqtt
                if isinstance(device.raw_data, type(None)):
                    logger.debug(
                        "MQTT chached data not found for %s - requesting now", name
                    )

                    mqp = device.mqtt.send(name, force=True)
                    if isinstance(mqp, type(None)):
                        raise MQTTException("Couldn't send request to MQTT server.")
                    elif not isinstance(mqp, str):
                        while not mqp.is_published:
                            pass

            logger.debug("Setting MQTT connected flag TRUE")
            self.mqtt.connected = True
            self._events.call(LandroidEvent.MQTT_CONNECTION, state=self.mqtt.connected)

        else:
            logger.debug("Setting MQTT connected flag FALSE")
            self.mqtt.connected = False
            self._events.call(LandroidEvent.MQTT_CONNECTION, state=self.mqtt.connected)

            raise MQTTException(connack_string(rc))