custom-components / pyscript

Pyscript adds rich Python scripting to HASS
Apache License 2.0
874 stars 46 forks source link

Ordering various Pyscript script is unpredictable at cold boot #452

Closed dominig closed 1 year ago

dominig commented 1 year ago

I need to read a state variable maintain by a Pyscript from another pyscript. It works fine as long as I do not any cold boot. I have tried to make an active wait by trying to watch the variable creation with: state.names(domain=pyscript) before creating the triggers but it blocks the boot process on pyscript initialisation. A task.sleep(30) does not help either as it seems that initialisation of scripts is sequencial until a trigger call is reached. How to overcome the issue of requiring the existence of a state variable before proceeding ? A simple garanted startup order would do. Alphabetic, priority, ...

craigbarratt commented 1 year ago

As you discovered, the load order isn't guaranteed, and each file is loaded sequentially so you can't introduce delays at the top level.

Inside HASS & HACS, the load order of integrations isn't guaranteed either. So that's why pyscript doesn't arm any triggers until the EVENT_HOMEASSISTANT_STARTED event occurs, so it can be sure that all integrations are loaded and ready.

There are various solutions you could consider. For example, the script that sets the state variable can do so at load time (ie, not inside a function). The script that watches it can do so via a @state_trigger and/or @time_trigger("startup").

There are more direct ways of passing information between pyscript scripts. For example, you could put common code in a module and import that module into both scripts. You could also use async message queues or other constructs for sharing data. It's hard to tell which approach is best without knowing what you are trying to do.

dominig commented 1 year ago

Could be a good idea to make it clear in the documentation. Thanks Dominig

Le 27 mars 2023 01:19:09 GMT+02:00, Craig Barratt @.***> a écrit :

As you discovered, the load order isn't guaranteed, and each file is loaded sequentially so you can't introduce delays at the top level.

Inside HASS & HACS, the load order of integrations isn't guaranteed either. So that's why pyscript doesn't arm any triggers until the EVENT_HOMEASSISTANT_STARTED event occurs.

There are various solutions you could consider. For example, the script that sets the state variable can do so at load time (ie, not inside a function). The script that watches it can do so via a @._trigger` and/or @._trigger("startup")`.

-- Reply to this email directly or view it on GitHub: https://github.com/custom-components/pyscript/issues/452#issuecomment-1484261908 You are receiving this because you authored the thread.

Message ID: @.***>

craigbarratt commented 1 year ago

Actually, looking at the code, when it loads the scripts it does sort them in order of global context name. So the order should be repeatable.