-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathnode_helper.js
More file actions
277 lines (234 loc) · 9.55 KB
/
node_helper.js
File metadata and controls
277 lines (234 loc) · 9.55 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
/**
* Node Helper for MMM-SantaTracker
* Handles backend processing and data management
*/
const NodeHelper = require("node_helper");
const fs = require("fs");
const path = require("path");
const utils = require("./utils");
module.exports = NodeHelper.create({
start: function () {
console.log("Starting node_helper for: " + this.name);
this.santaData = null;
this.arrivalSet = [];
this.locationMap = new Map();
this.config = {
debug: false,
moduleName: this.name
};
// Override time tracking - advances by 1 minute each update when set
this.overrideTimeStart = null;
this.overrideTimeOffset = 0; // Minutes elapsed since override started
},
debugLog: function (message) {
utils.debugLog(message);
},
/**
* Load and parse the Santa route data file
*/
loadDataFile: function (dataFile) {
const filePath = path.resolve(__dirname, dataFile);
this.debugLog("Loading Santa data from: " + filePath);
try {
const data = fs.readFileSync(filePath, 'utf8');
this.santaData = JSON.parse(data);
this.processData();
this.debugLog("Santa data loaded successfully. " + this.arrivalSet.length + " locations loaded.");
return true;
} catch (error) {
console.error("Error loading Santa data: ", error);
return false;
}
},
/**
* Process the data and build lookup structures
*/
processData: function () {
if (!this.santaData || !this.santaData.destinations) {
console.error("No Santa data to process");
return;
}
const locations = this.santaData.destinations;
this.arrivalSet = [];
this.locationMap.clear();
for (let i = 0; i < locations.length; i++) {
const entry = locations[i];
// Basic validation: entry and location must exist and have lat/lng
if (!entry || typeof entry.arrival === 'undefined' || !entry.location || typeof entry.location.lat !== 'number' || typeof entry.location.lng !== 'number') {
this.debugLog(`Skipping invalid or incomplete entry at index ${i}`);
continue;
}
const arrive = this.convertDateToThisYear(entry.arrival);
if (arrive === null || !Number.isFinite(arrive)) {
this.debugLog(`Skipping entry with invalid converted arrival at index ${i}`);
continue;
}
this.arrivalSet.push(arrive);
this.locationMap.set(arrive, entry);
}
// Sort arrival times for binary search
this.arrivalSet.sort((a, b) => a - b);
this.debugLog("Processed " + this.arrivalSet.length + " Santa locations");
},
/**
* Convert dates from source file to current year
*/
convertDateToThisYear: function (epochDate) {
// Validate input
if (!Number.isFinite(epochDate)) {
this.debugLog("Invalid epochDate passed to convertDateToThisYear: " + epochDate);
return null;
}
// Use UTC construction to avoid mixing UTC getters with local Date constructor
const year = new Date().getUTCFullYear();
const sd = new Date(epochDate);
const utcMillis = Date.UTC(year, sd.getUTCMonth(), sd.getUTCDate(), sd.getUTCHours(), sd.getUTCMinutes(), sd.getUTCSeconds());
return utcMillis;
},
/**
* Binary search to find Santa's current location efficiently
*/
findCurrentLocation: function (currentTime) {
return utils.findCurrentLocation(this.arrivalSet, currentTime);
},
/**
* Get Santa's current location
* If overTime is set in config, advances by 1 minute on each call
*/
getSantaLocation: function (currentTime) {
let timeToUse = currentTime;
// Handle override time if configured
if (this.config.overTime != null) {
// Initialize override time tracking on first use
if (this.overrideTimeStart === null) {
this.debugLog("Starting override time progression from: '" + this.config.overTime + "'");
this.overrideTimeStart = new Date(this.config.overTime);
this.overrideTimeOffset = 0;
}
// Add elapsed minutes (1 minute per update)
this.overrideTimeOffset++;
var calculatedTime = new Date(this.overrideTimeStart.getTime() + (this.overrideTimeOffset * 60000));
this.debugLog("Override time progressed to: " + calculatedTime.toISOString() + " (+" + this.overrideTimeOffset + " minutes)");
timeToUse = calculatedTime.valueOf();
} else {
// Reset override tracking if overTime is removed
this.overrideTimeStart = null;
this.overrideTimeOffset = 0;
}
this.debugLog("Getting Santa's location for time: " + new Date(timeToUse).toISOString());
this.debugLog("Time value (ms): " + timeToUse);
const timestamp = this.findCurrentLocation(timeToUse);
if (timestamp === null) {
this.debugLog("No location found");
return null;
}
const location = this.locationMap.get(timestamp);
if (!location) {
this.debugLog("Location data not found for timestamp: " + timestamp);
return null;
}
this.debugLog("Santa is at: " + location.city + ", " + location.region);
return {
timestamp: timestamp,
location: location,
arrivalTime: new Date(timestamp).toISOString()
};
},
/**
* Get all locations for initial map rendering
*/
getAllLocations: function () {
if (!this.santaData || !this.santaData.destinations) {
return [];
}
// Filter out invalid entries so frontend doesn't need to guard for them
const results = [];
for (let i = 0; i < this.santaData.destinations.length; i++) {
const entry = this.santaData.destinations[i];
const arrival = this.convertDateToThisYear(entry.arrival);
const departure = this.convertDateToThisYear(entry.departure);
if (!entry || !entry.location || typeof entry.location.lat !== 'number' || typeof entry.location.lng !== 'number' || arrival === null) {
this.debugLog(`Skipping invalid entry for ALL_LOCATIONS at index ${i}`);
continue;
}
results.push({
id: entry.id,
city: entry.city,
region: entry.region,
location: entry.location,
arrival: arrival,
departure: departure,
population: entry.population,
presentsDelivered: entry.presentsDelivered,
details: entry.details
});
}
return results;
},
/**
* Get locations Santa has visited so far
*/
getVisitedLocations: function (currentTime) {
const visited = [];
for (let i = 0; i < this.arrivalSet.length; i++) {
if (this.arrivalSet[i] <= currentTime) {
const location = this.locationMap.get(this.arrivalSet[i]);
if (location) {
visited.push({
timestamp: this.arrivalSet[i],
location: location
});
}
} else {
break; // Array is sorted, so we can stop here
}
}
return visited;
},
/**
* Handle socket notifications from the frontend
*/
socketNotificationReceived: function (notification, payload) {
this.debugLog("Received notification: " + notification);
switch (notification) {
case "LOAD_SANTA_DATA":
// Store the full config from frontend
if (payload.config) {
this.config = Object.assign({}, this.config, payload.config);
this.config.moduleName = this.name;
// Pass config to utils
utils.setConfig({
debug: this.config.debug,
moduleName: this.name
});
}
const success = this.loadDataFile(payload.dataFile);
if (success) {
this.sendSocketNotification("SANTA_DATA_LOADED", {
success: true,
locationCount: this.arrivalSet.length
});
} else {
this.sendSocketNotification("SANTA_DATA_LOADED", {
success: false,
error: "Failed to load data file"
});
}
break;
case "GET_ALL_LOCATIONS":
const allLocations = this.getAllLocations();
this.sendSocketNotification("ALL_LOCATIONS", allLocations);
break;
case "GET_SANTA_LOCATION":
const santaLocation = this.getSantaLocation(payload.currentTime);
this.sendSocketNotification("SANTA_LOCATION_UPDATE", santaLocation);
break;
case "GET_VISITED_LOCATIONS":
const visited = this.getVisitedLocations(payload.currentTime);
this.sendSocketNotification("VISITED_LOCATIONS", visited);
break;
default:
this.debugLog("Unknown notification: " + notification);
}
}
});