How to avoid warning when setting brightness on turned off lamp

God morning all automation champions! I need your input to fix a small problem with my newest automation.

I have four automations in my living room (controlled by my TV remote via IR):

  1. Turn on / Toggle HUE scene,
  2. decrease brightness,
  3. increate brightness and
  4. turn off lights.

This works (almost) flawlessly!

Main question
How do I avoid setting the brightness on turned off bulbs which yields a massive warning in the home assistant log? (see bonus question)

See my automations here:

- alias: IRR_RED
  hide_entity: True
  trigger:
    platform: state
    entity_id: sensor.irremote
    to: 'red'
  action:
    service: script.next_preset_scene_tvstue

- alias: IRR_GREEN_1
  hide_entity: True
  trigger:
    platform: state
    entity_id: sensor.irremote
    to: 'green'
  #condition: state
  #  entity_id: light.tv_bnk
  #  state: 'on'
  action:
  - service: light.turn_on
    entity_id: light.tv_bnk
    data_template:
      #transition: 1
      brightness: >
        {% set state = (states.light.tv_bnk.attributes.brightness | int) - 50 -%}
        {%- if state < 0 -%}
          {%- set state = (0 | int)  -%}
        {%- endif %}
        {{ state }}
  - service: light.turn_on
    entity_id: light.pantella
    data_template:
      #transition: 1
      brightness: >
        {% set state = (states.light.pantella.attributes.brightness | int) - 50 -%}
        {%- if state < 0 -%}
          {%- set state = (0 | int)  -%}
        {%- endif %}
        {{ state }}
  - service: light.turn_on
    entity_id: light.sofabord
    data_template:
      #transition: 1
      brightness: >
        {% set state = (states.light.sofabord.attributes.brightness | int) - 50 -%}
        {%- if state < 0 -%}
          {%- set state = (0 | int)  -%}
        {%- endif %}
        {{ state }}

- alias: IRR_YELLOW
  hide_entity: True
  trigger:
    platform: state
    entity_id: sensor.irremote
    to: 'yellow'
  action:
  - service: light.turn_on
    entity_id: light.tv_bnk
    data_template:
      #transition: 1
      brightness: >
        {% set state = (states.light.tv_bnk.attributes.brightness | int) + 50 -%}
        {%- if state > 254 -%}
          {%- set state = (254 | int)  -%}
        {%- endif %}
        {{ state }}
  - service: light.turn_on
    entity_id: light.pantella
    data_template:
      #transition: 1
      brightness: >
        {% set state = (states.light.pantella.attributes.brightness | int) + 50 -%}
        {%- if state > 254 -%}
          {%- set state = (254 | int)  -%}
        {%- endif %}
        {{ state }}
  - service: light.turn_on
    entity_id: light.sofabord
    data_template:
      #transition: 1
      brightness: >
        {% set state = (states.light.sofabord.attributes.brightness | int) + 50 -%}
        {%- if state > 254 -%}
          {%- set state = (254 | int)  -%}
        {%- endif %}
        {{ state }}

- alias: IRR_BLUE
  hide_entity: True
  trigger:
    platform: state
    entity_id: sensor.irremote
    to: 'blue'
  action:
    service: light.turn_off
    entity_id: light.tv_bnk, light.sofabord, light.pantella

Bonus question:
WHY (ON EARTH!!!) (WHY WHY WHY) does the crime off setting the brightness on a turned off bulb yield a 39 (!!!) line warning in the log?

^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@$
Traceback (most recent call last):
  File "/srv/hass/hass_venv/lib/python3.4/site-packages/homeassistant/helpers/template.py", line 102, in async_render
    return self._compiled.render(kwargs).strip()
  File "/srv/hass/hass_venv/lib/python3.4/site-packages/jinja2/environment.py", line 1008, in render
    return self.environment.handle_exception(exc_info, True)
  File "/srv/hass/hass_venv/lib/python3.4/site-packages/jinja2/environment.py", line 780, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "/srv/hass/hass_venv/lib/python3.4/site-packages/jinja2/_compat.py", line 37, in reraise
    raise value.with_traceback(tb)
  File "<template>", line 1, in top-level template code
  File "/srv/hass/hass_venv/lib/python3.4/site-packages/jinja2/filters.py", line 542, in do_int
    return int(value)
jinja2.exceptions.UndefinedError: 'mappingproxy object' has no attribute 'brightness'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/usr/lib/python3.4/asyncio/tasks.py", line 237, in _step
    result = next(coro)
  File "/srv/hass/hass_venv/lib/python3.4/site-packages/homeassistant/components/automation/__init__.py", line 343, in async_trigger
    yield from self._async_action(self.entity_id, variables)
  File "/srv/hass/hass_venv/lib/python3.4/site-packages/homeassistant/components/automation/__init__.py", line 433, in action
    yield from script_obj.async_run(variables)
  File "/srv/hass/hass_venv/lib/python3.4/site-packages/homeassistant/helpers/script.py", line 151, in async_run
    yield from self._async_call_service(action, variables)
  File "/srv/hass/hass_venv/lib/python3.4/site-packages/homeassistant/helpers/script.py", line 181, in _async_call_service
    self.hass, action, True, variables, validate_config=False)
  File "/srv/hass/hass_venv/lib/python3.4/site-packages/homeassistant/helpers/service.py", line 74, in async_call_from_config
    config[CONF_SERVICE_DATA_TEMPLATE]))
  File "/srv/hass/hass_venv/lib/python3.4/site-packages/homeassistant/helpers/service.py", line 70, in _data_template_creator
    for key, item in value.items()}
  File "/srv/hass/hass_venv/lib/python3.4/site-packages/homeassistant/helpers/service.py", line 70, in <dictcomp>
    for key, item in value.items()}
  File "/srv/hass/hass_venv/lib/python3.4/site-packages/homeassistant/helpers/service.py", line 72, in _data_template_creator
    return value.async_render(variables)
  File "/srv/hass/hass_venv/lib/python3.4/site-packages/homeassistant/helpers/template.py", line 104, in async_render
    raise TemplateError(err)
homeassistant.exceptions.TemplateError: UndefinedError: 'mappingproxy object' has no attribute 'brightness'

You could check if the bulb is on first (use a condition), then it wouldn’t give the error, since an off bulb can’t accept a brightness call.

I kinda tried that with out luck, but I will look into it again. BUT … then the big question arises: Can I do this with some sort of a loop?

I need to check for each bulb, and I dont like the idea of having to create an automation for each bulb with a conditional check for the specific bulb … perhaps a script called for each bulb you might answer!? Great idea, I’ll try that!! (Some times the answers comes while asking the questions)

But still, a loop would be cool! Any ideas on this?

:sunglasses::metal:
/Tonkin

The following could work …
I haven’t tried the python script below …

#Python script
on = 0
for entity_id in hass.states.entity_ids('light'):
    state = hass.states.get(entity_id)
    if state.state == 'on':
        on = on + 1
for entity_id in hass.states.entity_ids('switch'):
    state = hass.states.get(entity_id)
    if state.state == 'on':
        on = on + 1
hass.states.set('sensor.lights_on', on, {
    'unit_of_measurement': 'lights',
    'friendly_name': 'Lights On'
})


This works in the dev panel but I can't get it to work as a sensor in HA
# Counts the number of lights/switches that are 'on'
       {% for state in states
           if ( 'light' in state.entity_id 
                and state.domain in ['light','switch']
                and state.state == 'on' ) -%}
         {% if loop.last -%}
           {{ loop.index }}
         {%- endif %}
       {% else %}
         0
       {%- endfor %}