@apocaliss92/nodedreame 1.11.11 → 1.12.1
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/README.md +151 -5
- package/dist/index.cjs +2303 -66
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +1122 -5
- package/dist/index.d.ts +1122 -5
- package/dist/index.js +2258 -64
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// src/support/version.ts
|
|
2
2
|
var LIBRARY_NAME = "nodedreame";
|
|
3
|
-
var LIBRARY_VERSION = "1.
|
|
3
|
+
var LIBRARY_VERSION = "1.12.0";
|
|
4
4
|
|
|
5
5
|
// src/transport/errors.ts
|
|
6
6
|
var DreameError = class extends Error {
|
|
@@ -385,6 +385,34 @@ async function postForToken(ctx, body) {
|
|
|
385
385
|
return session;
|
|
386
386
|
}
|
|
387
387
|
|
|
388
|
+
// src/cloud/connectivity.ts
|
|
389
|
+
var str = (v) => typeof v === "string" && v.length > 0 ? v : null;
|
|
390
|
+
var numOrNull = (v) => typeof v === "number" && Number.isFinite(v) ? v : null;
|
|
391
|
+
function parseBroker(bindDomain) {
|
|
392
|
+
const s = str(bindDomain);
|
|
393
|
+
if (!s) return null;
|
|
394
|
+
const idx = s.lastIndexOf(":");
|
|
395
|
+
if (idx < 0) return { host: s, port: null };
|
|
396
|
+
const port = Number(s.slice(idx + 1));
|
|
397
|
+
return { host: s.slice(0, idx), port: Number.isFinite(port) ? port : null };
|
|
398
|
+
}
|
|
399
|
+
function parseConnectivity(raw) {
|
|
400
|
+
const deviceInfo = raw["deviceInfo"] ?? {};
|
|
401
|
+
return {
|
|
402
|
+
online: raw["online"] === true,
|
|
403
|
+
connectionType: str(deviceInfo["scType"]),
|
|
404
|
+
mac: str(raw["mac"]),
|
|
405
|
+
broker: parseBroker(raw["bindDomain"]),
|
|
406
|
+
region: str(raw["region"]),
|
|
407
|
+
cloudVendor: str(raw["vendor"]),
|
|
408
|
+
firmwareVersion: str(raw["ver"]),
|
|
409
|
+
serialNumber: str(raw["sn"]),
|
|
410
|
+
subModel: str(raw["subModel"]),
|
|
411
|
+
battery: numOrNull(raw["battery"]),
|
|
412
|
+
statusCode: numOrNull(raw["latestStatus"])
|
|
413
|
+
};
|
|
414
|
+
}
|
|
415
|
+
|
|
388
416
|
// src/cloud/devices.ts
|
|
389
417
|
async function listDevices(input) {
|
|
390
418
|
const ctx = input.ctx ?? RequestContext.from({ ...input, host: input.apiHost });
|
|
@@ -429,7 +457,8 @@ function toDevice(rawIn) {
|
|
|
429
457
|
name,
|
|
430
458
|
online,
|
|
431
459
|
raw,
|
|
432
|
-
cloudState: parseCloudState(raw)
|
|
460
|
+
cloudState: parseCloudState(raw),
|
|
461
|
+
connectivity: parseConnectivity(raw)
|
|
433
462
|
};
|
|
434
463
|
if (rawIn.mac) {
|
|
435
464
|
device.mac = String(rawIn.mac);
|
|
@@ -2014,8 +2043,1032 @@ var VacuumCapabilityResolver = class {
|
|
|
2014
2043
|
}
|
|
2015
2044
|
};
|
|
2016
2045
|
|
|
2046
|
+
// src/video/schemas.ts
|
|
2047
|
+
import { z as z3 } from "zod";
|
|
2048
|
+
var VideoAccessTokenResponseSchema = z3.object({
|
|
2049
|
+
code: z3.number().optional(),
|
|
2050
|
+
msg: z3.string().nullish(),
|
|
2051
|
+
data: z3.object({
|
|
2052
|
+
data: z3.object({
|
|
2053
|
+
token: z3.string(),
|
|
2054
|
+
userId: z3.union([z3.string(), z3.number()]).optional(),
|
|
2055
|
+
expireAt: z3.number().optional()
|
|
2056
|
+
}).passthrough()
|
|
2057
|
+
}).passthrough()
|
|
2058
|
+
}).passthrough();
|
|
2059
|
+
var AuthCodeResponseSchema = z3.object({
|
|
2060
|
+
code: z3.number().optional(),
|
|
2061
|
+
msg: z3.string().nullish(),
|
|
2062
|
+
data: z3.string()
|
|
2063
|
+
}).passthrough();
|
|
2064
|
+
var FamilyIdResponseSchema = z3.object({
|
|
2065
|
+
code: z3.number().optional(),
|
|
2066
|
+
msg: z3.string().nullish(),
|
|
2067
|
+
data: z3.object({ data: z3.object({ familyId: z3.string() }).passthrough() }).passthrough()
|
|
2068
|
+
}).passthrough();
|
|
2069
|
+
var DeviceVideoInfoSchema = z3.object({
|
|
2070
|
+
model: z3.string().optional(),
|
|
2071
|
+
displayName: z3.string().optional(),
|
|
2072
|
+
permit: z3.string().optional(),
|
|
2073
|
+
videoDynamicVendor: z3.boolean().optional(),
|
|
2074
|
+
defaultVendors: z3.array(z3.string()).optional(),
|
|
2075
|
+
productId: z3.union([z3.string(), z3.number()]).optional()
|
|
2076
|
+
}).passthrough();
|
|
2077
|
+
var DeviceInfoRecordSchema = z3.object({
|
|
2078
|
+
did: z3.union([z3.string(), z3.number()]).optional(),
|
|
2079
|
+
model: z3.string().optional(),
|
|
2080
|
+
customName: z3.string().optional(),
|
|
2081
|
+
vendor: z3.string().optional(),
|
|
2082
|
+
online: z3.boolean().optional(),
|
|
2083
|
+
lwt: z3.number().optional(),
|
|
2084
|
+
property: z3.string().optional(),
|
|
2085
|
+
bindDomain: z3.string().optional(),
|
|
2086
|
+
deviceInfo: DeviceVideoInfoSchema.optional()
|
|
2087
|
+
}).passthrough();
|
|
2088
|
+
var DeviceInfoResponseSchema = z3.object({
|
|
2089
|
+
code: z3.number().optional(),
|
|
2090
|
+
msg: z3.string().nullish(),
|
|
2091
|
+
data: DeviceInfoRecordSchema
|
|
2092
|
+
}).passthrough();
|
|
2093
|
+
|
|
2094
|
+
// src/video/profile.ts
|
|
2095
|
+
var KNOWN_VENDORS = ["tx", "ali"];
|
|
2096
|
+
function asVendor(v) {
|
|
2097
|
+
return v === "tx" || v === "ali" ? v : null;
|
|
2098
|
+
}
|
|
2099
|
+
function parseProperty(property) {
|
|
2100
|
+
if (!property) {
|
|
2101
|
+
return { iotId: null, lwt: null };
|
|
2102
|
+
}
|
|
2103
|
+
try {
|
|
2104
|
+
const p = JSON.parse(property);
|
|
2105
|
+
return {
|
|
2106
|
+
iotId: typeof p.iotId === "string" && p.iotId.length > 0 ? p.iotId : null,
|
|
2107
|
+
lwt: typeof p.lwt === "number" ? p.lwt : null
|
|
2108
|
+
};
|
|
2109
|
+
} catch {
|
|
2110
|
+
return { iotId: null, lwt: null };
|
|
2111
|
+
}
|
|
2112
|
+
}
|
|
2113
|
+
function toVideoProfile(record) {
|
|
2114
|
+
const info = record.deviceInfo ?? {};
|
|
2115
|
+
const supportedVendors = (info.defaultVendors ?? []).filter(
|
|
2116
|
+
(v) => KNOWN_VENDORS.includes(v)
|
|
2117
|
+
);
|
|
2118
|
+
const prop = parseProperty(record.property);
|
|
2119
|
+
const online = record.online === true || record.lwt === 1 || prop.lwt === 1;
|
|
2120
|
+
return {
|
|
2121
|
+
did: String(record.did ?? ""),
|
|
2122
|
+
model: String(record.model ?? info.model ?? ""),
|
|
2123
|
+
displayName: info.displayName ?? null,
|
|
2124
|
+
videoCapable: info.permit === "video" || supportedVendors.length > 0,
|
|
2125
|
+
currentVendor: asVendor(record.vendor),
|
|
2126
|
+
supportedVendors,
|
|
2127
|
+
dynamicVendor: info.videoDynamicVendor === true,
|
|
2128
|
+
iotId: prop.iotId,
|
|
2129
|
+
online
|
|
2130
|
+
};
|
|
2131
|
+
}
|
|
2132
|
+
|
|
2133
|
+
// src/video/client.ts
|
|
2134
|
+
var P_THIRD_VIDEO = "/dreame-third-video";
|
|
2135
|
+
var P_SMARTHOME = "/dreame-smarthome";
|
|
2136
|
+
var P_USER_IOT = "/dreame-user-iot";
|
|
2137
|
+
var DEFAULT_OS = "android";
|
|
2138
|
+
function resolveCtx(input) {
|
|
2139
|
+
return input.ctx ?? RequestContext.from({ ...input, host: input.apiHost });
|
|
2140
|
+
}
|
|
2141
|
+
function passthrough(input) {
|
|
2142
|
+
return {
|
|
2143
|
+
accessToken: input.session.accessToken,
|
|
2144
|
+
...input.signal !== void 0 ? { signal: input.signal } : {},
|
|
2145
|
+
...input.timeoutMs !== void 0 ? { timeoutMs: input.timeoutMs } : {}
|
|
2146
|
+
};
|
|
2147
|
+
}
|
|
2148
|
+
async function getVideoAccessToken(input) {
|
|
2149
|
+
const ctx = resolveCtx(input);
|
|
2150
|
+
const raw = await httpPostJsonBody({
|
|
2151
|
+
ctx,
|
|
2152
|
+
path: `${P_THIRD_VIDEO}/tx/user/accesstoken`,
|
|
2153
|
+
body: { os: DEFAULT_OS },
|
|
2154
|
+
context: "video accesstoken",
|
|
2155
|
+
...passthrough(input)
|
|
2156
|
+
});
|
|
2157
|
+
const parsed = VideoAccessTokenResponseSchema.parse(raw);
|
|
2158
|
+
const d = parsed.data.data;
|
|
2159
|
+
return {
|
|
2160
|
+
token: d.token,
|
|
2161
|
+
userId: d.userId !== void 0 ? String(d.userId) : null,
|
|
2162
|
+
// Cloud reports expiry in epoch-seconds; expose epoch-ms like DreameSession.
|
|
2163
|
+
expiresAt: d.expireAt !== void 0 ? d.expireAt * 1e3 : 0
|
|
2164
|
+
};
|
|
2165
|
+
}
|
|
2166
|
+
async function getAliyunAuthCode(input) {
|
|
2167
|
+
const ctx = resolveCtx(input);
|
|
2168
|
+
const raw = await httpPostJsonBody({
|
|
2169
|
+
ctx,
|
|
2170
|
+
path: `${P_SMARTHOME}/aliIot/getAuthCodeV3`,
|
|
2171
|
+
body: { os: DEFAULT_OS },
|
|
2172
|
+
context: "aliyun authCode",
|
|
2173
|
+
...passthrough(input)
|
|
2174
|
+
});
|
|
2175
|
+
return AuthCodeResponseSchema.parse(raw).data;
|
|
2176
|
+
}
|
|
2177
|
+
async function getVideoFamilyId(input) {
|
|
2178
|
+
const ctx = resolveCtx(input);
|
|
2179
|
+
const videoToken = input.videoToken ?? (await getVideoAccessToken({ ...input, ctx })).token;
|
|
2180
|
+
const raw = await httpPostJsonBody({
|
|
2181
|
+
ctx,
|
|
2182
|
+
path: `${P_THIRD_VIDEO}/tx/mgr/family/getFamilyId`,
|
|
2183
|
+
body: { accesstoken: videoToken, os: DEFAULT_OS },
|
|
2184
|
+
context: "video familyId",
|
|
2185
|
+
...passthrough(input)
|
|
2186
|
+
});
|
|
2187
|
+
return FamilyIdResponseSchema.parse(raw).data.data.familyId;
|
|
2188
|
+
}
|
|
2189
|
+
async function getDeviceVideoProfile(input) {
|
|
2190
|
+
const ctx = resolveCtx(input);
|
|
2191
|
+
const raw = await httpPostJsonBody({
|
|
2192
|
+
ctx,
|
|
2193
|
+
path: `${P_USER_IOT}/iotuserbind/device/info`,
|
|
2194
|
+
body: { did: input.did },
|
|
2195
|
+
context: "device video info",
|
|
2196
|
+
...passthrough(input)
|
|
2197
|
+
});
|
|
2198
|
+
return toVideoProfile(DeviceInfoResponseSchema.parse(raw).data);
|
|
2199
|
+
}
|
|
2200
|
+
|
|
2201
|
+
// src/video/aliyun/constants.ts
|
|
2202
|
+
var ALIYUN_APP_KEY = "33974273";
|
|
2203
|
+
var ALIYUN_APP_SECRET = "65a62f03ae5eda97af962fecc2e3efa6";
|
|
2204
|
+
var ALIYUN_REGION_ID = {
|
|
2205
|
+
eu: "eu-central-1",
|
|
2206
|
+
de: "eu-central-1",
|
|
2207
|
+
us: "us-east-1",
|
|
2208
|
+
cn: "cn-shanghai",
|
|
2209
|
+
ru: "eu-central-1",
|
|
2210
|
+
sg: "ap-southeast-1",
|
|
2211
|
+
in: "ap-southeast-1",
|
|
2212
|
+
tw: "cn-shanghai"
|
|
2213
|
+
};
|
|
2214
|
+
function livingAccountHost(regionId) {
|
|
2215
|
+
return `living-account.${regionId}.aliyuncs.com`;
|
|
2216
|
+
}
|
|
2217
|
+
function apiIotHost(regionId) {
|
|
2218
|
+
return `${regionId}.api-iot.aliyuncs.com`;
|
|
2219
|
+
}
|
|
2220
|
+
var VISION_STREAM_QUERY = "/vision/customer/stream/query";
|
|
2221
|
+
|
|
2222
|
+
// src/video/aliyun/identity.ts
|
|
2223
|
+
import { randomUUID } from "crypto";
|
|
2224
|
+
import { z as z4 } from "zod";
|
|
2225
|
+
|
|
2226
|
+
// src/video/aliyun/signing.ts
|
|
2227
|
+
import { createHash as createHash2, createHmac } from "crypto";
|
|
2228
|
+
var CT_JSON = "application/json; charset=UTF-8";
|
|
2229
|
+
var CT_FORM = "application/x-www-form-urlencoded; charset=UTF-8";
|
|
2230
|
+
function md5Base64(s) {
|
|
2231
|
+
return createHash2("md5").update(s, "utf8").digest("base64");
|
|
2232
|
+
}
|
|
2233
|
+
function signApiGatewayRequest(input) {
|
|
2234
|
+
const accept = CT_JSON;
|
|
2235
|
+
const contentType = input.json !== void 0 ? CT_JSON : CT_FORM;
|
|
2236
|
+
const date = input.date ?? (/* @__PURE__ */ new Date()).toUTCString();
|
|
2237
|
+
let body;
|
|
2238
|
+
let contentMd5 = "";
|
|
2239
|
+
let formParams;
|
|
2240
|
+
if (input.json !== void 0) {
|
|
2241
|
+
body = JSON.stringify(input.json);
|
|
2242
|
+
contentMd5 = md5Base64(body);
|
|
2243
|
+
} else {
|
|
2244
|
+
const form = input.form ?? {};
|
|
2245
|
+
body = Object.entries(form).map(([k, v]) => `${k}=${encodeURIComponent(v)}`).join("&");
|
|
2246
|
+
formParams = form;
|
|
2247
|
+
}
|
|
2248
|
+
const caHeaders = {
|
|
2249
|
+
"X-Ca-Key": input.appKey,
|
|
2250
|
+
"X-Ca-Nonce": input.nonce ?? crypto.randomUUID().toUpperCase(),
|
|
2251
|
+
"X-Ca-Timestamp": String(input.timestamp ?? Date.now()),
|
|
2252
|
+
"X-Ca-Version": "1",
|
|
2253
|
+
...input.extraCaHeaders ?? {}
|
|
2254
|
+
};
|
|
2255
|
+
const signedHeaderNames = Object.keys(caHeaders).sort(
|
|
2256
|
+
(a, b) => a.toLowerCase() < b.toLowerCase() ? -1 : a.toLowerCase() > b.toLowerCase() ? 1 : 0
|
|
2257
|
+
);
|
|
2258
|
+
const headerBlock = signedHeaderNames.map((k) => `${k}:${caHeaders[k]}
|
|
2259
|
+
`).join("");
|
|
2260
|
+
let resource = input.path;
|
|
2261
|
+
if (formParams && Object.keys(formParams).length > 0) {
|
|
2262
|
+
const sorted = Object.keys(formParams).sort();
|
|
2263
|
+
resource += "?" + sorted.map((k) => `${k}=${formParams[k]}`).join("&");
|
|
2264
|
+
}
|
|
2265
|
+
const stringToSign = `${input.method}
|
|
2266
|
+
${accept}
|
|
2267
|
+
${contentMd5}
|
|
2268
|
+
${contentType}
|
|
2269
|
+
${date}
|
|
2270
|
+
${headerBlock}${resource}`;
|
|
2271
|
+
const signature = createHmac("sha1", input.appSecret).update(stringToSign, "utf8").digest("base64");
|
|
2272
|
+
const headers = {
|
|
2273
|
+
"Content-Type": contentType,
|
|
2274
|
+
Accept: accept,
|
|
2275
|
+
Date: date,
|
|
2276
|
+
"X-Ca-Signature": signature,
|
|
2277
|
+
"X-Ca-Signature-Method": "HmacSHA1",
|
|
2278
|
+
"X-Ca-Signature-Headers": signedHeaderNames.join(","),
|
|
2279
|
+
...caHeaders
|
|
2280
|
+
};
|
|
2281
|
+
if (contentMd5) {
|
|
2282
|
+
headers["Content-MD5"] = contentMd5;
|
|
2283
|
+
}
|
|
2284
|
+
return { headers, body };
|
|
2285
|
+
}
|
|
2286
|
+
|
|
2287
|
+
// src/video/aliyun/identity.ts
|
|
2288
|
+
var LoginByOauthSchema = z4.object({
|
|
2289
|
+
data: z4.object({
|
|
2290
|
+
data: z4.object({
|
|
2291
|
+
loginSuccessResult: z4.object({
|
|
2292
|
+
sid: z4.string(),
|
|
2293
|
+
refreshToken: z4.string().optional(),
|
|
2294
|
+
token: z4.string().optional(),
|
|
2295
|
+
openAccount: z4.object({ openId: z4.string().optional() }).passthrough().optional()
|
|
2296
|
+
}).passthrough()
|
|
2297
|
+
}).passthrough()
|
|
2298
|
+
}).passthrough()
|
|
2299
|
+
}).passthrough();
|
|
2300
|
+
var CreateSessionSchema = z4.object({
|
|
2301
|
+
code: z4.number().optional(),
|
|
2302
|
+
message: z4.string().nullish(),
|
|
2303
|
+
data: z4.object({
|
|
2304
|
+
iotToken: z4.string(),
|
|
2305
|
+
refreshToken: z4.string().optional(),
|
|
2306
|
+
identityId: z4.string().optional(),
|
|
2307
|
+
iotTokenExpire: z4.number().optional()
|
|
2308
|
+
}).passthrough()
|
|
2309
|
+
}).passthrough();
|
|
2310
|
+
async function postJson(url, headers, body, fetchImpl, ctx) {
|
|
2311
|
+
const res = await fetchImpl(url, { method: "POST", headers, body });
|
|
2312
|
+
const text = await res.text();
|
|
2313
|
+
try {
|
|
2314
|
+
return JSON.parse(text);
|
|
2315
|
+
} catch {
|
|
2316
|
+
throw new DreameApiError(`${ctx} returned non-JSON (status ${res.status})`, res.status);
|
|
2317
|
+
}
|
|
2318
|
+
}
|
|
2319
|
+
async function loginByOauth(input) {
|
|
2320
|
+
const host = livingAccountHost(input.regionId);
|
|
2321
|
+
const riskControlInfo = {
|
|
2322
|
+
createIfNotExist: "true",
|
|
2323
|
+
sdkVersion: "3.4.0.27",
|
|
2324
|
+
openaccountVersion: "3.4.0.27",
|
|
2325
|
+
platformName: "iOS",
|
|
2326
|
+
netType: "wifi",
|
|
2327
|
+
brand: "Apple",
|
|
2328
|
+
USE_H5_NC: "true",
|
|
2329
|
+
deviceId: input.deviceId ?? randomUUID(),
|
|
2330
|
+
locale: "en-US",
|
|
2331
|
+
platformVersion: "26.5.2",
|
|
2332
|
+
platform: "iPhone",
|
|
2333
|
+
appKey: ALIYUN_APP_KEY,
|
|
2334
|
+
USE_OA_PWD_ENCRYPT: "true",
|
|
2335
|
+
model: "iPhone16,2",
|
|
2336
|
+
utdid: input.utdid ?? randomUUID().replace(/-/g, "").slice(0, 20),
|
|
2337
|
+
appVersion: "1895"
|
|
2338
|
+
};
|
|
2339
|
+
const value = JSON.stringify({
|
|
2340
|
+
riskControlInfo,
|
|
2341
|
+
oauthPlateform: 23,
|
|
2342
|
+
oauthAppKey: ALIYUN_APP_KEY,
|
|
2343
|
+
authCode: input.authCode
|
|
2344
|
+
});
|
|
2345
|
+
const signed = signApiGatewayRequest({
|
|
2346
|
+
method: "POST",
|
|
2347
|
+
host,
|
|
2348
|
+
path: "/api/prd/loginbyoauth.json",
|
|
2349
|
+
appKey: ALIYUN_APP_KEY,
|
|
2350
|
+
appSecret: ALIYUN_APP_SECRET,
|
|
2351
|
+
form: { loginByOauthRequest: value }
|
|
2352
|
+
});
|
|
2353
|
+
const json = await postJson(
|
|
2354
|
+
`https://${host}/api/prd/loginbyoauth.json`,
|
|
2355
|
+
signed.headers,
|
|
2356
|
+
signed.body,
|
|
2357
|
+
input.fetchImpl ?? defaultFetch,
|
|
2358
|
+
"loginbyoauth"
|
|
2359
|
+
);
|
|
2360
|
+
const r = LoginByOauthSchema.parse(json).data.data.loginSuccessResult;
|
|
2361
|
+
return {
|
|
2362
|
+
sid: r.sid,
|
|
2363
|
+
refreshToken: r.refreshToken ?? "",
|
|
2364
|
+
openId: r.openAccount?.openId ?? ""
|
|
2365
|
+
};
|
|
2366
|
+
}
|
|
2367
|
+
async function createIotSession(input) {
|
|
2368
|
+
const host = apiIotHost(input.regionId);
|
|
2369
|
+
const path = "/account/createSessionByAuthCode";
|
|
2370
|
+
const payload = {
|
|
2371
|
+
id: randomUUID().toUpperCase(),
|
|
2372
|
+
params: { request: { appKey: ALIYUN_APP_KEY, authCode: input.sid, accountType: "OA_SESSION" } },
|
|
2373
|
+
request: { apiVer: "1.0.4", language: "en-US", appKey: ALIYUN_APP_KEY },
|
|
2374
|
+
version: "1.0.0"
|
|
2375
|
+
};
|
|
2376
|
+
const signed = signApiGatewayRequest({
|
|
2377
|
+
method: "POST",
|
|
2378
|
+
host,
|
|
2379
|
+
path,
|
|
2380
|
+
appKey: ALIYUN_APP_KEY,
|
|
2381
|
+
appSecret: ALIYUN_APP_SECRET,
|
|
2382
|
+
json: payload,
|
|
2383
|
+
extraCaHeaders: { "X-Ca-Stage": "RELEASE" }
|
|
2384
|
+
});
|
|
2385
|
+
const json = await postJson(
|
|
2386
|
+
`https://${host}${path}`,
|
|
2387
|
+
signed.headers,
|
|
2388
|
+
signed.body,
|
|
2389
|
+
input.fetchImpl ?? defaultFetch,
|
|
2390
|
+
"createSessionByAuthCode"
|
|
2391
|
+
);
|
|
2392
|
+
const parsed = CreateSessionSchema.parse(json);
|
|
2393
|
+
if (parsed.code !== 200 && parsed.code !== 0) {
|
|
2394
|
+
throw new DreameApiError(`createSession rejected: code=${parsed.code} msg=${parsed.message ?? "?"}`, 200, parsed);
|
|
2395
|
+
}
|
|
2396
|
+
const d = parsed.data;
|
|
2397
|
+
return {
|
|
2398
|
+
iotToken: d.iotToken,
|
|
2399
|
+
refreshToken: d.refreshToken ?? "",
|
|
2400
|
+
identityId: d.identityId ?? "",
|
|
2401
|
+
expiresAt: Date.now() + (d.iotTokenExpire ?? 72e3) * 1e3
|
|
2402
|
+
};
|
|
2403
|
+
}
|
|
2404
|
+
|
|
2405
|
+
// src/video/aliyun/vision.ts
|
|
2406
|
+
import { z as z5 } from "zod";
|
|
2407
|
+
var VISION_DEVICE_OFFLINE = 9201;
|
|
2408
|
+
var StreamQueryResponseSchema = z5.object({
|
|
2409
|
+
code: z5.number().optional(),
|
|
2410
|
+
message: z5.string().nullish(),
|
|
2411
|
+
data: z5.object({
|
|
2412
|
+
typeList: z5.array(z5.string()).optional(),
|
|
2413
|
+
relayUrl: z5.string().optional(),
|
|
2414
|
+
relayDecryptKey: z5.object({ iv: z5.string().optional(), key: z5.string().optional() }).passthrough().optional(),
|
|
2415
|
+
p2pInfo: z5.object({
|
|
2416
|
+
stunUrl: z5.string().optional(),
|
|
2417
|
+
alterStunUrl: z5.string().optional(),
|
|
2418
|
+
signalUrl: z5.string().optional(),
|
|
2419
|
+
portDetectStunUrlList: z5.array(z5.string()).optional()
|
|
2420
|
+
}).passthrough().optional(),
|
|
2421
|
+
supportVisionPtz: z5.boolean().optional()
|
|
2422
|
+
}).passthrough().optional()
|
|
2423
|
+
}).passthrough();
|
|
2424
|
+
async function streamQuery(input) {
|
|
2425
|
+
const appKey = input.appKey ?? ALIYUN_APP_KEY;
|
|
2426
|
+
const appSecret = input.appSecret ?? ALIYUN_APP_SECRET;
|
|
2427
|
+
const host = apiIotHost(input.regionId);
|
|
2428
|
+
const payload = {
|
|
2429
|
+
id: crypto.randomUUID().toUpperCase(),
|
|
2430
|
+
params: {
|
|
2431
|
+
streamType: input.streamType ?? 0,
|
|
2432
|
+
needDomainName: true,
|
|
2433
|
+
relayEncryptType: 0,
|
|
2434
|
+
clientType: "iOS",
|
|
2435
|
+
iotId: input.iotId,
|
|
2436
|
+
enablePortPredict: true,
|
|
2437
|
+
enableWebSocket: true,
|
|
2438
|
+
forceIFrame: true,
|
|
2439
|
+
cacheDuration: 3e3,
|
|
2440
|
+
relayEncrypted: input.relayEncrypted ?? false
|
|
2441
|
+
},
|
|
2442
|
+
request: { language: "en-US", appKey, iotToken: input.iotToken, apiVer: "2.2.0" },
|
|
2443
|
+
version: "1.0.0"
|
|
2444
|
+
};
|
|
2445
|
+
const signed = signApiGatewayRequest({
|
|
2446
|
+
method: "POST",
|
|
2447
|
+
host,
|
|
2448
|
+
path: VISION_STREAM_QUERY,
|
|
2449
|
+
appKey,
|
|
2450
|
+
appSecret,
|
|
2451
|
+
json: payload,
|
|
2452
|
+
extraCaHeaders: { "X-Ca-Stage": "RELEASE" }
|
|
2453
|
+
});
|
|
2454
|
+
const fetchImpl = input.fetchImpl ?? defaultFetch;
|
|
2455
|
+
const res = await fetchImpl(`https://${host}${VISION_STREAM_QUERY}`, {
|
|
2456
|
+
method: "POST",
|
|
2457
|
+
headers: signed.headers,
|
|
2458
|
+
body: signed.body,
|
|
2459
|
+
...input.signal ? { signal: input.signal } : {}
|
|
2460
|
+
});
|
|
2461
|
+
const text = await res.text();
|
|
2462
|
+
let json;
|
|
2463
|
+
try {
|
|
2464
|
+
json = JSON.parse(text);
|
|
2465
|
+
} catch {
|
|
2466
|
+
throw new DreameApiError(`stream/query returned non-JSON (status ${res.status})`, res.status);
|
|
2467
|
+
}
|
|
2468
|
+
const parsed = StreamQueryResponseSchema.parse(json);
|
|
2469
|
+
if (parsed.code === VISION_DEVICE_OFFLINE) {
|
|
2470
|
+
throw new DreameDeviceOfflineError(
|
|
2471
|
+
`stream/query: device video agent offline (code ${VISION_DEVICE_OFFLINE}) \u2014 retry to wake`,
|
|
2472
|
+
res.status,
|
|
2473
|
+
parsed
|
|
2474
|
+
);
|
|
2475
|
+
}
|
|
2476
|
+
if (parsed.code !== 200 && parsed.code !== 0) {
|
|
2477
|
+
throw new DreameApiError(
|
|
2478
|
+
`stream/query rejected: code=${parsed.code} msg=${parsed.message ?? "?"}`,
|
|
2479
|
+
res.status,
|
|
2480
|
+
parsed
|
|
2481
|
+
);
|
|
2482
|
+
}
|
|
2483
|
+
const d = parsed.data ?? {};
|
|
2484
|
+
const dk = d.relayDecryptKey;
|
|
2485
|
+
const hasKey = dk && dk.iv && dk.key;
|
|
2486
|
+
const p = d.p2pInfo;
|
|
2487
|
+
const p2pInfo = p ? {
|
|
2488
|
+
...p.stunUrl !== void 0 ? { stunUrl: p.stunUrl } : {},
|
|
2489
|
+
...p.alterStunUrl !== void 0 ? { alterStunUrl: p.alterStunUrl } : {},
|
|
2490
|
+
...p.signalUrl !== void 0 ? { signalUrl: p.signalUrl } : {},
|
|
2491
|
+
...p.portDetectStunUrlList !== void 0 ? { portDetectStunUrlList: p.portDetectStunUrlList } : {}
|
|
2492
|
+
} : null;
|
|
2493
|
+
return {
|
|
2494
|
+
typeList: d.typeList ?? [],
|
|
2495
|
+
relayUrl: d.relayUrl ?? null,
|
|
2496
|
+
relayDecryptKey: hasKey ? { iv: dk.iv, key: dk.key } : null,
|
|
2497
|
+
p2pInfo,
|
|
2498
|
+
...d.supportVisionPtz !== void 0 ? { supportVisionPtz: d.supportVisionPtz } : {}
|
|
2499
|
+
};
|
|
2500
|
+
}
|
|
2501
|
+
|
|
2502
|
+
// src/video/aliyun/session.ts
|
|
2503
|
+
var DEFAULT_WAKE_TIMEOUT_MS = 3e4;
|
|
2504
|
+
var DEFAULT_WAKE_POLL_MS = 2e3;
|
|
2505
|
+
var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
2506
|
+
var REFRESH_LEEWAY_MS = 6e4;
|
|
2507
|
+
var DreameVideoSession = class {
|
|
2508
|
+
#session;
|
|
2509
|
+
#region;
|
|
2510
|
+
#regionId;
|
|
2511
|
+
#fetchImpl;
|
|
2512
|
+
#iot = null;
|
|
2513
|
+
#inFlight = null;
|
|
2514
|
+
constructor(input) {
|
|
2515
|
+
this.#session = input.session;
|
|
2516
|
+
this.#region = input.region;
|
|
2517
|
+
this.#regionId = ALIYUN_REGION_ID[input.region];
|
|
2518
|
+
this.#fetchImpl = input.fetchImpl;
|
|
2519
|
+
}
|
|
2520
|
+
/** The resolved Aliyun IoT region id (e.g. `eu-central-1`). */
|
|
2521
|
+
get regionId() {
|
|
2522
|
+
return this.#regionId;
|
|
2523
|
+
}
|
|
2524
|
+
/** Mint (or reuse) a valid Aliyun IoT session, refreshing before expiry. */
|
|
2525
|
+
async ensureIotSession() {
|
|
2526
|
+
const cur = this.#iot;
|
|
2527
|
+
if (cur && Date.now() < cur.expiresAt - REFRESH_LEEWAY_MS) {
|
|
2528
|
+
return cur;
|
|
2529
|
+
}
|
|
2530
|
+
if (this.#inFlight) {
|
|
2531
|
+
return this.#inFlight;
|
|
2532
|
+
}
|
|
2533
|
+
this.#inFlight = this.#mint();
|
|
2534
|
+
try {
|
|
2535
|
+
this.#iot = await this.#inFlight;
|
|
2536
|
+
return this.#iot;
|
|
2537
|
+
} finally {
|
|
2538
|
+
this.#inFlight = null;
|
|
2539
|
+
}
|
|
2540
|
+
}
|
|
2541
|
+
async #mint() {
|
|
2542
|
+
const base = {
|
|
2543
|
+
session: this.#session,
|
|
2544
|
+
region: this.#region,
|
|
2545
|
+
...this.#fetchImpl ? { fetchImpl: this.#fetchImpl } : {}
|
|
2546
|
+
};
|
|
2547
|
+
const authCode = await getAliyunAuthCode(base);
|
|
2548
|
+
const oa = await loginByOauth({
|
|
2549
|
+
authCode,
|
|
2550
|
+
regionId: this.#regionId,
|
|
2551
|
+
...this.#fetchImpl ? { fetchImpl: this.#fetchImpl } : {}
|
|
2552
|
+
});
|
|
2553
|
+
return createIotSession({
|
|
2554
|
+
sid: oa.sid,
|
|
2555
|
+
regionId: this.#regionId,
|
|
2556
|
+
...this.#fetchImpl ? { fetchImpl: this.#fetchImpl } : {}
|
|
2557
|
+
});
|
|
2558
|
+
}
|
|
2559
|
+
/**
|
|
2560
|
+
* Mint a fresh LinkVisual stream descriptor for a device. `encrypted:false`
|
|
2561
|
+
* (default) yields a plain RTMP relay URL directly playable by ffmpeg.
|
|
2562
|
+
*
|
|
2563
|
+
* A camera that has been idle reports "device offline" until the query wakes
|
|
2564
|
+
* its video agent via the LinkVisual cloud. This transparently retries on that
|
|
2565
|
+
* (up to `wakeTimeoutMs`, default 30s) so a single call returns a live stream;
|
|
2566
|
+
* pass `wakeTimeoutMs: 0` to fail fast instead.
|
|
2567
|
+
*/
|
|
2568
|
+
async getStreamInfo(iotId, opts) {
|
|
2569
|
+
const deadline = Date.now() + (opts?.wakeTimeoutMs ?? DEFAULT_WAKE_TIMEOUT_MS);
|
|
2570
|
+
const pollMs = opts?.pollMs ?? DEFAULT_WAKE_POLL_MS;
|
|
2571
|
+
for (; ; ) {
|
|
2572
|
+
const iot = await this.ensureIotSession();
|
|
2573
|
+
try {
|
|
2574
|
+
return await streamQuery({
|
|
2575
|
+
regionId: this.#regionId,
|
|
2576
|
+
iotToken: iot.iotToken,
|
|
2577
|
+
iotId,
|
|
2578
|
+
relayEncrypted: opts?.encrypted ?? false,
|
|
2579
|
+
...this.#fetchImpl ? { fetchImpl: this.#fetchImpl } : {}
|
|
2580
|
+
});
|
|
2581
|
+
} catch (err) {
|
|
2582
|
+
if (err instanceof DreameDeviceOfflineError && Date.now() + pollMs < deadline) {
|
|
2583
|
+
await sleep(pollMs);
|
|
2584
|
+
continue;
|
|
2585
|
+
}
|
|
2586
|
+
throw err;
|
|
2587
|
+
}
|
|
2588
|
+
}
|
|
2589
|
+
}
|
|
2590
|
+
/**
|
|
2591
|
+
* Convenience: mint a fresh plain RTMP relay URL for a device, or `null` when
|
|
2592
|
+
* the device is not currently streaming (no relay available).
|
|
2593
|
+
*/
|
|
2594
|
+
async getRtmpUrl(iotId) {
|
|
2595
|
+
const info = await this.getStreamInfo(iotId, { encrypted: false });
|
|
2596
|
+
return info.relayUrl;
|
|
2597
|
+
}
|
|
2598
|
+
};
|
|
2599
|
+
|
|
2600
|
+
// src/video/camera-availability.ts
|
|
2601
|
+
function explainNoCameraChannel(profile) {
|
|
2602
|
+
if (profile.iotId) {
|
|
2603
|
+
return null;
|
|
2604
|
+
}
|
|
2605
|
+
const who = `${profile.model || "unknown model"} (${profile.did || "no did"})`;
|
|
2606
|
+
if (!profile.videoCapable) {
|
|
2607
|
+
return `${who} is not a camera: the cloud lists no video permit and no supported video vendor for it, so there is no channel to open.`;
|
|
2608
|
+
}
|
|
2609
|
+
if (!profile.online) {
|
|
2610
|
+
return `${who} is a camera but is OFFLINE. The video binding is published by the device itself, so there is nothing to read until it connects \u2014 this is not a provisioning fault.`;
|
|
2611
|
+
}
|
|
2612
|
+
const on = profile.currentVendor ?? "none";
|
|
2613
|
+
const supports = profile.supportedVendors.length > 0 ? profile.supportedVendors.join(", ") : "none";
|
|
2614
|
+
return `${who} is a camera and online, but has no video channel yet (vendor: ${on}; supports: ${supports}). The device has not bound to the video service \u2014 open its camera once in the Dreame app to create the binding, then retry.`;
|
|
2615
|
+
}
|
|
2616
|
+
|
|
2617
|
+
// src/video/monitor/constants.ts
|
|
2618
|
+
var MONITOR_SIID = 10001;
|
|
2619
|
+
var MONITOR_AIID = {
|
|
2620
|
+
/** Stream lifecycle + keep-alive (monitor start/end, keep_alive). */
|
|
2621
|
+
CAMERA_OPERATE: 1,
|
|
2622
|
+
/** Two-way intercom start/end. */
|
|
2623
|
+
VOICE_OPERATE: 2,
|
|
2624
|
+
/** Generic property-scoped operations. */
|
|
2625
|
+
PROPERTY_OPERATE: 3,
|
|
2626
|
+
/** Privacy access-code gate (launch/verify/set/reset). */
|
|
2627
|
+
ACCESS_CODE_OPERATE: 4,
|
|
2628
|
+
/** Video-vendor SDK init / switch. */
|
|
2629
|
+
VIDEO_VENDOR: 7
|
|
2630
|
+
};
|
|
2631
|
+
var MONITOR_PIID = {
|
|
2632
|
+
MONITOR_STATUS: 1,
|
|
2633
|
+
MONITOR_AUDIO_STATUS: 2,
|
|
2634
|
+
MONITOR_RECORD_STATUS: 4,
|
|
2635
|
+
TAKE_PHOTO: 5,
|
|
2636
|
+
KEEP_ALIVE: 6,
|
|
2637
|
+
MONITOR_FAULTS: 7,
|
|
2638
|
+
FILL_LIGHT_SET: 9,
|
|
2639
|
+
CAMERA_LIGHT_SWITCH: 10,
|
|
2640
|
+
VIDEO_VENDOR_STATUS: 11,
|
|
2641
|
+
GET_PROPERTY: 99,
|
|
2642
|
+
PERSON_DATA: 110,
|
|
2643
|
+
VIDEO_OBSTACLE_SWITCH: 111,
|
|
2644
|
+
VIDEO_OBSTACLE_DATA: 112,
|
|
2645
|
+
MONITOR_TASK_STATUS: 103,
|
|
2646
|
+
UPLOAD_STATUS: 1003,
|
|
2647
|
+
GET_ACCESS_CODE: 1100,
|
|
2648
|
+
SET_ACCESS_CODE: 1101,
|
|
2649
|
+
VERIFY_ACCESS_CODE: 1102,
|
|
2650
|
+
MONITOR_REST_MODE: 1103,
|
|
2651
|
+
SET_ACCESS_HOT_STATUS: 1104,
|
|
2652
|
+
MONITOR_SPACE: 2003
|
|
2653
|
+
};
|
|
2654
|
+
var MONITOR_VENDOR_TOKEN = {
|
|
2655
|
+
ali: "alify",
|
|
2656
|
+
tx: "tx"
|
|
2657
|
+
};
|
|
2658
|
+
var VACUUM_SIID = 4;
|
|
2659
|
+
var VACUUM_MOVE = {
|
|
2660
|
+
/** Remote-drive state property (set_properties), sent ~1 Hz while held. */
|
|
2661
|
+
REMOTE_STATE_PIID: 15,
|
|
2662
|
+
/** Work-mode action instance (go-to-point, cruise, person-follow start). */
|
|
2663
|
+
WORK_AIID: 1,
|
|
2664
|
+
/** Work-mode stop action instance (person-follow stop). */
|
|
2665
|
+
STOP_AIID: 2,
|
|
2666
|
+
/** piid carrying the work-mode selector value in the WORK action. */
|
|
2667
|
+
MODE_PIID: 1,
|
|
2668
|
+
/** piid carrying the point-info JSON in the WORK action. */
|
|
2669
|
+
POINT_PIID: 10,
|
|
2670
|
+
/** Work-mode selector values. */
|
|
2671
|
+
MODE_SPOT: 23,
|
|
2672
|
+
// go to point (MonitorSpotMode)
|
|
2673
|
+
MODE_CRUISE: 22,
|
|
2674
|
+
// cruise / patrol / find-pet
|
|
2675
|
+
MODE_PERSON_FOLLOW: 26,
|
|
2676
|
+
MODE_SPOT_CLEAN: 20,
|
|
2677
|
+
// spot-clean the current position (SpotClean)
|
|
2678
|
+
/** Auto-switch setter property (fill-light auto/full toggle lives here). */
|
|
2679
|
+
AUTO_SWITCH_PIID: 50
|
|
2680
|
+
};
|
|
2681
|
+
var VACUUM_CHARGE = { siid: 3, aiid: 1 };
|
|
2682
|
+
var VOICE_SIID = 7;
|
|
2683
|
+
var VOICE_LOCATE_AIID = 1;
|
|
2684
|
+
var VOICE_PLAY_SOUND_AIID = 2;
|
|
2685
|
+
var VOICE_SOUND_PIID = 4;
|
|
2686
|
+
var VACUUM_LOCATE = { siid: VOICE_SIID, aiid: VOICE_LOCATE_AIID };
|
|
2687
|
+
var PET_SOUNDS = {
|
|
2688
|
+
meow: 684,
|
|
2689
|
+
bark: 685,
|
|
2690
|
+
footsteps: 686,
|
|
2691
|
+
purring: 687,
|
|
2692
|
+
tickTock: 688
|
|
2693
|
+
};
|
|
2694
|
+
var VACUUM_ACTIONS = {
|
|
2695
|
+
startClean: { siid: 2, aiid: 1 },
|
|
2696
|
+
pauseClean: { siid: 2, aiid: 2 },
|
|
2697
|
+
stopClean: { siid: 4, aiid: 2 },
|
|
2698
|
+
dockWash: { siid: 4, aiid: 4 },
|
|
2699
|
+
autoEmpty: { siid: 15, aiid: 1 }
|
|
2700
|
+
};
|
|
2701
|
+
|
|
2702
|
+
// src/video/monitor/protocol.ts
|
|
2703
|
+
import { createHash as createHash3 } from "crypto";
|
|
2704
|
+
function makeMonitorSession(accountId, now = Date.now()) {
|
|
2705
|
+
return createHash3("md5").update(`${accountId}_${now}`).digest("hex");
|
|
2706
|
+
}
|
|
2707
|
+
function hashAccessCode(code) {
|
|
2708
|
+
return createHash3("sha256").update(code).digest("hex");
|
|
2709
|
+
}
|
|
2710
|
+
function buildActionInput(piid, params, session) {
|
|
2711
|
+
const value = JSON.stringify({ ...params ?? {}, session });
|
|
2712
|
+
return { piid, value };
|
|
2713
|
+
}
|
|
2714
|
+
function startMonitorParams(iotId, vendor, area) {
|
|
2715
|
+
return {
|
|
2716
|
+
token: MONITOR_VENDOR_TOKEN[vendor],
|
|
2717
|
+
channelId: iotId,
|
|
2718
|
+
area,
|
|
2719
|
+
operType: "monitor",
|
|
2720
|
+
operation: "start"
|
|
2721
|
+
};
|
|
2722
|
+
}
|
|
2723
|
+
function stopMonitorParams() {
|
|
2724
|
+
return { operType: "monitor", operation: "end" };
|
|
2725
|
+
}
|
|
2726
|
+
function keepAliveParams(videoStatus) {
|
|
2727
|
+
return { operType: "keep_alive", videoStatus };
|
|
2728
|
+
}
|
|
2729
|
+
function accessCodeLaunchParams() {
|
|
2730
|
+
return { open: true };
|
|
2731
|
+
}
|
|
2732
|
+
function verifyAccessCodeParams(code, lazymode = 0) {
|
|
2733
|
+
return { oldcode: hashAccessCode(code), lazymode };
|
|
2734
|
+
}
|
|
2735
|
+
function intercomStartParams(opts) {
|
|
2736
|
+
return {
|
|
2737
|
+
operType: "intercom",
|
|
2738
|
+
operation: "start",
|
|
2739
|
+
...opts?.needRecordSound !== void 0 ? { need_record_sound: opts.needRecordSound } : {},
|
|
2740
|
+
...opts?.videoCall ? { phone: 1 } : {}
|
|
2741
|
+
};
|
|
2742
|
+
}
|
|
2743
|
+
function intercomStopParams() {
|
|
2744
|
+
return { operType: "intercom", operation: "end" };
|
|
2745
|
+
}
|
|
2746
|
+
function fillLightParams(value) {
|
|
2747
|
+
return { value: String(value) };
|
|
2748
|
+
}
|
|
2749
|
+
function takePhotoParams() {
|
|
2750
|
+
return { operType: "takephoto", operation: "start" };
|
|
2751
|
+
}
|
|
2752
|
+
function remoteDriveValue(spdv, spdw, now = Date.now()) {
|
|
2753
|
+
return JSON.stringify({
|
|
2754
|
+
spdv,
|
|
2755
|
+
spdw,
|
|
2756
|
+
audio: "false",
|
|
2757
|
+
random: Math.floor(Math.random() * 1e3),
|
|
2758
|
+
timestamp: now
|
|
2759
|
+
});
|
|
2760
|
+
}
|
|
2761
|
+
var DRIVE_DIRECTIONS = {
|
|
2762
|
+
forward: [200, 0],
|
|
2763
|
+
left: [0, 45],
|
|
2764
|
+
right: [0, -45],
|
|
2765
|
+
turnAround: [0, 180],
|
|
2766
|
+
stop: [0, 0]
|
|
2767
|
+
};
|
|
2768
|
+
function actionCode(res) {
|
|
2769
|
+
const r = res;
|
|
2770
|
+
return typeof r?.code === "number" ? r.code : null;
|
|
2771
|
+
}
|
|
2772
|
+
function firstOutValue(res) {
|
|
2773
|
+
const r = res;
|
|
2774
|
+
const out = r?.out ?? r?.result?.out;
|
|
2775
|
+
return Array.isArray(out) && out.length > 0 ? out[0]?.value : void 0;
|
|
2776
|
+
}
|
|
2777
|
+
|
|
2778
|
+
// src/video/monitor/controller.ts
|
|
2779
|
+
var DEFAULT_KEEP_ALIVE_MS = 1e4;
|
|
2780
|
+
var DEFAULT_AREA = "4";
|
|
2781
|
+
var DreameCameraController = class {
|
|
2782
|
+
#device;
|
|
2783
|
+
#relay;
|
|
2784
|
+
#iotId;
|
|
2785
|
+
#accountId;
|
|
2786
|
+
#vendor;
|
|
2787
|
+
#accessCode;
|
|
2788
|
+
#area;
|
|
2789
|
+
#keepAliveIntervalMs;
|
|
2790
|
+
#wakeTimeoutMs;
|
|
2791
|
+
#onKeepAliveError;
|
|
2792
|
+
#log;
|
|
2793
|
+
#session = null;
|
|
2794
|
+
#keepAliveTimer = null;
|
|
2795
|
+
#opened = false;
|
|
2796
|
+
constructor(input) {
|
|
2797
|
+
this.#device = input.device;
|
|
2798
|
+
this.#relay = input.relay;
|
|
2799
|
+
this.#iotId = input.iotId;
|
|
2800
|
+
this.#accountId = input.accountId;
|
|
2801
|
+
this.#vendor = input.vendor ?? "ali";
|
|
2802
|
+
this.#accessCode = input.accessCode;
|
|
2803
|
+
this.#area = input.area ?? DEFAULT_AREA;
|
|
2804
|
+
this.#keepAliveIntervalMs = input.keepAliveIntervalMs ?? DEFAULT_KEEP_ALIVE_MS;
|
|
2805
|
+
this.#wakeTimeoutMs = input.wakeTimeoutMs;
|
|
2806
|
+
this.#onKeepAliveError = input.onKeepAliveError;
|
|
2807
|
+
this.#log = input.log ?? (() => {
|
|
2808
|
+
});
|
|
2809
|
+
}
|
|
2810
|
+
#logLine(msg) {
|
|
2811
|
+
this.#log(`[nodedreame:monitor] ${msg}`);
|
|
2812
|
+
}
|
|
2813
|
+
/** True while a monitor session is active (between {@link open} and {@link close}). */
|
|
2814
|
+
get isOpen() {
|
|
2815
|
+
return this.#opened;
|
|
2816
|
+
}
|
|
2817
|
+
/** Send one camera action, resolving to the raw device reply. */
|
|
2818
|
+
async #action(aiid, piid, params) {
|
|
2819
|
+
if (!this.#session) {
|
|
2820
|
+
throw new DreameError("camera controller has no session; call open() first");
|
|
2821
|
+
}
|
|
2822
|
+
const input = buildActionInput(piid, params, this.#session);
|
|
2823
|
+
return this.#device.callAction(MONITOR_SIID, aiid, [input]);
|
|
2824
|
+
}
|
|
2825
|
+
/**
|
|
2826
|
+
* Run the full cold-start sequence and return a live relay URL. Starts the
|
|
2827
|
+
* keep-alive loop; the caller MUST {@link close} when done to release the
|
|
2828
|
+
* device. Throws if the monitor cannot be started or no relay comes up.
|
|
2829
|
+
*/
|
|
2830
|
+
async open() {
|
|
2831
|
+
if (this.#opened) {
|
|
2832
|
+
throw new DreameError("camera stream already open");
|
|
2833
|
+
}
|
|
2834
|
+
this.#session = makeMonitorSession(this.#accountId);
|
|
2835
|
+
this.#logLine(`open: vendor=${this.#vendor} iotId=${this.#iotId} area=${this.#area}`);
|
|
2836
|
+
await this.#tryPrime();
|
|
2837
|
+
const startRes = await this.#startMonitorWithGate();
|
|
2838
|
+
const encryptionKey = asString(firstOutValue(startRes));
|
|
2839
|
+
this.#logLine(`startMonitor accepted (encryptionKey=${encryptionKey ? "yes" : "no"})`);
|
|
2840
|
+
this.#opened = true;
|
|
2841
|
+
this.#startKeepAlive();
|
|
2842
|
+
let relayUrl;
|
|
2843
|
+
try {
|
|
2844
|
+
const info = await this.#relay.getStreamInfo(this.#iotId, {
|
|
2845
|
+
encrypted: false,
|
|
2846
|
+
...this.#wakeTimeoutMs !== void 0 ? { wakeTimeoutMs: this.#wakeTimeoutMs } : {}
|
|
2847
|
+
});
|
|
2848
|
+
relayUrl = info.relayUrl;
|
|
2849
|
+
} catch (err) {
|
|
2850
|
+
this.#logLine(`relay mint failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
2851
|
+
await this.close();
|
|
2852
|
+
throw err;
|
|
2853
|
+
}
|
|
2854
|
+
if (!relayUrl) {
|
|
2855
|
+
await this.close();
|
|
2856
|
+
throw new DreameError("monitor started but no relay URL was returned");
|
|
2857
|
+
}
|
|
2858
|
+
this.#logLine("relay up");
|
|
2859
|
+
return { rtmpUrl: relayUrl, encryptionKey };
|
|
2860
|
+
}
|
|
2861
|
+
async #tryPrime() {
|
|
2862
|
+
try {
|
|
2863
|
+
await this.#action(MONITOR_AIID.ACCESS_CODE_OPERATE, MONITOR_PIID.GET_ACCESS_CODE, accessCodeLaunchParams());
|
|
2864
|
+
} catch {
|
|
2865
|
+
}
|
|
2866
|
+
try {
|
|
2867
|
+
await this.#action(MONITOR_AIID.VIDEO_VENDOR, MONITOR_PIID.VIDEO_VENDOR_STATUS, null);
|
|
2868
|
+
} catch {
|
|
2869
|
+
}
|
|
2870
|
+
}
|
|
2871
|
+
async #startMonitorWithGate() {
|
|
2872
|
+
const params = startMonitorParams(this.#iotId, this.#vendor, this.#area);
|
|
2873
|
+
let res = await this.#action(MONITOR_AIID.CAMERA_OPERATE, MONITOR_PIID.MONITOR_STATUS, params);
|
|
2874
|
+
if (actionCode(res) === 0) {
|
|
2875
|
+
return res;
|
|
2876
|
+
}
|
|
2877
|
+
this.#logLine(`startMonitor refused (code ${actionCode(res) ?? "?"}); verifying access code`);
|
|
2878
|
+
if (this.#accessCode) {
|
|
2879
|
+
await this.#action(
|
|
2880
|
+
MONITOR_AIID.ACCESS_CODE_OPERATE,
|
|
2881
|
+
MONITOR_PIID.VERIFY_ACCESS_CODE,
|
|
2882
|
+
verifyAccessCodeParams(this.#accessCode)
|
|
2883
|
+
);
|
|
2884
|
+
res = await this.#action(MONITOR_AIID.CAMERA_OPERATE, MONITOR_PIID.MONITOR_STATUS, params);
|
|
2885
|
+
}
|
|
2886
|
+
if (actionCode(res) !== 0) {
|
|
2887
|
+
const code = actionCode(res);
|
|
2888
|
+
throw new DreameError(
|
|
2889
|
+
`startMonitor refused (code ${code ?? "?"})` + (this.#accessCode ? "" : "; device likely requires an accessCode")
|
|
2890
|
+
);
|
|
2891
|
+
}
|
|
2892
|
+
return res;
|
|
2893
|
+
}
|
|
2894
|
+
#startKeepAlive() {
|
|
2895
|
+
this.#stopKeepAlive();
|
|
2896
|
+
this.#keepAliveTimer = setInterval(() => {
|
|
2897
|
+
void this.#action(MONITOR_AIID.CAMERA_OPERATE, MONITOR_PIID.KEEP_ALIVE, keepAliveParams("opened")).catch(
|
|
2898
|
+
(err) => this.#onKeepAliveError?.(err)
|
|
2899
|
+
);
|
|
2900
|
+
}, this.#keepAliveIntervalMs);
|
|
2901
|
+
this.#keepAliveTimer.unref?.();
|
|
2902
|
+
}
|
|
2903
|
+
#stopKeepAlive() {
|
|
2904
|
+
if (this.#keepAliveTimer) {
|
|
2905
|
+
clearInterval(this.#keepAliveTimer);
|
|
2906
|
+
this.#keepAliveTimer = null;
|
|
2907
|
+
}
|
|
2908
|
+
}
|
|
2909
|
+
/**
|
|
2910
|
+
* Mint a FRESH single-use RTMP relay URL for the already-open monitor. Each
|
|
2911
|
+
* consumer needs its own relay URL, so call this once per ffmpeg/consumer.
|
|
2912
|
+
* Throws if the stream is not open.
|
|
2913
|
+
*/
|
|
2914
|
+
async mintRelayUrl() {
|
|
2915
|
+
if (!this.#opened) {
|
|
2916
|
+
throw new DreameError("camera stream is not open; call open() first");
|
|
2917
|
+
}
|
|
2918
|
+
const info = await this.#relay.getStreamInfo(this.#iotId, {
|
|
2919
|
+
encrypted: false,
|
|
2920
|
+
...this.#wakeTimeoutMs !== void 0 ? { wakeTimeoutMs: this.#wakeTimeoutMs } : {}
|
|
2921
|
+
});
|
|
2922
|
+
if (!info.relayUrl) {
|
|
2923
|
+
throw new DreameError("no relay URL available for the open monitor");
|
|
2924
|
+
}
|
|
2925
|
+
return info.relayUrl;
|
|
2926
|
+
}
|
|
2927
|
+
/** Start the two-way intercom session (control plane only; see module docs on mic uplink). */
|
|
2928
|
+
async startIntercom(opts) {
|
|
2929
|
+
return this.#action(MONITOR_AIID.VOICE_OPERATE, MONITOR_PIID.MONITOR_AUDIO_STATUS, intercomStartParams(opts));
|
|
2930
|
+
}
|
|
2931
|
+
/** Stop the two-way intercom session. */
|
|
2932
|
+
async stopIntercom() {
|
|
2933
|
+
return this.#action(MONITOR_AIID.VOICE_OPERATE, MONITOR_PIID.MONITOR_AUDIO_STATUS, intercomStopParams());
|
|
2934
|
+
}
|
|
2935
|
+
/** Set the fill-light brightness (40–100 = manual %, below 40 / 101 = auto). */
|
|
2936
|
+
async setFillLight(value) {
|
|
2937
|
+
return this.#action(MONITOR_AIID.PROPERTY_OPERATE, MONITOR_PIID.FILL_LIGHT_SET, fillLightParams(value));
|
|
2938
|
+
}
|
|
2939
|
+
/**
|
|
2940
|
+
* Device-side snapshot: the robot captures a still and uploads it to cloud
|
|
2941
|
+
* storage (read the result back from the `uploadStatus` property). Prefer a
|
|
2942
|
+
* frame-grab from the live stream for an instant image.
|
|
2943
|
+
*/
|
|
2944
|
+
async takePhoto() {
|
|
2945
|
+
return this.#action(MONITOR_AIID.CAMERA_OPERATE, MONITOR_PIID.TAKE_PHOTO, takePhotoParams());
|
|
2946
|
+
}
|
|
2947
|
+
/**
|
|
2948
|
+
* Remote-drive the robot ("PTZ" substitute — the camera is fixed, the robot
|
|
2949
|
+
* moves). `spdv` = forward speed, `spdw` = turn; send repeatedly (~1 Hz) while
|
|
2950
|
+
* a direction is held, then `stop`. Only valid while the stream is open.
|
|
2951
|
+
*/
|
|
2952
|
+
async drive(spdv, spdw) {
|
|
2953
|
+
this.#requireSession();
|
|
2954
|
+
if (!this.#device.setProperty) {
|
|
2955
|
+
throw new DreameError("device does not support setProperty; cannot remote-drive");
|
|
2956
|
+
}
|
|
2957
|
+
return this.#device.setProperty({
|
|
2958
|
+
siid: VACUUM_SIID,
|
|
2959
|
+
piid: VACUUM_MOVE.REMOTE_STATE_PIID,
|
|
2960
|
+
value: remoteDriveValue(spdv, spdw)
|
|
2961
|
+
});
|
|
2962
|
+
}
|
|
2963
|
+
/** Remote-drive by named direction (forward/left/right/turnAround/stop). */
|
|
2964
|
+
async driveDirection(direction) {
|
|
2965
|
+
const [spdv, spdw] = DRIVE_DIRECTIONS[direction];
|
|
2966
|
+
return this.drive(spdv, spdw);
|
|
2967
|
+
}
|
|
2968
|
+
/** Start person-follow mode (robot tracks a detected person). */
|
|
2969
|
+
async startPersonFollow() {
|
|
2970
|
+
this.#requireSession();
|
|
2971
|
+
return this.#device.callAction(VACUUM_SIID, VACUUM_MOVE.WORK_AIID, [
|
|
2972
|
+
{ piid: VACUUM_MOVE.MODE_PIID, value: VACUUM_MOVE.MODE_PERSON_FOLLOW }
|
|
2973
|
+
]);
|
|
2974
|
+
}
|
|
2975
|
+
/**
|
|
2976
|
+
* Universal stop for the current work mode — stops person-follow, spot-clean,
|
|
2977
|
+
* go-to-point, cruise, etc. (siid 4 / aiid 2).
|
|
2978
|
+
*/
|
|
2979
|
+
async stopWork() {
|
|
2980
|
+
return this.#device.callAction(VACUUM_SIID, VACUUM_MOVE.STOP_AIID, []);
|
|
2981
|
+
}
|
|
2982
|
+
/** Stop person-follow mode (alias for {@link stopWork}). */
|
|
2983
|
+
async stopPersonFollow() {
|
|
2984
|
+
return this.stopWork();
|
|
2985
|
+
}
|
|
2986
|
+
/** Spot-clean the robot's current position (WorkMode SpotClean). */
|
|
2987
|
+
async spotClean() {
|
|
2988
|
+
return this.#device.callAction(VACUUM_SIID, VACUUM_MOVE.WORK_AIID, [
|
|
2989
|
+
{ piid: VACUUM_MOVE.MODE_PIID, value: VACUUM_MOVE.MODE_SPOT_CLEAN }
|
|
2990
|
+
]);
|
|
2991
|
+
}
|
|
2992
|
+
/** Play one of the robot's sound clips (e.g. pet sounds) by id. */
|
|
2993
|
+
async playSound(soundId) {
|
|
2994
|
+
return this.#device.callAction(VOICE_SIID, VOICE_PLAY_SOUND_AIID, [
|
|
2995
|
+
{ piid: VOICE_SOUND_PIID, value: soundId }
|
|
2996
|
+
]);
|
|
2997
|
+
}
|
|
2998
|
+
/** Play a named pet-teasing sound (meow/bark/footsteps/purring/tickTock). */
|
|
2999
|
+
async playPetSound(sound) {
|
|
3000
|
+
return this.playSound(PET_SOUNDS[sound]);
|
|
3001
|
+
}
|
|
3002
|
+
/** Run a common whole-robot action (startClean/pauseClean/stopClean/dockWash/autoEmpty). */
|
|
3003
|
+
async runVacuumAction(action) {
|
|
3004
|
+
const a = VACUUM_ACTIONS[action];
|
|
3005
|
+
return this.#device.callAction(a.siid, a.aiid, []);
|
|
3006
|
+
}
|
|
3007
|
+
/** Find-pet: cruise the home looking for the pet. */
|
|
3008
|
+
async findPet() {
|
|
3009
|
+
this.#requireSession();
|
|
3010
|
+
return this.#device.callAction(VACUUM_SIID, VACUUM_MOVE.WORK_AIID, [
|
|
3011
|
+
{ piid: VACUUM_MOVE.MODE_PIID, value: VACUUM_MOVE.MODE_CRUISE },
|
|
3012
|
+
{ piid: VACUUM_MOVE.POINT_PIID, value: JSON.stringify({ findpet: "" }) }
|
|
3013
|
+
]);
|
|
3014
|
+
}
|
|
3015
|
+
/** Send the robot to a map point (`spoint` current, `tpoint` targets). */
|
|
3016
|
+
async goToPoint(spoint, tpoint) {
|
|
3017
|
+
this.#requireSession();
|
|
3018
|
+
return this.#device.callAction(VACUUM_SIID, VACUUM_MOVE.WORK_AIID, [
|
|
3019
|
+
{ piid: VACUUM_MOVE.MODE_PIID, value: VACUUM_MOVE.MODE_SPOT },
|
|
3020
|
+
{ piid: VACUUM_MOVE.POINT_PIID, value: JSON.stringify({ spoint, tpoint }) }
|
|
3021
|
+
]);
|
|
3022
|
+
}
|
|
3023
|
+
/** Toggle the fill light between auto (`full=false`) and full-on (`full=true`). */
|
|
3024
|
+
async setFillLightAuto(full) {
|
|
3025
|
+
if (!this.#device.setProperty) {
|
|
3026
|
+
throw new DreameError("device does not support setProperty; cannot toggle fill light");
|
|
3027
|
+
}
|
|
3028
|
+
return this.#device.setProperty({
|
|
3029
|
+
siid: VACUUM_SIID,
|
|
3030
|
+
piid: VACUUM_MOVE.AUTO_SWITCH_PIID,
|
|
3031
|
+
value: JSON.stringify({ k: "FillinLight", v: full ? 1 : 0 })
|
|
3032
|
+
});
|
|
3033
|
+
}
|
|
3034
|
+
/**
|
|
3035
|
+
* Send the robot back to its dock to charge ("go home"). Works regardless of
|
|
3036
|
+
* stream state — usable as a standalone command or a PTZ "home" preset.
|
|
3037
|
+
*/
|
|
3038
|
+
async returnToDock() {
|
|
3039
|
+
return this.#device.callAction(VACUUM_CHARGE.siid, VACUUM_CHARGE.aiid, []);
|
|
3040
|
+
}
|
|
3041
|
+
/** Locate the robot — it beeps. Works regardless of stream state. */
|
|
3042
|
+
async locate() {
|
|
3043
|
+
return this.#device.callAction(VACUUM_LOCATE.siid, VACUUM_LOCATE.aiid, []);
|
|
3044
|
+
}
|
|
3045
|
+
#requireSession() {
|
|
3046
|
+
if (!this.#opened) {
|
|
3047
|
+
throw new DreameError("camera stream is not open; call open() first");
|
|
3048
|
+
}
|
|
3049
|
+
}
|
|
3050
|
+
/** Stop the keep-alive loop and release the monitor on the device. Idempotent. */
|
|
3051
|
+
async close() {
|
|
3052
|
+
this.#stopKeepAlive();
|
|
3053
|
+
if (!this.#opened) {
|
|
3054
|
+
this.#session = null;
|
|
3055
|
+
return;
|
|
3056
|
+
}
|
|
3057
|
+
this.#opened = false;
|
|
3058
|
+
this.#logLine("close: stopping monitor");
|
|
3059
|
+
try {
|
|
3060
|
+
await this.#action(MONITOR_AIID.CAMERA_OPERATE, MONITOR_PIID.MONITOR_STATUS, stopMonitorParams());
|
|
3061
|
+
} finally {
|
|
3062
|
+
this.#session = null;
|
|
3063
|
+
}
|
|
3064
|
+
}
|
|
3065
|
+
};
|
|
3066
|
+
function asString(v) {
|
|
3067
|
+
return typeof v === "string" ? v : null;
|
|
3068
|
+
}
|
|
3069
|
+
|
|
2017
3070
|
// src/models/vacuum/map/envelope.ts
|
|
2018
|
-
import { createDecipheriv, createHash as
|
|
3071
|
+
import { createDecipheriv, createHash as createHash4 } from "crypto";
|
|
2019
3072
|
import * as zlib from "zlib";
|
|
2020
3073
|
var HEADER_SIZE = 27;
|
|
2021
3074
|
var ANGLE_ABSENT = 32767;
|
|
@@ -2093,7 +3146,7 @@ function looksLikeBase64Zlib(buf) {
|
|
|
2093
3146
|
}
|
|
2094
3147
|
function aesCbcDecrypt(cipher, rawKey, iv) {
|
|
2095
3148
|
const keyBytes = Buffer.from(
|
|
2096
|
-
|
|
3149
|
+
createHash4("sha256").update(rawKey).digest("hex").slice(0, 32),
|
|
2097
3150
|
"utf8"
|
|
2098
3151
|
);
|
|
2099
3152
|
const ivBytes = Buffer.from(iv, "utf8");
|
|
@@ -3434,6 +4487,97 @@ function drawLabel(png, cx, cy, text, color, px) {
|
|
|
3434
4487
|
}
|
|
3435
4488
|
}
|
|
3436
4489
|
|
|
4490
|
+
// src/models/vacuum/map/wifi.ts
|
|
4491
|
+
import { PNG as PNG2 } from "pngjs";
|
|
4492
|
+
var NIBBLE_TO_BARS = { 10: 0, 11: 1, 12: 2, 13: 3, 14: 4 };
|
|
4493
|
+
var isWifiNibble = (n) => n >= 10 && n <= 14;
|
|
4494
|
+
var NIBBLE_RGBA = {
|
|
4495
|
+
2: [176, 182, 190, 255],
|
|
4496
|
+
// map border (context)
|
|
4497
|
+
3: [242, 244, 247, 255],
|
|
4498
|
+
// mapped floor (context)
|
|
4499
|
+
10: [229, 234, 238, 255],
|
|
4500
|
+
// unreached
|
|
4501
|
+
11: [217, 226, 239, 255],
|
|
4502
|
+
// 1 bar
|
|
4503
|
+
12: [205, 218, 239, 255],
|
|
4504
|
+
// 2 bars
|
|
4505
|
+
13: [161, 189, 242, 255],
|
|
4506
|
+
// 3 bars
|
|
4507
|
+
14: [129, 168, 245, 255]
|
|
4508
|
+
// 4 bars
|
|
4509
|
+
};
|
|
4510
|
+
var poseOrNull = (x, y, a) => x === 0 && y === 0 ? null : { x, y, angle: a === ANGLE_ABSENT ? 0 : a };
|
|
4511
|
+
function decodeWifiSignalMap(input, opts = {}) {
|
|
4512
|
+
const inflated = typeof input === "string" ? unwrapEnvelope(input, opts) : looksLikeBase64Zlib(input) ? unwrapEnvelope(input.toString("latin1"), opts) : input;
|
|
4513
|
+
const header = parseMapHeader(inflated);
|
|
4514
|
+
const { width, height, gridSize, left, top } = header;
|
|
4515
|
+
const pixelEnd = HEADER_SIZE + width * height;
|
|
4516
|
+
const grid = inflated.subarray(HEADER_SIZE, pixelEnd);
|
|
4517
|
+
const cells = new Uint8Array(width * height);
|
|
4518
|
+
for (let i = 0; i < cells.length; i++) cells[i] = (grid[i] ?? 0) & 15;
|
|
4519
|
+
const dimensions = { left, top, width, height, gridSize };
|
|
4520
|
+
const robot = poseOrNull(header.robotX, header.robotY, header.robotA);
|
|
4521
|
+
const dock = poseOrNull(header.chargerX, header.chargerY, header.chargerA);
|
|
4522
|
+
const signalAt = (worldX, worldY) => {
|
|
4523
|
+
if (gridSize <= 0) return null;
|
|
4524
|
+
const col = Math.floor((worldX - left) / gridSize);
|
|
4525
|
+
const row = Math.floor((worldY - top) / gridSize);
|
|
4526
|
+
if (col < 0 || col >= width || row < 0 || row >= height) return null;
|
|
4527
|
+
const nibble = cells[row * width + col] ?? 0;
|
|
4528
|
+
return isWifiNibble(nibble) ? NIBBLE_TO_BARS[nibble] : null;
|
|
4529
|
+
};
|
|
4530
|
+
return {
|
|
4531
|
+
dimensions,
|
|
4532
|
+
robot,
|
|
4533
|
+
dock,
|
|
4534
|
+
cells,
|
|
4535
|
+
signalAt,
|
|
4536
|
+
currentSignal: robot ? signalAt(robot.x, robot.y) : null
|
|
4537
|
+
};
|
|
4538
|
+
}
|
|
4539
|
+
function renderWifiSignalPng(map, opts = {}) {
|
|
4540
|
+
const scale = Math.max(1, Math.floor(opts.scale ?? 4));
|
|
4541
|
+
const { width, height, left, top, gridSize } = map.dimensions;
|
|
4542
|
+
const png = new PNG2({ width: width * scale, height: height * scale, colorType: 6 });
|
|
4543
|
+
for (let row = 0; row < height; row++) {
|
|
4544
|
+
for (let col = 0; col < width; col++) {
|
|
4545
|
+
const nibble = map.cells[row * width + col] ?? 0;
|
|
4546
|
+
const rgba = NIBBLE_RGBA[nibble];
|
|
4547
|
+
if (!rgba) continue;
|
|
4548
|
+
for (let dy = 0; dy < scale; dy++) {
|
|
4549
|
+
for (let dx = 0; dx < scale; dx++) {
|
|
4550
|
+
const px = col * scale + dx + (row * scale + dy) * width * scale;
|
|
4551
|
+
const o = px << 2;
|
|
4552
|
+
png.data[o] = rgba[0];
|
|
4553
|
+
png.data[o + 1] = rgba[1];
|
|
4554
|
+
png.data[o + 2] = rgba[2];
|
|
4555
|
+
png.data[o + 3] = rgba[3];
|
|
4556
|
+
}
|
|
4557
|
+
}
|
|
4558
|
+
}
|
|
4559
|
+
}
|
|
4560
|
+
if ((opts.markRobot ?? true) && map.robot && gridSize > 0) {
|
|
4561
|
+
const cx = Math.floor((map.robot.x - left) / gridSize) * scale + Math.floor(scale / 2);
|
|
4562
|
+
const cy = Math.floor((map.robot.y - top) / gridSize) * scale + Math.floor(scale / 2);
|
|
4563
|
+
const r = Math.max(2, scale);
|
|
4564
|
+
for (let dy = -r; dy <= r; dy++) {
|
|
4565
|
+
for (let dx = -r; dx <= r; dx++) {
|
|
4566
|
+
if (dx * dx + dy * dy > r * r) continue;
|
|
4567
|
+
const x = cx + dx;
|
|
4568
|
+
const y = cy + dy;
|
|
4569
|
+
if (x < 0 || y < 0 || x >= width * scale || y >= height * scale) continue;
|
|
4570
|
+
const o = x + y * width * scale << 2;
|
|
4571
|
+
png.data[o] = 255;
|
|
4572
|
+
png.data[o + 1] = 69;
|
|
4573
|
+
png.data[o + 2] = 0;
|
|
4574
|
+
png.data[o + 3] = 255;
|
|
4575
|
+
}
|
|
4576
|
+
}
|
|
4577
|
+
}
|
|
4578
|
+
return PNG2.sync.write(png);
|
|
4579
|
+
}
|
|
4580
|
+
|
|
3437
4581
|
// src/models/vacuum/map/oss-fetch.ts
|
|
3438
4582
|
var OSS_DOWNLOAD_PATH = "/dreame-user-iot/iotfile/getDownloadUrl";
|
|
3439
4583
|
var DEFAULT_TTL_MS = 30 * 60 * 1e3;
|
|
@@ -3919,11 +5063,11 @@ var VacuumDevice = class _VacuumDevice extends BaseDevice {
|
|
|
3919
5063
|
}
|
|
3920
5064
|
this.#requireCap(this.#caps.canCleanPerRoom, "cleanZones", "per-room cleaning");
|
|
3921
5065
|
const { repeats, fan, water } = this.#resolveCleanOpts(opts);
|
|
3922
|
-
const areas = zones.map((
|
|
3923
|
-
Math.round(
|
|
3924
|
-
Math.round(
|
|
3925
|
-
Math.round(
|
|
3926
|
-
Math.round(
|
|
5066
|
+
const areas = zones.map((z7) => [
|
|
5067
|
+
Math.round(z7.x0),
|
|
5068
|
+
Math.round(z7.y0),
|
|
5069
|
+
Math.round(z7.x1),
|
|
5070
|
+
Math.round(z7.y1),
|
|
3927
5071
|
repeats,
|
|
3928
5072
|
fan,
|
|
3929
5073
|
water
|
|
@@ -4051,6 +5195,66 @@ var VacuumDevice = class _VacuumDevice extends BaseDevice {
|
|
|
4051
5195
|
...input.iv !== void 0 ? { iv: input.iv } : {}
|
|
4052
5196
|
};
|
|
4053
5197
|
}
|
|
5198
|
+
/**
|
|
5199
|
+
* Fetch the robot's Wi-Fi signal map — the last stored coverage heatmap, with
|
|
5200
|
+
* NO robot movement. Requests it (map service `wifiMap` action, siid 6 aiid 4),
|
|
5201
|
+
* polls `PropWifiMap` (6/15) for the OSS object it advertises, fetches + decodes
|
|
5202
|
+
* it into a per-cell signal grid + geometry + robot/dock poses. The signal at
|
|
5203
|
+
* any world point (incl. the robot's own position) is a lookup — see
|
|
5204
|
+
* {@link WifiSignalMap.signalAt} / {@link WifiSignalMap.currentSignal}.
|
|
5205
|
+
*
|
|
5206
|
+
* Pass `requestFresh: false` to skip the request and read whatever is already
|
|
5207
|
+
* advertised. Throws if no Wi-Fi map exists yet (never run on this device).
|
|
5208
|
+
*/
|
|
5209
|
+
async getWifiSignalMap(input = {}) {
|
|
5210
|
+
if (input.requestFresh !== false) {
|
|
5211
|
+
try {
|
|
5212
|
+
await this.callAction(6, 4, []);
|
|
5213
|
+
} catch {
|
|
5214
|
+
}
|
|
5215
|
+
}
|
|
5216
|
+
const pollMs = input.pollMs ?? 2500;
|
|
5217
|
+
const deadline = Date.now() + (input.maxWaitMs ?? 2e4);
|
|
5218
|
+
let objectName = "";
|
|
5219
|
+
for (; ; ) {
|
|
5220
|
+
const res = await this.refreshProperties([{ siid: 6, piid: 15 }]);
|
|
5221
|
+
const val = res[0]?.value;
|
|
5222
|
+
if (typeof val === "string" && val.length > 0) {
|
|
5223
|
+
objectName = val;
|
|
5224
|
+
break;
|
|
5225
|
+
}
|
|
5226
|
+
if (Date.now() + pollMs >= deadline) {
|
|
5227
|
+
throw new DreameError("wifi signal map not available (none stored yet, or request timed out)");
|
|
5228
|
+
}
|
|
5229
|
+
await new Promise((r) => setTimeout(r, pollMs));
|
|
5230
|
+
}
|
|
5231
|
+
const filename = objectName.replace(/^\d+,/, "");
|
|
5232
|
+
const blob = await this.#fetchMapBlob({
|
|
5233
|
+
filename,
|
|
5234
|
+
...input.fetcher ? { fetcher: input.fetcher } : {},
|
|
5235
|
+
...input.host ? { host: input.host } : {},
|
|
5236
|
+
...input.timeoutMs !== void 0 ? { timeoutMs: input.timeoutMs } : {},
|
|
5237
|
+
...input.signal ? { signal: input.signal } : {}
|
|
5238
|
+
});
|
|
5239
|
+
return decodeWifiSignalMap(blob, this.#decodeOpts(input));
|
|
5240
|
+
}
|
|
5241
|
+
/**
|
|
5242
|
+
* Render the Wi-Fi signal map as a simple PNG heatmap image (weakest→strongest,
|
|
5243
|
+
* unreached grey, robot marker) — ready to display. Convenience over
|
|
5244
|
+
* {@link getWifiSignalMap} + {@link renderWifiSignalPng}.
|
|
5245
|
+
*/
|
|
5246
|
+
async getWifiSignalImage(input = {}) {
|
|
5247
|
+
const map = await this.getWifiSignalMap(input);
|
|
5248
|
+
return renderWifiSignalPng(map, input);
|
|
5249
|
+
}
|
|
5250
|
+
/**
|
|
5251
|
+
* The one-call "current Wi-Fi signal": fetches the signal map and returns the
|
|
5252
|
+
* bars (1–4, 0 = unreached) at the robot's own position, or null when unknown.
|
|
5253
|
+
*/
|
|
5254
|
+
async getCurrentSignal(input = {}) {
|
|
5255
|
+
const map = await this.getWifiSignalMap(input);
|
|
5256
|
+
return map.currentSignal;
|
|
5257
|
+
}
|
|
4054
5258
|
/**
|
|
4055
5259
|
* The merge base for live P-frame streaming — always an INFLATED frame buffer.
|
|
4056
5260
|
* An I-frame (re)seeds it; each P-frame merge replaces it with the merged
|
|
@@ -4114,6 +5318,43 @@ var VacuumDevice = class _VacuumDevice extends BaseDevice {
|
|
|
4114
5318
|
this.emit("map", frame);
|
|
4115
5319
|
return frame;
|
|
4116
5320
|
}
|
|
5321
|
+
/**
|
|
5322
|
+
* Build a {@link DreameCameraController} for this device's camera, wired to
|
|
5323
|
+
* both planes it needs: the MIoT action transport (this device handle) and a
|
|
5324
|
+
* fresh Aliyun {@link DreameVideoSession} for the relay. Call
|
|
5325
|
+
* `controller.open()` to autonomously cold-start the stream and get a pullable
|
|
5326
|
+
* RTMP URL, then `controller.close()` to release it.
|
|
5327
|
+
*
|
|
5328
|
+
* The camera's per-session privacy gate means a coded camera needs its PIN:
|
|
5329
|
+
* pass `accessCode` (the code set at pairing). `iotId` is resolved from the
|
|
5330
|
+
* device's cloud video profile when not supplied.
|
|
5331
|
+
*/
|
|
5332
|
+
async createCameraController(opts) {
|
|
5333
|
+
const session = this.currentSession();
|
|
5334
|
+
const region = this.region;
|
|
5335
|
+
const relay = opts?.relay ?? new DreameVideoSession({ session, region });
|
|
5336
|
+
let iotId = opts?.iotId ?? null;
|
|
5337
|
+
if (!iotId) {
|
|
5338
|
+
const profile = await getDeviceVideoProfile({ session, region, did: this.deviceId });
|
|
5339
|
+
iotId = profile.iotId;
|
|
5340
|
+
if (!iotId) {
|
|
5341
|
+
throw new DreameError(explainNoCameraChannel(profile) ?? "device has no video channel");
|
|
5342
|
+
}
|
|
5343
|
+
}
|
|
5344
|
+
return new DreameCameraController({
|
|
5345
|
+
device: this,
|
|
5346
|
+
relay,
|
|
5347
|
+
iotId,
|
|
5348
|
+
accountId: session.uid,
|
|
5349
|
+
...opts?.vendor ? { vendor: opts.vendor } : {},
|
|
5350
|
+
...opts?.accessCode !== void 0 ? { accessCode: opts.accessCode } : {},
|
|
5351
|
+
...opts?.area ? { area: opts.area } : {},
|
|
5352
|
+
...opts?.keepAliveIntervalMs !== void 0 ? { keepAliveIntervalMs: opts.keepAliveIntervalMs } : {},
|
|
5353
|
+
...opts?.wakeTimeoutMs !== void 0 ? { wakeTimeoutMs: opts.wakeTimeoutMs } : {},
|
|
5354
|
+
...opts?.onKeepAliveError ? { onKeepAliveError: opts.onKeepAliveError } : {},
|
|
5355
|
+
...opts?.log ? { log: opts.log } : {}
|
|
5356
|
+
});
|
|
5357
|
+
}
|
|
4117
5358
|
/** Props worth seeding on start() / polling — exported for the facade. */
|
|
4118
5359
|
static DEFAULT_PROPS = [
|
|
4119
5360
|
VACUUM_PROP.STATE,
|
|
@@ -4652,7 +5893,7 @@ function isRecord3(v) {
|
|
|
4652
5893
|
function asNumber(v, fallback) {
|
|
4653
5894
|
return typeof v === "number" && Number.isFinite(v) ? v : fallback;
|
|
4654
5895
|
}
|
|
4655
|
-
function
|
|
5896
|
+
function asString2(v, fallback) {
|
|
4656
5897
|
return typeof v === "string" ? v : fallback;
|
|
4657
5898
|
}
|
|
4658
5899
|
function mapIdFromIndex(mapIndex) {
|
|
@@ -4747,7 +5988,7 @@ function parseZones(list, includeTimes) {
|
|
|
4747
5988
|
out.push({
|
|
4748
5989
|
zoneId: asNumber(id, 0),
|
|
4749
5990
|
path: extractPathCoords(data["path"]),
|
|
4750
|
-
name:
|
|
5991
|
+
name: asString2(data["name"], ""),
|
|
4751
5992
|
zoneType: asNumber(data["type"], 0),
|
|
4752
5993
|
shapeType: includeTimes ? asNumber(data["shapeType"], 0) : 0,
|
|
4753
5994
|
area: includeTimes ? asNumber(data["area"], 0) : 0,
|
|
@@ -4768,7 +6009,7 @@ function parseSpotAreas(list) {
|
|
|
4768
6009
|
out.push({
|
|
4769
6010
|
areaId: Math.trunc(asNumber(id, 0)),
|
|
4770
6011
|
path: extractPathCoords(data["path"]),
|
|
4771
|
-
name:
|
|
6012
|
+
name: asString2(data["name"], ""),
|
|
4772
6013
|
shapeType: asNumber(data["shapeType"], 0),
|
|
4773
6014
|
area: asNumber(data["area"], 0)
|
|
4774
6015
|
});
|
|
@@ -4832,7 +6073,7 @@ function parseMowerMap(mapJsonStr) {
|
|
|
4832
6073
|
contours: parseContours(parsePolygonList(data["contours"])),
|
|
4833
6074
|
boundary: parseBoundary(data["boundary"]),
|
|
4834
6075
|
totalArea: asNumber(data["totalArea"], 0),
|
|
4835
|
-
name:
|
|
6076
|
+
name: asString2(data["name"], ""),
|
|
4836
6077
|
mapIndex,
|
|
4837
6078
|
mapId: mapIdFromIndex(mapIndex),
|
|
4838
6079
|
mowPaths: [],
|
|
@@ -5360,7 +6601,7 @@ var MowerDevice = class _MowerDevice extends BaseDevice {
|
|
|
5360
6601
|
if (zoneIds.length === 0) {
|
|
5361
6602
|
throw new RangeError("startMowingZones: zoneIds must not be empty");
|
|
5362
6603
|
}
|
|
5363
|
-
return this.#sendTask(buildZonePayload(zoneIds.map((
|
|
6604
|
+
return this.#sendTask(buildZonePayload(zoneIds.map((z7) => Math.trunc(z7))));
|
|
5364
6605
|
}
|
|
5365
6606
|
/** Edge / contour mowing (2:50 o:101). Contour ids are two-int pairs [[1,0]]. */
|
|
5366
6607
|
async startMowingEdges(contourIds) {
|
|
@@ -5716,10 +6957,13 @@ var Nodreame = class extends TypedEmitter {
|
|
|
5716
6957
|
if (this.#closed) {
|
|
5717
6958
|
return;
|
|
5718
6959
|
}
|
|
5719
|
-
this.#refreshTimer = setTimeout(
|
|
5720
|
-
|
|
5721
|
-
|
|
5722
|
-
|
|
6960
|
+
this.#refreshTimer = setTimeout(
|
|
6961
|
+
() => {
|
|
6962
|
+
this.#refreshTimer = null;
|
|
6963
|
+
void this.#runProactiveRefresh();
|
|
6964
|
+
},
|
|
6965
|
+
Math.max(0, delayMs)
|
|
6966
|
+
);
|
|
5723
6967
|
}
|
|
5724
6968
|
/** (Re)arm the proactive-refresh timer against the current session's expiry. */
|
|
5725
6969
|
#scheduleProactiveRefresh() {
|
|
@@ -5877,59 +7121,59 @@ function redact(value) {
|
|
|
5877
7121
|
}
|
|
5878
7122
|
|
|
5879
7123
|
// src/diagnostics/dump-format.ts
|
|
5880
|
-
import { z as
|
|
5881
|
-
var DumpScalarSchema =
|
|
5882
|
-
var PropertyObservationSchema =
|
|
5883
|
-
values:
|
|
5884
|
-
unmapped:
|
|
5885
|
-
enum:
|
|
5886
|
-
count:
|
|
5887
|
-
firstSeen:
|
|
5888
|
-
lastSeen:
|
|
7124
|
+
import { z as z6 } from "zod";
|
|
7125
|
+
var DumpScalarSchema = z6.union([z6.string(), z6.number(), z6.boolean()]);
|
|
7126
|
+
var PropertyObservationSchema = z6.object({
|
|
7127
|
+
values: z6.array(DumpScalarSchema),
|
|
7128
|
+
unmapped: z6.array(DumpScalarSchema),
|
|
7129
|
+
enum: z6.string().optional(),
|
|
7130
|
+
count: z6.number(),
|
|
7131
|
+
firstSeen: z6.number(),
|
|
7132
|
+
lastSeen: z6.number()
|
|
5889
7133
|
});
|
|
5890
|
-
var EventObservationSchema =
|
|
5891
|
-
at:
|
|
5892
|
-
type:
|
|
5893
|
-
data:
|
|
7134
|
+
var EventObservationSchema = z6.object({
|
|
7135
|
+
at: z6.number(),
|
|
7136
|
+
type: z6.string(),
|
|
7137
|
+
data: z6.unknown().optional()
|
|
5894
7138
|
});
|
|
5895
|
-
var RawFrameSchema =
|
|
5896
|
-
at:
|
|
5897
|
-
source:
|
|
5898
|
-
payload:
|
|
7139
|
+
var RawFrameSchema = z6.object({
|
|
7140
|
+
at: z6.number(),
|
|
7141
|
+
source: z6.string(),
|
|
7142
|
+
payload: z6.unknown()
|
|
5899
7143
|
});
|
|
5900
|
-
var CommandSchema =
|
|
5901
|
-
name:
|
|
5902
|
-
siid:
|
|
5903
|
-
aiid:
|
|
7144
|
+
var CommandSchema = z6.object({
|
|
7145
|
+
name: z6.string(),
|
|
7146
|
+
siid: z6.number().optional(),
|
|
7147
|
+
aiid: z6.number().optional()
|
|
5904
7148
|
});
|
|
5905
|
-
var SensorSchema =
|
|
5906
|
-
model:
|
|
5907
|
-
channel:
|
|
7149
|
+
var SensorSchema = z6.object({
|
|
7150
|
+
model: z6.string(),
|
|
7151
|
+
channel: z6.number().optional()
|
|
5908
7152
|
});
|
|
5909
|
-
var DeviceDumpSchema =
|
|
5910
|
-
schemaVersion:
|
|
5911
|
-
library:
|
|
5912
|
-
libraryVersion:
|
|
5913
|
-
device:
|
|
5914
|
-
model:
|
|
5915
|
-
firmware:
|
|
5916
|
-
region:
|
|
5917
|
-
type:
|
|
7153
|
+
var DeviceDumpSchema = z6.object({
|
|
7154
|
+
schemaVersion: z6.literal(1),
|
|
7155
|
+
library: z6.union([z6.literal("nodedreame"), z6.literal("nodewitt")]),
|
|
7156
|
+
libraryVersion: z6.string(),
|
|
7157
|
+
device: z6.object({
|
|
7158
|
+
model: z6.string(),
|
|
7159
|
+
firmware: z6.string().optional(),
|
|
7160
|
+
region: z6.string().optional(),
|
|
7161
|
+
type: z6.string().optional()
|
|
5918
7162
|
}),
|
|
5919
|
-
observations:
|
|
5920
|
-
properties:
|
|
5921
|
-
events:
|
|
5922
|
-
rawFrames:
|
|
7163
|
+
observations: z6.object({
|
|
7164
|
+
properties: z6.record(z6.string(), PropertyObservationSchema),
|
|
7165
|
+
events: z6.array(EventObservationSchema),
|
|
7166
|
+
rawFrames: z6.array(RawFrameSchema).optional()
|
|
5923
7167
|
}),
|
|
5924
|
-
catalog:
|
|
5925
|
-
commands:
|
|
5926
|
-
capabilities:
|
|
5927
|
-
sensors:
|
|
7168
|
+
catalog: z6.object({
|
|
7169
|
+
commands: z6.array(CommandSchema).optional(),
|
|
7170
|
+
capabilities: z6.record(z6.string(), z6.unknown()).optional(),
|
|
7171
|
+
sensors: z6.array(SensorSchema).optional()
|
|
5928
7172
|
}),
|
|
5929
|
-
meta:
|
|
5930
|
-
startedAt:
|
|
5931
|
-
durationMs:
|
|
5932
|
-
generatedAt:
|
|
7173
|
+
meta: z6.object({
|
|
7174
|
+
startedAt: z6.number(),
|
|
7175
|
+
durationMs: z6.number(),
|
|
7176
|
+
generatedAt: z6.number()
|
|
5933
7177
|
})
|
|
5934
7178
|
});
|
|
5935
7179
|
|
|
@@ -6218,20 +7462,938 @@ function createDumper(target, options) {
|
|
|
6218
7462
|
function createClientDumper(client, options) {
|
|
6219
7463
|
return client.devices.map((d) => createDumper(d, options));
|
|
6220
7464
|
}
|
|
7465
|
+
|
|
7466
|
+
// src/video/monitor/detections.ts
|
|
7467
|
+
var asRecord = (value) => {
|
|
7468
|
+
if (typeof value === "string") {
|
|
7469
|
+
try {
|
|
7470
|
+
const parsed = JSON.parse(value);
|
|
7471
|
+
return parsed && typeof parsed === "object" ? parsed : null;
|
|
7472
|
+
} catch {
|
|
7473
|
+
return null;
|
|
7474
|
+
}
|
|
7475
|
+
}
|
|
7476
|
+
return value && typeof value === "object" ? value : null;
|
|
7477
|
+
};
|
|
7478
|
+
var num = (v) => typeof v === "number" && Number.isFinite(v) ? v : void 0;
|
|
7479
|
+
var toMs = (raw) => {
|
|
7480
|
+
const n = num(raw);
|
|
7481
|
+
if (n === void 0) return Date.now();
|
|
7482
|
+
return n > 1e15 ? Math.round(n / 1e6) : n;
|
|
7483
|
+
};
|
|
7484
|
+
var toBox = (raw) => {
|
|
7485
|
+
if (Array.isArray(raw) && raw.length >= 4) {
|
|
7486
|
+
const [x2, y2, w2, h2] = raw;
|
|
7487
|
+
if ([x2, y2, w2, h2].every((v) => num(v) !== void 0)) {
|
|
7488
|
+
return { x: x2, y: y2, w: w2, h: h2 };
|
|
7489
|
+
}
|
|
7490
|
+
return null;
|
|
7491
|
+
}
|
|
7492
|
+
const r = asRecord(raw);
|
|
7493
|
+
if (!r) return null;
|
|
7494
|
+
const x = num(r["x"]);
|
|
7495
|
+
const y = num(r["y"]);
|
|
7496
|
+
const w = num(r["w"]) ?? num(r["width"]);
|
|
7497
|
+
const h = num(r["h"]) ?? num(r["height"]);
|
|
7498
|
+
if (x === void 0 || y === void 0 || w === void 0 || h === void 0) return null;
|
|
7499
|
+
const label = typeof r["label"] === "string" ? r["label"] : void 0;
|
|
7500
|
+
const score = num(r["score"]) ?? num(r["confidence"]);
|
|
7501
|
+
return { x, y, w, h, ...label !== void 0 ? { label } : {}, ...score !== void 0 ? { score } : {} };
|
|
7502
|
+
};
|
|
7503
|
+
function parsePersonFollow(value) {
|
|
7504
|
+
const r = asRecord(value);
|
|
7505
|
+
if (!r) return null;
|
|
7506
|
+
return {
|
|
7507
|
+
timestampMs: toMs(r["timestamp"] ?? r["time"]),
|
|
7508
|
+
box: toBox(r["bbox"] ?? r["box"])
|
|
7509
|
+
};
|
|
7510
|
+
}
|
|
7511
|
+
function parseObstacleData(value) {
|
|
7512
|
+
const r = asRecord(value);
|
|
7513
|
+
if (!r) return null;
|
|
7514
|
+
const list = r["boxlist"] ?? r["boxes"] ?? r["boxList"];
|
|
7515
|
+
const boxes = [];
|
|
7516
|
+
if (Array.isArray(list)) {
|
|
7517
|
+
for (const item of list) {
|
|
7518
|
+
const box = toBox(item);
|
|
7519
|
+
if (box) boxes.push(box);
|
|
7520
|
+
}
|
|
7521
|
+
}
|
|
7522
|
+
return { timestampMs: toMs(r["timestamp"] ?? r["time"]), boxes };
|
|
7523
|
+
}
|
|
7524
|
+
|
|
7525
|
+
// src/video/media/lv-rtmp-client.ts
|
|
7526
|
+
import net from "net";
|
|
7527
|
+
import { EventEmitter as EventEmitter2 } from "events";
|
|
7528
|
+
import { randomBytes as randomBytes2 } from "crypto";
|
|
7529
|
+
|
|
7530
|
+
// src/video/media/amf0.ts
|
|
7531
|
+
var AMF0 = {
|
|
7532
|
+
NUMBER: 0,
|
|
7533
|
+
BOOLEAN: 1,
|
|
7534
|
+
STRING: 2,
|
|
7535
|
+
OBJECT: 3,
|
|
7536
|
+
NULL: 5,
|
|
7537
|
+
UNDEFINED: 6,
|
|
7538
|
+
ECMA_ARRAY: 8,
|
|
7539
|
+
OBJECT_END: 9,
|
|
7540
|
+
STRICT_ARRAY: 10,
|
|
7541
|
+
LONG_STRING: 12
|
|
7542
|
+
};
|
|
7543
|
+
function amfNumber(n) {
|
|
7544
|
+
const b = Buffer.alloc(9);
|
|
7545
|
+
b[0] = AMF0.NUMBER;
|
|
7546
|
+
b.writeDoubleBE(n, 1);
|
|
7547
|
+
return b;
|
|
7548
|
+
}
|
|
7549
|
+
function amfBoolean(v) {
|
|
7550
|
+
return Buffer.from([AMF0.BOOLEAN, v ? 1 : 0]);
|
|
7551
|
+
}
|
|
7552
|
+
function amfString(s) {
|
|
7553
|
+
const str2 = Buffer.from(s, "utf8");
|
|
7554
|
+
const b = Buffer.alloc(3 + str2.length);
|
|
7555
|
+
b[0] = AMF0.STRING;
|
|
7556
|
+
b.writeUInt16BE(str2.length, 1);
|
|
7557
|
+
str2.copy(b, 3);
|
|
7558
|
+
return b;
|
|
7559
|
+
}
|
|
7560
|
+
function amfNull() {
|
|
7561
|
+
return Buffer.from([AMF0.NULL]);
|
|
7562
|
+
}
|
|
7563
|
+
function amfNamed(key2, value) {
|
|
7564
|
+
const k = Buffer.from(key2, "utf8");
|
|
7565
|
+
const b = Buffer.alloc(2 + k.length);
|
|
7566
|
+
b.writeUInt16BE(k.length, 0);
|
|
7567
|
+
k.copy(b, 2);
|
|
7568
|
+
return Buffer.concat([b, value]);
|
|
7569
|
+
}
|
|
7570
|
+
function amfObject(pairs) {
|
|
7571
|
+
const parts = [Buffer.from([AMF0.OBJECT])];
|
|
7572
|
+
for (const [k, v] of pairs) parts.push(amfNamed(k, v));
|
|
7573
|
+
parts.push(Buffer.from([0, 0, AMF0.OBJECT_END]));
|
|
7574
|
+
return Buffer.concat(parts);
|
|
7575
|
+
}
|
|
7576
|
+
function decodeOne(buf, pos) {
|
|
7577
|
+
const type = buf[pos];
|
|
7578
|
+
let p = pos + 1;
|
|
7579
|
+
switch (type) {
|
|
7580
|
+
case AMF0.NUMBER:
|
|
7581
|
+
return { value: buf.readDoubleBE(p), next: p + 8 };
|
|
7582
|
+
case AMF0.BOOLEAN:
|
|
7583
|
+
return { value: buf[p] !== 0, next: p + 1 };
|
|
7584
|
+
case AMF0.STRING: {
|
|
7585
|
+
const len = buf.readUInt16BE(p);
|
|
7586
|
+
return { value: buf.toString("utf8", p + 2, p + 2 + len), next: p + 2 + len };
|
|
7587
|
+
}
|
|
7588
|
+
case AMF0.LONG_STRING: {
|
|
7589
|
+
const len = buf.readUInt32BE(p);
|
|
7590
|
+
return { value: buf.toString("utf8", p + 4, p + 4 + len), next: p + 4 + len };
|
|
7591
|
+
}
|
|
7592
|
+
case AMF0.NULL:
|
|
7593
|
+
return { value: null, next: p };
|
|
7594
|
+
case AMF0.UNDEFINED:
|
|
7595
|
+
return { value: void 0, next: p };
|
|
7596
|
+
case AMF0.ECMA_ARRAY:
|
|
7597
|
+
case AMF0.OBJECT: {
|
|
7598
|
+
if (type === AMF0.ECMA_ARRAY) p += 4;
|
|
7599
|
+
const obj = {};
|
|
7600
|
+
for (; ; ) {
|
|
7601
|
+
const klen = buf.readUInt16BE(p);
|
|
7602
|
+
if (klen === 0 && buf[p + 2] === AMF0.OBJECT_END) return { value: obj, next: p + 3 };
|
|
7603
|
+
const key2 = buf.toString("utf8", p + 2, p + 2 + klen);
|
|
7604
|
+
const r = decodeOne(buf, p + 2 + klen);
|
|
7605
|
+
obj[key2] = r.value;
|
|
7606
|
+
p = r.next;
|
|
7607
|
+
}
|
|
7608
|
+
}
|
|
7609
|
+
case AMF0.STRICT_ARRAY: {
|
|
7610
|
+
const count = buf.readUInt32BE(p);
|
|
7611
|
+
p += 4;
|
|
7612
|
+
const arr = [];
|
|
7613
|
+
for (let i = 0; i < count; i++) {
|
|
7614
|
+
const r = decodeOne(buf, p);
|
|
7615
|
+
arr.push(r.value);
|
|
7616
|
+
p = r.next;
|
|
7617
|
+
}
|
|
7618
|
+
return { value: arr, next: p };
|
|
7619
|
+
}
|
|
7620
|
+
default:
|
|
7621
|
+
throw new Error(`AMF0: unsupported type 0x${(type ?? -1).toString(16)} at ${pos}`);
|
|
7622
|
+
}
|
|
7623
|
+
}
|
|
7624
|
+
function decodeAmf0(buf) {
|
|
7625
|
+
const out = [];
|
|
7626
|
+
let pos = 0;
|
|
7627
|
+
while (pos < buf.length) {
|
|
7628
|
+
const r = decodeOne(buf, pos);
|
|
7629
|
+
out.push(r.value);
|
|
7630
|
+
pos = r.next;
|
|
7631
|
+
}
|
|
7632
|
+
return out;
|
|
7633
|
+
}
|
|
7634
|
+
|
|
7635
|
+
// src/video/media/chunk.ts
|
|
7636
|
+
var MSG = {
|
|
7637
|
+
SET_CHUNK_SIZE: 1,
|
|
7638
|
+
ABORT: 2,
|
|
7639
|
+
ACK: 3,
|
|
7640
|
+
USER_CONTROL: 4,
|
|
7641
|
+
WINDOW_ACK_SIZE: 5,
|
|
7642
|
+
SET_PEER_BW: 6,
|
|
7643
|
+
AUDIO: 8,
|
|
7644
|
+
VIDEO: 9,
|
|
7645
|
+
DATA_AMF0: 18,
|
|
7646
|
+
COMMAND_AMF0: 20
|
|
7647
|
+
};
|
|
7648
|
+
var PRIVATE_MODE_CHUNK_SIZE = 6e4;
|
|
7649
|
+
function basicHeader(fmt, csid) {
|
|
7650
|
+
if (csid < 64) return Buffer.from([fmt << 6 | csid]);
|
|
7651
|
+
if (csid < 320) return Buffer.from([fmt << 6, csid - 64]);
|
|
7652
|
+
return Buffer.from([fmt << 6 | 1, csid - 64 & 255, csid - 64 >> 8]);
|
|
7653
|
+
}
|
|
7654
|
+
function encodeMessage(o) {
|
|
7655
|
+
if (o.body.length > PRIVATE_MODE_CHUNK_SIZE) {
|
|
7656
|
+
throw new Error(`message body ${o.body.length} exceeds private-mode chunk size ${PRIVATE_MODE_CHUNK_SIZE}`);
|
|
7657
|
+
}
|
|
7658
|
+
const ts = o.timestamp ?? 0;
|
|
7659
|
+
const hdrLen = o.fmt === 0 ? 11 : 7;
|
|
7660
|
+
const hdr = Buffer.alloc(hdrLen);
|
|
7661
|
+
hdr.writeUIntBE(ts >= 16777215 ? 16777215 : ts, 0, 3);
|
|
7662
|
+
hdr.writeUIntBE(o.body.length, 3, 3);
|
|
7663
|
+
hdr[6] = o.type;
|
|
7664
|
+
if (o.fmt === 0) hdr.writeUInt32LE(o.msid ?? 0, 7);
|
|
7665
|
+
const ext = ts >= 16777215 ? (() => {
|
|
7666
|
+
const e = Buffer.alloc(4);
|
|
7667
|
+
e.writeUInt32BE(ts, 0);
|
|
7668
|
+
return e;
|
|
7669
|
+
})() : Buffer.alloc(0);
|
|
7670
|
+
return Buffer.concat([basicHeader(o.fmt, o.csid), hdr, ext, o.body]);
|
|
7671
|
+
}
|
|
7672
|
+
function freshState() {
|
|
7673
|
+
return { timestamp: 0, delta: 0, length: 0, type: 0, msid: 0, extTs: false, partial: [], received: 0 };
|
|
7674
|
+
}
|
|
7675
|
+
var ChunkReader = class {
|
|
7676
|
+
chunkSize;
|
|
7677
|
+
pending = Buffer.alloc(0);
|
|
7678
|
+
streams = /* @__PURE__ */ new Map();
|
|
7679
|
+
constructor(chunkSize = PRIVATE_MODE_CHUNK_SIZE) {
|
|
7680
|
+
this.chunkSize = chunkSize;
|
|
7681
|
+
}
|
|
7682
|
+
feed(data) {
|
|
7683
|
+
this.pending = this.pending.length ? Buffer.concat([this.pending, data]) : data;
|
|
7684
|
+
const out = [];
|
|
7685
|
+
for (; ; ) {
|
|
7686
|
+
const consumed = this.tryReadChunk(out);
|
|
7687
|
+
if (consumed === 0) break;
|
|
7688
|
+
this.pending = this.pending.subarray(consumed);
|
|
7689
|
+
}
|
|
7690
|
+
return out;
|
|
7691
|
+
}
|
|
7692
|
+
/** Returns bytes consumed for one chunk, or 0 if more data is needed. */
|
|
7693
|
+
tryReadChunk(out) {
|
|
7694
|
+
const buf = this.pending;
|
|
7695
|
+
if (buf.length < 1) return 0;
|
|
7696
|
+
const fmt = buf[0] >> 6;
|
|
7697
|
+
let csid = buf[0] & 63;
|
|
7698
|
+
let p = 1;
|
|
7699
|
+
if (csid === 0) {
|
|
7700
|
+
if (buf.length < 2) return 0;
|
|
7701
|
+
csid = 64 + buf[1];
|
|
7702
|
+
p = 2;
|
|
7703
|
+
} else if (csid === 1) {
|
|
7704
|
+
if (buf.length < 3) return 0;
|
|
7705
|
+
csid = 64 + buf[1] + buf[2] * 256;
|
|
7706
|
+
p = 3;
|
|
7707
|
+
}
|
|
7708
|
+
const st = this.streams.get(csid) ?? freshState();
|
|
7709
|
+
const hdrLen = fmt === 0 ? 11 : fmt === 1 ? 7 : fmt === 2 ? 3 : 0;
|
|
7710
|
+
if (buf.length < p + hdrLen) return 0;
|
|
7711
|
+
let tsField = 0;
|
|
7712
|
+
if (fmt <= 2) {
|
|
7713
|
+
tsField = buf.readUIntBE(p, 3);
|
|
7714
|
+
if (fmt <= 1) {
|
|
7715
|
+
st.length = buf.readUIntBE(p + 3, 3);
|
|
7716
|
+
st.type = buf[p + 6];
|
|
7717
|
+
}
|
|
7718
|
+
if (fmt === 0) st.msid = buf.readUInt32LE(p + 7);
|
|
7719
|
+
st.extTs = tsField === 16777215;
|
|
7720
|
+
}
|
|
7721
|
+
p += hdrLen;
|
|
7722
|
+
if (st.extTs) {
|
|
7723
|
+
if (buf.length < p + 4) return 0;
|
|
7724
|
+
tsField = buf.readUInt32BE(p);
|
|
7725
|
+
p += 4;
|
|
7726
|
+
}
|
|
7727
|
+
const startOfMessage = st.received === 0;
|
|
7728
|
+
if (startOfMessage) {
|
|
7729
|
+
if (fmt === 0) {
|
|
7730
|
+
st.timestamp = tsField;
|
|
7731
|
+
st.delta = 0;
|
|
7732
|
+
} else if (fmt <= 2) {
|
|
7733
|
+
st.delta = tsField;
|
|
7734
|
+
st.timestamp += tsField;
|
|
7735
|
+
} else st.timestamp += st.delta;
|
|
7736
|
+
}
|
|
7737
|
+
const take = Math.min(this.chunkSize, st.length - st.received);
|
|
7738
|
+
if (buf.length < p + take) return 0;
|
|
7739
|
+
st.partial.push(Buffer.from(buf.subarray(p, p + take)));
|
|
7740
|
+
st.received += take;
|
|
7741
|
+
if (st.received >= st.length) {
|
|
7742
|
+
out.push({ csid, msid: st.msid, timestamp: st.timestamp, type: st.type, body: Buffer.concat(st.partial) });
|
|
7743
|
+
st.partial = [];
|
|
7744
|
+
st.received = 0;
|
|
7745
|
+
}
|
|
7746
|
+
this.streams.set(csid, st);
|
|
7747
|
+
return p + take;
|
|
7748
|
+
}
|
|
7749
|
+
};
|
|
7750
|
+
|
|
7751
|
+
// src/video/media/flv.ts
|
|
7752
|
+
var ANNEXB_START = Buffer.from([0, 0, 0, 1]);
|
|
7753
|
+
function parseVideoTag(body) {
|
|
7754
|
+
if (body.length < 5) return null;
|
|
7755
|
+
const b0 = body[0];
|
|
7756
|
+
return {
|
|
7757
|
+
frameType: b0 >> 4,
|
|
7758
|
+
codecId: b0 & 15,
|
|
7759
|
+
avcPacketType: body[1],
|
|
7760
|
+
compositionTime: body.readIntBE(2, 3),
|
|
7761
|
+
data: body.subarray(5)
|
|
7762
|
+
};
|
|
7763
|
+
}
|
|
7764
|
+
function parseAudioTag(body) {
|
|
7765
|
+
if (body.length < 1) return null;
|
|
7766
|
+
const b0 = body[0];
|
|
7767
|
+
const soundFormat = b0 >> 4;
|
|
7768
|
+
const isAac = soundFormat === 10;
|
|
7769
|
+
if (isAac && body.length < 2) return null;
|
|
7770
|
+
return {
|
|
7771
|
+
soundFormat,
|
|
7772
|
+
sampleRateIndex: b0 >> 2 & 3,
|
|
7773
|
+
channels: (b0 & 1) + 1,
|
|
7774
|
+
aacPacketType: isAac ? body[1] : null,
|
|
7775
|
+
data: body.subarray(isAac ? 2 : 1)
|
|
7776
|
+
};
|
|
7777
|
+
}
|
|
7778
|
+
function parseAvcConfig(rec) {
|
|
7779
|
+
const nalLengthSize = (rec[4] & 3) + 1;
|
|
7780
|
+
let p = 5;
|
|
7781
|
+
const sps = [];
|
|
7782
|
+
const pps = [];
|
|
7783
|
+
const numSps = rec[p++] & 31;
|
|
7784
|
+
for (let i = 0; i < numSps; i++) {
|
|
7785
|
+
const n = rec.readUInt16BE(p);
|
|
7786
|
+
sps.push(Buffer.from(rec.subarray(p + 2, p + 2 + n)));
|
|
7787
|
+
p += 2 + n;
|
|
7788
|
+
}
|
|
7789
|
+
const numPps = rec[p++];
|
|
7790
|
+
for (let i = 0; i < numPps; i++) {
|
|
7791
|
+
const n = rec.readUInt16BE(p);
|
|
7792
|
+
pps.push(Buffer.from(rec.subarray(p + 2, p + 2 + n)));
|
|
7793
|
+
p += 2 + n;
|
|
7794
|
+
}
|
|
7795
|
+
return { sps, pps, nalLengthSize };
|
|
7796
|
+
}
|
|
7797
|
+
function avccToAnnexB(data, cfg, prependParams) {
|
|
7798
|
+
const parts = [];
|
|
7799
|
+
if (prependParams) for (const nal of [...cfg.sps, ...cfg.pps]) parts.push(ANNEXB_START, nal);
|
|
7800
|
+
let p = 0;
|
|
7801
|
+
while (p + cfg.nalLengthSize <= data.length) {
|
|
7802
|
+
const len = data.readUIntBE(p, cfg.nalLengthSize);
|
|
7803
|
+
p += cfg.nalLengthSize;
|
|
7804
|
+
if (len === 0 || p + len > data.length) break;
|
|
7805
|
+
parts.push(ANNEXB_START, data.subarray(p, p + len));
|
|
7806
|
+
p += len;
|
|
7807
|
+
}
|
|
7808
|
+
return Buffer.concat(parts);
|
|
7809
|
+
}
|
|
7810
|
+
function parseAacConfig(asc) {
|
|
7811
|
+
const a0 = asc[0];
|
|
7812
|
+
const a1 = asc[1];
|
|
7813
|
+
return {
|
|
7814
|
+
objectType: a0 >> 3,
|
|
7815
|
+
samplingFrequencyIndex: (a0 & 7) << 1 | a1 >> 7,
|
|
7816
|
+
channelConfiguration: a1 >> 3 & 15
|
|
7817
|
+
};
|
|
7818
|
+
}
|
|
7819
|
+
var AAC_SAMPLE_RATES = [96e3, 88200, 64e3, 48e3, 44100, 32e3, 24e3, 22050, 16e3, 12e3, 11025, 8e3, 7350];
|
|
7820
|
+
function aacSampleRate(cfg) {
|
|
7821
|
+
return AAC_SAMPLE_RATES[cfg.samplingFrequencyIndex] ?? 0;
|
|
7822
|
+
}
|
|
7823
|
+
function aacToAdts(raw, cfg) {
|
|
7824
|
+
const frameLen = raw.length + 7;
|
|
7825
|
+
const h = Buffer.alloc(7);
|
|
7826
|
+
h[0] = 255;
|
|
7827
|
+
h[1] = 241;
|
|
7828
|
+
h[2] = cfg.objectType - 1 << 6 | cfg.samplingFrequencyIndex << 2 | cfg.channelConfiguration >> 2;
|
|
7829
|
+
h[3] = (cfg.channelConfiguration & 3) << 6 | frameLen >> 11 & 3;
|
|
7830
|
+
h[4] = frameLen >> 3 & 255;
|
|
7831
|
+
h[5] = (frameLen & 7) << 5 | 31;
|
|
7832
|
+
h[6] = 252;
|
|
7833
|
+
return Buffer.concat([h, raw]);
|
|
7834
|
+
}
|
|
7835
|
+
|
|
7836
|
+
// src/video/media/lv-rtmp-client.ts
|
|
7837
|
+
var LV_STATUS = {
|
|
7838
|
+
REQUEST_AUDIO_TYPE: "NetStream.RequestAudioType",
|
|
7839
|
+
FORCE_IFRAME_START: "NetStream.ForceIFrame.Start",
|
|
7840
|
+
PING_START: "NetStream.Ping.Start",
|
|
7841
|
+
PING_RESPONSE: "NetStream.Ping.Response",
|
|
7842
|
+
PRE_CONNECT: "NetStream.PreConnect",
|
|
7843
|
+
KEEPALIVE: "NetStream.Keepalive",
|
|
7844
|
+
SERVER_INFO: "NetStream.ServerInfo",
|
|
7845
|
+
TRANSFER_DATA: "NetStream.TransferData",
|
|
7846
|
+
PLAY_START: "NetStream.Play.Start",
|
|
7847
|
+
/** Server signals the talk (intercom uplink) channel is ready. */
|
|
7848
|
+
TALK_READY: "NetStream.TalkReady"
|
|
7849
|
+
};
|
|
7850
|
+
var TALK_AUDIO_HEADER_G711A = 114;
|
|
7851
|
+
var CONNECT_CAPABILITIES = 15;
|
|
7852
|
+
var CONNECT_AUDIO_CODECS = 3191;
|
|
7853
|
+
var CONNECT_VIDEO_CODECS = 252;
|
|
7854
|
+
var CONNECT_VIDEO_FUNCTION = 1;
|
|
7855
|
+
var PLAY_START_LIVE = -1e3;
|
|
7856
|
+
var HANDSHAKE_C0_PRIVATE = 4;
|
|
7857
|
+
var HANDSHAKE_S0S1_LEN = 1537;
|
|
7858
|
+
var DEFAULT_PING_INTERVAL_MS = 3e4;
|
|
7859
|
+
var DEFAULT_CACHE_DURATION_MS = 3e3;
|
|
7860
|
+
var ACK_THRESHOLD_BYTES = 25e4;
|
|
7861
|
+
var CSID_CONTROL = 2;
|
|
7862
|
+
var CSID_COMMAND = 3;
|
|
7863
|
+
var CSID_TALK = 4;
|
|
7864
|
+
var CSID_PLAY = 8;
|
|
7865
|
+
var PLAY_STREAM_ID = 1;
|
|
7866
|
+
function parseRelayUrl(url, cacheDurationMs) {
|
|
7867
|
+
const m = /^rtmp:\/\/([^/:]+)(?::(\d+))?\/(.*)$/.exec(url);
|
|
7868
|
+
if (!m) throw new Error(`not an rtmp:// url: ${url}`);
|
|
7869
|
+
const host = m[1];
|
|
7870
|
+
const port = m[2] ? Number(m[2]) : 1935;
|
|
7871
|
+
const path = m[3];
|
|
7872
|
+
const slash = path.lastIndexOf("/");
|
|
7873
|
+
if (slash < 0) throw new Error(`relay url has no playpath: ${url}`);
|
|
7874
|
+
let app = path.slice(0, slash);
|
|
7875
|
+
const playpath = path.slice(slash + 1);
|
|
7876
|
+
if (!/[?&]cacheDuration=/.test(app)) app += `${app.includes("?") ? "&" : "?"}cacheDuration=${cacheDurationMs}`;
|
|
7877
|
+
return { host, port, app, playpath, tcUrl: `rtmp://${host}:${port}/${app}` };
|
|
7878
|
+
}
|
|
7879
|
+
var LvRtmpClient = class extends EventEmitter2 {
|
|
7880
|
+
opts;
|
|
7881
|
+
endpoint;
|
|
7882
|
+
socket = null;
|
|
7883
|
+
handshakeBuf = Buffer.alloc(0);
|
|
7884
|
+
handshakeDone = false;
|
|
7885
|
+
c1Time = 0;
|
|
7886
|
+
reader = new ChunkReader(PRIVATE_MODE_CHUNK_SIZE);
|
|
7887
|
+
transactionId = 0;
|
|
7888
|
+
bytesIn = 0;
|
|
7889
|
+
bytesAcked = 0;
|
|
7890
|
+
ackWindow = ACK_THRESHOLD_BYTES;
|
|
7891
|
+
pingTimer = null;
|
|
7892
|
+
firstMessageSeen = false;
|
|
7893
|
+
avcConfig = null;
|
|
7894
|
+
aacConfig = null;
|
|
7895
|
+
closed = false;
|
|
7896
|
+
constructor(options) {
|
|
7897
|
+
super();
|
|
7898
|
+
this.opts = {
|
|
7899
|
+
url: options.url,
|
|
7900
|
+
cacheDurationMs: options.cacheDurationMs ?? DEFAULT_CACHE_DURATION_MS,
|
|
7901
|
+
requestAudioType: options.requestAudioType ?? true,
|
|
7902
|
+
ping: options.ping ?? true,
|
|
7903
|
+
pingIntervalMs: options.pingIntervalMs ?? DEFAULT_PING_INTERVAL_MS,
|
|
7904
|
+
forceIFrameOnStart: options.forceIFrameOnStart ?? false,
|
|
7905
|
+
connectTimeoutMs: options.connectTimeoutMs ?? 1e4,
|
|
7906
|
+
log: options.log ?? (() => {
|
|
7907
|
+
})
|
|
7908
|
+
};
|
|
7909
|
+
this.endpoint = parseRelayUrl(this.opts.url, this.opts.cacheDurationMs);
|
|
7910
|
+
}
|
|
7911
|
+
/** Open TCP, write C0+C1 and the pipelined connect/play/RequestAudioType. Resolves once written. */
|
|
7912
|
+
connect() {
|
|
7913
|
+
return new Promise((resolve, reject) => {
|
|
7914
|
+
const sock = net.createConnection({ host: this.endpoint.host, port: this.endpoint.port });
|
|
7915
|
+
this.socket = sock;
|
|
7916
|
+
sock.setNoDelay(true);
|
|
7917
|
+
sock.setTimeout(this.opts.connectTimeoutMs, () => {
|
|
7918
|
+
if (!this.handshakeDone) this.fail(new Error("handshake timeout"));
|
|
7919
|
+
});
|
|
7920
|
+
sock.once("error", (err) => {
|
|
7921
|
+
this.emit("error", err);
|
|
7922
|
+
reject(err);
|
|
7923
|
+
});
|
|
7924
|
+
sock.on("data", (d) => this.onData(d));
|
|
7925
|
+
sock.on("close", () => this.onClose());
|
|
7926
|
+
sock.once("connect", () => {
|
|
7927
|
+
this.opts.log(`tcp connected ${this.endpoint.host}:${this.endpoint.port}`);
|
|
7928
|
+
sock.write(Buffer.concat([this.buildC0C1(), ...this.buildOpeningSequence()]));
|
|
7929
|
+
this.emit("connected");
|
|
7930
|
+
resolve();
|
|
7931
|
+
});
|
|
7932
|
+
});
|
|
7933
|
+
}
|
|
7934
|
+
close() {
|
|
7935
|
+
this.closed = true;
|
|
7936
|
+
if (this.pingTimer) clearInterval(this.pingTimer);
|
|
7937
|
+
this.pingTimer = null;
|
|
7938
|
+
this.socket?.destroy();
|
|
7939
|
+
}
|
|
7940
|
+
/** onStatus encoder — byte-exact replica of liblvmedia IOT_RTMP_SendMessage (csid 3, fmt 1, ts 0). */
|
|
7941
|
+
buildStatus(code, extra) {
|
|
7942
|
+
const pairs = [
|
|
7943
|
+
["level", amfString("status")],
|
|
7944
|
+
["code", amfString(code)],
|
|
7945
|
+
["description", amfString("desc")]
|
|
7946
|
+
];
|
|
7947
|
+
if (extra) pairs.push([extra[0], amfString(extra[1])]);
|
|
7948
|
+
const body = Buffer.concat([amfString("onStatus"), amfNumber(++this.transactionId), amfNull(), amfObject(pairs)]);
|
|
7949
|
+
return encodeMessage({ fmt: 1, csid: CSID_COMMAND, type: MSG.COMMAND_AMF0, body });
|
|
7950
|
+
}
|
|
7951
|
+
sendStatus(code, extra) {
|
|
7952
|
+
this.write(this.buildStatus(code, extra));
|
|
7953
|
+
this.opts.log(`>> onStatus ${code}${extra ? ` ${extra[0]}=${extra[1]}` : ""} (txn ${this.transactionId})`);
|
|
7954
|
+
}
|
|
7955
|
+
forceIFrame() {
|
|
7956
|
+
this.sendStatus(LV_STATUS.FORCE_IFRAME_START);
|
|
7957
|
+
}
|
|
7958
|
+
// ---------------------------------------------------------------- outgoing
|
|
7959
|
+
buildC0C1() {
|
|
7960
|
+
this.c1Time = Math.floor(performance.now()) >>> 0;
|
|
7961
|
+
const c1 = Buffer.alloc(1536);
|
|
7962
|
+
c1.writeUInt32BE(this.c1Time, 0);
|
|
7963
|
+
c1.writeUInt32BE(0, 4);
|
|
7964
|
+
randomBytes2(1528).copy(c1, 8);
|
|
7965
|
+
return Buffer.concat([Buffer.from([HANDSHAKE_C0_PRIVATE]), c1]);
|
|
7966
|
+
}
|
|
7967
|
+
buildConnect() {
|
|
7968
|
+
const obj = amfObject([
|
|
7969
|
+
["app", amfString(this.endpoint.app)],
|
|
7970
|
+
["tcUrl", amfString(this.endpoint.tcUrl)],
|
|
7971
|
+
["fpad", amfBoolean(false)],
|
|
7972
|
+
["capabilities", amfNumber(CONNECT_CAPABILITIES)],
|
|
7973
|
+
["audioCodecs", amfNumber(CONNECT_AUDIO_CODECS)],
|
|
7974
|
+
["videoCodecs", amfNumber(CONNECT_VIDEO_CODECS)],
|
|
7975
|
+
["videoFunction", amfNumber(CONNECT_VIDEO_FUNCTION)]
|
|
7976
|
+
]);
|
|
7977
|
+
const body = Buffer.concat([amfString("connect"), amfNumber(++this.transactionId), obj]);
|
|
7978
|
+
return encodeMessage({ fmt: 0, csid: CSID_COMMAND, msid: 0, type: MSG.COMMAND_AMF0, body });
|
|
7979
|
+
}
|
|
7980
|
+
buildPlay() {
|
|
7981
|
+
const body = Buffer.concat([
|
|
7982
|
+
amfString("play"),
|
|
7983
|
+
amfNumber(++this.transactionId),
|
|
7984
|
+
amfNull(),
|
|
7985
|
+
amfString(this.endpoint.playpath),
|
|
7986
|
+
amfNumber(PLAY_START_LIVE)
|
|
7987
|
+
]);
|
|
7988
|
+
return encodeMessage({ fmt: 0, csid: CSID_PLAY, msid: PLAY_STREAM_ID, type: MSG.COMMAND_AMF0, body });
|
|
7989
|
+
}
|
|
7990
|
+
/** Exposed for the byte-exact self-test against the pcap. */
|
|
7991
|
+
buildOpeningSequence() {
|
|
7992
|
+
const seq = [this.buildConnect(), this.buildPlay()];
|
|
7993
|
+
if (this.opts.requestAudioType) seq.push(this.buildStatus(LV_STATUS.REQUEST_AUDIO_TYPE, ["audio_type", "1"]));
|
|
7994
|
+
return seq;
|
|
7995
|
+
}
|
|
7996
|
+
/**
|
|
7997
|
+
* Push one intercom (talk-back) audio frame UPSTREAM to the device — an RTMP
|
|
7998
|
+
* type-8 audio message on the talk chunk stream (csid 4, msid 1), exactly as
|
|
7999
|
+
* liblvmedia's `IOT_RTMP_SendAudio` does. `payload` is the raw codec audio
|
|
8000
|
+
* (default framing = G.711 A-law); `tsMs` is a running millisecond timestamp.
|
|
8001
|
+
* Only meaningful after the server sends {@link LV_STATUS.TALK_READY}.
|
|
8002
|
+
*/
|
|
8003
|
+
sendAudioFrame(payload, tsMs, header = TALK_AUDIO_HEADER_G711A) {
|
|
8004
|
+
const body = Buffer.concat([Buffer.from([header]), payload]);
|
|
8005
|
+
this.write(
|
|
8006
|
+
encodeMessage({ fmt: 0, csid: CSID_TALK, msid: PLAY_STREAM_ID, timestamp: tsMs >>> 0, type: MSG.AUDIO, body })
|
|
8007
|
+
);
|
|
8008
|
+
}
|
|
8009
|
+
write(buf) {
|
|
8010
|
+
if (!this.socket || this.socket.destroyed) return;
|
|
8011
|
+
this.socket.write(buf);
|
|
8012
|
+
}
|
|
8013
|
+
sendAck() {
|
|
8014
|
+
const b = Buffer.alloc(4);
|
|
8015
|
+
b.writeUInt32BE(this.bytesIn >>> 0, 0);
|
|
8016
|
+
this.write(encodeMessage({ fmt: 0, csid: CSID_CONTROL, msid: 0, type: MSG.ACK, body: b }));
|
|
8017
|
+
this.bytesAcked = this.bytesIn;
|
|
8018
|
+
}
|
|
8019
|
+
sendPingResponse(serverTs) {
|
|
8020
|
+
const body = Buffer.concat([Buffer.from([0, 7]), serverTs]);
|
|
8021
|
+
this.write(encodeMessage({ fmt: 0, csid: CSID_CONTROL, msid: 0, type: MSG.USER_CONTROL, body }));
|
|
8022
|
+
}
|
|
8023
|
+
startPinging() {
|
|
8024
|
+
if (!this.opts.ping || this.pingTimer) return;
|
|
8025
|
+
this.sendStatus(LV_STATUS.PING_START);
|
|
8026
|
+
this.pingTimer = setInterval(() => this.sendStatus(LV_STATUS.PING_START), this.opts.pingIntervalMs);
|
|
8027
|
+
}
|
|
8028
|
+
// ---------------------------------------------------------------- incoming
|
|
8029
|
+
onData(data) {
|
|
8030
|
+
this.bytesIn += data.length;
|
|
8031
|
+
let payload = data;
|
|
8032
|
+
if (!this.handshakeDone) {
|
|
8033
|
+
this.handshakeBuf = Buffer.concat([this.handshakeBuf, data]);
|
|
8034
|
+
if (this.handshakeBuf.length < HANDSHAKE_S0S1_LEN) return;
|
|
8035
|
+
this.onHandshake(this.handshakeBuf.subarray(0, HANDSHAKE_S0S1_LEN));
|
|
8036
|
+
payload = this.handshakeBuf.subarray(HANDSHAKE_S0S1_LEN);
|
|
8037
|
+
this.handshakeBuf = Buffer.alloc(0);
|
|
8038
|
+
this.handshakeDone = true;
|
|
8039
|
+
if (payload.length === 0) return;
|
|
8040
|
+
}
|
|
8041
|
+
let messages;
|
|
8042
|
+
try {
|
|
8043
|
+
messages = this.reader.feed(payload);
|
|
8044
|
+
} catch (err) {
|
|
8045
|
+
this.fail(err instanceof Error ? err : new Error(String(err)));
|
|
8046
|
+
return;
|
|
8047
|
+
}
|
|
8048
|
+
for (const m of messages) this.dispatch(m);
|
|
8049
|
+
if (this.bytesIn - this.bytesAcked >= this.ackWindow) this.sendAck();
|
|
8050
|
+
}
|
|
8051
|
+
onHandshake(s0s1) {
|
|
8052
|
+
const s0 = s0s1[0];
|
|
8053
|
+
const serverTime = s0s1.readUInt32BE(1);
|
|
8054
|
+
const zero = s0s1.readUInt32BE(5);
|
|
8055
|
+
this.opts.log(`<< S0=0x${s0.toString(16)} S1.time=${serverTime} S1.zero=0x${zero.toString(16)} (client sent 0x04; app logs a mismatch but continues)`);
|
|
8056
|
+
}
|
|
8057
|
+
dispatch(m) {
|
|
8058
|
+
if (!this.firstMessageSeen) {
|
|
8059
|
+
this.firstMessageSeen = true;
|
|
8060
|
+
this.startPinging();
|
|
8061
|
+
}
|
|
8062
|
+
switch (m.type) {
|
|
8063
|
+
case MSG.SET_CHUNK_SIZE: {
|
|
8064
|
+
const size = m.body.readUInt32BE(0) & 2147483647;
|
|
8065
|
+
this.opts.log(`<< SetChunkSize ${size}`);
|
|
8066
|
+
this.reader.chunkSize = size;
|
|
8067
|
+
return;
|
|
8068
|
+
}
|
|
8069
|
+
case MSG.WINDOW_ACK_SIZE:
|
|
8070
|
+
this.ackWindow = Math.min(ACK_THRESHOLD_BYTES, m.body.readUInt32BE(0));
|
|
8071
|
+
this.opts.log(`<< WindowAckSize ${m.body.readUInt32BE(0)}`);
|
|
8072
|
+
return;
|
|
8073
|
+
case MSG.SET_PEER_BW:
|
|
8074
|
+
this.opts.log(`<< SetPeerBandwidth ${m.body.readUInt32BE(0)} limit=${m.body[4]}`);
|
|
8075
|
+
return;
|
|
8076
|
+
case MSG.ACK:
|
|
8077
|
+
case MSG.ABORT:
|
|
8078
|
+
return;
|
|
8079
|
+
case MSG.USER_CONTROL:
|
|
8080
|
+
return this.onUserControl(m.body);
|
|
8081
|
+
case MSG.COMMAND_AMF0:
|
|
8082
|
+
return this.onCommand(m);
|
|
8083
|
+
case MSG.DATA_AMF0:
|
|
8084
|
+
return this.onDataMessage(m.body);
|
|
8085
|
+
case MSG.AUDIO:
|
|
8086
|
+
return this.onAudio(m);
|
|
8087
|
+
case MSG.VIDEO:
|
|
8088
|
+
return this.onVideo(m);
|
|
8089
|
+
default:
|
|
8090
|
+
this.opts.log(`<< unknown message type ${m.type} len=${m.body.length}`);
|
|
8091
|
+
}
|
|
8092
|
+
}
|
|
8093
|
+
onUserControl(body) {
|
|
8094
|
+
const event = body.readUInt16BE(0);
|
|
8095
|
+
const names = { 0: "StreamBegin", 1: "StreamEOF", 2: "StreamDry", 4: "StreamIsRecorded", 6: "PingRequest", 7: "PingResponse" };
|
|
8096
|
+
this.opts.log(`<< UserControl ${names[event] ?? event} ${body.subarray(2).toString("hex")}`);
|
|
8097
|
+
if (event === 6) this.sendPingResponse(body.subarray(2, 6));
|
|
8098
|
+
}
|
|
8099
|
+
onCommand(m) {
|
|
8100
|
+
let values;
|
|
8101
|
+
try {
|
|
8102
|
+
values = decodeAmf0(m.body);
|
|
8103
|
+
} catch (err) {
|
|
8104
|
+
this.opts.log(`<< undecodable command: ${m.body.toString("hex")}`);
|
|
8105
|
+
return;
|
|
8106
|
+
}
|
|
8107
|
+
const [name, txn, , info] = values;
|
|
8108
|
+
this.opts.log(`<< ${String(name)} ${JSON.stringify(values.slice(1))}`);
|
|
8109
|
+
this.emit("command", String(name), values);
|
|
8110
|
+
if (name === "onStatus" && info && typeof info === "object" && !Array.isArray(info)) {
|
|
8111
|
+
const fields = info;
|
|
8112
|
+
this.emit("status", {
|
|
8113
|
+
code: String(fields.code ?? ""),
|
|
8114
|
+
level: String(fields.level ?? ""),
|
|
8115
|
+
description: String(fields.description ?? ""),
|
|
8116
|
+
fields,
|
|
8117
|
+
transactionId: typeof txn === "number" ? txn : 0
|
|
8118
|
+
});
|
|
8119
|
+
if (fields.code === LV_STATUS.PLAY_START && this.opts.forceIFrameOnStart) this.forceIFrame();
|
|
8120
|
+
}
|
|
8121
|
+
}
|
|
8122
|
+
onDataMessage(body) {
|
|
8123
|
+
try {
|
|
8124
|
+
const values = decodeAmf0(body);
|
|
8125
|
+
this.opts.log(`<< data ${JSON.stringify(values).slice(0, 300)}`);
|
|
8126
|
+
const obj = values.find((v) => v && typeof v === "object" && !Array.isArray(v));
|
|
8127
|
+
if (obj) this.emit("metadata", obj);
|
|
8128
|
+
} catch {
|
|
8129
|
+
this.opts.log(`<< undecodable data message len=${body.length}`);
|
|
8130
|
+
}
|
|
8131
|
+
}
|
|
8132
|
+
onAudio(m) {
|
|
8133
|
+
this.emit("audio", { timestamp: m.timestamp, body: m.body });
|
|
8134
|
+
const tag = parseAudioTag(m.body);
|
|
8135
|
+
if (!tag) return;
|
|
8136
|
+
if (tag.soundFormat === 10) {
|
|
8137
|
+
if (tag.aacPacketType === 0) {
|
|
8138
|
+
this.aacConfig = parseAacConfig(tag.data);
|
|
8139
|
+
this.emit("audioInfo", { codec: "aac", sampleRate: aacSampleRate(this.aacConfig), channels: this.aacConfig.channelConfiguration });
|
|
8140
|
+
return;
|
|
8141
|
+
}
|
|
8142
|
+
if (this.aacConfig) this.emit("audioFrame", aacToAdts(tag.data, this.aacConfig));
|
|
8143
|
+
return;
|
|
8144
|
+
}
|
|
8145
|
+
if (tag.soundFormat === 7 || tag.soundFormat === 8) {
|
|
8146
|
+
if (!this.aacConfig) this.emit("audioInfo", { codec: tag.soundFormat === 7 ? "g711a" : "g711u", sampleRate: 8e3, channels: 1 });
|
|
8147
|
+
this.emit("audioFrame", tag.data);
|
|
8148
|
+
return;
|
|
8149
|
+
}
|
|
8150
|
+
this.emit("audioInfo", { codec: "unknown", sampleRate: 0, channels: tag.channels });
|
|
8151
|
+
}
|
|
8152
|
+
onVideo(m) {
|
|
8153
|
+
this.emit("video", { timestamp: m.timestamp, body: m.body });
|
|
8154
|
+
const tag = parseVideoTag(m.body);
|
|
8155
|
+
if (!tag || tag.codecId !== 7) return;
|
|
8156
|
+
if (tag.avcPacketType === 0) {
|
|
8157
|
+
this.avcConfig = parseAvcConfig(tag.data);
|
|
8158
|
+
return;
|
|
8159
|
+
}
|
|
8160
|
+
if (tag.avcPacketType !== 1 || !this.avcConfig) return;
|
|
8161
|
+
const isKeyframe = tag.frameType === 1;
|
|
8162
|
+
this.emit("videoAccessUnit", {
|
|
8163
|
+
data: avccToAnnexB(tag.data, this.avcConfig, isKeyframe),
|
|
8164
|
+
isKeyframe,
|
|
8165
|
+
videoType: "H264",
|
|
8166
|
+
microseconds: m.timestamp * 1e3,
|
|
8167
|
+
time: m.timestamp + tag.compositionTime
|
|
8168
|
+
});
|
|
8169
|
+
}
|
|
8170
|
+
fail(err) {
|
|
8171
|
+
this.opts.log(`!! ${err.message}`);
|
|
8172
|
+
this.emit("error", err);
|
|
8173
|
+
this.close();
|
|
8174
|
+
}
|
|
8175
|
+
onClose() {
|
|
8176
|
+
if (this.pingTimer) clearInterval(this.pingTimer);
|
|
8177
|
+
this.pingTimer = null;
|
|
8178
|
+
if (!this.closed) this.opts.log("socket closed by peer");
|
|
8179
|
+
this.closed = true;
|
|
8180
|
+
this.emit("close");
|
|
8181
|
+
}
|
|
8182
|
+
};
|
|
8183
|
+
|
|
8184
|
+
// src/video/media/g711.ts
|
|
8185
|
+
var ALAW_SEG_END = [31, 63, 127, 255, 511, 1023, 2047, 4095];
|
|
8186
|
+
function pcm16ToALaw(sample) {
|
|
8187
|
+
let s = sample;
|
|
8188
|
+
let sign = ~s >> 8 & 128;
|
|
8189
|
+
if (sign === 0) s = -s;
|
|
8190
|
+
if (s > 32635) s = 32635;
|
|
8191
|
+
let aval;
|
|
8192
|
+
if (s >= 256) {
|
|
8193
|
+
let seg = 7;
|
|
8194
|
+
for (let i = 0; i < 8; i++) {
|
|
8195
|
+
if (s <= ALAW_SEG_END[i]) {
|
|
8196
|
+
seg = i;
|
|
8197
|
+
break;
|
|
8198
|
+
}
|
|
8199
|
+
}
|
|
8200
|
+
const mantissa = s >> seg + 3 & 15;
|
|
8201
|
+
aval = seg << 4 | mantissa;
|
|
8202
|
+
} else {
|
|
8203
|
+
aval = s >> 4;
|
|
8204
|
+
}
|
|
8205
|
+
return (aval ^ sign ^ 85) & 255;
|
|
8206
|
+
}
|
|
8207
|
+
function pcm16leToALaw(pcm) {
|
|
8208
|
+
const count = pcm.length >> 1;
|
|
8209
|
+
const out = Buffer.allocUnsafe(count);
|
|
8210
|
+
for (let i = 0; i < count; i++) {
|
|
8211
|
+
out[i] = pcm16ToALaw(pcm.readInt16LE(i * 2));
|
|
8212
|
+
}
|
|
8213
|
+
return out;
|
|
8214
|
+
}
|
|
8215
|
+
|
|
8216
|
+
// src/video/media/camera-stream.ts
|
|
8217
|
+
var DreameCameraStream = class extends TypedEmitter {
|
|
8218
|
+
#controller;
|
|
8219
|
+
#clientFactory;
|
|
8220
|
+
#log;
|
|
8221
|
+
#client = null;
|
|
8222
|
+
#state = "idle";
|
|
8223
|
+
#videoFrames = 0;
|
|
8224
|
+
#audioFrames = 0;
|
|
8225
|
+
#talkReady = false;
|
|
8226
|
+
#talkWaiters = [];
|
|
8227
|
+
#talkTs = 0;
|
|
8228
|
+
constructor(input) {
|
|
8229
|
+
super();
|
|
8230
|
+
this.#controller = input.controller;
|
|
8231
|
+
this.#log = input.log ?? (() => {
|
|
8232
|
+
});
|
|
8233
|
+
this.#clientFactory = input.clientFactory ?? ((url) => new LvRtmpClient({
|
|
8234
|
+
url,
|
|
8235
|
+
...input.requestAudioType !== void 0 ? { requestAudioType: input.requestAudioType } : {},
|
|
8236
|
+
...input.ping !== void 0 ? { ping: input.ping } : {},
|
|
8237
|
+
...input.log ? { log: input.log } : {}
|
|
8238
|
+
}));
|
|
8239
|
+
}
|
|
8240
|
+
/** True while frames are flowing. */
|
|
8241
|
+
get isRunning() {
|
|
8242
|
+
return this.#state === "running";
|
|
8243
|
+
}
|
|
8244
|
+
/**
|
|
8245
|
+
* Cold-start the monitor, connect to the relay, and begin emitting frames.
|
|
8246
|
+
* Resolves once connected. Throws (and cleans up) if the monitor or relay
|
|
8247
|
+
* connection fails.
|
|
8248
|
+
*/
|
|
8249
|
+
async start() {
|
|
8250
|
+
if (this.#state !== "idle") {
|
|
8251
|
+
throw new DreameError(`camera stream cannot start from state '${this.#state}'`);
|
|
8252
|
+
}
|
|
8253
|
+
this.#state = "starting";
|
|
8254
|
+
try {
|
|
8255
|
+
this.#log("[nodedreame:stream] starting");
|
|
8256
|
+
const handle = await this.#controller.open();
|
|
8257
|
+
const client = this.#clientFactory(handle.rtmpUrl);
|
|
8258
|
+
this.#client = client;
|
|
8259
|
+
client.on("videoAccessUnit", (e) => {
|
|
8260
|
+
this.#videoFrames += 1;
|
|
8261
|
+
if (this.#videoFrames === 1) this.#log("[nodedreame:stream] first video access unit");
|
|
8262
|
+
this.emit("videoAccessUnit", e);
|
|
8263
|
+
});
|
|
8264
|
+
client.on("audioFrame", (buf) => {
|
|
8265
|
+
this.#audioFrames += 1;
|
|
8266
|
+
if (this.#audioFrames === 1) this.#log("[nodedreame:stream] first audio frame");
|
|
8267
|
+
this.emit("audioFrame", buf);
|
|
8268
|
+
});
|
|
8269
|
+
client.on("audioInfo", (info) => {
|
|
8270
|
+
this.#log(`[nodedreame:stream] audio ${info.codec} ${info.sampleRate}Hz x${info.channels}`);
|
|
8271
|
+
this.emit("audioInfo", info);
|
|
8272
|
+
});
|
|
8273
|
+
client.on("status", (e) => {
|
|
8274
|
+
if (e.code === LV_STATUS.TALK_READY) {
|
|
8275
|
+
this.#log("[nodedreame:stream] talk channel ready");
|
|
8276
|
+
this.#talkReady = true;
|
|
8277
|
+
const waiters = this.#talkWaiters;
|
|
8278
|
+
this.#talkWaiters = [];
|
|
8279
|
+
for (const w of waiters) w();
|
|
8280
|
+
}
|
|
8281
|
+
});
|
|
8282
|
+
client.on("error", (err) => {
|
|
8283
|
+
this.#log(`[nodedreame:stream] rtmp error: ${err.message}`);
|
|
8284
|
+
this.emit("error", err);
|
|
8285
|
+
});
|
|
8286
|
+
client.on("close", () => {
|
|
8287
|
+
this.#log("[nodedreame:stream] upstream relay closed");
|
|
8288
|
+
if (this.#state === "running") void this.stop();
|
|
8289
|
+
});
|
|
8290
|
+
await client.connect();
|
|
8291
|
+
this.#state = "running";
|
|
8292
|
+
this.#log("[nodedreame:stream] connected to relay");
|
|
8293
|
+
this.emit("started", { rtmpUrl: handle.rtmpUrl });
|
|
8294
|
+
return { rtmpUrl: handle.rtmpUrl };
|
|
8295
|
+
} catch (err) {
|
|
8296
|
+
this.#state = "idle";
|
|
8297
|
+
await this.#safeTeardown();
|
|
8298
|
+
throw err;
|
|
8299
|
+
}
|
|
8300
|
+
}
|
|
8301
|
+
/** Close the relay connection and release the monitor. Idempotent. */
|
|
8302
|
+
async stop() {
|
|
8303
|
+
if (this.#state === "idle" || this.#state === "stopping") return;
|
|
8304
|
+
this.#state = "stopping";
|
|
8305
|
+
this.#log(`[nodedreame:stream] stopping (video=${this.#videoFrames} audio=${this.#audioFrames})`);
|
|
8306
|
+
await this.#safeTeardown();
|
|
8307
|
+
this.#state = "idle";
|
|
8308
|
+
this.emit("stopped");
|
|
8309
|
+
}
|
|
8310
|
+
/**
|
|
8311
|
+
* Open the two-way intercom: send the MIoT start, then resolve once the relay
|
|
8312
|
+
* signals the talk channel is ready (so it's safe to {@link sendTalkPcm}).
|
|
8313
|
+
* Rejects if not ready within `timeoutMs`.
|
|
8314
|
+
*/
|
|
8315
|
+
async startTalk(opts) {
|
|
8316
|
+
if (this.#state !== "running") throw new DreameError("stream is not running; start() first");
|
|
8317
|
+
this.#log("[nodedreame:stream] intercom start");
|
|
8318
|
+
await this.#controller.startIntercom(
|
|
8319
|
+
opts?.needRecordSound !== void 0 || opts?.videoCall !== void 0 ? { ...opts.needRecordSound !== void 0 ? { needRecordSound: opts.needRecordSound } : {}, ...opts.videoCall ? { videoCall: true } : {} } : void 0
|
|
8320
|
+
);
|
|
8321
|
+
this.#talkTs = 0;
|
|
8322
|
+
await this.whenTalkReady(opts?.timeoutMs ?? 5e3);
|
|
8323
|
+
}
|
|
8324
|
+
/** Resolve when the talk channel is ready (or reject on timeout). */
|
|
8325
|
+
whenTalkReady(timeoutMs = 5e3) {
|
|
8326
|
+
if (this.#talkReady) return Promise.resolve();
|
|
8327
|
+
return new Promise((resolve, reject) => {
|
|
8328
|
+
const timer = setTimeout(() => reject(new DreameError("timed out waiting for TalkReady")), timeoutMs);
|
|
8329
|
+
timer.unref?.();
|
|
8330
|
+
this.#talkWaiters.push(() => {
|
|
8331
|
+
clearTimeout(timer);
|
|
8332
|
+
resolve();
|
|
8333
|
+
});
|
|
8334
|
+
});
|
|
8335
|
+
}
|
|
8336
|
+
/**
|
|
8337
|
+
* Encode 16-bit LE mono PCM (8 kHz) to G.711 A-law and push it upstream.
|
|
8338
|
+
* `tsMs` defaults to a running clock advanced by the frame duration.
|
|
8339
|
+
*/
|
|
8340
|
+
sendTalkPcm(pcm16le, tsMs) {
|
|
8341
|
+
const alaw = pcm16leToALaw(pcm16le);
|
|
8342
|
+
this.sendTalkAlaw(alaw, tsMs);
|
|
8343
|
+
}
|
|
8344
|
+
/** Push raw A-law audio upstream (advancing the running talk clock). */
|
|
8345
|
+
sendTalkAlaw(alaw, tsMs) {
|
|
8346
|
+
if (!this.#client) throw new DreameError("stream is not running");
|
|
8347
|
+
const ts = tsMs ?? this.#talkTs;
|
|
8348
|
+
this.#client.sendAudioFrame(alaw, ts);
|
|
8349
|
+
this.#talkTs = ts + Math.round(alaw.length / 8);
|
|
8350
|
+
}
|
|
8351
|
+
/** Close the two-way intercom (MIoT stop). */
|
|
8352
|
+
async stopTalk() {
|
|
8353
|
+
this.#talkReady = false;
|
|
8354
|
+
this.#log("[nodedreame:stream] intercom stop");
|
|
8355
|
+
await this.#controller.stopIntercom();
|
|
8356
|
+
}
|
|
8357
|
+
async #safeTeardown() {
|
|
8358
|
+
this.#talkReady = false;
|
|
8359
|
+
this.#talkWaiters = [];
|
|
8360
|
+
try {
|
|
8361
|
+
this.#client?.close();
|
|
8362
|
+
} catch {
|
|
8363
|
+
}
|
|
8364
|
+
this.#client = null;
|
|
8365
|
+
try {
|
|
8366
|
+
await this.#controller.close();
|
|
8367
|
+
} catch (err) {
|
|
8368
|
+
this.emit("error", err instanceof Error ? err : new Error(String(err)));
|
|
8369
|
+
}
|
|
8370
|
+
}
|
|
8371
|
+
};
|
|
6221
8372
|
export {
|
|
6222
8373
|
AI_FEATURE_BIT,
|
|
6223
8374
|
AI_FEATURE_JSON_KEY,
|
|
8375
|
+
ALIYUN_REGION_ID,
|
|
6224
8376
|
AUTO_SWITCH_JSON_KEY,
|
|
6225
8377
|
BaseDevice,
|
|
6226
8378
|
ChargingStatus,
|
|
6227
8379
|
CleaningMode,
|
|
8380
|
+
DRIVE_DIRECTIONS,
|
|
6228
8381
|
DefaultCapabilityResolver,
|
|
6229
8382
|
DreameApiError,
|
|
6230
8383
|
DreameAuthError,
|
|
8384
|
+
DreameCameraController,
|
|
8385
|
+
DreameCameraStream,
|
|
6231
8386
|
DreameDeviceOfflineError,
|
|
6232
8387
|
DreameError,
|
|
6233
8388
|
DreameTransportError,
|
|
8389
|
+
DreameVideoSession,
|
|
6234
8390
|
LIBRARY_NAME,
|
|
8391
|
+
LV_STATUS,
|
|
8392
|
+
LvRtmpClient,
|
|
8393
|
+
MONITOR_AIID,
|
|
8394
|
+
MONITOR_PIID,
|
|
8395
|
+
MONITOR_SIID,
|
|
8396
|
+
MONITOR_VENDOR_TOKEN,
|
|
6235
8397
|
MODEL_CAPABILITIES2 as MOWER_MODEL_CAPABILITIES,
|
|
6236
8398
|
MOWER_TASK_SUBSTATES,
|
|
6237
8399
|
MiotError,
|
|
@@ -6244,34 +8406,66 @@ export {
|
|
|
6244
8406
|
MowerStatus,
|
|
6245
8407
|
MowerTaskStatus,
|
|
6246
8408
|
Nodreame,
|
|
8409
|
+
PET_SOUNDS,
|
|
6247
8410
|
SuctionLevel,
|
|
8411
|
+
TALK_AUDIO_HEADER_G711A,
|
|
6248
8412
|
TaskStatus,
|
|
8413
|
+
VACUUM_ACTIONS,
|
|
6249
8414
|
VACUUM_CONSUMABLES,
|
|
6250
8415
|
MODEL_CAPABILITIES as VACUUM_MODEL_CAPABILITIES,
|
|
8416
|
+
VACUUM_MOVE,
|
|
8417
|
+
VACUUM_SIID,
|
|
6251
8418
|
VacuumCapabilityResolver,
|
|
6252
8419
|
VacuumDevice,
|
|
6253
8420
|
WaterVolume,
|
|
8421
|
+
aacSampleRate,
|
|
8422
|
+
aacToAdts,
|
|
8423
|
+
avccToAnnexB,
|
|
6254
8424
|
consumableSpec,
|
|
6255
8425
|
createClientDumper,
|
|
6256
8426
|
createDumper,
|
|
8427
|
+
createIotSession,
|
|
6257
8428
|
decodeAiFeature,
|
|
6258
8429
|
decodeAutoSwitch,
|
|
6259
8430
|
decodeAutoSwitchAll,
|
|
8431
|
+
decodeWifiSignalMap,
|
|
6260
8432
|
encodeAiFeatureWrite,
|
|
6261
8433
|
encodeAutoSwitchWrite,
|
|
8434
|
+
explainNoCameraChannel,
|
|
6262
8435
|
extractMowerConsumableValues,
|
|
8436
|
+
getAliyunAuthCode,
|
|
8437
|
+
getDeviceVideoProfile,
|
|
6263
8438
|
getMowerCapabilities,
|
|
6264
8439
|
getVacuumCapabilities,
|
|
8440
|
+
getVideoAccessToken,
|
|
8441
|
+
getVideoFamilyId,
|
|
8442
|
+
hashAccessCode,
|
|
6265
8443
|
isAuthRefusedError,
|
|
6266
8444
|
isDreameConsumableKey,
|
|
8445
|
+
listDevices,
|
|
8446
|
+
loginByOauth,
|
|
8447
|
+
makeMonitorSession,
|
|
6267
8448
|
mowerConsumableIndex,
|
|
6268
8449
|
mowerFaultSeverity,
|
|
8450
|
+
parseAacConfig,
|
|
8451
|
+
parseAvcConfig,
|
|
8452
|
+
parseConnectivity,
|
|
6269
8453
|
parseMowerConsumables,
|
|
6270
8454
|
parseMowerHeartbeat,
|
|
6271
8455
|
parseMowingProgress,
|
|
8456
|
+
parseObstacleData,
|
|
8457
|
+
parsePersonFollow,
|
|
8458
|
+
parseRelayUrl,
|
|
8459
|
+
pcm16ToALaw,
|
|
8460
|
+
pcm16leToALaw,
|
|
8461
|
+
remoteDriveValue,
|
|
6272
8462
|
renderMowerSvg,
|
|
6273
8463
|
renderVacuumPng,
|
|
8464
|
+
renderWifiSignalPng,
|
|
6274
8465
|
resolveCapabilities,
|
|
6275
|
-
|
|
8466
|
+
signApiGatewayRequest,
|
|
8467
|
+
streamQuery,
|
|
8468
|
+
supportedAutoSwitchKeys,
|
|
8469
|
+
toVideoProfile
|
|
6276
8470
|
};
|
|
6277
8471
|
//# sourceMappingURL=index.js.map
|