-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.ts
206 lines (192 loc) · 7.11 KB
/
index.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
import os from 'node:os'
import {
calculateCodeChallenge,
CODE_CHALLENGE_METHOD,
generateCodeVerifier,
} from './authCode'
import { discoverGatewayIP } from './mdnsDiscovery'
import { closeWebSocket, initializeWebSocket } from './ws'
import type { Home } from './types/Home'
import type { Event } from './types/event/Event'
import hub from './api/hub'
import devices from './api/devices'
import lights from './api/lights'
import outlets from './api/outlets'
import controllers from './api/controllers'
import speakers from './api/speakers'
import blinds from './api/blinds'
import airPurifiers from './api/airPurifiers'
import repeaters from './api/repeaters'
import motionSensors from './api/motionSensors'
import environmentSensors from './api/environmentSensors'
import openCloseSensors from './api/openCloseSensors'
import deviceSets from './api/deviceSets'
import rooms from './api/rooms'
import scenes from './api/scenes'
import music from './api/music'
import users from './api/users'
export type DirigeraClient = Awaited<ReturnType<typeof createDirigeraClient>>
export type { AirPurifier } from './types/device/AirPurifier'
export type { Blinds } from './types/device/Blinds'
export type { Capabilities } from './types/Capabilities'
export type { Controller } from './types/device/Controller'
export type { Device } from './types/device/Device'
export type { DeviceSet } from './types/DeviceSet'
export type { EnvironmentSensor } from './types/device/EnvironmentSensor'
export type { Home } from './types/Home'
export type { Hub } from './types/device/Hub'
export type { Light } from './types/device/Light'
export type { MotionSensor } from './types/device/MotionSensor'
export type { Music } from './types/Music'
export type { OpenCloseSensor } from './types/device/OpenCloseSensor'
export type { Outlet } from './types/device/Outlet'
export type { Repeater } from './types/device/Repeater'
export type { Room } from './types/Room'
export type { Scene } from './types/Scene'
export type { Speaker } from './types/device/Speaker'
export type { User } from './types/User'
export type { Event } from './types/event/Event'
export type { DeviceAddedEvent } from './types/event/DeviceAddedEvent'
export type { DeviceConfigurationChangedEvent } from './types/event/DeviceConfigurationChangedEvent'
export type { DeviceDiscoveredEvent } from './types/event/DeviceDiscoveredEvent'
export type { DeviceRemovedEvent } from './types/event/DeviceRemovedEvent'
export type { DeviceSetCreatedEvent } from './types/event/DeviceSetCreatedEvent'
export type { DeviceSetDeletedEvent } from './types/event/DeviceSetDeletedEvent'
export type { DeviceSetUpdatedEvent } from './types/event/DeviceSetUpdatedEvent'
export type { DeviceStateChangedEvent } from './types/event/DeviceStateChangedEvent'
export type { MusicUpdatedEvent } from './types/event/MusicUpdatedEvent'
export type { PingEvent } from './types/event/PingEvent'
export type { PongEvent } from './types/event/PongEvent'
export type { RoomCreatedEvent } from './types/event/RoomCreatedEvent'
export type { RoomDeletedEvent } from './types/event/RoomDeletedEvent'
export type { RoomUpdatedEvent } from './types/event/RoomUpdatedEvent'
export type { SceneCompletedEvent } from './types/event/SceneCompletedEvent'
export type { SceneCreatedEvent } from './types/event/SceneCreatedEvent'
export type { SceneDeletedEvent } from './types/event/SceneDeletedEvent'
export type { SceneTriggeredEvent } from './types/event/SceneTriggeredEvent'
export type { SceneUpdatedEvent } from './types/event/SceneUpdatedEvent'
export type { TerminationEvent } from './types/event/TerminationEvent'
export async function createDirigeraClient({
gatewayIP,
accessToken,
}: {
gatewayIP?: string
accessToken?: string
} = {}) {
const ip = gatewayIP ?? (await discoverGatewayIP())
const { got } = await import('got')
const gotInstance = got.extend({
prefixUrl: `https://${ip}:8443/v1`,
headers: {
...(accessToken ? { authorization: `Bearer ${accessToken}` } : null),
},
https: {
rejectUnauthorized: false,
},
hooks: {
beforeError: [
(error) => {
if (
error.code === 'ERR_NON_2XX_3XX_RESPONSE' &&
error?.response?.body
) {
error.name = 'DirigeraError'
error.message = `${error.response.body}`
}
return error
},
],
},
})
return {
async authenticate({ verbose = false }: { verbose?: boolean } = {}) {
const codeVerifier = generateCodeVerifier()
const codeChallenge = calculateCodeChallenge(codeVerifier)
const { code }: { code: string } = await gotInstance
.get(`oauth/authorize`, {
searchParams: {
audience: 'homesmart.local',
response_type: 'code',
code_challenge: codeChallenge,
code_challenge_method: CODE_CHALLENGE_METHOD,
},
})
.json()
const { default: pRetry } = await import('p-retry')
if (verbose) {
console.log(
'Press the Action Button on the bottom of your Dirigera Hub within 60 seconds.'
)
}
return await pRetry(
async () => {
const { access_token }: { access_token: string } = await gotInstance
.post(`oauth/token`, {
form: {
code,
name: os.hostname(),
grant_type: 'authorization_code',
code_verifier: codeVerifier,
},
})
.json()
if (!access_token) {
throw new Error('Access token is missing.')
}
if (verbose) {
process.stdout.write('\n')
}
return access_token
},
{
retries: 59,
minTimeout: 1000,
factor: 1,
onFailedAttempt: (error) => {
if (verbose) {
process.stdout.write(
`\rTime left: ${String(error.retriesLeft).padStart(2, ' ')} seconds`
)
if (error.retriesLeft === 0) {
process.stdout.write('\n')
}
}
},
}
)
},
async home() {
return await gotInstance.get(`home`).json<Home>()
},
hub: hub(gotInstance),
devices: devices(gotInstance),
lights: lights(gotInstance),
outlets: outlets(gotInstance),
controllers: controllers(gotInstance),
speakers: speakers(gotInstance),
blinds: blinds(gotInstance),
airPurifiers: airPurifiers(gotInstance),
repeaters: repeaters(gotInstance),
motionSensors: motionSensors(gotInstance),
environmentSensors: environmentSensors(gotInstance),
openCloseSensors: openCloseSensors(gotInstance),
deviceSets: deviceSets(gotInstance),
rooms: rooms(gotInstance),
scenes: scenes(gotInstance),
music: music(gotInstance),
users: users(gotInstance),
startListeningForUpdates(callback: (updateEvent: Event) => void) {
if (!accessToken) {
throw new Error('Access token is missing.')
}
initializeWebSocket({
ip,
accessToken,
callback,
})
},
stopListeningForUpdates() {
closeWebSocket()
},
}
}