forked from Alblahm/avea_node
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLuz_VerticalComedor_accessory.js
342 lines (320 loc) · 14 KB
/
Luz_VerticalComedor_accessory.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
var Accessory = require('../').Accessory;
var Service = require('../').Service;
var Characteristic = require('../').Characteristic;
var uuid = require('../').uuid;
var noble = require("noble");
var avea = require("avea_node");
var colorS = require("onecolor");
var bulb = null;
var perifSel = null;
const uuidMyLamp = "7cec79d7ad1d";
const txtIdLamp="la lampara de pie del comedor"
// Replace the ".txt" extension with ".js" and paste the file inside the accesories folder of your Hombridge instalation folder.
// Example Created by Alblahm, Nov 20th.
// Thank's to Marmelatze for the base code.
// Changelog:
// Color correspondence between ios and avea_light updated.
// Here's the hardware device that we'll expose to HomeKit
var OFFICELIGHT = {
powerOn: false,
brightness: 50, // percentage
hue: 359,
saturation: 99,
setPowerOn: function(onValue) {
OFFICELIGHT.powerOn = onValue;
//Se modifica el estado del dispositivo ...
OFFICELIGHT.sendToLight(onValue);
},
setHue: function(hue){
//console.log("... Fijando el matiz a %s", hue);
OFFICELIGHT.hue = hue;
OFFICELIGHT.sendToLight(true);
},
setSaturation: function(saturation){
//console.log("... Fijando la saturacion a %s", saturation);
OFFICELIGHT.saturation = saturation;
},
setBrightness: function(brightness) {
//console.log("... Fijando el brillo a %s", brightness);
OFFICELIGHT.brightness = brightness;
},
sendToLight: function(posValue){
// setColor(white,red,green,blue,TimeToSet en ms), los valores van de 0 a 4095
if(posValue==true){
console.log("... Encendiendo %s!",txtIdLamp);
//console.log("... Enviando comando a la luz");
//console.log("... Color AVEA: Hue:" + (OFFICELIGHT.hue).toString() + ", Sat:" + (OFFICELIGHT.saturation).toString() + ", Bright:" + (OFFICELIGHT.brightness).toString());
var myHsbColor = colorS('hsv(' + (OFFICELIGHT.hue).toString() + ',' + (OFFICELIGHT.saturation).toString() + ',' + (OFFICELIGHT.brightness).toString() +')');
//console.log("... Color RGB: RED:" + Math.floor(myHsbColor.red()*255).toString() + ", GREEN:" + Math.floor(myHsbColor.green()*255).toString() + ", BLUE:" + Math.floor(myHsbColor.blue()*255).toString());
var rComp="0x" + Math.floor(Math.min(4095,(myHsbColor.red()*4096))).toString(16).toUpperCase();
var gComp="0x" + Math.floor(Math.min(4095,(myHsbColor.green()*4096))).toString(16).toUpperCase();
var bComp="0x" + Math.floor(Math.min(4095,(myHsbColor.blue()*4096))).toString(16).toUpperCase();
var iComp="0x" + Math.floor(Math.min(4095,(OFFICELIGHT.brightness*4096)/100)).toString(16).toUpperCase();
bulb.setColor(new avea.Color(iComp, rComp, gComp, bComp), 0x0ff);
}else{
console.log("... Apagando %s!", txtIdLamp);
bulb.setColor(new avea.Color(0x000, 0x000, 0x000, 0x000), 0x5ff);
}
},
identify: function() {
console.log("Identify the light!");
}
}
// Generate a consistent UUID for our light Accessory that will remain the same even when
// restarting our server. We use the `uuid.generate` helper function to create a deterministic
// UUID based on an arbitrary "namespace" and the word "OFFICELIGHT".
var lightUUID = uuid.generate('hap-nodejs:accessories:OFFICELIGHT');
// This is the Accessory that we'll return to HAP-NodeJS that represents our fake light.
var light = exports.accessory = new Accessory('Office Light', lightUUID);
// Add properties for publishing (in case we're using Core.js and not BridgedCore.js)
light.username = "FF:FF:FF:FF:FF:1A";
light.pincode = "031-45-154";
// set some basic properties (these values are arbitrary and setting them is optional)
light
.getService(Service.AccessoryInformation)
.setCharacteristic(Characteristic.Manufacturer, "ELGATO-AVEA")
.setCharacteristic(Characteristic.Model, "AVEA Light")
.setCharacteristic(Characteristic.SerialNumber, "3333333");
// listen for the "identify" event for this Accessory
light
.on('identify', function(paired, callback) {
OFFICELIGHT.identify();
callback(); // success
});
// Add the actual Lightbulb Service and listen for change events from iOS.
// We can see the complete list of Services and Characteristics in `lib/gen/HomeKitTypes.js`
light
.addService(Service.Lightbulb, "Lampara de Pie") // services exposed to the user should have "names" like "Fake Light" for us
.getCharacteristic(Characteristic.On)
.on('set', function(value, callback) {
if(perifSel!=null){
//console.log("... Click -> Perif: " + perifSel.state + " / Luz: " + bulb.connected);
if(value==true){
//console.log("... Encendiendo %d!", txtIdLamp);
}else{
//console.log("... Apagando %s!", txtIdLamp);
}
// Ahora se hace la solicitud a la función si está conectado el leBT
if((perifSel.state == "connected") && (bulb.connected==true)){
OFFICELIGHT.setPowerOn(value);
callback();
// Our fake Light is synchronous - this value has been successfully set
}else{
console.log("reconectando... ");
noble.startScanning(['f815e810456c6761746f4d756e696368'], false);
OFFICELIGHT.setPowerOn(value);
callback();
}
}else{
console.log("... La luz aun no está disponible o está desconectada!!");
callback(new Error("Device not Ready"));
}
});
// We want to intercept requests for our current power state so we can query the hardware itself instead of
// allowing HAP-NodeJS to return the cached Characteristic.value.
light
.getService(Service.Lightbulb)
.getCharacteristic(Characteristic.On)
.on('get', function(callback) {
// this event is emitted when you ask Siri directly whether your light is on or not. you might query
// the light hardware itself to find this out, then call the callback. But if you take longer than a
// few seconds to respond, Siri will give up.
var err = null; // in case there were any problems
// Ahora se hace la solicitud a la función si está conectado el leBT
if(perifSel!=null){
// Se lee el valor actual de data devuelto por Promise, que contendrá algo como:
// { current: Color { white: 0, red: 0, green: 0, blue: 0 }, target: Color { white: 0, red: 0, green: 0, blue: 0 } }
if((perifSel.state == "connected") && (bulb.connected==true)){
Promise.resolve(bulb.getColor()).then((data) => {
var bCheckColor=((data.target.white==0)&&(data.target.red==0)&&(data.target.green==0)&&(data.target.blue==0));
//console.log(data.target);
if (bCheckColor == true){
console.log("... Estaba encendida " + txtIdLamp + "? No.");
OFFICELIGHT.powerOn = false;
callback(err, false);
}else{
console.log("... Estaba encendida " + txtIdLamp + "? Si.");
OFFICELIGHT.powerOn = true;
//OFFICELIGHT.brightness = parseInt(data.current.white)*100/4096;
callback(err, true, OFFICELIGHT.brightness);
}
}).catch(e => {
console.log(e);
});
}else{
console.log("reconectando... ");
noble.startScanning(['f815e810456c6761746f4d756e696368'], false);
Promise.resolve(bulb.getColor()).then((data) => {
var bCheckColor=((data.target.white==0)&&(data.target.red==0)&&(data.target.green==0)&&(data.target.blue==0));
//console.log(data.target);
if (bCheckColor == true){
console.log("... Estaba encendida %s? No.", txtIdLamp);
OFFICELIGHT.powerOn = false;
callback(err, false);
}else{
console.log("... Estaba encendida %s? Si.", txtIdLamp);
OFFICELIGHT.powerOn = true;
//OFFICELIGHT.brightness = parseInt(data.current.white)*100/4096;
callback(err, true, OFFICELIGHT.brightness);
}
}).catch(e => {
console.log(e);
});
}
}else{
console.log("... La luz aun no está disponible o está desconectada!!");
callback(new Error("Device not Ready"));
}
});
// also add an "optional" Characteristic for Brightness
light
.getService(Service.Lightbulb)
.addCharacteristic(Characteristic.Brightness)
.on('get', function(callback) {
if(perifSel!=null){
//console.log("... El brillo de %s estaba fijado a %s", txtIdLamp, OFFICELIGHT.brightness);
callback(null, OFFICELIGHT.brightness);
}else{
callback(new Error("Device not Ready"));
}
})
.on('set', function(value, callback) {
console.log("... Nuevo valor de brillo: %s", value);
if(perifSel!=null){
// Ahora se hace la solicitud a la función si está conectado el leBT
if((perifSel.state == "connected") && (bulb.connected==true)){
OFFICELIGHT.setBrightness(value);
callback();
// Our fake Light is synchronous - this value has been successfully set
}else{
console.log("reconectando... ");
noble.startScanning(['f815e810456c6761746f4d756e696368'], false);
OFFICELIGHT.setBrightness(value);
callback();
}
}else{
callback(new Error("Device not Ready"));
}
});
light
.getService(Service.Lightbulb)
.addCharacteristic(Characteristic.Hue)
.on('get',function(callback){
if(perifSel!=null){
//console.log("... El matiz de %s estaba fijado a %s", txtIdLamp, OFFICELIGHT.hue);
callback(null, OFFICELIGHT.hue);
}else{
callback(new Error("Device not Ready"));
}
})
.on('set',function(value,callback){
//console.log("... Nuevo valor de matiz: %s", value);
if(perifSel!=null){
// Ahora se hace la solicitud a la función si está conectado el leBT
if((perifSel.state == "connected") && (bulb.connected==true)){
OFFICELIGHT.setHue(value);
callback();
// Our fake Light is synchronous - this value has been successfully set
}else{
console.log("reconectando... ");
noble.startScanning(['f815e810456c6761746f4d756e696368'], false);
OFFICELIGHT.setHue(value);
callback();
}
}else{
callback(new Error("Device not Ready"));
}
});
light
.getService(Service.Lightbulb)
.addCharacteristic(Characteristic.Saturation)
.on('get',function(callback){
if(perifSel!=null){
//console.log("... La saturacion de %s estaba fijada a %s", txtIdLamp, OFFICELIGHT.saturation);
callback(null, OFFICELIGHT.saturation);
}else{
callback(new Error("Device not Ready"));
}
})
.on('set',function(value,callback){
//console.log("... Nuevo valor de saturacion: %s", value);
if(perifSel!=null){
// Ahora se hace la solicitud a la función si está conectado el leBT
if((perifSel.state == "connected") && (bulb.connected==true)){
OFFICELIGHT.setSaturation(value);
callback();
// Our fake Light is synchronous - this value has been successfully set
}else{
console.log("reconectando... ");
noble.startScanning(['f815e810456c6761746f4d756e696368'], false);
OFFICELIGHT.setSaturation(value);
callback();
}
}else{
callback(new Error("Device not Ready"));
}
});
// Mas info del paquete noble en: https://www.npmjs.com/package/noble
noble.on("discover", function(peripheral) {
// La primera vez se conecta al dispositivo identificado y se crea una nueva luz Avea...
if(perifSel==null){
//console.log(peripheral.uuid + " / " + uuidMyLamp);
if((peripheral.uuid==uuidMyLamp)||(uuidMyLamp==null)){
perifSel=peripheral;
//console.log("... Dispositivo identificado");
//console.log("... (Init) Perif: " + perifSel.state);
perifSel.connect(function(error) {
//console.log('... (Init) conectando el dispositivo: ' + perifSel.uuid);
bulb = new avea.Avea(perifSel);
bulb.connect();
//console.log("... (Init) Perif: " + perifSel.state + " / Luz: " + bulb.connected);
});
}
// De ahí en adelante tan solo se reconecta la luz y ya conecta el dispositivo al hacerlo
}else{
console.log("... (InitB) Perif: " + perifSel.state);
}
});
// Tras iniciar el programa cambia el estado del servicio a poweredOn, y se lanza un scan de dispositivos
noble.on('stateChange', function(state) {
// possible state values: "unknown", "resetting", "unsupported", "unauthorized", "poweredOff", "poweredOn"
//console.log("... Estado del servicio NOBLE: %s", state);
if (state === 'poweredOn') {
noble.startScanning(['f815e810456c6761746f4d756e696368'], false);
} else {
noble.stopScanning();
}
});
//
// Here we show the list of Siri voice commands accepted with this accessory file.
// ***********************************************************************************
// The name asigned in the ios home app to this sample device is "Lámpara de Pie" and it is placed in a room called "Comedor" for the spanish version,
// if you use any other name or room use the name assigned instead of the name shown here. This section is only informative, there is no code here, so
// any change inside this section do not affect the behaviour of the ios home app.
// --------------------------------------------------
// Accessory room(english): "living-room"
// Accessory room(spanish): "Comedor"
// Accessory room(german): "****"
// Accessory room(...): "****"
// --------------------------------------------------
// Accessory name(english): "lamp"
// Accessory name(spanish): "Lámpara de Pie"
// Accessory name(german): "*****"
// Accessory name(...): "*****"
// --------------------------------------------------
// Command 1(english): "turn on the living room lamp"
// Command 1(spanish): "Enciende la lampara de pie del comedor"
// Command 1(german): "*****"
// --------------------------------------------------
// Command 2(english): "turn off the living room lamp"
// Command 2(spanish): "Apaga la lampara de pie del comedor"
// Command 3(german): "*****"
// --------------------------------------------------
// Command 3(english): change the brightness of the living room lamp to 50
// Command 3(spanish): Cambia el brillo de la Lámpara de Pie a 50
// Command 3(german): "*****"
// --------------------------------------------------
// Command 4(english): change the color of the living room lamp to red
// Command 4(spanish): Cambia el color de la Lámpara de Pie a rojo
// Command 4(german): "*****"
// --------------------------------------------------