import json import ubinascii import machine import network WIFI_CHANNEL_DEFAULT = 5 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" sta = network.WLAN(network.STA_IF) sta.active(True) #use led-mac for name mac = sta.config("mac") mac = ubinascii.hexlify(mac).decode().lower() self["name"] = "led-" + mac self["debug"] = False self["default"] = "on" self["last_preset"] = "" # Power-on: "default" | "last" | "off" self["startup_mode"] = "default" self["brightness"] = 32 self["wifi_channel"] = WIFI_CHANNEL_DEFAULT def save(self): try: j = json.dumps(self) with open(self.SETTINGS_FILE, 'w') as file: file.write(j) 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) old_recent = self.pop("recent_presets", None) if isinstance(old_recent, list) and old_recent and not self.get("last_preset"): for x in reversed(old_recent): if isinstance(x, str) and x.strip(): self["last_preset"] = x.strip() break if x is not None: s = str(x).strip() if s: self["last_preset"] = s break 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()