Pyscript - new integration for easy and powerful Python scripting

Thanks!!! it works!!!

1 Like

I have an issue where an function doesn’t trigger, and for the life of me I can’t find out why.

The function with triggers:

@state_trigger("binary_sensor.platetopp == 'on' or binary_sensor.stekeovn == 'on'")
@state_trigger("binary_sensor.platetopp == 'off' or binary_sensor.stekeovn == 'off'", state_hold=900)
def manage_kitchen_fan(value=None, var_name=None):
    if value == 'on':
        switch.turn_on(entity_id='switch.kjokken_vifte')

        if var_name == 'binary_sensor.platetopp':
            light.turn_on(entity_id="light.kjokken_viftelys", brightness=255)
    else:
        switch.turn_off(entity_id='switch.kjokken_vifte')

        if not light.taklys_kjokken == 'on':
            light.turn_off(entity_id="light.kjokken_viftelys")

And history (at 09:04 I shut off the switch kjokken_vifte and light kjokken_viftelys manually.

By my account it should have trigger at 08:54 but as you can see that never happend?

You can only have one (1) @state_trigger (that’s why the first has a “or” statement").

I would split them up in 2 functions, one triggers when on and the other when off for 900s. That way you can ditch the if statement.

I’m not sure I fully understand what you are trying to do. However, given your example, the 2nd @state_trigger indeed will not trigger since binary_sensor.stekeovn == 'off' is always True, and therefore the expression binary_sensor.platetopp == 'off' or binary_sensor.stekeovn == 'off' will also be always True. Since that expression never transitions from False to True, the 2nd trigger does not occur.

Do you simply need to use and instead of or? So the second trigger will be:

state_trigger("binary_sensor.platetopp == 'off' and binary_sensor.stekeovn == 'off'", state_hold=900)

The expression will be False when either are on, and will become True when both are off. Then the trigger will happen 900 sec later, provided they both stay off.

No, you can have multiple @state_triggers on a single function.

Also, using or to combine multiple expressions will not behave the same as separate triggers:

@state_trigger("EXPR1 or EXPR2")

is not the same as:

@state_trigger("EXPR1")
@state_trigger("EXPR2")

For example, consider the case where EXPR1 is True. In the first case the trigger will never happen, no matter how EXPR2 changes, since the overall expression is always True. In the 2nd case. EXPR2 will cause a trigger whenever it changes from False to True.

2 Likes

I’m trying integrate my domotic system with HA.
Integration doesn’t exist yet.
I’m new to python and even more with HA coding

But I’ve manage to write in virtual code studio a python that open the connection and can send a command.
i’d like to execute this via ha and tought pyscript could do it.

Am I on the correct path ?
Any suggestion is welcome :slight_smile:

@state_trigger("EXPR1 or EXPR2")

is not the same as:

@state_trigger("EXPR1")
@state_trigger("EXPR2")

I am aware you are the author of Pyscript, but is that correct? Your docs say:

Whenever any of the state variables or attribute values mentioned in the expression change (or specified via the watch argument), the expression is evaluated and the trigger occurs if it evaluates to True (or non-zero).
(Reference — hacs-pyscript 1.5.0 documentation)

I understand that such that actually, @state_trigger("EXPR1 or EXPR2") should trigger whenver EXPR2 changes, while EXPR1 is constantly True.

First of all, @craigb, let me thank you for this great Addon to HA. In only a few days, it has completely changed my approach to automations and blown the scope of what I consider possible and doable. I was working with NodeRed before, and while it is capable of a lot of things, it’s just so tedious to figure out how to do something a bit more complex. With pyscript, it’s all super easy and straightforward.

I have one question, though, maybe I am to blind to figure it out by myself: can I create an entity from pyscript, that I can manipulate directly from Lovelace? Specifically, I would like to set up enable switches for my various automations.

Any variables withing the pyscript domain can apparently be displayed, but not modified in lovelace.
I tried to create input_booleans from pyscript, and they appear in the UI, but too, can’t be manipulated.

Anything I am missing here?

I am a trying to use the motion_lights app from the pyscript wiki here: Writing an App in Pyscript · custom-components/pyscript Wiki · GitHub

I have copied the converted code with comments from the wiki page and placed the motion_lights.py file in the apps folder:

/config/configuration.yaml
pyscript: !include pyscript/config.yaml

And placed the motion_lights.py in:
/config/pyscript/apps/motion_lights.py

and in the /config/pyscript/config.yaml I have this config:

pyscript:
  allow_all_imports: true
  apps:
    motion_lights:
      - motion_id: binary_sensor.bevegelsesensor_kjokken
        light_id: light.lys_kjokken
        time_id: input_number.light_timer_5_minutt

The pyscript debug logs config not present:

2023-04-26 13:20:36.536 DEBUG (MainThread) [custom_components.pyscript] reload: yaml, reloading scripts, and restarting

2023-04-26 13:20:36.606 DEBUG (MainThread) [custom_components.pyscript] No new packages to install

2023-04-26 13:20:36.607 DEBUG (SyncWorker_8) [custom_components.pyscript] load_scripts: skipping /config/pyscript/apps/motion_lights.py (app_name=motion_lights) because config not present

Anything I am missing here?

My pyscript functions work well but unfortunately they always run whenever I restart hass (so certain lights will go on or off when some people are sleeping). I would love to be able to stop this from happening. Anybody can give me some directions?

@state_trigger("switch.light_switch")
def switch_trigger():
    task.unique("switch_trigger", True)
    # DO SOMETHING
    pass

After reading the documentation here: Reference — hacs-pyscript 1.5.0 documentation I found out the pyscript yaml configuration must be placed in /config/configuration.yaml like this:

# File includes
group: !include groups.yaml
automation: !include automations.yaml
script: !include scripts.yaml
scene: !include scenes.yaml
pyscript: !include pyscript/config.yaml

logger:
  default: info
  logs:
    custom_components.pyscript: debug

Then I removed pyscript: in the pyscript configuration file /config/pyscript/config.yaml and adjusted the indention like this:

allow_all_imports: true
apps:
  motion_lights:
    - motion_id: binary_sensor.bevegelsesensor_kjokken
      light_id: light.lys_kjokken
      time_id: input_number.light_timer_5_minutt

`

Has anyone had luck getting autocomplete working for the Jupyter notebook in PyCharm?

Been banging my head against the wall all weekend without much luck. I have it working in the browser, but it makes development so much slower switching over to the browser. I’ll even take a guide on setting up VS Code, I’m very unfamiliar with it, but it atleast supports IntelliJ key bindings. Had no luck with VS Code my first try but it was a fresh install and I had no idea how to set it up.

I’m trying to create a MQTT watchdog in pyscript. It should be simple enough, just post a timestamp on something like watchdog/timestamp and then check it agains dt.timestamp(dt.now())…

Then I thought, maybe also use QOS and check if the message actually gets posted, but when I use mqtt.publish(topic=topic, payload=timestamp,qos=2) I don’t get an error or anything in the return of that function. I understand this is not really a pyscript issue, the strange thing is. If I try the same in the dev-console I do get an error saying it can’t connect to the mqtt broker (also with QOS=0).

So my question is, how do I catch an exception from mqtt.publish?

If the docs are right, that kind of trigger (just a state, without comparison) will not trigger on startup, but whenever the state changes (independent of the value). Can you check the state history? Maybe it gets initialized as ‘unavailable’ at startup and then the change to ‘on’ or ‘off’, once it becomes available, triggers your function.

Anyway, I ask myself why that would trigger unintended light switches, it sounds like a problem in the way you implemented the function itself. Maybe it makes more sense to define separate functions for on and off:

@state_trigger("switch.light_switch=='on'")
def switch_on():
    task.unique("switch_triggered")
    # DO SOMETHING
    pass

@state_trigger("switch.light_switch=='off'")
def switch_off():
    task.unique("switch_triggered")
    # DO SOMETHING
    pass

Like that, always the right state should be kept, even in case of restart (unless there’s something more complicated at work here, which you did not explain).

1 Like

Question. Is there a way using pyscript to manually change an attribute of a sensor. I’m building a “to-do” list and I have all the tasks as attributes of a main sensor and would like to change the status attribute to “completed” when done since when is created is “open”. Thank you.

Hello everyone. I installed Pyscript using Home Assistant Community Store, and when I go to Developer Tools → Services → and type in pyscript, the only services that show up are Reload Pyscript and Start Jupiter Kernel. I’ve created more scripts in my custom_components/pyscripts directory, however they don’t show up in my services. I’ve restarted home assistant, made sure everything is correct in my configuration.yaml file, checked the debug statements, and cannot find what is wrong. Any advice would be great!

From the docs:

Add files with a suffix of .py in the folder <config>/pyscript

I followed the steps to create the example.py file, and tried creating a file of my own. I then called the reload scripts service and restarted home assistant. The new services, such as the services in example.py and the other file still won’t show up. Pretty confused about what is happening.

<config> means the HA config folder, so you should have/create a pyscript folder where your HA configuration.yaml lives, not in custom_component/pyscript.

I’m experiencing the same issue as @davidbd7.

I created two files:

config/pyscript/shopping_list_sync.py 
config/pyscript_modules/write_file.py

I reload pyscript and only see the reload and jupyter service; error log reports:

Exception in </config/pyscript/shopping_list_sync.py> line 8: import write_file ^ ModuleNotFoundError: No module named 'write_file'

I also added write_file.py to the config/pyscript folder and that isn’t recognized either.