node-miio 0.7.0 → 0.8.0

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.
Files changed (77) hide show
  1. package/README.md +4 -0
  2. package/dist/cli/commands/roborock/call.d.ts +10 -0
  3. package/dist/cli/commands/roborock/call.js +34 -0
  4. package/dist/cli/commands/roborock/call.js.map +1 -0
  5. package/dist/cli/commands/roborock/devices.d.ts +8 -0
  6. package/dist/cli/commands/roborock/devices.js +58 -0
  7. package/dist/cli/commands/roborock/devices.js.map +1 -0
  8. package/dist/cli/commands/roborock/login.d.ts +7 -0
  9. package/dist/cli/commands/roborock/login.js +34 -0
  10. package/dist/cli/commands/roborock/login.js.map +1 -0
  11. package/dist/cli/commands/roborock/logout.d.ts +4 -0
  12. package/dist/cli/commands/roborock/logout.js +14 -0
  13. package/dist/cli/commands/roborock/logout.js.map +1 -0
  14. package/dist/cli/commands/roborock/map.d.ts +10 -0
  15. package/dist/cli/commands/roborock/map.js +74 -0
  16. package/dist/cli/commands/roborock/map.js.map +1 -0
  17. package/dist/cli/commands/roborock/robot.d.ts +30 -0
  18. package/dist/cli/commands/roborock/robot.js +61 -0
  19. package/dist/cli/commands/roborock/robot.js.map +1 -0
  20. package/dist/cli/commands/roborock/rooms.d.ts +9 -0
  21. package/dist/cli/commands/roborock/rooms.js +40 -0
  22. package/dist/cli/commands/roborock/rooms.js.map +1 -0
  23. package/dist/cli/commands/roborock.d.ts +5 -0
  24. package/dist/cli/commands/roborock.js +55 -0
  25. package/dist/cli/commands/roborock.js.map +1 -0
  26. package/dist/cli/index.js +2 -0
  27. package/dist/cli/index.js.map +1 -1
  28. package/dist/lib/device_info.d.ts +6 -0
  29. package/dist/lib/devices/vacuums/vacuum.d.ts +3 -3
  30. package/dist/lib/devices/vacuums/vacuum.js +13 -3
  31. package/dist/lib/devices/vacuums/vacuum.js.map +1 -1
  32. package/dist/lib/devices/vacuums/vacuum_modes.d.ts +2 -0
  33. package/dist/lib/devices/vacuums/vacuum_modes.js +15 -0
  34. package/dist/lib/devices/vacuums/vacuum_modes.js.map +1 -1
  35. package/dist/lib/index.d.ts +1 -0
  36. package/dist/lib/index.js +1 -0
  37. package/dist/lib/index.js.map +1 -1
  38. package/dist/lib/logger.js +1 -1
  39. package/dist/lib/logger.js.map +1 -1
  40. package/dist/lib/management.d.ts +2 -2
  41. package/dist/lib/management.js.map +1 -1
  42. package/dist/lib/roborock/device.d.ts +118 -0
  43. package/dist/lib/roborock/device.js +273 -0
  44. package/dist/lib/roborock/device.js.map +1 -0
  45. package/dist/lib/roborock/errors.d.ts +18 -0
  46. package/dist/lib/roborock/errors.js +37 -0
  47. package/dist/lib/roborock/errors.js.map +1 -0
  48. package/dist/lib/roborock/hawk.d.ts +39 -0
  49. package/dist/lib/roborock/hawk.js +48 -0
  50. package/dist/lib/roborock/hawk.js.map +1 -0
  51. package/dist/lib/roborock/index.d.ts +9 -0
  52. package/dist/lib/roborock/index.js +36 -0
  53. package/dist/lib/roborock/index.js.map +1 -0
  54. package/dist/lib/roborock/local_connection.d.ts +72 -0
  55. package/dist/lib/roborock/local_connection.js +232 -0
  56. package/dist/lib/roborock/local_connection.js.map +1 -0
  57. package/dist/lib/roborock/map_response.d.ts +26 -0
  58. package/dist/lib/roborock/map_response.js +104 -0
  59. package/dist/lib/roborock/map_response.js.map +1 -0
  60. package/dist/lib/roborock/message.d.ts +110 -0
  61. package/dist/lib/roborock/message.js +313 -0
  62. package/dist/lib/roborock/message.js.map +1 -0
  63. package/dist/lib/roborock/mqtt.d.ts +119 -0
  64. package/dist/lib/roborock/mqtt.js +305 -0
  65. package/dist/lib/roborock/mqtt.js.map +1 -0
  66. package/dist/lib/roborock/rooms.d.ts +17 -0
  67. package/dist/lib/roborock/rooms.js +23 -0
  68. package/dist/lib/roborock/rooms.js.map +1 -0
  69. package/dist/lib/roborock/session_store.d.ts +21 -0
  70. package/dist/lib/roborock/session_store.js +52 -0
  71. package/dist/lib/roborock/session_store.js.map +1 -0
  72. package/dist/lib/roborock/web_api.d.ts +142 -0
  73. package/dist/lib/roborock/web_api.js +334 -0
  74. package/dist/lib/roborock/web_api.js.map +1 -0
  75. package/docs/roborock.md +91 -0
  76. package/package.json +2 -1
  77. package/snapshots/vacuum-specs.json.gz +0 -0
