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

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