ble2wled.config - Configuration Management
Configuration management using environment variables and .env files.
This module provides centralized configuration management for BLE2WLED using environment variables and .env files. Configuration is loaded from .env on initialization and provides property-based access with type conversion, validation, and sensible defaults.
- Configuration Hierarchy:
.env file (if it exists)
Environment variables
Default values
Example
Load and use configuration:
from ble2wled.config import Config
config = Config('.env')
config.validate() # Check all values are valid
# Access configuration properties
print(f"WLED host: {config.wled_host}")
print(f"LED count: {config.led_count}")
print(f"MQTT broker: {config.mqtt_broker}")
# Log all configuration
import json
print(json.dumps(config.to_dict(), indent=2))
- class ble2wled.config.Config(env_file: str | None = None)[source]
Bases:
objectCentralized configuration management for BLE2WLED.
Loads configuration from .env file and environment variables. Provides property-based access to configuration with automatic type conversion, validation, and sensible defaults.
All configuration values are read through environment variables, which can be set via .env file or directly in the process environment.
- __init__(env_file: str | None = None)[source]
Initialize configuration.
Loads environment variables from .env file if it exists. Configuration properties can then be accessed via the property methods.
- Parameters:
env_file (str) – Path to .env file. If None, defaults to “.env” in the current directory.
Example
Load configuration from default .env file:
config = Config() # Loads from .env
Or from a specific file:
config = Config('/path/to/.env.production')
- property wled_host: str
WLED device hostname or IP address.
Default: ‘wled.local’
- Returns:
Hostname or IP address of WLED device.
- Return type:
Example
Access WLED host:
print(config.wled_host) # 'wled.local'
- property led_count: int
Number of LEDs in the strip.
Default: 60
- Returns:
LED count (must be positive).
- Return type:
- Raises:
ValueError – If LED_COUNT is not positive.
Example
Access LED count:
leds = [[0, 0, 0] for _ in range(config.led_count)]
- property output_mode: str
‘udp’ or ‘http’.
‘udp’: Fast real-time protocol (DRGB)
‘http’: Slower but more reliable JSON API
Default: ‘udp’
- Returns:
Output mode (‘udp’ or ‘http’).
- Return type:
- Raises:
ValueError – If OUTPUT_MODE is not ‘udp’ or ‘http’.
Example
Check output mode:
if config.output_mode == 'udp': print('Using fast UDP updates')
- Type:
LED output mode
- property http_timeout: float
HTTP request timeout in seconds.
Default: 1.0
- Returns:
Timeout in seconds.
- Return type:
Example
Set HTTP request timeout:
requests.post(url, json=data, timeout=config.http_timeout)
- property udp_port: int
UDP DRGB protocol port.
Default: 21324
- Returns:
UDP port number.
- Return type:
Example
Use configured UDP port:
controller = WLEDUDPController( config.wled_host, config.led_count, port=config.udp_port )
- property mqtt_broker: str
MQTT broker hostname or IP address.
Default: ‘localhost’
- Returns:
MQTT broker hostname or IP.
- Return type:
Example
Connect to MQTT broker:
listener = EspresenseBeaconListener( state, broker=config.mqtt_broker, port=config.mqtt_port )
- property mqtt_location: str
Location name for espresense filtering.
Used to filter beacon messages from a specific location. Example values: ‘balkon’, ‘bedroom’, ‘living_room’
Default: ‘balkon’
- Returns:
Location name.
- Return type:
Example
Filter beacons by location:
listener = EspresenseBeaconListener( state, broker=config.mqtt_broker, location=config.mqtt_location )
- property mqtt_username: str | None
MQTT broker username for authentication.
If set, used to authenticate with the MQTT broker.
Default: None (no authentication)
- Returns:
MQTT username or None if not set.
- Return type:
Optional[str]
Example
Authenticate with MQTT broker:
if config.mqtt_username: client.username_pw_set( config.mqtt_username, config.mqtt_password )
- property mqtt_password: str | None
MQTT broker password for authentication.
If set along with mqtt_username, used to authenticate with the MQTT broker.
Default: None (no authentication)
- Returns:
MQTT password or None if not set.
- Return type:
Optional[str]
- property beacon_timeout_seconds: float
Beacon timeout duration in seconds.
Time before a beacon is considered timed out (no updates received).
Default: 6.0
- Returns:
Timeout duration in seconds.
- Return type:
Example
Create beacon state with configured timeout:
state = BeaconState( timeout_seconds=config.beacon_timeout_seconds, fade_out_seconds=config.beacon_fade_out_seconds )
- property beacon_fade_out_seconds: float
Beacon fade-out duration in seconds.
Time to fade out a beacon after timeout.
Default: 4.0
- Returns:
Fade-out duration in seconds.
- Return type:
- property update_interval: float
LED update interval in seconds.
Time between LED updates. Smaller values = smoother but higher CPU.
Default: 0.2
- Returns:
Update interval in seconds.
- Return type:
Example
Run animation loop with configured interval:
run_wled_beacons( controller, led_count=config.led_count, beacon_state=state, update_interval=config.update_interval, trail_length=config.trail_length, fade_factor=config.fade_factor )
- property trail_length: int
Motion trail length in LEDs.
Number of LEDs in the motion trail behind each beacon.
Default: 10
- Returns:
Trail length in LEDs.
- Return type:
Example
Use trail length for rendering:
add_trail(leds, pos, color, trail_length=config.trail_length, fade_factor=config.fade_factor)
- property fade_factor: float
Trail brightness fade factor per segment.
Brightness decay per trail segment (0.0 < x <= 1.0). 0.75 = each segment is 75% brightness of previous.
Default: 0.75
- Returns:
Fade factor (0.0 to 1.0).
- Return type:
- Raises:
ValueError – If fade factor is not in valid range.
Example
Configure trail rendering:
add_trail(leds, pos, color, trail_length=config.trail_length, fade_factor=config.fade_factor)
- property log_level: str
Logging level (DEBUG, INFO, WARNING, ERROR, CRITICAL).
Controls verbosity of application logging.
Default: ‘INFO’
- Returns:
Log level name (DEBUG, INFO, WARNING, ERROR, CRITICAL).
- Return type:
- Raises:
ValueError – If log level is not recognized.
Example
Configure logging:
import logging logging.basicConfig(level=config.log_level)
- validate() None[source]
Validate all configuration values.
Runs all property getters to check for invalid values. Useful for catching configuration errors at startup.
- Raises:
ValueError – If any configuration value is invalid.
Example
Validate configuration on startup:
config = Config('.env') try: config.validate() print("Configuration is valid") except ValueError as e: print(f"Configuration error: {e}") sys.exit(1)
- to_dict() dict[source]
Export configuration as dictionary.
Returns all configuration values as a dictionary. Useful for logging or debugging configuration state.
- Returns:
Dictionary with all configuration values.
- Return type:
Example
Log configuration on startup:
import json config = Config('.env') print(json.dumps(config.to_dict(), indent=2))
Overview
The config module provides centralized configuration management for BLE2WLED using environment variables and .env files.
Configuration is loaded from:
.env file (if present)
Environment variables
Default values
Quick Example
from ble2wled.config import Config
# Load configuration from .env
config = Config('.env')
# Validate all required values are present
config.validate()
# Access configuration properties
print(f"WLED: {config.wled_host}:{config.led_count}")
print(f"MQTT: {config.mqtt_broker}:{config.mqtt_port}")
# Export as dictionary for logging
import json
print(json.dumps(config.to_dict(), indent=2))
Properties
WLED Device
wled_host(str, required) - WLED device hostname/IPled_count(int, default 60) - Number of LEDs in stripwled_http_timeout(float, default 1.0) - HTTP request timeoutwled_http_retries(int, default 3) - HTTP retry attemptswled_udp_port(int, default 21324) - UDP DRGB port
MQTT Broker
mqtt_broker(str, required if using MQTT) - MQTT broker hostname/IPmqtt_port(int, default 1883) - MQTT portmqtt_location(str, required if using MQTT) - Location/room identifiermqtt_username(str, optional) - MQTT authentication usernamemqtt_password(str, optional) - MQTT authentication password
Animation
animation_update_interval(float, default 0.05) - Animation update intervalanimation_trail_length(int, default 8) - Motion trail lengthanimation_fade_factor(float, default 0.7) - Trail fade factor
Beacon Detection
beacon_timeout_seconds(float, default 6.0) - Beacon timeoutbeacon_fade_out_seconds(float, default 4.0) - Fade out duration
Methods
__init__(env_file: Optional[str] = None)Initialize configuration, optionally loading from .env file.
validate() -> NoneValidate that all required configuration values are present.
to_dict() -> Dict[str, Any]Export configuration as dictionary (useful for logging/debugging).
Examples
Load from .env File
config = Config('.env')
print(f"LED count: {config.led_count}")
Load from Environment Variables
export WLED_HOST=192.168.1.100
export LED_COUNT=120
export MQTT_BROKER=localhost
config = Config() # Reads from environment
print(f"LED count: {config.led_count}") # 120
Validate Configuration
config = Config('.env')
try:
config.validate()
print("Configuration valid!")
except ValueError as e:
print(f"Invalid config: {e}")
Use with MQTT Authentication
config = Config('.env')
from ble2wled.mqtt import EspresenseBeaconListener
listener = EspresenseBeaconListener(
beacon_state,
broker=config.mqtt_broker,
port=config.mqtt_port,
location=config.mqtt_location,
username=config.mqtt_username, # Optional
password=config.mqtt_password # Optional
)
Export for Logging
import json
config = Config('.env')
# Print formatted configuration
print(json.dumps(config.to_dict(), indent=2))
# Output:
# {
# "wled_host": "192.168.1.100",
# "led_count": 60,
# "mqtt_broker": "192.168.1.50",
# ...
# }
See Also
Configuration - Full configuration guide
Quickstart - Quick start with configuration