forked from dgreif/ring
-
Notifications
You must be signed in to change notification settings - Fork 0
/
lock.ts
81 lines (67 loc) · 2.11 KB
/
lock.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
import { BaseDeviceAccessory } from './base-device-accessory'
import { RingDevice, RingDeviceData } from '../api'
import { distinctUntilChanged } from 'rxjs/operators'
import { hap } from './hap'
import { RingPlatformConfig } from './config'
import { Logging, PlatformAccessory } from 'homebridge'
function getCurrentState({ locked }: RingDeviceData) {
const {
Characteristic: { LockCurrentState: State },
} = hap
switch (locked) {
case 'unlocked':
return State.UNSECURED
case 'locked':
return State.SECURED
case 'jammed':
return State.JAMMED
default:
return State.UNKNOWN
}
}
export class Lock extends BaseDeviceAccessory {
private targetState: any
constructor(
public readonly device: RingDevice,
public readonly accessory: PlatformAccessory,
public readonly logger: Logging,
public readonly config: RingPlatformConfig
) {
super()
const { Characteristic, Service } = hap
this.device.onData
.pipe(distinctUntilChanged((a, b) => a.locked === b.locked))
.subscribe((data) => {
this.targetState = this.getTargetState(data)
})
this.registerCharacteristic({
characteristicType: Characteristic.LockCurrentState,
serviceType: Service.LockMechanism,
getValue: (data) => {
const state = getCurrentState(data)
if (state === this.targetState) {
this.targetState = undefined
}
return state
},
})
this.registerCharacteristic({
characteristicType: Characteristic.LockTargetState,
serviceType: Service.LockMechanism,
getValue: (data) => this.getTargetState(data),
setValue: (value) => this.setTargetState(value),
})
}
setTargetState(state: any) {
const {
Characteristic: { LockTargetState: State },
} = hap,
command = state === State.SECURED ? 'lock' : 'unlock'
this.targetState =
state === getCurrentState(this.device.data) ? undefined : state
return this.device.sendCommand(`lock.${command}`)
}
getTargetState(data: RingDeviceData) {
return this.targetState || getCurrentState(data)
}
}