Skip to content

Instantly share code, notes, and snippets.

@SamMousa
Created November 20, 2023 13:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SamMousa/35116327d1f3f2b2c6fe21c5492edb6c to your computer and use it in GitHub Desktop.
Save SamMousa/35116327d1f3f2b2c6fe21c5492edb6c to your computer and use it in GitHub Desktop.
HA Scripted Mutex

Final solution:

  • Acquiring a lock is the only action that is serialized via a script
  • Releasing the lock is done by writing an empty value to the input_text helper

The script looks like this

alias: lock1
sequence:
  - wait_template: "{{ is_state('input_text.lock1_owner', '') }}"
    continue_on_timeout: true
    alias: Wait for lock to be available
  - service: input_text.set_value
    data:
      value: "{{ owner }}"
    target:
      entity_id: input_text.lock1_owner
    alias: Set lock owner
mode: queued
fields:
  owner:
    selector:
      text: null
    name: owner
    description: Name of the owner
    required: true

You will need 1 script and 1 variable per mutex.

Example automations that use the mutex:

alias: Exclusive 1
description: ""
trigger:
  - platform: event
    event_type: ""
condition: []
action:
  - variables:
      lock_name: exclusive1
  - service: script.lock1
    data:
      owner: "{{ lock_name }}"
    alias: Request lock
  - delay:
      hours: 0
      minutes: 0
      seconds: 10
      milliseconds: 0
  - alias: Release lock
    service: input_text.set_value
    data:
      value: ""
    target:
      entity_id: input_text.lock1_owner
mode: single

And another one that contests the same lock

alias: Exclusive 2
description: ""
trigger:
  - platform: event
    event_type: ""
condition: []
action:
  - variables:
      lock_name: exclusive2
  - service: script.lock1
    data:
      owner: "{{ lock_name }}"
    alias: Request lock
  - delay:
      hours: 0
      minutes: 0
      seconds: 10
      milliseconds: 0
  - alias: Release lock
    service: input_text.set_value
    data:
      value: ""
    target:
      entity_id: input_text.lock1_owner
mode: single
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment