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()
This commit is contained in:
2026-01-27 13:05:02 +13:00
parent a7e921805a
commit d7fabf58a4

View File

@@ -45,6 +45,12 @@ class Model(dict):
j = json.dumps(self) j = json.dumps(self)
with open(self.file, 'w') as file: with open(self.file, 'w') as file:
file.write(j) 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}") print(f"{self.class_name} saved successfully to {self.file}")
except Exception as e: except Exception as e:
print(f"Error saving {self.class_name} to {self.file}: {e}") print(f"Error saving {self.class_name} to {self.file}: {e}")
@@ -52,12 +58,47 @@ class Model(dict):
sys.print_exception(e) sys.print_exception(e)
def load(self): def load(self):
try:
# Check if file exists first
try: try:
with open(self.file, 'r') as file: with open(self.file, 'r') as file:
loaded_settings = json.load(file) content = file.read().strip()
self.update(loaded_settings) 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.") print(f"{self.class_name} loaded successfully.")
except Exception as e: except OSError as e:
print(f"Error loading {self.class_name}") # 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.set_defaults()
self.save() self.save()