alias: Awtrix App - DPC Alert
description: ""
trigger:
  - platform: state
    entity_id:
      - binary_sensor.dpc_idrogeologico_oggi
      - binary_sensor.dpc_idraulico_oggi
      - binary_sensor.dpc_temporali_oggi
      - binary_sensor.dpc_idrogeologico_domani
      - binary_sensor.dpc_idraulico_domani
      - binary_sensor.dpc_temporali_domani
condition:
  - condition: template
    value_template: >-
      {{ trigger.to_state.state == 'on' and (trigger.from_state.state == 'off'
      or (trigger.to_state.attributes != trigger.from_state.attributes))}}
action:
  - service: mqtt.publish
    data:
      qos: 0
      retain: false
      topic: awtrix_xxx/custom/dpc_alert
  - variables:
      payload_apps: >
        {%- set entity = 'sensor.dpc_alert' -%}   {%- set days_map =
        {'today':'Oggi','tomorrow':'Domani'} -%}  {%- set alert_color =
        {0:"#FFFFFF", 1:'#00FF00', 2:'#ffff00', 3:'#ffa500', 4:'#ff0000'}
        -%}        {%- set risk_icon =
        {'Temporali':'11428','Idraulico':'63','Idrogeologico':'2661'} -%}
        {%- set ns = namespace(data=false) -%}{%- set events_today =
        state_attr(entity, 'events_today') -%} 
          {%- if events_today -%} 
            {%- for ev in events_today if events_today is defined -%}
            {%- set evloop = loop -%}
            {%- if ev -%}
            {%- set ns.data = true -%}
            {
                "icon": "{{ risk_icon.get(ev['risk']) }}",
                "text": 
                  [
                    {
                      "t": "Oggi {{ ev['alert']}} ({{ ev['risk'] }})",
                      "c": "{{ alert_color.get(ev['level']) }}"
                    }
                  ]
              }
            {%- endif  -%}
            {%- if not evloop.last -%},{%- endif -%}
            {%- endfor -%}
          {%- endif -%}
        {%- set events_tomorrow = state_attr(entity, 'events_tomorrow') -%} 
          {%- if events_tomorrow -%} 
            {%- for ev in events_tomorrow if events_tomorrow is defined -%}
            {%- set evloop = loop -%}
            {%- if ev -%}
            {%- if ns.data == true -%},{%- endif %}
            {%- set ns.data = true -%}
              {
                "icon": "{{ risk_icon.get(ev['risk']) }}",
                "text": 
                  [
                    {
                      "t": "Domani {{ ev['alert']}} ({{ ev['risk'] }})",
                      "c": "{{ alert_color.get(ev['level']) }}"
                    }
                  ]
              }
            {%- endif -%}
            {%- endfor -%}
          {%- endif -%}
      payload: |
        {%- if payload_apps -%}
          [
            {{ payload_apps }}
          ]
        {%- else -%}
         {}
        {%- endif -%}
  - service: mqtt.publish
    data:
      qos: 0
      retain: false
      topic: awtrix_xxx/custom/dpc_alert
      payload: |
        {{ payload | tojson }}
mode: queued
max_exceeded: silent
max: 10