@@ -0,0 +1,18 @@
1
+ /** Base class of the errors thrown by the Roborock account client */
2
+ export declare class RoborockError extends Error {
3
+ constructor(message: string);
4
+ }
5
+ /** The account doesn't exist, or the verification code is wrong */
6
+ export declare class RoborockAuthError extends RoborockError {
7
+ readonly code?: number | undefined;
8
+ constructor(message: string, code?: number | undefined);
9
+ }
10
+ /** The session is no longer valid: log in again */
11
+ export declare class RoborockSessionExpiredError extends RoborockError {
12
+ constructor();
13
+ }
14
+ /** The API returned an error */
15
+ export declare class RoborockApiError extends RoborockError {
16
+ readonly code?: number | string | undefined;
17
+ constructor(message: string, code?: number | string | undefined);
18
+ }
@@ -0,0 +1,37 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.RoborockApiError = exports.RoborockSessionExpiredError = exports.RoborockAuthError = exports.RoborockError = void 0;
4
+ /** Base class of the errors thrown by the Roborock account client */
5
+ class RoborockError extends Error {
6
+ constructor(message) {
7
+ super(message);
8
+ this.name = new.target.name;
9
+ }
10
+ }
11
+ exports.RoborockError = RoborockError;
12
+ /** The account doesn't exist, or the verification code is wrong */
13
+ class RoborockAuthError extends RoborockError {
14
+ code;
15
+ constructor(message, code) {
16
+ super(message);
17
+ this.code = code;
18
+ }
19
+ }
20
+ exports.RoborockAuthError = RoborockAuthError;
21
+ /** The session is no longer valid: log in again */
22
+ class RoborockSessionExpiredError extends RoborockError {
23
+ constructor() {
24
+ super("The Roborock session expired: please log in again");
25
+ }
26
+ }
27
+ exports.RoborockSessionExpiredError = RoborockSessionExpiredError;
28
+ /** The API returned an error */
29
+ class RoborockApiError extends RoborockError {
30
+ code;
31
+ constructor(message, code) {
32
+ super(message);
33
+ this.code = code;
34
+ }
35
+ }
36
+ exports.RoborockApiError = RoborockApiError;
37
+ //# sourceMappingURL=errors.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.js","sourceRoot":"","sources":["../../../src/lib/roborock/errors.ts"],"names":[],"mappings":";;;AAAA,qEAAqE;AACrE,MAAa,aAAc,SAAQ,KAAK;IACtC,YAAY,OAAe;QACzB,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,IAAI,GAAG,GAAG,CAAC,MAAM,CAAC,IAAI,CAAC;IAC9B,CAAC;CACF;AALD,sCAKC;AAED,mEAAmE;AACnE,MAAa,iBAAkB,SAAQ,aAAa;IAGhC;IAFlB,YACE,OAAe,EACC,IAAa;QAE7B,KAAK,CAAC,OAAO,CAAC,CAAC;QAFC,SAAI,GAAJ,IAAI,CAAS;IAG/B,CAAC;CACF;AAPD,8CAOC;AAED,mDAAmD;AACnD,MAAa,2BAA4B,SAAQ,aAAa;IAC5D;QACE,KAAK,CAAC,mDAAmD,CAAC,CAAC;IAC7D,CAAC;CACF;AAJD,kEAIC;AAED,gCAAgC;AAChC,MAAa,gBAAiB,SAAQ,aAAa;IAG/B;IAFlB,YACE,OAAe,EACC,IAAsB;QAEtC,KAAK,CAAC,OAAO,CAAC,CAAC;QAFC,SAAI,GAAJ,IAAI,CAAkB;IAGxC,CAAC;CACF;AAPD,4CAOC"}
@@ -0,0 +1,39 @@
1
+ /**
2
+ * The `rriot` credentials returned by the Roborock login. `u`/`s`/`h` sign the requests to the RRIoT API (`r.a`);
3
+ * `k` and `r.m` are for MQTT.
4
+ */
5
+ export interface RoborockRriot {
6
+ u: string;
7
+ s: string;
8
+ h: string;
9
+ k: string;
10
+ r: {
11
+ /** The region */
12
+ r: string;
13
+ /** The RRIoT API URL */
14
+ a: string;
15
+ /** The MQTT URL */
16
+ m: string;
17
+ l?: string;
18
+ };
19
+ }
20
+ export interface HawkOptions {
21
+ /** Query params of the request */
22
+ params?: Record<string, string>;
23
+ /** Form fields of the request body */
24
+ form?: Record<string, string>;
25
+ /** Unix time in seconds (injectable for tests) */
26
+ timestamp?: number;
27
+ /** Random nonce (injectable for tests) */
28
+ nonce?: string;
29
+ }
30
+ /**
31
+ * The `Authorization` header of the RRIoT API (Hawk-like signature).
32
+ * Format documented by python-roborock (Apache-2.0), `roborock/web_api/_hawk.py`.
33
+ *
34
+ * @param rriot The credentials from the login
35
+ * @param path The path of the request (without host or query string)
36
+ * @param options The params and form of the request
37
+ * @returns The header value
38
+ */
39
+ export declare function hawkAuthorization(rriot: RoborockRriot, path: string, options?: HawkOptions): string;
@@ -0,0 +1,48 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.hawkAuthorization = hawkAuthorization;
7
+ const node_crypto_1 = __importDefault(require("node:crypto"));
8
+ const md5 = (value) => node_crypto_1.default.createHash("md5").update(value).digest("hex");
9
+ /**
10
+ * @param values The params
11
+ * @returns The MD5 of the params sorted by key (`a=1&b=2`), or `""` if there are none
12
+ */
13
+ function hashParams(values) {
14
+ if (!values)
15
+ return "";
16
+ return md5(Object.keys(values)
17
+ .sort()
18
+ .map((key) => `${key}=${values[key]}`)
19
+ .join("&"));
20
+ }
21
+ /**
22
+ * The `Authorization` header of the RRIoT API (Hawk-like signature).
23
+ * Format documented by python-roborock (Apache-2.0), `roborock/web_api/_hawk.py`.
24
+ *
25
+ * @param rriot The credentials from the login
26
+ * @param path The path of the request (without host or query string)
27
+ * @param options The params and form of the request
28
+ * @returns The header value
29
+ */
30
+ function hawkAuthorization(rriot, path, options = {}) {
31
+ const timestamp = options.timestamp ?? Math.floor(Date.now() / 1000);
32
+ const nonce = options.nonce ?? node_crypto_1.default.randomBytes(6).toString("base64url");
33
+ const prestr = [
34
+ rriot.u,
35
+ rriot.s,
36
+ nonce,
37
+ String(timestamp),
38
+ md5(path),
39
+ hashParams(options.params),
40
+ hashParams(options.form),
41
+ ].join(":");
42
+ const mac = node_crypto_1.default
43
+ .createHmac("sha256", rriot.h)
44
+ .update(prestr)
45
+ .digest("base64");
46
+ return `Hawk id="${rriot.u}",s="${rriot.s}",ts="${timestamp}",nonce="${nonce}",mac="${mac}"`;
47
+ }
48
+ //# sourceMappingURL=hawk.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"hawk.js","sourceRoot":"","sources":["../../../src/lib/roborock/hawk.ts"],"names":[],"mappings":";;;;;AA2DA,8CAqBC;AAhFD,8DAAiC;AAsBjC,MAAM,GAAG,GAAG,CAAC,KAAa,EAAE,EAAE,CAC5B,qBAAM,CAAC,UAAU,CAAC,KAAK,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;AAEvD;;;GAGG;AACH,SAAS,UAAU,CAAC,MAA+B;IACjD,IAAI,CAAC,MAAM;QAAE,OAAO,EAAE,CAAC;IACvB,OAAO,GAAG,CACR,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC;SAChB,IAAI,EAAE;SACN,GAAG,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,GAAG,GAAG,IAAI,MAAM,CAAC,GAAG,CAAC,EAAE,CAAC;SACrC,IAAI,CAAC,GAAG,CAAC,CACb,CAAC;AACJ,CAAC;AAaD;;;;;;;;GAQG;AACH,SAAgB,iBAAiB,CAC/B,KAAoB,EACpB,IAAY,EACZ,UAAuB,EAAE;IAEzB,MAAM,SAAS,GAAG,OAAO,CAAC,SAAS,IAAI,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,GAAG,EAAE,GAAG,IAAI,CAAC,CAAC;IACrE,MAAM,KAAK,GAAG,OAAO,CAAC,KAAK,IAAI,qBAAM,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,WAAW,CAAC,CAAC;IAC3E,MAAM,MAAM,GAAG;QACb,KAAK,CAAC,CAAC;QACP,KAAK,CAAC,CAAC;QACP,KAAK;QACL,MAAM,CAAC,SAAS,CAAC;QACjB,GAAG,CAAC,IAAI,CAAC;QACT,UAAU,CAAC,OAAO,CAAC,MAAM,CAAC;QAC1B,UAAU,CAAC,OAAO,CAAC,IAAI,CAAC;KACzB,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;IACZ,MAAM,GAAG,GAAG,qBAAM;SACf,UAAU,CAAC,QAAQ,EAAE,KAAK,CAAC,CAAC,CAAC;SAC7B,MAAM,CAAC,MAAM,CAAC;SACd,MAAM,CAAC,QAAQ,CAAC,CAAC;IACpB,OAAO,YAAY,KAAK,CAAC,CAAC,QAAQ,KAAK,CAAC,CAAC,SAAS,SAAS,YAAY,KAAK,UAAU,GAAG,GAAG,CAAC;AAC/F,CAAC"}
@@ -0,0 +1,9 @@
1
+ export { RoborockLogin, RoborockWebApi, ROBOROCK_BASE_URLS, toDevices, type RoborockSession, type RoborockUserData, type RoborockHomeData, type RoborockHomeDevice, type RoborockProduct, type RoborockDevice, type RoborockWebApiOptions, } from "./web_api";
2
+ export { hawkAuthorization, type RoborockRriot } from "./hawk";
3
+ export { RoborockError, RoborockAuthError, RoborockSessionExpiredError, RoborockApiError, } from "./errors";
4
+ export { saveRoborockSession, loadRoborockSession, deleteRoborockSession, defaultRoborockSessionFile, } from "./session_store";
5
+ export { roborockDevice, roborockApiOf, RoborockDeviceApi, type RoborockDeviceOptions, } from "./device";
6
+ export { RoborockLocalConnection, ROBOROCK_LOCAL_PORT, type RoborockLocalConnectionOptions, } from "./local_connection";
7
+ export { roomNames, type RoborockRoom } from "./rooms";
8
+ export { RoborockMqttSession, RoborockMqttConnection, mqttParams, type MqttClientLike, type MqttConnect, type RoborockMqttSessionOptions, type RoborockMqttConnectionOptions, } from "./mqtt";
9
+ export { MapResponseAssembler, type MapResponse } from "./map_response";
@@ -0,0 +1,36 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.MapResponseAssembler = exports.mqttParams = exports.RoborockMqttConnection = exports.RoborockMqttSession = exports.roomNames = exports.ROBOROCK_LOCAL_PORT = exports.RoborockLocalConnection = exports.RoborockDeviceApi = exports.roborockApiOf = exports.roborockDevice = exports.defaultRoborockSessionFile = exports.deleteRoborockSession = exports.loadRoborockSession = exports.saveRoborockSession = exports.RoborockApiError = exports.RoborockSessionExpiredError = exports.RoborockAuthError = exports.RoborockError = exports.hawkAuthorization = exports.toDevices = exports.ROBOROCK_BASE_URLS = exports.RoborockWebApi = exports.RoborockLogin = void 0;
4
+ var web_api_1 = require("./web_api");
5
+ Object.defineProperty(exports, "RoborockLogin", { enumerable: true, get: function () { return web_api_1.RoborockLogin; } });
6
+ Object.defineProperty(exports, "RoborockWebApi", { enumerable: true, get: function () { return web_api_1.RoborockWebApi; } });
7
+ Object.defineProperty(exports, "ROBOROCK_BASE_URLS", { enumerable: true, get: function () { return web_api_1.ROBOROCK_BASE_URLS; } });
8
+ Object.defineProperty(exports, "toDevices", { enumerable: true, get: function () { return web_api_1.toDevices; } });
9
+ var hawk_1 = require("./hawk");
10
+ Object.defineProperty(exports, "hawkAuthorization", { enumerable: true, get: function () { return hawk_1.hawkAuthorization; } });
11
+ var errors_1 = require("./errors");
12
+ Object.defineProperty(exports, "RoborockError", { enumerable: true, get: function () { return errors_1.RoborockError; } });
13
+ Object.defineProperty(exports, "RoborockAuthError", { enumerable: true, get: function () { return errors_1.RoborockAuthError; } });
14
+ Object.defineProperty(exports, "RoborockSessionExpiredError", { enumerable: true, get: function () { return errors_1.RoborockSessionExpiredError; } });
15
+ Object.defineProperty(exports, "RoborockApiError", { enumerable: true, get: function () { return errors_1.RoborockApiError; } });
16
+ var session_store_1 = require("./session_store");
17
+ Object.defineProperty(exports, "saveRoborockSession", { enumerable: true, get: function () { return session_store_1.saveRoborockSession; } });
18
+ Object.defineProperty(exports, "loadRoborockSession", { enumerable: true, get: function () { return session_store_1.loadRoborockSession; } });
19
+ Object.defineProperty(exports, "deleteRoborockSession", { enumerable: true, get: function () { return session_store_1.deleteRoborockSession; } });
20
+ Object.defineProperty(exports, "defaultRoborockSessionFile", { enumerable: true, get: function () { return session_store_1.defaultRoborockSessionFile; } });
21
+ var device_1 = require("./device");
22
+ Object.defineProperty(exports, "roborockDevice", { enumerable: true, get: function () { return device_1.roborockDevice; } });
23
+ Object.defineProperty(exports, "roborockApiOf", { enumerable: true, get: function () { return device_1.roborockApiOf; } });
24
+ Object.defineProperty(exports, "RoborockDeviceApi", { enumerable: true, get: function () { return device_1.RoborockDeviceApi; } });
25
+ var local_connection_1 = require("./local_connection");
26
+ Object.defineProperty(exports, "RoborockLocalConnection", { enumerable: true, get: function () { return local_connection_1.RoborockLocalConnection; } });
27
+ Object.defineProperty(exports, "ROBOROCK_LOCAL_PORT", { enumerable: true, get: function () { return local_connection_1.ROBOROCK_LOCAL_PORT; } });
28
+ var rooms_1 = require("./rooms");
29
+ Object.defineProperty(exports, "roomNames", { enumerable: true, get: function () { return rooms_1.roomNames; } });
30
+ var mqtt_1 = require("./mqtt");
31
+ Object.defineProperty(exports, "RoborockMqttSession", { enumerable: true, get: function () { return mqtt_1.RoborockMqttSession; } });
32
+ Object.defineProperty(exports, "RoborockMqttConnection", { enumerable: true, get: function () { return mqtt_1.RoborockMqttConnection; } });
33
+ Object.defineProperty(exports, "mqttParams", { enumerable: true, get: function () { return mqtt_1.mqttParams; } });
34
+ var map_response_1 = require("./map_response");
35
+ Object.defineProperty(exports, "MapResponseAssembler", { enumerable: true, get: function () { return map_response_1.MapResponseAssembler; } });
36
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/lib/roborock/index.ts"],"names":[],"mappings":";;;AAAA,qCAYmB;AAXjB,wGAAA,aAAa,OAAA;AACb,yGAAA,cAAc,OAAA;AACd,6GAAA,kBAAkB,OAAA;AAClB,oGAAA,SAAS,OAAA;AASX,+BAA+D;AAAtD,yGAAA,iBAAiB,OAAA;AAC1B,mCAKkB;AAJhB,uGAAA,aAAa,OAAA;AACb,2GAAA,iBAAiB,OAAA;AACjB,qHAAA,2BAA2B,OAAA;AAC3B,0GAAA,gBAAgB,OAAA;AAElB,iDAKyB;AAJvB,oHAAA,mBAAmB,OAAA;AACnB,oHAAA,mBAAmB,OAAA;AACnB,sHAAA,qBAAqB,OAAA;AACrB,2HAAA,0BAA0B,OAAA;AAE5B,mCAKkB;AAJhB,wGAAA,cAAc,OAAA;AACd,uGAAA,aAAa,OAAA;AACb,2GAAA,iBAAiB,OAAA;AAGnB,uDAI4B;AAH1B,2HAAA,uBAAuB,OAAA;AACvB,uHAAA,mBAAmB,OAAA;AAGrB,iCAAuD;AAA9C,kGAAA,SAAS,OAAA;AAClB,+BAQgB;AAPd,2GAAA,mBAAmB,OAAA;AACnB,8GAAA,sBAAsB,OAAA;AACtB,kGAAA,UAAU,OAAA;AAMZ,+CAAwE;AAA/D,oHAAA,oBAAoB,OAAA"}
@@ -0,0 +1,72 @@
1
+ import { EventEmitter } from "node:events";
2
+ import { type MiioLogger } from "../logger";
3
+ import { type RoborockMessageVersion } from "./message";
4
+ /** The TCP port of the robots' local API */
5
+ export declare const ROBOROCK_LOCAL_PORT = 58867;
6
+ export interface RoborockLocalConnectionOptions {
7
+ /** The robot's IP address */
8
+ address: string;
9
+ /** The robot's local key (from the account's home data) */
10
+ localKey: string;
11
+ /** Default {@link ROBOROCK_LOCAL_PORT} */
12
+ port?: number;
13
+ /** Timeout of the connection and of each request (default 10s) */
14
+ timeoutMs?: number;
15
+ /**
16
+ * The local protocol version to try first. Robots speak `1.0` or `L01` locally, which may differ from the
17
+ * protocol version of the home data: both are tried, and the one that works is remembered.
18
+ */
19
+ protocolVersion?: RoborockMessageVersion;
20
+ logger?: MiioLogger;
21
+ }
22
+ /**
23
+ * A local connection to a Roborock robot, over TCP port 58867 (local protocols `1.0` and `L01`).
24
+ *
25
+ * Events: `message` (every message received, e.g. status pushes), `close`.
26
+ */
27
+ export declare class RoborockLocalConnection extends EventEmitter {
28
+ private readonly options;
29
+ private session?;
30
+ private readonly waiting;
31
+ private pingTimer?;
32
+ private connecting?;
33
+ private preferredVersion?;
34
+ private readonly debug;
35
+ private seq;
36
+ /** @returns The next message sequence number (the hello is 1) */
37
+ private nextSeq;
38
+ constructor(options: RoborockLocalConnectionOptions);
39
+ /** Whether the connection is open and the robot answered the hello */
40
+ get connected(): boolean;
41
+ /** The local protocol version the robot answered to (`undefined` until connected) */
42
+ get protocolVersion(): RoborockMessageVersion | undefined;
43
+ private get timeoutMs();
44
+ /**
45
+ * Connects (if not connected yet) and says hello to the robot.
46
+ */
47
+ connect(): Promise<void>;
48
+ private open;
49
+ private openSocket;
50
+ private startPing;
51
+ private onData;
52
+ private onClose;
53
+ /**
54
+ * Sends a message and waits for the first received message that matches.
55
+ *
56
+ * @param message The message to send
57
+ * @param matches Whether a received message is the response
58
+ * @param timeoutMs How long to wait for the response
59
+ * @returns The response
60
+ */
61
+ private request;
62
+ /**
63
+ * Calls a method on the robot (the same methods as miIO: `get_status`, `app_start`…).
64
+ *
65
+ * @param method The method
66
+ * @param params The params
67
+ * @returns The result
68
+ */
69
+ call<T = unknown>(method: string, params?: unknown): Promise<T>;
70
+ /** Closes the connection */
71
+ close(): void;
72
+ }
@@ -0,0 +1,232 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.RoborockLocalConnection = exports.ROBOROCK_LOCAL_PORT = void 0;
7
+ const node_crypto_1 = __importDefault(require("node:crypto"));
8
+ const node_events_1 = require("node:events");
9
+ const node_net_1 = __importDefault(require("node:net"));
10
+ const logger_1 = require("../logger");
11
+ const errors_1 = require("./errors");
12
+ const message_1 = require("./message");
13
+ /** The TCP port of the robots' local API */
14
+ exports.ROBOROCK_LOCAL_PORT = 58867;
15
+ const PING_INTERVAL_MS = 10_000;
16
+ /** How long to wait for the answer to a hello before trying the other protocol version */
17
+ const HELLO_TIMEOUT_MS = 4_000;
18
+ /** Unix time in seconds */
19
+ const now = () => Math.floor(Date.now() / 1000);
20
+ const randomInt = (min, max) => node_crypto_1.default.randomInt(min, max);
21
+ /**
22
+ * A local connection to a Roborock robot, over TCP port 58867 (local protocols `1.0` and `L01`).
23
+ *
24
+ * Events: `message` (every message received, e.g. status pushes), `close`.
25
+ */
26
+ class RoborockLocalConnection extends node_events_1.EventEmitter {
27
+ options;
28
+ session;
29
+ waiting = new Set();
30
+ pingTimer;
31
+ connecting;
32
+ preferredVersion;
33
+ debug;
34
+ seq = 1;
35
+ /** @returns The next message sequence number (the hello is 1) */
36
+ nextSeq() {
37
+ this.seq = this.seq >= 0x7fffffff ? 2 : this.seq + 1;
38
+ return this.seq;
39
+ }
40
+ constructor(options) {
41
+ super();
42
+ this.options = options;
43
+ this.preferredVersion = options.protocolVersion;
44
+ this.debug = (0, logger_1.createDebug)(`miio:roborock:local:${options.address}`, () => options.logger);
45
+ }
46
+ /** Whether the connection is open and the robot answered the hello */
47
+ get connected() {
48
+ return Boolean(this.session && !this.session.socket.destroyed && !this.connecting);
49
+ }
50
+ /** The local protocol version the robot answered to (`undefined` until connected) */
51
+ get protocolVersion() {
52
+ return this.session?.version ?? this.preferredVersion;
53
+ }
54
+ get timeoutMs() {
55
+ return this.options.timeoutMs ?? 10_000;
56
+ }
57
+ /**
58
+ * Connects (if not connected yet) and says hello to the robot.
59
+ */
60
+ async connect() {
61
+ if (this.connected)
62
+ return;
63
+ this.connecting ??= this.open().finally(() => {
64
+ this.connecting = undefined;
65
+ });
66
+ return this.connecting;
67
+ }
68
+ async open() {
69
+ const versions = this.preferredVersion === "L01" ? ["L01", "1.0"] : ["1.0", "L01"];
70
+ for (const version of versions) {
71
+ const socket = await this.openSocket();
72
+ const session = {
73
+ socket,
74
+ version,
75
+ nonces: { connectNonce: randomInt(10000, 32767) },
76
+ reader: new message_1.LengthPrefixedReader(),
77
+ };
78
+ this.seq = 1;
79
+ this.session = session;
80
+ socket.on("data", (chunk) => this.onData(session, chunk));
81
+ socket.on("error", (err) => this.debug(`Socket error: ${err.message}`));
82
+ socket.on("close", () => this.onClose(session));
83
+ try {
84
+ const response = await this.request({
85
+ version,
86
+ seq: 1,
87
+ random: session.nonces.connectNonce,
88
+ timestamp: now(),
89
+ protocol: message_1.RoborockProtocol.HELLO_REQUEST,
90
+ }, (m) => m.protocol === message_1.RoborockProtocol.HELLO_RESPONSE &&
91
+ m.version === version, Math.min(this.timeoutMs, HELLO_TIMEOUT_MS));
92
+ session.nonces.ackNonce = response.random;
93
+ this.preferredVersion = version;
94
+ this.debug(`Connected (local protocol ${version})`);
95
+ this.startPing();
96
+ return;
97
+ }
98
+ catch (err) {
99
+ this.debug(`No answer to the ${version} hello: ${err.message}`);
100
+ this.session = undefined;
101
+ socket.destroy();
102
+ }
103
+ }
104
+ throw new errors_1.RoborockError(`The robot at ${this.options.address} didn't answer the hello (local protocols 1.0 and L01)`);
105
+ }
106
+ openSocket() {
107
+ return new Promise((resolve, reject) => {
108
+ const s = node_net_1.default.connect({
109
+ host: this.options.address,
110
+ port: this.options.port ?? exports.ROBOROCK_LOCAL_PORT,
111
+ timeout: this.timeoutMs,
112
+ });
113
+ s.once("connect", () => {
114
+ s.setTimeout(0);
115
+ resolve(s);
116
+ });
117
+ s.once("timeout", () => {
118
+ s.destroy();
119
+ reject(new errors_1.RoborockError(`Couldn't connect to ${this.options.address}: timed out`));
120
+ });
121
+ s.once("error", (err) => reject(new errors_1.RoborockError(`Couldn't connect to ${this.options.address}: ${err.message}`)));
122
+ });
123
+ }
124
+ startPing() {
125
+ clearInterval(this.pingTimer);
126
+ this.pingTimer = setInterval(() => {
127
+ const version = this.session?.version;
128
+ if (!version)
129
+ return;
130
+ this.request({
131
+ version,
132
+ seq: this.nextSeq(),
133
+ random: randomInt(10000, 99999),
134
+ timestamp: now(),
135
+ protocol: message_1.RoborockProtocol.PING_REQUEST,
136
+ }, (m) => m.protocol === message_1.RoborockProtocol.PING_RESPONSE).catch((err) => {
137
+ this.debug(`Ping failed, closing: ${err.message}`);
138
+ this.close();
139
+ });
140
+ }, PING_INTERVAL_MS);
141
+ this.pingTimer.unref?.();
142
+ }
143
+ onData(session, chunk) {
144
+ for (const frame of session.reader.push(chunk)) {
145
+ let message;
146
+ try {
147
+ message = (0, message_1.decodeMessage)(frame, this.options.localKey, session.nonces);
148
+ }
149
+ catch (err) {
150
+ this.debug(`Ignoring a message: ${err.message}`);
151
+ continue;
152
+ }
153
+ for (const matcher of this.waiting) {
154
+ if (matcher(message))
155
+ this.waiting.delete(matcher);
156
+ }
157
+ this.emit("message", message);
158
+ }
159
+ }
160
+ onClose(session) {
161
+ if (this.session !== session)
162
+ return;
163
+ this.debug("Disconnected");
164
+ clearInterval(this.pingTimer);
165
+ this.session = undefined;
166
+ this.emit("close");
167
+ }
168
+ /**
169
+ * Sends a message and waits for the first received message that matches.
170
+ *
171
+ * @param message The message to send
172
+ * @param matches Whether a received message is the response
173
+ * @param timeoutMs How long to wait for the response
174
+ * @returns The response
175
+ */
176
+ request(message, matches, timeoutMs = this.timeoutMs) {
177
+ const session = this.session;
178
+ if (!session || session.socket.destroyed) {
179
+ return Promise.reject(new errors_1.RoborockError("Not connected"));
180
+ }
181
+ return new Promise((resolve, reject) => {
182
+ const matcher = (received) => {
183
+ if (!matches(received))
184
+ return false;
185
+ clearTimeout(timer);
186
+ resolve(received);
187
+ return true;
188
+ };
189
+ const timer = setTimeout(() => {
190
+ this.waiting.delete(matcher);
191
+ reject(new errors_1.RoborockError(`No response after ${timeoutMs} ms`));
192
+ }, timeoutMs);
193
+ this.waiting.add(matcher);
194
+ session.socket.write((0, message_1.withLengthPrefix)((0, message_1.encodeMessage)(message, this.options.localKey, session.nonces)));
195
+ });
196
+ }
197
+ /**
198
+ * Calls a method on the robot (the same methods as miIO: `get_status`, `app_start`…).
199
+ *
200
+ * @param method The method
201
+ * @param params The params
202
+ * @returns The result
203
+ */
204
+ async call(method, params = []) {
205
+ await this.connect();
206
+ const version = this.session?.version ?? "1.0";
207
+ const id = randomInt(10000, 32767);
208
+ const timestamp = now();
209
+ this.debug(`-> ${method} (${id})`, JSON.stringify(params));
210
+ const response = await this.request({
211
+ version,
212
+ seq: this.nextSeq(),
213
+ random: randomInt(10000, 99999),
214
+ timestamp,
215
+ protocol: message_1.RoborockProtocol.GENERAL_REQUEST,
216
+ payload: (0, message_1.rpcPayload)({ id, method, params }, timestamp),
217
+ }, (m) => (0, message_1.rpcResponse)(m)?.id === id);
218
+ // The matcher only accepts messages with an RPC response
219
+ const rpc = (0, message_1.rpcResponse)(response);
220
+ this.debug(`<- ${method} (${id})`, JSON.stringify(rpc.result ?? rpc.error));
221
+ return (0, message_1.rpcResult)(method, rpc);
222
+ }
223
+ /** Closes the connection */
224
+ close() {
225
+ clearInterval(this.pingTimer);
226
+ for (const matcher of this.waiting)
227
+ this.waiting.delete(matcher);
228
+ this.session?.socket.destroy();
229
+ }
230
+ }
231
+ exports.RoborockLocalConnection = RoborockLocalConnection;
232
+ //# sourceMappingURL=local_connection.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"local_connection.js","sourceRoot":"","sources":["../../../src/lib/roborock/local_connection.ts"],"names":[],"mappings":";;;;;;AAAA,8DAAiC;AACjC,6CAA2C;AAC3C,wDAA2B;AAE3B,sCAAyD;AAEzD,qCAAyC;AACzC,uCAYmB;AAEnB,4CAA4C;AAC/B,QAAA,mBAAmB,GAAG,KAAK,CAAC;AAEzC,MAAM,gBAAgB,GAAG,MAAM,CAAC;AAChC,0FAA0F;AAC1F,MAAM,gBAAgB,GAAG,KAAK,CAAC;AAmB/B,2BAA2B;AAC3B,MAAM,GAAG,GAAG,GAAG,EAAE,CAAC,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,GAAG,EAAE,GAAG,IAAI,CAAC,CAAC;AAChD,MAAM,SAAS,GAAG,CAAC,GAAW,EAAE,GAAW,EAAE,EAAE,CAAC,qBAAM,CAAC,SAAS,CAA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file (decrypted and decompressed) */
5
+ data: Buffer;
6
+ }
7
+ /**
8
+ * Collects the parts of the map responses and decodes them once complete.
9
+ */
10
+ export declare class MapResponseAssembler {
11
+ private readonly nonce;
12
+ private readonly endpoint;
13
+ private readonly pending;
14
+ /**
15
+ * @param endpoint The `endpoint` of the requests' security block
16
+ * @param nonce The `nonce` of the requests' security block (the AES key)
17
+ */
18
+ constructor(endpoint: string, nonce: Buffer);
19
+ /**
20
+ * @param message A received message
21
+ * @returns The map, once all its parts arrived (`undefined` otherwise, or for maps requested by someone else)
22
+ */
23
+ push(message: RoborockMessage): MapResponse | undefined;
24
+ private isFirstPart;
25
+ private decode;
26
+ }
@@ -0,0 +1,104 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.MapResponseAssembler = void 0;
7
+ /**
8
+ * The map responses of `get_map_v1` over MQTT (protocols 300/301).
9
+ *
10
+ * ```
11
+ * endpoint (8, ASCII) | ? (8) | request id u16 LE | ? (6) | AES-128-CBC(gzip(map file)), key = the request's nonce, IV = 0
12
+ * ```
13
+ *
14
+ * Large maps are split in several messages sharing `random` and `timestamp`, numbered by `seq`: all but the last are
15
+ * protocol 300, the last one 301; only the first part has the header. Parts may arrive out of order.
16
+ *
17
+ * Format documented by python-roborock (Apache-2.0), `roborock/protocols/v1_protocol.py`. No code is copied from it.
18
+ */
19
+ const node_crypto_1 = __importDefault(require("node:crypto"));
20
+ const node_zlib_1 = require("node:zlib");
21
+ const errors_1 = require("./errors");
22
+ const message_1 = require("./message");
23
+ const HEADER_LENGTH = 24;
24
+ /** Incomplete multi-part responses kept while waiting for their missing parts */
25
+ const MAX_PENDING = 4;
26
+ /**
27
+ * Collects the parts of the map responses and decodes them once complete.
28
+ */
29
+ class MapResponseAssembler {
30
+ nonce;
31
+ endpoint;
32
+ pending = new Map();
33
+ /**
34
+ * @param endpoint The `endpoint` of the requests' security block
35
+ * @param nonce The `nonce` of the requests' security block (the AES key)
36
+ */
37
+ constructor(endpoint, nonce) {
38
+ this.nonce = nonce;
39
+ this.endpoint = Buffer.from(endpoint, "latin1");
40
+ }
41
+ /**
42
+ * @param message A received message
43
+ * @returns The map, once all its parts arrived (`undefined` otherwise, or for maps requested by someone else)
44
+ */
45
+ push(message) {
46
+ if (message.protocol !== message_1.RoborockProtocol.MAP_RESPONSE &&
47
+ message.protocol !== message_1.RoborockProtocol.MAP_RESPONSE_PART) {
48
+ return undefined;
49
+ }
50
+ const payload = message.payload;
51
+ if (!payload?.length) {
52
+ throw new errors_1.RoborockError("Map response without payload");
53
+ }
54
+ const last = message.protocol === message_1.RoborockProtocol.MAP_RESPONSE;
55
+ const key = `${message.random}:${message.timestamp}`;
56
+ if (last && !this.pending.has(key) && this.isFirstPart(payload)) {
57
+ return this.decode(payload);
58
+ }
59
+ const parts = this.pending.get(key) ?? new Map();
60
+ this.pending.delete(key);
61
+ parts.set(message.seq, { last, payload });
62
+ const ordered = [...parts.entries()].sort(([a], [b]) => a - b);
63
+ const first = ordered[0];
64
+ const lastPart = ordered[ordered.length - 1];
65
+ const complete = lastPart[1].last &&
66
+ lastPart[0] - first[0] === ordered.length - 1 &&
67
+ this.isFirstPart(first[1].payload);
68
+ if (!complete) {
69
+ this.pending.set(key, parts);
70
+ while (this.pending.size > MAX_PENDING) {
71
+ this.pending.delete(this.pending.keys().next().value);
72
+ }
73
+ return undefined;
74
+ }
75
+ return this.decode(Buffer.concat(ordered.map(([, part]) => part.payload)));
76
+ }
77
+ isFirstPart(payload) {
78
+ return (payload.length >= this.endpoint.length &&
79
+ payload.subarray(0, this.endpoint.length).equals(this.endpoint));
80
+ }
81
+ decode(payload) {
82
+ if (payload.length < HEADER_LENGTH) {
83
+ throw new errors_1.RoborockError("Map response too short");
84
+ }
85
+ // Another client's map (same account): not ours
86
+ if (!this.isFirstPart(payload))
87
+ return undefined;
88
+ const requestId = payload.readUInt16LE(16);
89
+ let data;
90
+ try {
91
+ const decipher = node_crypto_1.default.createDecipheriv("aes-128-cbc", this.nonce, Buffer.alloc(16));
92
+ data = (0, node_zlib_1.gunzipSync)(Buffer.concat([
93
+ decipher.update(payload.subarray(HEADER_LENGTH)),
94
+ decipher.final(),
95
+ ]));
96
+ }
97
+ catch (err) {
98
+ throw new errors_1.RoborockError(`Couldn't decode the map: ${err.message}`);
99
+ }
100
+ return { requestId, data };
101
+ }
102
+ }
103
+ exports.MapResponseAssembler = MapResponseAssembler;
104
+ //# sourceMappingURL=map_response.js.map