I’m asking this question mainly as a jinja / template learning exercise and because I know @petro is a Template Master.
state_attr(‘sensor.security_ingress_json’,‘json_xpath_status’) has this dict value:
{
"Count": [
{
"type": "all",
"name": "ntotal",
"status": 9
},
{
"type": "all",
"name": "nopen",
"status": 0
},
{
"type": "all",
"name": "nclosed",
"status": 9
}
],
"Home": [
{
"type": "Door",
"name": "Front",
"status": "closed"
},
{
"type": "Door",
"name": "Back Patio",
"status": "closed"
}
],
"Living_Room": [
{
"type": "Window",
"name": "East",
"status": "closed"
},
{
"type": "Window",
"name": "West",
"status": "closed"
}
],
"Bedrooms": [
{
"type": "Window",
"name": "SE",
"status": "closed"
}
],
"Garage": [
{
"type": "Door",
"name": "Overhead",
"status": "closed"
},
{
"type": "Door",
"name": "Side",
"status": "closed"
},
{
"type": "Window",
"name": "East",
"status": "closed"
}
],
"Basement": [
{
"type": "Window",
"name": "Escape",
"status": "closed"
},
{
"type": "Window",
"name": "South",
"status": "closed"
}
]
}
The goal is to display in the only those doors and windows that are OPEN. Here’s the Jinja code which gets the job done, but I’m wondering if it can be improved:
Ingress Detection
{% set ingress_status = 'open' -%}
{% set ingress_pts = state_attr('sensor.security_ingress_json','json_xpath_status') -%}
{% set ns = namespace(list='```', strlen=0, hdrlen=0) -%}
{% for ingress_type in ['Door', 'Window'] -%}
{% for area in (ingress_pts|list) -%}
{% if (loop.index == 1) -%}
{% if ns.list|length() > ns.strlen -%}
{% set prefix = ns.list ~'\n' -%}
{% else-%}
{% set prefix = '```\n' -%}
{% endif-%}
{% set ns.list = prefix ~ ingress_status.title() ~' '~ ingress_type ~'s:' -%}
{% set ns.strlen = ns.list|length() -%}
{% set ns.hdrlen = ns.strlen - prefix|length() + 1 %}
{% endif -%}
{% set ingress_pt_list = ingress_pts[area]|selectattr('type','==',ingress_type)|list -%}
{% set ingress_pt_status = ingress_pt_list|selectattr('status','==',ingress_status)|list -%}
{% for ingress_pt in range(ingress_pt_status|count()) -%}
{% if ingress_pt_status|length>0 -%}
{% set ns.list = ns.list ~'\n- '~ ingress_pt_status[ingress_pt]['name'] ~ ' ' ~ area.replace('rooms','room') ~' '~ ingress_type -%}
{% endif -%}
{% endfor -%}
{% endfor -%}
{% if ns.list|length() == ns.strlen-%}
{% set ns.list = ns.list[0:ns.strlen - ns.hdrlen] -%}
{% else -%}
{% set ns.list = ns.list ~ '\n' -%}
{% endif-%}
{% endfor-%}
{{- ns.list }}
Example Output:
Ingress Detection
Open Windows:
- Escape Basement Window
- South Basement Window