This repository has been archived by the owner on Mar 6, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
HiveStorage.h
122 lines (89 loc) · 2.36 KB
/
HiveStorage.h
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
/*
HiveStorage.h - Abstraction class for storing data on a SD card
with fallback to EEPROM
*/
#ifndef HiveStorage_h
#define HiveStorage_h
#include "EEPROM.h"
#include "SD.h"
#include "SPI.h"
#include "HiveSetup.h"
#include "DeviceDispatch.h"
extern uint8_t StorageType;
uint8_t initStorage();
uint8_t initSDStorage();
uint8_t initEEPROMStorage();
void saveSystemSettings();
uint8_t loadSystemSettings();
template <class T> int writeStorage(int position, const T& value) {
const byte *p = (const byte*)(const void*)&value;
int8_t i = 0;
File myFile;
if (StorageType == EEPROMStorage) {
Serial.print(F("Writing to EEPROM"));
for (i = 0; i < sizeof(value); i++)
EEPROM.write(position++, *p++);
return i;
}
if (StorageType == SDStorage) {
// DEBUG
Serial.print(F("Writing to SD to file "));
Serial.println(StorageFileName);
// Select slave SPI device
useDevice(DeviceIdSD);
myFile = SD.open(StorageFileName, FILE_WRITE);
if (myFile) {
// DEBUG
Serial.println(F("Opened file for writing"));
if (myFile.seek(position)) {
for (i = 0; i < sizeof(value); i++)
myFile.write(*p++);
} else {
i = -1;
}
myFile.close();
return i;
} else {
// DEBUG
Serial.println("Unable to open storage file fo writing");
myFile.close();
return -1;
}
}
return -1;
}
template <class T> int readStorage(int position, T& value) {
byte *p = (byte*)(void*)&value;
int8_t i = 0;
File myFile;
if (StorageType == EEPROMStorage) {
for (i = 0; i < sizeof(value); i++)
*p++ = EEPROM.read(position++);
return i;
}
if (StorageType == SDStorage) {
// DEBUG
Serial.println(F("Reading from SD card"));
useDevice(DeviceIdSD);
myFile = SD.open(StorageFileName);
if (myFile) {
// DEBUG
Serial.println(F("File is open"));
if ((position + sizeof(value)) <= myFile.size()) {
if (myFile.seek(position)) {
for (i = 0; i < sizeof(value); i++)
*p++ = myFile.read();
}
} else {
i = -1;
// DEBUG
Serial.println(F("ERROR: Value position is beyond the file size"));
}
myFile.close();
return i;
}
myFile.close();
}
return -1;
}
#endif