forked from alexryd/homebridge-shelly
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdevice-wrapper.js
121 lines (102 loc) · 2.89 KB
/
device-wrapper.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
const { handleFailedRequest } = require('./util/error-handlers')
module.exports = homebridge => {
class DeviceWrapper {
constructor(platform, device, config, ...accessories) {
this.platform = platform
this.device = device
this.config = config || {}
this.accessories = accessories
if (config && config.username && config.password) {
device.setAuthCredentials(config.username, config.password)
}
if (config && config.name) {
device.name = config.name
}
device
.on('online', this.deviceOnlineHandler, this)
.on('offline', this.deviceOfflineHandler, this)
.on('change:host', this.changeHostHandler, this)
.on('change:mode', this.changeModeHandler, this)
if (device.online) {
this.loadSettings()
}
}
get platformAccessories() {
return this.accessories.map(a => a.platformAccessory)
}
deviceOnlineHandler() {
this.platform.log.debug(
'Device',
this.device.type,
this.device.id,
'came online'
)
this.loadSettings()
}
deviceOfflineHandler() {
this.platform.log.debug(
'Device',
this.device.type,
this.device.id,
'went offline'
)
}
changeHostHandler(newValue, oldValue) {
this.platform.log.debug(
'Device',
this.device.type,
this.device.id,
'changed host from',
oldValue,
'to',
newValue
)
homebridge.updatePlatformAccessories(this.platformAccessories)
}
changeModeHandler(newValue, oldValue) {
this.platform.log.debug(
'Device',
this.device.type,
this.device.id,
'changed mode from',
oldValue,
'to',
newValue
)
// re-add the device since we need to replace its accessories
this.platform.removeDevice(this.device)
this.platform.addDevice(this.device)
}
loadSettings() {
const d = this.device
if (!d.settings) {
this.platform.log.debug('Loading settings for device', d.type, d.id)
d.getSettings()
.then(settings => {
d.settings = settings
})
.catch(error => {
handleFailedRequest(
this.platform.log,
d,
error,
'Failed to load device settings'
)
d.online = false
})
}
}
destroy() {
this.device
.removeListener('online', this.deviceOnlineHandler, this)
.removeListener('offline', this.deviceOfflineHandler, this)
.removeListener('change:host', this.changeHostHandler, this)
.removeListener('change:mode', this.changeModeHandler, this)
for (const accessory of this.accessories) {
accessory.detach()
}
this.accessories.length = 0
}
}
return DeviceWrapper
}