forked from gerjomarty/MMM-DarkSkyForecast
-
Notifications
You must be signed in to change notification settings - Fork 17
/
MMM-OpenWeatherMapForecast.js
687 lines (588 loc) · 23.5 KB
/
MMM-OpenWeatherMapForecast.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
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
/*********************************
MagicMirror² Module:
MMM-OpenWeatherMapForecast
https://github.com/MarcLandis/MMM-OpenWeatherMapForecast
Icons in use by this module:
Skycons - Animated icon set by Dark Sky
http://darkskyapp.github.io/skycons/
(using the fork created by Maxime Warner
that allows individual details of the icons
to be coloured
https://github.com/maxdow/skycons)
Climacons by Adam Whitcroft
http://adamwhitcroft.com/climacons/
Free Weather Icons by Svilen Petrov
https://www.behance.net/gallery/12410195/Free-Weather-Icons
Weather Icons by Thom
(Designed for DuckDuckGo)
https://dribbble.com/shots/1832162-Weather-Icons
Sets 4 and 5 were found on Graphberry, but I couldn't find
the original artists.
https://www.graphberry.com/item/weather-icons
https://www.graphberry.com/item/weathera-weather-forecast-icons
Weather animated Icons by basmilius
https://github.com/basmilius/weather-icons
Some of the icons were modified to better work with the module's
structure and aesthetic.
Weather data provided by OpenWeatherMap One Call API
By Jeff Clarke
Modified by Dirk Rettschlag
MIT Licensed
*********************************/
Module.register("MMM-OpenWeatherMapForecast", {
requiresVersion: "2.2.0",
defaults: {
apikey: "",
latitude: "",
longitude: "",
endpoint: "https://api.openweathermap.org/data/3.0/onecall",
updateInterval: 10, // minutes
requestDelay: 0,
units: config.units,
showCurrentConditions: true,
showExtraCurrentConditions: true,
showSummary: true,
forecastHeaderText: "",
showForecastTableColumnHeaderIcons: true,
showHourlyForecast: true,
hourlyForecastInterval: 3,
maxHourliesToShow: 3,
showDailyForecast: true,
maxDailiesToShow: 3,
includeTodayInDailyForecast: false,
showPrecipitation: true,
concise: true,
showWind: true,
showFeelsLike: true,
language: config.language,
iconset: "1c",
useAnimatedIcons: true,
animateMainIconOnly: true,
colored: true,
forecastLayout: "tiled",
showInlineIcons: true,
mainIconSize: 100,
forecastTiledIconSize: 70,
forecastTableIconSize: 30,
updateFadeSpeed: 500,
label_maximum: "max",
label_high: "H",
label_low: "L",
label_timeFormat: "h a",
label_days: ["Sun", "Mon", "Tue", "Wed", "Thur", "Fri", "Sat"],
label_ordinals: ["N", "NNE", "NE", "ENE", "E", "ESE", "SE", "SSE", "S", "SSW", "SW", "WSW", "W", "WNW", "NW", "NNW"],
moduleTimestampIdPrefix: "OPENWEATHER_ONE_CALL_TIMESTAMP_"
},
validUnits: ["imperial", "metric", ""],
validLayouts: ["tiled", "table"],
getScripts: function() {
return ["moment.js", this.file("skycons.js")];
},
getStyles: function() {
return ["MMM-OpenWeatherMapForecast.css"];
},
getTemplate: function() {
return "MMM-OpenWeatherMapForecast.njk";
},
/*
Data object provided to the Nunjucks template. The template does not
do any data minipulation; the strings provided here are displayed as-is.
The only logic in the template are conditional blocks that determine if
a certain section should be displayed, and simple loops for the hourly
and daily forecast.
*/
getTemplateData: function() {
return {
phrases: {
loading: this.translate("LOADING")
},
loading: this.formattedWeatherData == null ? true : false,
config: this.config,
forecast: this.formattedWeatherData,
inlineIcons: {
rain: this.generateIconSrc("i-rain"),
snow: this.generateIconSrc("i-snow"),
wind: this.generateIconSrc("i-wind")
},
animatedIconSizes: {
main: this.config.mainIconSize,
forecast: this.config.forecastLayout == "tiled" ? this.config.forecastTiledIconSize : this.config.forecastTableIconSize
},
moduleTimestampIdPrefix: this.config.moduleTimestampIdPrefix,
identifier: this.identifier,
timeStamp: this.dataRefreshTimeStamp
};
},
start: function() {
Log.info("Starting module: " + this.name);
this.weatherData = null;
this.iconIdCounter = 0;
this.formattedWeatherData = null;
this.animatedIconDrawTimer = null;
/*
Optionally, Dark Sky's Skycons animated icon
set can be used. If so, it is drawn to the DOM
and animated on demand as opposed to being
contained in animated images such as GIFs or SVGs.
This initializes the colours for the icons to use.
*/
if (this.config.useAnimatedIcons) {
this.skycons = new Skycons({
"monochrome": false,
"colors": {
"main": "#FFFFFF",
"moon": this.config.colored ? "#FFFDC2" : "#FFFFFF",
"fog": "#FFFFFF",
"fogbank": "#FFFFFF",
"cloud": this.config.colored ? "#BEBEBE" : "#999999",
"snow": "#FFFFFF",
"leaf": this.config.colored ? "#98D24D" : "#FFFFFF",
"rain": this.config.colored ? "#7CD5FF" : "#FFFFFF",
"sun": this.config.colored ? "#FFD550" : "#FFFFFF"
}
});
}
//sanitize optional parameters
if (this.validUnits.indexOf(this.config.units) == -1) {
this.config.units = "imperial";
}
if (this.validLayouts.indexOf(this.config.forecastLayout) == -1) {
this.config.forecastLayout = "tiled";
}
if (this.iconsets[this.config.iconset] == null) {
this.config.iconset = "1c";
}
if (this.iconsets[this.config.mainIconset] == null) {
this.config.mainIconset = this.config.iconset;
}
this.sanitizeNumbers([
"updateInterval",
"requestDelay",
"hourlyForecastInterval",
"maxHourliesToShow",
"maxDailiesToShow",
"mainIconSize",
"forecastIconSize",
"updateFadeSpeed",
"animatedIconPlayDelay"
]);
//force icon set to mono version whern config.coloured = false
if (this.config.colored == false) {
this.config.iconset = this.config.iconset.replace("c", "m");
}
//start data poll
var self = this;
setTimeout(function() {
//first data pull is delayed by config
self.getData();
setInterval(function() {
self.getData();
}, self.config.updateInterval * 60 * 1000); //convert to milliseconds
}, this.config.requestDelay);
},
getData: function() {
this.sendSocketNotification("OPENWEATHER_ONE_CALL_FORECAST_GET", {
apikey: this.config.apikey,
latitude: this.config.latitude,
longitude: this.config.longitude,
units: this.config.units,
language: this.config.language,
instanceId: this.identifier,
requestDelay: this.config.requestDelay,
endpoint: this.config.endpoint
});
},
socketNotificationReceived: function(notification, payload) {
if (notification === "OPENWEATHER_ONE_CALL_FORECAST_DATA" && payload.instanceId === this.identifier) {
//clear animated icon cache
if (this.config.useAnimatedIcons) {
this.clearIcons();
}
//process weather data
this.dataRefreshTimeStamp = moment().format("x");
this.weatherData = payload;
this.formattedWeatherData = this.processWeatherData();
this.updateDom(this.config.updateFadeSpeed);
//broadcast weather update
this.sendNotification("OPENWEATHER_ONE_CALL_FORECAST_WEATHER_UPDATE", payload);
/*
Start icon playback. We need to wait until the DOM update
is complete before drawing and starting the icons.
The DOM object has a timestamp embedded that we will look
for. If the timestamp can be found then the DOM has been
fully updated.
*/
if (this.config.useAnimatedIcons) {
var self = this;
this.animatedIconDrawTimer = setInterval(function() {
var elToTest = document.getElementById(self.config.moduleTimestampIdPrefix + self.identifier);
if (elToTest != null && elToTest.getAttribute("data-timestamp") == self.dataRefreshTimeStamp) {
clearInterval(self.animatedIconDrawTimer);
self.playIcons(self);
}
}, 100);
}
}
},
/*
This prepares the data to be used by the Nunjucks template. The template does not do any logic other
if statements to determine if a certain section should be displayed, and a simple loop to go through
the houly / daily forecast items.
*/
processWeatherData: function() {
var summary;
if (this.config.concise) {
summary = this.weatherData.hourly ? this.weatherData.hourly[0].weather[0].description : this.weatherData.current.weather[0].description;
} else {
summary = (this.weatherData.current.weather[0].description + ".") + " " +
(this.weatherData.hourly ? this.weatherData.hourly[0].weather[0].description + " " : "") +
(this.weatherData.daily ? this.weatherData.daily[0].weather[0].description : "");
}
var hourlies = [];
if (this.config.showHourlyForecast) {
var displayCounter = 0;
var currentIndex = this.config.hourlyForecastInterval;
while (displayCounter < this.config.maxHourliesToShow) {
if (this.weatherData.hourly[currentIndex] == null) {
break;
}
hourlies.push(this.forecastItemFactory(this.weatherData.hourly[currentIndex], "hourly"));
currentIndex += this.config.hourlyForecastInterval;
displayCounter++;
}
}
var dailies = [];
if (this.config.showDailyForecast) {
var i = 1;
var maxi = this.config.maxDailiesToShow;
if (this.config.includeTodayInDailyForecast) {
i = 0;
maxi = this.config.maxDailiesToShow - 1;
}
for (i; i <= maxi; i++) {
if (this.weatherData.daily[i] == null) {
break;
}
dailies.push(this.forecastItemFactory(this.weatherData.daily[i], "daily"));
}
}
return {
"currently": {
temperature: Math.round(this.weatherData.current.temp) + "°",
feelslike: Math.round(this.weatherData.current.feels_like) + "°",
animatedIconId: this.config.useAnimatedIcons ? this.getAnimatedIconId() : null,
animatedIconName: this.convertOpenWeatherIdToIcon(this.weatherData.current.weather[0].id, this.weatherData.current.weather[0].icon),
iconPath: this.generateIconSrc(this.convertOpenWeatherIdToIcon(this.weatherData.current.weather[0].id, this.weatherData.current.weather[0].icon), true),
tempRange: this.formatHiLowTemperature(this.weatherData.daily[0].temp.max, this.weatherData.daily[0].temp.min),
precipitation: this.formatPrecipitation(null, this.weatherData.current.rain, this.weatherData.current.snow),
wind: this.formatWind(this.weatherData.current.wind_speed, this.weatherData.current.wind_deg, this.weatherData.current.wind_gust),
},
"summary": summary,
"hourly": hourlies,
"daily": dailies,
};
},
/*
Hourly and Daily forecast items are very similar. So one routine builds the data
objects for both.
*/
forecastItemFactory: function(fData, type) {
var fItem = new Object();
// --------- Date / Time Display ---------
if (type == "daily") {
//day name (e.g.: "MON")
fItem.day = this.config.label_days[moment(fData.dt * 1000).format("d")];
} else { //hourly
//time (e.g.: "5 PM")
fItem.time = moment(fData.dt * 1000).format(this.config.label_timeFormat);
}
// --------- Icon ---------
if (this.config.useAnimatedIcons && !this.config.animateMainIconOnly) {
fItem.animatedIconId = this.getAnimatedIconId();
fItem.animatedIconName = this.convertOpenWeatherIdToIcon(fData.weather[0].id, fData.weather[0].icon);
}
fItem.iconPath = this.generateIconSrc(this.convertOpenWeatherIdToIcon(fData.weather[0].id, fData.weather[0].icon));
// --------- Temperature ---------
if (type == "hourly") { //just display projected temperature for that hour
fItem.temperature = Math.round(fData.temp) + "°";
} else { //display High / Low temperatures
fItem.tempRange = this.formatHiLowTemperature(fData.temp.max, fData.temp.min);
}
// --------- Precipitation ---------
fItem.precipitation = this.formatPrecipitation(fData.pop, fData.rain, fData.snow);
// --------- Wind ---------
fItem.wind = (this.formatWind(fData.wind_speed, fData.wind_deg, fData.wind_gust));
return fItem;
},
/*
Returns a formatted data object for High / Low temperature range
*/
formatHiLowTemperature: function(h, l) {
return {
high: (!this.config.concise ? this.config.label_high + " " : "") + Math.round(h) + "°",
low: (!this.config.concise ? this.config.label_low + " " : "") + Math.round(l) + "°"
};
},
/*
Returns a formatted data object for precipitation
*/
formatPrecipitation: function(percentChance, rainAccumulation, snowAccumulation) {
var accumulation = null;
var accumulationtype = null;
var pop = null;
//accumulation
if (snowAccumulation) {
accumulationtype = "snow";
if (typeof snowAccumulation === "number") {
if (this.getUnit("accumulationSnow") === "in") {
accumulation = Math.round(snowAccumulation*100/25.4)/100;
} else {
accumulation = Math.round(snowAccumulation);
}
} else if (typeof snowAccumulation === "object" && snowAccumulation["1h"]) {
if (this.getUnit("accumulationSnow") === "in") {
accumulation = Math.round(snowAccumulation["1h"]*100/25.4)/100;
} else {
accumulation = Math.round(snowAccumulation["1h"]);
}
}
accumulation = accumulation + " " + this.getUnit("accumulationSnow");
} else if (rainAccumulation) {
accumulationtype = "rain";
if (typeof rainAccumulation === "number") {
if (this.getUnit("accumulationRain") === "in") {
accumulation = Math.round(rainAccumulation*100/25.4)/100;
} else {
accumulation = Math.round(rainAccumulation);
}
} else if (typeof rainAccumulation === "object" && rainAccumulation["1h"]) {
if (this.getUnit("accumulationRain") === "in") {
accumulation = Math.round(rainAccumulation["1h"]*100/25.4)/100;
} else {
accumulation = Math.round(rainAccumulation["1h"]);
}
}
accumulation = accumulation + " " + this.getUnit("accumulationRain");
}
if (percentChance) {
pop = Math.round(percentChance * 100) + "%";
}
return {
pop: pop,
accumulation: accumulation,
accumulationtype: accumulationtype
};
},
/*
Returns a formatted data object for wind conditions
*/
formatWind: function(speed, bearing, gust) {
//wind gust
var windGust = null;
if (!this.config.concise && gust) {
windGust = " (" + this.config.label_maximum + " " + Math.round(gust) + " " + this.getUnit("windSpeed") + ")";
}
return {
windSpeed: Math.round(speed) + " " + this.getUnit("windSpeed") + (!this.config.concise ? " " + this.getOrdinal(bearing) : ""),
windGust: windGust
};
},
/*
Returns the units in use for the data pull from OpenWeather
*/
getUnit: function(metric) {
return this.units[metric][this.config.units];
},
/*
Formats the wind direction into common ordinals (e.g.: NE, WSW, etc.)
Wind direction is provided in degress from North in the data feed.
*/
getOrdinal: function(bearing) {
return this.config.label_ordinals[Math.round(bearing * 16 / 360) % 16];
},
/*
Some display items need the unit beside them. This returns the correct
unit for the given metric based on the unit set in use.
*/
units: {
accumulationRain: {
imperial: "in",
metric: "mm",
"": "mm"
},
accumulationSnow: {
imperial: "in",
metric: "mm",
"": "mm"
},
windSpeed: {
imperial: "mph",
metric: "m/s",
"": "m/s"
}
},
/*
Icon sets can be added here. The path is relative to
MagicMirror/modules/MMM-OpenWeatherMapForecast/icons, and the format
is specified here so that you can use icons in any format
that works for you.
OpenWeatherMap currently specifies one of ten icons for weather
conditions:
clear-day
clear-night
cloudy
fog
partly-cloudy-day
partly-cloudy-night
rain
sleet
snow
wind
All of the icon sets below support these ten plus an
additional three in anticipation of OpenWeatherMap enabling
a few more:
hail,
thunderstorm,
tornado
Lastly, the icons also contain three icons for use as inline
indicators beside precipitation and wind conditions. These
ones look best if designed to a 24px X 24px artboard.
i-rain
i-snow
i-wind
*/
iconsets: {
"1m": { path: "1m" , format: "svg" },
"1c": { path: "1c" , format: "svg" },
"2m": { path: "2m" , format: "svg" },
"2c": { path: "2c" , format: "svg" },
"3m": { path: "3m" , format: "svg" },
"3c": { path: "3c" , format: "svg" },
"4m": { path: "4m" , format: "svg" },
"4c": { path: "4c" , format: "svg" },
"5m": { path: "5m" , format: "svg" },
"5c": { path: "5c" , format: "svg" },
"6fa": { path: "6fa" , format: "svg" },
"6oa": { path: "6oa" , format: "svg" }
},
/*
This converts OpenWeatherMap icon id to icon names
*/
convertOpenWeatherIdToIcon: function(id, openweather_icon) {
if (id >= 200 && id < 300) {
// Thunderstorm
return "thunderstorm";
} else if (id >= 300 && id < 400) {
// Drizzle
return "rain";
} else if (id === 511) {
// Rain - freezing rain
return "sleet";
} else if (id >= 500 && id < 600) {
// Rain
return "rain";
} else if (id >= 610 && id < 620) {
// Snow - sleet or with rain
return "sleet";
} else if (id >= 600 && id < 700) {
// Snow
return "snow";
} else if (id === 781) {
// Atmosphere - tornado
return "tornado";
} else if (id >= 700 && id < 800) {
// Atmosphere
return "fog";
} else if (id >= 800 && id < 810) {
var isDay = openweather_icon.slice(-1) === "d";
if (id === 800) {
// Clear
if (isDay) {
return "clear-day";
} else {
return "clear-night";
}
} else if (id === 801 || id == 802) {
// Clouds - few or scattered
if (isDay) {
return "partly-cloudy-day";
} else {
return "partly-cloudy-night";
}
} else if (id === 803 || id === 804) {
// Clouds - broken or overcast
return "cloudy";
}
}
},
/*
This generates a URL to the icon file
*/
generateIconSrc: function(icon, mainIcon) {
if (mainIcon) {
return this.file("icons/" + this.iconsets[this.config.mainIconset].path + "/" +
icon + "." + this.iconsets[this.config.mainIconset].format);
}
return this.file("icons/" + this.iconsets[this.config.iconset].path + "/" +
icon + "." + this.iconsets[this.config.iconset].format);
},
/*
When the Skycons animated set is in use, the icons need
to be rebuilt with each data refresh. This traverses the
DOM to find all of the current animated icon canvas elements
and removes them by id from the skycons object.
*/
clearIcons: function() {
this.skycons.pause();
var self = this;
var animatedIconCanvases = document.querySelectorAll(".skycon-" + this.identifier);
animatedIconCanvases.forEach(function(icon) {
self.skycons.remove(icon.id);
});
this.iconIdCounter = 0;
},
/*
When the Skycons animated set is in use, the icons need
to be rebuilt with each data refresh. This returns a
unique id that will be assigned the icon's canvas element.
*/
getAnimatedIconId: function() {
//id to use for the canvas element
var iconId = "skycon_" + this.identifier + "_" + this.iconIdCounter;
this.iconIdCounter++;
return iconId;
},
/*
For use with the Skycons animated icon set. Once the
DOM is updated, the icons are built and set to animate.
Name is a bit misleading. We needed to wait until
the canvas elements got added to the DOM, which doesn't
happen until after updateDom() finishes executing
before actually drawing the icons.
This routine traverses the DOM for all canavas elements
prepared for an animated icon, and adds the icon to the
skycons object. Then the icons are played.
*/
playIcons: function(inst) {
var animatedIconCanvases = document.querySelectorAll(".skycon-" + inst.identifier);
animatedIconCanvases.forEach(function(icon) {
inst.skycons.add(icon.id, icon.getAttribute("data-animated-icon-name"));
});
inst.skycons.play();
},
/*
For any config parameters that are expected as integers, this
routine ensures they are numbers, and if they cannot be
converted to integers, then the module defaults are used.
*/
sanitizeNumbers: function(keys) {
var self = this;
keys.forEach(function(key) {
if (isNaN(parseInt(self.config[key]))) {
self.config[key] = self.defaults[key];
} else {
self.config[key] = parseInt(self.config[key]);
}
});
}
});