Skip to content
Snippets Groups Projects
Commit f04c65ee authored by ave's avatar ave
Browse files

st3m/utils: add save_file_if_changed function

parent 9b7829f5
Branches
Tags
No related merge requests found
......@@ -3,6 +3,7 @@ from st3m.input import InputState
from st3m.goose import Optional
from st3m.ui.view import ViewManager
from st3m.settings import SETTINGS_JSON_FILE
from st3m.utils import save_file_if_changed
from ctx import Context
import network
import leds
......@@ -210,23 +211,19 @@ class WifiApp(Application):
settings_json["system"]["wifi"]["ssid"] = ssid
settings_json["system"]["wifi"]["psk"] = psk
with open(SETTINGS_JSON_FILE, "w") as f:
json.dump(settings_json, f)
save_file_if_changed(SETTINGS_JSON_FILE, json.dumps(settings_json))
def add_wlan_to_config_json(self, ssid: str, psk: str) -> None:
self._wifi_config["networks"][ssid] = {"psk": psk}
self.save_config_json()
def save_config_json(self) -> None:
with open(self.WIFI_CONFIG_FILE, "w") as f:
json.dump(self._wifi_config, f)
config_str = json.dumps(self._wifi_config)
save_file_if_changed(self.WIFI_CONFIG_FILE, config_str)
if sd_card_plugged():
try:
if os.path.exists(self.WIFI_CONFIG_FILE_SD):
os.remove(self.WIFI_CONFIG_FILE_SD)
copy_across_devices(self.WIFI_CONFIG_FILE, self.WIFI_CONFIG_FILE_SD)
save_file_if_changed(self.WIFI_CONFIG_FILE_SD, config_str)
except OSError as e:
print("SD issue:", str(e), ":(")
......
......@@ -20,7 +20,7 @@ from st3m.goose import (
Optional,
Callable,
)
from st3m.utils import reduce
from st3m.utils import reduce, save_file_if_changed
log = logging.Log(__name__, level=logging.INFO)
......@@ -319,16 +319,20 @@ def save_all() -> None:
Save all settings to flash.
"""
res: Dict[str, Any] = {}
saved_settings = False
for setting in load_save_settings:
res = _update(res, setting.save())
try:
with open(SETTINGS_JSON_FILE, "w") as f:
json.dump(res, f)
saved_settings = save_file_if_changed(SETTINGS_JSON_FILE, json.dumps(res))
except Exception as e:
log.warning("Could not save settings: " + str(e))
return
log.info("Saved settings to flash")
log.info(
"Saved settings to flash"
if saved_settings
else "Skipped saving settings to flash as nothing changed"
)
load_all()
import math
import os
try:
import inspect
......@@ -121,4 +122,19 @@ def get_function_args(fun: Any) -> list[str]:
raise NotImplementedError("No implementation of getfullargspec found")
def save_file_if_changed(filename: str, desired_contents: str) -> bool:
save = False
if not os.path.exists(filename):
save = True
else:
with open(filename, "r") as f:
save = f.read() != desired_contents
if save:
with open(filename, "w") as f:
f.write(desired_contents)
return save
tau = math.pi * 2
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment