Fallback entities for unreliable devices in automations

I have a situation where I can get the same information from two different integrations. Specifically, I’m using the qolsysgw integration to poll sensor state from my alarm panel, and the alarmdotcom integration to scrape the same information from the web. When both are working, the qolsysgw is preferable because it has much lower latency, but when qolsysgw is down (because the WiFi is down or I’m upgrading appdaemon), I can still use alarmdotcom to determine sensor status, which is better than nothing.

I’d like to use my alarm sensor status all over the place in automations. For example, I might want to cut the heat if a window is open, turn off a light if there is no motion detected someplace, lock a zwave deadbolt when the door closes, or prevent a zwave deadbolt from locking when the door is open. To that end, I defined a macro I could use in templates like this:

{% macro first_binsensor(sensors) -%}
{%- set ns = namespace(bsens=[]) -%}
{%- for s in sensors -%}
  {%- set ns.bsens = ns.bsens + ["binary_sensor." ~ s] -%}
{%- endfor -%}
{{ ns.bsens | map("states") | reject("eq", "unavailable")
  | first | default("unavailable") }}
{%- endmacro %}

My idea was to use this macro all over the place where I would previously have accessed the entity state directly. For example, I’d use {{ first_binsensor(["kitchen_door_2", "kitchen_door"]) }} to get the kitchen door state, and if the first binary sensor is unavailable (binary_sensor.kitchen_door_2), it would use the second one (binary_sensor.kitchen_door).

The good news is that my macro seems to work well in the template tab of the developer tools. Unfortunately, I couldn’t figure out where to put the macro such that I could access it in multiple automations. I tried putting it at the top of the automations.yaml file, but that seemed to cause all sorts of problems and prevent me from editing automations through the web gui. Searching around, it seems like homeassistant doesn’t support global ninja macros that span different automations.

My question: is there a better way of using fallback entities that would require a huge amount of typing, or am I missing some way of defining global macros in my homeassistant configuration? Thanks.

You’re not missing anything. For now, Jinja macros are not super useful as they are local to a given configuration entry. As I understand it, there is currently work being done on this function. As it stands your best bet is to create a template binary sensor for each pair of sensors. If you have a lot of sensors you can use the template tool to build out the yaml and copy/paste it into your config as show here

It will support global Jinja2 macros in the near future (possibly in April’s release).