Restart IOT devices when unavailable but still reachable

Hello,

I’ve built an automation which should restart my Shelly devices whenever they are unavailable by HA but it is still possibe to access through http that I check with the NMAP integration. Together with automation this I’ve built two python scripts that handle the Shelly API Gen1 and Gen2.

Starting by the error:

2024-03-30 17:01:23.070 ERROR (MainThread) [homeassistant.helpers.template] Template variable error: 'None' has no attribute 'split' when rendering '{{ device_attr('{{ trigger.to_state.state.entity_id }}','configuration_url').split('/')[2].title()}}'
2024-03-30 17:01:23.071 ERROR (MainThread) [homeassistant.components.automation.shelly_restart_when_unavailable] Error rendering variables: UndefinedError: 'None' has no attribute 'split'

This works on the template editor:

{{ device_attr('sensor.shelly_luz_garagem_rssi','configuration_url').split('/')[2].title()}}

Result: 192.168.1.129

However this fails in the automation (btw I’m not proficient in yaml…) and no doubt the issue is here and all the other variables that use the the trigger.to_state
I’ve already tried different combinations… before open this topic :slight_smile: but without success.

{{ device_attr('{{ trigger.to_state.state.entity_id }}','configuration_url').split('/')[2].title()}}

Here is the automation that might be usefull for somebody:

- id: shelly_restart_when_unavailable
  alias: shelly_restart_when_unavailable
  description: 'Reboot Shelly if Unavailable for x Minutes'
  trigger:
    - platform: state
      entity_id: 
        - sensor.shelly_luz_escadas_sotao_e_arrecadacao_rssi
        - sensor.shelly_luz_escadas_andar_1_rssi
        - sensor.shelly_luz_garagem_rssi
        - sensor.shelly_em_maquina_lavar_secar_rssi
        - sensor.shelly_em_quadro_sotao_rssi
        - sensor.shellyplug_4aa5fc_rssi
        - sensor.shelly_recuperador_calor_rssi
        - sensor.receptor_satelite_sala_rssi
        - sensor.shelly_luz_wc_andar_1_rssi
        - sensor.shelly_luz_wc_servico_rssi
        - sensor.shelly_luz_wc_suite_rssi
        - sensor.shelly_pro_3em_quadro_principal_rssi
      to:
        - unavailable
      for:
        minutes: 5
  variables: # missing code for  Shelly Gen3
    shelly_name: >
       {{ device_attr('{{ trigger.to_state.state.entity_id }}','name_by_user')}}
    shelly_ip: >
      {{ device_attr('{{ trigger.to_state.state.entity_id }}','configuration_url').split('/')[2].title()}}             
    shelly_gen: >
      {{ device_attr('{{ trigger.to_state.state.entity_id }}','hw_version').split(' ')[0]}}  
    shelly_device_tracker: >
      {% set ip_dev= device_attr('{{ trigger.to_state.state.entity_id }}','configuration_url').split('/')[2].title()%}
        {{ (states.device_tracker | map(attribute='entity_id') | select('is_state_attr', 'ip', ip_dev) | list)[0] }}
    service_gen: >
      {% if (device_attr('{{ trigger.to_state.state.entity_id }}','hw_version').split(' ')[0]) == 'gen1' %}
        pyscript.shelly_gen1_reboot
      {% else %}
        pyscript.shelly_gen2_reboot
      {% endif %}   
  action:
    - if:
      - condition: template
        value_template: >-
          {{ states('{{ shelly_device_tracker }}') == 'home' }}    
      then: 
        - service: '{{ service_gen }}'
          data:
            ip: '{{ shelly_ip }}'
        - wait_template: "{{ trigger.to_state.state != 'unavailable' and trigger.to_state.state != 'unknown' }}"
          timeout:
            minutes: 3
        - if:
            - "{{ wait.completed }}"
          then:
            - service: persistent_notification.create
              data:
                title: >
                  Shelly Available after Restart!
                message: >
                  Dispositivo: {{ shelly_name }}{{ '\n' -}}
                  Generation: {{ shelly_gen }}{{ '\n' -}}
                  Endereço IP: {{ shelly_ip }}{{ '\n' -}}
                  Shelly Device Tracker: {{ states('{{ shelly_device_tracker }}') }}{{ '\n' -}}
                  Em {{as_timestamp(now()) | timestamp_custom('%d/%m/%Y as %T')}}
          else:
            - service: notify.joao_ios_mobile
              data:
                title: "Shelly Unavailable After Restart! \u26a0\ufe0f"
                message: >
                  Generation: {{ shelly_gen }}{{'\n'}}
                  Endereço IP: {{ shelly_ip }}{{'\n'}}
                  Em {{ as_timestamp(now()) | timestamp_custom('%d/%m/%Y as %T') }}
                data:
                  subtitle: "{{ shelly_name  }}"
                  url: /lovelace/main-control
                  presentation_option:
                    - alert
                    - badge          
                  push:
                    interruption-level: time-sensitive          
                    badge: 191
                    sound: none            
      else:
        - service: notify.joao_ios_mobile
          data:
            title: "Shelly Unavailable & Offline! \u26a0\ufe0f"
            message: >
              Generation: {{ shelly_gen }}{{'\n'}}
              Endereço IP: {{ shelly_ip }}{{'\n'}}
              Em {{ as_timestamp(now()) | timestamp_custom('%d/%m/%Y as %T') }}
            data:
              subtitle: "{{ shelly_name  }}"
              url: /lovelace/main-control
              presentation_option:
                - alert
                - badge          
              push:
                interruption-level: time-sensitive          
                badge: 191
                sound: none
  mode: parallel
  max: 15 

