I defined, in Home Assistant, and automation which emits an event when an MQTT message is received. This was done to allow listening to these events in AppDaemon and act accordingly.
I now would like to move the MQTT part to AppDaemon (as MQTT is supported there as well).
The problem: I do not know how to call HA entities from within a class which herits from mqtt.MQTT. Consider the following code and the comments at the end:
import appdaemon.plugins.mqtt.mqttapi as mqtt
# import appdaemon.plugins.hass.hassapi as hass
class RF433Button(mqtt.Mqtt):
def initialize(self):
self.listen_event(self.guess_button, 'MQTT_MESSAGE', topic="rfbridge-1/rfin")
def guess_button(self, event_name, data, kwargs):
code = data.decode()
self.log(f"received RF433 code {code}")
# a typical scenario
if code.endswith("3CCBA1"):
self.toggle("switch.chambre_1_main")
# ^-- here I would like to call switch.chambre_1_main defined in HA,
# but it is not available as the class inherits from mqtt.MQTT and not hass.HASS
thats where the namespaces come in.
it should be working with:
self.toggle("switch.chambre_1_main", namepace = "the namespace that you did set for the hass plugin")
i hope that toggle also has been changed, if not it will throw an error.
in that case there is a workaround option:
self.set_namespace("the namespace that you did set for the hass plugin")
self.toggle("switch.chambre_1_main")
self.set_namespace("the namespace that you did set for the mqtt plugin")
if you did not set the namespace for 1 of the plugins it will be called “default”
setting the namespace defines which version of the functions like listen_event, listen_state, etc. will be used.
with set_namepace you only set the default namespace that is used when you dont specify it in the function.
for example something i got in 1 of my apps that inherits from mqtt:
if not self.entity_exists(entity,namespace = "hass"):
self.log("the light: {} doesnt exist in HA create it".format(entity))
Is this solution still valid or has AppDaemon changed since then? I can’t get it to work, the callback is never executed even though AppDaemon receives Mqtt messages.
import appdaemon.plugins.hass.hassapi as hass
import appdaemon.plugins.mqtt.mqttapi as mqtt
class rtl433Restarter(hass.Hass):
def initialize(self):
self.listen_event(self.my_callback,
"MQTT_MESSAGE",
topic="homeassistant/sensor/rtl433/#",
namespace="mqtt")
self.log("Init complete")
def my_callback(self):
self.log("Message received")
That’s the AppDaemon MQTT plugin in verbose mode (INFO AppDaemon: MQTT:…), but not the actual app that I want to react to incoming messages (INFO restart_rtl433:…).
If my callback executed I’d expect it to show up like this:
INFO restart_rtl433: Message received
INFO restart_rtl433: [The event name]
INFO restart_rtl433: [The data]
So yeah it’s what I need but I can’t get my app to react to it.