@ray-js/robot-data-stream 0.0.13-beta-5 → 0.0.13-beta-7

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 (58) hide show
  1. package/lib/api/index.d.ts +12 -2
  2. package/lib/api/index.js +172 -1
  3. package/lib/api/p2pApi.d.ts +27 -8
  4. package/lib/api/p2pApi.js +169 -271
  5. package/lib/api/sweeperP2p.d.ts +23 -49
  6. package/lib/api/sweeperP2p.js +248 -311
  7. package/lib/constant.d.ts +52 -0
  8. package/lib/constant.js +54 -0
  9. package/lib/index.d.ts +1 -10
  10. package/lib/index.js +2 -165
  11. package/lib/mqtt/createCommonOptions.d.ts +56 -15
  12. package/lib/mqtt/createCommonOptions.js +44 -8
  13. package/lib/mqtt/index.d.ts +2 -1
  14. package/lib/mqtt/index.js +2 -1
  15. package/lib/mqtt/mqttProvider.d.ts +23 -15
  16. package/lib/mqtt/mqttProvider.js +63 -26
  17. package/lib/mqtt/promise.js +8 -3
  18. package/lib/mqtt/type/index.d.ts +14 -0
  19. package/lib/mqtt/type/index.js +14 -0
  20. package/lib/mqtt/type/requestType.d.ts +8 -0
  21. package/lib/mqtt/type/requestType.js +10 -0
  22. package/lib/mqtt/useDevInfo.d.ts +2 -7
  23. package/lib/mqtt/useDevInfo.js +25 -9
  24. package/lib/mqtt/useHistoryMap.d.ts +13 -21
  25. package/lib/mqtt/useHistoryMap.js +82 -32
  26. package/lib/mqtt/usePartDivision.d.ts +5 -7
  27. package/lib/mqtt/usePartDivision.js +41 -16
  28. package/lib/mqtt/usePartMerge.d.ts +5 -7
  29. package/lib/mqtt/usePartMerge.js +36 -18
  30. package/lib/mqtt/usePassword.js +59 -28
  31. package/lib/mqtt/useQuiteHours.d.ts +9 -24
  32. package/lib/mqtt/useQuiteHours.js +95 -52
  33. package/lib/mqtt/useResetMap.d.ts +10 -7
  34. package/lib/mqtt/useResetMap.js +40 -11
  35. package/lib/mqtt/useRoomProperty.js +23 -16
  36. package/lib/mqtt/useSchedule.d.ts +17 -4
  37. package/lib/mqtt/useSchedule.js +101 -49
  38. package/lib/mqtt/useSelectRoomClean.d.ts +20 -16
  39. package/lib/mqtt/useSelectRoomClean.js +145 -49
  40. package/lib/mqtt/useSpotClean.d.ts +3 -3
  41. package/lib/mqtt/useSpotClean.js +72 -50
  42. package/lib/mqtt/useVirtualArea.d.ts +6 -9
  43. package/lib/mqtt/useVirtualArea.js +112 -42
  44. package/lib/mqtt/useVirtualWall.d.ts +13 -10
  45. package/lib/mqtt/useVirtualWall.js +97 -34
  46. package/lib/mqtt/useVoice.d.ts +3 -6
  47. package/lib/mqtt/useVoice.js +73 -33
  48. package/lib/mqtt/useWifiMap.d.ts +8 -0
  49. package/lib/mqtt/useWifiMap.js +53 -0
  50. package/lib/mqtt/useZoneClean.d.ts +13 -13
  51. package/lib/mqtt/useZoneClean.js +149 -76
  52. package/lib/ttt/index.d.ts +153 -0
  53. package/lib/ttt/index.js +458 -0
  54. package/lib/utils/index.d.ts +20 -1
  55. package/lib/utils/index.js +19 -0
  56. package/package.json +1 -1
  57. package/lib/mqtt/myError.d.ts +0 -4
  58. package/lib/mqtt/myError.js +0 -6
package/lib/constant.d.ts CHANGED
@@ -1,3 +1,55 @@
1
1
  export declare const SUCTION_MAP: Record<string, number>;
2
2
  export declare const CISTERN_MAP: Record<string, number>;
3
3
  export declare const CLEAN_MODE_MAP: Record<string, number>;
