-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathindex.js
executable file
·214 lines (185 loc) · 7.3 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
const axios = require('axios')
const { CronJob } = require('cron')
const DEFAULT_REQUEST_PARAMS = {
url: 'https://api.nature.global/1/devices',
method: 'GET'
}
const TIMEOUT = 2500
const REGEX_TIMEOUT_ERROR_CODE = /E(?:(?:SOCKET)?TIMEDOUT|CONNABORTED)/
let version
let Service
let Characteristic
module.exports = homebridge => {
version = homebridge.version
Service = homebridge.hap.Service
Characteristic = homebridge.hap.Characteristic
homebridge.registerAccessory('homebridge-nature-remo-sensor', 'remo-sensor', NatureRemoSensor, true)
}
class NatureRemoSensor {
constructor (log, config, api) {
log('homebridge API version: ' + version)
log('NatureRemo Init')
this.log = log
this.config = config
this.name = config.name
this.mini = config.mini ?? false
this.deviceName = config.deviceName
this.accessToken = config.accessToken
this.schedule = config.schedule || '*/5 * * * *'
this.cache = config.cache ?? false
this.previousSensorValue = null
const sensors = config.sensors ?? {}
const isEnabledTemperature = sensors.temperature !== false
const isEnabledHumidity = this.mini !== true && sensors.humidity !== false
const isEnabledLight = this.mini !== true && sensors.light !== false
if (this.mini) {
log('Humidity and light sensors are disabled in NatureRemo mini')
}
this.informationService = new Service.AccessoryInformation()
this.temperatureSensorService = isEnabledTemperature ? new Service.TemperatureSensor(config.name) : null
this.humiditySensorService = isEnabledHumidity ? new Service.HumiditySensor(config.name) : null
this.lightSensorService = isEnabledLight ? new Service.LightSensor(config.name) : null
this.job = new CronJob({
cronTime: this.schedule,
onTick: () => {
this.log('> [Schedule]')
this.request().then((data) => {
this.previousSensorValue = this.parseResponseData(data)
const { humidity, temperature, light } = this.previousSensorValue
if (this.temperatureSensorService) {
this.log(`>>> [Update] temperature => ${temperature}`)
this.temperatureSensorService.getCharacteristic(Characteristic.CurrentTemperature).updateValue(temperature)
}
if (this.humiditySensorService) {
this.log(`>>> [Update] humidity => ${humidity}`)
this.humiditySensorService.getCharacteristic(Characteristic.CurrentRelativeHumidity).updateValue(humidity)
}
if (this.lightSensorService) {
this.log(`>>> [Update] light => ${light}`)
this.lightSensorService.getCharacteristic(Characteristic.CurrentAmbientLightLevel).updateValue(light)
}
this.log('> [Schedule] finish')
}).catch((error) => {
this.log(`>>> [Error] "${error}"`)
this.previousSensorValue = null
if (this.temperatureSensorService) {
this.temperatureSensorService.getCharacteristic(Characteristic.CurrentTemperature).updateValue(error)
}
if (this.humiditySensorService) {
this.humiditySensorService.getCharacteristic(Characteristic.CurrentRelativeHumidity).updateValue(error)
}
if (this.lightSensorService) {
this.lightSensorService.getCharacteristic(Characteristic.CurrentAmbientLightLevel).updateValue(error)
}
this.log('> [Schedule] finish')
})
},
runOnInit: true
})
this.job.start()
this.getTemperature = this.createGetSensorFunc('temperature')
this.getHumidity = this.createGetSensorFunc('humidity')
this.getLight = this.createGetSensorFunc('light')
}
request (option) {
if (!this.runningPromise) {
const options = Object.assign({}, DEFAULT_REQUEST_PARAMS, {
headers: {
authorization: `Bearer ${this.accessToken}`
}
}, typeof option === 'object' ? option : {})
this.log('>> [request] start')
this.runningPromise = axios(options)
.then((response) => {
const limit = response.headers?.['x-rate-limit-limit'] ?? 0
const remaining = response.headers?.['x-rate-limit-remaining'] ?? 0
this.log(`>>> [response] status: ${response.status}, limit: ${remaining}/${limit}`)
delete this.runningPromise
return response.data
})
.catch((error) => {
const response = error?.response
const limit = response?.headers?.['x-rate-limit-limit'] ?? 0
const remaining = response?.headers?.['x-rate-limit-remaining'] ?? 0
this.log(`>>> [response] status: ${response?.status ?? 'NONE'}, limit: ${remaining}/${limit}`)
delete this.runningPromise
throw error
})
}
return this.runningPromise
}
parseResponseData (responseData) {
let humidity = null
let temperature = null
let light = null
let data
if (this.deviceName) {
data = (responseData || []).find((device, i) => {
return device.name === this.deviceName
})
}
data = data ?? (responseData || [])[0]
if (data && data.newest_events) {
if (data.newest_events.hu) {
humidity = data.newest_events.hu.val
}
if (data.newest_events.te) {
temperature = data.newest_events.te.val
}
if (data.newest_events.il) {
light = data.newest_events.il.val
}
}
return { humidity, temperature, light }
}
createGetSensorFunc (type) {
return (callback) => {
this.log(`> [Getting] ${type}`)
const previousSensorValue = this.previousSensorValue?.[type]
if (this.cache && typeof previousSensorValue === 'number') {
this.log(`>>> [Getting] ${type} => ${previousSensorValue} (from cache)`)
callback(null, previousSensorValue)
} else {
this.request({ timeout: TIMEOUT }).then((data) => {
const value = this.parseResponseData(data)?.[type]
this.log(`>>> [Getting] ${type} => ${value}`)
callback(null, value)
}).catch((error) => {
this.log(`>>> [Error] "${error}"`)
if (REGEX_TIMEOUT_ERROR_CODE.test(error.code) && typeof previousSensorValue === 'number') {
callback(null, previousSensorValue)
} else {
callback(error)
}
})
}
}
}
getServices () {
this.log(`start homebridge Server ${this.name}`)
this.informationService
.setCharacteristic(Characteristic.Manufacturer, 'Nature')
.setCharacteristic(Characteristic.Model, 'Remo')
.setCharacteristic(Characteristic.SerialNumber, '031-45-154')
const services = [this.informationService]
if (this.temperatureSensorService) {
this.temperatureSensorService
.getCharacteristic(Characteristic.CurrentTemperature)
.on('get', this.getTemperature.bind(this))
services.push(this.temperatureSensorService)
}
if (this.humiditySensorService) {
this.humiditySensorService
.getCharacteristic(Characteristic.CurrentRelativeHumidity)
.on('get', this.getHumidity.bind(this))
services.push(this.humiditySensorService)
}
if (this.lightSensorService) {
this.lightSensorService
.getCharacteristic(Characteristic.CurrentAmbientLightLevel)
.on('get', this.getLight.bind(this))
services.push(this.lightSensorService)
}
return services
}
}