From d7fabf58a47a379eea509e7fb824b27c55842171 Mon Sep 17 00:00:00 2001 From: jimmy Date: Tue, 27 Jan 2026 13:05:02 +1300 Subject: [PATCH] Fix MicroPython compatibility issues in Model class - Fix JSONDecodeError handling (use ValueError for MicroPython) - Fix sys.print_exception argument issues - Improve error handling in load() method - Add proper file persistence with flush() and os.sync() --- src/models/model.py | 51 ++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 46 insertions(+), 5 deletions(-) diff --git a/src/models/model.py b/src/models/model.py index cb924a1..ccb7a3e 100644 --- a/src/models/model.py +++ b/src/models/model.py @@ -45,6 +45,12 @@ class Model(dict): j = json.dumps(self) with open(self.file, 'w') as file: file.write(j) + file.flush() # Ensure data is written to buffer + # Try to sync filesystem if available (MicroPython) + try: + os.sync() + except (AttributeError, OSError): + pass # os.sync() not available on all platforms print(f"{self.class_name} saved successfully to {self.file}") except Exception as e: print(f"Error saving {self.class_name} to {self.file}: {e}") @@ -53,11 +59,46 @@ class Model(dict): def load(self): try: - with open(self.file, 'r') as file: - loaded_settings = json.load(file) - self.update(loaded_settings) + # Check if file exists first + try: + with open(self.file, 'r') as file: + content = file.read().strip() + except OSError: + # File doesn't exist + raise + + if not content: + # Empty file + loaded_settings = {} + else: + # Parse JSON content + loaded_settings = json.loads(content) + + # Verify it's a dictionary + if not isinstance(loaded_settings, dict): + raise ValueError(f"File does not contain a dictionary, got {type(loaded_settings)}") + + # Clear and update with loaded data + # Clear first + self.clear() + # Manually copy items to avoid any update() method issues + for key, value in loaded_settings.items(): + self[key] = value print(f"{self.class_name} loaded successfully.") - except Exception as e: - print(f"Error loading {self.class_name}") + except OSError as e: + # File doesn't exist yet - this is normal on first run + # Create an empty file with defaults + self.set_defaults() + self.save() + print(f"{self.class_name} initialized (new file created).") + except ValueError: + # JSON parsing error - file exists but is corrupted + # Note: MicroPython uses ValueError for JSON errors, not JSONDecodeError + print(f"Error loading {self.class_name}: Invalid JSON format. Resetting to defaults.") + self.set_defaults() + self.save() + except Exception: + # Other unexpected errors - avoid trying to format exception to prevent further errors + print(f"Error loading {self.class_name}. Resetting to defaults.") self.set_defaults() self.save()