-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathLoom_MongoDB.cpp
More file actions
332 lines (285 loc) · 12.6 KB
/
Loom_MongoDB.cpp
File metadata and controls
332 lines (285 loc) · 12.6 KB
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
#include "Loom_MongoDB.h"
#include "../../../Sensors/Loom_Analog/Loom_Analog.h"
#include "Logger.h"
//////////////////////////////////////////////////////////////////////////////////////////////////////
Loom_MongoDB::Loom_MongoDB(Manager &man, NetworkComponent &internet_client,
const char *broker_address, int broker_port, const char *database_name,
const char *broker_user, const char *broker_pass,
const char *projectServer)
: MQTTComponent("MongoDB", internet_client), manInst(&man) {
/* MQTT Connection parameters */
strncpy(this->address, broker_address, 100);
port = broker_port;
strncpy(this->username, broker_user, 100);
strncpy(this->password, broker_pass, 100);
/* Local MongoDB parameters */
strncpy(this->database_name, database_name, 100);
strncpy(this->projectServer, projectServer, 100);
}
//////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////
Loom_MongoDB::Loom_MongoDB(Manager &man, NetworkComponent &internet_client)
: MQTTComponent("MongoDB", internet_client), manInst(&man) {
moduleInitialized = false;
}
//////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////
bool Loom_MongoDB::publish() {
FUNCTION_START;
char jsonString[MAX_JSON_SIZE];
if (moduleInitialized) {
// TIMER_DISABLE;
if (strlen(projectServer) > 0)
// Formulate a topic to publish on with the format
// "ProjectName/DatabaseName/DeviceNameInstanceNumber" eg. WeatherChimes/Chimes/Chime1
snprintf_P(topic, MAX_TOPIC_LENGTH, PSTR("%s/%s/%s%i"), projectServer, database_name,
manInst->get_device_name(), manInst->get_instance_num());
else
// Formulate a topic to publish on with the format
// "DatabaseName/DeviceNameInstanceNumber" eg. WeatherChimes/Chime1
snprintf_P(topic, MAX_TOPIC_LENGTH, PSTR("%s/%s%i"), database_name,
manInst->get_device_name(), manInst->get_instance_num());
/* Attempt to connect to the broker if it fails we should just return */
if (!connectToBroker()) {
FUNCTION_END;
return false;
}
/* Attempt to publish the data to the given topic */
manInst->getJSONString(jsonString);
if (!publishMessage(topic, jsonString)) {
FUNCTION_END;
return false;
}
} else {
WARNING(F("Module not initialized! If using credentials from SD make sure they are loaded "
"first."));
FUNCTION_END;
return false;
}
FUNCTION_END;
// TIMER_ENABLE;
return true;
}
//////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////
bool Loom_MongoDB::publishMetadata(char *metadata) {
FUNCTION_START;
if (moduleInitialized) {
char jsonString[MAX_JSON_SIZE];
// TIMER_DISABLE;
if (strlen(projectServer) > 0)
// Formulate a topic to publish on with the format
// "ProjectName/DatabaseName/DeviceNameInstanceNumber" eg. WeatherChimes/Chimes/Chime1
snprintf_P(topic, MAX_TOPIC_LENGTH, PSTR("%s/%s/%s%i"), projectServer, database_name,
manInst->get_device_name(), manInst->get_instance_num());
else
// Formulate a topic to publish on with the format
// "DatabaseName/DeviceNameInstanceNumber" eg. WeatherChimes/Chime1
snprintf_P(topic, MAX_TOPIC_LENGTH, PSTR("%s/%s%i"), database_name,
manInst->get_device_name(), manInst->get_instance_num());
/* Attempt to connect to the broker if it fails we should just return */
if (!connectToBroker()) {
FUNCTION_END;
return false;
}
LOG(F("Attempting to publish metadata!"));
/* Attempt to publish the data to the given topic */
if (!publishMessage(topic, metadata)) {
FUNCTION_END;
return false;
}
} else {
WARNING(F("Module not initialized! If using credentials from SD make sure they are loaded "
"first."));
FUNCTION_END;
return false;
}
FUNCTION_END;
// TIMER_ENABLE;
return true;
}
//////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////
bool Loom_MongoDB::publish(Loom_BatchSD &batchSD) {
FUNCTION_START;
char output[OUTPUT_SIZE];
if (Loom_Analog::getBatteryVoltage() < 3.4) {
WARNING(F("Module not initialized! Battery doesn't have enough power."));
FUNCTION_END;
return false;
}
char line[MAX_JSON_SIZE] = {};
int packetNumber = 0;
int index = 0;
bool lineOverflow = false;
if (moduleInitialized) {
// TIMER_DISABLE;
if (batchSD.shouldPublish()) {
if (strlen(projectServer) > 0)
// Formulate a topic to publish on with the format
// "ProjectName/DatabaseName/DeviceNameInstanceNumber" eg.
// WeatherChimes/Chimes/Chime1
snprintf_P(topic, MAX_TOPIC_LENGTH, PSTR("%s/%s%i"), database_name,
manInst->get_device_name(), manInst->get_instance_num());
else
// Formulate a topic to publish on with the format
// "DatabaseName/DeviceNameInstanceNumber" eg. WeatherChimes/Chime1
snprintf_P(topic, MAX_TOPIC_LENGTH, PSTR("%s/%s%i"), database_name,
manInst->get_device_name(), manInst->get_instance_num());
/* Attempt to connect to the broker */
if (!connectToBroker())
return false;
/* Get the file containing our batch of data */
File fileOutput = batchSD.getBatch();
bool allDataSuccess = true;
auto publishCurrentLine = [&]() {
packetNumber++;
if (lineOverflow) {
snprintf_P(output, OUTPUT_SIZE,
PSTR("Dropped oversized packet #%i (len >= %i bytes)"), packetNumber,
MAX_JSON_SIZE);
WARNING(output);
allDataSuccess = false;
lineOverflow = false;
index = 0;
line[0] = '\0';
return;
}
if (index <= 0) {
line[0] = '\0';
return;
}
// Ensure null-termination before publish
line[index] = '\0';
snprintf_P(output, OUTPUT_SIZE, PSTR("Publishing Packet %i of %i with len=%d"),
packetNumber, batchSD.getBatchSize(), index);
LOG(output);
if (!publishMessage(topic, line)) {
snprintf_P(output, OUTPUT_SIZE, PSTR("Failed to publish packet #%i"),
packetNumber);
WARNING(output);
allDataSuccess = false;
}
delay(500);
index = 0;
line[0] = '\0';
};
/* Utilize a stream so it doesn't matter how much data we have as its read in one by one
*/
while (fileOutput.available()) {
int readValue = fileOutput.read();
if (readValue < 0) {
WARNING(F("Failed to read from batch file."));
allDataSuccess = false;
break;
}
char c = (char)readValue;
/* Attempt to reconnect if connection has been stopped during publishMessage
* The previous packet that was lost due a stopped connected will not be
* retransmitted.
*/
if (!isConnected()) {
connectToBroker();
if (!isConnected()) {
WARNING(F("Connection lost during batch publish."));
allDataSuccess = false;
break;
}
}
// Handle both CR and LF line endings.
if (c == '\r' || c == '\n') {
// Ignore empty lines and LF from CRLF pairs.
if (index > 0 || lineOverflow) {
publishCurrentLine();
}
continue;
}
// Add data while leaving room for null terminator.
if (index < (MAX_JSON_SIZE - 1)) {
line[index] = c;
index++;
} else {
lineOverflow = true;
}
}
// Flush trailing data if file does not end in CR/LF.
if (index > 0 || lineOverflow) {
publishCurrentLine();
}
fileOutput.close();
// Check if we actually sent all the data successfully
if (allDataSuccess)
LOG(F("Data has been successfully sent!"));
else {
WARNING(F("1 or more packets failed to send!"));
FUNCTION_END;
return false;
}
} else {
snprintf_P(output, OUTPUT_SIZE, PSTR("Batch not ready to publish: %i/%i"),
batchSD.getCurrentBatch(), batchSD.getBatchSize());
LOG(output);
FUNCTION_END;
return false;
}
} else {
WARNING(F("Module not initialized! If using credentials from SD make sure they are loaded "
"first."));
FUNCTION_END;
return false;
}
FUNCTION_END;
// TIMER_ENABLE;
return true;
}
//////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////
void Loom_MongoDB::loadConfigFromJSON(char *json) {
FUNCTION_START;
char output[OUTPUT_SIZE];
char topic[MAX_TOPIC_LENGTH];
// Doc to store the JSON data from the SD card in
StaticJsonDocument<300> doc;
DeserializationError deserialError = deserializeJson(doc, (const char *)json);
// Check if an error occurred and if so print it
if (deserialError != DeserializationError::Ok) {
snprintf_P(output, OUTPUT_SIZE,
PSTR("There was an error reading the MQTT credentials from SD: %s"),
deserialError.c_str());
ERROR(output);
}
// Clear the strings and set port = 0
memset(address, '\0', 100);
memset(database_name, '\0', 100);
memset(username, '\0', 100);
memset(password, '\0', 100);
port = 0;
/* We should check if any parameter is null */
if (!doc["broker"].isNull())
strncpy(address, doc["broker"].as<const char *>(), 100);
if (!doc["database"].isNull())
strncpy(database_name, doc["database"].as<const char *>(), 100);
if (!doc["username"].isNull())
strncpy(username, doc["username"].as<const char *>(), 100);
if (!doc["password"].isNull())
strncpy(password, doc["password"].as<const char *>(), 100);
if (!doc["project"].isNull())
strncpy(projectServer, doc["project"].as<const char *>(), 100);
if (!doc["port"].isNull())
port = doc["port"].as<int>();
if (strlen(projectServer) > 0) {
// Formulate a topic to publish on with the format
// "ProjectName/DatabaseName/DeviceNameInstanceNumber" eg. WeatherChimes/Chimes/Chime1
snprintf_P(topic, MAX_TOPIC_LENGTH, PSTR("%s/%s/%s%i"), projectServer, database_name,
manInst->get_device_name(), manInst->get_instance_num());
} else {
// Formulate a topic to publish on with the format "DatabaseName/DeviceNameInstanceNumber"
// eg. WeatherChimes/Chime1
snprintf_P(topic, MAX_TOPIC_LENGTH, PSTR("%s/%s%i"), database_name,
manInst->get_device_name(), manInst->get_instance_num());
}
moduleInitialized = true;
free(json);
FUNCTION_END;
}
//////////////////////////////////////////////////////////////////////////////////////////////////////