forked from itsmepetrov/homebridge-zigbee
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
328 lines (288 loc) · 9.74 KB
/
index.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
const path = require('path')
const get = require('lodash.get')
const retry = require('async-retry')
const requireDir = require('require-dir')
const zigbee = require('./lib/zigbee')
const sleep = require('./lib/utils/sleep')
const castArray = require('./lib/utils/castArray')
const parseModel = require('./lib/utils/parseModel')
const routerPolling = require('./lib/utils/routerPolling')
const findSerialPort = require('./lib/utils/findSerialPort')
const addEveTypes = require('./lib/types/EveTypes')
const addSetupTypes = require('./lib/types/SetupTypes')
const PermitJoinAccessory = require('./lib/PermitJoinAccessory')
const PLUGIN_NAME = 'homebridge-zigbee'
const PLATFORM_NAME = 'ZigBeePlatform'
const devices = Object.values(requireDir('./lib/devices'))
// Only for beta period
process.on('uncaughtException', (error) => {
console.error('Uncaught Exception', error) // eslint-disable-line no-console
})
process.on('unhandledRejection', (reason) => {
console.error('Unhandled Rejection', reason) // eslint-disable-line no-console
})
// eslint-disable-next-line one-var, one-var-declaration-per-line
let Accessory, Service, Characteristic, UUIDGen
module.exports = function main(homebridge) {
addEveTypes(homebridge)
addSetupTypes(homebridge)
Accessory = homebridge.platformAccessory
Service = homebridge.hap.Service
Characteristic = homebridge.hap.Characteristic
UUIDGen = homebridge.hap.uuid
homebridge.registerPlatform(PLUGIN_NAME, PLATFORM_NAME, ZigBeePlatform, true)
}
class ZigBeePlatform {
constructor(log, config, api) {
this.log = log
this.api = api
this.config = config
this.devices = {}
this.accessories = {}
this.permitJoinAccessory = null
// Bind handlers
this.handleZigBeeError = this.handleZigBeeError.bind(this)
this.handleZigBeeReady = this.handleZigBeeReady.bind(this)
this.handleZigBeeIndication = this.handleZigBeeIndication.bind(this)
this.handleInitialization = this.handleInitialization.bind(this)
this.configureAccessory = this.configureAccessory.bind(this)
// Listen events
this.api.on('didFinishLaunching', this.handleInitialization)
this.log('ZigBee platform initialization')
}
handleInitialization() {
this.startZigBee().catch(this.log)
}
async startZigBee() {
zigbee.init({
port: this.config.port || await findSerialPort(),
db: this.config.database || path.join(this.api.user.storagePath(), './zigbee.db'),
panId: this.config.panId || 0xFFFF,
channel: this.config.channel || 11,
})
zigbee.on('ready', this.handleZigBeeReady)
zigbee.on('error', this.handleZigBeeError)
zigbee.on('ind', this.handleZigBeeIndication)
const retrier = async () => {
try {
await zigbee.start()
} catch (error) {
await zigbee.stop()
throw error
}
}
try {
await retry(retrier, {
retries: 20,
minTimeout: 5000,
maxTimeout: 5000,
onRetry: () => this.log('Retrying connect to hardware'),
})
} catch (error) {
this.log('error:', error)
}
}
handleZigBeeError(error) {
this.log('error:', error)
}
handleZigBeeIndication(message) { // eslint-disable-line consistent-return
switch (message.type) {
// Supported indication messages
case 'attReport':
case 'statusChange':
return this.handleZigBeeAttrChange(message)
case 'devInterview':
return this.handleZigBeeDevInterview(message)
case 'devIncoming':
return this.handleZigBeeDevIncoming(message)
case 'devLeaving':
return this.handleZigBeeDevLeaving(message)
default:
// Do nothing
}
}
handleZigBeeAttrChange(message) {
const ieeeAddr = get(message, 'endpoints[0].device.ieeeAddr')
if (!ieeeAddr) {
return this.log('Unable to parse device ieeeAddr from message:', message)
}
const device = this.getDevice(ieeeAddr)
if (!device) {
return this.log('Received message from unknown device:', ieeeAddr)
}
device.zigbee.handleIndicationMessage(message)
}
handleZigBeeDevInterview(message) {
const endpoint = get(message, 'status.endpoint.current')
const endpointTotal = get(message, 'status.endpoint.total')
const cluster = get(message, 'status.endpoint.cluster.current')
const clusterTotal = get(message, 'status.endpoint.cluster.total')
this.log(
`Join progress: interview endpoint ${endpoint} of ${endpointTotal} `
+ `and cluster ${cluster} of ${clusterTotal}`
)
}
async handleZigBeeDevIncoming(message) {
const ieeeAddr = message.data
// Stop permit join
this.permitJoinAccessory.setPermitJoin(false)
this.log(`Device announced incoming and is added, id: ${ieeeAddr}`)
// Ignore if the device exists
if (!this.getDevice(ieeeAddr)) {
// Wait a little bit for a database sync
await sleep(1500)
const data = zigbee.device(ieeeAddr)
this.initDevice(data)
}
}
handleZigBeeDevLeaving(message) {
const ieeeAddr = message.data
// Stop permit join
this.permitJoinAccessory.setPermitJoin(false)
this.log(`Device announced leaving and is removed, id: ${ieeeAddr}`)
const uuid = UUIDGen.generate(ieeeAddr)
const accessory = this.getAccessory(uuid)
// Sometimes we can unpair device which doesn't exist in HomeKit
if (accessory) {
this.api.unregisterPlatformAccessories(PLUGIN_NAME, PLATFORM_NAME, [accessory])
this.removeDevice(ieeeAddr)
this.removeAccessory(uuid)
}
}
handleZigBeeReady() {
const info = zigbee.info()
this.log('ZigBee platform initialized, info:')
this.log('------------------------------------')
this.log('channel:', info.net.channel)
this.log('pan id:', info.net.panId)
this.log('extended pan id:', info.net.extPanId)
this.log('ieee address:', info.net.ieeeAddr)
this.log('nwk address:', info.net.nwkAddr)
this.log('firmware version:', info.firmware.version)
this.log('firmware revision:', info.firmware.revision)
this.log('------------------------------------')
// Set led indicator
zigbee.request('UTIL', 'ledControl', {
ledid: 3, mode: this.config.disableLed ? 0 : 1,
}).catch(() => {
/* Unable to set led indicator, may be your device doesn\'t support it */
})
// Init permit join accessory
this.initPermitJoinAccessory()
// Init devices
zigbee.list().forEach(data => this.initDevice(data))
// Init log for router polling service
if (!this.config.disablePingLog) {
routerPolling.log = this.log
}
// Some routers need polling to prevent them from sleeping.
routerPolling.start(this.config.routerPollingInterval)
}
setDevice(device) {
this.devices[device.ieeeAddr] = device
}
getDevice(ieeeAddr) {
return this.devices[ieeeAddr]
}
setAccessory(accessory) {
this.accessories[accessory.UUID] = accessory
}
getAccessory(uuid) {
return this.accessories[uuid]
}
registerAccessory(accessory) {
this.setAccessory(accessory)
this.api.registerPlatformAccessories(PLUGIN_NAME, PLATFORM_NAME, [accessory])
}
recognizeDevice({ model, manufacturer }) {
for (const Device of devices) {
if (!Device.description) {
continue // eslint-disable-line no-continue
}
if (
castArray(Device.description.model).includes(model)
&& castArray(Device.description.manufacturer).includes(manufacturer)
) {
return Device
}
}
}
initDevice(data) {
try {
const platform = this
const model = parseModel(data.modelId)
const manufacturer = data.manufName
const ieeeAddr = data.ieeeAddr
const uuid = UUIDGen.generate(ieeeAddr)
const accessory = this.getAccessory(uuid)
const log = (...args) => this.log(manufacturer, model, ieeeAddr, ...args)
const Device = this.recognizeDevice({ model, manufacturer })
const name = get(Device, 'description.name')
if (!Device) {
return this.log('Unrecognized device:', ieeeAddr, manufacturer, model)
}
const device = new Device({
name,
model,
manufacturer,
ieeeAddr,
accessory,
platform,
log,
Accessory,
Service,
Characteristic,
UUIDGen,
})
this.setDevice(device)
this.log('Registered device:', ieeeAddr, manufacturer, model)
} catch (error) {
this.log(
`Unable to initialize device ${data && data.ieeeAddr}, `
+ 'try to remove it and add it again.\n')
this.log('Reason:', error)
}
}
initPermitJoinAccessory() {
const platform = this
const uuid = UUIDGen.generate('zigbee:permit-join')
const accessory = this.getAccessory(uuid)
const log = (...args) => this.log('[PermitJoinAccessory]', ...args)
this.permitJoinAccessory = new PermitJoinAccessory({
accessory,
platform,
log,
Accessory,
Service,
Characteristic,
UUIDGen,
})
}
configureAccessory(accessory) {
this.setAccessory(accessory)
}
removeDevice(ieeeAddr) {
const device = this.devices[ieeeAddr]
if (device) {
device.unregister()
delete this.devices[ieeeAddr]
this.removeAccessory(UUIDGen.generate(ieeeAddr))
}
}
removeAccessory(uuid) {
delete this.accessories[uuid]
}
async unpairDevice(device) {
try {
this.log('Unpairing device:', device.ieeeAddr)
await zigbee.remove(device.ieeeAddr)
} catch (error) {
this.log('Unable to unpairing properly, trying to unregister device:', device.ieeeAddr)
await zigbee.unregister(device.ieeeAddr)
} finally {
this.log('Device has been unpaired:', device.ieeeAddr)
this.api.unregisterPlatformAccessories(PLUGIN_NAME, PLATFORM_NAME, [device.accessory])
this.removeDevice(device.ieeeAddr)
}
}
}