forked from tbouron/MMM-FlightTracker
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnode_helper.js
More file actions
308 lines (267 loc) · 12.4 KB
/
node_helper.js
File metadata and controls
308 lines (267 loc) · 12.4 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
const NodeHelper = require('node_helper');
const Adsb = require('./lib/adsb');
const { parse } = require('csv-parse');
const fs = require('fs');
const path = require('path');
module.exports = NodeHelper.create({
airlines: [],
aircrafts: [],
clients: [],
isConnected: null,
adsb: null,
init: function() {
this.adsb = new Adsb();
this._loadDatabases();
},
_loadDatabases: function() {
// Load CSV databases for network/SBS1 mode (tar1090 mode doesn't need these)
const airlineParser = parse({
delimiter: ',',
columns: ['id', 'name', 'alias', 'iata', 'icao', 'callsign', 'country', 'active']
});
const aircraftsParser = parse({
delimiter: ',',
columns: ['icao', 'regid', 'mdl', 'type', 'operator']
});
const airlinesPath = path.join(__dirname, 'data', 'airlines.csv');
const aircraftsPath = path.join(__dirname, 'data', 'aircrafts.csv');
if (fs.existsSync(airlinesPath)) {
fs.createReadStream(airlinesPath)
.pipe(airlineParser)
.on('error', err => console.error('Airlines DB error:', err))
.on('data', row => {
Object.keys(row).forEach(key => {
if (row[key] === '\\N') row[key] = null;
});
row.id = Number.parseInt(row.id, 10);
row.active = row.active === 'Y';
this.airlines.push(row);
})
.on('end', () => console.log('Airlines DB loaded'));
}
if (fs.existsSync(aircraftsPath)) {
fs.createReadStream(aircraftsPath)
.pipe(aircraftsParser)
.on('error', err => console.error('Aircrafts DB error:', err))
.on('data', row => {
Object.keys(row).forEach(key => {
if (row[key] === '') row[key] = null;
});
this.aircrafts.push(row);
})
.on('end', () => console.log('Aircrafts DB loaded'));
}
},
stop: function() {
console.log('Closing down ADS-B client ...');
this.adsb.stop();
},
socketNotificationReceived: function(id, payload) {
if (id === 'START_TRACKING') {
this.startTracking(payload);
}
if (id === 'GET_IS_CONNECTED') {
this.sendSocketNotification('SET_IS_CONNECTED', this.isConnected);
}
if (id === 'GET_AIRCRAFTS') {
this.trackAircrafts(payload);
}
},
startTracking: function(config) {
if (this.clients.includes(JSON.stringify(config.client))) {
console.log('An instance of ADS-B client with the same configuration already exists. Skipping ...');
this.isConnected = true;
return;
}
console.log('Initialising ADS-B client ...');
this.clients.push(JSON.stringify(config.client));
if (config.hasOwnProperty('orderBy') && config.orderBy.split(':').length !== 2) {
console.warn('The format of "orderBy" config is not valid, it will be ignored.');
}
try {
// Pass interval from main config to client
const clientConfig = {
...config.client,
interval: config.interval || 1
};
this.adsb.on('socket-closed', () => {
this.isConnected = null;
this.sendSocketNotification('SET_IS_CONNECTED', this.isConnected);
}).on('socket-opened', () => {
this.isConnected = true;
this.sendSocketNotification('SET_IS_CONNECTED', this.isConnected);
}).start(clientConfig);
this.isConnected = true;
} catch (e) {
console.error('Failed to initialise ADS-B client', e);
this.clients.pop();
this.isConnected = false;
}
},
trackAircrafts: function(config) {
let aircrafts;
if (this.adsb.getMode() === 'tar1090') {
// tar1090 mode - data is already enriched
aircrafts = this._getAircraftsTar1090(config);
} else {
// Network/SBS1 mode - need to enrich with CSV databases
aircrafts = this._getAircraftsNetwork(config);
}
// Apply altitude filtering
if (config.minAltitude > 0) {
aircrafts = aircrafts.filter(ac => ac.altitude && ac.altitude >= config.minAltitude);
}
if (config.maxAltitude > 0) {
aircrafts = aircrafts.filter(ac => ac.altitude && ac.altitude <= config.maxAltitude);
}
// Apply distance filtering (config is in nautical miles)
if (config.minDistance > 0 || config.maxDistance > 0) {
aircrafts = aircrafts.filter(ac => {
if (!ac.distance) return false;
// Convert to nautical miles if needed (network mode uses meters)
const distanceNm = ac.distanceUnit === 'nm' ? ac.distance : ac.distance / 1852;
if (config.minDistance > 0 && distanceNm < config.minDistance) return false;
if (config.maxDistance > 0 && distanceNm > config.maxDistance) return false;
return true;
});
}
// Apply sorting
aircrafts = this._sortAircrafts(aircrafts, config);
// Apply limit
if (config.hasOwnProperty('limit') && config.limit > 0 && aircrafts.length > config.limit) {
aircrafts = aircrafts.slice(0, config.limit);
}
this.sendSocketNotification('SET_AIRCRAFTS', aircrafts);
},
_getAircraftsTar1090: function(config) {
// tar1090 provides enriched data directly
return this.adsb.getAircrafts()
.filter(aircraft => aircraft.callsign)
.map(aircraft => {
const result = {
callsign: aircraft.callsign,
airline: this._getAirlineFromCallsign(aircraft.callsign) || aircraft.operator,
type: aircraft.type,
description: aircraft.description,
registration: aircraft.registration,
altitude: aircraft.altitude,
speed: aircraft.speed,
heading: aircraft.heading,
verticalRate: aircraft.verticalRate,
lat: aircraft.lat,
lng: aircraft.lng,
distance: aircraft.distance, // In nautical miles if from tar1090
direction: aircraft.direction, // In degrees if from tar1090
route: aircraft.route,
squawk: aircraft.squawk,
distanceUnit: 'nm'
};
// Fallback: calculate distance if not provided by tar1090 (e.g., dump1090-fa)
// but latLng config and aircraft position are available
if (!aircraft.distance && aircraft.lat && aircraft.lng &&
config.latLng && Array.isArray(config.latLng) && config.latLng.length === 2) {
const R = 6371e3; // Earth radius in metres
const radLat1 = this._toRadians(config.latLng[0]);
const radLat2 = this._toRadians(aircraft.lat);
const deltaLat = this._toRadians(aircraft.lat - config.latLng[0]);
const deltaLng = this._toRadians(aircraft.lng - config.latLng[1]);
const a = Math.sin(deltaLat / 2) * Math.sin(deltaLat / 2) +
Math.cos(radLat1) * Math.cos(radLat2) *
Math.sin(deltaLng / 2) * Math.sin(deltaLng / 2);
const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
// Convert meters to nautical miles (1 nm = 1852 m)
result.distance = (R * c) / 1852;
// Calculate bearing/direction
const y = Math.sin(deltaLng) * Math.cos(radLat2);
const x = Math.cos(radLat1) * Math.sin(radLat2) -
Math.sin(radLat1) * Math.cos(radLat2) * Math.cos(deltaLng);
const bearing = this._toDegrees(Math.atan2(y, x));
result.direction = (bearing + 360) % 360;
}
return result;
});
},
_getAircraftsNetwork: function(config) {
// Network/SBS1 mode - enrich with CSV databases and calculate distance
return this.adsb.getStore().getAircrafts()
.filter(aircraft => aircraft.callsign)
.map(aircraft => {
const icao = parseInt(aircraft.icao, 10).toString(16);
const plane = this.aircrafts.find(p => p.icao === icao);
const enriched = {
...aircraft,
airline: this._getAirlineForAircraft(aircraft, plane),
type: aircraft.type || (plane && plane.type),
distanceUnit: 'm' // Distance will be in meters
};
// Calculate distance and direction from base coordinates
if (aircraft.lat && aircraft.lng && config.latLng && Array.isArray(config.latLng)) {
const R = 6371e3; // metres
const radLat1 = this._toRadians(config.latLng[0]);
const radLat2 = this._toRadians(aircraft.lat);
const deltaLat = this._toRadians(aircraft.lat - config.latLng[0]);
const deltaLng = this._toRadians(aircraft.lng - config.latLng[1]);
const a = Math.sin(deltaLat / 2) * Math.sin(deltaLat / 2) +
Math.cos(radLat1) * Math.cos(radLat2) *
Math.sin(deltaLng / 2) * Math.sin(deltaLng / 2);
const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
enriched.distance = R * c; // In meters
const y = Math.sin(deltaLng) * Math.cos(radLat2);
const x = Math.cos(radLat1) * Math.sin(radLat2) -
Math.sin(radLat1) * Math.cos(radLat2) * Math.cos(deltaLng);
const bearing = this._toDegrees(Math.atan2(y, x));
enriched.direction = (bearing + 360) % 360;
}
return enriched;
});
},
_getAirlineFromCallsign: function(callsign) {
if (!callsign) return null;
// No digits = likely a private registration, not a commercial callsign
if (!/\d/.test(callsign)) return null;
const airline = this.airlines.find(a => a.icao === callsign.substr(0, 3));
if (airline) {
return airline.alias || airline.name;
}
// Has digits but no matching airline - could be cargo, charter, etc.
return null;
},
_getAirlineForAircraft: function(aircraft, plane) {
if (!/\d/.test(aircraft.callsign)) return 'Private';
if (plane && plane.operator) return plane.operator;
const airline = this.airlines.find(a => a.icao === aircraft.callsign.substr(0, 3));
if (airline) {
let name = airline.alias || airline.name;
if (!airline.active) name += '*';
return name;
}
return 'Unknown';
},
_sortAircrafts: function(aircrafts, config) {
const orderBy = config.orderBy ? config.orderBy.split(':') : [];
if (orderBy.length !== 2) return aircrafts;
const property = orderBy[0] === 'age' ? 'count' : orderBy[0];
const multiplier = orderBy[1] === 'asc' ? 1 : -1;
return aircrafts
.filter(aircraft => aircraft.hasOwnProperty(property))
.sort((a, b) => {
const valueA = a[property];
const valueB = b[property];
if (typeof valueA === 'string' && typeof valueB === 'string') {
return valueA.toLowerCase() < valueB.toLowerCase()
? -1 * multiplier
: valueA.toLowerCase() > valueB.toLowerCase() ? multiplier : 0;
}
if (typeof valueA === 'number' && typeof valueB === 'number') {
return (valueA - valueB) * multiplier;
}
return 0;
});
},
_toRadians: function(n) {
return n * Math.PI / 180;
},
_toDegrees: function(n) {
return n * 180 / Math.PI;
}
});