-
Notifications
You must be signed in to change notification settings - Fork 1
/
lightbulb.js
441 lines (367 loc) · 16.3 KB
/
lightbulb.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
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
/**
* NodeRED HomeKit MQTT
* Copyright (C) 2017 Michael Jacobsen / Marius Schmeding.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
**/
module.exports = function (RED) {
'use strict'
var API = require('./lib/api.js')(RED)
var HapNodeJS = require('hap-nodejs')
var HK = require('./lib/common_functions.js')
var inherits = require('util').inherits;
var Accessory = HapNodeJS.Accessory
var Service = HapNodeJS.Service
var Characteristic = HapNodeJS.Characteristic
var uuid = HapNodeJS.uuid
var TYPE = {
ON: 1,
BRIGHTNESS: 2,
ALL: 3
}
function HAPLightbulbNode(config) {
//
// Lightbulb with only 'On' characteristic
//
this.myLightbulb1 = function(displayName, subtype) {
Service.call(this, displayName, '00000043-0000-1000-8000-0026BB765291', subtype);
// Required Characteristics
this.addCharacteristic(Characteristic.On);
// Optional Characteristics
this.addOptionalCharacteristic(Characteristic.Name);
};
inherits(this.myLightbulb1, Service);
this.myLightbulb1.UUID = '00000043-0000-1000-8000-0026BB765291';
//
// Lightbulb with only 'On' and 'Brightness' characteristics
//
this.myLightbulb2 = function(displayName, subtype) {
Service.call(this, displayName, '00000043-0000-1000-8000-0026BB765291', subtype);
// Required Characteristics
this.addCharacteristic(Characteristic.On);
// Optional Characteristics
this.addOptionalCharacteristic(Characteristic.Brightness);
this.addOptionalCharacteristic(Characteristic.Name);
};
inherits(this.myLightbulb2, Service);
this.myLightbulb2.UUID = '00000043-0000-1000-8000-0026BB765291';
RED.nodes.createNode(this, config)
// MQTT properties
this.qos = 0
this.retain = false
this.nodename = config.nodename
this.dataId = config.dataid
this.wdt = -1
this.wdtStatus = -1
this.alive = null
this.lastVal = {}
this.rpccnt = 1
this.topicDelim = "/"
if (config.wdt > 0) {
this.wdt = config.wdt * 1000
}
this.client = config.client
this.clientConn = RED.nodes.getNode(this.client)
if (!this.clientConn) {
this.error(RED._("msgbus-v2.errors.missing-config"))
return
}
/*if (this.nodename == "client007") {
this.debug = true
} else {
this.debug = false
}*/
this.debug = false
// HomeKit properties
this.name = config.name
this.serviceName = config.serviceName // 'Lightbulb'
this.brightness = config.brightness
this.hue = config.hue
this.saturation = config.saturation
this.configNode = RED.nodes.getNode(config.accessory)
// generate UUID from node id
var subtypeUUID = uuid.generate(this.id)
//console.log("service; ", Service[this.serviceName])
// add service
var accessory = this.configNode.accessory
//var service = accessory.addService(Service[this.serviceName], this.name, subtypeUUID)
//var service = accessory.addService(this.myLightbulb1, this.name, subtypeUUID)
//this.service = service
var node = this
var service = null
if (node.hue > -1 || node.saturation > -1) {
// lightbulb with all characteristics
try {
// this might fail if node is being restarted (!)
service = accessory.addService(Service[this.serviceName], this.name, subtypeUUID)
} catch(err) {
RED.log.debug("HAPLightbulbNode(): service already exists")
service = accessory.getService(subtypeUUID)
}
node.service = service
node.lighttype = TYPE.ALL
} else if (node.brightness > -1) {
// lightbulb with brightness characteristics
try {
// this might fail if node is being restarted (!)
service = accessory.addService(this.myLightbulb2, this.name, subtypeUUID)
} catch(err) {
RED.log.debug("HAPLightbulbNode(): service already exists")
service = accessory.getService(subtypeUUID)
}
node.service = service
node.lighttype = TYPE.BRIGHTNESS
} else {
// lightbulb with only 'On' characteristic
try {
// this might fail if node is being restarted (!)
service = accessory.addService(this.myLightbulb1, this.name, subtypeUUID)
} catch(err) {
RED.log.debug("HAPLightbulbNode(): service already exists")
service = accessory.getService(subtypeUUID)
}
node.service = service
node.lighttype = TYPE.ON
}
// the pinCode should be shown to the user until interaction with iOS client starts
node.status({fill: 'yellow', shape: 'ring', text: node.configNode.pinCode})
if (this.clientConn) {
node.clientConn.register(this)
node.clientConn.startAliveTimer(node)
} else {
RED.log.error("HAPLightbulbNode(): no clientConn")
}
// which characteristics are supported?
var supported = { read: [], write: []}
var allCharacteristics = service.characteristics.concat(service.optionalCharacteristics)
allCharacteristics.map(function (characteristic, index) {
var cKey = characteristic.displayName.replace(/ /g, '')
if (characteristic.props.perms.indexOf('pw') > -1) {
supported.read.push(cKey)
}
if ((characteristic.props.perms.indexOf('pr') + characteristic.props.perms.indexOf('ev')) > -2) {
supported.write.push(cKey)
}
})
//
// set defaults
//
switch (node.lighttype) {
case TYPE.BRIGHTNESS:
RED.log.debug("HAPLightbulbNode(): setting default brightness")
node.service.setCharacteristic(Characteristic["Brightness"], node.brightness)
break
case TYPE.ALL:
RED.log.debug("HAPLightbulbNode(): setting default brightness")
node.service.setCharacteristic(Characteristic["Brightness"], node.brightness)
RED.log.debug("HAPLightbulbNode(): setting default hue")
node.service.setCharacteristic(Characteristic["Hue"], node.hue)
RED.log.debug("HAPLightbulbNode(): setting default saturation")
node.service.setCharacteristic(Characteristic["Saturation"], node.saturation)
break
}
//
// incoming regular updates from device
//
this.clientConn.updateSubscribe(this.nodename, this.dataId, this.qos, function(topic, payload, packet) {
RED.log.debug("HAPLightbulbNode(updateSubscribe): nodename = " + node.nodename +
", dataId = " + node.dataId +
", payload = " + payload.toString())
try {
var obj = JSON.parse(payload)
if (obj.hasOwnProperty('on')) {
node.service.setCharacteristic(Characteristic["On"], obj.on)
RED.log.debug("HAPLightbulbNode(updateSubscribe): on = " + obj.on)
}
} catch(err) {
RED.log.error("malformed object: " + payload.toString())
}
node.clientConn.startAliveTimer(node)
}, this.id)
//
// emit message when value changes (sent from HomeKit)
//
service.on('characteristic-change', function (info) {
var key = info.characteristic.displayName.replace(/ /g, '')
if (node.debug) {
console.log("characteristic-change: key = ", key, "value = ", info.newValue)
}
RED.log.debug("HAPLightbulbNode(characteristic-change): key = " + key + ", value = " + info.newValue)
node.status({fill: 'yellow', shape: 'dot', text: key + ': ' + info.newValue})
setTimeout(function () { node.status({}) }, 3000)
var msg = { payload: {}}
msg.manufacturer = node.configNode.manufacturer
msg.serialno = node.configNode.serialNo
msg.model = node.configNode.model
msg.name = node.configNode.name
msg.format = info.characteristic.props.format
msg.payload = HK.FormatValue(info.characteristic.props.format, info.newValue)
msg.topic = HK.CreateOutTopic(node.nodename, node.dataId, key)
if (msg.payload == null) {
RED.log.warn("Unable to format value")
return
}
if (msg.format == Characteristic.Formats.INT) {
msg.format = "uint8"
}
var l = node.clientConn.timeNowString()
var msgLog = {
topic: "log",
payload: l + " > " + node.nodename + ", " + node.dataId + ": " + key + " = " + msg.payload
}
switch (key) {
case "On":
RED.log.debug("HAPLightbulbNode(characteristic-change): On")
break
case "Brightness":
RED.log.debug("HAPLightbulbNode(characteristic-change): Brightness")
break
case "Hue":
RED.log.debug("HAPLightbulbNode(characteristic-change): Hue")
break
case "Saturation":
RED.log.debug("HAPLightbulbNode(characteristic-change): Saturation")
break
default:
RED.log.warn("Unknown characteristics '" + key + "'")
return
}
node.publishAll()
node.send([msg, msgLog, null])
})
//
// RPC replies coming from MQTT
//
this.rpcReply = function(reply) {
RED.log.debug("HAPLightbulbNode(rpcReply)" + JSON.stringify(reply))
node.clientConn.startAliveTimer(node)
}
//
// device online/offline transitions
//
this.online = function(status) {
RED.log.debug("HAPLightbulbNode(online): " + status)
if (status) {
//node.publishAll()
}
}
this.publishAll = function() {
if (node.wdtStatus != 1) {
RED.log.debug("HAPLightbulbNode(publishAll): not online")
return
}
var d = {}
switch (node.lighttype) {
case TYPE.ON:
RED.log.debug("HAPLightbulbNode(publishAll): TYPE.ON")
var d = {
on: service.getCharacteristic(Characteristic["On"]).value,
}
break
case TYPE.BRIGHTNESS:
RED.log.debug("HAPLightbulbNode(publishAll): TYPE.BRIGHTNESS")
var d = {
on: service.getCharacteristic(Characteristic["On"]).value,
brightness: service.getCharacteristic(Characteristic["Brightness"]).value
}
break
case TYPE.ALL:
RED.log.debug("HAPLightbulbNode(publishAll): TYPE.ALL")
var d = {
on: service.getCharacteristic(Characteristic["On"]).value,
hue: service.getCharacteristic(Characteristic["Hue"]).value,
saturation: service.getCharacteristic(Characteristic["Saturation"]).value,
brightness: service.getCharacteristic(Characteristic["Brightness"]).value
}
break
}
node.clientConn.rpcPublish(node.nodename, node.rpccnt++, node.dataId, "All", d)
}
//
// respond to inputs from NodeRED
//
this.on('input', function (msg) {
var characteristic
var val
if (!msg.hasOwnProperty('topic')) {
RED.log.warn('Invalid message (topic missing)')
return
} else if (!msg.hasOwnProperty('payload')) {
RED.log.warn('Invalid message (payload missing)')
return
} else {
let topicArr = msg.topic.split(node.topicDelim);
let topic = topicArr[topicArr.length - 1]; // get last part of topic
//
// deal with the msg.topic
//
if (topic.toUpperCase() == "ON") {
characteristic = "On"
} else if (topic.toUpperCase() == "BRIGHTNESS") {
characteristic = "Brightness"
} else if (topic.toUpperCase() == "HUE") {
characteristic = "Hue"
} else if (topic.toUpperCase() == "SATURATION") {
characteristic = "Saturation"
} else {
if (msg.payload.hasOwnProperty('on')) {
RED.log.debug("HAPLightbulbNode(input): on")
node.service.setCharacteristic(Characteristic["On"], msg.payload.on)
}
if (msg.payload.hasOwnProperty('brightness')) {
RED.log.debug("HAPLightbulbNode(input): brightness")
node.service.setCharacteristic(Characteristic["Brightness"], msg.payload.brightness)
}
if (msg.payload.hasOwnProperty('hue')) {
RED.log.debug("HAPLightbulbNode(input): hue")
node.service.setCharacteristic(Characteristic["Hue"], msg.payload.hue)
}
if (msg.payload.hasOwnProperty('saturation')) {
RED.log.debug("HAPLightbulbNode(input): saturation")
node.service.setCharacteristic(Characteristic["Saturation"], msg.payload.saturation)
}
return
}
//
// deal with the msg.payload
//
val = HK.FormatValue(service.getCharacteristic(Characteristic[characteristic]).props.format, msg.payload)
if (val == null) {
RED.log.warn("Unable to format value")
return
}
}
if (supported.write.indexOf(characteristic) < 0) {
RED.log.warn("Characteristic " + characteristic + " cannot be written to")
} else {
// send to HomeKit
if (service.getCharacteristic(Characteristic[characteristic]).value != val) {
node.service.setCharacteristic(Characteristic[characteristic], val)
}
}
})
this.on('close', function(removed, done) {
node.accessory.removeService(node.service)
if (node.clientConn) {
node.clientConn.deregister(node, done)
}
if (removed) {
// This node has been deleted
} else {
// This node is being restarted
}
})
}
RED.nodes.registerType('homekit-lightbulb-v2', HAPLightbulbNode)
}