-
Notifications
You must be signed in to change notification settings - Fork 47
/
MMM-forecast-io.js
525 lines (447 loc) · 16.3 KB
/
MMM-forecast-io.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
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
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
Module.register("MMM-forecast-io", {
defaults: {
apiKey: "",
apiBase: "https://api.darksky.net/forecast",
units: config.units,
language: config.language,
updateInterval: 5 * 60 * 1000, // every 5 minutes
animationSpeed: 1000,
initialLoadDelay: 0, // 0 seconds delay
retryDelay: 2500,
tempDecimalPlaces: 0, // round temperatures to this many decimal places
geoLocationOptions: {
enableHighAccuracy: true,
timeout: 5000
},
latitude: null,
longitude: null,
showCurrentWeather: true,
showIndoorTemperature: false,
showTextSummary: true,
showWind: true,
showSunriseSunset: true,
showForecast: true,
fadeForecast: false,
showFeelsLike: false, // new FeelsLike option
forecastTableFontSize: 'medium',
maxDaysForecast: 7, // maximum number of days to show in forecast
enablePrecipitationGraph: true,
alwaysShowPrecipitationGraph: false,
showDailyPrecipitationChance: true,
precipitationGraphWidth: 400,
precipitationFillColor: 'white',
precipitationProbabilityThreshold: 0.1,
precipitationIntensityScaleTop: 0.2,
unitTable: {
'default': 'auto',
'metric': 'si',
'imperial': 'us'
},
iconTable: {
'clear-day': 'wi-day-sunny',
'clear-night': 'wi-night-clear',
'rain': 'wi-rain',
'snow': 'wi-snow',
'sleet': 'wi-rain-mix',
'wind': 'wi-cloudy-gusts',
'fog': 'wi-fog',
'cloudy': 'wi-cloudy',
'partly-cloudy-day': 'wi-day-cloudy',
'partly-cloudy-night': 'wi-night-cloudy',
'hail': 'wi-hail',
'thunderstorm': 'wi-thunderstorm',
'tornado': 'wi-tornado'
},
debug: false
},
getTranslations: function () {
return false;
},
getScripts: function () {
return [
'jsonp.js',
'moment.js'
];
},
getStyles: function () {
return ["font-awesome.css", "weather-icons.css", "weather-icons-wind.css", "MMM-forecast-io.css"];
},
shouldLookupGeolocation: function () {
return this.config.latitude == null &&
this.config.longitude == null;
},
start: function () {
Log.info("Starting module: " + this.name);
// still accept the old config
if (this.config.hasOwnProperty("showPrecipitationGraph")) {
this.config.enablePrecipitationGraph = this.config.showPrecipitationGraph;
}
if (this.shouldLookupGeolocation()) {
this.getLocation();
}
this.scheduleUpdate(this.config.initialLoadDelay);
},
updateWeather: function () {
if (this.geoLocationLookupFailed) {
return;
}
if (this.shouldLookupGeolocation() && !this.geoLocationLookupSuccess) {
this.scheduleUpdate(1000); // try again in one second
return;
}
var units = this.config.unitTable[this.config.units] || 'auto';
var url = this.config.apiBase + '/' + this.config.apiKey + '/' + this.config.latitude + ',' + this.config.longitude + '?units=' + units + '&lang=' + this.config.language;
if (this.config.data) {
// for debugging
this.processWeather(this.config.data);
} else {
getJSONP(url, this.processWeather.bind(this), this.processWeatherError.bind(this));
}
},
processWeather: function (data) {
if (this.config.debug) {
console.log('weather data', data);
}
this.loaded = true;
this.weatherData = data;
this.feelsLike = this.roundTemp(this.weatherData.currently.apparentTemperature); // process feelsLike data
this.temp = this.roundTemp(this.weatherData.currently.temperature);
this.updateDom(this.config.animationSpeed);
this.scheduleUpdate();
},
processWeatherError: function (error) {
if (this.config.debug) {
console.log('process weather error', error);
}
// try later
this.scheduleUpdate();
},
notificationReceived: function(notification, payload, sender) {
switch(notification) {
case "DOM_OBJECTS_CREATED":
break;
case "INDOOR_TEMPERATURE":
if (this.config.showIndoorTemperature) {
this.roomTemperature = payload;
this.updateDom(this.config.animationSpeed);
}
break;
}
},
getDom: function() {
var wrapper = document.createElement("div");
if (this.config.apiKey === "") {
wrapper.innerHTML = "Please set the correct forcast.io <i>apiKey</i> in the config for module: " + this.name + ".";
wrapper.className = "dimmed light small";
return wrapper;
}
if (this.geoLocationLookupFailed) {
wrapper.innerHTML = "Geolocaiton lookup failed, please set <i>latitude</i> and <i>longitude</i> in the config for module: " + this.name + ".";
wrapper.className = "dimmed light small";
return wrapper;
}
if (!this.loaded) {
wrapper.innerHTML = this.translate('LOADING');
wrapper.className = "dimmed light small";
return wrapper;
}
var currentWeather = this.weatherData.currently;
var daily = this.weatherData.daily;
var hourly = this.weatherData.hourly;
var minutely = this.weatherData.minutely;
var large = document.createElement("div");
large.className = "large light";
if(this.config.showCurrentWeather) {
var icon = currentWeather ? currentWeather.icon : hourly.icon;
var iconClass = this.config.iconTable[icon];
var icon = document.createElement("span");
icon.className = 'big-icon wi ' + iconClass;
large.appendChild(icon);
var temperature = document.createElement("span");
temperature.className = "bright";
temperature.innerHTML = " " + this.temp + "°";
large.appendChild(temperature);
}
if (this.roomTemperature !== undefined) {
var icon = document.createElement("span");
icon.className = 'fa fa-home';
large.appendChild(icon);
var temperature = document.createElement("span");
temperature.className = "bright";
temperature.innerHTML = " " + this.roomTemperature + "°";
large.appendChild(temperature);
}
/* --- new FeelsLike row --- */
if (this.config.showFeelsLike && ((this.temp - this.feelsLike > 1) || (this.feelsLike - this.temp > 1))) {
var feelsLike = document.createElement("div");
feelsLike.className = "medium bright";
feelsLike.innerHTML = "Feels like " + this.feelsLike + "°";
large.appendChild(feelsLike);
}
/* --- --- */
var wind = document.createElement("div");
wind.className = "small dimmed wind";
var windBearing = document.createElement("span");
windBearing.className = "wi wi-wind from-" + Math.round(currentWeather.windBearing) + "-deg";
wind.appendChild(windBearing);
var cardinalDirection = this.translate(this.degreeToCardinal(currentWeather.windBearing));
var windSpeed = document.createElement("span");
if (this.config.units === 'metric') {
var windSpeedUnit = "m/s";
} else {
var windSpeedUnit = "mph";
}
windSpeed.innerHTML = " " + cardinalDirection + " " + Math.round(currentWeather.windSpeed) + "-" + Math.round(currentWeather.windGust) + windSpeedUnit;
wind.appendChild(windSpeed);
var sunriseSunset = document.createElement("div");
sunriseSunset.className = "small dimmed sunrise-sunset";
var sunriseIcon = document.createElement("span");
sunriseIcon.className = "wi wi-sunrise";
sunriseSunset.appendChild(sunriseIcon);
var sunriseTime = document.createElement("span");
sunriseTime.innerHTML = moment(new Date(daily.data[0].sunriseTime * 1000)).format("LT") + " ";
sunriseSunset.appendChild(sunriseTime);
var sunsetIcon = document.createElement("span");
sunsetIcon.className = "wi wi-sunset";
sunriseSunset.appendChild(sunsetIcon);
var sunsetTime = document.createElement("span");
sunsetTime.innerHTML = moment(new Date(daily.data[0].sunsetTime * 1000)).format("LT");
sunriseSunset.appendChild(sunsetTime);
wrapper.appendChild(large);
if (this.config.showTextSummary) {
var summaryText = minutely ? minutely.summary : hourly.summary;
var summary = document.createElement("div");
summary.className = "small dimmed summary";
summary.innerHTML = summaryText;
wrapper.appendChild(summary);
}
if (this.config.showSunriseSunset) {
wrapper.appendChild(sunriseSunset);
}
if (this.config.showWind) {
wrapper.appendChild(wind);
}
if (this.config.alwaysShowPrecipitationGraph ||
(this.config.enablePrecipitationGraph &&
this.isAnyPrecipitation(minutely))) {
wrapper.appendChild(this.renderPrecipitationGraph());
}
if (this.config.showForecast) {
wrapper.appendChild(this.renderWeatherForecast());
}
return wrapper;
},
isAnyPrecipitation: function (minutely) {
if (!minutely) {
return false;
}
var data = this.weatherData.minutely.data;
var threshold = this.config.precipitationProbabilityThreshold;
for (i = 0; i < data.length; i++) {
if (data[i].precipProbability > threshold) {
return true;
}
}
return false;
},
renderPrecipitationGraph: function () {
var i;
var width = this.config.precipitationGraphWidth;
var height = Math.round(width * 0.3);
var element = document.createElement('canvas');
element.className = "precipitation-graph";
element.width = width;
element.height = height;
var context = element.getContext('2d');
var sixth = Math.round(width / 6);
context.save();
context.strokeStyle = 'gray';
context.lineWidth = 2;
for (i = 1; i < 6; i++) {
context.moveTo(i * sixth, height);
context.lineTo(i * sixth, height - 10);
context.stroke();
}
context.restore();
var third = Math.round(height / 3);
context.save();
context.strokeStyle = 'gray';
context.setLineDash([5, 15]);
context.lineWidth = 1;
for (i = 1; i < 3; i++) {
context.moveTo(0, i * third);
context.lineTo(width, i * third);
context.stroke();
}
context.restore();
var data = this.weatherData.minutely.data;
var stepSize = Math.round(width / data.length);
context.save();
context.strokeStyle = 'white';
context.fillStyle = this.config.precipitationFillColor;
context.globalCompositeOperation = 'xor';
context.beginPath();
context.moveTo(0, height);
var threshold = this.config.precipitationProbabilityThreshold;
var intensity;
// figure out how we're going to scale our graph
var maxIntensity = 0;
for (i = 0; i < data.length; i++) {
maxIntensity = Math.max(maxIntensity, data[i].precipIntensity);
}
// if current intensity is above our normal scale top, make that the top
if (maxIntensity < this.config.precipitationIntensityScaleTop) {
maxIntensity = this.config.precipitationIntensityScaleTop;
}
for (i = 0; i < data.length; i++) {
if (data[i].precipProbability < threshold) {
intensity = 0;
} else {
intensity = height * (data[i].precipIntensity / maxIntensity);
}
context.lineTo(i * stepSize, height - intensity);
}
context.lineTo(width, height);
context.closePath();
context.fill();
context.restore();
return element;
},
getDayFromTime: function (time) {
var dt = new Date(time * 1000);
return moment.weekdaysShort(dt.getDay());
},
renderForecastRow: function (data, min, max, addClass) {
var total = max - min;
var interval = 100 / total;
var rowMinTemp = this.roundTemp(data.temperatureMin);
var rowMaxTemp = this.roundTemp(data.temperatureMax);
var row = document.createElement("tr");
row.className = "forecast-row" + (addClass ? " " + addClass : "");
var dayTextSpan = document.createElement("span");
dayTextSpan.className = "forecast-day"
dayTextSpan.innerHTML = this.getDayFromTime(data.time);
var iconClass = this.config.iconTable[data.icon];
var icon = document.createElement("span");
icon.className = 'wi weathericon ' + iconClass;
var dayPrecipProb = document.createElement("span");
dayPrecipProb.className = "forecast-precip-prob";
if (data.precipProbability > 0) {
dayPrecipProb.innerHTML = Math.round(data.precipProbability * 100) + "%";
} else {
dayPrecipProb.innerHTML = " ";
}
var forecastBar = document.createElement("div");
forecastBar.className = "forecast-bar";
var minTemp = document.createElement("span");
minTemp.innerHTML = rowMinTemp + "°";
minTemp.className = "temp min-temp";
var maxTemp = document.createElement("span");
maxTemp.innerHTML = rowMaxTemp + "°";
maxTemp.className = "temp max-temp";
var bar = document.createElement("span");
bar.className = "bar";
bar.innerHTML = " ";
var barWidth = Math.round(interval * (rowMaxTemp - rowMinTemp));
bar.style.width = barWidth + '%';
var leftSpacer = document.createElement("span");
leftSpacer.style.width = (interval * (rowMinTemp - min)) + "%";
var rightSpacer = document.createElement("span");
rightSpacer.style.width = (interval * (max - rowMaxTemp)) + "%";
forecastBar.appendChild(leftSpacer);
forecastBar.appendChild(minTemp);
forecastBar.appendChild(bar);
forecastBar.appendChild(maxTemp);
forecastBar.appendChild(rightSpacer);
var forecastBarWrapper = document.createElement("td");
forecastBarWrapper.appendChild(forecastBar);
row.appendChild(dayTextSpan);
row.appendChild(icon);
if (this.config.showDailyPrecipitationChance) {
row.appendChild(dayPrecipProb);
}
row.appendChild(forecastBarWrapper);
return row;
},
renderWeatherForecast: function () {
var numDays = this.config.maxDaysForecast;
var i;
var filteredDays =
this.weatherData.daily.data.filter( function(d, i) { return (i < numDays); });
var min = Number.MAX_VALUE;
var max = -Number.MAX_VALUE;
for (i = 0; i < filteredDays.length; i++) {
var day = filteredDays[i];
min = Math.min(min, day.temperatureMin);
max = Math.max(max, day.temperatureMax);
}
min = Math.round(min);
max = Math.round(max);
var display = document.createElement("table");
display.className = this.config.forecastTableFontSize + " forecast";
for (i = 0; i < filteredDays.length; i++) {
var day = filteredDays[i];
var addClass = "";
if(this.config.fadeForecast) {
if(i+2 == filteredDays.length) {
addClass = "dark";
}
if(i+1 == filteredDays.length) {
addClass = "darker";
}
}
var row = this.renderForecastRow(day, min, max, addClass);
display.appendChild(row);
}
return display;
},
getLocation: function () {
var self = this;
navigator.geolocation.getCurrentPosition(
function (location) {
if (self.config.debug) {
console.log("geolocation success", location);
}
self.config.latitude = location.coords.latitude;
self.config.longitude = location.coords.longitude;
self.geoLocationLookupSuccess = true;
},
function (error) {
if (self.config.debug) {
console.log("geolocation error", error);
}
self.geoLocationLookupFailed = true;
self.updateDom(self.config.animationSpeed);
},
this.config.geoLocationOptions);
},
// Round the temperature based on tempDecimalPlaces
roundTemp: function (temp) {
var scalar = 1 << this.config.tempDecimalPlaces;
temp *= scalar;
temp = Math.round( temp );
temp /= scalar;
return temp;
},
// convert windBearing (which is technically a heading) into cardinal direction
degreeToCardinal: function (degree) {
// N repeated 2nd time for easier calculation of degrees between 348.75 and 359.99
var cardinalDirections = ['N', 'NNE', 'NE', 'ENE',
'E', 'ESE', 'SE', 'SSE',
'S', 'SSW', 'SW', 'WSW',
'W', 'WNW', 'NW', 'NNW',
'N'];
var index = Math.trunc((degree+11.25)/22.5);
return cardinalDirections[index];
},
scheduleUpdate: function(delay) {
var nextLoad = this.config.updateInterval;
if (typeof delay !== "undefined" && delay >= 0) {
nextLoad = delay;
}
var self = this;
setTimeout(function() {
self.updateWeather();
}, nextLoad);
}
});