### Run Jupyter Notebook Source: https://nbviewer.org/github/craigbarratt/hass-pyscript-jupyter/blob/master/pyscript_tutorial This command initiates a Jupyter notebook session. Ensure you have the pyscript Jupyter kernel installed to run the tutorial interactively. ```shell jupyter notebook pyscript_tutorial.ipynb ``` -------------------------------- ### Type Casting for HASS State Variable Comparisons Source: https://nbviewer.org/github/craigbarratt/hass-pyscript-jupyter/blob/master/pyscript_tutorial Illustrates the need for type casting when performing comparisons on HASS state variables, as they are stored as strings. This example shows casting to an integer for a greater-than comparison. ```python if int(pyscript.example_var) > 10: log.debug(f"pyscript.example_var = {pyscript.example_var}, which is greater than 10") # Output: pyscript.example_var = 20, which is greater than 10 ``` -------------------------------- ### Verify Global Variable Scope in PyScript Source: https://nbviewer.org/github/craigbarratt/hass-pyscript-jupyter/blob/master/pyscript_tutorial This example shows how a global variable defined in one PyScript context ('file.scripts') is not accessible when the global context is switched back to another ('jupyter_0'). It confirms that variables are scoped to their respective contexts, preventing NameError exceptions. ```python pyscript.set_global_ctx("jupyter_0") x_in_file_scripts ``` -------------------------------- ### Run PyScript Services with Task Unique and Delayed Second Call Source: https://nbviewer.org/github/craigbarratt/hass-pyscript-jupyter/blob/master/pyscript_tutorial Executes two instances of the `long_running` service, with a short delay between the calls. The first call `task0` starts, but when the second call `task1` begins and encounters `task.unique`, it causes `task0` to be killed, illustrating the task-killing behavior of `task.unique` when not using `kill_me=True`. ```python pyscript.long_running(name="task0", loop_cnt=3) task.sleep(0.5) pyscript.long_running(name="task1", loop_cnt=4) ``` -------------------------------- ### Define a Conditional Event Trigger in Python Source: https://nbviewer.org/github/craigbarratt/hass-pyscript-jupyter/blob/master/pyscript_tutorial This example demonstrates defining an event trigger with a condition. The function `got_my_event` will only be called if the `my_param1` event parameter is between 50 and 150. It explicitly defines expected parameters `my_param1` and `fruit`, logging their values when the function executes. This allows for more specific event handling. ```python from homeassistant.core import event from homeassistant.helpers.script import script_events @event_trigger("my_event", "50 <= my_param1 <= 150") def got_my_event(my_param1=None, fruit=None): log.info(f"got my_event: my_param1={my_param1}, fruit={fruit}") # Firing events to test the condition: event.fire("my_event", my_param1=40, fruit="apple") event.fire("my_event", my_param1=110, fruit="orange") event.fire("my_event", my_param1=180, fruit="banana") ``` -------------------------------- ### Monitor State Changes with Event Trigger in Python Source: https://nbviewer.org/github/craigbarratt/hass-pyscript-jupyter/blob/master/pyscript_tutorial This snippet shows how to monitor state changes for a specific component ('sun') using the `EVENT_STATE_CHANGED` event. The trigger is conditional on the `entity_id` starting with 'sun.'. The function logs the old and new state values and attributes. Note: It's recommended to use `@state_trigger` for state changes instead of this general approach. ```python from homeassistant.const import EVENT_STATE_CHANGED @event_trigger(EVENT_STATE_CHANGED, "entity_id.startswith('sun.')") def monitor_state_change(entity_id=None, new_state=None, old_state=None): old_value = old_state.state if old_state else None log.info(f"entity {entity_id} changed from {old_value} to {new_state.state} and attributes are now {new_state.attributes}") # To trigger manually for testing (not recommended for production): sun.my_new_var = 13 # To delete the trigger: del monitor_state_change ``` -------------------------------- ### Get Current Global Context in PyScript Source: https://nbviewer.org/github/craigbarratt/hass-pyscript-jupyter/blob/master/pyscript_tutorial This function retrieves the identifier of the currently active global context. Knowing the current context is essential for managing variable scopes and ensuring code runs in the intended environment. ```python pyscript.get_global_ctx() ``` -------------------------------- ### Manually Trigger Task Unique to Kill Running Task Source: https://nbviewer.org/github/craigbarratt/hass-pyscript-jupyter/blob/master/pyscript_tutorial Demonstrates manually calling `task.unique` with the argument "long_running_service". This action is intended to terminate any currently running task that was started with `task.unique("long_running_service")`. This is useful for stopping a long-running process externally. ```python task.unique("long_running_service") ``` -------------------------------- ### Accessing HASS State Variables and Attributes Source: https://nbviewer.org/github/craigbarratt/hass-pyscript-jupyter/blob/master/pyscript_tutorial Demonstrates how to read the current state of a Home Assistant entity (e.g., sun.sun) and access its attributes (e.g., elevation). ```python sun.sun # Output: 'above_horizon' sun.sun.elevation # Output: 34.47 ``` -------------------------------- ### Basic Arithmetic in PyScript/Jupyter Source: https://nbviewer.org/github/craigbarratt/hass-pyscript-jupyter/blob/master/pyscript_tutorial Demonstrates basic arithmetic operations within the PyScript/Jupyter environment. This serves as a simple check to confirm the kernel connection. The output of the operation is displayed. ```python 1 + 2 ``` -------------------------------- ### List Global Contexts in PyScript Source: https://nbviewer.org/github/craigbarratt/hass-pyscript-jupyter/blob/master/pyscript_tutorial This function lists all available global contexts in the PyScript environment. Contexts typically include one for each script file and one for the Jupyter session. This is useful for understanding the scope of your Python code. ```python pyscript.list_global_ctx() ``` -------------------------------- ### Register HASS Service with **kwargs for Dynamic Parameters Source: https://nbviewer.org/github/craigbarratt/hass-pyscript-jupyter/blob/master/pyscript_tutorial A service function can accept all keyword arguments using `**kwargs`. This captures all service call parameters into a dictionary. Note that HASS UI will not prompt for parameters if `**kwargs` is used. ```python @service def test_service2(**kwargs): log.debug(f"test_service2 called with parameters {kwargs}") pyscript.test_service2(param1=45, other_param=[6,8,12]) ``` ```python del test_service2 ``` -------------------------------- ### Setting HASS State Variables by Direct Assignment Source: https://nbviewer.org/github/craigbarratt/hass-pyscript-jupyter/blob/master/pyscript_tutorial Shows how to set a HASS state variable by directly assigning a value to it. Note that values are automatically cast to strings. ```python pyscript.example_var = 20 pyscript.example_var # Output: '20' ``` -------------------------------- ### Formatted String Debug Message in PyScript/Jupyter Source: https://nbviewer.org/github/craigbarratt/hass-pyscript-jupyter/blob/master/pyscript_tutorial Illustrates how to include variables within a debug message using f-strings in PyScript within a Jupyter notebook. This allows for dynamic and informative logging. The formatted message is displayed interactively. ```python x = 10 y = "a string" list1 = [1, 2, 3] log.debug(f"this is a formatted string with variables x = {x}, y = {y}, list1 = {list1}") ``` -------------------------------- ### Defining and Calling a Python Function with HASS State Source: https://nbviewer.org/github/craigbarratt/hass-pyscript-jupyter/blob/master/pyscript_tutorial Defines a Python function `func1` that takes two arguments and uses the Home Assistant sun's elevation to conditionally perform calculations and log messages. Attribute values are directly used as floats. ```python def func1(x, y): if sun.sun.elevation > 30: log.info(f"The sun's elevation is {sun.sun.elevation}, which is > 30 degrees") return x + 2 * y else: log.info(f"The sun's elevation is {sun.sun.elevation}, which is <= 30 degrees") return x - y func1(1, 2) # Output: 5 # Output: The sun's elevation is 34.47, which is > 30 degrees ``` -------------------------------- ### Call Function on Startup with @time_trigger Source: https://nbviewer.org/github/craigbarratt/hass-pyscript-jupyter/blob/master/pyscript_tutorial A bare `@time_trigger` decorator without arguments causes the decorated function to be called on startup or when the script is loaded. In a Jupyter environment, this occurs when the cell defining the function is executed. ```python @time_trigger def on_startup(): log.debug("on_startup: running") task.sleep(2) log.debug("on_startup: finished") ``` -------------------------------- ### Define a Basic Event Trigger in Python Source: https://nbviewer.org/github/craigbarratt/hass-pyscript-jupyter/blob/master/pyscript_tutorial This snippet shows how to define a function that triggers when a specific event ('my_event') occurs. It uses the `@event_trigger` decorator. The function accepts all event parameters using `**kwargs` and logs them. This is useful for general event monitoring. ```python from homeassistant.core import event from homeassistant.helpers.script import script_events @event_trigger("my_event") def got_my_event(**kwargs): log.info(f"got my_event: kwargs={kwargs}") # To test, fire the event: event.fire("my_event", my_param1=100, fruit="apple") ``` -------------------------------- ### Display Debug Message in PyScript/Jupyter Source: https://nbviewer.org/github/craigbarratt/hass-pyscript-jupyter/blob/master/pyscript_tutorial Shows how to display debug messages using the `log.debug` function in PyScript within a Jupyter notebook. The `print` function is not supported. The message is displayed interactively and also logged in the HASS log file. ```python log.debug("this text will be displayed") ``` -------------------------------- ### Define and Access Global Variable in PyScript Context Source: https://nbviewer.org/github/craigbarratt/hass-pyscript-jupyter/blob/master/pyscript_tutorial This code snippet demonstrates defining a global variable ('x_in_file_scripts') within a specific PyScript context ('file.scripts') and then accessing its value. It highlights how variables are associated with their context. ```python x_in_file_scripts = 123 x_in_file_scripts ``` -------------------------------- ### Run Multiple Independent PyScript Long-Running Tasks Source: https://nbviewer.org/github/craigbarratt/hass-pyscript-jupyter/blob/master/pyscript_tutorial Initiates two independent instances of the `long_running` PyScript service, `task0` and `task1`, with different loop counts. This showcases how PyScript handles concurrent asynchronous tasks, allowing them to run and complete independently, with their execution times varying based on their respective loop counts and sleep intervals. ```python pyscript.long_running(name="task0", loop_cnt=3) pyscript.long_running(name="task1", loop_cnt=4) ``` -------------------------------- ### Wait for State Trigger with Timeout - Python Source: https://nbviewer.org/github/craigbarratt/hass-pyscript-jupyter/blob/master/pyscript_tutorial Waits for a specific state trigger to occur within a given timeout. If the trigger is met, it returns details about the trigger; otherwise, it returns a timeout indication. This is useful for ensuring conditions are met within a certain timeframe. ```python @state_trigger("input_boolean.test_sensor1 == 'on'") def sensor1_active(): task.unique('sensor1_active') log.debug("waiting for sensor2") result = task.wait_until(state_trigger="input_boolean.test_sensor2 == 'on'", timeout=10) log.debug(f"result = {result}") ``` ```python # reset both sensors input_boolean.test_sensor1 = "off" input_boolean.test_sensor2 = "off" # this will trigger the function input_boolean.test_sensor1 = "on" # wait a few seconds, then turn sensor2 on: task.sleep(3) input_boolean.test_sensor2 = "on" ``` ```python waiting for sensor2 result = {'trigger_type': 'state', 'var_name': 'input_boolean.test_sensor2', 'value': 'on', 'old_value': 'off'} ``` ```python # reset both sensors input_boolean.test_sensor1 = "off" input_boolean.test_sensor2 = "off" # this will trigger the function input_boolean.test_sensor1 = "on" # wait a few seconds, then turn sensor2 on: task.sleep(12) input_boolean.test_sensor2 = "on" ``` ```python waiting for sensor2 result = {'trigger_type': 'timeout'} ``` -------------------------------- ### Define PyScript Service with Task Unique (Kill Me Mode) Source: https://nbviewer.org/github/craigbarratt/hass-pyscript-jupyter/blob/master/pyscript_tutorial Defines the `long_running` PyScript service with `task.unique("long_running_service", kill_me=True)`. This configuration ensures that when multiple instances of the service are called, the *new* task is terminated, allowing the *existing* task to continue running. This reverses the default behavior of `task.unique`. ```python @service def long_running(name="task", loop_cnt=10): task.unique("long_running_service", kill_me=True) log.debug(f"{name}: starting") for i in range(loop_cnt): task.sleep(3) log.debug(f"{name}: completed loop #{i}") log.debug(f"{name}: finished") ``` -------------------------------- ### Wait for Multiple Triggers or Timeout - Python Source: https://nbviewer.org/github/craigbarratt/hass-pyscript-jupyter/blob/master/pyscript_tutorial Waits for either a secondary state trigger or for the primary sensor to turn off, within a specified timeout. It then logs different messages based on whether a timeout occurred, the secondary sensor activated, or the primary sensor deactivated. ```python @state_trigger("input_boolean.test_sensor1 == 'on'") def sensor1_active(): task.unique('sensor1_active') log.debug("waiting for sensor2") result = task.wait_until( state_trigger="input_boolean.test_sensor2 == 'on' or input_boolean.test_sensor1 == 'off'", timeout=10 ) if result["trigger_type"] == "timeout": log.debug(f"sensor2 didn't turn on within 10 seconds") elif result["trigger_type"] == "state": if result["var_name"] == "input_boolean.test_sensor2": log.debug(f"sensor2 turned on within 10 seconds of sensor1 turning on") else: log.debug(f"sensor1 turned off before sensor2 turned on") ``` ```python # reset both sensors input_boolean.test_sensor1 = "off" input_boolean.test_sensor2 = "off" # this will trigger the function input_boolean.test_sensor1 = "on" # wait a few seconds, then turn sensor2 on: task.sleep(3) input_boolean.test_sensor2 = "on" ``` ```python waiting for sensor2 sensor2 turned on within 10 seconds of sensor1 turning on ``` ```python # reset both sensors input_boolean.test_sensor1 = "off" input_boolean.test_sensor2 = "off" # this will trigger the function input_boolean.test_sensor1 = "on" # wait a few seconds, then turn sensor1 off immediately before sensor2: task.sleep(3) input_boolean.test_sensor1 = "off" input_boolean.test_sensor2 = "on" ``` ```python waiting for sensor2 sensor1 turned off before sensor2 turned on ``` ```python # reset both sensors input_boolean.test_sensor1 = "off" input_boolean.test_sensor2 = "off" # this will trigger the function input_boolean.test_sensor1 = "on" # wait for a longer time, then turn sensor2 on: task.sleep(12) input_boolean.test_sensor2 = "on" ``` ```python waiting for sensor2 sensor2 didn't turn on within 10 seconds ``` -------------------------------- ### Call PyScript Service with Custom Loop Count Source: https://nbviewer.org/github/craigbarratt/hass-pyscript-jupyter/blob/master/pyscript_tutorial Demonstrates calling the `long_running` PyScript service with a specific `loop_cnt` of 3. This action triggers the execution of the `long_running` function as an asynchronous task, running its defined loops and sleep intervals. ```python pyscript.long_running(loop_cnt=3) ``` -------------------------------- ### Setting HASS State Variables and Attributes with `state.set` Source: https://nbviewer.org/github/craigbarratt/hass-pyscript-jupyter/blob/master/pyscript_tutorial Utilizes the `state.set` function to set a HASS state variable and its attributes. This method preserves Python data types for attributes. ```python state.set("pyscript.example_var", 30, attr1=30, attr2=23.7, attr3="abc") pyscript.example_var.attr2 # Output: 23.7 ``` -------------------------------- ### Test Combined Triggers: Correct State Value Source: https://nbviewer.org/github/craigbarratt/hass-pyscript-jupyter/blob/master/pyscript_tutorial This code sets the state variables to the correct values to activate the combined trigger. When `pyscript.state_trig_active` is set to '10' and `pyscript.state_trig_run` changes to '1', the `state_trig_func` should execute, provided the time condition is met. ```python pyscript.state_trig_active = 10 pyscript.state_trig_run = 2 pyscript.state_trig_run = 1 ``` -------------------------------- ### Define State Trigger with Additional State and Time Conditions Source: https://nbviewer.org/github/craigbarratt/hass-pyscript-jupyter/blob/master/pyscript_tutorial This snippet shows how to combine the `@state_trigger` with `@state_active` and `@time_active` decorators. The function will only execute if `pyscript.state_trig_run` is '1', `pyscript.state_trig_active` is '10', and the current time is between 3:00 and 23:00. ```python @state_trigger("pyscript.state_trig_run == '1'") @state_active("pyscript.state_trig_active == '10'") @time_active("range(3:00, 23:00)") def state_trig_func(**kwargs): log.info(f"state_trig_func called with kwargs={kwargs}") ``` -------------------------------- ### Set Global Context in PyScript Source: https://nbviewer.org/github/craigbarratt/hass-pyscript-jupyter/blob/master/pyscript_tutorial This function allows you to switch the active global context to a specified context identifier. This is crucial for managing different sets of global variables and ensuring code executes within its intended scope. ```python pyscript.set_global_ctx("file.scripts") ``` -------------------------------- ### Time Trigger with State Condition using @time_trigger and @state_active Source: https://nbviewer.org/github/craigbarratt/hass-pyscript-jupyter/blob/master/pyscript_tutorial This configuration triggers a function every 5 seconds, but only executes the function body if the `pyscript.ok1` state variable is equal to '1'. The function stops executing when the state variable is set to '0' or the function is deleted. ```python @time_trigger("period(0:00, 5 sec)") @state_active("pyscript.ok1 == '1'") def every_5_seconds(): log.debug("every_5_seconds: running now") ``` ```python pyscript.ok1 = 1 ``` ```python pyscript.ok1 = 0 ``` ```python del every_5_seconds ``` -------------------------------- ### Define Simple State Trigger with @state_trigger Source: https://nbviewer.org/github/craigbarratt/hass-pyscript-jupyter/blob/master/pyscript_tutorial This snippet defines a Python function that is triggered when a specific state variable changes. The function `state_trig_func` will be executed asynchronously whenever the state variable `pyscript.state_trig_run` is set to '1' (either as an integer or a string). The function receives keyword arguments detailing the trigger event. ```python from homeassistant.core import state_trigger from homeassistant.helpers.event import state_active, time_active import logging log = logging.getLogger(__name__) @state_trigger("pyscript.state_trig_run == '1'") def state_trig_func(**kwargs): log.info(f"state_trig_func called with kwargs={kwargs}") ``` -------------------------------- ### Define PyScript Service with Task Unique for Task Management Source: https://nbviewer.org/github/craigbarratt/hass-pyscript-jupyter/blob/master/pyscript_tutorial Modifies the `long_running` PyScript service to include `task.unique("long_running_service")`. This ensures that only one instance of a task identified by "long_running_service" can run at a time. Any subsequent calls to this service while an instance is active will be managed according to the `task.unique` behavior (in this case, the new task is effectively prevented from running concurrently by the existing one). ```python @service def long_running(name="task", loop_cnt=10): task.unique("long_running_service") log.debug(f"{name}: starting") for i in range(loop_cnt): task.sleep(3) log.debug(f"{name}: completed loop #{i}") log.debug(f"{name}: finished") ``` -------------------------------- ### Register HASS Service with @service Decorator Source: https://nbviewer.org/github/craigbarratt/hass-pyscript-jupyter/blob/master/pyscript_tutorial The `@service` decorator registers a Python function as a HASS service. The service name follows the format `pyscript.`. Parameters passed to the service call are received as function arguments. The service can be called directly or using `service.call`. Undefining the function removes the service. ```python @service def test_service(param1=None, other_param=None): log.debug(f"test_service called with param1={param1}, other_param={other_param}") ``` ```python pyscript.test_service(param1=45, other_param=[6,8,12]) ``` ```python service.call("pyscript", "test_service", param1=45, other_param=[6,8,12]) ``` ```python del test_service ``` ```python service.has_service("pyscript", "test_service") ``` -------------------------------- ### Test State Trigger: Setting Variable to Non-Triggering Value Source: https://nbviewer.org/github/craigbarratt/hass-pyscript-jupyter/blob/master/pyscript_tutorial This code snippet demonstrates setting a state variable to a value that will not trigger the associated function. It's used to show that the trigger only activates when the specified condition is met. ```python pyscript.state_trig_run = 2 ``` -------------------------------- ### Define Long-Running PyScript Service with Task Sleep Source: https://nbviewer.org/github/craigbarratt/hass-pyscript-jupyter/blob/master/pyscript_tutorial Defines a PyScript service function named `long_running` that executes a specified number of loops. Each loop includes a 3-second sleep using `task.sleep` and logs its progress. This function is designed to run as a separate asynchronous task, allowing for long-running operations without blocking the main thread. ```python @service def long_running(name="task", loop_cnt=10): log.debug(f"{name}: starting") for i in range(loop_cnt): task.sleep(3) log.debug(f"{name}: completed loop #{i}") log.debug(f"{name}: finished") ``` -------------------------------- ### Test State Trigger: Setting Variable to Triggering Value Source: https://nbviewer.org/github/craigbarratt/hass-pyscript-jupyter/blob/master/pyscript_tutorial This code snippet sets the state variable to the value that causes the state trigger to activate. When `pyscript.state_trig_run` is set to 1, the previously defined `state_trig_func` will be called. ```python pyscript.state_trig_run = 1 ``` -------------------------------- ### Test Combined Triggers: Incorrect State Value Source: https://nbviewer.org/github/craigbarratt/hass-pyscript-jupyter/blob/master/pyscript_tutorial This code demonstrates setting state variables to values that should prevent the combined trigger from activating. It checks that the function is not called when `pyscript.state_trig_active` is not '10'. ```python pyscript.state_trig_active = 5 pyscript.state_trig_run = 2 pyscript.state_trig_run = 1 ``` -------------------------------- ### Delete State Trigger Function Source: https://nbviewer.org/github/craigbarratt/hass-pyscript-jupyter/blob/master/pyscript_tutorial This snippet shows how to remove a previously defined state trigger function. Using `del` on the function name effectively unregisters it, preventing it from being called by future triggers. ```python del state_trig_func ``` -------------------------------- ### Delete PyScript Function Definition Source: https://nbviewer.org/github/craigbarratt/hass-pyscript-jupyter/blob/master/pyscript_tutorial Removes the `long_running` function definition from the current scope. This is typically done to clean up the environment after demonstrating or testing the function's behavior. ```python del long_running ``` -------------------------------- ### Delete Function Definition - Python Source: https://nbviewer.org/github/craigbarratt/hass-pyscript-jupyter/blob/master/pyscript_tutorial Removes a previously defined function from the current scope. This is typically used for cleanup or to redefine a function with new logic. ```python del sensor1_active ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.