How best to generate a consistently random number?

Following HA’s documentation, I’d created a random sensor, but despite the doc saying “it generates a new state every time it is polled”, that wasn’t my experience (though I haven’t tried it since Oct 2020, can anyone confirm whether it works reliably now?).

Elsewhere in this forum I’ve seen mention of calling a python script, but I’m not currently a python coder. I could do it in a shell script, but am unaware how to import the value back into the automation.

My automation does the following – is this perhaps not “polling” the sensor sufficiently?

data_template:
  entity_id: input_number.process_chooser
  value: '{{ (states("sensor.random_number") | int) % 4 + 1 }}'
service: input_number.set_value

Is there a better alternative?

Thanks.

2 Likes

That isn’t meant to be understood as “every time the state is read”"
Factually, the value changes every 30 seconds.

You can use a template like

{{ range(1, 51) | random }}
4 Likes

Keep in mind that most “random” is not very random at all.
Most is a programmed sequence where you start at a different place and it loops the sequence.

There are some languages and functions that do better random than other, but I have no knowledge of yaml and python in this area.

This works perfectly. Thank you!

Ever since the upgrade to 7.X, this code has been giving me the following error:

2021-12-11 10:49:52 ERROR (SyncWorker_0) [homeassistant.util.yaml.loader] invalid key: "OrderedDict([('(range(3', None), ('10)|random)', None)])"
in "/config/automations.yaml", line 383, column 0
2021-12-11 10:49:52 ERROR (MainThread) [homeassistant.bootstrap] Failed to parse configuration.yaml: invalid key: "OrderedDict([('(range(3', None), ('10)|random)', None)])"
in "/config/automations.yaml", line 383, column 0. Activating safe mode

Anyone else having the same issue?

Hi,
Use quotemarks with the template and it’ll work as intended :slight_smile: e.g.

value_template: "{{ range(1, 51) | random }}"
3 Likes