2024-02-12 17:54:08 +00:00
|
|
|
import appdaemon.plugins.hass.hassapi as hass
|
|
|
|
import appdaemon.plugins.mqtt.mqttapi as mqtt
|
|
|
|
import appdaemon.adbase as base
|
|
|
|
|
|
|
|
|
2024-09-25 16:36:50 +00:00
|
|
|
class hass_mqtt_state_sync(hass.Hass,mqtt.Mqtt):
|
2024-02-12 17:54:08 +00:00
|
|
|
|
|
|
|
def initialize(self):
|
|
|
|
self.entity_id = self.args["entity_id"]
|
2024-09-25 16:36:50 +00:00
|
|
|
self.entity = self.get_entity(self.entity_id)
|
2024-02-12 17:54:08 +00:00
|
|
|
self.mqtt_topic_state = self.args["mqtt_topic_state"]
|
|
|
|
self.mqtt_topic_set_state = self.args["mqtt_topic_set_state"]
|
|
|
|
self.mqtt_topic_request = self.args["mqtt_topic_request"]
|
|
|
|
|
2024-09-25 16:36:50 +00:00
|
|
|
self.mqtt_subscribe(self.mqtt_topic_set_state, namespace="mqtt")
|
|
|
|
self.mqtt_subscribe(self.mqtt_topic_request, namespace="mqtt")
|
|
|
|
self.listen_event(self.handle_set_state_payload, "MQTT_MESSAGE", topic=self.mqtt_topic_set_state, namespace="mqtt")
|
|
|
|
self.listen_event(self.handle_request_payload, "MQTT_MESSAGE", topic=self.mqtt_topic_request, namespace="mqtt")
|
2024-02-12 17:54:08 +00:00
|
|
|
self.entity.listen_state(self.handle_hass_state_change)
|
2024-09-25 16:36:50 +00:00
|
|
|
self.publish_state_to_mqtt()
|
2024-02-12 17:54:08 +00:00
|
|
|
|
|
|
|
def publish_state_to_mqtt(self):
|
2024-09-25 16:36:50 +00:00
|
|
|
state = self.get_state(self.entity_id)
|
|
|
|
self.mqtt_publish(self.mqtt_topic_state, str(state), namespace="mqtt")
|
2024-02-12 17:54:08 +00:00
|
|
|
|
|
|
|
def handle_set_state_payload(self, event_name, data, cb_args):
|
|
|
|
self.entity.set_state(state = data["payload"])
|
|
|
|
|
|
|
|
def handle_request_payload(self, event_name, data, cb_args):
|
|
|
|
self.publish_state_to_mqtt()
|
|
|
|
|
|
|
|
def handle_hass_state_change(self, entity, attribute, old, new, cb_args):
|
2024-09-25 16:36:50 +00:00
|
|
|
self.log("State change detected: {} -> {}".format(old, new))
|
2024-02-12 17:54:08 +00:00
|
|
|
self.publish_state_to_mqtt()
|