forked from jclarke0000/MMM-OpenWeatherForecast
-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathnode_helper.js
More file actions
118 lines (104 loc) · 4.61 KB
/
Copy pathnode_helper.js
File metadata and controls
118 lines (104 loc) · 4.61 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
/**
********************************
*
*Node Helper for MMM-OpenWeatherForecast.
*
*This helper is responsible for the data pull from OpenWeather's
*One Call API. At a minimum the API key, Latitude and Longitude
*parameters must be provided. If any of these are missing, the
*request to OpenWeather will not be executed, and instead an error
*will be output the the MagicMirror log.
*
*Additional, this module supplies two optional parameters:
*
* units - one of "standard", "metric" or "imperial"
* lang - Any of the languages OpenWeather supports, as listed here: https://openweathermap.org/api/one-call-api#multi
*
*The OpenWeather OneCall API request looks like this:
*
* https://api.openweathermap.org/data/3.0/onecall?lat={lat}&lon={lon}&exclude=minutely&appid={API key}&units={units}&lang={lang}
*
********************************
*/
const Log = require("logger");
const NodeHelper = require("node_helper");
const moment = require("moment");
module.exports = NodeHelper.create({
start () {
Log.log(`Starting node_helper for: ${this.name}`);
},
evalHaTemplateString(template, config) {
return template.replace(/{{(.*?)}}/g, (_, key) => config[key.trim()] ?? "");
},
async socketNotificationReceived (notification, payload) {
if (notification === "OPENWEATHER_FORECAST_GET") {
if (payload.apikey === null || payload.apikey === "") {
Log.error(`[MMM-OpenWeatherForecast] ${moment().format("D-MMM-YY HH:mm")} ** ERROR ** No API key configured. Get an API key at https://openweathermap.org/`);
} else if (payload.latitude === null || payload.latitude === "" || payload.longitude === null || payload.longitude === "") {
Log.error(`[MMM-OpenWeatherForecast] ${moment().format("D-MMM-YY HH:mm")} ** ERROR ** Latitude and/or longitude not provided.`);
} else {
// make request to OpenWeather One Call API
const url = `${payload.apiBaseURL
}lat=${payload.latitude
}&lon=${payload.longitude
}&exclude=minutely` +
`&appid=${payload.apikey
}&units=${payload.units
}&lang=${payload.language}`;
if (typeof this.config !== "undefined") {
Log.debug(`[MMM-OpenWeatherForecast] Fetching url: ${url}`);
}
try {
const response = await fetch(url);
if (response.status !== 200) {
Log.error(`[MMM-OpenWeatherForecast] API response error: ${response.status} ${response.statusText}`);
return;
}
const data = await response.json();
if (typeof data !== "undefined") {
data.instanceId = payload.instanceId;
// --- START: Home Assistant Temperature integration ---
// Check config.js
if (payload.haUrl != null) {
try {
const haFetchUrl = this.evalHaTemplateString(payload.haUrlTemplate, payload);
Log.debug(`[MMM-OpenWeatherForecast] Fetching HA Url: ${haFetchUrl}`);
// Request data from Home Assistant
const haResponse = await fetch(haFetchUrl, {
method: 'GET',
headers: {
'Authorization': `Bearer ${payload.haToken}`,
'Content-Type': 'application/json'
}
});
if (haResponse.ok) {
const haData = await haResponse.json();
Log.info(`[MMM-OpenWeatherForecast] Using ha data: ${haData}`);
// Overwrite Openweather Temo
if (haData && haData.state) {
const haTemp = parseFloat(haData.state);
if (!isNaN(haTemp) && data.current) {
Log.debug(`[MMM-OpenWeatherForecast] Using HA temperature ${haTemp}`);
data.current.temp = haTemp;
}
}
} else {
Log.warn(`[MMM-OpenWeatherForecast] Home Assistant API Fehler: ${haResponse.status}`);
}
} catch (haError) {
// Log HA unavailability
Log.error(`[MMM-OpenWeatherForecast] Error connecting to HA: ${haError}`);
}
}
// --- END: Home Assistant Temperature Integration ---
this.sendSocketNotification("OPENWEATHER_FORECAST_DATA", data);
}
} catch (error) {
Log.error(`[MMM-OpenWeatherForecast] ${moment().format("D-MMM-YY HH:mm")} ** ERROR ** ${error}\n${error.stack}`);
}
}
} else if (notification === "CONFIG") {
this.config = payload;
}
}
});