Pyscript - new integration for easy and powerful Python scripting

Nope! I suspect pyscript takes care of that itself. You should be good just calling it normally.

Understood. Something is not right then. See error above.

I am most certain that the timer is running and expiring otherwise this code would not be executed. The issue is that it is giving that error instead of firing the event. Seems like what you provided is close to working as intended but does not.

from datetime import datetime

@service
def schedule_event_at_time(event_name: str, event_data: dict = {}, target_time: str = ""):
    # Parse the target time from the input string
    target_time = datetime.strptime(target_time, "%Y-%m-%d %H:%M:%S")
    
    # Get the current time
    now = datetime.now()
    
    # If the target time is in the past, log an error and return
    if target_time < now:
        log.error(f"Target time {target_time} is in the past. Event not scheduled.")
        return
    
    # Calculate the sleep duration
    sleep_duration = (target_time - now).total_seconds()
    
    # Wait until the target time
    task.sleep(sleep_duration)
    
    # Fire the event
    event.fire(event_name, **event_data)
    log.warning(f"Event '{event_name}' fired at {target_time}")

I spent a bunch of time troubleshooting and writing and then decided to see if GPT could help. Got me here with a few hand edits based on what I learned from the links @Slalamander supplied.

This works great butā€¦for some unknown reason the service call gets made but does not return until the timer completes. This is problematic as I am trying this to voice so:

Me: ā€œSet a timer for 30 secondsā€
Thirty seconds pass
Assist: ā€œTimer set for 30 secondsā€

Shouldnā€™t this be running the service in the background?

EDIT Got this going with a bit of help in HA Discord:

from datetime import datetime

def timerwait(duration, event_name, event_data, target_time):
    task.sleep (duration)

    # Fire the event
    event.fire(event_name, **event_data)
    log.warning(f"Event '{event_name}' fired at {target_time}")    
    
@service
def schedule_event_at_time(event_name: str, event_data: dict = {}, target_time: str = ""):

    # Parse the target time from the input string
    target_time = datetime.strptime(target_time, "%Y-%m-%d %H:%M:%S")
    
    # Get the current time
    now = datetime.now()
    
    # Calculate the sleep duration
    sleep_duration = (target_time - now).total_seconds()
    
    # Wait until the target time
    task.create(timerwait, sleep_duration, event_name, event_data, target_time)
1 Like

Ah, thanks for sharing! I wasnā€™t aware pyscript had its own asyncio wrapper.

Does that mean the timers work now? :smiley:

Yes! Finally have it working and the beginnings of a very big missing piece for voice. I know that there is a timer implementation for voice but it is limited to only ESPHome satellites whereas this is much more universal.

Thank you for your continued help and patience.

1 Like

No problem! It helps me learn too, and youā€™ve always been clear in your questions, as well as polite and very appreciative in your answers. On multiple occasions Iā€™ve found myself wanting to give a short answer, only to fall into a rabbit hole because I want to give one that is actually complete :joy:

1 Like

hello, I need some advice. for a python script that reads out my energymeter information folliwing packages / modules are required:

import requests
import time 
import json
import datetime
import logging      #from loggerdate import loggerdate
from pprint import pprint
import paho.mqtt.client as mqtt
import sys

is there a change to get it running with the pyscript addon and a requirements.txt?

I think so, most libraries should already be available from the Home Assistant installation. I think paho and pprint should be in requirements however.

I think the major problem could lie in using the paho library, as from looking at that you will need to implement the external event loop example in it.

Iā€™m not too well acquainted with mqtt, but I think it would function better to configure the client in Home Assistantā€™s MQTT integration, and forward the gotten data to a pyscript defined service.

thanks for your replay ā€¦ I rather think of writing a custom component for this. not that I still know how but seems to be for longterm a better solution.

Anyone seeing errors loading Pyscript using HA 2024.10? Iā€™m getting this:

