From c0b08339052547a6e47abd1749be723ccf92c5ea Mon Sep 17 00:00:00 2001 From: Jimmy Date: Sun, 6 Oct 2024 22:01:34 +1300 Subject: [PATCH] Save settings between powers cycles --- settings.py | 55 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 settings.py diff --git a/settings.py b/settings.py new file mode 100644 index 0000000..0f626e6 --- /dev/null +++ b/settings.py @@ -0,0 +1,55 @@ +import json +import os +import uasyncio as asyncio + +class Settings(dict): + SETTINGS_FILE = "/settings.json" + + def __init__(self): + super().__init__() + self.load() # Load settings from file during initialization + + def set_defaults(self): + self["num_leds"] = 50 + self["selected_pattern"] = "blink" + self["color1"] = "#000f00" + self["color2"] = "#0f0000" + self["delay"] = 100 + self["brightness"] = 100 + self["wifi"] = {"ssid": "", "password": ""} + + 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: {e}") + self.set_defaults() + +# 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() \ No newline at end of file