-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
api.cpp
246 lines (206 loc) · 6.35 KB
/
api.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
/* noisemeter-device - Firmware for CivicTechTO's Noisemeter Device
* Copyright (C) 2024 Clyne Sullivan
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#include "api.h"
#include "board.h"
#include "certs.h"
#include "url-encode.h"
#include <HTTPClient.h>
#include <WiFiClientSecure.h>
#include <cmath>
API::Request::Request(const char endpoint[])
{
url.reserve(128);
url.concat(Base);
url.concat(endpoint);
params.reserve(128);
}
API::Request& API::Request::addParam(const char param[], String value)
{
params.concat('&');
params.concat(param);
params.concat('=');
params.concat(urlEncode(value));
return *this;
}
std::optional<JsonDocument> API::sendAuthorizedRequest(const API::Request& req)
{
WiFiClientSecure client;
client.setCACert(rootCertificate());
#ifdef API_VERBOSE
SERIAL.print("[api] Authorized request: ");
SERIAL.println(req.url);
#endif
HTTPClient https;
if (https.begin(client, req.url)) {
https.addHeader("Content-Type", "application/x-www-form-urlencoded");
https.addHeader("Authorization", String("Token ") + token);
return sendHttpPOST(https, req.params.substring(1));
#ifdef API_VERBOSE
} else {
SERIAL.println("[api] Failed to https.begin()");
#endif
}
return {};
}
std::optional<JsonDocument> API::sendNonauthorizedRequest(const API::Request& req)
{
WiFiClientSecure client;
client.setCACert(rootCertificate());
#ifdef API_VERBOSE
SERIAL.print("[api] Non-authorized request: ");
SERIAL.println(req.url);
#endif
HTTPClient https;
if (https.begin(client, req.url)) {
https.addHeader("Content-Type", "application/x-www-form-urlencoded");
return sendHttpPOST(https, req.params.substring(1));
#ifdef API_VERBOSE
} else {
SERIAL.println("[api] Failed to https.begin()");
#endif
}
return {};
}
std::optional<JsonDocument> API::sendHttpGET(HTTPClient& https)
{
const auto code = https.GET();
if (code == HTTP_CODE_OK || code == HTTP_CODE_MOVED_PERMANENTLY) {
return handleHttpResponse(https);
#ifdef API_VERBOSE
} else {
SERIAL.print("[api] HTTP error: ");
SERIAL.println(code);
#endif
}
return {};
}
std::optional<JsonDocument> API::sendHttpPOST(HTTPClient& https, const String& payload)
{
#ifdef API_VERBOSE
SERIAL.print("[api] payload: ");
SERIAL.println(payload);
#endif
const auto code = https.POST(payload);
if (code == HTTP_CODE_OK || code == HTTP_CODE_MOVED_PERMANENTLY) {
return handleHttpResponse(https);
#ifdef API_VERBOSE
} else {
SERIAL.print("[api] HTTP error: ");
SERIAL.println(code);
#endif
}
return {};
}
std::optional<JsonDocument> API::handleHttpResponse(HTTPClient& https)
{
const auto response = https.getString();
const auto json = responseToJson(response);
https.end();
if (json) {
#ifdef API_VERBOSE
SERIAL.print("[api] ");
SERIAL.print((String)(*json)["result"]);
SERIAL.print(": ");
SERIAL.println((String)(*json)["message"]);
#endif
return *json;
#ifdef API_VERBOSE
} else {
SERIAL.print("[api] Invalid JSON!");
#endif
}
return {};
}
std::optional<JsonDocument> API::responseToJson(const String& response)
{
JsonDocument doc;
const auto error = deserializeJson(doc, response);
if (error) {
SERIAL.println(error.f_str());
return {};
} else {
return doc;
}
}
API::API(UUID id_, String token_):
id(id_), token(token_) {}
bool API::sendMeasurement(const DataPacket& packet)
{
const auto request = Request("measurement")
.addParam("device", id)
.addParam("timestamp", packet.timestamp)
.addParam("min", String(std::lround(packet.minimum)))
.addParam("max", String(std::lround(packet.maximum)))
.addParam("mean", String(std::lround(packet.average)));
const auto resp = sendAuthorizedRequest(request);
return resp && (*resp)["result"] == "ok";
}
bool API::sendMeasurementWithDiagnostics(const DataPacket& packet, String version, String boottime)
{
const auto request = Request("measurement")
.addParam("device", id)
.addParam("timestamp", packet.timestamp)
.addParam("min", String(std::lround(packet.minimum)))
.addParam("max", String(std::lround(packet.maximum)))
.addParam("mean", String(std::lround(packet.average)))
.addParam("version", version)
.addParam("boottime", boottime);
const auto resp = sendAuthorizedRequest(request);
return resp && (*resp)["result"] == "ok";
}
std::optional<String> API::sendRegister(String email)
{
const auto request = Request("device/register")
.addParam("device", id)
.addParam("email", email);
const auto resp = sendNonauthorizedRequest(request);
if (resp && (*resp)["result"] == "ok")
return (*resp)["token"];
else
return {};
}
std::optional<API::LatestSoftware> API::getLatestSoftware()
{
const auto request = Request("software/latest");
WiFiClientSecure client;
client.setCACert(rootCertificate());
String endpoint = request.url + '?' + request.params.substring(1);
#ifdef API_VERBOSE
SERIAL.print("[api] Non-authorized request: ");
SERIAL.println(endpoint);
#endif
HTTPClient https;
if (https.begin(client, endpoint)) {
const auto resp = sendHttpGET(https);
if (resp && (*resp)["result"] == "ok") {
LatestSoftware ls = {
(*resp)["version"],
(*resp)["url"]
};
return ls;
}
#ifdef API_VERBOSE
} else {
SERIAL.println("[api] Failed to https.begin()");
#endif
}
return {};
}
const char *API::rootCertificate()
{
return cert_ISRG_Root_X1;
}