-
Notifications
You must be signed in to change notification settings - Fork 0
/
MMM-HomeAssistant.js
100 lines (85 loc) · 3.23 KB
/
MMM-HomeAssistant.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
Module.register("MMM-HomeAssistant", {
defaults: {
updateInterval: 60000,
homeAssistantUrl: "http://localhost:8123",
accessToken: "YOUR_ACCESS_TOKEN",
entities: []
},
start: function() {
this.sendSocketNotification("GET_HOME_ASSISTANT_DATA", {
homeAssistantUrl: this.config.homeAssistantUrl,
accessToken: this.config.accessToken
});
this.scheduleUpdate();
},
getData: function() {
var self = this;
var url = this.config.homeAssistantUrl + "/api/states";
var headers = {
"Authorization": "Bearer " + this.config.accessToken
};
fetch(url, { headers: headers })
.then(response => response.json())
.then(data => {
self.processData(data);
})
.catch(error => {
console.error("Error fetching data from Home Assistant:", error);
});
},
processData: function(data) {
this.entities = data.filter(entity => {
let configEntity = this.config.entities.find(e => e.entity_id === entity.entity_id);
if (!configEntity) return false;
if (configEntity.condition) {
let conditionMet = false;
let entityState = parseFloat(entity.state);
let conditionValue = parseFloat(configEntity.condition.value);
switch (configEntity.condition.operator) {
case "above":
conditionMet = entityState > conditionValue;
break;
case "below":
conditionMet = entityState < conditionValue;
break;
case "equal":
conditionMet = entityState === conditionValue;
break;
default:
conditionMet = true;
}
return conditionMet;
}
return true;
});
this.updateDom();
},
scheduleUpdate: function() {
var self = this;
setInterval(function() {
self.getData();
}, this.config.updateInterval);
},
getDom: function() {
var wrapper = document.createElement("div");
this.entities.forEach(entity => {
var entityDiv = document.createElement("div");
var unit = entity.attributes.unit_of_measurement ? ` ${entity.attributes.unit_of_measurement}` : "";
var displayName = entity.attributes.friendly_name;
let configEntity = this.config.entities.find(e => e.entity_id === entity.entity_id);
if (configEntity) {
if (configEntity.hide_friendly_name) {
displayName = configEntity.alternative_name || "";
}
}
entityDiv.innerHTML = displayName ? `${displayName}: ${entity.state}${unit}` : `${entity.state}${unit}`;
wrapper.appendChild(entityDiv);
});
return wrapper;
},
socketNotificationReceived: function(notification, payload) {
if (notification === "HOME_ASSISTANT_DATA") {
this.processData(payload);
}
}
});