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"
37 Retrieves the power state of a WLED device.
38 Sends a GET request to the WLED device's JSON API endpoint to fetch the current state
40 bool: True if the WLED device is on, False otherwise. Returns None if the device is unreachable.
44 response = requests.get(f
"http://{WLED_HOST}/json/state", timeout=3)
45 response.raise_for_status()
46 data = response.json()
47 return data.get(
"on",
False)
48 except (requests.exceptions.RequestException, TimeoutError)
as e:
49 logger.error(f
"WLED nicht erreichbar: {e}")
54 Sends a request to turn off the lights by setting the segment color to black.
55 This function creates a JSON payload to set the color of a segment of lights to black (hex code "000000")
56 and sends a POST request to the specified API endpoint to turn off the lights.
58 requests.exceptions.RequestException: If there is an issue with the HTTP request.
60 req = json.dumps({
"seg": {
"i": [0, 50,
"000000"]}})
61 requests.post(API, req, timeout=10)
66 Sends a request to set the color of a specific position on a WLED device.
68 pos (int): The position to set the color for.
72 req = json.dumps({
"seg": {
"i": [pos,
"FF0000"]}})
73 requests.post(API, req, timeout=10)
78 Sends a POST request to the WLED API to load the default state.
79 This function creates a JSON payload with a preset state identifier and sends it to the WLED API endpoint using a POST request.
81 requests.exceptions.RequestException: If there is an issue with the HTTP request.
83 req = json.dumps({
"ps": 1})
84 requests.post(API, req, timeout=10)
89 Change the power state of the device.
91 state (bool): The desired power state. True to turn on, False to turn off.
95 req = json.dumps({
"on": state})
96 requests.post(API, req, timeout=10)
None load_default_state()
None change_power_state(state)