-
Notifications
You must be signed in to change notification settings - Fork 59
/
control-ha-light-entity-with-boolean.js
79 lines (70 loc) · 1.85 KB
/
control-ha-light-entity-with-boolean.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
const CONFIG = {
ha_ip: "", // Home Assistant IP
ha_port: 8123, // Home Assistant Port
ha_token: "", // Home assistant Long-Lived Access Token
ha_entity_id: "light.shelly1pmminig3_84fce6xxxxxx_switch_0", // Home Assistant Light Entity ID
boolean_id: 200, // Boolean Component ID to toggle the light entity
};
const HEADERS = {
Authorization: "Bearer " + CONFIG.ha_token,
"Content-Type": "application/json",
};
function entityStateResponseHandler(response, err_no, err_msg) {
if (err_no !== 0) {
console.log(err_msg);
return;
}
const result = JSON.parse(response.body);
Shelly.call("boolean.set", {
id: CONFIG.boolean_id,
value: result.state === "on",
});
}
function checkEntityState(entity_id) {
Shelly.call(
"http.request",
{
method: "GET",
headers: HEADERS,
url:
"http://" +
CONFIG.ha_ip +
":" +
JSON.stringify(CONFIG.ha_port) +
"/api/states/" +
entity_id,
},
entityStateResponseHandler
);
}
/**
* Sets the light entity state based on the method
* @param {*} entity_id entity id
* @param {*} method turn_on | turn_off | toggle
*/
function setLightEntityState(entity_id, method) {
Shelly.call("http.request", {
method: "POST",
headers: HEADERS,
url:
"http://" +
CONFIG.ha_ip +
":" +
JSON.stringify(CONFIG.ha_port) +
"/api/services/light/" +
method,
body: JSON.stringify({
entity_id: entity_id,
}),
});
checkEntityState(entity_id);
}
Shelly.addStatusHandler(function (status_data) {
if (status_data.name !== "boolean" || status_data.id !== CONFIG.boolean_id) {
return;
}
const invoke_state = status_data.delta.value ? "turn_on" : "turn_off";
setLightEntityState(CONFIG.ha_entity_id, invoke_state);
});
// Initial sync with the entity state
checkEntityState(CONFIG.ha_entity_id);