Add Docs for template locks' code_format_template (#32791)

* Add docs for code_format_template

* Handle template render errors

* Apply suggestions from code review

Co-authored-by: c0ffeeca7 <38767475+c0ffeeca7@users.noreply.github.com>

---------

Co-authored-by: c0ffeeca7 <38767475+c0ffeeca7@users.noreply.github.com>
This commit is contained in:
chammp 2024-06-10 14:00:37 +02:00 committed by GitHub
parent a4ba880f0a
commit a14dbc7d89
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -60,6 +60,11 @@ lock:
required: false
type: template
default: true
code_format_template:
description: Defines a template to get the `code_format` attribute of the entity. This template must evaluate to a valid [Python regular expression](https://docs.python.org/3/library/re.html#regular-expression-syntax) or `None`. If it evaluates to a not-`None` value, the user is prompted to enter a code when interacting with the lock. The code will be matched against the regular expression, and only if it matches, the lock/unlock actions will be executed. The actual _validity_ of the entered code must be verified within these actions. If there's a syntax error in the template, the entity will be unavailable. If the template fails to render for other reasons or if the regular expression is invalid, no code will be accepted and the lock/unlock actions will never be invoked.
required: false
type: template
default: None
lock:
description: Defines an action to run when the lock is locked.
required: true
@ -156,3 +161,40 @@ lock:
```
{% endraw %}
### Lock from switch with dynamic code
This example shows a lock that copies data from a switch. It needs a PIN code defined as a [secret](/docs/configuration/secrets) to unlock and no code to lock. Note that the actual validity check of the code is part of the `unlock` action and should always happen there or in scripts called from these actions. In this way, you can not only perform code checks against static values, but also dynamic ones (for instance, TOTPs).
{% raw %}
```yaml
lock:
- platform: template
name: Garage Door
value_template: "{{ is_state('switch.source', 'on') }}"
code_format_template: "{{ '\\d{4}' if is_state('switch.source', 'on') else None }}"
lock:
- service: switch.turn_on
target:
entity_id: switch.source
unlock:
- variables:
pin: !secret garage_door_pin
- condition: "{{ code == pin }}"
- service: switch.turn_off
target:
entity_id: switch.source
```
{% endraw %}
In `secrets.yaml`:
{% raw %}
```yaml
garage_door_pin: "1234"
```
{% endraw %}