Problem (bug?) with Reload Scripts when using 'delay'

In order not to unnecessarily hammer an external api I often introduce looping scripts with delays.

It seems to me that there is a problem with using ‘Reload Scripts’ if you have scripts that use delay. Now, I don’t expect the delay itself to be maintained across reloads but I think this goes beyond that.

I have an example below of how I do it followed by the errors I get if I manually start the script after a reload.

I’d be interested if anyone here who has a development instance of HA can reproduce this? Or of course offer an alternative explanation for the errors I get?

script:
  smartweather_set_sensor_interval:
    sequence:
      - service_template: >
          script.loop_smartweather_set_sensor_interval
        data_template:
          interval: >
            {% if states('sensor.elevation') | float >= -6 and 
                  states('input_select.sensor_for_darkness') == 'smartweather_average_illuminance' %}
              {% if states('sensor.smartweather_average_illuminance') | int <= 5000 %}
                00:01:00
              {% elif states('sensor.smartweather_average_illuminance') | int <= 7500 %}
                00:15:00
              {% else %}
                00:30:00
              {% endif %}
            {% elif states('sensor.elevation') | float >= -6 and 
                    states('input_select.sensor_for_darkness') == 'brightness' %}
              {% if states('sensor.brightness') | int <= 25 %}
                00:01:00
              {% elif states('sensor.brightness') | int <= 30 %}
                00:15:00
              {% else %}
                00:30:00
              {% endif %}
            {% else %}
              18:00:00
            {% endif %}


  #========================================================================
  #=== Update the sensor and loop the script that sets the sensor interval
  #===
  #=== Passed
  #===  interval - time to wait between sensor updates
  #========================================================================
  loop_smartweather_set_sensor_interval:
    sequence:
      - service: homeassistant.update_entity
        entity_id: sensor.smartweather_aaaa

      - delay: "00:00:05"
      
      - service: homeassistant.update_entity
        entity_id: sensor.smartweather_bbbb

      - delay: "00:00:05"
      
      - service: homeassistant.update_entity
        entity_id: sensor.smartweather_cccc

      - delay: "{{ interval }}"

      - service: script.smartweather_set_sensor_interval

Errors:

Error executing service <ServiceCall script.smartweather_set_sensor_interval (c:ea2f27a05309415da9bd38a574812dcb)>
Traceback (most recent call last):
  File "/usr/src/homeassistant/homeassistant/core.py", line 1244, in _safe_execute
    await self._execute_service(handler, service_call)
  File "/usr/src/homeassistant/homeassistant/core.py", line 1261, in _execute_service
    await handler.func(service_call)
  File "/usr/src/homeassistant/homeassistant/components/script/__init__.py", line 142, in service_handler
    await script.async_turn_on(variables=service.data, context=service.context)
  File "/usr/src/homeassistant/homeassistant/components/script/__init__.py", line 214, in async_turn_on
    raise err
  File "/usr/src/homeassistant/homeassistant/components/script/__init__.py", line 209, in async_turn_on
    await self.script.async_run(kwargs.get(ATTR_VARIABLES), context)
  File "/usr/src/homeassistant/homeassistant/helpers/script.py", line 190, in async_run
    await self._handle_action(action, variables, context)
  File "/usr/src/homeassistant/homeassistant/helpers/script.py", line 274, in _handle_action
    await self._actions[_determine_action(action)](action, variables, context)
  File "/usr/src/homeassistant/homeassistant/helpers/script.py", line 357, in _async_call_service
    context=context,
  File "/usr/src/homeassistant/homeassistant/helpers/service.py", line 97, in async_call_from_config
    domain, service_name, service_data, blocking=blocking, context=context
  File "/usr/src/homeassistant/homeassistant/core.py", line 1236, in async_call
    await asyncio.shield(self._execute_service(handler, service_call))
  File "/usr/src/homeassistant/homeassistant/core.py", line 1261, in _execute_service
    await handler.func(service_call)
  File "/usr/src/homeassistant/homeassistant/components/script/__init__.py", line 139, in service_handler
    if script.is_on:
AttributeError: 'NoneType' object has no attribute 'is_on'

-------------
Error executing script script.smartweather_set_sensor_interval. Unknown error for call_service at pos 1: 
Traceback (most recent call last):
  File "/usr/src/homeassistant/homeassistant/components/script/__init__.py", line 209, in async_turn_on
    await self.script.async_run(kwargs.get(ATTR_VARIABLES), context)
  File "/usr/src/homeassistant/homeassistant/helpers/script.py", line 190, in async_run
    await self._handle_action(action, variables, context)
  File "/usr/src/homeassistant/homeassistant/helpers/script.py", line 274, in _handle_action
    await self._actions[_determine_action(action)](action, variables, context)
  File "/usr/src/homeassistant/homeassistant/helpers/script.py", line 357, in _async_call_service
    context=context,
  File "/usr/src/homeassistant/homeassistant/helpers/service.py", line 97, in async_call_from_config
    domain, service_name, service_data, blocking=blocking, context=context
  File "/usr/src/homeassistant/homeassistant/core.py", line 1236, in async_call
    await asyncio.shield(self._execute_service(handler, service_call))
  File "/usr/src/homeassistant/homeassistant/core.py", line 1261, in _execute_service
    await handler.func(service_call)
  File "/usr/src/homeassistant/homeassistant/components/script/__init__.py", line 139, in service_handler
    if script.is_on:
AttributeError: 'NoneType' object has no attribute 'is_on'

Seems like it’s trying to access the script before it exists.

Yeah that could make sense (I think) as I have an automation that kicks the whole thing off but I wouldn’t have expected a script reload to have triggered the automation.

