-
Notifications
You must be signed in to change notification settings - Fork 65
/
Copy pathhue-lights-control.js
144 lines (125 loc) · 2.62 KB
/
hue-lights-control.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
const CONFIG = {
ip: '', // Hue bridge IP
user: '', // Hue bridge user
lights: [1, 2, 3], // Light bulb IDs
handlers: {
// bthomesensor:201 - first button
'bthomesensor:201': {
// on single push
single_push: [
{
// by omitting the id, the request is sent to all bulb from the config
on: true,
bri: 20,
hue: 3500
}
]
},
// bthomesensor:202 - second button
'bthomesensor:202': {
single_push: [
{
on: true,
hue: 200,
bri: 60
},
{
id: 2, // specifying the bulb ID will send request only to this device
on: true,
hue: 6000,
bri: 20
}
],
double_push: [
{
on: false,
}
]
},
// button:201 - virtual button
'button:201': {
single_push: [
{
id: 1,
on: true,
hue: 5124,
bri: 250
}
]
}
}
};
/**
* Bulk set the state of all light bulbs
* @param {*} on bulb id
* @param {*} bri brightness
* @param {*} hue hue value
* @param {*} sat saturation
*/
function SetAll(on, bri, hue, sat) {
for (const id of CONFIG.lights) {
Set(id, on, bri, hue, sat);
}
}
/**
* Set the light bulb state
* @param {*} id bulb id
* @param {*} on on/off state
* @param {*} bri brightness
* @param {*} hue hue value
* @param {*} sat saturation
*/
function Set(id, on, bri, hue, sat) {
let body = {};
if (typeof on === 'boolean') {
body.on = on;
}
if (typeof bri === 'number') {
body.bri = bri;
}
if (typeof hue === 'number') {
body.hue = hue;
}
if (typeof sat === 'number') {
body.sat = sat;
}
const uri =
'http://' + CONFIG.ip + '/api/' + CONFIG.user + '/lights/' + id + '/state';
Shelly.call('http.request', {
method: 'PUT',
url: uri,
body: body,
});
}
function onEvent(event_data) {
const component = event_data.component;
const info = event_data.info;
if (!info) {
return;
}
const handlers = CONFIG.handlers[component];
if (!handlers) {
console.log('no handler for ', sensorId);
return;
}
const event = info.event;
const handler = handlers[event];
if (!Array.isArray(handler)) {
console.log('no handler for', event);
return;
}
for (const obj of handler) {
let bulbId = obj.id;
let hue = obj.hue;
let bri = obj.bri;
let on = obj.on;
let sat = obj.sat;
if (typeof bulbId === 'number') {
Set(bulbId, on, bri, hue, sat);
}
else {
SetAll(on, bri, hue, sat);
}
}
}
Shelly.addEventHandler(onEvent);