forked from dgreif/ring
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ring-platform.ts
377 lines (342 loc) · 11.7 KB
/
ring-platform.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
import {
RingApi,
RingCamera,
RingCameraKind,
RingChime,
RingDevice,
RingDeviceCategory,
RingDeviceType,
} from '../api'
import { hap } from './hap'
import {
API,
DynamicPlatformPlugin,
Logging,
PlatformAccessory,
PlatformConfig,
} from 'homebridge'
import { SecurityPanel } from './security-panel'
import { BaseStation } from './base-station'
import { Chime } from './chime'
import { Keypad } from './keypad'
import { ContactSensor } from './contact-sensor'
import { MotionSensor } from './motion-sensor'
import { Lock } from './lock'
import { SmokeAlarm } from './smoke-alarm'
import { CoAlarm } from './co-alarm'
import { SmokeCoListener } from './smoke-co-listener'
import {
getSystemId,
RingPlatformConfig,
updateHomebridgeConfig,
} from './config'
import { Beam } from './beam'
import { MultiLevelSwitch } from './multi-level-switch'
import { Fan } from './fan'
import { Outlet } from './outlet'
import { Switch } from './switch'
import { Camera } from './camera'
import { PanicButtons } from './panic-buttons'
import { RefreshTokenAuth } from '../api/rest-client'
import { useLogger } from '../api/util'
import { BaseAccessory } from './base-accessory'
import { FloodFreezeSensor } from './flood-freeze-sensor'
import { FreezeSensor } from './freeze-sensor'
import { TemperatureSensor } from './temperature-sensor'
import { WaterSensor } from './water-sensor'
import { LocationModeSwitch } from './location-mode-switch'
import { Thermostat } from './thermostat'
import { generateMacAddress } from './util'
const debug = __filename.includes('release-homebridge'),
unsupportedDeviceTypes: (
| RingDeviceType
| RingCameraKind
| RingChime['deviceType']
)[] = [RingDeviceType.BaseStation, RingDeviceType.Keypad],
ignoreHiddenDeviceTypes: string[] = [
RingDeviceType.RingNetAdapter,
RingDeviceType.ZigbeeAdapter,
RingDeviceType.CodeVault,
RingDeviceType.SecurityAccessCode,
RingDeviceType.ZWaveAdapter,
RingDeviceType.ZWaveExtender,
RingDeviceType.BeamsDevice,
RingDeviceType.PanicButton,
]
export const platformName = 'Ring'
export const pluginName = 'homebridge-ring'
process.env.RING_DEBUG = debug ? 'true' : ''
function getAccessoryClass(
device: RingDevice
): (new (...args: any[]) => BaseAccessory<RingDevice>) | null {
const { deviceType } = device
if (device.data.status === 'disabled') {
return null
}
switch (deviceType) {
case RingDeviceType.ContactSensor:
case RingDeviceType.RetrofitZone:
case RingDeviceType.TiltSensor:
return ContactSensor
case RingDeviceType.MotionSensor:
return MotionSensor
case RingDeviceType.FloodFreezeSensor:
return FloodFreezeSensor
case RingDeviceType.FreezeSensor:
return FreezeSensor
case RingDeviceType.SecurityPanel:
return SecurityPanel
case RingDeviceType.BaseStation:
return BaseStation
case RingDeviceType.Keypad:
return Keypad
case RingDeviceType.SmokeAlarm:
return SmokeAlarm
case RingDeviceType.CoAlarm:
return CoAlarm
case RingDeviceType.SmokeCoListener:
return SmokeCoListener
case RingDeviceType.BeamsMotionSensor:
case RingDeviceType.BeamsSwitch:
case RingDeviceType.BeamsMultiLevelSwitch:
case RingDeviceType.BeamsTransformerSwitch:
case RingDeviceType.BeamsLightGroupSwitch:
return Beam
case RingDeviceType.MultiLevelSwitch:
return device instanceof RingDevice &&
device.categoryId === RingDeviceCategory.Fans
? Fan
: MultiLevelSwitch
case RingDeviceType.MultiLevelBulb:
return MultiLevelSwitch
case RingDeviceType.Switch:
return device instanceof RingDevice &&
device.categoryId === RingDeviceCategory.Outlets
? Outlet
: Switch
case RingDeviceType.TemperatureSensor:
return TemperatureSensor
case RingDeviceType.WaterSensor:
return WaterSensor
case RingDeviceType.Thermostat:
return Thermostat
}
if (/^lock($|\.)/.test(deviceType)) {
return Lock
}
if (deviceType === RingDeviceType.Sensor) {
// Generic sensor that could be any type of sensor, but should at least have `faulted`
if (device.name.toLowerCase().includes('motion')) {
return MotionSensor
}
return ContactSensor
}
return null
}
export class RingPlatform implements DynamicPlatformPlugin {
private readonly homebridgeAccessories: {
[uuid: string]: PlatformAccessory
} = {}
constructor(
public log: Logging,
public config: PlatformConfig & RingPlatformConfig & RefreshTokenAuth,
public api: API
) {
useLogger({
logInfo(message) {
log.info(message)
},
logError(message) {
log.error(message)
},
})
if (!config) {
this.log.info('No configuration found for platform Ring')
return
}
config.cameraStatusPollingSeconds = config.cameraStatusPollingSeconds ?? 20
config.cameraDingsPollingSeconds = config.cameraDingsPollingSeconds ?? 2
config.locationModePollingSeconds = config.locationModePollingSeconds ?? 20
this.api.on('didFinishLaunching', () => {
this.log.debug('didFinishLaunching')
this.connectToApi().catch((e) => {
this.log.error('Error connecting to API')
this.log.error(e)
})
})
this.homebridgeAccessories = {}
}
configureAccessory(accessory: PlatformAccessory) {
this.log.info(
`Configuring cached accessory ${accessory.UUID} ${accessory.displayName}`
)
this.log.debug('%j', accessory)
this.homebridgeAccessories[accessory.UUID] = accessory
}
async connectToApi() {
const { api, config } = this,
systemId = getSystemId(api),
ringApi = new RingApi({
controlCenterDisplayName: 'homebridge-ring',
...config,
systemId,
}),
locations = await ringApi.getLocations(),
cachedAccessoryIds = Object.keys(this.homebridgeAccessories),
platformAccessories: PlatformAccessory[] = [],
activeAccessoryIds: string[] = []
this.log.info('Found the following locations:')
locations.forEach((location) => {
this.log.info(` locationId: ${location.id} - ${location.name}`)
})
await Promise.all(
locations.map(async (location) => {
const devices = await location.getDevices(),
cameras = location.cameras,
chimes = location.chimes,
allDevices = [...devices, ...cameras, ...chimes],
securityPanel = devices.find(
(x) => x.deviceType === RingDeviceType.SecurityPanel
),
debugPrefix = debug ? 'TEST ' : '',
hapDevices = allDevices.map((device) => {
const isCamera = device instanceof RingCamera,
cameraIdDifferentiator = isCamera ? 'camera' : '', // this forces bridged cameras from old version of the plugin to be seen as "stale"
AccessoryClass = (
device instanceof RingCamera
? Camera
: device instanceof RingChime
? Chime
: getAccessoryClass(device)
) as (new (...args: any[]) => BaseAccessory<any>) | null
return {
deviceType: device.deviceType as string,
device: device as any,
isCamera,
id: device.id.toString() + cameraIdDifferentiator,
name: device.name,
AccessoryClass,
}
}),
hideDeviceIds = config.hideDeviceIds || [],
onlyDeviceTypes = config.onlyDeviceTypes?.length
? config.onlyDeviceTypes
: undefined
if (config.showPanicButtons && securityPanel) {
hapDevices.push({
deviceType: securityPanel.deviceType,
device: securityPanel,
isCamera: false,
id: securityPanel.id.toString() + 'panic',
name: 'Panic Buttons',
AccessoryClass: PanicButtons,
})
}
if (
config.locationModePollingSeconds &&
(await location.supportsLocationModeSwitching())
) {
hapDevices.push({
deviceType: 'location.mode',
device: location,
isCamera: false,
id: location.id + 'mode',
name: location.name + ' Mode',
AccessoryClass: LocationModeSwitch,
})
}
this.log.info(
`Configuring ${cameras.length} cameras and ${hapDevices.length} devices for location "${location.name}" - locationId: ${location.id}`
)
hapDevices.forEach(
({ deviceType, device, isCamera, id, name, AccessoryClass }) => {
const uuid = hap.uuid.generate(debugPrefix + id),
displayName = debugPrefix + name
if (
!AccessoryClass ||
(config.hideLightGroups &&
deviceType === RingDeviceType.BeamsLightGroupSwitch) ||
(config.hideUnsupportedServices &&
unsupportedDeviceTypes.includes(deviceType as any)) ||
hideDeviceIds.includes(uuid) ||
(onlyDeviceTypes && !onlyDeviceTypes.includes(deviceType))
) {
if (!ignoreHiddenDeviceTypes.includes(deviceType)) {
this.log.info(
`Hidden accessory ${uuid} ${deviceType} ${displayName}`
)
}
return
}
const createHomebridgeAccessory = () => {
const accessory = new api.platformAccessory(
displayName,
uuid,
isCamera
? hap.Categories.CAMERA
: hap.Categories.SECURITY_SYSTEM
)
this.log.info(
`Adding new accessory ${uuid} ${deviceType} ${displayName}`
)
platformAccessories.push(accessory)
if (
isCamera &&
typeof hap.Accessory.cleanupAccessoryData === 'function'
) {
// This is a one-time cleanup that will remove persist files for old external accessories from before camera bridging in version 8
hap.Accessory.cleanupAccessoryData(
generateMacAddress(accessory.UUID)
)
}
return accessory
},
homebridgeAccessory =
this.homebridgeAccessories[uuid] || createHomebridgeAccessory(),
accessory = new AccessoryClass(
device as any,
homebridgeAccessory,
this.log,
config
)
accessory.initBase()
this.homebridgeAccessories[uuid] = homebridgeAccessory
activeAccessoryIds.push(uuid)
}
)
})
)
if (platformAccessories.length) {
api.registerPlatformAccessories(
pluginName,
platformName,
platformAccessories
)
}
const staleAccessories = cachedAccessoryIds
.filter((cachedId) => !activeAccessoryIds.includes(cachedId))
.map((id) => this.homebridgeAccessories[id])
staleAccessories.forEach((staleAccessory) => {
this.log.info(
`Removing stale cached accessory ${staleAccessory.UUID} ${staleAccessory.displayName}`
)
})
if (staleAccessories.length) {
this.api.unregisterPlatformAccessories(
pluginName,
platformName,
staleAccessories
)
}
ringApi.onRefreshTokenUpdated.subscribe(
({ oldRefreshToken, newRefreshToken }) => {
if (!oldRefreshToken) {
return
}
updateHomebridgeConfig(this.api, (configContents) => {
return configContents.replace(oldRefreshToken, newRefreshToken)
})
}
)
}
}