Repository navigation
Expand file tree
/
Copy pathnode_helper.js
More file actions
350 lines (281 loc) · 8.62 KB
/
Copy pathnode_helper.js
File metadata and controls
350 lines (281 loc) · 8.62 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
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
const NodeHelper = require("node_helper");
module.exports = NodeHelper.create({
start: function () {
},
socketNotificationReceived: function (notification, payload) {
if (notification === "GET_AUTOBAHN_DATA") {
this.getData(payload);
}
},
getData: async function (payload) {
const roads = payload?.config?.roads || [];
const roadData = [];
const seen = new Set();
let successfulRequests = 0;
for (const roadObject of roads) {
try {
const data =
await this.fetchWarningsWithEmptyRetry(
roadObject.road
);
successfulRequests++;
for (const warning of data.warning) {
warning.road = roadObject.road;
if (!this.warningMatchesFilter(warning, roadObject)) {
continue;
}
const id =
warning.identifier ||
`${warning.road}-${warning.title}-${warning.startTimestamp}`;
if (seen.has(id)) {
continue;
}
seen.add(id);
roadData.push(warning);
}
} catch (error) {
console.error(
`[MMM-Autobahn] Failed to fetch ${roadObject.road}:`,
error.message
);
}
}
if (roads.length > 0 && successfulRequests === 0) {
this.sendSocketNotification(
"AUTOBAHN_DATA_ERROR",
{
message: "Could not retrieve traffic data."
}
);
return;
}
this.sendSocketNotification(
"AUTOBAHN_DATA",
roadData
);
},
fetchWarningsWithEmptyRetry: async function (road) {
const warningUrl =
`https://verkehr.autobahn.de/o/autobahn/${road}/services/warning`;
const retryDelays = [
0,
2000
];
for (let attempt = 0; attempt < retryDelays.length; attempt++) {
if (retryDelays[attempt] > 0) {
console.log(
`[MMM-Autobahn] ${road}: empty API response, retrying`
);
await new Promise(resolve =>
setTimeout(
resolve,
retryDelays[attempt]
)
);
}
const response = await fetch(warningUrl, {
signal: AbortSignal.timeout(60000)
});
if (!response.ok) {
throw new Error(
`HTTP ${response.status} for ${road}`
);
}
const data = await response.json();
if (!data || !Array.isArray(data.warning)) {
throw new Error(
`Invalid API response for ${road}`
);
}
if (data.warning.length > 0) {
return data;
}
if (attempt === retryDelays.length - 1) {
return data;
}
}
},
warningMatchesFilter: function (warning, roadObject) {
/*
* Preferred filter:
* route polyline + configurable corridor.
*/
if (
Array.isArray(roadObject.route) &&
roadObject.route.length >= 2
) {
return this.warningMatchesRoute(
warning,
roadObject
);
}
/*
* Backwards-compatible legacy filter.
*/
const from = Number(roadObject.from);
const to = Number(roadObject.to);
if (
Number.isFinite(from) &&
Number.isFinite(to)
) {
return this.warningMatchesLegacyRange(
warning,
from,
to
);
}
/*
* No filter:
* display all warnings for this road.
*/
return true;
},
warningMatchesLegacyRange: function (warning, from, to) {
/*
* Remove the Autobahn number itself before looking
* for possible junction numbers.
*/
const title = String(warning?.title || "")
.replace(/^\s*A\d+\s*\|\s*/i, "");
const matches = title.match(/\d+/g) || [];
/*
* Current API titles frequently contain no junction
* numbers at all. In that case there is no reliable
* legacy value to filter by.
*/
if (matches.length === 0) {
return true;
}
const min = Math.min(from, to);
const max = Math.max(from, to);
return matches.some(value => {
const number = Number(value);
return (
Number.isFinite(number) &&
number >= min &&
number <= max
);
});
},
warningMatchesRoute: function (warning, roadObject) {
const route = roadObject.route;
const corridorKm =
Number.isFinite(Number(roadObject.corridorKm))
? Number(roadObject.corridorKm)
: 4;
const warningPoints =
this.getWarningPoints(warning);
if (warningPoints.length === 0) {
return false;
}
for (const warningPoint of warningPoints) {
for (let i = 0; i < route.length - 1; i++) {
const distance =
this.distancePointToSegmentKm(
warningPoint,
route[i],
route[i + 1]
);
if (distance <= corridorKm) {
return true;
}
}
}
return false;
},
getWarningPoints: function (warning) {
/*
* GeoJSON LineString:
* [longitude, latitude]
*/
if (
warning?.geometry?.type === "LineString" &&
Array.isArray(warning.geometry.coordinates)
) {
return warning.geometry.coordinates
.filter(point =>
Array.isArray(point) &&
point.length >= 2 &&
Number.isFinite(Number(point[0])) &&
Number.isFinite(Number(point[1]))
)
.map(point => ({
lat: Number(point[1]),
long: Number(point[0])
}));
}
/*
* Fallback if no LineString geometry is available.
*/
if (
warning?.coordinate &&
Number.isFinite(Number(warning.coordinate.lat)) &&
Number.isFinite(Number(warning.coordinate.long))
) {
return [{
lat: Number(warning.coordinate.lat),
long: Number(warning.coordinate.long)
}];
}
return [];
},
distancePointToSegmentKm: function (point, start, end) {
const earthRadiusKm = 6371;
const latRef =
(
Number(point.lat) +
Number(start.lat) +
Number(end.lat)
) / 3;
const latRefRad =
this.toRadians(latRef);
/*
* Local equirectangular projection.
*/
const project = p => ({
x:
earthRadiusKm *
this.toRadians(Number(p.long)) *
Math.cos(latRefRad),
y:
earthRadiusKm *
this.toRadians(Number(p.lat))
});
const p = project(point);
const a = project(start);
const b = project(end);
const abX = b.x - a.x;
const abY = b.y - a.y;
const apX = p.x - a.x;
const apY = p.y - a.y;
const abLengthSquared =
abX * abX +
abY * abY;
if (abLengthSquared === 0) {
return Math.hypot(
p.x - a.x,
p.y - a.y
);
}
let t =
(
apX * abX +
apY * abY
) /
abLengthSquared;
t = Math.max(0, Math.min(1, t));
const nearestX =
a.x +
t * abX;
const nearestY =
a.y +
t * abY;
return Math.hypot(
p.x - nearestX,
p.y - nearestY
);
},
toRadians: function (value) {
return value * Math.PI / 180;
}
});