4
+ export declare enum FileNameEnum {
5
+ map = "map.bin",
6
+ mapStructured = "map_structured.bin",
7
+ cleanPath = "cleanPath.bin",
8
+ mapStream = "map.bin.stream",
9
+ mapStructuredStream = "map_structured.bin.stream",
10
+ cleanPathStream = "cleanPath.bin.stream",
11
+ ai = "ai.bin",
12
+ aiStream = "ai.bin.stream",
13
+ aiHD = "aiHD_XXXX_YYYY.bin",
14
+ aiHDStream = "aiHD_XXXX_YYYY.bin.stream",
15
+ wifiMap = "wifi_map.bin",
16
+ wifiMapStream = "wifi_map.bin.stream"
17
+ }
18
+ export declare const FILE_NAME_MAP: {
19
+ readonly "map.bin": {
20
+ readonly type: 0;
21
+ };
22
+ readonly "map_structured.bin": {
23
+ readonly type: 6;
24
+ };
25
+ readonly "cleanPath.bin": {
26
+ readonly type: 1;
27
+ };
28
+ readonly "map.bin.stream": {
29
+ readonly type: 0;
30
+ };
31
+ readonly "map_structured.bin.stream": {
32
+ readonly type: 6;
33
+ };
34
+ readonly "cleanPath.bin.stream": {
35
+ readonly type: 1;
36
+ };
37
+ readonly "ai.bin": {
38
+ readonly type: 4;
39
+ };
40
+ readonly "ai.bin.stream": {
41
+ readonly type: 4;
42
+ };
43
+ readonly "aiHD_XXXX_YYYY.bin": {
44
+ readonly type: 5;
45
+ };
46
+ readonly "aiHD_XXXX_YYYY.bin.stream": {
47
+ readonly type: 5;
48
+ };
49
+ readonly "wifi_map.bin": {
50
+ readonly type: 7;
51
+ };
52
+ readonly "wifi_map.bin.stream": {
53
+ readonly type: 7;
54
+ };
55
+ };
package/lib/constant.js CHANGED
@@ -1,3 +1,4 @@
1
+ import "core-js/modules/esnext.iterator.map.js";
1
2
  // 吸力
