@homelib/xiaomi 0.0.0-wip.01265bf1cc90
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +19 -0
- package/README.md +26 -0
- package/bld/library/backend/client.d.ts +73 -0
- package/bld/library/backend/client.js +490 -0
- package/bld/library/backend/client.js.map +1 -0
- package/bld/library/backend/constants.d.ts +7 -0
- package/bld/library/backend/constants.js +11 -0
- package/bld/library/backend/constants.js.map +1 -0
- package/bld/library/backend/index.d.ts +3 -0
- package/bld/library/backend/index.js +4 -0
- package/bld/library/backend/index.js.map +1 -0
- package/bld/library/backend/oauth.d.ts +24 -0
- package/bld/library/backend/oauth.js +121 -0
- package/bld/library/backend/oauth.js.map +1 -0
- package/bld/library/binding.d.ts +44 -0
- package/bld/library/binding.js +212 -0
- package/bld/library/binding.js.map +1 -0
- package/bld/library/cloud/client.d.ts +27 -0
- package/bld/library/cloud/client.js +109 -0
- package/bld/library/cloud/client.js.map +1 -0
- package/bld/library/cloud/constants.d.ts +9 -0
- package/bld/library/cloud/constants.js +11 -0
- package/bld/library/cloud/constants.js.map +1 -0
- package/bld/library/cloud/device.d.ts +84 -0
- package/bld/library/cloud/device.js +686 -0
- package/bld/library/cloud/device.js.map +1 -0
- package/bld/library/cloud/index.d.ts +5 -0
- package/bld/library/cloud/index.js +6 -0
- package/bld/library/cloud/index.js.map +1 -0
- package/bld/library/cloud/mqtt.d.ts +69 -0
- package/bld/library/cloud/mqtt.js +517 -0
- package/bld/library/cloud/mqtt.js.map +1 -0
- package/bld/library/cloud/transport.d.ts +8 -0
- package/bld/library/cloud/transport.js +34 -0
- package/bld/library/cloud/transport.js.map +1 -0
- package/bld/library/command.d.ts +6 -0
- package/bld/library/command.js +6 -0
- package/bld/library/command.js.map +1 -0
- package/bld/library/configuration.d.ts +62 -0
- package/bld/library/configuration.js +303 -0
- package/bld/library/configuration.js.map +1 -0
- package/bld/library/device.d.ts +69 -0
- package/bld/library/device.js +266 -0
- package/bld/library/device.js.map +1 -0
- package/bld/library/devices/air-conditioner.d.ts +48 -0
- package/bld/library/devices/air-conditioner.js +155 -0
- package/bld/library/devices/air-conditioner.js.map +1 -0
- package/bld/library/devices/command-effect.d.ts +35 -0
- package/bld/library/devices/command-effect.js +269 -0
- package/bld/library/devices/command-effect.js.map +1 -0
- package/bld/library/devices/dehumidifier.d.ts +41 -0
- package/bld/library/devices/dehumidifier.js +124 -0
- package/bld/library/devices/dehumidifier.js.map +1 -0
- package/bld/library/devices/fan.d.ts +37 -0
- package/bld/library/devices/fan.js +135 -0
- package/bld/library/devices/fan.js.map +1 -0
- package/bld/library/devices/index.d.ts +9 -0
- package/bld/library/devices/index.js +10 -0
- package/bld/library/devices/index.js.map +1 -0
- package/bld/library/devices/light.d.ts +22 -0
- package/bld/library/devices/light.js +112 -0
- package/bld/library/devices/light.js.map +1 -0
- package/bld/library/devices/pet-feeder.d.ts +36 -0
- package/bld/library/devices/pet-feeder.js +116 -0
- package/bld/library/devices/pet-feeder.js.map +1 -0
- package/bld/library/devices/placeholder.d.ts +3 -0
- package/bld/library/devices/placeholder.js +4 -0
- package/bld/library/devices/placeholder.js.map +1 -0
- package/bld/library/devices/temperature-humidity-sensor.d.ts +14 -0
- package/bld/library/devices/temperature-humidity-sensor.js +56 -0
- package/bld/library/devices/temperature-humidity-sensor.js.map +1 -0
- package/bld/library/devices/value-range.d.ts +2 -0
- package/bld/library/devices/value-range.js +6 -0
- package/bld/library/devices/value-range.js.map +1 -0
- package/bld/library/endpoint-connection.d.ts +168 -0
- package/bld/library/endpoint-connection.js +510 -0
- package/bld/library/endpoint-connection.js.map +1 -0
- package/bld/library/index.d.ts +26 -0
- package/bld/library/index.js +33 -0
- package/bld/library/index.js.map +1 -0
- package/bld/library/local/certificate.d.ts +31 -0
- package/bld/library/local/certificate.js +298 -0
- package/bld/library/local/certificate.js.map +1 -0
- package/bld/library/local/controller.d.ts +70 -0
- package/bld/library/local/controller.js +498 -0
- package/bld/library/local/controller.js.map +1 -0
- package/bld/library/local/discovery.d.ts +29 -0
- package/bld/library/local/discovery.js +321 -0
- package/bld/library/local/discovery.js.map +1 -0
- package/bld/library/local/index.d.ts +6 -0
- package/bld/library/local/index.js +7 -0
- package/bld/library/local/index.js.map +1 -0
- package/bld/library/local/message.d.ts +11 -0
- package/bld/library/local/message.js +128 -0
- package/bld/library/local/message.js.map +1 -0
- package/bld/library/local/mqtt.d.ts +113 -0
- package/bld/library/local/mqtt.js +1074 -0
- package/bld/library/local/mqtt.js.map +1 -0
- package/bld/library/local/routed-message-client.d.ts +49 -0
- package/bld/library/local/routed-message-client.js +326 -0
- package/bld/library/local/routed-message-client.js.map +1 -0
- package/bld/library/miot/index.d.ts +4 -0
- package/bld/library/miot/index.js +5 -0
- package/bld/library/miot/index.js.map +1 -0
- package/bld/library/miot/matcher.d.ts +84 -0
- package/bld/library/miot/matcher.js +326 -0
- package/bld/library/miot/matcher.js.map +1 -0
- package/bld/library/miot/request.d.ts +33 -0
- package/bld/library/miot/request.js +57 -0
- package/bld/library/miot/request.js.map +1 -0
- package/bld/library/miot/result.d.ts +8 -0
- package/bld/library/miot/result.js +5 -0
- package/bld/library/miot/result.js.map +1 -0
- package/bld/library/miot/spec.d.ts +96 -0
- package/bld/library/miot/spec.js +86 -0
- package/bld/library/miot/spec.js.map +1 -0
- package/bld/library/provider.d.ts +78 -0
- package/bld/library/provider.js +600 -0
- package/bld/library/provider.js.map +1 -0
- package/bld/library/session-manager.d.ts +34 -0
- package/bld/library/session-manager.js +177 -0
- package/bld/library/session-manager.js.map +1 -0
- package/bld/library/session.d.ts +36 -0
- package/bld/library/session.js +370 -0
- package/bld/library/session.js.map +1 -0
- package/bld/library/storage.d.ts +2 -0
- package/bld/library/storage.js +66 -0
- package/bld/library/storage.js.map +1 -0
- package/bld/library/terminal/bindings.d.ts +3 -0
- package/bld/library/terminal/bindings.js +306 -0
- package/bld/library/terminal/bindings.js.map +1 -0
- package/bld/library/terminal/index.d.ts +2 -0
- package/bld/library/terminal/index.js +3 -0
- package/bld/library/terminal/index.js.map +1 -0
- package/bld/library/terminal/provider-details.d.ts +3 -0
- package/bld/library/terminal/provider-details.js +477 -0
- package/bld/library/terminal/provider-details.js.map +1 -0
- package/package.json +29 -0
- package/src/library/backend/client.ts +737 -0
- package/src/library/backend/constants.ts +17 -0
- package/src/library/backend/index.ts +3 -0
- package/src/library/backend/oauth.ts +170 -0
- package/src/library/binding.ts +387 -0
- package/src/library/cloud/client.ts +155 -0
- package/src/library/cloud/constants.ts +19 -0
- package/src/library/cloud/device.ts +938 -0
- package/src/library/cloud/index.ts +5 -0
- package/src/library/cloud/mqtt.ts +671 -0
- package/src/library/cloud/transport.ts +46 -0
- package/src/library/command.ts +7 -0
- package/src/library/configuration.ts +480 -0
- package/src/library/device.ts +601 -0
- package/src/library/devices/air-conditioner.ts +171 -0
- package/src/library/devices/command-effect.ts +425 -0
- package/src/library/devices/dehumidifier.ts +131 -0
- package/src/library/devices/fan.ts +140 -0
- package/src/library/devices/index.ts +9 -0
- package/src/library/devices/light.ts +119 -0
- package/src/library/devices/pet-feeder.ts +129 -0
- package/src/library/devices/placeholder.ts +3 -0
- package/src/library/devices/temperature-humidity-sensor.ts +49 -0
- package/src/library/devices/value-range.ts +14 -0
- package/src/library/endpoint-connection.ts +841 -0
- package/src/library/index.ts +71 -0
- package/src/library/local/certificate.ts +401 -0
- package/src/library/local/controller.ts +693 -0
- package/src/library/local/discovery.ts +485 -0
- package/src/library/local/index.ts +6 -0
- package/src/library/local/message.ts +174 -0
- package/src/library/local/mqtt.ts +1555 -0
- package/src/library/local/routed-message-client.ts +377 -0
- package/src/library/miot/index.ts +4 -0
- package/src/library/miot/matcher.ts +683 -0
- package/src/library/miot/request.ts +70 -0
- package/src/library/miot/result.ts +14 -0
- package/src/library/miot/spec.ts +114 -0
- package/src/library/provider.ts +745 -0
- package/src/library/session-manager.ts +224 -0
- package/src/library/session.ts +528 -0
- package/src/library/storage.ts +83 -0
- package/src/library/terminal/bindings.tsx +692 -0
- package/src/library/terminal/index.ts +2 -0
- package/src/library/terminal/provider-details.tsx +871 -0
|
@@ -0,0 +1,737 @@
|
|
|
1
|
+
import * as x from 'x-value';
|
|
2
|
+
|
|
3
|
+
import type {
|
|
4
|
+
MiotInvokeActionRequest,
|
|
5
|
+
MiotProperty,
|
|
6
|
+
MiotSetPropertyRequest,
|
|
7
|
+
} from '../miot/index.js';
|
|
8
|
+
|
|
9
|
+
import {
|
|
10
|
+
BACKEND_API_TIMEOUT,
|
|
11
|
+
type CloudServer,
|
|
12
|
+
DEFAULT_CLOUD_SERVER,
|
|
13
|
+
OAUTH2_CLIENT_ID,
|
|
14
|
+
getBackendApiHost,
|
|
15
|
+
} from './constants.js';
|
|
16
|
+
|
|
17
|
+
const HOME_PAGE_SIZE = 150;
|
|
18
|
+
const DEVICE_REQUEST_SIZE = 150;
|
|
19
|
+
const DEVICE_PAGE_SIZE = 200;
|
|
20
|
+
|
|
21
|
+
const BackendApiResponse = x.object({
|
|
22
|
+
code: x.number,
|
|
23
|
+
message: x.string.optional(),
|
|
24
|
+
result: x.unknown.optional(),
|
|
25
|
+
});
|
|
26
|
+
|
|
27
|
+
const BackendPropertyResultValue = x.object({
|
|
28
|
+
did: x.string,
|
|
29
|
+
siid: x.number,
|
|
30
|
+
piid: x.number,
|
|
31
|
+
value: x.unknown.optional(),
|
|
32
|
+
code: x.number,
|
|
33
|
+
});
|
|
34
|
+
|
|
35
|
+
const BackendActionResultValue = x.object({
|
|
36
|
+
code: x.number,
|
|
37
|
+
});
|
|
38
|
+
|
|
39
|
+
export class BackendClient {
|
|
40
|
+
readonly uuid: string;
|
|
41
|
+
|
|
42
|
+
readonly cloudServer: CloudServer;
|
|
43
|
+
|
|
44
|
+
private token: string;
|
|
45
|
+
|
|
46
|
+
private readonly apiUrl: string;
|
|
47
|
+
|
|
48
|
+
constructor(options: BackendClientOptions) {
|
|
49
|
+
this.uuid = options.uuid;
|
|
50
|
+
this.cloudServer = options.cloudServer ?? DEFAULT_CLOUD_SERVER;
|
|
51
|
+
this.token = options.accessToken;
|
|
52
|
+
this.apiUrl = `https://${getBackendApiHost(this.cloudServer)}`;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
get accessToken(): string {
|
|
56
|
+
return this.token;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
updateAccessToken(accessToken: string): void {
|
|
60
|
+
this.token = accessToken;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
async discoverDevices(): Promise<BackendDeviceDiscovery> {
|
|
64
|
+
const {userId, homes, locations} = await this.getHomes();
|
|
65
|
+
const homeDeviceMap = await this.getDevicesWithDids([...locations.keys()]);
|
|
66
|
+
const allDeviceMap = await this.getDeviceListPage([]);
|
|
67
|
+
|
|
68
|
+
for (const [did, device] of allDeviceMap) {
|
|
69
|
+
if (locations.has(did)) {
|
|
70
|
+
continue;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
if (device.ownerId === undefined || device.ownerName === undefined) {
|
|
74
|
+
continue;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
const home = getOrCreateSharedDeviceHome(
|
|
78
|
+
homes,
|
|
79
|
+
device.ownerId,
|
|
80
|
+
device.ownerName,
|
|
81
|
+
);
|
|
82
|
+
locations.set(did, {
|
|
83
|
+
source: 'shared-device',
|
|
84
|
+
homeId: home.id,
|
|
85
|
+
homeName: home.name,
|
|
86
|
+
roomId: 'shared-device',
|
|
87
|
+
roomName: 'shared-device',
|
|
88
|
+
});
|
|
89
|
+
homeDeviceMap.set(did, device);
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
const devices = [...homeDeviceMap.values()].map(device => ({
|
|
93
|
+
did: device.did,
|
|
94
|
+
name: device.name,
|
|
95
|
+
model: device.model,
|
|
96
|
+
specType: device.specType,
|
|
97
|
+
online: device.online,
|
|
98
|
+
parentDid: device.parentDid,
|
|
99
|
+
firmwareVersion: device.firmwareVersion,
|
|
100
|
+
...locations.get(device.did),
|
|
101
|
+
}));
|
|
102
|
+
|
|
103
|
+
devices.sort(compareDevices);
|
|
104
|
+
|
|
105
|
+
return {
|
|
106
|
+
userId,
|
|
107
|
+
homes: [...homes.values()]
|
|
108
|
+
.map(home => ({
|
|
109
|
+
id: home.id,
|
|
110
|
+
name: home.name,
|
|
111
|
+
source: home.source,
|
|
112
|
+
userId: home.userId,
|
|
113
|
+
rooms: [...home.rooms.values()].sort(compareNames),
|
|
114
|
+
}))
|
|
115
|
+
.sort(compareNames),
|
|
116
|
+
devices,
|
|
117
|
+
};
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
async getDeviceOnline(did: string): Promise<boolean> {
|
|
121
|
+
const device = (await this.getDeviceListPage([did])).get(did);
|
|
122
|
+
|
|
123
|
+
if (device === undefined) {
|
|
124
|
+
throw new Error(`Cloud device was not returned: ${did}.`);
|
|
125
|
+
} else if (device.online === undefined) {
|
|
126
|
+
throw new Error(`Cloud device ${did} returned invalid online state.`);
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
return device.online;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
async getProperties(
|
|
133
|
+
properties: readonly MiotProperty[],
|
|
134
|
+
): Promise<readonly BackendPropertyResult[]> {
|
|
135
|
+
const result = await this.post('/app/v2/miotspec/prop/get', {
|
|
136
|
+
datasource: 1,
|
|
137
|
+
params: properties,
|
|
138
|
+
});
|
|
139
|
+
|
|
140
|
+
return x.array(BackendPropertyResultValue).satisfies(result);
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
async setProperties(
|
|
144
|
+
requests: readonly MiotSetPropertyRequest[],
|
|
145
|
+
): Promise<readonly BackendPropertyResult[]> {
|
|
146
|
+
const result = await this.post('/app/v2/miotspec/prop/set', {
|
|
147
|
+
params: requests.map(request => ({
|
|
148
|
+
...request.property,
|
|
149
|
+
value: request.value,
|
|
150
|
+
})),
|
|
151
|
+
});
|
|
152
|
+
|
|
153
|
+
return x.array(BackendPropertyResultValue).satisfies(result);
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
async invokeAction(
|
|
157
|
+
request: MiotInvokeActionRequest,
|
|
158
|
+
): Promise<BackendActionResult> {
|
|
159
|
+
const result = await this.post('/app/v2/miotspec/action', {
|
|
160
|
+
params: {
|
|
161
|
+
...request.action,
|
|
162
|
+
// The Xiaomi cloud API accepts action input values without PIIDs.
|
|
163
|
+
in: request.inputs.map(input => input.value),
|
|
164
|
+
},
|
|
165
|
+
});
|
|
166
|
+
|
|
167
|
+
return BackendActionResultValue.satisfies(result);
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
async getCentralCertificate(certificateRequest: string): Promise<string> {
|
|
171
|
+
const result = requireRecord(
|
|
172
|
+
await this.post('/app/v2/ha/oauth/get_central_crt', {
|
|
173
|
+
csr: Buffer.from(certificateRequest).toString('base64'),
|
|
174
|
+
}),
|
|
175
|
+
'central certificate result',
|
|
176
|
+
);
|
|
177
|
+
const certificate = readString(result.cert);
|
|
178
|
+
|
|
179
|
+
if (certificate === undefined) {
|
|
180
|
+
throw new Error('Cloud API returned an invalid central certificate.');
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
return certificate;
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
private async getHomes(): Promise<HomeDiscovery> {
|
|
187
|
+
const result = requireRecord(
|
|
188
|
+
await this.post('/app/v2/homeroom/gethome', {
|
|
189
|
+
limit: HOME_PAGE_SIZE,
|
|
190
|
+
fetch_share: true,
|
|
191
|
+
fetch_share_dev: true,
|
|
192
|
+
plat_form: 0,
|
|
193
|
+
app_ver: 9,
|
|
194
|
+
}),
|
|
195
|
+
'home list result',
|
|
196
|
+
);
|
|
197
|
+
const homes = new Map<string, MutableHome>();
|
|
198
|
+
const locations = new Map<string, DeviceLocation>();
|
|
199
|
+
let userId: string | undefined;
|
|
200
|
+
|
|
201
|
+
for (const [key, source] of [
|
|
202
|
+
['homelist', 'owned'],
|
|
203
|
+
['share_home_list', 'shared-home'],
|
|
204
|
+
] as const) {
|
|
205
|
+
for (const value of readArray(result[key])) {
|
|
206
|
+
const home = readHome(value, source);
|
|
207
|
+
|
|
208
|
+
if (home === undefined) {
|
|
209
|
+
continue;
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
homes.set(getHomeKey(home.source, home.id), home);
|
|
213
|
+
indexHome(home, locations);
|
|
214
|
+
|
|
215
|
+
if (source === 'owned' && userId === undefined) {
|
|
216
|
+
userId = home.userId;
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
const hasMore = result.has_more === true;
|
|
222
|
+
const maxId = readString(result.max_id);
|
|
223
|
+
|
|
224
|
+
if (hasMore && maxId !== undefined) {
|
|
225
|
+
await this.extendHomes(homes, locations, maxId);
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
return {userId, homes, locations};
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
private async extendHomes(
|
|
232
|
+
homes: Map<string, MutableHome>,
|
|
233
|
+
locations: Map<string, DeviceLocation>,
|
|
234
|
+
initialMaxId: string,
|
|
235
|
+
): Promise<void> {
|
|
236
|
+
let maxId: string | undefined = initialMaxId;
|
|
237
|
+
|
|
238
|
+
while (maxId !== undefined) {
|
|
239
|
+
const currentMaxId: string = maxId;
|
|
240
|
+
const result = requireRecord(
|
|
241
|
+
await this.post('/app/v2/homeroom/get_dev_room_page', {
|
|
242
|
+
start_id: currentMaxId,
|
|
243
|
+
limit: HOME_PAGE_SIZE,
|
|
244
|
+
}),
|
|
245
|
+
'home room page result',
|
|
246
|
+
);
|
|
247
|
+
|
|
248
|
+
for (const value of readArray(result.info)) {
|
|
249
|
+
const pageHome = requireRecord(value, 'home room page item');
|
|
250
|
+
const homeId = readIdentifier(pageHome.id);
|
|
251
|
+
const home =
|
|
252
|
+
homeId === undefined ? undefined : getHomeById(homes, homeId);
|
|
253
|
+
|
|
254
|
+
if (home === undefined) {
|
|
255
|
+
continue;
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
mergeHomePage(home, pageHome);
|
|
259
|
+
indexHome(home, locations);
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
const nextMaxId = readString(result.max_id);
|
|
263
|
+
|
|
264
|
+
if (result.has_more !== true) {
|
|
265
|
+
maxId = undefined;
|
|
266
|
+
} else if (nextMaxId === undefined || nextMaxId === currentMaxId) {
|
|
267
|
+
throw new Error('Cloud home pagination returned an invalid cursor.');
|
|
268
|
+
} else {
|
|
269
|
+
maxId = nextMaxId;
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
private async getDevicesWithDids(
|
|
275
|
+
dids: string[],
|
|
276
|
+
): Promise<Map<string, DeviceDetail>> {
|
|
277
|
+
const results = await Promise.all(
|
|
278
|
+
chunk(dids, DEVICE_REQUEST_SIZE).map(batch =>
|
|
279
|
+
this.getDeviceListPage(batch),
|
|
280
|
+
),
|
|
281
|
+
);
|
|
282
|
+
const devices = new Map<string, DeviceDetail>();
|
|
283
|
+
|
|
284
|
+
for (const result of results) {
|
|
285
|
+
for (const [did, device] of result) {
|
|
286
|
+
devices.set(did, device);
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
return devices;
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
private async getDeviceListPage(
|
|
294
|
+
dids: string[],
|
|
295
|
+
): Promise<Map<string, DeviceDetail>> {
|
|
296
|
+
const devices = new Map<string, DeviceDetail>();
|
|
297
|
+
let startDid: string | undefined;
|
|
298
|
+
|
|
299
|
+
while (true) {
|
|
300
|
+
const data: Record<string, unknown> = {
|
|
301
|
+
limit: DEVICE_PAGE_SIZE,
|
|
302
|
+
get_split_device: true,
|
|
303
|
+
get_third_device: true,
|
|
304
|
+
dids,
|
|
305
|
+
};
|
|
306
|
+
|
|
307
|
+
if (startDid !== undefined) {
|
|
308
|
+
data.start_did = startDid;
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
const result = requireRecord(
|
|
312
|
+
await this.post('/app/v2/home/device_list_page', data),
|
|
313
|
+
'device list result',
|
|
314
|
+
);
|
|
315
|
+
|
|
316
|
+
for (const value of readArray(result.list)) {
|
|
317
|
+
const device = readDevice(value);
|
|
318
|
+
|
|
319
|
+
if (device !== undefined) {
|
|
320
|
+
devices.set(device.did, device);
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
const nextStartDid = readString(result.next_start_did);
|
|
325
|
+
|
|
326
|
+
if (result.has_more !== true) {
|
|
327
|
+
break;
|
|
328
|
+
} else if (nextStartDid === undefined || nextStartDid === startDid) {
|
|
329
|
+
throw new Error('Cloud device pagination returned an invalid cursor.');
|
|
330
|
+
} else {
|
|
331
|
+
startDid = nextStartDid;
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
return devices;
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
private post(path: string, data: Record<string, unknown>): Promise<unknown> {
|
|
339
|
+
return withRequestTimeout(
|
|
340
|
+
this.sendPost(path, data),
|
|
341
|
+
`Cloud API request timed out (${path}).`,
|
|
342
|
+
);
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
private async sendPost(
|
|
346
|
+
path: string,
|
|
347
|
+
data: Record<string, unknown>,
|
|
348
|
+
): Promise<unknown> {
|
|
349
|
+
const response = await fetch(`${this.apiUrl}${path}`, {
|
|
350
|
+
method: 'POST',
|
|
351
|
+
headers: {
|
|
352
|
+
'content-type': 'application/json',
|
|
353
|
+
'x-client-bizid': 'haapi',
|
|
354
|
+
'x-client-appid': OAUTH2_CLIENT_ID,
|
|
355
|
+
// Xiaomi's HA API expects no space after "Bearer".
|
|
356
|
+
authorization: `Bearer${this.token}`,
|
|
357
|
+
},
|
|
358
|
+
body: JSON.stringify(data),
|
|
359
|
+
});
|
|
360
|
+
|
|
361
|
+
if (response.status === 401) {
|
|
362
|
+
throw new Error('Cloud API access token was rejected.');
|
|
363
|
+
} else if (!response.ok) {
|
|
364
|
+
throw new Error(
|
|
365
|
+
`Cloud API request failed: ${response.status} (${path}).`,
|
|
366
|
+
);
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
const {code, message, result} = BackendApiResponse.satisfies(
|
|
370
|
+
await response.json(),
|
|
371
|
+
);
|
|
372
|
+
|
|
373
|
+
if (code !== 0) {
|
|
374
|
+
throw new Error(
|
|
375
|
+
`Cloud API request failed: ${code}${message === undefined ? '' : ` (${message})`} (${path}).`,
|
|
376
|
+
);
|
|
377
|
+
} else if (result === undefined) {
|
|
378
|
+
throw new Error(`Cloud API response is missing a result (${path}).`);
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
return result;
|
|
382
|
+
}
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
export type BackendDeviceDiscovery = {
|
|
386
|
+
readonly userId?: string;
|
|
387
|
+
readonly homes: readonly BackendHome[];
|
|
388
|
+
readonly devices: readonly BackendDevice[];
|
|
389
|
+
};
|
|
390
|
+
|
|
391
|
+
export type BackendClientOptions = {
|
|
392
|
+
readonly uuid: string;
|
|
393
|
+
readonly accessToken: string;
|
|
394
|
+
readonly cloudServer?: CloudServer;
|
|
395
|
+
};
|
|
396
|
+
|
|
397
|
+
export type BackendPropertyResult = x.TypeOf<typeof BackendPropertyResultValue>;
|
|
398
|
+
|
|
399
|
+
export type BackendActionResult = x.TypeOf<typeof BackendActionResultValue>;
|
|
400
|
+
|
|
401
|
+
export type BackendHomeSource = 'owned' | 'shared-home' | 'shared-device';
|
|
402
|
+
|
|
403
|
+
export type BackendHome = {
|
|
404
|
+
readonly id: string;
|
|
405
|
+
readonly name: string;
|
|
406
|
+
readonly source: BackendHomeSource;
|
|
407
|
+
readonly userId?: string;
|
|
408
|
+
readonly rooms: readonly BackendRoom[];
|
|
409
|
+
};
|
|
410
|
+
|
|
411
|
+
export type BackendRoom = {
|
|
412
|
+
readonly id: string;
|
|
413
|
+
readonly name: string;
|
|
414
|
+
};
|
|
415
|
+
|
|
416
|
+
export type BackendDevice = {
|
|
417
|
+
readonly did: string;
|
|
418
|
+
readonly name?: string;
|
|
419
|
+
readonly model?: string;
|
|
420
|
+
readonly specType?: string;
|
|
421
|
+
readonly online?: boolean;
|
|
422
|
+
readonly parentDid?: string;
|
|
423
|
+
readonly firmwareVersion?: string;
|
|
424
|
+
readonly source?: BackendHomeSource;
|
|
425
|
+
readonly homeId?: string;
|
|
426
|
+
readonly homeName?: string;
|
|
427
|
+
readonly roomId?: string;
|
|
428
|
+
readonly roomName?: string;
|
|
429
|
+
};
|
|
430
|
+
|
|
431
|
+
type HomeDiscovery = {
|
|
432
|
+
readonly userId?: string;
|
|
433
|
+
readonly homes: Map<string, MutableHome>;
|
|
434
|
+
readonly locations: Map<string, DeviceLocation>;
|
|
435
|
+
};
|
|
436
|
+
|
|
437
|
+
type MutableHome = {
|
|
438
|
+
readonly id: string;
|
|
439
|
+
readonly name: string;
|
|
440
|
+
readonly source: BackendHomeSource;
|
|
441
|
+
readonly userId?: string;
|
|
442
|
+
readonly deviceIds: Set<string>;
|
|
443
|
+
readonly rooms: Map<string, MutableRoom>;
|
|
444
|
+
};
|
|
445
|
+
|
|
446
|
+
type MutableRoom = {
|
|
447
|
+
readonly id: string;
|
|
448
|
+
readonly name: string;
|
|
449
|
+
readonly deviceIds: Set<string>;
|
|
450
|
+
};
|
|
451
|
+
|
|
452
|
+
type DeviceLocation = {
|
|
453
|
+
readonly source: BackendHomeSource;
|
|
454
|
+
readonly homeId: string;
|
|
455
|
+
readonly homeName: string;
|
|
456
|
+
readonly roomId: string;
|
|
457
|
+
readonly roomName: string;
|
|
458
|
+
};
|
|
459
|
+
|
|
460
|
+
type DeviceDetail = {
|
|
461
|
+
readonly did: string;
|
|
462
|
+
readonly name?: string;
|
|
463
|
+
readonly model?: string;
|
|
464
|
+
readonly specType?: string;
|
|
465
|
+
readonly online?: boolean;
|
|
466
|
+
readonly parentDid?: string;
|
|
467
|
+
readonly firmwareVersion?: string;
|
|
468
|
+
readonly ownerId?: string;
|
|
469
|
+
readonly ownerName?: string;
|
|
470
|
+
};
|
|
471
|
+
|
|
472
|
+
function readHome(
|
|
473
|
+
value: unknown,
|
|
474
|
+
source: BackendHomeSource,
|
|
475
|
+
): MutableHome | undefined {
|
|
476
|
+
const record = readRecord(value);
|
|
477
|
+
const id = readIdentifier(record?.id);
|
|
478
|
+
const name = readString(record?.name);
|
|
479
|
+
|
|
480
|
+
if (record === undefined || id === undefined || name === undefined) {
|
|
481
|
+
return undefined;
|
|
482
|
+
}
|
|
483
|
+
|
|
484
|
+
const home: MutableHome = {
|
|
485
|
+
id,
|
|
486
|
+
name,
|
|
487
|
+
source,
|
|
488
|
+
userId: readIdentifier(record.uid),
|
|
489
|
+
deviceIds: new Set(readIdentifiers(record.dids)),
|
|
490
|
+
rooms: new Map(),
|
|
491
|
+
};
|
|
492
|
+
|
|
493
|
+
for (const roomValue of readArray(record.roomlist)) {
|
|
494
|
+
const roomRecord = readRecord(roomValue);
|
|
495
|
+
const roomId = readIdentifier(roomRecord?.id);
|
|
496
|
+
const roomName = readString(roomRecord?.name);
|
|
497
|
+
|
|
498
|
+
if (roomRecord !== undefined && roomId !== undefined) {
|
|
499
|
+
home.rooms.set(roomId, {
|
|
500
|
+
id: roomId,
|
|
501
|
+
name: roomName ?? '',
|
|
502
|
+
deviceIds: new Set(readIdentifiers(roomRecord.dids)),
|
|
503
|
+
});
|
|
504
|
+
}
|
|
505
|
+
}
|
|
506
|
+
|
|
507
|
+
return home;
|
|
508
|
+
}
|
|
509
|
+
|
|
510
|
+
function mergeHomePage(home: MutableHome, page: Record<string, unknown>): void {
|
|
511
|
+
for (const did of readIdentifiers(page.dids)) {
|
|
512
|
+
home.deviceIds.add(did);
|
|
513
|
+
}
|
|
514
|
+
|
|
515
|
+
for (const roomValue of readArray(page.roomlist)) {
|
|
516
|
+
const roomRecord = readRecord(roomValue);
|
|
517
|
+
const roomId = readIdentifier(roomRecord?.id);
|
|
518
|
+
|
|
519
|
+
if (roomRecord === undefined || roomId === undefined) {
|
|
520
|
+
continue;
|
|
521
|
+
}
|
|
522
|
+
|
|
523
|
+
let room = home.rooms.get(roomId);
|
|
524
|
+
|
|
525
|
+
if (room === undefined) {
|
|
526
|
+
room = {
|
|
527
|
+
id: roomId,
|
|
528
|
+
name: readString(roomRecord.name) ?? '',
|
|
529
|
+
deviceIds: new Set(),
|
|
530
|
+
};
|
|
531
|
+
home.rooms.set(roomId, room);
|
|
532
|
+
}
|
|
533
|
+
|
|
534
|
+
for (const did of readIdentifiers(roomRecord.dids)) {
|
|
535
|
+
room.deviceIds.add(did);
|
|
536
|
+
}
|
|
537
|
+
}
|
|
538
|
+
}
|
|
539
|
+
|
|
540
|
+
function indexHome(
|
|
541
|
+
home: MutableHome,
|
|
542
|
+
locations: Map<string, DeviceLocation>,
|
|
543
|
+
): void {
|
|
544
|
+
for (const did of home.deviceIds) {
|
|
545
|
+
locations.set(did, {
|
|
546
|
+
source: home.source,
|
|
547
|
+
homeId: home.id,
|
|
548
|
+
homeName: home.name,
|
|
549
|
+
roomId: home.id,
|
|
550
|
+
roomName: home.name,
|
|
551
|
+
});
|
|
552
|
+
}
|
|
553
|
+
|
|
554
|
+
for (const room of home.rooms.values()) {
|
|
555
|
+
for (const did of room.deviceIds) {
|
|
556
|
+
locations.set(did, {
|
|
557
|
+
source: home.source,
|
|
558
|
+
homeId: home.id,
|
|
559
|
+
homeName: home.name,
|
|
560
|
+
roomId: room.id,
|
|
561
|
+
roomName: room.name,
|
|
562
|
+
});
|
|
563
|
+
}
|
|
564
|
+
}
|
|
565
|
+
}
|
|
566
|
+
|
|
567
|
+
function readDevice(value: unknown): DeviceDetail | undefined {
|
|
568
|
+
const record = readRecord(value);
|
|
569
|
+
const did = readString(record?.did);
|
|
570
|
+
|
|
571
|
+
if (record === undefined || did === undefined) {
|
|
572
|
+
return undefined;
|
|
573
|
+
}
|
|
574
|
+
|
|
575
|
+
const extra = readRecord(record.extra);
|
|
576
|
+
const owner = readRecord(record.owner);
|
|
577
|
+
|
|
578
|
+
return {
|
|
579
|
+
did,
|
|
580
|
+
name: readString(record.name),
|
|
581
|
+
model: readString(record.model),
|
|
582
|
+
specType: readString(record.spec_type),
|
|
583
|
+
online: readBoolean(record.isOnline),
|
|
584
|
+
parentDid: readString(record.parent_id),
|
|
585
|
+
firmwareVersion: readString(extra?.fw_version),
|
|
586
|
+
ownerId: readIdentifier(owner?.userid),
|
|
587
|
+
ownerName: readString(owner?.nickname),
|
|
588
|
+
};
|
|
589
|
+
}
|
|
590
|
+
|
|
591
|
+
function getOrCreateSharedDeviceHome(
|
|
592
|
+
homes: Map<string, MutableHome>,
|
|
593
|
+
ownerId: string,
|
|
594
|
+
ownerName: string,
|
|
595
|
+
): MutableHome {
|
|
596
|
+
const key = getHomeKey('shared-device', ownerId);
|
|
597
|
+
const existing = homes.get(key);
|
|
598
|
+
|
|
599
|
+
if (existing !== undefined) {
|
|
600
|
+
return existing;
|
|
601
|
+
}
|
|
602
|
+
|
|
603
|
+
const home: MutableHome = {
|
|
604
|
+
id: ownerId,
|
|
605
|
+
name: ownerName,
|
|
606
|
+
source: 'shared-device',
|
|
607
|
+
userId: ownerId,
|
|
608
|
+
deviceIds: new Set(),
|
|
609
|
+
rooms: new Map([
|
|
610
|
+
[
|
|
611
|
+
'shared-device',
|
|
612
|
+
{id: 'shared-device', name: 'shared-device', deviceIds: new Set()},
|
|
613
|
+
],
|
|
614
|
+
]),
|
|
615
|
+
};
|
|
616
|
+
homes.set(key, home);
|
|
617
|
+
return home;
|
|
618
|
+
}
|
|
619
|
+
|
|
620
|
+
function getHomeKey(source: BackendHomeSource, id: string): string {
|
|
621
|
+
return JSON.stringify([source, id]);
|
|
622
|
+
}
|
|
623
|
+
|
|
624
|
+
function getHomeById(
|
|
625
|
+
homes: ReadonlyMap<string, MutableHome>,
|
|
626
|
+
id: string,
|
|
627
|
+
): MutableHome | undefined {
|
|
628
|
+
let matchingHome: MutableHome | undefined;
|
|
629
|
+
|
|
630
|
+
for (const home of homes.values()) {
|
|
631
|
+
if (home.id !== id) {
|
|
632
|
+
continue;
|
|
633
|
+
} else if (matchingHome !== undefined) {
|
|
634
|
+
throw new Error(
|
|
635
|
+
`Cloud home pagination returned ambiguous home id: ${id}.`,
|
|
636
|
+
);
|
|
637
|
+
}
|
|
638
|
+
|
|
639
|
+
matchingHome = home;
|
|
640
|
+
}
|
|
641
|
+
|
|
642
|
+
return matchingHome;
|
|
643
|
+
}
|
|
644
|
+
|
|
645
|
+
function requireRecord(
|
|
646
|
+
value: unknown,
|
|
647
|
+
description: string,
|
|
648
|
+
): Record<string, unknown> {
|
|
649
|
+
const record = readRecord(value);
|
|
650
|
+
|
|
651
|
+
if (record === undefined) {
|
|
652
|
+
throw new Error(`Cloud API returned an invalid ${description}.`);
|
|
653
|
+
}
|
|
654
|
+
|
|
655
|
+
return record;
|
|
656
|
+
}
|
|
657
|
+
|
|
658
|
+
function readRecord(value: unknown): Record<string, unknown> | undefined {
|
|
659
|
+
if (typeof value !== 'object' || value === null || Array.isArray(value)) {
|
|
660
|
+
return undefined;
|
|
661
|
+
}
|
|
662
|
+
|
|
663
|
+
return value as Record<string, unknown>;
|
|
664
|
+
}
|
|
665
|
+
|
|
666
|
+
function readArray(value: unknown): readonly unknown[] {
|
|
667
|
+
return Array.isArray(value) ? value : [];
|
|
668
|
+
}
|
|
669
|
+
|
|
670
|
+
function readString(value: unknown): string | undefined {
|
|
671
|
+
return typeof value === 'string' ? value : undefined;
|
|
672
|
+
}
|
|
673
|
+
|
|
674
|
+
function readIdentifier(value: unknown): string | undefined {
|
|
675
|
+
if (typeof value === 'string') {
|
|
676
|
+
return value;
|
|
677
|
+
} else if (typeof value === 'number' && Number.isSafeInteger(value)) {
|
|
678
|
+
return String(value);
|
|
679
|
+
}
|
|
680
|
+
|
|
681
|
+
return undefined;
|
|
682
|
+
}
|
|
683
|
+
|
|
684
|
+
function readIdentifiers(value: unknown): string[] {
|
|
685
|
+
return readArray(value)
|
|
686
|
+
.map(readIdentifier)
|
|
687
|
+
.filter((item): item is string => item !== undefined);
|
|
688
|
+
}
|
|
689
|
+
|
|
690
|
+
function readBoolean(value: unknown): boolean | undefined {
|
|
691
|
+
return typeof value === 'boolean' ? value : undefined;
|
|
692
|
+
}
|
|
693
|
+
|
|
694
|
+
function chunk<T>(values: readonly T[], size: number): T[][] {
|
|
695
|
+
const chunks: T[][] = [];
|
|
696
|
+
|
|
697
|
+
for (let index = 0; index < values.length; index += size) {
|
|
698
|
+
chunks.push(values.slice(index, index + size));
|
|
699
|
+
}
|
|
700
|
+
|
|
701
|
+
return chunks;
|
|
702
|
+
}
|
|
703
|
+
|
|
704
|
+
function compareDevices(left: BackendDevice, right: BackendDevice): number {
|
|
705
|
+
return (
|
|
706
|
+
(left.homeName ?? '').localeCompare(right.homeName ?? '') ||
|
|
707
|
+
(left.roomName ?? '').localeCompare(right.roomName ?? '') ||
|
|
708
|
+
(left.name ?? '').localeCompare(right.name ?? '') ||
|
|
709
|
+
left.did.localeCompare(right.did)
|
|
710
|
+
);
|
|
711
|
+
}
|
|
712
|
+
|
|
713
|
+
function compareNames(
|
|
714
|
+
left: {readonly name: string},
|
|
715
|
+
right: {readonly name: string},
|
|
716
|
+
): number {
|
|
717
|
+
return left.name.localeCompare(right.name);
|
|
718
|
+
}
|
|
719
|
+
|
|
720
|
+
function withRequestTimeout<T>(
|
|
721
|
+
request: Promise<T>,
|
|
722
|
+
message: string,
|
|
723
|
+
): Promise<T> {
|
|
724
|
+
let timeout: ReturnType<typeof setTimeout> | undefined;
|
|
725
|
+
const timeoutPromise = new Promise<never>((_resolve, reject) => {
|
|
726
|
+
timeout = setTimeout(() => {
|
|
727
|
+
reject(new Error(message));
|
|
728
|
+
}, BACKEND_API_TIMEOUT);
|
|
729
|
+
});
|
|
730
|
+
|
|
731
|
+
// This only bounds the caller's wait; the underlying fetch keeps running.
|
|
732
|
+
return Promise.race([request, timeoutPromise]).finally(() => {
|
|
733
|
+
if (timeout !== undefined) {
|
|
734
|
+
clearTimeout(timeout);
|
|
735
|
+
}
|
|
736
|
+
});
|
|
737
|
+
}
|