Count how often script is called

This is a simple script that will count the number of times that it is invoked.

counter = hass.states.get('sensor.my_counter')

if counter is None:
    value = 0
else:
    value = int(counter.state)

hass.states.set('sensor.my_counter', value + 1)

6 Likes

Could you also add the counter as an attribute?

this_script = hass.states.get('python_script.this_script')

attributes = this_script.attributes.copy()
try:
    attributes['counter'] += 1
except KeyError:
    attributes['counter'] = 1

hass.states.set('sensor.my_counter',
    this_script.state, attributes=attributes)

Yep, you could do that too. Note that state attributes are immutable. Instead, you should create a copy and update it.

hass.states.set('sensor.my_counter', this_script.state, {
  'counter': value
})

So, would my edited code above be correct?

Try it out :stuck_out_tongue_winking_eye:

Ok, I have a script that works now. How do I make it run on a regular basis?

You will have to create an automation to trigger that. Also, please post the updated working script :slight_smile:

1 Like

Here is a sample python script that hides all the devices that have state “Online”, leaving just the “Offline” ones in the UI… I got so many devices, and I only ant to see the Offline devices in the group/card. This script takes care of that.

count = 0
for entity_id in hass.states.entity_ids('sensor'):
    entity_state_object = hass.states.get(entity_id)
    if entity_state_object.state == 'Online':
        attributes = entity_state_object.attributes.copy()
        attributes['hidden'] = True
        hass.states.set(entity_id, entity_state_object.state, attributes=attributes)
        count = count + 1

logger.info("{} entities are hidden.".format(count))
2 Likes

I think I’m doing the same thing here but, the attribute doesn’t appear to be updating:

    entity_id  = data.get('entity_id')
    states = hass.states.get(entity_id)
    atts = states.attributes.copy()

    if states.state == "off":
      atts['blackout'] = False
      hass.states.set(entity_id, states.state, atts)
    else:
      if states.attributes.get('blackout') == False:
        atts['blackout'] = True
        hass.states.set(entity_id, states.state, atts)

After the script has run while the entity is off I do not see the blackout attribute added to the entity. Where did I go wrong?

I didn’t think you could control the visiblity of entities / devices, only groups.

https://home-assistant.io/docs/configuration/group_visibility/