2This module provides functions to interact with a WLED device via its JSON API.
3It allows for turning off lights, setting colors at specific positions, loading default states,
4changing power states, and retrieving the current power state of the WLED device.
7 turn_off_lights(): Sends a request to turn off the lights by setting the segment color to black.
8 color_pos(pos): Sends a request to set the color of a specific position on a WLED device.
9 load_default_state(): Sends a POST request to the WLED API to load the default state.
10 change_power_state(state): Change the power state of the device.
11 get_power_state(): Retrieves the power state of a WLED device.
13from typing
import Annotated
18from dotenv
import load_dotenv
20from logger_config
import logger
23ENV_PATH: Annotated[str,
"path to environment variables"] = os.path.join(
24 os.path.dirname(__file__),
"data/.env"
26load_dotenv(dotenv_path=ENV_PATH)
28WLED_HOST: Annotated[str,
"environment variable for WLED address"] = os.getenv(
31logger.info(f
"WLED host is: {WLED_HOST}")
33API: Annotated[str,
"URL to WLED"] = f
"http://{WLED_HOST}/json"
38 Sends a request to turn off the lights by setting the segment color to black.
39 This function creates a JSON payload to set the color of a segment of lights to black (hex code "000000")
40 and sends a POST request to the specified API endpoint to turn off the lights.
42 requests.exceptions.RequestException: If there is an issue with the HTTP request.
44 req = json.dumps({
"seg": {
"i": [0, 50,
"000000"]}})
45 requests.post(API, req, timeout=10)
50 Sends a request to set the color of a specific position on a WLED device.
52 pos (int): The position to set the color for.
56 req = json.dumps({
"seg": {
"i": [pos,
"FF0000"]}})
57 requests.post(API, req, timeout=10)
62 Sends a POST request to the WLED API to load the default state.
63 This function creates a JSON payload with a preset state identifier and sends it to the WLED API endpoint using a POST request.
65 requests.exceptions.RequestException: If there is an issue with the HTTP request.
67 req = json.dumps({
"ps": 1})
68 requests.post(API, req, timeout=10)
73 Change the power state of the device.
75 state (bool): The desired power state. True to turn on, False to turn off.
79 req = json.dumps({
"on": state})
80 requests.post(API, req, timeout=10)
83def get_power_state() -> Annotated[bool, "True if power is on, false if power is off"]:
85 Retrieves the power state of a WLED device.
86 Sends a GET request to the WLED device's JSON API endpoint to fetch the current state.
87 Parses the JSON response to determine if the device is on or off.
89 bool: True if the WLED device is on, False otherwise.
91 state = requests.get(f
"http://{WLED_HOST}/json/state", timeout=10)
92 return json.loads(state.text)[
"on"]
None load_default_state()
Annotated[bool, "True if power is on, false if power is off"] get_power_state()
None change_power_state(state)