-
-
Notifications
You must be signed in to change notification settings - Fork 52
/
ServiceUtils.ts
470 lines (412 loc) · 14.6 KB
/
ServiceUtils.ts
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
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
import HostType from '../types/HostType'
import HAPServiceNodeType from '../types/HAPServiceNodeType'
import {
Accessory,
Characteristic,
CharacteristicChange,
CharacteristicGetCallback,
CharacteristicSetCallback,
CharacteristicValue,
Service,
} from 'hap-nodejs'
import HAPServiceConfigType from '../types/HAPServiceConfigType'
import { HAPConnection } from 'hap-nodejs/dist/lib/util/eventedhttp'
import { logger } from '@nrchkb/logger'
import NRCHKBError from '../NRCHKBError'
module.exports = function (node: HAPServiceNodeType) {
const log = logger('NRCHKB', 'ServiceUtils', node.config.name, node)
const HapNodeJS = require('hap-nodejs')
const Service = HapNodeJS.Service
const Characteristic = HapNodeJS.Characteristic
const CameraSource = require('../cameraSource').Camera
const NO_RESPONSE_MSG = 'NO_RESPONSE'
const prepareHapData = (context: any, connection?: HAPConnection) => {
const hap: { [key: string]: any } = {}
if (connection) {
hap.session = {
sessionID: connection.sessionID,
username: connection.username,
remoteAddress: connection.remoteAddress,
localAddress: connection.localAddress,
httpPort: connection.remotePort,
}
hap.context = {}
}
if (context) {
hap.context = context
}
return hap
}
const onCharacteristicGet = function (
this: Characteristic,
callback: CharacteristicGetCallback,
context: any,
connection?: HAPConnection
) {
log.debug(
`onCharacteristicGet with status: ${this.statusCode}, value: ${
this.value
}, reachability is ${
node.accessory.reachable
} with context ${JSON.stringify(context)} on connection ${
connection?.sessionID
}`
)
if (callback) {
try {
callback(
node.accessory.reachable
? this.statusCode
: new Error(NO_RESPONSE_MSG),
this.value
)
} catch (_) {}
}
}
const onValueChange = function (
this: Characteristic,
allCharacteristics: Characteristic[],
outputNumber: number,
{ oldValue, newValue, context }: any,
connection?: HAPConnection
) {
const topic = node.config.topic ? node.config.topic : node.topic_in
const msg: {
payload: { [key: string]: any }
hap: any
name?: string
topic: string
} = { payload: {}, hap: {}, name: node.name, topic: topic }
const key = this.constructor.name
msg.payload[key] = newValue
msg.hap = prepareHapData(context, connection)
msg.hap.allChars = allCharacteristics.reduce<{ [key: string]: any }>(
(allChars, singleChar) => {
allChars[singleChar.displayName] = singleChar.value
return allChars
},
{}
)
if (oldValue !== undefined) {
msg.hap.oldValue = oldValue
}
msg.hap.newValue = newValue
const statusId = node.setStatus({
fill: 'yellow',
shape: 'dot',
text: key + ': ' + newValue,
})
setTimeout(function () {
node.clearStatus(statusId)
}, 3000)
log.debug(`${node.name} received ${key} : ${newValue}`)
if (
connection ||
context ||
node.hostNode.config.allowMessagePassthrough
) {
if (outputNumber === 0) {
node.send(msg)
} else if (outputNumber === 1) {
node.send([null!, msg])
}
}
}
// eslint-disable-next-line no-unused-vars
const onCharacteristicSet = (allCharacteristics: Characteristic[]) =>
function (
this: Characteristic,
newValue: CharacteristicValue,
callback: CharacteristicSetCallback,
context: any,
connection?: HAPConnection
) {
log.debug(
`onCharacteristicSet with status: ${this.statusCode}, value: ${
this.value
}, reachability is ${node.accessory.reachable}
with context ${JSON.stringify(context)} on connection ${
connection?.sessionID
}`
)
try {
if (callback) {
callback(
node.accessory.reachable
? null
: new Error(NO_RESPONSE_MSG)
)
}
} catch (_) {}
onValueChange.call(
this,
allCharacteristics,
1,
{
newValue,
context,
},
connection
)
}
const onCharacteristicChange = (allCharacteristics: Characteristic[]) =>
function (this: Characteristic, change: CharacteristicChange) {
const { oldValue, newValue, context, originator, reason } = change
log.debug(
`onCharacteristicChange with reason: ${reason}, oldValue: ${oldValue}, newValue: ${newValue}, reachability is ${
node.accessory.reachable
}
with context ${JSON.stringify(context)} on connection ${
originator?.sessionID
}`
)
if (oldValue != newValue) {
onValueChange.call(
this,
allCharacteristics,
0,
{
oldValue,
newValue,
context,
},
originator
)
}
}
const onInput = function (msg: Record<string, any>) {
if (msg.hasOwnProperty('payload')) {
// payload must be an object
const type = typeof msg.payload
if (type !== 'object') {
log.error(`Invalid payload type: ${type}`)
return
}
} else {
log.error('Invalid message (payload missing)')
return
}
const topic = node.config.topic ? node.config.topic : node.name
if (node.config.filter && msg.topic !== topic) {
log.debug(
"msg.topic doesn't match configured value and filter is enabled. Dropping message."
)
return
}
let context: any = null
if (msg.payload.hasOwnProperty('Context')) {
context = msg.payload.Context
delete msg.payload.Context
}
node.topic_in = msg.topic ? msg.topic : ''
// iterate over characteristics to be written
// eslint-disable-next-line no-unused-vars
Object.keys(msg.payload).map((key: string) => {
if (node.supported.indexOf(key) < 0) {
log.error(
`Instead of ${key} try one of these characteristics: ${node.supported.join(
', '
)}`
)
} else {
if (
(node.config.isParent &&
node.config.hostType == HostType.BRIDGE) ||
(!node.config.isParent &&
node.hostNode.hostType == HostType.BRIDGE)
) {
// updateReachability is only supported on bridged accessories
node.accessory.updateReachability(
msg.payload[key] !== NO_RESPONSE_MSG
)
}
const characteristic = node.service.getCharacteristic(
Characteristic[key]
)
if (context !== null) {
characteristic.setValue(
msg.payload[key],
undefined,
context
)
} else {
characteristic.setValue(msg.payload[key])
}
}
})
}
const onClose = function (removed: boolean, done: () => void) {
const characteristics = node.service.characteristics.concat(
node.service.optionalCharacteristics
)
characteristics.forEach(function (characteristic) {
// cleanup all node specific listeners
characteristic.removeListener('get', node.onCharacteristicGet)
characteristic.removeListener('set', node.onCharacteristicSet)
characteristic.removeListener('change', node.onCharacteristicChange)
})
if (node.config.isParent) {
// remove identify listener to prevent errors with undefined values
node.accessory.removeListener('identify', node.onIdentify)
}
if (removed) {
// This node has been deleted
if (node.config.isParent) {
// remove accessory from bridge
node.hostNode.host.removeBridgedAccessories([node.accessory])
node.accessory.destroy()
} else {
// only remove the service if it is not a parent
node.accessory.removeService(node.service)
node.parentService.removeLinkedService(node.service)
}
}
done()
}
const getOrCreate = function (
accessory: Accessory,
serviceInformation: {
name: string
UUID: string
serviceName: string
config: HAPServiceConfigType
},
parentService: Service
) {
const newService = new Service[serviceInformation.serviceName](
serviceInformation.name,
serviceInformation.UUID
)
log.debug(
`Looking for service with UUID ${serviceInformation.UUID} ...`
)
// search for a service with the same subtype
let service: Service | undefined = accessory.services.find(
(service) => {
return newService.subtype === service.subtype
}
)
if (service && newService.UUID !== service.UUID) {
// if the UUID and therefore the type changed, the whole service
// will be replaced
log.debug('... service type changed! Removing the old service.')
accessory.removeService(service)
service = undefined
}
if (!service) {
// if no matching service was found or the type changed, then a new
// service will be added
log.debug(
`... didn't find it. Adding new ${serviceInformation.serviceName} service.`
)
if (serviceInformation.serviceName === 'CameraControl') {
configureCameraSource(
accessory,
newService,
serviceInformation.config
)
service = newService
} else {
service = accessory.addService(newService)
}
} else {
// if a service with the same UUID and subtype was found it will
// be updated and used
log.debug('... found it! Updating it.')
service
.getCharacteristic(Characteristic.Name)
.setValue(serviceInformation.name)
}
if (parentService) {
if (serviceInformation.serviceName === 'CameraControl') {
//We don't add or link it since configureCameraSource do this already.
log.debug('... and adding service to accessory.')
} else if (service) {
log.debug('... and linking service to parent.')
parentService.addLinkedService(service)
}
}
return service
}
const configureCameraSource = function (
accessory: Accessory,
service: Service,
config: HAPServiceConfigType
) {
if (config.cameraConfigSource) {
log.debug('Configuring Camera Source')
if (!config.cameraConfigVideoProcessor) {
log.error(
'Missing configuration for CameraControl: videoProcessor cannot be empty!'
)
} else {
// Use of deprecated method to be replaced with new Camera API
accessory.configureCameraSource(
new CameraSource(service, config, node)
)
}
} else {
log.error('Missing configuration for CameraControl.')
}
}
const waitForParent = () => {
log.debug('Waiting for Parent Service')
return new Promise((resolve) => {
node.setStatus({
fill: 'blue',
shape: 'dot',
text: 'Waiting for Parent Service',
})
const checkAndWait = () => {
const parentNode: HAPServiceNodeType = node.RED.nodes.getNode(
node.config.parentService
) as HAPServiceNodeType
if (parentNode && parentNode.configured) {
resolve(parentNode)
} else {
setTimeout(checkAndWait, 1000)
}
}
checkAndWait()
}).catch((error) => {
log.error(`Waiting for Parent Service failed due to: ${error}`)
throw new NRCHKBError(error)
})
}
const handleWaitForSetup = (
config: HAPServiceConfigType,
msg: Record<string, any>,
resolve: (newConfig: HAPServiceConfigType) => void
) => {
if (node.setupDone) {
return
}
if (
msg.hasOwnProperty('payload') &&
msg.payload.hasOwnProperty('nrchkb') &&
msg.payload.nrchkb.hasOwnProperty('setup')
) {
node.setupDone = true
const newConfig = {
...config,
...msg.payload.nrchkb.setup,
}
node.removeListener('input', node.handleWaitForSetup)
resolve(newConfig)
} else {
log.error(
'Invalid message (required {"payload":{"nrchkb":{"setup":{}}}})'
)
}
}
return {
getOrCreate,
onCharacteristicGet,
onCharacteristicSet,
onCharacteristicChange,
onInput,
onClose,
waitForParent,
handleWaitForSetup,
}
}