-
Notifications
You must be signed in to change notification settings - Fork 0
/
SlicingDice.cpp
100 lines (86 loc) · 2.76 KB
/
SlicingDice.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
#include "SlicingDice.h"
SlicingDice::SlicingDice(String apiUserKey, boolean useProduction, const char* customHost, int customPort) {
construct(apiUserKey, customHost, customPort, useProduction);
}
void SlicingDice::construct(String apiUserKey, const char* customHost, int customPort, boolean production) {
host = customHost;
port = customPort;
apiKey = apiUserKey;
useProduction = production;
}
/* Insert data on Slicing Dice API
*
* query - the query to send to Slicing Dice API
*/
void SlicingDice::insert(JsonObject& query) {
char queryConverted[query.measureLength() + 1];
query.printTo(queryConverted, sizeof(queryConverted));
makeRequest(queryConverted);
}
/* Make a HTTP request to Slicing Dice API
*
* query - the query to send to Slicing Dice API
*/
void SlicingDice::makeRequest(const char* query){
client.connect(host, port);
while (!client.connected()) {
client.connect(host, port);
}
String testEndPoint = String("");
if (!useProduction) {
testEndPoint = String("test/");
}
client.println("POST /v1/" + testEndPoint + "insert HTTP/1.1");
client.println(F("Content-Type: application/json"));
String hostString = String(host);
client.println("Host: " + hostString);
client.println("Authorization: " + apiKey);
client.println(F("Connection: close"));
String actualLength = String(strlen(query));
client.println("Content-Length: " + actualLength);
client.println();
client.println(query);
readResponse();
client.stop();
}
//Read response from HTTP request to Slicing Dice API
void SlicingDice::readResponse(){
response = " ";
boolean currentLineIsBlank = true;
boolean hasBody = false;
boolean inStatus = false;
char statusCodeRequest[4];
int i = 0;
while (client.connected()){
if (client.available()) {
char c = client.read();
// Set status code request
if(c == ' ' && !inStatus){
inStatus = true;
}
if(inStatus && i < 3 && c != ' '){
statusCodeRequest[i] = c;
i++;
}
if(i == 3){
statusCodeRequest[i] = '\0';
statusCode = atoi(statusCodeRequest);
}
// Set response request
if(hasBody){
if(response != NULL) response.concat(c);
} else {
if (c == '\n' && currentLineIsBlank) {
hasBody = true;
}
else if (c == '\n') {
currentLineIsBlank = true;
}
else if (c != '\r') {
currentLineIsBlank = false;
}
}
}
}
response.trim();
}