-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStorage.cpp
More file actions
111 lines (96 loc) · 2.37 KB
/
Storage.cpp
File metadata and controls
111 lines (96 loc) · 2.37 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
#include "Storage.h"
#include <Arduino.h>
#include <EEPROM.h>
#include <string.h>
namespace storage
{
namespace
{
void copyString(char *dest, size_t size, const std::string &value)
{
if (size == 0)
return;
strncpy(dest, value.c_str(), size - 1);
dest[size - 1] = '\0';
}
void pack(const app::AppConfigData &config, PersistedConfig &cfg)
{
memset(&cfg, 0, sizeof(cfg));
cfg.magic = kMagic;
cfg.version = kVersion;
cfg.brightness = config.lcdBrightness;
cfg.rotation = config.lcdRotation;
copyString(cfg.wifiSsid, sizeof(cfg.wifiSsid), config.wifiSsid);
copyString(cfg.wifiPsk, sizeof(cfg.wifiPsk), config.wifiPsk);
copyString(cfg.remoteBaseUrl, sizeof(cfg.remoteBaseUrl), config.remoteBaseUrl);
copyString(cfg.remoteDeviceId, sizeof(cfg.remoteDeviceId), config.remoteDeviceId);
}
void unpack(const PersistedConfig &cfg, app::AppConfigData &config)
{
config.lcdBrightness = cfg.brightness;
config.lcdRotation = cfg.rotation;
config.wifiSsid = cfg.wifiSsid;
config.wifiPsk = cfg.wifiPsk;
config.remoteBaseUrl = cfg.remoteBaseUrl;
config.remoteDeviceId = cfg.remoteDeviceId;
if (config.remoteBaseUrl.empty())
{
config.remoteBaseUrl = app_config::kDefaultRemoteRenderBaseUrl;
}
if (config.remoteDeviceId.empty())
{
config.remoteDeviceId = app_config::kDefaultRemoteDeviceId;
}
}
void writeBlob(const void *buf, size_t len)
{
const uint8_t *p = (const uint8_t *)buf;
for (size_t i = 0; i < len; i++)
{
EEPROM.write(i, p[i]);
}
EEPROM.commit();
}
void readBlob(void *buf, size_t len)
{
uint8_t *p = (uint8_t *)buf;
for (size_t i = 0; i < len; i++)
{
p[i] = EEPROM.read(i);
}
}
} // namespace
void begin()
{
EEPROM.begin(kEepromSize);
}
bool loadConfig(app::AppConfigData &config)
{
PersistedConfig cfg;
readBlob(&cfg, sizeof(cfg));
if (cfg.magic == kMagic && cfg.version == kVersion)
{
unpack(cfg, config);
Serial.println(F("[Storage] loaded"));
return true;
}
config = app::AppConfigData{};
saveConfig(config);
Serial.println(F("[Storage] invalid config, reset to defaults"));
return false;
}
void saveConfig(const app::AppConfigData &config)
{
PersistedConfig cfg;
pack(config, cfg);
writeBlob(&cfg, sizeof(cfg));
}
void clearWifiCredentials()
{
app::AppConfigData config;
loadConfig(config);
config.wifiSsid.clear();
config.wifiPsk.clear();
saveConfig(config);
}
} // namespace storage