-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathconfig2eeprom.cpp
115 lines (98 loc) · 2.69 KB
/
config2eeprom.cpp
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
112
113
114
115
#include "config2eeprom.hpp"
// Start with starting address 0 if not mentioned
config2eeprom::config2eeprom()
{
_beginByte = 0;
}
// Start with mentioned byte starting address
config2eeprom::config2eeprom(unsigned int beginByte)
{
_beginByte = beginByte;
}
// Save staticDOC json hash to EEPROM
void config2eeprom::save(staticConfigDoc doc)
{
#ifdef DEBUG_EEPROM
Serial.print("Config2EEPRom: Saving data from begin byte:");
Serial.println(_beginByte);
#endif
// Mount EEPROM partiton
EEPROM.begin(EEPROM_SIZE);
char serialized[EEPROM_DOC_SIZE];
serializeMsgPack(doc, serialized);
// Write to EEPROM byte by byte
for (short n = 0; n < sizeof(serialized); n++) // automatically adjust for chars
{
EEPROM.write(n + _beginByte, serialized[n]);
}
// Commit and unmount
if (!EEPROM.commit())
{
Serial.print("Config2EEPRom: Error while commit to eeprom.");
}
EEPROM.end();
}
// Load staticDOC json hash from EEPROM. Return false on error or empty.
bool config2eeprom::load(staticConfigDoc &doc)
{
#ifdef DEBUG_EEPROM
Serial.print("Config2EEPRom: Loading data from begin byte:");
Serial.println(_beginByte);
#endif
// Mount EEPROM partiton
EEPROM.begin(EEPROM_SIZE);
char serialized[EEPROM_DOC_SIZE];
// Read from EEPROM byte by byte
for (short n = 0; n < sizeof(serialized); n++) // automatically adjust for chars
{
serialized[n] = EEPROM.read(n + _beginByte);
}
// Unmount eeprom
EEPROM.end();
#ifdef DEBUG_EEPROM
Serial.println("Config2EEPRom: Got bytes from eeprom:");
Serial.println(serialized);
#endif
// Deserialize from msgPack
DeserializationError error = deserializeMsgPack(doc, serialized);
// Check for errors
if (error.code() != DeserializationError::Ok)
{
#ifdef DEBUG_EEPROM
Serial.print("Config2EEProm got deserialization error:");
Serial.println(error.c_str());
#endif
return false;
}
// Check for empty
if (doc.size() == 0)
{
#ifdef DEBUG_EEPROM
Serial.println("Config2EEProm: got empty array from load().");
#endif
return false;
}
#ifdef DEBUG_EEPROM
Serial.print("Config2EEProm: Deserialized document with size:");
Serial.println(doc.size());
#endif
return true;
}
// Clear EEPROM
void config2eeprom::clear()
{
#ifdef DEBUG_EEPROM
Serial.print("Config2EEPRom: Clearing EEPROM begin byte:");
Serial.println(_beginByte);
#endif
EEPROM.begin(EEPROM_SIZE);
for (int i = 0; i < EEPROM_DOC_SIZE; i++)
{
EEPROM.write(i + _beginByte, 0);
}
if (!EEPROM.commit())
{
Serial.print("Config2EEPRom: Error while commit to eeprom.");
}
EEPROM.end();
}