- id: aviso_chuva_aberto
  alias: Aviso - chuva com porta ou janela aberta
  description: A cada 15 min olha a previsão horária da Met.no (próximas 2 h). Se
    prevê chuva e há porta/janela  aberta, avisa no iPhone. No máximo 1 aviso
    a cada 2 h.
  triggers:
  - trigger: time_pattern
    minutes: /15
  - trigger: state
    entity_id:
    - binary_sensor.opening_1
    - binary_sensor.opening_2
    - binary_sensor.opening_3
    - binary_sensor.opening_4
    - binary_sensor.opening_5
    - binary_sensor.opening_6
    - binary_sensor.opening_7
    - binary_sensor.opening_8
    - binary_sensor.opening_9
    from: 'off'
    to: 'on'
    for: 00:02:00
  conditions:
  - condition: template
    value_template: '{{ ["binary_sensor.opening_1", "binary_sensor.opening_2",
      "binary_sensor.opening_3", "binary_sensor.opening_4",
      "binary_sensor.opening_5", "binary_sensor.opening_6",
      "binary_sensor.opening_7", "binary_sensor.opening_8",
      "binary_sensor.opening_9"] | select(''is_state'',''on'') | list |
      count > 0 }}'
  - condition: template
    value_template: '{{ states(''input_datetime.ultimo_aviso_de_chuva'') in [''unknown'','''']
      or (now() - (states(''input_datetime.ultimo_aviso_de_chuva'') | as_datetime
      | as_local)).total_seconds() > 7200 }}'
  actions:
  - action: weather.get_forecasts
    target:
      entity_id: weather.forecast_home
    data:
      type: hourly
    response_variable: prev
  - variables:
      chuva: '{% set f = prev[''weather.forecast_home''].forecast[:2] %}{{ f | selectattr(''condition'',''in'',[''rainy'',''pouring'',''lightning-rainy'',''snowy-rainy'',''hail''])
        | list | count > 0 or (f | map(attribute=''precipitation'') | map(''float'',0)
        | max) >= 0.5 }}'
      mm: '{{ prev[''weather.forecast_home''].forecast[:2] | map(attribute=''precipitation'')
        | map(''float'',0) | max }}'
      abertos: '{% set ns = namespace(l=[]) %}{% for e in ["binary_sensor.opening_1",
        "binary_sensor.opening_2", "binary_sensor.opening_3",
        "binary_sensor.opening_4", "binary_sensor.opening_5",
        "binary_sensor.opening_6", "binary_sensor.opening_7",
        "binary_sensor.opening_8", "binary_sensor.opening_9"]
        if is_state(e,''on'') %}{% set ns.l = ns.l + [state_attr(e,''friendly_name'')
        | replace(''AMT 4010 '','''')] %}{% endfor %}{{ ns.l | join('', '') }}'
  - condition: template
    value_template: '{{ chuva }}'
  - action: notify.mobile_app_my_phone
    data:
      title: 🌧️ Previsão de chuva
      message: 'Pode chover nas próximas 2 h (até {{ mm }} mm/h). Aberto: {{ abertos
        }}.'
      data:
        push:
          interruption-level: time-sensitive
  - action: input_datetime.set_datetime
    target:
      entity_id: input_datetime.ultimo_aviso_de_chuva
    data:
      datetime: '{{ now().strftime(''%Y-%m-%d %H:%M:%S'') }}'
  mode: single
