I misunderstood what your code does. This was the bit of information I was missing: Input Number - Home Assistant
It took me a while to twig input numbers
are a “thing”.
This is what I have done:
templates.yaml
- trigger:
- platform: time
at: '00:00:00'
- platform: event
event_type: event_template_reloaded
- platform: homeassistant
event: start
sensor:
- name: 'Random time'
unique_id: 'random_time'
state: >
{% set x = states('input_number.random_time_offset') | int(0) %}
{{ today_at('00:14') + timedelta(minutes = [x, -x] | random) }}
device_class: timestamp
configuration.yaml
# standard bits...
automation: !include automations.yaml
template: !include templates.yaml
input_number:
random_time_offset:
name: random_time_offset
initial: 10
min: 0
max: 59
step: 1
unit_of_measurement: minutes
The documentation says to do this by UI, under Settings > Devices & Services > Helpers, but I couldn’t see the initial
attribute in the UI which I believed was the way to set the value, but this is not the case as @123 says:
This is what I have done:
automations.yaml
alias: lights-outdoor-off-22:40r
description: Turn off outside lights
trigger:
- platform: time
at: sensor.random_time
condition: []
action:
... etc ...
This has been a great learning exercise, but it seems a little overkill for what I was trying to achieve. All I want is to be able to set a variable with the value of x
…
…further reading…
…perhaps the term “constant” is more appropriate here. I don’t wish to get into any arguments about programming terminology, but in another automation tool (Azure DevOps) I can do this:
somefile.yaml
variables:
- name: projectName
value: contoso
steps:
- bash: echo $(projectName)
- powershell: echo $(projectName)
- script: echo $(projectName)
Source: Define variables - Azure Pipelines | Microsoft Learn
In this case, I get that the “variable” is not changing, so “constant” is possibly more appropriate, but, it is possible to programmatically change the value of projectName
so I guess this is why Microsoft call them variables, Although, in Hashicorp’s Terraform, they use the term “variable” and their values don’t change programmatically. Their values are set at runtime.
As discussed here, it would be nice to set a variable/constant and refer back to it, so if it changes, it only has to be changed once. So for example:
Theoretical example - doesn’t work
variables:
- name: time_offset
value: 10
sensor:
- name: 'Random time'
unique_id: 'random_time'
state: >
{{ today_at('00:14') + timedelta(minutes = [var.time_offset, -var.time_offset] | random) }}
device_class: timestamp
I hope that makes sense and thanks for the help.