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'].

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.