There are multiple changes I would make to make this work.
First, I would use homeassistant.turn_off instead of light or switch. That way, you can use a single service to turn off lights and switches.
Second, you need to list the services instead of using a single service. This is defined by using a - in the turn_on/turn_off section. They are like actions, they can contain a single service or multiple if you format it correctly.
3rd, I’d try to shorten the value_template. Some people don’t like this because it is more complicated. Anways, what it does is search through all the lights listed in the list, finds which ones are off. Then it compares the length of the off list to the length of the list you provided. If they are not equal, that means one of the lights is on. The beauty of this format is that if you get more lights, you just need to add it to the list. Quick and easy. You could even put all your lights into a group and adjust the formula so you don’t need to call out the list.
Using a list:
modo_notte:
friendly_name: Modo notte
value_template: >
{% set locked = is_state('lock.porta_ingresso', 'locked') %}
{% set lights = [ 'light.cameretta', 'light.cucina', 'light.soggiorno', 'light.ingresso', 'light.ripostiglio', 'switch.salotto_luci_vetrina' ] %}
{% set off = states | selectattr('entity_id', 'in', lights) | selectattr('state','eq','off') | list %}
{{ locked and off | length == lights | length }}
turn_on:
- service: lock.lock
data:
entity_id: lock.porta_ingresso
- service: homeassistant.turn_off
data:
entity_id: light.cameretta, light.cucina, light.ingresso, light.soggiorno, light.ripostiglio, switch.salotto_luci_vetrina
turn_off:
- service: lock.unlock
data:
entity_id: lock.porta_ingresso
This next example uses a group. It’s very complicated code but all you have to do for maitnence is add a light to a group instead of modifying your switch template. I used an example group with the entity id of group.mylights.
modo_notte:
friendly_name: Modo notte
value_template: >
{% set locked = is_state('lock.porta_ingresso', 'locked') %}
{% set lights = state_attr('group.mylights','entity_id') %}
{% set off = states | selectattr('entity_id', 'in', lights) | selectattr('state','eq','off') | list %}
{{ locked and off | length == lights | length }}
turn_on:
- service: lock.lock
data:
entity_id: lock.porta_ingresso
- service: homeassistant.turn_off
data_template:
entity_id: >
{{ states | selectattr('entity_id', 'in', state_attr('group.mylights', 'entity_id')) | selectattr('state', 'eq', 'on') | map(attribute='entity_id') | list | join(', ') }}
turn_off:
- service: lock.unlock
data:
entity_id: lock.porta_ingresso