-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPermanentStore.cpp
79 lines (62 loc) · 1.62 KB
/
PermanentStore.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
#include "PermanentStore.h"
// no table only used rarely
uint8_t PermanentStore::crc(const uint8_t *message, int n) {
uint8_t remainder = 0;
for (int byte = 0; byte < n; ++byte) {
remainder ^= message[byte];
for (uint8_t bit = 8; bit > 0; --bit) {
if (remainder & 0x80) {
remainder = (remainder << 1) ^ 0xD8;
} else {
remainder = (remainder << 1);
}
}
}
return remainder;
}
void PermanentStore::writeRecord(int addr, record *r) {
uint8_t *p = (uint8_t *)r;
for (int i = 0; i < sizeof(record); ++i) {
uint8_t v = EEPROM.read(addr + i);
if (*p != v) {
EEPROM.write(addr + i, *p);
}
++p;
}
}
void PermanentStore::readRecord(int addr, record *r) {
uint8_t *p = (uint8_t *)r;
for (int i = 0; i < sizeof(record); ++i) {
*p++ = EEPROM.read(addr + i);
}
}
uint8_t PermanentStore::computeId(Model *m) {
const char *p = m->name;
int length = 0;
while (*p++ != '\0') ++length;
return crc((const uint8_t *) m->name, length);
}
void PermanentStore::save(Model *m) {
rec.id = computeId(m);
for (int i = 0; i<4; ++i) {
rec.values[i] = m->trim[i];
}
rec.crc = crc(((uint8_t *)&rec)+1,sizeof(record)-1);
// store it
writeRecord(m->id * sizeof(record), &rec);
}
void PermanentStore::load(Model *m) {
// load it
readRecord(m->id * sizeof(record), &rec);
uint8_t id = computeId(m);
uint8_t crcVal = crc(((uint8_t *)&rec)+1,sizeof(record)-1);
if (id == rec.id && crcVal == rec.crc) {
for (int i = 0; i < 4; ++i) {
m->trim[i] = rec.values[i];
}
} else {
for (int i = 0; i < 4; ++i) {
m->trim[i] = 0;
}
}
}