-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
dataverse.cpp
320 lines (268 loc) · 11.9 KB
/
dataverse.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
/*
Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0)
2022 Miguel Tomas
https://creativecommons.org/licenses/by-nc-sa/4.0/legalcode
You are free to:
Share — copy and redistribute the material in any medium or format
Adapt — remix, transform, and build upon the material
The licensor cannot revoke these freedoms as long as you follow the license terms.
Under the following terms:
Attribution — You must give appropriate credit, provide a link to the license, and indicate if
changes were made.You may do so in any reasonable manner, but not in any way that
suggests the licensor endorses you or your use.
NonCommercial — You may not use the material for commercial purposes.
ShareAlike — If you remix, transform, or build upon the material, you must distribute your contributions
under the same license as the original.
No additional restrictions — You may not apply legal terms or technological measures that legally restrict
others from doing anything the license permits.
*/
#include "Dataverse.h"
/*! @brief Constructor for Dataverse */
Dataverse::Dataverse(){}
// *********************************************************
// Upload a file to a Dataset on a Dataverse
// *********************************************************
void Dataverse::UploadToDataverse(byte counter) {
Dataverse::UploadToDataverse(0);
}
// *********************************************************
void Dataverse::UploadToDataverse(byte counter) {
if(counter> THIS->MAX_ATTEMPT_REQUESTS)
return;
//Check WiFi connection status
if(WiFi.status() != WL_CONNECTED){
mserial.printStrln("WiFi Disconnected");
if (connect2WIFInetowrk()){
UploadToDataverse(counter+1);
}
}
bool uploadStatusNotOK=true;
if(datasetInfoJson["data"].containsKey("id")){
if(datasetInfoJson["data"]["id"] !=""){
String rawResponse = GetInfoFromDataverse("/api/datasets/"+ datasetInfoJson["data"]["id"] +"/locks");
const size_t capacity =2*rawResponse.length() + JSON_ARRAY_SIZE(1) + 7*JSON_OBJECT_SIZE(1);
DynamicJsonDocument datasetLocksJson(capacity);
// Parse JSON object
DeserializationError error = deserializeJson(datasetLocksJson, rawResponse);
if (error) {
mserial.printStr("unable to retrive dataset lock status. Upload not possible. ERR: "+error.f_str());
//mserial.printStrln(rawResponse);
return;
}else{
String stat = datasetInfoJson["status"];
if(datasetInfoJson.containsKey("lockType")){
String locktype = datasetInfoJson["data"]["lockType"];
mserial.printStrln("There is a Lock on the dataset: "+ locktype);
mserial.printStrln("Upload of most recent data is not possible without removal of the lock.");
// Do unlocking
}else{
mserial.printStrln("The dataset is unlocked. Upload possible.");
uploadStatusNotOK=false;
}
}
}else{
mserial.printStrln("dataset ID is empty. Upload not possible. ");
}
}else{
mserial.printStrln("dataset metadata not loaded. Upload not possible. ");
}
if(uploadStatusNotOK){
return;
}
// Open the dataset file and prepare for binary upload
File datasetFile = FFat.open("/"+EXPERIMENTAL_DATA_FILENAME, FILE_READ);
if (!datasetFile){
mserial.printStrln("Dataset file not found");
return;
}
String boundary = "7MA4YWxkTrZu0gW";
String contentType = "text/csv";
DATASET_REPOSITORY_URL = "/api/datasets/:persistentId/add?persistentId="+PERSISTENT_ID;
String datasetFileName = datasetFile.name();
String datasetFileSize = String(datasetFile.size());
mserial.printStrln("Dataset File Details:");
mserial.printStrln("Filename:" + datasetFileName);
mserial.printStrln("size (bytes): "+ datasetFileSize);
mserial.printStrln("");
int str_len = SERVER_URL.length() + 1; // Length (with one extra character for the null terminator)
char SERVER_URL_char [str_len]; // Prepare the character array (the buffer)
SERVER_URL.toCharArray(SERVER_URL_char, str_len); // Copy it over
client.stop();
client.setCACert(HARVARD_ROOT_CA_RSA_SHA1);
if (!client.connect(SERVER_URL_char, SERVER_PORT)) {
mserial.printStrln("Cloud server URL connection FAILED!");
mserial.printStrln(SERVER_URL_char);
int server_status = client.connected();
mserial.printStrln("Server status code: " + String(server_status));
return;
}
mserial.printStrln("Connected to the dataverse of Harvard University");
mserial.printStrln("");
mserial.printStr("Requesting URL: " + DATASET_REPOSITORY_URL);
// Make a HTTP request and add HTTP headers
String postHeader = "POST " + DATASET_REPOSITORY_URL + " HTTP/1.1\r\n";
postHeader += "Host: " + SERVER_URL + ":" + String(SERVER_PORT) + "\r\n";
postHeader += "X-Dataverse-key: " + API_TOKEN + "\r\n";
postHeader += "Content-Type: multipart/form-data; boundary=" + boundary + "\r\n";
postHeader += "Accept: text/html,application/xhtml+xml,application/xml,application/json;q=0.9,*/*;q=0.8\r\n";
postHeader += "Accept-Encoding: gzip,deflate\r\n";
postHeader += "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7\r\n";
postHeader += "User-Agent: AeonLabs LDAD Smart DAQ device\r\n";
postHeader += "Keep-Alive: 300\r\n";
postHeader += "Connection: keep-alive\r\n";
postHeader += "Accept-Language: en-us\r\n";
// jsonData header
String jsonData = "{\"description\":\"LIVE Experimental data upload from LDAD Smart 12bit DAQ \",\"categories\":[\"Data\"], \"restrict\":\"false\", \"tabIngest\":\"false\"}";
String jsonDataHeader = "--" + boundary + "\r\n";
jsonDataHeader += "Content-Disposition: form-data; name=\"jsonData\"\r\n\r\n";
jsonDataHeader += jsonData+"\r\n";
// dataset header
String datasetHead = "--" + boundary + "\r\n";
datasetHead += "Content-Disposition: form-data; name=\"file\"; filename=\"" + datasetFileName + "\"\r\n";
datasetHead += "Content-Type: " + contentType + "\r\n\r\n";
// request tail
String tail = "\r\n--" + boundary + "--\r\n\r\n";
// content length
int contentLength = jsonDataHeader.length() + datasetHead.length() + datasetFile.size() + tail.length();
postHeader += "Content-Length: " + String(contentLength, DEC) + "\n\n";
// send post header
int postHeader_len=postHeader.length() + 1;
char charBuf0[postHeader_len];
postHeader.toCharArray(charBuf0, postHeader_len);
client.print(charBuf0);
mserial.printStr(charBuf0);
// send key header
char charBufKey[jsonDataHeader.length() + 1];
jsonDataHeader.toCharArray(charBufKey, jsonDataHeader.length() + 1);
client.print(charBufKey);
mserial.printStr(charBufKey);
// send request buffer
char charBuf1[datasetHead.length() + 1];
datasetHead.toCharArray(charBuf1, datasetHead.length() + 1);
client.print(charBuf1);
mserial.printStr(charBuf1);
// create buffer
const int bufSize = 2048;
byte clientBuf[bufSize];
int clientCount = 0;
while (datasetFile.available()) {
clientBuf[clientCount] = datasetFile.read();
clientCount++;
if (clientCount > (bufSize - 1)) {
client.write((const uint8_t *)clientBuf, bufSize);
clientCount = 0;
}
}
datasetFile.close();
if (clientCount > 0) {
client.write((const uint8_t *)clientBuf, clientCount);
mserial.printStrln("[binary data]");
}
// send tail
char charBuf3[tail.length() + 1];
tail.toCharArray(charBuf3, tail.length() + 1);
client.print(charBuf3);
mserial.printStr(charBuf3);
// Read all the lines on reply back from server and print them to mserial
mserial.printStrln("");
mserial.printStrln("Response Headers:");
String responseHeaders = "";
while (client.connected()) {
// mserial.printStrln("while client connected");
responseHeaders = client.readStringUntil('\n');
mserial.printStrln(responseHeaders);
if (responseHeaders == "\r") {
mserial.printStrln("====== end of headers ======");
break;
}
}
String responseContent = client.readStringUntil('\n');
mserial.printStrln("Harvard University's Dataverse reply was:");
mserial.printStrln("==========");
mserial.printStrln(responseContent);
mserial.printStrln("==========");
mserial.printStrln("closing connection");
client.stop();
}
// *********************************************************
// Make data request to Dataverse (GET)
// *********************************************************
void Dataverse::GetInfoFromDataverse(String url) {
Dataverse::GetInfoFromDataverse(url,0);
}
// *********************************************************
String Dataverse::GetInfoFromDataverse(String url, byte counter) {
if(counter> THIS->MAX_ATTEMPT_REQUESTS)
return;
//Check WiFi connection status
if(WiFi.status() != WL_CONNECTED){
mserial.printStrln("WiFi Disconnected");
if (connect2WIFInetowrk()){
GetInfoFromDataverse(url, counter+1);
}
}
int str_len = SERVER_URL.length() + 1; // Length (with one extra character for the null terminator)
char SERVER_URL_char [str_len]; // Prepare the character array (the buffer)
SERVER_URL.toCharArray(SERVER_URL_char, str_len); // Copy it over
client.stop();
client.setCACert(HARVARD_ROOT_CA_RSA_SHA1);
if (!client.connect(SERVER_URL_char, SERVER_PORT)) {
mserial.printStrln("Cloud server URL connection FAILED!");
mserial.printStrln(SERVER_URL_char);
int server_status = client.connected();
mserial.printStrln("Server status code: " + String(server_status));
return "";
}
mserial.printStrln("Connected to the dataverse of Harvard University");
mserial.printStrln("");
// We now create a URI for the request
mserial.printStr("Requesting URL: ");
mserial.printStrln(url);
// Make a HTTP request and add HTTP headers
// post header
String postHeader = "GET " + url + " HTTP/1.1\r\n";
postHeader += "Host: " + SERVER_URL + ":" + String(SERVER_PORT) + "\r\n";
//postHeader += "X-Dataverse-key: " + API_TOKEN + "\r\n";
postHeader += "Content-Type: text/json\r\n";
postHeader += "Accept: text/html,application/xhtml+xml,application/xml,application/json,text/json;q=0.9,*/*;q=0.8\r\n";
postHeader += "Accept-Encoding: gzip,deflate\r\n";
postHeader += "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7\r\n";
postHeader += "User-Agent: AeonLabs LDAD Smart DAQ device\r\n";
//postHeader += "Keep-Alive: 300\r\n";
postHeader += "Accept-Language: en-us\r\n";
postHeader += "Connection: close\r\n\r\n";
// request tail
String boundary = "7MA4YWxkTrZu0gW";
String tail = "\r\n--" + boundary + "--\r\n\r\n";
// content length
int contentLength = tail.length();
//postHeader += "Content-Length: " + String(contentLength, DEC) + "\n\n";
// send post header
int postHeader_len=postHeader.length() + 1;
char charBuf0[postHeader_len];
postHeader.toCharArray(charBuf0, postHeader_len);
client.print(charBuf0);
mserial.printStrln("======= Headers =======");
mserial.printStrln(charBuf0);
mserial.printStrln("======= End of Headers =======");
// Read all the lines of the reply from server and print them to mserial
String responseHeaders = "";
mserial.printStr("Waiting for server response...");
long timeout= millis();
long ttl=millis()-timeout;
while (client.connected() && abs(ttl) < HTTP_TTL) {
ttl=millis()-timeout;
responseHeaders = client.readStringUntil('\n');
if (responseHeaders == "\r") {
break;
}
}
if (abs(ttl) < 10000){
mserial.printStrln("OK");
}else{
mserial.printStrln("timed out.");
}
String responseContent = client.readStringUntil('\n');
client.stop();
return responseContent;
}