diff --git a/software/src/utils/__init__.py b/software/src/utils/__init__.py index abf0eae..3f5d65d 100644 --- a/software/src/utils/__init__.py +++ b/software/src/utils/__init__.py @@ -2,6 +2,7 @@ # Copyright (c) 2025 Matthias Blankertz from utils.buttons import Buttons +from utils.config import Configuration from utils.leds import LedManager from utils.mbrpartition import MBRPartition from utils.pinindex import get_pin_index @@ -9,5 +10,5 @@ from utils.playlistdb import BTreeDB, BTreeFileManager from utils.sdcontext import SDContext from utils.timer import TimerManager -__all__ = ["BTreeDB", "BTreeFileManager", "Buttons", "get_pin_index", "LedManager", "MBRPartition", "SDContext", - "TimerManager"] +__all__ = ["BTreeDB", "BTreeFileManager", "Buttons", "Configuration", "get_pin_index", "LedManager", "MBRPartition", + "SDContext", "TimerManager"] diff --git a/software/src/utils/config.py b/software/src/utils/config.py new file mode 100644 index 0000000..ea9b050 --- /dev/null +++ b/software/src/utils/config.py @@ -0,0 +1,44 @@ +# SPDX-License-Identifier: MIT +# Copyright (c) 2025 Matthias Blankertz + +from errno import ENOENT +import json +import os + + +class Configuration: + DEFAULT_CONFIG = { + } + + def __init__(self, config_path='/config.json'): + self.config_path = config_path + try: + with open(self.config_path, 'r') as conf_file: + self.config = json.load(conf_file) + except OSError as ex: + if ex.errno == ENOENT: + self.config = Configuration.DEFAULT_CONFIG + self._save() + else: + raise + except ValueError as ex: + print(f"Warning: Could not load configuration {self.config_path}:\n{ex}") + self._move_config_to_backup() + self.config = Configuration.DEFAULT_CONFIG + + def _move_config_to_backup(self): + # Remove old backup + try: + os.remove(self.config_path + '.bup') + os.rename(self.config_path, self.config_path + '.bup') + except OSError as ex: + if ex.errno != ENOENT: + raise + os.sync() + + def _save(self): + with open(self.config_path + '.new', 'w') as conf_file: + json.dump(self.config, conf_file) + self._move_config_to_backup() + os.rename(self.config_path + '.new', self.config_path) + os.sync()