Logger: homeassistant.config_entries
Source: config_entries.py:594
First occurred: 6:58:54 PM (1 occurrences)
Last logged: 6:58:54 PM

Error setting up entry pyscript for pyscript
Traceback (most recent call last):
  File "/usr/src/homeassistant/homeassistant/config_entries.py", line 594, in async_setup
    result = await component.async_setup_entry(hass, self)
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/config/custom_components/pyscript/__init__.py", line 280, in async_setup_entry
    await install_requirements(hass, config_entry, pyscript_folder)
  File "/config/custom_components/pyscript/requirements.py", line 297, in install_requirements
    await async_process_requirements(
  File "/usr/src/homeassistant/homeassistant/requirements.py", line 65, in async_process_requirements
    await _async_get_manager(hass).async_process_requirements(name, requirements)
  File "/usr/src/homeassistant/homeassistant/requirements.py", line 264, in async_process_requirements
    self._raise_for_failed_requirements(name, missing)
  File "/usr/src/homeassistant/homeassistant/requirements.py", line 292, in _raise_for_failed_requirements
    raise RequirementsNotFound(integration, [req])
homeassistant.requirements.RequirementsNotFound: Requirements for pyscript not found: ['PyDictionary'].
1 Like

Hello, new to pyscript. Anyone know how to pass tuple value?

def change_light_color(entity_id):

    light.turn_on(
        entity_id = entity_id,
        brightness = 255,
        color_temp = 196,
        hs_color = [27.12, 17.875] #error on this line
    )

The code above will throw MultipleInvalid: two or more values in the same group of exclusion 'Color descriptors' @ data[<Color descriptors>]

Any idea why?

color_temp is a way of specifying color. so is hs_color. i think you need to pick one.

I have had one successful pyscript but my second is an issue. This is the first time I have attempted to update a helper within a script and it has resulted in

state is not defined

My code is:

import colorsys
import sys
import os
import time

@service
def change_hsv_to_rgb(h,s,v, entity):

  contents, exception = task.executor(convert_hsv, h, s, v, entity)
  if exception:
      raise exception
  log.info(f"contents = {contents}")
  
@pyscript_compile
def convert_hsv(h, s, v, entity):

  hdecimal = round(h/100, 2)
  sdecimal = round(s/100, 2)
  vdecimal = round(v/100, 2)

  rgb_value = colorsys.hsv_to_rgb(hdecimal, sdecimal, vdecimal)
  state.set(entity, value=rgb_value)

The call I used for testing is:

convert_hsv(3,100,100,'input_text.front_bedroom_right_lamp_converted_rgb')

The full error is:

Exception in <jupyter_3> line 1:
    convert_hsv(3,100,100,'input_text.front_bedroom_right_lamp_converted_rgb')
                          ^
NameError: name 'state' is not defined

I am testing via JupyterLabs but have also received the same error when attempting to run in Developer Tools. I thought ā€œstateā€ was built in Pyscript functionality?

UPDATE: MY mistake. Used the 1st script i wrote as a template. That needed compiled python for file manipulation. I put the state.set in this compiled function. Of course, it is not treated as pyscript. So have removed the compile section and merged into the service as i do not need compiled functionality. All works now

I think I am having the same problem. But I am new to HA and trying to write python for it for the first time, so I donā€™t know if my setup would have worked before the october update.

Is pydictionary something you wrote, or something you installed by pip, orā€¦?
In my case I have created a pyscript_modules directory as described in the importing section of the docs, and included it in the requirements.txt (itā€™s the only entry at this time) and I get the same error you mention:

homeassistant.requirements.RequirementsNotFound: Requirements for pyscript not found: ['HAlocalIOutils'].

Did you ever find a solution?

I canā€™t remember the details but I think I just had it in the file that is used for includes. I did not write pydictionary. My solution was to remove it from the includes file as I was not still using the script I wrote that called it.

This isnā€™t much help to you Iā€™m afraid. Good luck.

1 Like