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

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 +55 -21
  6. package/lib/api/sweeperP2p.js +376 -246
  7. package/lib/constant.d.ts +0 -52
  8. package/lib/constant.js +0 -54
  9. package/lib/index.d.ts +12 -1
  10. package/lib/index.js +187 -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 +7 -18
  52. package/lib/utils/index.js +13 -15
  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,16 @@
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
+ enableCustomLog?: boolean | undefined;
7
+ onReceiveAIPicData?: ((data: string) => void) | undefined;
8
+ onReceiveAIPicHDData?: ((data: string) => void) | undefined;
9
+ onReceiveWifiMapData?: ((data: string) => void) | undefined;
10
+ onLogger?: TOnLogger | undefined;
11
+ onDefineStructuredMode?: ((isStructured: boolean) => void) | undefined;
12
+ } | undefined) => {
13
+ appendDownloadStreamDuringTask: (files: Array<string>, successCb?: () => void, failedCb?: () => void) => Promise<boolean> | void;
14
+ };
4
15
  declare const StreamDataNotificationCenter: import("mitt").Emitter<Record<import("mitt").EventType, unknown>>;
5
16
  export { StreamDataNotificationCenter, useP2PDataStream };
package/lib/index.js CHANGED
@@ -1,6 +1,191 @@
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 { SweeperP2pInstance } from './api';
6
+ import { trace } from './trace';
7
+ import { emitter, logger, logP2PDataIfEnabled } from './utils';
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
+ enableCustomLog = false,
16
+ onReceiveAIPicData,
17
+ onReceiveAIPicHDData,
18
+ onReceiveWifiMapData,
19
+ onLogger,
20
+ onDefineStructuredMode
21
+ } = opt || {};
22
+ SweeperP2pInstance.enableCustomLog = enableCustomLog;
23
+ logP2PDataIfEnabled(enableCustomLog, devId, 'hooks_init', `useP2PDataStream initialized, traceId: ${traceId}`);
24
+ const isInit = useRef(false);
25
+ const offSessionStatusChange = useRef(null);
26
+ const isAppOnBackground = useRef(false);
27
+ const timer = useRef(null);
28
+ const isIDE = getSystemInfoSync().brand === 'devtools';
29
+ const handleAppHide = useCallback(() => {
30
+ logger('info', {
31
+ msg: 'hooks onAppHide'
32
+ }, onLogger);
33
+ logP2PDataIfEnabled(enableCustomLog, devId, 'app_hide', 'Application hidden');
34
+ isAppOnBackground.current = true;
35
+ if (isInit.current) {
36
+ timer.current = setTimeout(() => {
37
+ logger('info', {
38
+ msg: `background timer has been exe,isAppOnBackground: ${isAppOnBackground.current}`
39
+ }, onLogger);
40
+ if (isAppOnBackground.current) {
41
+ logP2PDataIfEnabled(enableCustomLog, devId, 'background_timeout', 'Background timeout, unmounting P2P connection');
42
+ unmount();
43
+ }
44
+ clearTimeout(timer.current);
45
+ timer.current = null;
46
+ }, 10 * 1000);
47
+ }
48
+ }, []);
49
+ const handleAppShow = useCallback(() => {
50
+ logger('info', {
51
+ msg: 'hooks onAppShow'
52
+ }, onLogger);
53
+ logger('info', {
54
+ msg: `clear timer ${timer.current}`
55
+ }, onLogger);
56
+ logP2PDataIfEnabled(enableCustomLog, devId, 'app_show', 'Application shown');
57
+ isAppOnBackground.current = false;
58
+ timer.current && clearTimeout(timer.current);
59
+ setTimeout(() => {
60
+ var _ty$p2p$isP2PActiveSy, _ty$p2p, _ty$p2p$isP2PActiveSy2, _ty$p2p2;
61
+ logger('info', {
62
+ 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, {
63
+ deviceId: devId
64
+ })}`
65
+ }, onLogger);
66
+ if ((!isInit.current || !((_ty$p2p$isP2PActiveSy2 = (_ty$p2p2 = ty.p2p).isP2PActiveSync) !== null && _ty$p2p$isP2PActiveSy2 !== void 0 && _ty$p2p$isP2PActiveSy2.call(_ty$p2p2, {
67
+ deviceId: devId
68
+ }))) && !SweeperP2pInstance.isConnecting) {
69
+ logP2PDataIfEnabled(enableCustomLog, devId, 'app_show_reconnect', 'Reconnecting P2P after app show');
70
+ connectP2p();
71
+ }
72
+ }, 500);
73
+ }, []);
74
+ useEffect(() => {
75
+ if (logTag) {
76
+ log4js.setTag(logTag);
77
+ }
78
+ if (traceId) {
79
+ trace.traceId = traceId;
80
+ }
81
+ if (isIDE) {
82
+ logger('warn', {
83
+ msg: `You are using the IDE environment. To perform P2P and map debugging, please ensure the 'Robot Vacuum Debugger' plugin is installed.`
84
+ }, onLogger);
85
+ logP2PDataIfEnabled(enableCustomLog, devId, 'ide_mode', 'IDE environment detected, using mock P2P');
86
+ SweeperP2pInstance.onReceiveMapData = onReceiveMapData;
87
+ SweeperP2pInstance.onReceivePathData = onReceivePathData;
88
+ SweeperP2pInstance.onDefineStructuredMode = onDefineStructuredMode;
89
+ SweeperP2pInstance.registerP2pDownloadEvent();
90
+ SweeperP2pInstance.onLogger = onLogger;
91
+ return () => {
92
+ logP2PDataIfEnabled(enableCustomLog, devId, 'ide_mode_cleanup', 'Cleaning up IDE mode P2P events');
93
+ SweeperP2pInstance.removeP2pDownloadEvent();
94
+ };
95
+ }
96
+ if (devId.startsWith('vdevo')) {
97
+ logger('warn', {
98
+ msg: 'virtual device cannot use p2p'
99
+ }, onLogger);
100
+ logP2PDataIfEnabled(enableCustomLog, devId, 'virtual_device', 'Virtual device detected, P2P not available');
101
+ return;
102
+ }
103
+ SweeperP2pInstance.onLogger = onLogger;
104
+ logP2PDataIfEnabled(enableCustomLog, devId, 'init_p2p_sdk_start', 'Starting P2P SDK initialization');
105
+ SweeperP2pInstance.initP2pSdk(devId).then(() => {
106
+ logP2PDataIfEnabled(enableCustomLog, devId, 'init_p2p_sdk_success', 'P2P SDK initialized successfully');
107
+ connectP2p();
108
+ trace.pointFn({
109
+ devId,
110
+ eventName: 'initP2pSdk'
111
+ });
112
+ }).catch(e => {
113
+ logP2PDataIfEnabled(enableCustomLog, devId, 'init_p2p_sdk_fail', `P2P SDK initialization failed: ${(e === null || e === void 0 ? void 0 : e.message) || 'unknown error'}`);
114
+ trace.pointFn({
115
+ devId,
116
+ eventName: 'initP2pSdkFail'
117
+ });
118
+ });
119
+ ty.onAppHide(handleAppHide);
120
+ ty.onAppShow(handleAppShow);
121
+ }, []);
122
+ usePageEvent('onUnload', () => {
123
+ logP2PDataIfEnabled(enableCustomLog, devId, 'page_unload', 'Page unloading, cleaning up P2P connection');
124
+ unmount();
125
+ ty.offAppHide(handleAppHide);
126
+ ty.offAppShow(handleAppShow);
127
+ SweeperP2pInstance.deInitP2PSDK();
128
+ });
129
+
130
+ /**
131
+ * p2p连接
132
+ */
133
+ const connectP2p = async () => {
134
+ logger('info', {
135
+ msg: 'hooks has been started connectP2p'
136
+ }, onLogger);
137
+ logP2PDataIfEnabled(enableCustomLog, devId, 'connect_p2p_start', 'Starting P2P connection');
138
+ // 开始进行连接时作为整个p2p连接的开始,将trace的开始时间戳记录下来
139
+ trace.initTimeStamps = Date.now();
140
+ SweeperP2pInstance.connectDevice(() => {
141
+ logP2PDataIfEnabled(enableCustomLog, devId, 'connect_p2p_success', 'P2P connection established successfully');
142
+ trace.pointFn({
143
+ devId,
144
+ eventName: 'connectDeviceSuccess'
145
+ });
146
+ isInit.current = true;
147
+ logP2PDataIfEnabled(enableCustomLog, devId, 'start_observer_data', 'Starting to observe sweeper data by P2P');
148
+ SweeperP2pInstance.startObserverSweeperDataByP2P(1, devId, onReceiveMapData, onReceivePathData, onReceiveAIPicData, onReceiveAIPicHDData, onReceiveWifiMapData, onDefineStructuredMode);
149
+ offSessionStatusChange.current = SweeperP2pInstance.onSessionStatusChange(SweeperP2pInstance.sessionStatusCallback);
150
+ }, () => {
151
+ logP2PDataIfEnabled(enableCustomLog, devId, 'connect_p2p_fail', 'P2P connection failed, attempting reconnect');
152
+ trace.pointFn({
153
+ devId,
154
+ eventName: 'connectDeviceFail'
155
+ });
156
+ SweeperP2pInstance.reconnectP2p(() => {
157
+ logP2PDataIfEnabled(enableCustomLog, devId, 'reconnect_p2p_success', 'P2P reconnected successfully');
158
+ isInit.current = true;
159
+ trace.pointFn({
160
+ devId,
161
+ eventName: 'reconnectP2p'
162
+ });
163
+ logP2PDataIfEnabled(enableCustomLog, devId, 'start_observer_data_after_reconnect', 'Starting to observe sweeper data after reconnect');
164
+ SweeperP2pInstance.startObserverSweeperDataByP2P(1, devId, onReceiveMapData, onReceivePathData, onReceiveAIPicData, onReceiveAIPicHDData, onReceiveWifiMapData);
165
+ // 这里失败重连需要注册断开重连的事件
166
+ offSessionStatusChange.current = SweeperP2pInstance.onSessionStatusChange(SweeperP2pInstance.sessionStatusCallback);
167
+ }, '');
168
+ });
169
+ };
170
+
171
+ /**
172
+ * p2p断开
173
+ */
174
+ const unmount = () => {
175
+ logger('info', {
176
+ msg: 'hooks has been started unmount'
177
+ }, onLogger);
178
+ logP2PDataIfEnabled(enableCustomLog, devId, 'unmount_p2p', 'Unmounting P2P connection');
179
+ isInit.current = false;
180
+ SweeperP2pInstance.stopObserverSweeperDataByP2P();
181
+ if (offSessionStatusChange.current) {
182
+ offSessionStatusChange.current();
183
+ offSessionStatusChange.current = null;
184
+ }
185
+ };
186
+ return {
187
+ appendDownloadStreamDuringTask: SweeperP2pInstance.appendDownloadStreamDuringTask
188
+ };
189
+ };
5
190
  const StreamDataNotificationCenter = emitter;
6
191
  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
+ }