-
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathDBAPI.cpp
339 lines (316 loc) · 9.73 KB
/
DBAPI.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
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
#include "DBAPI.h"
#include <WiFiClientSecure.h>
#include <ArduinoJson.h>
#ifdef DEBUG_ESP_PORT
#define DB_DEBUG_MSG(...) DEBUG_ESP_PORT.printf( __VA_ARGS__ )
#else
#define DB_DEBUG_MSG(...)
#endif
DBAPI::DBAPI() {
}
DBstation* DBAPI::getStation(
const char* name,
const char* address,
uint8_t num
) {
while (stations != NULL) {
DBstation* next = stations->next;
free(stations);
stations = next;
}
/*
bool isStation;
if (name != NULL) {
isStation = true;
} else if (address != NULL) {
isStation = false;
} else {
return NULL;
}
*/
WiFiClientSecure client;
client.setInsecure(); // Don't check fingerprint
if (!client.connect(host, 443)) {
DB_DEBUG_MSG("DBAPI: Connection to Host failed.\n");
return NULL;
}
String json = String("{\"locationTypes\":[\"ST\"],\"searchTerm\":\"") + name + "\"}";
client.print(String("POST /mob/location/search HTTP/1.1\r\nConnection: close\r\nX-Correlation-ID: Arduino\r\nContent-Type: application/x.db.vendo.mob.location.v3+json\r\nAccept: application/x.db.vendo.mob.location.v3+json\r\nHost: ") + host +
"\r\nContent-Length: " + json.length() + "\r\n\r\n" +
json
);
char endOfHeaders[] = "\r\n\r\n";
if (!client.find(endOfHeaders)) {
DB_DEBUG_MSG("Did not find headers\n");
return stations;
}
JsonDocument doc;
DeserializationError error = deserializeJson(doc, client);
if (error) {
DB_DEBUG_MSG("deserializeJson() on Station failed");
DB_DEBUG_MSG(error.c_str());
return stations;
}
DBstation* prev = NULL;
for (uint8_t i = 0; i < doc.size(); i++) {
DBstation* station = new DBstation();
JsonObject st = doc[i];
String stationname = st["name"];
switch (repum) {
case REP_AGFX:
stationname.replace("ß", "\xE0");
stationname.replace("Ä", "\x8E");
stationname.replace("Ö", "\x99");
stationname.replace("Ü", "\x9A");
stationname.replace("ä", "\x84");
stationname.replace("ö", "\x94");
stationname.replace("ü", "\x81");
break;
case REP_UML:
stationname.replace("ß", "ss");
stationname.replace("Ä", "Ae");
stationname.replace("Ö", "Oe");
stationname.replace("Ü", "Ue");
stationname.replace("ä", "ae");
stationname.replace("ö", "oe");
stationname.replace("ü", "ue");
break;
default:
break;
}
strncpy(station->name, stationname.c_str(), sizeof(station->name));
strncpy(station->stationId, st["locationId"], sizeof(station->stationId));
station->longitude = st["coordinates"]["longitude"];
station->latitude = st["coordinates"]["latitude"];
station->next = NULL;
if (prev == NULL) { // First element
stations = station;
} else {
prev->next = station;
}
prev = station;
}
return stations;
}
DBstation* DBAPI::getStationByCoord(
uint32_t latitude,
uint32_t longitude,
uint8_t num,
uint16_t maxDistance
) {
return NULL;
}
DBdeparr* DBAPI::getStationBoard(
const char type[8],
const char* stationId,
const char* target,
time_t time,
uint8_t maxCount,
uint8_t maxDuration,
uint16_t productFilter
) {
while (deparr != NULL) {
DBdeparr* next = deparr->next;
free(deparr);
deparr = next;
}
bool abfahrt = strcmp(type, "abfahrt") == 0;
DBdeparr* prev = NULL;
uint8_t cnt = 0;
// Set static request parameters
JsonDocument reqDoc;
JsonArray verkehrsmittel = reqDoc["verkehrsmittel"].to<JsonArray>();
for (uint8_t i = 0; i < 10; i++) {
if (productFilter & (1 << (9 - i))) {
verkehrsmittel.add(services[i]);
}
}
reqDoc["ursprungsBahnhofId"] = stationId;
for (uint8_t offset = 0; offset < maxDuration; offset++) {
// Get current time, if requesting more than one hour and no request time is set
// Sanity check, that year is > 2020, so only successful synced time is used
// Your device would probably not survive 2020 years without restart, huh?
if (time == 0 && maxDuration > 1 && year() > 2020) {
time = now();
}
// Set params
if (time != 0) {
// Nobody knows, what happens at DST switch... ¯\_(ツ)_/¯
char buf[11];
// Setting the time offset - this might generate duplicates.
// Train would have departed in queried hour but has delay of 70 min:
// Will now be shown in the currently queried hour as the regular time matches.
// But also in the next hour, because it will be reachable due to the delay.
uint32_t tr = time + offset * 3600;
snprintf(buf, 11, "%02d:%02d", hour(tr), minute(tr));
reqDoc["anfragezeit"] = buf;
snprintf(buf, 11, "%4d-%02d-%02d", year(tr), month(tr), day(tr));
reqDoc["datum"] = buf;
}
size_t outputCapacity = 350;
char* output = (char*)calloc(outputCapacity, sizeof(char));
serializeJson(reqDoc, output, outputCapacity);
// Init new client for each request
WiFiClientSecure client;
client.setInsecure(); // Don't check fingerprint
if (!client.connect(host, 443)) {
DB_DEBUG_MSG("DBAPI: Connection to Host failed.\n");
free(output);
return NULL;
}
DB_DEBUG_MSG("DBAPI: Requesting StationBoard.\n");
DB_DEBUG_MSG(output);
client.print(String("POST /mob/bahnhofstafel/") + type + " HTTP/1.1\r\n" +
"Host: " + host + "\r\n" +
"Content-Type: application/x.db.vendo.mob.bahnhofstafeln.v2+json\r\n" +
"Accept: application/x.db.vendo.mob.bahnhofstafeln.v2+json\r\n" +
"X-Correlation-ID: Arduino\r\n" +
"Content-Length: " + strlen(output) + "\r\n" +
"Connection: close\r\n\r\n" + output);
free(output);
char endOfHeaders[] = "\r\n\r\n";
if (!client.find(endOfHeaders)) {
DB_DEBUG_MSG("Did not find headers\n");
return deparr;
}
JsonDocument doc;
client.find(":["); // Skip to first element
do {
DeserializationError error = deserializeJson(doc, client);
if (error) {
DB_DEBUG_MSG("deserializeJson() on departures/arrivals failed");
DB_DEBUG_MSG(error.c_str());
return deparr;
}
DBdeparr* da = new DBdeparr();
String targ = doc[abfahrt?"richtung":"abgangsOrt"];
switch (repum) {
case REP_AGFX:
targ.replace("ß", "\xE0");
targ.replace("Ä", "\x8E");
targ.replace("Ö", "\x99");
targ.replace("Ü", "\x9A");
targ.replace("ä", "\x84");
targ.replace("ö", "\x94");
targ.replace("ü", "\x81");
break;
case REP_UML:
targ.replace("ß", "ss");
targ.replace("Ä", "Ae");
targ.replace("Ö", "Oe");
targ.replace("Ü", "Ue");
targ.replace("ä", "ae");
targ.replace("ö", "oe");
targ.replace("ü", "ue");
break;
default:
break;
}
targ.toCharArray(da->target, sizeof(DBdeparr::target));
strncpy(da->product, doc["kurztext"], sizeof(DBdeparr::product));
//strncpy(da->product, doc["produktGattung"], sizeof(DBdeparr::product));
strncpy(da->textline, doc["mitteltext"], sizeof(DBdeparr::textline));
for (uint8_t i = 0; i < strlen(da->textline); i++) {
if (da->textline[i] >= '0' && da->textline[i] <= '9') {
strncpy(da->textline, &doc["mitteltext"].as<const char*>()[i], sizeof(DBdeparr::textline));
da->line = atol(da->textline);
break;
}
}
if (!doc["gleis"].isNull()) {
strncpy(da->platform, doc["gleis"], sizeof(DBdeparr::platform));
} else {
da->platform[0] = 0;
}
if (!doc["ezGleis"].isNull()) {
strncpy(da->newPlatform, doc["ezGleis"], sizeof(DBdeparr::newPlatform));
} else {
da->newPlatform[0] = 0;
}
JsonArray arr = doc["echtzeitNotizen"];
da->cancelled = false;
for (uint8_t i = 0; i < arr.size(); i++) {
if (arr[i]["text"].as<String>().equals("Halt entfällt")) {
da->cancelled = true;
break; // Not interested in other notes right now
} else {
//Serial.println(arr[i]["text"].as<String>());
}
}
da->time = this->parseTime(String(doc[abfahrt ? "abgangsDatum" : "ankunftsDatum"]));
if (doc[abfahrt ? "ezAbgangsDatum" : "ezAnkunftsDatum"].isNull()) {
da->realTime = da->time;
} else {
da->realTime = this->parseTime(String(doc[abfahrt ? "ezAbgangsDatum" : "ezAnkunftsDatum"]));
}
da->delay = da->realTime - da->time;
da->delay /= 60;
da->next = NULL;
if (prev == NULL) {
DB_DEBUG_MSG("DBAPI: Got first departure.");
deparr = da;
} else {
DB_DEBUG_MSG("DBAPI: Got next departure.");
prev->next = da;
}
prev = da;
cnt++;
} while (client.findUntil(",","]") && cnt < maxCount);
if (maxDuration > 0 && time == 0 && prev != NULL) {
// If no synced time available, set request time to last known depature - 59 minutes
time = prev->time - 3540;
}
if (year(time) < 2020) break; // Can't query more hours, as there is no valid timestamp
}
return deparr;
}
time_t DBAPI::parseTime(String t) {
tmElements_t time;
// 0123-56-89T12:45:67+90:23
// Year in timeElements is years since 1970
time.Year = atoi(t.substring(0,4).c_str()) - 1970;
time.Month = atoi(t.substring(5,7).c_str());
time.Day = atoi(t.substring(8,10).c_str());
time.Hour = atoi(t.substring(11,13).c_str());
time.Minute = atoi(t.substring(14,16).c_str());
time.Second = 0;
return makeTime(time);
}
DBdeparr* DBAPI::getDepartures(
const char* stationId,
const char* target,
time_t time,
uint8_t maxCount,
uint8_t maxDuration,
uint16_t productFilter
) {
return getStationBoard("abfahrt", stationId, target, time, maxCount, maxDuration, productFilter);
}
DBdeparr* DBAPI::getArrivals(
const char* stationId,
const char* target,
time_t time,
uint8_t maxCount,
uint8_t maxDuration,
uint16_t productFilter
) {
return getStationBoard("ankunft", stationId, target, time, maxCount, maxDuration, productFilter);
}
void DBAPI::setAGFXOutput(bool gfx) {
repum = gfx ? REP_AGFX : REP_UML;
}
void DBAPI::setUmlaut(enum DBumlaut uml) {
repum = uml;
}
const char* DBAPI::services[] = {
"HOCHGESCHWINDIGKEITSZUEGE",
"INTERCITYUNDEUROCITYZUEGE",
"INTERREGIOUNDSCHNELLZUEGE",
"NAHVERKEHRSONSTIGEZUEGE",
"SBAHNEN",
"BUSSE",
"SCHIFFE",
"UBAHN",
"STRASSENBAHN",
"ANRUFPFLICHTIGEVERKEHRE"
};