And in any case even if I left it a minute I still couldn’t get the script to start. Something is getting its knickers in a twist. I did a restart and all is well so maybe I need to just be a bit cautious when using reload?

Just for completeness, here is the automation (sun elevation is currently way below -6)

  - alias: SmartWeather Set Up Sensors
    trigger:
      - platform: homeassistant
        event: start

      - platform: numeric_state
        entity_id: sensor.elevation
        value_template: "{{ states('sensor_elevation') | float }}"
        above: -6

    action:
      - service: homeassistant.turn_off
        entity_id: 
          - script.loop_smartweather_set_sensor_interval
          - script.smartweather_set_sensor_interval
      
      - delay: '00:00:01'

      - service: script.smartweather_set_sensor_interval


it depends on the automation. What’s the trigger for the automation?

Sorry I was editing as you replied, see post above.

Reloads might be treated as a start event but I doubt it. Might be worth writing up an issue.

Does it produce that error only right after you reload the scripts or does it continue doing it until you restart HA?

I know I’ve experienced a considerable delay (up to 5 minutes) sometimes between the time scripts actually reload and when the green highlighting on the reload scripts button has flashed. I also usually get a cryptic error or two in the log along the lines of script something or other already exists. I actually watch for those errors now to determine if the scripts have reloaded yet or not before I test for the changes. It’s not the same error as you’re getting here though.

This caught my eye because I have a similar situation with my google traffic sensors. I have to limit the API calls so I don’t run up any charges there. I approached it a little differently than you did though. I’m wondering if changing it to something like the way you’ve done it might be a little more efficient.

Basically I have a handful of automations like the one below with various time pattern triggers that use conditions to determine which one should be running. I’m probably doing a lot of unnecessary polling though? Honestly I’m not sure how much unnecessary resources are used when automations are constructed like this. Seems to run well enough.

  trigger:
    - platform: time_pattern
      minutes: '/2'
  condition:
    - condition: state
      entity_id: binary_sensor.afternoons_work_commute
      state: 'on'
  action:
    - service: homeassistant.update_entity
      entity_id: sensor.jason_time_to_work

Back to your error (don’t mean to hijack your thread!). Have you tried reloading your scripts without the delays in this one to make sure that’s where the issue is?

It makes sense that this error only occurs on scripts with delays. Scripts with delays are on when executing and off when not executing. Scripts without delays do not have a toggling state, they always appear off. And his error is specifically related to ‘is_on’ property of a script.

EDIT: reworded

@jazzyisj
I think it carries on until I restart HA. I will do some experimenting but not now, there are too many people in the house to want to risk upsetting them with things not working ! :slight_smile:

Either way it is good to know I might have a more efficient method for you to investigate. I always wonder about polling too but also wonder how necessary that concern is… I do try to avoid time pattern triggers unless it is absolutely necessary.

@petro
Where would I raise this? And I don’t want to be flippant but will anyone care? Is it a bug or expected behaviour, albeit not very welcome? Could it be related only to reloading with packages? I know it took a while before reloading was even possible with packages and I never understood why it was introduced without even a whisper so could it be that it is kind of unofficial and we just take it or leave it?

github on the backend home assistant repository.

I think you’d get a response from the dev team.

I personally don’t think it’s expected behavior. That section of code should be testing against None type objects, which it’s not. That’s the root cause of the error.

Yes, but I’ve seen the error before and I don’t use packages. Was just too lazy to dive into the root cause of the issue.

Purely up to you. I’m sure it will be brought up in the future if it already hasn’t been brought up. Remember, there’s no harm in writing up an issue. It’s always good to document.

2 Likes

Ok, I’ll raise an issue in the next day or so.

In the meantime perhaps you could confirm or deny a fairly major documentation error I came across whilst I’ve been troubleshooting and refining this?

I could not define an input_boolean without providing min: and max: but the docs clearly say that everything is optional.


My config was this - config check passed and no errors in the logs but none of the input texts were created:
input_text:
  smartweather_1111_timestamp:

  smartweather_2222_timestamp:

  smartweather_3333_timestamp:

This worked:

input_text:
  smartweather_1111_timestamp:
    min: 0
    max: 15

  smartweather_2222_timestamp:
    min: 0
    max: 15

  smartweather_3333_timestamp:
    min: 0
    max: 15

What’s the error? I’d be willing to bet the voluptuous is set up incorrectly. EDIT: It looks correct. So, what’s the error?

That’s just it. there wasn’t one.
The input texts just didn’t exist.
Took me ages to realise as I was looking for problems elsewhere. didn’t even think to look at those input texts until I’d exhausted everything else

Hmm, that doesn’t make sense. The flow shows that it should be created no matter what.

Yeah… it felt a bit unlikely to me too.
Which is why I slipped it into a topic no one else seems to be reading. :sunglasses:

I’ll see if I can replicate it again…

I got a bit worried for a minute… I added an input text with no options to the file with some already defined and it worked. :scream:

I then created a new file and just put one input text on it’s own.
That didn’t work.

Here are the details.

Input texts defined in file 1:

#================
#=== Input Texts
#================
input_text:
  smartweather_1111_timestamp:
    min: 0
    max: 15

  smartweather_2222_timestamp:
    min: 0
    max: 15

  smartweather_3333_timestamp:
    min: 0
    max: 15

Input text defined in file 2:

#================
#=== Input Texts
#================
input_text:
  smartweather_1234_timestamp:

Dev-States:

I’ve now raised issues for both of these…

I am adding the link to the script issue as there has been no notice taken of it so far on Github. Just in case anyone else reads this and wants to comment.

(The input_text issue has been fixed)