Random Sensor - how to get new random number for every pull?

I am trying to get the Random sensor to provide a new random number every time I make a service call.

In the test-example below I’m checking the state, but as you can see, it’s giving me the same random number repeatedly. I’m only seeing the Random Sensor change output every 20 to 60 seconds… My actual use-case requires a sequence of 3-5 random numbers (in a python script) all at the same time.

I feel like I’m missing something… any guesses?

Here’s what i’m doing - happens to be in a Python_Script, but I’m simply making calls to the sensor state, so I can’t imagine this is significantly different behavior via YAML:

r1 = float(hass.states.get('sensor.Random').state)
logger.warning('TEST -- number 1 is ' + str(r1))

r2 = float(hass.states.get('sensor.Random').state)
logger.warning('TEST -- number 2 is ' + str(r2))

r3 = float(hass.states.get('sensor.Random').state)
logger.warning('TEST -- number 3 is ' + str(r3))

Looking at the log, I got the same number all three requests:

TEST – number 3 is 362.0
7:26 AM components/python_script/init.py (WARNING)

TEST – number 2 is 362.0
7:26 AM components/python_script/init.py (WARNING)

TEST – number 1 is 362.0
7:26 AM components/python_script/init.py (WARNING)

Any thoughts? Again, I can waiting a bit and re-run, which provides a new random numbers, but only after some number of seconds (or maybe some cache expiring). I need them all basically at the same time.

Lastly, just for completeness’ sake, my Configuration.yaml entry for the sensor itself. This is why the random number is well above the normal Max default of 20:

- platform: random
  name: random
  minimum: 0
  maximum: 1000
  icon: mdi:dice-5

Any ideas / extra bits of knowledge (and of course, overt solutions) are most welcome! Thanks!

Since you want random numbers to use in python_script, why not use random function directly?

In python_script:

r1=random.random()*1000;
r2=random.random()*1000;
logger.warning('TEST -- number 1 is ' + str(r1)+'  -- number 2 is ' + str(r2))

TEST -- number 1 is 106.6380579977787 -- number 2 is 249.06186242782601

The random numbers can also be saved using hass.services.call to entities like input_number or sensor.

1 Like

So… OK. Easiest answer ever, thank you!

I swear, I tried using random.random() in the past and it didn’t work. Python scripts within HA have disallowed importing libraries, and last time I tried to get a random number (for another use-case) the random lib wasn’t loaded and I couldn’t import myself.

Apparently the random lib is now loaded. Yay! On the down-side, that makes this the stupidest question I’ve ever asked. Boo!

Anyway, thanks for the help!

I know, python_script can be hit-n-miss with the lib.
Welcome back.