-
Notifications
You must be signed in to change notification settings - Fork 0
/
MMM-WeatherAlerts.js
executable file
·305 lines (271 loc) · 8.89 KB
/
MMM-WeatherAlerts.js
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
/* global Module */
/* MagicMirror²
* Module: MMM-WeatherAlerts
*
* By Gary Jones
* MIT Licensed.
*/
Module.register("MMM-WeatherAlerts", {
defaults: {
weatherAlertProvider: "openweathermapalerts",
roundTemp: false,
type: "alerts", // alerts (only with OpenWeatherMap /onecall endpoint)
units: config.units,
tempUnits: config.units,
windUnits: config.units,
updateInterval: 10 * 60 * 1000, // every 10 minutes
animationSpeed: 1000,
timeFormat: config.timeFormat,
showPeriod: true,
showPeriodUpper: false,
lang: config.language,
initialLoadDelay: 0, // 0 seconds delay
appendLocationNameToHeader: false,
calendarClass: "calendar",
tableClass: "small",
colored: false, // currently only supports NOAA NWS alert color-coding
maxNumberOfAlerts: 0, // set to 0 for no alert limit
showEndTime: true,
alertTimeFormat: "relative", // relative or absolute
alertDateFormat: "M/DD", // only used if alertTimeFormat is 'absolute'
showAlertDescription: true,
staticAlertDescription: false,
alertDescriptionScrollDelay: 85,
alertDescription: {
showHeader: true,
showWhat: true,
showWhere: true,
showWhen: true,
showImpacts: true,
showAdditionalDetails: true,
showPrecautionaryActions: true,
showOther: true,
},
},
// requiresVersion: "2.22.0", // Required version of MagicMirror
// Module properties.
weatherAlertProvider: null,
// Can be used by the provider to display location of event if nothing else is specified
firstEvent: null,
// Define required scripts.
getStyles: function () {
return ["font-awesome.css", "MMM-WeatherAlerts.css"];
},
// Return the scripts that are necessary for the weather module.
getScripts: function () {
Log.info(this.config.weatherAlertProvider);
return [
"moment.js",
// this.file("../default/utils.js"),
"weatheralertobject.js",
"weatheralertprovider.js",
this.file(
"providers/" + this.config.weatherAlertProvider.toLowerCase() + ".js"
),
];
},
// Override getHeader method.
getHeader: function () {
if (this.config.appendLocationNameToHeader && this.weatherAlertProvider) {
if (this.data.header)
return (
this.data.header + " " + this.weatherAlertProvider.fetchedLocation()
);
else return this.weatherAlertProvider.fetchedLocation();
}
if (this.weatherAlertProvider?.currentWeatherAlertsObject?.length) {
return this.data.header ? this.data.header : "";
} else {
return "";
}
},
start: function () {
moment.locale(this.config.lang);
if (this.config.useKmh) {
Log.warn(
"You are using the deprecated config values 'useKmh'. Please switch to windUnits!"
);
this.windUnits = "kmh";
} else if (this.config.useBeaufort) {
Log.warn(
"You are using the deprecated config values 'useBeaufort'. Please switch to windUnits!"
);
this.windUnits = "beaufort";
}
// Initialize the weather provider.
this.weatherAlertProvider = WeatherAlertProvider.initialize(
this.config.weatherAlertProvider,
this
);
// Let the weather provider know we are starting.
this.weatherAlertProvider.start();
// Add custom filterss
this.addFilters();
// Schedule the first update.
this.scheduleUpdate(this.config.initialLoadDelay);
},
// Override notification handler.
notificationReceived: function (notification, payload, sender) {
if (notification === "CALENDAR_EVENTS") {
const senderClasses = sender.data.classes.toLowerCase().split(" ");
if (
senderClasses.indexOf(this.config.calendarClass.toLowerCase()) !== -1
) {
this.firstEvent = null;
for (let event of payload) {
if (event.location || event.geo) {
this.firstEvent = event;
Log.debug("First upcoming event with location: ", event);
break;
}
}
}
} else if (notification === "INDOOR_TEMPERATURE") {
this.indoorTemperature = this.roundValue(payload);
this.updateDom(300);
} else if (notification === "INDOOR_HUMIDITY") {
this.indoorHumidity = this.roundValue(payload);
this.updateDom(300);
}
},
// Select the template depending on the display type.
getTemplate: function () {
switch (this.config.type.toLowerCase()) {
case "alerts":
return "alerts.njk";
//Set up this way to allow easy integration with default weather module in the future...
default:
return "alerts.njk";
}
},
// Add all the data to the template.
getTemplateData: function () {
return {
config: this.config,
alerts: this.weatherAlertProvider.currentWeatherAlerts(),
};
},
// What to do when the weather alert provider has new information available?
updateAvailable: function () {
Log.log("New weather alert information available.");
this.updateDom(0);
this.scheduleUpdate();
// if (this.weatherAlertProvider.currentWeather()) {
// this.sendNotification("CURRENTWEATHER_TYPE", { type: this.weatherAlertProvider.currentWeather().weatherType.replace("-", "_") });
// }
const notificationPayload = {
currentWeatherAlerts:
this.weatherAlertProvider?.currentWeatherAlertsObject?.map((ar) =>
ar.simpleClone()
) ?? [],
locationName: this.weatherAlertProvider?.fetchedLocationName,
providerName: this.weatherAlertProvider.providerName,
};
//need to add alerts to the notification payload...
this.sendNotification("WEATHER_ALERTS_UPDATED", notificationPayload);
},
scheduleUpdate: function (delay = null) {
let nextLoad = this.config.updateInterval;
if (delay !== null && delay >= 0) {
nextLoad = delay;
}
setTimeout(() => {
switch (this.config.type.toLowerCase()) {
case "alerts":
this.weatherAlertProvider.fetchCurrentWeatherAlerts();
break;
default:
// Log.error(`Invalid type ${this.config.type} configured (must be one of 'current', 'hourly', 'daily' or 'forecast')`);
Log.error(
`Invalid type ${this.config.type} configured (must be one of 'alerts')`
);
}
}, nextLoad);
},
roundValue: function (temperature) {
const decimals = this.config.roundTemp ? 0 : 1;
const roundValue = parseFloat(temperature).toFixed(decimals);
return roundValue === "-0" ? 0 : roundValue;
},
addFilters() {
this.nunjucksEnvironment().addFilter(
"formatTime",
function (date) {
if (config.timeFormat !== 24) {
if (this.config.showPeriod) {
if (this.config.showPeriodUpper) {
return date.format("h:mm A");
} else {
return date.format("h:mm a");
}
} else {
return date.format("h:mm");
}
}
return date.format("HH:mm");
}.bind(this)
);
this.nunjucksEnvironment().addFilter(
"alertColorCode",
function (value) {
if (!value[0].match(/[a-z]/i)) {
// add a leading '_' if the event does not start with a letter
return "_" + value.toLowerCase().replaceAll(" ", "-");
} else {
return value.toLowerCase().replaceAll(" ", "-");
}
}.bind(this)
);
this.nunjucksEnvironment().addFilter(
"roundValue",
function (value) {
return this.roundValue(value);
}.bind(this)
);
this.nunjucksEnvironment().addFilter(
"decimalSymbol",
function (value) {
return value.toString().replace(/\./g, this.config.decimalSymbol);
}.bind(this)
);
// this.nunjucksEnvironment().addFilter(
// "calcNumSteps",
// function (alerts) {
// return Math.min(alerts.length, this.config.maxNumberOfDays);
// }.bind(this)
// );
this.nunjucksEnvironment().addFilter(
"calcNumAlerts",
function (alerts) {
return this.config.maxNumberOfAlerts
? Math.min(alerts.length, this.config.maxNumberOfAlerts)
: alerts.length;
}.bind(this)
);
this.nunjucksEnvironment().addFilter(
"calcNumEntries",
function (dataArray) {
return Math.min(dataArray.length, this.config.maxEntries);
}.bind(this)
);
this.nunjucksEnvironment().addFilter(
"opacity",
function (currentStep, numSteps) {
if (this.config.fade && this.config.fadePoint < 1) {
if (this.config.fadePoint < 0) {
this.config.fadePoint = 0;
}
const startingPoint = numSteps * this.config.fadePoint;
const numFadesteps = numSteps - startingPoint;
if (currentStep >= startingPoint) {
return 1 - (currentStep - startingPoint) / numFadesteps;
} else {
return 1;
}
} else {
return 1;
}
}.bind(this)
);
},
});