forked from renssies/homebridge-am43-blinds
-
Notifications
You must be signed in to change notification settings - Fork 0
/
AM43Platform.js
444 lines (389 loc) · 14.2 KB
/
AM43Platform.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
442
443
444
// @ts-check
const AM43DeviceModule = require("./AM43Device")
const AM43Device = AM43DeviceModule.AM43Device
const packageJSON = require("../package.json")
const noble = require("@abandonware/noble")
const {
CONFIG_KEY_ALLOWED_DEVICES,
CONFIG_KEY_HAP_INTERACTION_TIMEOUT,
CONFIG_KEY_POLL_INTERVAL,
MINIMUM_POLL_INTERVAL,
DEFAULT_HAP_INTERACTION_TIMEOUT,
HAP_NO_INTERACTION_GRACE_PERIOD,
MISSING_DEVICES_SCANNING_TIMEOUT,
POSITION_UPDATE_INTERVAL,
DEFAULT_POLL_INTERVAL,
DEFAULT_SCANNING_TIMEOUT,
} = require("./variables/platform")
const { discoverBlinds } = require("./ble/discover")
const { sleep } = require("./utils")
class AM43Platform {
constructor(log, config, api) {
this.configJSON = config
this.log = log
this.api = api
this.packageJSON = packageJSON
this.accessories = []
this.log.info("Starting AM43 platform")
this.isScanning = false
this.discoveredDevices = []
let configuredAllowedDevicesList = this.configJSON[
CONFIG_KEY_ALLOWED_DEVICES
]
if (configuredAllowedDevicesList !== undefined) {
if (configuredAllowedDevicesList == null) {
this.allowedDevices = null
} else if (Array.isArray(configuredAllowedDevicesList)) {
this.allowedDevices = configuredAllowedDevicesList
} else {
this.log.error(
`The config.json defines '${CONFIG_KEY_ALLOWED_DEVICES}' list but it seems to be an invalid format. The list should be an array, example: ['MAC1', 'MAC2']`
)
this.allowedDevices = []
}
} else {
this.log(
`No ${CONFIG_KEY_ALLOWED_DEVICES} field found. Ignoring all devices`
)
this.allowedDevices = []
}
if (
this.configJSON[CONFIG_KEY_HAP_INTERACTION_TIMEOUT] != undefined &&
this.configJSON[CONFIG_KEY_HAP_INTERACTION_TIMEOUT] <= 0
) {
this.log.warn(
"Automatic disconnection of AM43 devices is disabled and the connection will be kept open. This might cause higher power usage of the devices but improve responsiveness."
)
}
if (
this.configJSON[CONFIG_KEY_POLL_INTERVAL] != undefined &&
this.configJSON[CONFIG_KEY_POLL_INTERVAL] < MINIMUM_POLL_INTERVAL
) {
this.log.warn(
`Polling for devices is disabled due too a low poll interval. This might cause an incorrect state in HomeKit apps. Polling requires a value of ${MINIMUM_POLL_INTERVAL} (seconds) or higher.`
)
}
api.on("didFinishLaunching", () => {
this.scanForDevices()
setInterval(() => this.disconnectUnusedDevices(), 20e3)
})
api.on("shutdown", () => {
this.shutdown()
})
}
disconnectUnusedDevices() {
const interactionTimeout =
(this.configJSON[CONFIG_KEY_HAP_INTERACTION_TIMEOUT] ||
DEFAULT_HAP_INTERACTION_TIMEOUT) * 1000
this.accessories
.filter(({ am43device }) => am43device && am43device.isConnected)
.forEach((accessory) => {
const timeSinceInteraction =
Date.now() - accessory.am43device.lastCommandTimestamp
if (
interactionTimeout > 0 &&
timeSinceInteraction > interactionTimeout
) {
this.log(`${accessory.displayName}: disconnecting unused device`)
accessory.context.am43.lastPosition = accessory.am43device.position
accessory.context.am43.lastBatteryPercentage =
accessory.am43device.batteryPercentage
accessory.am43device.disconnectAsync()
}
})
}
async scanForDevices() {
// Start scanning with noble!
if (this.isScanning) return
this.isScanning = true
const blinds = await discoverBlinds(
this.allowedDevices,
this.log,
DEFAULT_SCANNING_TIMEOUT
)
this.isScanning = false
const devices = blinds.map(
(rawBLEPeripheral) => new AM43Device(rawBLEPeripheral, this.log)
)
devices.forEach((device) => {
const uuid = this.api.hap.uuid.generate(device.id)
const existingAccessory = this.accessories.find(
(accessory) => accessory.UUID == uuid
)
if (!existingAccessory) {
this.log.info("Found new AM43 Motor: " + device.description)
let accessory = this.createAccessory(device, uuid)
this.configureDeviceOnAccessory(accessory, device)
this.api.registerPlatformAccessories(
"homebridge-am43-blinds",
"am43-blinds",
[accessory]
)
} else {
this.log.info("Found known AM43 Motor: " + device.description)
this.configureDeviceOnAccessory(existingAccessory, device)
this.api.updatePlatformAccessories([existingAccessory])
}
})
for (let index = 0; index < devices.length; index++) {
const device = devices[index]
device.prepareAsync()
await sleep(500)
}
}
shutdown() {
this.log.info(
"Homebridge is shutting down, disconnecting AM43 motors and saving state"
)
this.accessories.forEach((accessory) => {
if (!accessory.am43device) return
accessory.context.am43.lastPosition = accessory.am43device.position
accessory.context.am43.lastBatteryPercentage =
accessory.am43device.batteryPercentage
accessory.am43device.disconnectAsync()
})
}
configureAccessory(accessory) {
accessory.updateReachability(false)
this.configureServicesOnAccessory(accessory)
this.configurePropertiesOnAccessory(accessory)
this.accessories.push(accessory)
}
createAccessory(device, uuid) {
const accessory = new this.api.platformAccessory(device.name, uuid)
accessory.am43device = device
this.configureServicesOnAccessory(accessory)
this.configurePropertiesOnAccessory(accessory)
return accessory
}
configurePropertiesOnAccessory(accessory) {
accessory.updateInformation = async () => {
if (!accessory.am43device) return
this.log(
`Updating device information for ${accessory.displayName} from poll`
)
await sleep(200)
await accessory.am43device.updatePositionAsync()
await sleep(200)
await accessory.am43device.updateBatteryStatusAsync()
}
}
configureDeviceOnAccessory(accessory, device) {
accessory.updateReachability(true)
accessory.am43device = device
accessory.context.am43 = {
...accessory.context.am43,
id: device.id,
address: device.address,
}
if (accessory.context.am43.lastPosition) {
accessory.am43device.position = accessory.context.am43.lastPosition
}
if (accessory.context.am43.lastBatteryPercentage) {
accessory.am43device.batteryPercentage =
accessory.context.am43.lastBatteryPercentage
}
const updateTargetPosition = (target) => {
this.log(
`${accessory.displayName}: Notifying of target position ${target}%`
)
accessory.windowCoveringService
.getCharacteristic(this.api.hap.Characteristic.TargetPosition)
.updateValue(target)
}
const updateCurrentPosition = (position) => {
this.log(
`${accessory.displayName}: Notifying of current position ${position}%`
)
accessory.windowCoveringService
.getCharacteristic(this.api.hap.Characteristic.CurrentPosition)
.updateValue(position)
}
const updatePositionState = (direction) => {
this.log(
`${accessory.displayName}: Notifying of current direction ${direction}`
)
accessory.windowCoveringService
.getCharacteristic(this.api.hap.Characteristic.PositionState)
.updateValue(direction)
}
device.on("direction", (direction) => {
const { targetPosition, position } = accessory.am43device
this.log(
`${accessory.displayName}: Notifying of new direction (0 down, 1 up): ${direction}`
)
let target = targetPosition ? targetPosition : position
updatePositionState(direction)
if (direction === 2) {
updateCurrentPosition(100 - position)
updateTargetPosition(100 - target)
}
})
device.on("targetPosition", (position) => {
const targetPosition =
position == null ? accessory.am43device.position : position
updateTargetPosition(100 - targetPosition)
})
device.on("position", (position) => {
updateCurrentPosition(100 - position)
if (device.direction === 2) {
updateTargetPosition(100 - position)
}
})
device.on("batteryPercentage", (percentage) => {
this.log(
`${accessory.displayName}: Notifying of new battery percentage: ${percentage}`
)
accessory.batteryService
.getCharacteristic(this.api.hap.Characteristic.BatteryLevel)
.updateValue(percentage)
accessory.batteryService
.getCharacteristic(this.api.hap.Characteristic.StatusLowBattery)
.updateValue(percentage <= 10)
})
const pollInterval =
this.configJSON[CONFIG_KEY_POLL_INTERVAL] != undefined
? this.configJSON[CONFIG_KEY_POLL_INTERVAL]
: DEFAULT_POLL_INTERVAL
if (pollInterval >= MINIMUM_POLL_INTERVAL) {
setInterval(() => accessory.updateInformation(), pollInterval * 1000)
}
setTimeout(() => accessory.updateInformation(), Math.random() * 10e3)
}
configureServicesOnAccessory(accessory) {
this.configureWindowCoveringServiceOnAccessory(accessory)
this.configureInformationServiceOnAccessory(accessory)
this.configureBatteryServiceOnAccessory(accessory)
}
configureInformationServiceOnAccessory(accessory) {
const service =
accessory.getService(this.api.hap.Service.AccessoryInformation) ||
accessory.addService(this.api.hap.Service.AccessoryInformation)
service
.getCharacteristic(this.api.hap.Characteristic.Manufacturer)
.updateValue("renssies")
service
.getCharacteristic(this.api.hap.Characteristic.Model)
.updateValue("AM43")
service
.getCharacteristic(this.api.hap.Characteristic.Name)
.updateValue(`Blind: ${accessory.displayName}`)
service
.getCharacteristic(this.api.hap.Characteristic.SerialNumber)
.on("get", (callback) => {
if (!accessory.am43device) {
callback("No device found please try again", null)
return
}
return callback(null, accessory.am43device.id)
})
service
.getCharacteristic(this.api.hap.Characteristic.FirmwareRevision)
.on("get", (callback) => callback(null, this.packageJSON.version))
accessory.informationService = service
}
configureBatteryServiceOnAccessory(accessory) {
const service =
accessory.getService(this.api.hap.Service.BatteryService) ||
accessory.addService(this.api.hap.Service.BatteryService)
service
.getCharacteristic(this.api.hap.Characteristic.BatteryLevel)
.on("get", (callback) => {
if (!accessory.am43device) {
callback("No device found please try again", null)
return
}
accessory.am43device.updateBatteryStatusAsync()
return callback(null, accessory.am43device.batteryPercentage)
})
service
.getCharacteristic(this.api.hap.Characteristic.ChargingState)
.updateValue(0)
service
.getCharacteristic(this.api.hap.Characteristic.StatusLowBattery)
.on("get", (callback) => {
if (!accessory.am43device) {
callback("No device found please try again", null)
return
}
return callback(null, accessory.am43device.batteryPercentage <= 10)
})
accessory.batteryService = service
}
configureWindowCoveringServiceOnAccessory(accessory) {
const service =
accessory.getService(this.api.hap.Service.WindowCovering) ||
accessory.addService(this.api.hap.Service.WindowCovering)
service
.getCharacteristic(this.api.hap.Characteristic.CurrentPosition)
.on("get", (callback) => {
if (!accessory.am43device) {
this.scanForDevices()
callback("No device found please try again", null)
return
}
accessory.am43device.updatePositionAsync()
const position = 100 - accessory.am43device.position // In AM43 Devices 100% means fully closed, but in HomeKit 100% means fully opened
this.log(`${accessory.displayName}: Reporting position: ${position}`)
return callback(null, position)
})
service
.getCharacteristic(this.api.hap.Characteristic.TargetPosition)
.on("get", (callback) => {
if (!accessory.am43device) {
callback("No device found please try again", null)
return
}
const { targetPosition, position } = accessory.am43device
const currentTargetPosition = targetPosition ? targetPosition : position
this.log(
`${accessory.displayName}: Reporting target position: ${
100 - currentTargetPosition
}`
)
return callback(null, 100 - currentTargetPosition)
})
.on("set", async (value, callback) => {
if (!accessory.am43device) {
callback("No device found please try again")
return
}
const targetPosition = 100 - value // In AM43 Devices 100% means fully closed, but in HomeKit 100% means fully opened
this.log(`${accessory.displayName}: setting target position: ${value}`)
try {
await accessory.am43device.setPositionAsync(targetPosition, true)
return callback(null)
} catch (error) {
callback(error)
}
})
service
.getCharacteristic(this.api.hap.Characteristic.PositionState)
.on("get", (callback) => {
if (!accessory.am43device) {
callback("No device found please try again", null)
return
}
this.log(
`${accessory.displayName}: Reporting direction: ${accessory.am43device.direction}`
)
callback(null, accessory.am43device.direction)
})
service
.getCharacteristic(this.api.hap.Characteristic.HoldPosition)
.on("set", async (boolean, callback) => {
if (!accessory.am43device) {
callback("No device found please try again")
return
}
await accessory.am43device.stopAsync()
callback(null)
})
accessory.windowCoveringService = service
}
identify(callback) {
this.log.info("Identifying AM43 Blinds platform")
callback()
}
}
module.exports = AM43Platform