-
Notifications
You must be signed in to change notification settings - Fork 0
/
SDCard.cpp
354 lines (308 loc) · 12.4 KB
/
SDCard.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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
/**
* Copyright 2022 William Edward Fisher.
*/
#include "SDCard.h"
#include <ArduinoJson.h>
#include <SPI.h>
#include <StackString.hpp> // I have not yet understood how to use cstrings. Why are these hard?
using namespace Stack;
#include "Config.h"
#include "Utils.h"
/**
* @brief Abstraction for different SD/FS libraries across platforms.
*/
typedef struct RecollectionsFileSystem {
static File open(const char *filepath, uint8_t mode);
static bool exists(const char *filepath);
static bool mkdir(const char *filepath);
} RecollectionsFileSystem;
File RecollectionsFileSystem::open(const char *filepath, uint8_t mode = FILE_READ) {
#ifdef CORE_TEENSY
File file = SD.open(filepath, mode);
if (mode == FILE_WRITE_BEGIN) {
file.truncate();
}
return file;
#else // PICO
switch (mode) {
case SD_READ_CREATE: {
// SDFS offers no read + create option where writing is forbidden, so this must be done
// manually. Alternatively, we could use the "a+" mode, but this would allow writes to the
// end of an existing file. Paranoia, again.
return SDFS.exists(filepath) ? SDFS.open(filepath, "r") : SDFS.open(filepath, "w");
break;
}
case FILE_WRITE_BEGIN: {
return SDFS.open(filepath, "w");
break;
}
default: {
return SDFS.open(filepath, "r");
break;
}
}
#endif
}
bool RecollectionsFileSystem::exists(const char *filepath) {
#ifdef CORE_TEENSY
return SD.exists(filepath);
#else // PICO
return SDFS.exists(filepath);
#endif
}
bool RecollectionsFileSystem::mkdir(const char *filepath) {
#ifdef CORE_TEENSY
return SD.mkdir(filepath);
#else // PICO
return SDFS.mkdir(filepath);
#endif
}
void SDCard::confirmOrCreatePath(State state) {
int currentModuleLength = snprintf(NULL, 0, "%d", state.config.currentModule) + 1;
char currentModuleString[currentModuleLength];
sprintf(currentModuleString, "%d", state.config.currentModule);
StackString<100> modulePath = StackString<100>(MODULE_SD_PATH_PREFIX);
modulePath.append(currentModuleString);
if (!RecollectionsFileSystem::exists(modulePath.c_str())) {
if (!RecollectionsFileSystem::exists("Recollections")) {
RecollectionsFileSystem::mkdir("Recollections");
}
RecollectionsFileSystem::mkdir(modulePath.c_str());
}
}
Config SDCard::readConfigFile(Config config) {
File configFile = RecollectionsFileSystem::open(CONFIG_SD_PATH, SD_READ_CREATE);
if (!configFile) {
Serial.println("Could not open Config.txt");
return config;
} else {
Serial.println("Successfully opened Config.txt");
}
JsonDocument doc;
DeserializationError error = deserializeJson(doc, configFile);
if (error == DeserializationError::EmptyInput) {
Serial.println("Config.txt is an empty file");
return config;
}
else if (error) {
Serial.printf("%s %s \n", "deserializeJson() failed during read operation: ", error.c_str());
return config;
}
else {
Serial.println("Copying Config.txt to config struct");
if (doc["brightness"] != nullptr) {
config.brightness = doc["brightness"];
}
if (doc["colors"] != nullptr) {
copyArray(doc["colors"]["white"], config.colors.white);
copyArray(doc["colors"]["red"], config.colors.red);
copyArray(doc["colors"]["blue"], config.colors.blue);
copyArray(doc["colors"]["yellow"], config.colors.yellow);
copyArray(doc["colors"]["green"], config.colors.green);
copyArray(doc["colors"]["purple"], config.colors.purple);
copyArray(doc["colors"]["orange"], config.colors.orange);
copyArray(doc["colors"]["magenta"], config.colors.magenta);
copyArray(doc["colors"]["black"], config.colors.black);
}
if (doc["controllerOrientation"] != nullptr) {
config.controllerOrientation = doc["controllerOrientation"];
}
if (doc["currentModule"] != nullptr) {
config.currentModule = doc["currentModule"];
}
if (doc["isAdvancingMaxInterval"] != nullptr) {
config.isAdvancingMaxInterval = doc["isAdvancingMaxInterval"];
}
if (doc["isClockedTolerance"] != nullptr) {
config.isClockedTolerance = doc["isClockedTolerance"];
}
if (doc["randomOutputOverwrites"] != nullptr) {
config.randomOutputOverwrites = doc["randomOutputOverwrites"];
}
}
configFile.close();
return config;
}
State SDCard::readModuleDirectory(State state) {
state = SDCard::readModuleFile(state);
for (uint8_t bank = 0; bank < 16; bank++) {
state = SDCard::readBankFile(state, bank);
}
return state;
}
State SDCard::readModuleFile(State state) {
int currentModuleLength = snprintf(NULL, 0, "%d", state.config.currentModule) + 1;
char currentModuleString[currentModuleLength];
sprintf(currentModuleString, "%d", state.config.currentModule);
// Recollections/Module_15/Module.txt
StackString<100> modulePath = StackString<100>(MODULE_SD_PATH_PREFIX);
modulePath.append(currentModuleString);
modulePath.append("/Module.txt");
File moduleFile = RecollectionsFileSystem::open(modulePath.c_str(), SD_READ_CREATE);
if (!moduleFile) {
Serial.println("Could not open Module.txt");
return state;
} else {
Serial.println("Successfully opened Module.txt");
}
JsonDocument doc;
DeserializationError error = deserializeJson(doc, moduleFile);
if (error == DeserializationError::EmptyInput) {
Serial.println("Module.txt is an empty file");
}
else if (error) {
Serial.printf("%s %s \n", "deserializeJson() failed during read operation: ", error.c_str());
}
else {
Serial.println("Copying Module.txt to state");
state.currentPreset = doc["currentPreset"];
state.currentBank = doc["currentBank"];
state.currentChannel = doc["currentChannel"];
copyArray(doc["removedPresets"], state.removedPresets);
}
moduleFile.close();
return state;
}
State SDCard::readBankFile(State state, uint8_t bank) {
int currentModuleLength = snprintf(NULL, 0, "%d", state.config.currentModule) + 1;
char currentModuleString[currentModuleLength];
sprintf(currentModuleString, "%d", state.config.currentModule);
int bankLength = snprintf(NULL, 0, "%d", bank) + 1;
char bankString[bankLength];
sprintf(bankString, "%d", bank);
// Recollections/Module_15/Bank_0.txt
StackString<100> bankPath = StackString<100>(MODULE_SD_PATH_PREFIX);
bankPath.append(currentModuleString);
bankPath.append("/Bank_");
bankPath.append(bankString);
bankPath.append(".txt");
File bankFile = RecollectionsFileSystem::open(bankPath.c_str(), SD_READ_CREATE);
if (!bankFile) {
Serial.printf("%s%s%s\n", "Could not open Bank_", bankString, ".txt");
return state;
} else {
Serial.printf("%s%s%s\n", "Successfully opened Bank_", bankString, ".txt");
}
JsonDocument doc;
DeserializationError error = deserializeJson(doc, bankFile);
if (error == DeserializationError::EmptyInput) {
Serial.printf("Bank_%s.txt is an empty file\n", bankString);
}
else if (error) {
Serial.printf("%s %s \n", "deserializeJson() failed during read operation: ", error.c_str());
}
else {
Serial.printf("Copying Bank_%s.txt to state\n", bankString);
copyArray(doc["activeVoltages"], state.activeVoltages[bank]);
copyArray(doc["autoRecordChannels"], state.autoRecordChannels[bank]);
copyArray(doc["gateChannels"], state.gateChannels[bank]);
copyArray(doc["gateVoltages"], state.gateVoltages[bank]);
copyArray(doc["lockedVoltages"], state.lockedVoltages[bank]);
copyArray(doc["randomInputChannels"], state.randomInputChannels[bank]);
copyArray(doc["randomOutputChannels"], state.randomOutputChannels[bank]);
copyArray(doc["randomVoltages"], state.randomVoltages[bank]);
copyArray(doc["voltages"], state.voltages[bank]);
}
bankFile.close();
return state;
}
bool SDCard::writeCurrentModuleAndBank(State state) {
Serial.println("writing to SD card");
SDCard::confirmOrCreatePath(state);
// TODO: I would like to abstract a lot of this into a function, since a lot of lines are repeated
// twice here and in the other SD card functions, but I am having trouble figuring out how to do
// this with cstrings in a way that makes sense and actually saves lines of code. Something to
// improve upon later.
// --------------------------- Module file ---------------------------------
int currentModuleLength = snprintf(NULL, 0, "%d", state.config.currentModule) + 1;
char currentModuleString[currentModuleLength];
sprintf(currentModuleString, "%d", state.config.currentModule);
// Recollections/Module_15/Module.txt
StackString<100> modulePath = StackString<100>(MODULE_SD_PATH_PREFIX);
modulePath.append(currentModuleString);
modulePath.append("/Module.txt");
File moduleFile = RecollectionsFileSystem::open(modulePath.c_str(), FILE_WRITE_BEGIN);
if (!moduleFile) {
Serial.println("Could not open Module.txt");
return false;
} else {
Serial.println("Successfully opened Module.txt");
}
JsonDocument moduleDoc;
moduleDoc["currentBank"] = state.currentBank;
moduleDoc["currentChannel"] = state.currentChannel;
moduleDoc["currentPreset"] = state.currentPreset;
for (uint8_t i = 0; i < 16; i++) {
moduleDoc["removedPresets"][i] = state.removedPresets[i];
}
WriteBufferingStream writeBufferingStream(moduleFile, 64);
size_t charsWritten = serializeJson(moduleDoc, writeBufferingStream);
writeBufferingStream.flush();
moduleFile.close();
if (charsWritten == 0) {
Serial.println("Failed to write any chars to SD card");
return false;
} else {
Serial.printf("%s %u \n", "chars written: ", charsWritten);
}
// --------------------------- Bank file -------------------------------------
uint8_t bank = state.currentBank;
int bankLength = snprintf(NULL, 0, "%d", bank) + 1;
char bankString[bankLength];
sprintf(bankString, "%d", bank);
// Recollections/Module_15/Bank_0.txt
StackString<100> bankPath = StackString<100>(MODULE_SD_PATH_PREFIX);
bankPath.append(currentModuleString);
bankPath.append("/Bank_");
bankPath.append(bankString);
bankPath.append(".txt");
File bankFile = RecollectionsFileSystem::open(bankPath.c_str(), FILE_WRITE_BEGIN);
if (!bankFile) {
Serial.printf("%s%s%s\n", "Could not open Bank_", bankString, ".txt");
return false;
} else {
Serial.printf("%s%s%s\n", "Successfully opened Bank_", bankString, ".txt");
}
JsonDocument bankDoc;
JsonObject bankRoot = bankDoc.to<JsonObject>();
JsonArray autoRecordChannels = bankRoot["autoRecordChannels"].to<JsonArray>();
JsonArray gateChannels = bankRoot["gateChannels"].to<JsonArray>();
JsonArray randomInputChannels = bankRoot["randomInputChannels"].to<JsonArray>();
JsonArray randomOutputChannels = bankRoot["randomOutputChannels"].to<JsonArray>();
for (uint8_t i = 0; i < 8; i++) {
autoRecordChannels.add(state.autoRecordChannels[bank][i]);
gateChannels.add(state.gateChannels[bank][i]);
randomInputChannels.add(state.randomInputChannels[bank][i]);
randomOutputChannels.add(state.randomOutputChannels[bank][i]);
}
JsonArray activeVoltages = bankRoot["activeVoltages"].to<JsonArray>();
JsonArray gateVoltages = bankRoot["gateVoltages"].to<JsonArray>();
JsonArray lockedVoltages = bankRoot["lockedVoltages"].to<JsonArray>();
JsonArray randomVoltages = bankRoot["randomVoltages"].to<JsonArray>();
JsonArray voltages = bankRoot["voltages"].to<JsonArray>();
for (uint8_t i = 0; i < 16; i++) {
JsonArray activeVoltagesChannelArray = activeVoltages.add<JsonArray>();
JsonArray gateVoltagesChannelArray = gateVoltages.add<JsonArray>();
JsonArray lockedVoltagesChannelArray = lockedVoltages.add<JsonArray>();
JsonArray randomVoltagesChannelArray = randomVoltages.add<JsonArray>();
JsonArray voltagesChannelArray = voltages.add<JsonArray>();
for (uint8_t j = 0; j < 8; j++) {
activeVoltagesChannelArray.add(state.activeVoltages[bank][i][j]);
gateVoltagesChannelArray.add(state.gateVoltages[bank][i][j]);
lockedVoltagesChannelArray.add(state.lockedVoltages[bank][i][j]);
randomVoltagesChannelArray.add(state.randomVoltages[bank][i][j]);
voltagesChannelArray.add(state.voltages[bank][i][j]);
}
}
WriteBufferingStream writeBankBufferingStream(bankFile, 64);
size_t bankCharsWritten = serializeJson(bankDoc, writeBankBufferingStream);
writeBankBufferingStream.flush();
bankFile.close();
if (bankCharsWritten == 0) {
Serial.println("Failed to write any chars to SD card");
return false;
} else {
Serial.printf("%s %u \n", "chars written: ", bankCharsWritten);
}
return true;
}