Newbie - trigger function

Hello everybody,
I have automation,which torn on / of switch when some device change status from / to home. Automation is working well, but I feel like it can be written in some mor sophisticated way. Somethong shorter with IF / ELSE maybe… What would be best syntax?

  alias: PowerOnNotebook
  description: ''
  trigger:
  - entity_id: device_tracker.notebook
    from: not_home
    platform: state
    to: home
  condition: []
  action:
  - data:
      entity_id:
      - switch.63743864dc4f22d434c2
    service: switch.turn_on
    
- id: '1572906181158'
  alias: PowerOffNotebook
  description: ''
  trigger:
  - entity_id: device_tracker.notebook
    from: home
    platform: state
    to: not_home
  condition: []
  action:
  - data:
      entity_id:
      - switch.63743864dc4f22d434c2
    service: switch.turn_off

Please read point 11 here and edit your post accordingly.

Done. Thank you for warning :slight_smile:

Thank you. If you really want to introduce another level of complexity you can do this:

 alias: PowerNotebook
 trigger:
   platform: state
   entity_id: device_tracker.notebook
 action:
   service_template: >
     {% if trigger.to_state.state == 'home' %}
       switch.turn_on
     {% else %}
       switch.turn_off
     {% endif %}
   entity_id: switch.63743864dc4f22d434c2
1 Like

Thanks. This is exactly what I was looking for…

Just be aware that states like ‘unknown’ or ‘unavailable’ will also cause the light to turn off.

It’s ok in this case… but for my learning. How to remake it in this “sophisticated” way to work only when changing from home to not_home and vice versa? Condition with IF ELSE ?

Just add a condition to check if the tracker is one of the two valid states.

alias: PowerNotebook
trigger:
  platform: state
  entity_id: device_tracker.notebook
condition:
  condition: or
  conditions:
    - condition: state
      entity_id: device_tracker.notebook
      state: 'home'
    - condition: state
      entity_id: device_tracker.notebook
      state: 'not_home'
action:
  service_template: >
    {% if trigger.to_state.state == 'home' %}
      switch.turn_on
    {% else %}
      switch.turn_off
    {% endif %}
  entity_id: switch.63743864dc4f22d434c2

OK. Thank you.