-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstorage.cpp
95 lines (81 loc) · 2.52 KB
/
storage.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
/* noisemeter-device - Firmware for CivicTechTO's Noisemeter Device
* Copyright (C) 2024 Clyne Sullivan, Nick Barnard
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#include "storage.h"
#include <Arduino.h>
#include <CRC32.h>
#include <array>
void Storage::begin(UUID key)
{
secret.key = key;
EEPROMClass::begin(addrOf(Entry::TotalSize));
delay(2000); // Ensure the eeprom peripheral has enough time to initialize.
}
bool Storage::valid() const noexcept
{
const auto calc = calculateChecksum();
const auto addr = _data + addrOf(Entry::Checksum);
const auto stored = *reinterpret_cast<uint32_t *>(addr);
return stored == calc;
}
bool Storage::canStore(String str) const noexcept
{
return str.length() < StringSize;
}
void Storage::clear() noexcept
{
for (auto i = 0u; i < addrOf(Entry::TotalSize); ++i)
writeByte(i, 0xFF);
set(Entry::Token, "\0");
EEPROMClass::commit();
}
String Storage::get(Entry entry) const noexcept
{
if (entry != Entry::Checksum) {
std::array<char, StringSize> buf;
secret.decrypt(_data + addrOf(entry), buf.data(), StringSize);
return buf.data();
} else {
return {};
}
}
void Storage::set(Entry entry, String str) noexcept
{
if (entry != Entry::Checksum && canStore(str)) {
secret.encrypt(str.c_str(), _data + addrOf(entry), StringSize);
}
}
void Storage::commit() noexcept
{
const auto csum = calculateChecksum();
writeUInt(addrOf(Entry::Checksum), csum);
EEPROMClass::commit();
}
#ifdef STORAGE_SHOW_CREDENTIALS
Storage::operator String() const noexcept
{
return String() +
"SSID \"" + get(Entry::SSID) +
"\" Passkey \"" + get(Entry::Passkey) +
'\"';
}
#endif
uint32_t Storage::calculateChecksum() const noexcept
{
const auto addr = _data + sizeof(uint32_t);
const auto size = addrOf(Entry::TotalSize) - sizeof(uint32_t);
return CRC32::calculate(addr, size);
}