Files
led-driver/src/settings.py
Jimmy 4c7646b2fe Adjust defaults and preset handling
- Switch startup_preset to default key
- Add built-in on/off presets and tweak device defaults

Made-with: Cursor
2026-03-14 02:41:07 +13:00

89 lines
2.7 KiB
Python

import json
import ubinascii
import machine
import network
class Settings(dict):
SETTINGS_FILE = "/settings.json"
def __init__(self):
super().__init__()
self.load() # Load settings from file during initialization
self.color_order = self.get_color_order(self["color_order"])
def set_defaults(self):
self["led_pin"] = 10
self["num_leds"] = 119
self["color_order"] = "rgb"
self["name"] = "a"
self["debug"] = False
self["default"] = "on"
self["brightness"] = 32
def save(self):
try:
j = json.dumps(self)
with open(self.SETTINGS_FILE, 'w') as file:
file.write(j)
print("Settings saved successfully.")
except Exception as e:
print(f"Error saving settings: {e}")
def load(self):
try:
with open(self.SETTINGS_FILE, 'r') as file:
loaded_settings = json.load(file)
self.update(loaded_settings)
print("Settings loaded successfully.")
except Exception as e:
print(f"Error loading settings")
self.set_defaults()
self.save()
def get_color_order(self, color_order):
"""Convert color order string to tuple of hex string indices."""
color_orders = {
"rgb": (1, 3, 5),
"rbg": (1, 5, 3),
"grb": (3, 1, 5),
"gbr": (3, 5, 1),
"brg": (5, 1, 3),
"bgr": (5, 3, 1)
}
return color_orders.get(color_order.lower(), (1, 3, 5)) # Default to RGB
def get_rgb_channel_order(self, color_order=None):
"""Convert color order string to RGB channel indices for reordering tuples.
Returns tuple of channel indices: (r_channel, g_channel, b_channel)
Example: 'grb' -> (1, 0, 2) means (G, R, B)"""
if color_order is None:
color_order = self.get("color_order", "rgb")
color_order = color_order.lower()
# Map hex string positions to RGB channel indices
# Position 1 (R in hex) -> channel 0, Position 3 (G) -> channel 1, Position 5 (B) -> channel 2
hex_to_channel = {1: 0, 3: 1, 5: 2}
hex_indices = self.get_color_order(color_order)
return tuple(hex_to_channel[pos] for pos in hex_indices)
# Example usage
def main():
settings = Settings()
print(f"Number of LEDs: {settings['num_leds']}")
settings['num_leds'] = 100
print(f"Updated number of LEDs: {settings['num_leds']}")
settings.save()
# Create a new Settings object to test loading
new_settings = Settings()
print(f"Loaded number of LEDs: {new_settings['num_leds']}")
print(settings)
# Run the example
if __name__ == "__main__":
main()