trigger.to_state is the state object of the entity that caused the trigger to fire. If you want the state (eg 'on' or '35.6' or 'unavailable') it is trigger.to_state.state. If you want the entity_id (e.g. 'sensor.kitchen_temperature') it is trigger.to_state.entity_id.

trigger.to_state.state.entity_id will always be undefined

Also, you can’t, and don’t need to, nest templates. If you don’t put quotes around text it will be interpreted as a variable. If shelly_device_tracker is a variable that contains an entity_id as a string, the template to check its state against the string home is simply:

{{ states(shelly_device_tracker) == 'home' }}
1 Like

I’ve started with that before… and didn’t work but I can try again. Do you mean like this?

{{ device_attr('{{ trigger.to_state.entity_id }}','configuration_url').split('/')[2].title()}}

Thank you for catching also this one.

Yes but without the nested template.

{{ device_attr(trigger.to_state.entity_id, 'configuration_url').split('/')[2].title() }}
1 Like

Why are the devices going unavailable?

I’d like to know too. I have a lot of Shelly devices and this doesn’t happen to mine.

One guess is a problematic network. Have you tried reloading the integration instead? Much simpler, but still a workaround for the real issue.

Have you updated the firmware of your Shelly devices?

2 Likes

Good question! I have the followig beaviour randomly after weeks or months.

  1. HA no longer manage them… status unavailable
    i. The shelly is out of the network (no ping, no access) - only turn off the breaker
    ii. The shelly is sttil in the network, the browser doesn’t load anymore

On both most of the times the physically switch stops control the device and the family complains :slight_smile:

As mentioned by @parautenbach, is the Shelly firmware up-to-date?

What are are the models of the Shelly devices having the problems?

This might be a hardware problem. Have you tried changing/replacing the device?

This is very randomly and I doubt that is an HW problem. I’m a firmware upgrade fanatic :slight_smile:
In fact has been improved over the time and sometimes take weeks or months. Please see my answer to @parautenbach

1 Like

I too have had doubts about hardware but I have been proven wrong many times.

If it is not a hardware or firmware problem, then I suspect it is a network issue.

This is most definitely a hardware or firmware problem. Because this. The device is hanging. That’s why it won’t control the load. That only happens when the firmware stops running. Because hardware or firmware.

2 Likes

Agree, but this has improved with the latest fw versions. As a curosity the ones used more often are the ones that hang more but still work for weeks before happen.

Forgot to share, have three models that already happened:

  1. Shelly 2PM (Gen2)
  2. Shelly 1 PM (Gen1)
  3. Shelly Plus Plug S (Gen2)

On these models I don’t recall of any issue:

  1. Shelly Pro 3M (I only have one unit) (Gen2)
  2. Shelly Plug (Gen1)
  3. Shelly EM (Gen1)

Have you tried enabling debugging to see what is happening?

image

No I did not but I can enable. The troubleshoot is quite long since can take 3 or 4 weeks to happen a again.

I’ve made the changes. As soon I get the confirmation that works will mark your answer as the solution. Thank you.