2
3
  export const SUCTION_MAP = {
3
4
  closed: 0,
@@ -26,4 +27,57 @@ export const CLEAN_MODE_MAP = {
26
27
  // 先扫后拖
27
28
  clean_before_mop: 3,
28
29
  sweep_after_mop: 3
30
+ };
31
+ export let FileNameEnum = /*#__PURE__*/function (FileNameEnum) {
32
+ FileNameEnum["map"] = "map.bin";
33
+ FileNameEnum["mapStructured"] = "map_structured.bin";
34
+ FileNameEnum["cleanPath"] = "cleanPath.bin";
35
+ FileNameEnum["mapStream"] = "map.bin.stream";
36
+ FileNameEnum["mapStructuredStream"] = "map_structured.bin.stream";
37
+ FileNameEnum["cleanPathStream"] = "cleanPath.bin.stream";
38
+ FileNameEnum["ai"] = "ai.bin";
39
+ FileNameEnum["aiStream"] = "ai.bin.stream";
40
+ FileNameEnum["aiHD"] = "aiHD_XXXX_YYYY.bin";
41
+ FileNameEnum["aiHDStream"] = "aiHD_XXXX_YYYY.bin.stream";
42
+ FileNameEnum["wifiMap"] = "wifi_map.bin";
43
+ FileNameEnum["wifiMapStream"] = "wifi_map.bin.stream";
44
+ return FileNameEnum;
45
+ }({});
46
+ export const FILE_NAME_MAP = {
47
+ [FileNameEnum.map]: {
48
+ type: 0
49
+ },
50
+ [FileNameEnum.mapStructured]: {
51
+ type: 6
52
+ },
53
+ [FileNameEnum.cleanPath]: {
54
+ type: 1
55
+ },
56
+ [FileNameEnum.mapStream]: {
57
+ type: 0
58
+ },
59
+ [FileNameEnum.mapStructuredStream]: {
60
+ type: 6
61
+ },
62
+ [FileNameEnum.cleanPathStream]: {
63
+ type: 1
64
+ },
65
+ [FileNameEnum.ai]: {
66
+ type: 4
67
+ },
68
+ [FileNameEnum.aiStream]: {
69
+ type: 4
70
+ },
71
+ [FileNameEnum.aiHD]: {
72
+ type: 5
73
+ },
74
+ [FileNameEnum.aiHDStream]: {
75
+ type: 5
76
+ },
77
+ [FileNameEnum.wifiMap]: {
78
+ type: 7
79
+ },
80
+ [FileNameEnum.wifiMapStream]: {
81
+ type: 7
82
+ }
29
83
  };
package/lib/index.d.ts CHANGED
@@ -1,14 +1,5 @@
1
+ import { useP2PDataStream } from './api';
1
2
  export * from './mqtt';
2
3
  export * from './mqtt/type/requestType';
3
- type TOnLogger = (type: 'warn' | 'error' | 'info', data: string) => void;
4
- declare const useP2PDataStream: (devId: string, onReceiveMapData: (data: string) => void, onReceivePathData: (data: string) => void, opt?: {
5
- logTag?: string | undefined;
6
- onReceiveAIPicData?: ((data: string) => void) | undefined;
7
- onReceiveAIPicHDData?: ((data: string) => void) | undefined;
8
- onLogger?: TOnLogger | undefined;
9
- onDefineStructuredMode?: ((isStructured: boolean) => void) | undefined;
10
- } | undefined) => {
11
- appendDownloadStreamDuringTask: (files: Array<string>, successCb?: () => void, failedCb?: () => void) => Promise<boolean> | void;
12
- };
13
4
  declare const StreamDataNotificationCenter: import("mitt").Emitter<Record<import("mitt").EventType, unknown>>;
14
5
  export { StreamDataNotificationCenter, useP2PDataStream };
package/lib/index.js CHANGED
@@ -1,169 +1,6 @@
1
- /* eslint-disable consistent-return */
2
- import log4js from '@ray-js/log4js';
3
- import { getSystemInfoSync, usePageEvent } from '@ray-js/ray';
4
- import { useCallback, useEffect, useRef } from 'react';
5
- import { trace } from './trace';
6
- import { emitter, logger } from './utils';
7
- import { SweeperP2pInstance } from './api';
1
+ import { useP2PDataStream } from './api';
2
+ import { emitter } from './utils';
8
3
  export * from './mqtt';
9
4
  export * from './mqtt/type/requestType';
10
- const useP2PDataStream = (devId, onReceiveMapData, onReceivePathData, opt) => {
11
- const traceId = `${devId}_${Date.now()}`;
12
- global.robotPanelTraceId = traceId;
13
- const {
14
- logTag,
15
- onReceiveAIPicData,
16
- onReceiveAIPicHDData,
17
- onLogger,
18
- onDefineStructuredMode
19
- } = opt || {};
20
- const isInit = useRef(false);
21
- const offSessionStatusChange = useRef(null);
22
- const isAppOnBackground = useRef(false);
23
- const timer = useRef(null);
24
- const isIDE = getSystemInfoSync().brand === 'devtools';
25
- const handleAppHide = useCallback(() => {
26
- logger('info', {
27
- msg: 'hooks onAppHide'
28
- }, onLogger);
29
- isAppOnBackground.current = true;
30
- if (isInit.current) {
31
- timer.current = setTimeout(() => {
32
- logger('info', {
33
- msg: `background timer has been exe,isAppOnBackground: ${isAppOnBackground.current}`
34
- }, onLogger);
35
- if (isAppOnBackground.current) {
36
- unmount();
37
- }
38
- clearTimeout(timer.current);
39
- timer.current = null;
40
- }, 10 * 1000);
41
- }
42
- }, []);
43
- const handleAppShow = useCallback(() => {
44
- logger('info', {
45
- msg: 'hooks onAppShow'
46
- }, onLogger);
47
- logger('info', {
48
- msg: `clear timer ${timer.current}`
49
- }, onLogger);
50
- isAppOnBackground.current = false;
51
- timer.current && clearTimeout(timer.current);
52
- setTimeout(() => {
53
- var _ty$p2p$isP2PActiveSy, _ty$p2p, _ty$p2p$isP2PActiveSy2, _ty$p2p2;
54
- logger('info', {
55
- msg: `hooks onAppShow and after 500ms : ${isInit.current} isP2PActiveSync: ${(_ty$p2p$isP2PActiveSy = (_ty$p2p = ty.p2p).isP2PActiveSync) === null || _ty$p2p$isP2PActiveSy === void 0 ? void 0 : _ty$p2p$isP2PActiveSy.call(_ty$p2p, {
56
- deviceId: devId
57
- })}`
58
- }, onLogger);
59
- if ((!isInit.current || !((_ty$p2p$isP2PActiveSy2 = (_ty$p2p2 = ty.p2p).isP2PActiveSync) !== null && _ty$p2p$isP2PActiveSy2 !== void 0 && _ty$p2p$isP2PActiveSy2.call(_ty$p2p2, {
60
- deviceId: devId
61
- }))) && !SweeperP2pInstance.isConnecting) {
62
- connectP2p();
63
- }
64
- }, 500);
65
- }, []);
66
- useEffect(() => {
67
- if (logTag) {
68
- log4js.setTag(logTag);
69
- }
70
- if (traceId) {
71
- trace.traceId = traceId;
72
- }
73
- if (isIDE) {
74
- logger('warn', {
75
- msg: `You are using the IDE environment. To perform P2P and map debugging, please ensure the 'Robot Vacuum Debugger' plugin is installed.`
76
- }, onLogger);
77
- SweeperP2pInstance.onReceiveMapData = onReceiveMapData;
78
- SweeperP2pInstance.onReceivePathData = onReceivePathData;
79
- SweeperP2pInstance.onDefineStructuredMode = onDefineStructuredMode;
80
- SweeperP2pInstance.registerP2pDownloadEvent();
81
- SweeperP2pInstance.onLogger = onLogger;
82
- return () => {
83
- SweeperP2pInstance.removeP2pDownloadEvent();
84
- };
85
- }
86
- if (devId.startsWith('vdevo')) {
87
- logger('warn', {
88
- msg: 'virtual device cannot use p2p'
89
- }, onLogger);
90
- return;
91
- }
92
- SweeperP2pInstance.onLogger = onLogger;
93
- SweeperP2pInstance.initP2pSdk(devId).then(() => {
94
- connectP2p();
95
- trace.pointFn({
96
- devId,
97
- eventName: 'initP2pSdk'
98
- });
99
- }).catch(() => {
100
- trace.pointFn({
101
- devId,
102
- eventName: 'initP2pSdkFail'
103
- });
104
- });
105
- ty.onAppHide(handleAppHide);
106
- ty.onAppShow(handleAppShow);
107
- }, []);
108
- usePageEvent('onUnload', () => {
109
- unmount();
110
- ty.offAppHide(handleAppHide);
111
- ty.offAppShow(handleAppShow);
112
- SweeperP2pInstance.deInitP2PSDK();
113
- });
114
-
115
- /**
116
- * p2p连接
117
- */
118
- const connectP2p = async () => {
119
- logger('info', {
120
- msg: 'hooks has been started connectP2p'
121
- }, onLogger);
122
- // 开始进行连接时作为整个p2p连接的开始,将trace的开始时间戳记录下来
123
- trace.initTimeStamps = Date.now();
124
- SweeperP2pInstance.connectDevice(() => {
125
- trace.pointFn({
126
- devId,
127
- eventName: 'connectDeviceSuccess'
128
- });
129
- isInit.current = true;
130
- SweeperP2pInstance.startObserverSweeperDataByP2P(1, devId, onReceiveMapData, onReceivePathData, onReceiveAIPicData, onReceiveAIPicHDData, onDefineStructuredMode);
131
- offSessionStatusChange.current = SweeperP2pInstance.onSessionStatusChange(SweeperP2pInstance.sessionStatusCallback);
132
- }, () => {
133
- trace.pointFn({
134
- devId,
135
- eventName: 'connectDeviceFail'
136
- });
137
- SweeperP2pInstance.reconnectP2p(() => {
138
- isInit.current = true;
139
- trace.pointFn({
140
- devId,
141
- eventName: 'reconnectP2p'
142
- });
143
- SweeperP2pInstance.startObserverSweeperDataByP2P(1, devId, onReceiveMapData, onReceivePathData, onReceiveAIPicData, onReceiveAIPicHDData);
144
- // 这里失败重连需要注册断开重连的事件
145
- offSessionStatusChange.current = SweeperP2pInstance.onSessionStatusChange(SweeperP2pInstance.sessionStatusCallback);
146
- }, '');
147
- });
148
- };
149
-
150
- /**
151
- * p2p断开
152
- */
153
- const unmount = () => {
154
- logger('info', {
155
- msg: 'hooks has been started unmount'
156
- }, onLogger);
157
- isInit.current = false;
158
- SweeperP2pInstance.stopObserverSweeperDataByP2P();
159
- if (offSessionStatusChange.current) {
160
- offSessionStatusChange.current();
161
- offSessionStatusChange.current = null;
162
- }
163
- };
164
- return {
165
- appendDownloadStreamDuringTask: SweeperP2pInstance.appendDownloadStreamDuringTask
166
- };
167
- };
168
5
  const StreamDataNotificationCenter = emitter;
169
6
  export { StreamDataNotificationCenter, useP2PDataStream };
@@ -1,24 +1,65 @@
1
- interface Message {
2
- [key: string]: string | number | string[] | number[] | any;
1
+ import { ProtocolEnum } from './type';
2
+ /**
3
+ * MQTT 消息体类型
4
+ */
5
+ export interface MqttMessage {
6
+ reqType: string;
7
+ version: string;
8
+ taskId: string;
9
+ [key: string]: string | number | string[] | number[] | boolean | null | undefined;
3
10
  }
4
- interface Options {
11
+ /**
12
+ * MQTT 选项类型
13
+ */
14
+ export interface MqttOptions {
5
15
  [key: string]: string;
6
16
  }
7
- export declare enum ProtocolEnum {
8
- appToRobot = 64,
9
- robotToApp = 65
10
- }
11
- interface Params {
17
+ /**
18
+ * 创建通用参数的输入参数
19
+ */
20
+ export interface CreateSetCommonParamsInput {
21
+ /** 设备ID */
12
22
  deviceId: string;
23
+ /** 请求类型 */
13
24
  reqType: string;
14
- message?: Message;
25
+ /** 消息体(可选) */
26
+ message?: Partial<MqttMessage>;
27
+ /** 版本号(可选,默认为 1.0.0) */
15
28
  version?: string;
16
- options?: Options;
29
+ /** 选项(可选) */
30
+ options?: MqttOptions;
17
31
  }
18
- export declare const createSetCommonParams: ({ deviceId, reqType, message, version, options, }: Params) => {
32
+ /**
33
+ * 创建通用参数的返回类型
34
+ */
35
+ export interface CreateSetCommonParamsOutput {
36
+ /** 设备ID */
19
37
  deviceId: string;
20
- message: Message;
21
- options: Options;
38
+ /** 消息体 */
39
+ message: MqttMessage;
40
+ /** 选项 */
41
+ options: MqttOptions;
42
+ /** 协议号 */
22
43
  protocol: ProtocolEnum;
23
- };
24
- export {};
44
+ }
45
+ /**
46
+ * 创建 MQTT 通用参数
47
+ *
48
+ * @param params - 参数对象
49
+ * @param params.deviceId - 设备ID
50
+ * @param params.reqType - 请求类型
51
+ * @param params.message - 消息体(可选)
52
+ * @param params.version - 版本号(可选,默认为 1.0.0)
53
+ * @param params.options - 选项(可选)
54
+ * @returns MQTT 通用参数对象
55
+ *
56
+ * @example
57
+ * ```ts
58
+ * const params = createSetCommonParams({
59
+ * deviceId: 'device123',
60
+ * reqType: 'devInfoQry',
61
+ * message: { customField: 'value' }
62
+ * });
63
+ * ```
64
+ */
65
+ export declare const createSetCommonParams: ({ deviceId, reqType, message, version, options, }: CreateSetCommonParamsInput) => CreateSetCommonParamsOutput;
@@ -1,17 +1,53 @@
1
1
  import _objectSpread from "@babel/runtime/helpers/esm/objectSpread2";
2
- const defaultVersion = '1.0.0';
3
- // mqtt协议号
4
- export let ProtocolEnum = /*#__PURE__*/function (ProtocolEnum) {
5
- ProtocolEnum[ProtocolEnum["appToRobot"] = 64] = "appToRobot";
6
- ProtocolEnum[ProtocolEnum["robotToApp"] = 65] = "robotToApp";
7
- return ProtocolEnum;
8
- }({});
2
+ import { ProtocolEnum } from './type';
3
+
4
+ /**
5
+ * MQTT 消息默认版本号
6
+ */
7
+ const DEFAULT_VERSION = '1.0.0';
8
+
9
+ /**
10
+ * MQTT 消息体类型
11
+ */
12
+
13
+ /**
14
+ * MQTT 选项类型
15
+ */
16
+
17
+ /**
18
+ * 创建通用参数的输入参数
19
+ */
20
+
21
+ /**
22
+ * 创建通用参数的返回类型
23
+ */
24
+
25
+ /**
26
+ * 创建 MQTT 通用参数
27
+ *
28
+ * @param params - 参数对象
29
+ * @param params.deviceId - 设备ID
30
+ * @param params.reqType - 请求类型
31
+ * @param params.message - 消息体(可选)
32
+ * @param params.version - 版本号(可选,默认为 1.0.0)
33
+ * @param params.options - 选项(可选)
34
+ * @returns MQTT 通用参数对象
35
+ *
36
+ * @example
37
+ * ```ts
38
+ * const params = createSetCommonParams({
39
+ * deviceId: 'device123',
40
+ * reqType: 'devInfoQry',
41
+ * message: { customField: 'value' }
42
+ * });
43
+ * ```
44
+ */
9
45
  export const createSetCommonParams = _ref => {
10
46
  let {
11
47
  deviceId,
12
48
  reqType,
13
49
  message = {},
14
- version = defaultVersion,
50
+ version = DEFAULT_VERSION,
15
51
  options = {}
16
52
  } = _ref;
17
53
  const taskId = Date.now();
@@ -3,6 +3,7 @@ import { useDevInfo } from './useDevInfo';
3
3
  import { usePartDivision } from './usePartDivision';
4
4
  import { usePartMerge } from './usePartMerge';
5
5
  import { usePassword } from './usePassword';
6
+ import { useWifiMap } from './useWifiMap';
6
7
  import { useQuiteHours } from './useQuiteHours';
7
8
  import { useVirtualArea } from './useVirtualArea';
8
9
  import { useSpotClean } from './useSpotClean';
@@ -14,4 +15,4 @@ import { useHistoryMap } from './useHistoryMap';
14
15
  import { useVoice } from './useVoice';
15
16
  import { useRoomProperty } from './useRoomProperty';
16
17
  import { useResetMap } from './useResetMap';
17
- export { useVoice, MqttProvider, useDevInfo, usePartMerge, usePartDivision, usePassword, useQuiteHours, useVirtualArea, useSpotClean, useZoneClean, useSelectRoomClean, useVirtualWall, useSchedule, useHistoryMap, useRoomProperty, useResetMap, };
18
+ export { useVoice, MqttProvider, useDevInfo, usePartMerge, usePartDivision, usePassword, useWifiMap, useQuiteHours, useVirtualArea, useSpotClean, useZoneClean, useSelectRoomClean, useVirtualWall, useSchedule, useHistoryMap, useRoomProperty, useResetMap, };
package/lib/mqtt/index.js CHANGED
@@ -3,6 +3,7 @@ import { useDevInfo } from './useDevInfo';
3
3
  import { usePartDivision } from './usePartDivision';
4
4
  import { usePartMerge } from './usePartMerge';
5
5
  import { usePassword } from './usePassword';
6
+ import { useWifiMap } from './useWifiMap';
6
7
  import { useQuiteHours } from './useQuiteHours';
7
8
  import { useVirtualArea } from './useVirtualArea';
8
9
  import { useSpotClean } from './useSpotClean';
@@ -14,4 +15,4 @@ import { useHistoryMap } from './useHistoryMap';
14
15
  import { useVoice } from './useVoice';
15
16
  import { useRoomProperty } from './useRoomProperty';
16
17
  import { useResetMap } from './useResetMap';
17
- export { useVoice, MqttProvider, useDevInfo, usePartMerge, usePartDivision, usePassword, useQuiteHours, useVirtualArea, useSpotClean, useZoneClean, useSelectRoomClean, useVirtualWall, useSchedule, useHistoryMap, useRoomProperty, useResetMap };
18
+ export { useVoice, MqttProvider, useDevInfo, usePartMerge, usePartDivision, usePassword, useWifiMap, useQuiteHours, useVirtualArea, useSpotClean, useZoneClean, useSelectRoomClean, useVirtualWall, useSchedule, useHistoryMap, useRoomProperty, useResetMap };
@@ -1,21 +1,29 @@
1
1
  import React from 'react';
2
- export declare const SingletonContext: React.Context<{
2
+ export interface MqttContextValue {
3
3
  useMqtt: boolean;
4
4
  commandVersion: '0' | '1';
5
5
  devices: {
6
- common: any;
6
+ common: {
7
+ getDevInfo: () => {
8
+ devId: string;
9
+ };
10
+ model: {
11
+ props?: any;
12
+ actions: {
13
+ [dpCode: string]: {
14
+ set: (command: string) => void;
15
+ };
16
+ };
17
+ };
18
+ };
7
19
  };
8
- }>;
9
- export declare function useMqtt(): {
20
+ }
21
+ export declare const SingletonContext: React.Context<MqttContextValue | null>;
22
+ export interface MqttProviderProps {
23
+ children: React.ReactNode;
10
24
  useMqtt: boolean;
11
- commandVersion: "0" | "1";
12
- devices: {
13
- common: any;
14
- };
15
- };
16
- export declare function MqttProvider({ children, useMqtt, commandVersion, devices }: {
17
- children: any;
18
- useMqtt: any;
19
- commandVersion: any;
20
- devices: any;
21
- }): React.JSX.Element;
25
+ commandVersion: '0' | '1';
26
+ devices: MqttContextValue['devices'];
27
+ }
28
+ export declare function useMqtt(): MqttContextValue;
29
+ export declare function MqttProvider({ children, useMqtt, commandVersion, devices }: MqttProviderProps): React.JSX.Element;
@@ -1,11 +1,18 @@
1
1
  import _objectSpread from "@babel/runtime/helpers/esm/objectSpread2";
2
2
  import { get, isNil } from 'lodash-es';
3
- import React, { createContext, useCallback, useContext, useRef, useState } from 'react';
3
+ import React, { createContext, useCallback, useContext, useEffect, useMemo, useRef } from 'react';
4
4
  import { emitter } from '../utils';
5
+ import { ProtocolEnum } from './type';
6
+
7
+ // Context 类型定义
5
8
 
6
9
  // 创建一个Context
7
10
  export const SingletonContext = /*#__PURE__*/createContext(null);
8
11
 
12
+ // MqttProvider Props 类型定义
13
+
14
+ // MQTT 消息数据类型
15
+
9
16
  // 创建一个自定义Hook来使用这个Context
10
17
  export function useMqtt() {
11
18
  const context = useContext(SingletonContext);
@@ -21,50 +28,80 @@ export function MqttProvider(_ref) {
21
28
  commandVersion,
22
29
  devices
23
30
  } = _ref;
24
- const [instance, setInstance] = useState(null);
31
+ // 使用 useMemo 创建实例,确保只在依赖项变化时重新创建
32
+ const instance = useMemo(() => ({
33
+ useMqtt,
34
+ commandVersion,
35
+ devices
36
+ }), [useMqtt, commandVersion, devices]);
37
+
38
+ // 使用 ref 存储设备 ID 和初始化状态,避免重复初始化
39
+ const devIdRef = useRef(null);
40
+ const isInitializedRef = useRef(false);
41
+
42
+ // MQTT 消息处理回调
25
43
  const onMqttMessageReceived = useCallback(data => {
44
+ var _messageData$errCode;
26
45
  const {
27
46
  messageData
28
47
  } = data || {};
29
48
  const reqType = get(messageData, 'reqType', '');
30
49
  if (!reqType) return;
31
- if (reqType) {
32
- console.log('mqtt message received:', reqType, messageData);
33
- emitter.emit(reqType, isNil(messageData === null || messageData === void 0 ? void 0 : messageData.success) ? _objectSpread(_objectSpread({}, messageData), {}, {
34
- success: true
35
- }) : messageData);
36
- }
50
+
51
+ // 确保消息数据包含 success errCode 字段
52
+ // errCode: 0 表示成功,非 0 表示失败
53
+ // success: true 表示成功,false 表示失败
54
+ const errCode = (_messageData$errCode = messageData === null || messageData === void 0 ? void 0 : messageData.errCode) !== null && _messageData$errCode !== void 0 ? _messageData$errCode : (messageData === null || messageData === void 0 ? void 0 : messageData.success) === false ? -1 : 0;
55
+ const success = isNil(messageData === null || messageData === void 0 ? void 0 : messageData.success) ? errCode === 0 : messageData.success;
56
+ const responseData = _objectSpread(_objectSpread({}, messageData), {}, {
57
+ success,
58
+ errCode
59
+ });
60
+ emitter.emit(reqType, responseData);
37
61
  }, []);
38
62
 
39
- // 使用ref确保实例只被创建一次
40
- const instanceRef = useRef(null);
41
- if (instanceRef.current === null) {
42
- const {
43
- devId
44
- } = devices.common.getDevInfo();
63
+ // 初始化 MQTT 监听器(只执行一次)
64
+ useEffect(() => {
65
+ // 防止重复初始化
66
+ if (isInitializedRef.current) return;
67
+
68
+ // 获取设备 ID
69
+ try {
70
+ const devInfo = devices.common.getDevInfo();
71
+ devIdRef.current = devInfo.devId;
72
+ } catch (error) {
73
+ console.error('Failed to get device info:', error);
74
+ return;
75
+ }
76
+ const devId = devIdRef.current;
77
+ if (!devId) {
78
+ console.error('Device ID is not available');
79
+ return;
80
+ }
81
+
82
+ // 注册 MQTT 协议监听器
45
83
  ty.device.registerMQTTProtocolListener({
46
- protocol: 65,
84
+ protocol: ProtocolEnum.robotToApp,
47
85
  success: () => {
48
86
  console.log('注册mqtt成功');
87
+ },
88
+ fail: error => {
89
+ console.error('注册mqtt失败:', error);
49
90
  }
50
91
  });
92
+
93
+ // 注册 MQTT 消息接收监听器
51
94
  ty.device.onMqttMessageReceived(data => {
52
95
  if (data.deviceId === devId) {
53
96
  onMqttMessageReceived(data);
54
97
  }
55
98
  });
56
- instanceRef.current = {
57
- // 是否走mqtt64/65通道
58
- useMqtt,
59
- // 指令协议版本(1byte or 4bytes)
60
- commandVersion,
61
- // sdm
62
- devices
63
- };
64
- setInstance(instanceRef.current);
65
- }
66
99
 
67
- // 将单例状态和行为作为value传递给消费组件
100
+ // 标记为已初始化
101
+ isInitializedRef.current = true;
102
+ }, [devices, onMqttMessageReceived]);
103
+
104
+ // 将实例作为 value 传递给消费组件
68
105
  return /*#__PURE__*/React.createElement(SingletonContext.Provider, {
69
106
  value: instance
70
107
  }, children);
@@ -13,7 +13,7 @@ class MyError extends Error {
13
13
  }
14
14
  }
15
15
 
16
- // 2. 定义 Message 类型
16
+ // 2. 定义 Message 类型(兼容 MQTT 响应格式)
17
17
 
18
18
  // 3. 定义 PromiseWithRejection 类型
19
19
 
@@ -28,15 +28,20 @@ export function normalResolve(reqType, taskId) {
28
28
  }));
29
29
  }, 10 * 1000);
30
30
  const handle = message => {
31
+ var _message$errCode;
32
+ // 通过 taskId 匹配响应
31
33
  if (`${message.taskId}` !== `${taskId}`) {
32
34
  return;
33
35
  }
34
36
  clearTimeout(timer);
35
- if (message.errCode === 0) {
37
+
38
+ // 优先使用 errCode,如果没有则使用 success 字段判断
39
+ const errCode = (_message$errCode = message.errCode) !== null && _message$errCode !== void 0 ? _message$errCode : message.success === false ? -1 : 0;
40
+ if (errCode === 0) {
36
41
  resolve(message);
37
42
  } else {
38
43
  reject(new MyError('Request failed', {
39
- errCode: message.errCode,
44
+ errCode,
40
45
  reqType
41
46
  }));
42
47
  }