@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,17 @@
|
|
|
1
|
+
export const OAUTH2_CLIENT_ID = '2882303761520251711';
|
|
2
|
+
|
|
3
|
+
export const DEFAULT_BACKEND_API_HOST = 'ha.api.io.mi.com';
|
|
4
|
+
|
|
5
|
+
export const BACKEND_API_TIMEOUT = 30_000;
|
|
6
|
+
|
|
7
|
+
export const DEFAULT_CLOUD_SERVER: CloudServer = 'cn';
|
|
8
|
+
|
|
9
|
+
export const CLOUD_SERVERS = ['cn', 'de', 'i2', 'ru', 'sg', 'us'] as const;
|
|
10
|
+
|
|
11
|
+
export type CloudServer = (typeof CLOUD_SERVERS)[number];
|
|
12
|
+
|
|
13
|
+
export function getBackendApiHost(cloudServer: CloudServer): string {
|
|
14
|
+
return cloudServer === 'cn'
|
|
15
|
+
? DEFAULT_BACKEND_API_HOST
|
|
16
|
+
: `${cloudServer}.${DEFAULT_BACKEND_API_HOST}`;
|
|
17
|
+
}
|
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
import {createHash} from 'node:crypto';
|
|
2
|
+
|
|
3
|
+
import * as x from 'x-value';
|
|
4
|
+
|
|
5
|
+
import {
|
|
6
|
+
BACKEND_API_TIMEOUT,
|
|
7
|
+
type CloudServer,
|
|
8
|
+
DEFAULT_CLOUD_SERVER,
|
|
9
|
+
OAUTH2_CLIENT_ID,
|
|
10
|
+
getBackendApiHost,
|
|
11
|
+
} from './constants.js';
|
|
12
|
+
|
|
13
|
+
export const OAUTH2_AUTH_URL = 'https://account.xiaomi.com/oauth2/authorize';
|
|
14
|
+
|
|
15
|
+
export const OAUTH_REDIRECT_URL = 'http://homeassistant.local:8123';
|
|
16
|
+
|
|
17
|
+
const OAuthTokenResponse = x.object({
|
|
18
|
+
code: x.number,
|
|
19
|
+
message: x.string.optional(),
|
|
20
|
+
result: x
|
|
21
|
+
.object({
|
|
22
|
+
access_token: x.string.optional(),
|
|
23
|
+
refresh_token: x.string.optional(),
|
|
24
|
+
expires_in: x.number.optional(),
|
|
25
|
+
mac_key: x.string.optional(),
|
|
26
|
+
error: x.number.optional(),
|
|
27
|
+
error_description: x.string.optional(),
|
|
28
|
+
})
|
|
29
|
+
.optional(),
|
|
30
|
+
});
|
|
31
|
+
|
|
32
|
+
export class OAuthClient {
|
|
33
|
+
/** Identifies this MIoT provider to Xiaomi, not a physical device. */
|
|
34
|
+
private readonly deviceId: string;
|
|
35
|
+
|
|
36
|
+
private readonly apiHost: string;
|
|
37
|
+
|
|
38
|
+
constructor(uuid: string, cloudServer: CloudServer = DEFAULT_CLOUD_SERVER) {
|
|
39
|
+
this.deviceId = `ha.${uuid}`;
|
|
40
|
+
this.apiHost = getBackendApiHost(cloudServer);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
createAuthorization(redirectUrl = OAUTH_REDIRECT_URL): OAuthAuthorization {
|
|
44
|
+
// Xiaomi's HA OAuth flow derives state from device_id instead of using a
|
|
45
|
+
// conventional random OAuth nonce. The callback is still checked against it.
|
|
46
|
+
const state = createHash('sha1').update(`d=${this.deviceId}`).digest('hex');
|
|
47
|
+
const parameters = new URLSearchParams({
|
|
48
|
+
redirect_uri: redirectUrl,
|
|
49
|
+
client_id: OAUTH2_CLIENT_ID,
|
|
50
|
+
response_type: 'code',
|
|
51
|
+
device_id: this.deviceId,
|
|
52
|
+
state,
|
|
53
|
+
skip_confirm: 'false',
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
return {
|
|
57
|
+
url: `${OAUTH2_AUTH_URL}?${parameters.toString()}`,
|
|
58
|
+
state,
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
async exchangeCode(
|
|
63
|
+
code: string,
|
|
64
|
+
redirectUrl = OAUTH_REDIRECT_URL,
|
|
65
|
+
): Promise<OAuthToken> {
|
|
66
|
+
return this.requestToken({
|
|
67
|
+
redirect_uri: redirectUrl,
|
|
68
|
+
code,
|
|
69
|
+
device_id: this.deviceId,
|
|
70
|
+
});
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
async refreshToken(
|
|
74
|
+
refreshToken: string,
|
|
75
|
+
redirectUrl = OAUTH_REDIRECT_URL,
|
|
76
|
+
): Promise<OAuthToken> {
|
|
77
|
+
return this.requestToken({
|
|
78
|
+
redirect_uri: redirectUrl,
|
|
79
|
+
refresh_token: refreshToken,
|
|
80
|
+
});
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
private requestToken(data: Record<string, string>): Promise<OAuthToken> {
|
|
84
|
+
return withRequestTimeout(
|
|
85
|
+
this.fetchToken(data),
|
|
86
|
+
'OAuth token request timed out.',
|
|
87
|
+
);
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
private async fetchToken(data: Record<string, string>): Promise<OAuthToken> {
|
|
91
|
+
const url = new URL(
|
|
92
|
+
'/app/v2/ha/oauth/get_token',
|
|
93
|
+
`https://${this.apiHost}`,
|
|
94
|
+
);
|
|
95
|
+
url.searchParams.set('data', createTokenRequestData(data));
|
|
96
|
+
|
|
97
|
+
const response = await fetch(url, {
|
|
98
|
+
headers: {'content-type': 'application/x-www-form-urlencoded'},
|
|
99
|
+
});
|
|
100
|
+
|
|
101
|
+
if (response.status === 401) {
|
|
102
|
+
throw new Error('OAuth token request was rejected.');
|
|
103
|
+
} else if (!response.ok) {
|
|
104
|
+
throw new Error(`OAuth token request failed: ${response.status}.`);
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
const {
|
|
108
|
+
code: responseCode,
|
|
109
|
+
message,
|
|
110
|
+
result,
|
|
111
|
+
} = OAuthTokenResponse.satisfies(await response.json());
|
|
112
|
+
|
|
113
|
+
if (responseCode !== 0) {
|
|
114
|
+
const errorCode = result?.error;
|
|
115
|
+
const description = result?.error_description ?? message;
|
|
116
|
+
throw new Error(
|
|
117
|
+
`OAuth token request failed: ${responseCode}${errorCode === undefined ? '' : `/${errorCode}`}${description === undefined ? '' : ` (${description})`}.`,
|
|
118
|
+
);
|
|
119
|
+
} else if (
|
|
120
|
+
result === undefined ||
|
|
121
|
+
result.access_token === undefined ||
|
|
122
|
+
result.refresh_token === undefined ||
|
|
123
|
+
result.expires_in === undefined
|
|
124
|
+
) {
|
|
125
|
+
throw new Error('OAuth token response is missing token data.');
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
return {
|
|
129
|
+
accessToken: result.access_token,
|
|
130
|
+
refreshToken: result.refresh_token,
|
|
131
|
+
expiresIn: result.expires_in,
|
|
132
|
+
macKey: result.mac_key,
|
|
133
|
+
};
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
export type OAuthAuthorization = {
|
|
138
|
+
readonly url: string;
|
|
139
|
+
readonly state: string;
|
|
140
|
+
};
|
|
141
|
+
|
|
142
|
+
export type OAuthToken = {
|
|
143
|
+
readonly accessToken: string;
|
|
144
|
+
readonly refreshToken: string;
|
|
145
|
+
readonly expiresIn: number;
|
|
146
|
+
readonly macKey?: string;
|
|
147
|
+
};
|
|
148
|
+
|
|
149
|
+
function createTokenRequestData(data: Record<string, string>): string {
|
|
150
|
+
return `{"client_id":${OAUTH2_CLIENT_ID},${JSON.stringify(data).slice(1)}`;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
function withRequestTimeout<T>(
|
|
154
|
+
request: Promise<T>,
|
|
155
|
+
message: string,
|
|
156
|
+
): Promise<T> {
|
|
157
|
+
let timeout: ReturnType<typeof setTimeout> | undefined;
|
|
158
|
+
const timeoutPromise = new Promise<never>((_resolve, reject) => {
|
|
159
|
+
timeout = setTimeout(() => {
|
|
160
|
+
reject(new Error(message));
|
|
161
|
+
}, BACKEND_API_TIMEOUT);
|
|
162
|
+
});
|
|
163
|
+
|
|
164
|
+
// This only bounds the caller's wait; the underlying fetch keeps running.
|
|
165
|
+
return Promise.race([request, timeoutPromise]).finally(() => {
|
|
166
|
+
if (timeout !== undefined) {
|
|
167
|
+
clearTimeout(timeout);
|
|
168
|
+
}
|
|
169
|
+
});
|
|
170
|
+
}
|
|
@@ -0,0 +1,387 @@
|
|
|
1
|
+
import {
|
|
2
|
+
type EndpointPath,
|
|
3
|
+
type ProviderBindingDevice,
|
|
4
|
+
type ProviderBindingEndpoint,
|
|
5
|
+
getEndpointPathKey,
|
|
6
|
+
} from '@homelib/core';
|
|
7
|
+
|
|
8
|
+
import type {BackendDevice} from './backend/index.js';
|
|
9
|
+
import type {MiotProviderConfiguration} from './configuration.js';
|
|
10
|
+
import {
|
|
11
|
+
createMiotEndpointConnectionMetadata,
|
|
12
|
+
matchMiotDevice,
|
|
13
|
+
miotEndpointConnectionMetadataEqual,
|
|
14
|
+
} from './device.js';
|
|
15
|
+
import {
|
|
16
|
+
type MiotEndpointConnectionMetadata,
|
|
17
|
+
getMiotEndpointConnectionResourceKeys,
|
|
18
|
+
normalizeMiotEndpointConnectionMetadata,
|
|
19
|
+
} from './endpoint-connection.js';
|
|
20
|
+
import {MiotSpecClient, type MiotSpecInstance} from './miot/index.js';
|
|
21
|
+
|
|
22
|
+
const SPEC_REQUEST_CONCURRENCY = 6;
|
|
23
|
+
const DEFAULT_MIOT_SPEC_CLIENT = new MiotSpecClient();
|
|
24
|
+
|
|
25
|
+
export async function discoverMiotBindingDevices(
|
|
26
|
+
provider: MiotBindingDiscoveryProvider,
|
|
27
|
+
logicalDevice: ProviderBindingDevice,
|
|
28
|
+
specClient: Pick<MiotSpecClient, 'getInstance'> = DEFAULT_MIOT_SPEC_CLIENT,
|
|
29
|
+
): Promise<MiotBindingDiscovery> {
|
|
30
|
+
const {endpoints} = logicalDevice;
|
|
31
|
+
const discovery = await provider.configuration.discoverDevices();
|
|
32
|
+
|
|
33
|
+
if (discovery === undefined) {
|
|
34
|
+
throw new Error('configure this miot provider before binding devices.');
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
const specTypeSet = new Set<string>();
|
|
38
|
+
|
|
39
|
+
for (const device of discovery.devices) {
|
|
40
|
+
if (device.specType !== undefined) {
|
|
41
|
+
specTypeSet.add(device.specType);
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
const specMap = await loadSpecInstances(
|
|
46
|
+
[...specTypeSet],
|
|
47
|
+
specClient,
|
|
48
|
+
SPEC_REQUEST_CONCURRENCY,
|
|
49
|
+
);
|
|
50
|
+
const devices: MiotBindingDeviceCandidate[] = [];
|
|
51
|
+
let failedDeviceCount = 0;
|
|
52
|
+
let incompleteDeviceCount = 0;
|
|
53
|
+
|
|
54
|
+
for (const device of discovery.devices) {
|
|
55
|
+
if (device.specType === undefined) {
|
|
56
|
+
incompleteDeviceCount++;
|
|
57
|
+
continue;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
const spec = specMap.get(device.specType);
|
|
61
|
+
|
|
62
|
+
if (spec === undefined) {
|
|
63
|
+
failedDeviceCount++;
|
|
64
|
+
continue;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
const candidate = createBindingDeviceCandidate(
|
|
68
|
+
{...device, specType: device.specType},
|
|
69
|
+
spec,
|
|
70
|
+
logicalDevice,
|
|
71
|
+
);
|
|
72
|
+
|
|
73
|
+
if (candidate !== undefined) {
|
|
74
|
+
devices.push(candidate);
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
devices.sort(
|
|
79
|
+
(left, right) =>
|
|
80
|
+
getDeviceMatchScore(right.device, endpoints) -
|
|
81
|
+
getDeviceMatchScore(left.device, endpoints),
|
|
82
|
+
);
|
|
83
|
+
|
|
84
|
+
return {devices, failedDeviceCount, incompleteDeviceCount};
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
export type MiotBindingDiscovery = {
|
|
88
|
+
readonly devices: readonly MiotBindingDeviceCandidate[];
|
|
89
|
+
readonly failedDeviceCount: number;
|
|
90
|
+
readonly incompleteDeviceCount: number;
|
|
91
|
+
};
|
|
92
|
+
|
|
93
|
+
export type MiotBindingDiscoveryProvider = {
|
|
94
|
+
readonly configuration: Pick<MiotProviderConfiguration, 'discoverDevices'>;
|
|
95
|
+
};
|
|
96
|
+
|
|
97
|
+
export type MiotBindingDeviceCandidate = {
|
|
98
|
+
readonly key: string;
|
|
99
|
+
readonly device: BackendDevice;
|
|
100
|
+
readonly endpoints: readonly MiotBindingEndpointCandidate[];
|
|
101
|
+
};
|
|
102
|
+
|
|
103
|
+
export type MiotBindingEndpointCandidate = {
|
|
104
|
+
readonly endpoint: ProviderBindingEndpoint;
|
|
105
|
+
readonly metadata: MiotEndpointConnectionMetadata;
|
|
106
|
+
readonly resourceKeys: readonly string[];
|
|
107
|
+
readonly label: string;
|
|
108
|
+
};
|
|
109
|
+
|
|
110
|
+
export type MiotBindingResourceBinding = {
|
|
111
|
+
readonly endpoint: EndpointPath;
|
|
112
|
+
readonly metadata: unknown;
|
|
113
|
+
};
|
|
114
|
+
|
|
115
|
+
export type MiotBindingDeviceProposal = {
|
|
116
|
+
readonly status: 'automatic' | 'existing' | 'unavailable';
|
|
117
|
+
readonly device: MiotBindingDeviceCandidate;
|
|
118
|
+
readonly endpoints: readonly MiotBindingEndpointProposal[];
|
|
119
|
+
readonly bindings: readonly MiotBindingProposalBinding[];
|
|
120
|
+
};
|
|
121
|
+
|
|
122
|
+
export type MiotBindingEndpointProposal = {
|
|
123
|
+
readonly status: 'automatic' | 'existing' | 'unavailable';
|
|
124
|
+
readonly endpoint: MiotBindingEndpointCandidate;
|
|
125
|
+
};
|
|
126
|
+
|
|
127
|
+
export type MiotBindingProposalBinding = {
|
|
128
|
+
readonly endpoint: EndpointPath;
|
|
129
|
+
readonly metadata: MiotEndpointConnectionMetadata;
|
|
130
|
+
};
|
|
131
|
+
|
|
132
|
+
export function resolveMiotBindingDeviceProposal(
|
|
133
|
+
device: MiotBindingDeviceCandidate,
|
|
134
|
+
providerBindings: readonly MiotBindingResourceBinding[],
|
|
135
|
+
): MiotBindingDeviceProposal {
|
|
136
|
+
const candidateEndpointPathKeySet = new Set(
|
|
137
|
+
device.endpoints.map(({endpoint}) => getEndpointPathKey(endpoint.path)),
|
|
138
|
+
);
|
|
139
|
+
const providerBindingMap = new Map(
|
|
140
|
+
providerBindings.map(binding => [
|
|
141
|
+
getEndpointPathKey(binding.endpoint),
|
|
142
|
+
binding,
|
|
143
|
+
]),
|
|
144
|
+
);
|
|
145
|
+
const occupiedResourceMap = getOccupiedResourceMap(providerBindings);
|
|
146
|
+
const existingEndpointPathKeySet = new Set<string>();
|
|
147
|
+
let resourcesUnavailable = false;
|
|
148
|
+
|
|
149
|
+
for (const endpoint of device.endpoints) {
|
|
150
|
+
const endpointPathKey = getEndpointPathKey(endpoint.endpoint.path);
|
|
151
|
+
const existingMetadata = normalizeMetadata(
|
|
152
|
+
providerBindingMap.get(endpointPathKey)?.metadata,
|
|
153
|
+
);
|
|
154
|
+
|
|
155
|
+
if (
|
|
156
|
+
existingMetadata !== undefined &&
|
|
157
|
+
miotEndpointConnectionMetadataEqual(endpoint.metadata, existingMetadata)
|
|
158
|
+
) {
|
|
159
|
+
existingEndpointPathKeySet.add(endpointPathKey);
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
const replaceableEndpointPathKeySet = new Set(
|
|
164
|
+
device.endpoints.flatMap(({endpoint}) => {
|
|
165
|
+
const endpointPathKey = getEndpointPathKey(endpoint.path);
|
|
166
|
+
|
|
167
|
+
if (
|
|
168
|
+
existingEndpointPathKeySet.has(endpointPathKey) ||
|
|
169
|
+
endpoint.binding === undefined ||
|
|
170
|
+
providerBindingMap.has(endpointPathKey)
|
|
171
|
+
) {
|
|
172
|
+
return [endpointPathKey];
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
return [];
|
|
176
|
+
}),
|
|
177
|
+
);
|
|
178
|
+
|
|
179
|
+
for (const endpoint of device.endpoints) {
|
|
180
|
+
for (const resourceKey of endpoint.resourceKeys) {
|
|
181
|
+
const ownerEndpointPathKey = occupiedResourceMap.get(resourceKey);
|
|
182
|
+
|
|
183
|
+
if (
|
|
184
|
+
ownerEndpointPathKey !== undefined &&
|
|
185
|
+
(!candidateEndpointPathKeySet.has(ownerEndpointPathKey) ||
|
|
186
|
+
!replaceableEndpointPathKeySet.has(ownerEndpointPathKey))
|
|
187
|
+
) {
|
|
188
|
+
resourcesUnavailable = true;
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
if (resourcesUnavailable) {
|
|
194
|
+
return {
|
|
195
|
+
status: 'unavailable',
|
|
196
|
+
device,
|
|
197
|
+
endpoints: device.endpoints.map(endpoint => ({
|
|
198
|
+
status: existingEndpointPathKeySet.has(
|
|
199
|
+
getEndpointPathKey(endpoint.endpoint.path),
|
|
200
|
+
)
|
|
201
|
+
? 'existing'
|
|
202
|
+
: 'unavailable',
|
|
203
|
+
endpoint,
|
|
204
|
+
})),
|
|
205
|
+
bindings: [],
|
|
206
|
+
};
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
const endpoints: MiotBindingEndpointProposal[] = device.endpoints.map(
|
|
210
|
+
endpoint => ({
|
|
211
|
+
status: existingEndpointPathKeySet.has(
|
|
212
|
+
getEndpointPathKey(endpoint.endpoint.path),
|
|
213
|
+
)
|
|
214
|
+
? 'existing'
|
|
215
|
+
: 'automatic',
|
|
216
|
+
endpoint,
|
|
217
|
+
}),
|
|
218
|
+
);
|
|
219
|
+
const bindings = endpoints.flatMap(proposal => {
|
|
220
|
+
if (proposal.status !== 'automatic') {
|
|
221
|
+
return [];
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
return [
|
|
225
|
+
{
|
|
226
|
+
endpoint: proposal.endpoint.endpoint.path,
|
|
227
|
+
metadata: proposal.endpoint.metadata,
|
|
228
|
+
},
|
|
229
|
+
];
|
|
230
|
+
});
|
|
231
|
+
|
|
232
|
+
return {
|
|
233
|
+
status: bindings.length === 0 ? 'existing' : 'automatic',
|
|
234
|
+
device,
|
|
235
|
+
endpoints,
|
|
236
|
+
bindings,
|
|
237
|
+
};
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
function createBindingDeviceCandidate(
|
|
241
|
+
device: BackendDevice & {readonly specType: string},
|
|
242
|
+
spec: MiotSpecInstance,
|
|
243
|
+
logicalDevice: ProviderBindingDevice,
|
|
244
|
+
): MiotBindingDeviceCandidate | undefined {
|
|
245
|
+
const match = matchMiotDevice(logicalDevice, spec);
|
|
246
|
+
|
|
247
|
+
if (match === undefined) {
|
|
248
|
+
return undefined;
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
const resourceKeySet = new Set<string>();
|
|
252
|
+
const endpointCandidates: MiotBindingEndpointCandidate[] = [];
|
|
253
|
+
|
|
254
|
+
for (const {endpoint, resources} of match.endpoints) {
|
|
255
|
+
const metadata = createMiotEndpointConnectionMetadata(
|
|
256
|
+
device,
|
|
257
|
+
spec.type,
|
|
258
|
+
resources,
|
|
259
|
+
);
|
|
260
|
+
const resourceKeys = getMiotEndpointConnectionResourceKeys(metadata);
|
|
261
|
+
|
|
262
|
+
if (resourceKeys.some(resourceKey => resourceKeySet.has(resourceKey))) {
|
|
263
|
+
return undefined;
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
for (const resourceKey of resourceKeys) {
|
|
267
|
+
resourceKeySet.add(resourceKey);
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
endpointCandidates.push({
|
|
271
|
+
endpoint,
|
|
272
|
+
metadata,
|
|
273
|
+
resourceKeys,
|
|
274
|
+
label: resources.map(({service}) => service.description).join(' + '),
|
|
275
|
+
});
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
return {key: device.did, device, endpoints: endpointCandidates};
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
function getOccupiedResourceMap(
|
|
282
|
+
providerBindings: readonly MiotBindingResourceBinding[],
|
|
283
|
+
): ReadonlyMap<string, string> {
|
|
284
|
+
const occupiedResourceMap = new Map<string, string>();
|
|
285
|
+
|
|
286
|
+
for (const binding of providerBindings) {
|
|
287
|
+
const metadata = normalizeMetadata(binding.metadata);
|
|
288
|
+
|
|
289
|
+
if (metadata === undefined) {
|
|
290
|
+
continue;
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
const endpointPathKey = getEndpointPathKey(binding.endpoint);
|
|
294
|
+
|
|
295
|
+
for (const resourceKey of getMiotEndpointConnectionResourceKeys(metadata)) {
|
|
296
|
+
occupiedResourceMap.set(resourceKey, endpointPathKey);
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
return occupiedResourceMap;
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
function normalizeMetadata(
|
|
304
|
+
value: unknown,
|
|
305
|
+
): MiotEndpointConnectionMetadata | undefined {
|
|
306
|
+
if (value === undefined) {
|
|
307
|
+
return undefined;
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
try {
|
|
311
|
+
return normalizeMiotEndpointConnectionMetadata(value);
|
|
312
|
+
} catch {
|
|
313
|
+
return undefined;
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
function getDeviceMatchScore(
|
|
318
|
+
device: BackendDevice,
|
|
319
|
+
endpoints: readonly ProviderBindingEndpoint[],
|
|
320
|
+
): number {
|
|
321
|
+
let score = 0;
|
|
322
|
+
|
|
323
|
+
for (const endpoint of endpoints) {
|
|
324
|
+
let endpointScore = 0;
|
|
325
|
+
|
|
326
|
+
if (device.name === endpoint.path.deviceName) {
|
|
327
|
+
endpointScore += 2;
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
if (device.roomName === endpoint.path.scopePath.at(-1)) {
|
|
331
|
+
endpointScore += 1;
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
if (isCurrentMiotDevice(endpoint, device.did)) {
|
|
335
|
+
endpointScore += 4;
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
score = Math.max(score, endpointScore);
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
return score;
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
function isCurrentMiotDevice(
|
|
345
|
+
endpoint: ProviderBindingEndpoint,
|
|
346
|
+
did: string,
|
|
347
|
+
): boolean {
|
|
348
|
+
const metadata = normalizeMetadata(endpoint.binding?.metadata);
|
|
349
|
+
|
|
350
|
+
return metadata?.device.did === did;
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
async function loadSpecInstances(
|
|
354
|
+
urns: readonly string[],
|
|
355
|
+
specClient: Pick<MiotSpecClient, 'getInstance'>,
|
|
356
|
+
concurrency: number,
|
|
357
|
+
): Promise<ReadonlyMap<string, MiotSpecInstance>> {
|
|
358
|
+
const specMap = new Map<string, MiotSpecInstance>();
|
|
359
|
+
let nextIndex = 0;
|
|
360
|
+
|
|
361
|
+
const loadNext = async (): Promise<void> => {
|
|
362
|
+
while (true) {
|
|
363
|
+
const urn = urns.at(nextIndex);
|
|
364
|
+
|
|
365
|
+
if (urn === undefined) {
|
|
366
|
+
return;
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
nextIndex++;
|
|
370
|
+
|
|
371
|
+
try {
|
|
372
|
+
specMap.set(urn, await specClient.getInstance(urn));
|
|
373
|
+
} catch {
|
|
374
|
+
// Failed specs are counted per affected device by the caller.
|
|
375
|
+
}
|
|
376
|
+
}
|
|
377
|
+
};
|
|
378
|
+
const workerCount = Math.min(concurrency, urns.length);
|
|
379
|
+
|
|
380
|
+
await Promise.all(
|
|
381
|
+
Array.from({length: workerCount}, async () => {
|
|
382
|
+
await loadNext();
|
|
383
|
+
}),
|
|
384
|
+
);
|
|
385
|
+
|
|
386
|
+
return specMap;
|
|
387
|
+
}
|