generated from homebridge/homebridge-plugin-template
-
Notifications
You must be signed in to change notification settings - Fork 16
/
platform.ts
384 lines (345 loc) · 14.2 KB
/
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
378
379
380
381
382
383
384
import { readFileSync, writeFileSync } from 'fs'
import { APIEvent, Service, Characteristic } from 'homebridge'
import type {
API,
DynamicPlatformPlugin,
Logger,
PlatformAccessory,
PlatformConfig,
} from 'homebridge'
import { PLATFORM_NAME, PLUGIN_NAME } from './settings'
import { LgAirConditionerPlatformAccessory } from './platformAccessory'
import ThinqApi from './thinq/api'
import ThinqAuth, { ThinqAuthConfig } from './thinq/auth'
import { ThinqConfig, PartialThinqConfig } from './thinq/thinqConfig'
const AUTH_REFRESH_INTERVAL = 10 * 60 * 1000 // 10 minutes
export type HomebridgeLgThinqPlatformConfig = {
remove_offline_devices_on_boot?: boolean
} & ThinqAuthConfig
/**
* HomebridgePlatform
* This class is the main constructor for your plugin, this is where you should
* parse the user config and discover/register accessories with Homebridge.
*/
export class HomebridgeLgThinqPlatform implements DynamicPlatformPlugin {
public readonly Service: typeof Service = this.api.hap.Service
public readonly Characteristic: typeof Characteristic =
this.api.hap.Characteristic
// this is used to track restored cached accessories
public readonly accessories: PlatformAccessory[] = []
public thinqAuth: ThinqAuth | undefined
public thinqApi: ThinqApi | undefined
private didFinishLaunching: Promise<void>
private handleFinishedLaunching?: () => void
constructor(
public readonly log: Logger,
public readonly config: PlatformConfig & HomebridgeLgThinqPlatformConfig,
public readonly api: API,
) {
this.didFinishLaunching = new Promise((resolve) => {
// Store the resolver locally.
// Steps that depend on this can `await didFinishLaunching`.
// When Homebridge is finishes launching, this will be called to resolve.
this.handleFinishedLaunching = resolve
})
this.log.debug('Finished initializing platform:', this.config.name)
this.initialize()
// When this event is fired it means Homebridge has restored all cached accessories from disk.
// Dynamic Platform plugins should only register new accessories after this event was fired,
// in order to ensure they weren't added to homebridge already. This event can also be used
// to start discovery of new accessories.
this.api.on(APIEvent.DID_FINISH_LAUNCHING, () => {
this.log.debug('Executed didFinishLaunching callback')
if (this.handleFinishedLaunching) {
this.handleFinishedLaunching()
}
})
}
/**
* This function is invoked when homebridge restores cached accessories from disk at startup.
* It should be used to setup event handlers for characteristics and update respective values.
*/
configureAccessory(accessory: PlatformAccessory) {
this.log.debug('Restoring accessory from cache:', accessory.displayName)
// add the restored accessory to the accessories cache so we can track if it has already been registered
this.accessories.push(accessory)
}
async initialize() {
try {
const thinqConfig = await this.initializeThinqConfig()
this.thinqAuth = ThinqAuth.fromConfig(this.log, thinqConfig, this.config)
this.thinqApi = new ThinqApi(thinqConfig, this.thinqAuth)
await this.inititializeAuth()
this.startRefreshTokenInterval()
this.discoverDevicesWhenReady()
} catch (error) {
this.log.error('Error initializing platform', `${error}`)
this.log.debug('Full error', error)
}
}
async initializeThinqConfig() {
const partialThinqConfig: PartialThinqConfig = {
// If a user installs via the homebridge UI, these values
// may not be guaranteed
countryCode: this.config.country_code || 'US',
languageCode: this.config.language_code || 'en-US',
}
const gatewayUri = await ThinqApi.getGatewayUri(partialThinqConfig)
const thinqConfig: ThinqConfig = {
apiBaseUri: gatewayUri.result.thinq2Uri,
accessTokenUri: `https://${partialThinqConfig.countryCode.toLowerCase()}.lgeapi.com/oauth/1.0/oauth2/token`,
redirectUri: `https://kr.m.lgaccount.com/login/iabClose`,
authorizationUri: `${gatewayUri.result.empSpxUri}/login/signIn`,
countryCode: partialThinqConfig.countryCode,
languageCode: partialThinqConfig.languageCode,
}
return thinqConfig
}
async inititializeAuth() {
this.updateAndReplaceConfig()
const redirectedUrl = this.config.auth_redirected_url as unknown
if (this.thinqAuth?.getIsLoggedIn()) {
this.log.info('Already logged into ThinQ')
await this.refreshAuth()
} else if (typeof redirectedUrl === 'string' && redirectedUrl !== '') {
this.log.info('Initiating auth with provided redirect URL')
try {
await this.thinqAuth!.processLoginResult(redirectedUrl)
this.updateAndReplaceConfig()
} catch (error) {
this.log.error('Error setting refresh token', error)
throw error
}
} else {
this.log.debug(
'Redirected URL not stored in config and no existing auth state. Skipping initializeAuth().',
)
throw new Error('Auth not ready yet, please log in.')
}
}
private startRefreshTokenInterval() {
setInterval(() => this.refreshAuth(), AUTH_REFRESH_INTERVAL)
}
private async refreshAuth() {
this.log.debug('refreshAuth()')
try {
await this.thinqAuth!.initiateRefreshToken()
this.updateAndReplaceConfig()
} catch (error) {
if (
error instanceof Object &&
// @ts-expect-error TS2339 from upgrade to Typescript 4.5, proven to work on-device regardless
error.body instanceof Object &&
// @ts-expect-error TS2339 from upgrade to Typescript 4.5, proven to work on-device regardless
error.body.error instanceof Object &&
// @ts-expect-error TS2339 from upgrade to Typescript 4.5, proven to work on-device regardless
error.body.error.code === 'LG.OAUTH.EC.4001'
) {
this.log.error(
'Login credentials have expired!\n\n' +
'Please re-configure the plugin:\n' +
' 1. Login again\n' +
' 2. Update the "redirected URL" in the config\n' +
' 3. Restart Homebridge\n',
)
this.thinqAuth?.clearStoredToken()
this.updateAndReplaceConfig()
} else {
this.log.error('Failed to refresh token', `${error}`)
}
}
}
private async discoverDevicesWhenReady() {
await this.didFinishLaunching
// run the method to discover / register your devices as accessories
try {
await this.discoverDevices()
} catch (error) {
const errorString = `${error}`
this.log.error('Error discovering devices', `${error}`)
if (errorString.includes('status code 400')) {
this.log.error(
'This can sometimes indicate the LG App has new agreements you must accept. If so:\n' +
' 1. Open the native LG App and sign in as usual\n' +
' 2. If an agreement pops up, review and accept it if appropriate\n' +
' 3. Restart Homebridge\n' +
'If there are no agreements to accept, try restarting Homebridge.\n' +
"If that still doesn't work, delete the config for this accessory and restart Homebridge to initiate a full reset.",
)
}
}
}
/**
* This is an example method showing how to register discovered accessories.
* Accessories must only be registered once, previously created accessories
* must not be registered again to prevent "duplicate UUID" errors.
*/
async discoverDevices() {
if (!this.thinqAuth?.getIsLoggedIn()) {
this.log.info('Not logged in; skipping discoverDevices()')
return
}
const dashboardResponse = await this.thinqApi!.getDashboard()
this.log.debug('dashboardResponse', dashboardResponse)
this.log.info(
`Discover found ${dashboardResponse.result.item.length} total devices`,
)
const devices = dashboardResponse.result.item.filter((item) => {
if (typeof item !== 'object') {
this.log.debug('Item is not an object, ignoring')
return false
}
if (item.deviceType !== 401) {
// Air Conditioners have a 401 device type
this.log.debug(`deviceType is ${item.deviceType}, ignoring`)
return false
}
if (item.platformType !== 'thinq2') {
this.log.error(
`"${item.alias}" (model ${item.modelName}) uses the ${item.platformType} platform, which is not supported. ` +
`Please see https://github.com/sman591/homebridge-lg-thinq-ac/issues/4 for updates.`,
)
return false
}
return true
})
// Keep a running list of all accessories we register or know were already registered
const matchedAccessories: PlatformAccessory[] = []
// loop over the discovered devices and register each one if it has not already been registered
for (const device of devices) {
// generate a unique id for the accessory this should be generated from
// something globally unique, but constant, for example, the device serial
// number or MAC address
const uuid = this.api.hap.uuid.generate(device.deviceId)
const matchingAccessories = this.accessories.filter(
(accessory) => accessory.UUID === uuid,
)
if (matchingAccessories.length > 0) {
this.log.info('Existing accessory:', device.alias)
// check that the device has not already been registered by checking the
// cached devices we stored in the `configureAccessory` method above
for (const accessory of matchingAccessories) {
accessory.context.device = device
matchedAccessories.push(accessory)
new LgAirConditionerPlatformAccessory(this, accessory)
}
} else if (!device.online) {
this.log.info(
`Accessory "${device.alias}" is offline and will not be added.`,
)
} else {
this.log.info('Registering new accessory:', device.alias)
// create a new accessory
const accessory = new this.api.platformAccessory(device.alias, uuid)
// store a copy of the device object in the `accessory.context`
// the `context` property can be used to store any data about the accessory you may need
accessory.context.device = device
// create the accessory handler
// this is imported from `platformAccessory.ts`
new LgAirConditionerPlatformAccessory(this, accessory)
// link the accessory to your platform
this.api.registerPlatformAccessories(PLUGIN_NAME, PLATFORM_NAME, [
accessory,
])
// push into accessory cache
this.accessories.push(accessory)
matchedAccessories.push(accessory)
}
}
// Unregister offline accessories if desired (set by config)
if (this.config.remove_offline_devices_on_boot) {
this.log.info('Attempting to remove offline devices from HomeKit...')
// Only remove once when config is enabled
this.config.remove_offline_devices_on_boot = false
this.updateAndReplaceConfig()
let wasADeviceRemoved = false
this.accessories.forEach((accessory) => {
const deviceContext = accessory.context?.device
if (deviceContext?.online === false) {
this.log.info(
`Removing offline device "${accessory.displayName}" from HomeKit. If you need this device again, please restart Homebridge.`,
)
// @ts-expect-error This is a hack
const jsInstance = accessory.jsInstance as
| LgAirConditionerPlatformAccessory
| undefined
if (
jsInstance &&
jsInstance instanceof LgAirConditionerPlatformAccessory
) {
jsInstance?.unregisterAccessory()
wasADeviceRemoved = true
} else {
this.log.warn(
`Device "${accessory.displayName}" is offline, but could not be removed. Please file a bug with homebridge-lg-thinq-ac.`,
)
}
}
})
if (!wasADeviceRemoved) {
this.log.warn(
'remove_offline_devices_on_boot was attempted but no offline devices were found',
)
}
}
// Unregister accessories that weren't matched from the API response.
// This helps clean up devices which:
// - You no longer have connected to your account
// - Were mistakenly registered in an older version of this plugin but aren't actually supported
this.accessories.forEach((accessory) => {
const didMatchAccessory = matchedAccessories.some(
(matchedAccessory) => matchedAccessory.UUID === accessory.UUID,
)
if (!didMatchAccessory) {
this.log.info(
'Un-registering unknown accessory:',
accessory.displayName,
)
this.api.unregisterPlatformAccessories(PLUGIN_NAME, PLATFORM_NAME, [
accessory,
])
}
})
}
getRefreshIntervalMinutes() {
const fallbackDefault = 1
try {
const parsedValue = parseFloat(this.config.refresh_interval)
if (parsedValue > 0.1 && parsedValue < 100000) {
return parsedValue
}
} catch (error) {
this.log.error('Failed to parse refresh_interval from config', error)
}
this.log.debug('Using fallback refresh interval')
return fallbackDefault
}
updateAndReplaceConfig() {
const configPath = this.api.user.configPath()
const configString = readFileSync(configPath).toString()
try {
const config = JSON.parse(configString)
// this.log.debug('config', config) DO NOT COMMIT THIS -- it could accidentally leak into GitHub issue reports
const platforms = config.platforms.filter(
(platform: Record<string, string>) =>
platform.platform === 'LgThinqAirConditioner',
)
const authConfig = this.thinqAuth!.serializeToConfig()
const generalConfig = {
remove_offline_devices_on_boot:
this.config.remove_offline_devices_on_boot || false,
}
const platformConfig: Required<HomebridgeLgThinqPlatformConfig> = {
...authConfig,
...generalConfig,
}
for (const platform of platforms) {
Object.assign(platform, platformConfig)
}
writeFileSync(configPath, JSON.stringify(config))
} catch (error) {
this.log.error('Failed to store updated config', `${error}`)
this.log.debug('Full error:', error)
}
}
}