From 74ebf2e947636024d7c443ca39730fcdc733544f Mon Sep 17 00:00:00 2001 From: Iamasoldier <1272745473@qq.com> Date: Fri, 11 Jul 2025 15:55:06 +0800 Subject: [PATCH] =?UTF-8?q?fix:=E6=9C=8D=E5=8A=A1=E5=95=86=E6=A8=A1?= =?UTF-8?q?=E5=BC=8F=E6=94=AF=E4=BB=98=E9=80=BB=E8=BE=91=E8=B0=83=E8=AF=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../controller/SysWechatConfigController.java | 21 +- .../wechat/feign/WechatConfigService.java | 2 +- .../WechatConfigServiceFallbackFactory.java | 2 +- .../main/frontend/WebSocket接口协议文档.md | 606 ++++++++++++++++++ .../src/main/frontend/config/proxy.ts | 32 +- 5 files changed, 633 insertions(+), 30 deletions(-) create mode 100644 zlt-web/react-web/src/main/frontend/WebSocket接口协议文档.md diff --git a/zlt-business/user-center/src/main/java/com/central/user/controller/SysWechatConfigController.java b/zlt-business/user-center/src/main/java/com/central/user/controller/SysWechatConfigController.java index 2f9457ca..f1dbfd9b 100644 --- a/zlt-business/user-center/src/main/java/com/central/user/controller/SysWechatConfigController.java +++ b/zlt-business/user-center/src/main/java/com/central/user/controller/SysWechatConfigController.java @@ -6,9 +6,6 @@ import com.central.common.model.Result; import com.central.user.service.WechatConfigService; import com.central.wechat.entity.WechatConfig; import io.swagger.v3.oas.annotations.Operation; -import io.swagger.v3.oas.annotations.Parameter; -import io.swagger.v3.oas.annotations.Parameters; -import io.swagger.v3.oas.annotations.enums.ParameterIn; import io.swagger.v3.oas.annotations.tags.Tag; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; @@ -43,10 +40,10 @@ public class SysWechatConfigController { } @Operation(summary = "根据类型和租户ID查询微信配置") - @GetMapping("/{type}") - public Result getConfig(@PathVariable String type, @RequestParam String tenantId) { + @GetMapping("/type/{type}") + public WechatConfig getConfig(@PathVariable String type, @RequestParam String tenantId) { WechatConfig config = wechatConfigService.getConfig(type, tenantId); - return Result.succeed(config); + return config; } @Operation(summary = "保存微信配置") @@ -74,23 +71,23 @@ public class SysWechatConfigController { @Operation(summary = "获取服务商配置") @GetMapping("/service/{tenantId}") - public Result getServiceConfig(@PathVariable String tenantId) { + public WechatConfig getServiceConfig(@PathVariable String tenantId) { WechatConfig config = wechatConfigService.getServiceConfig(tenantId); - return Result.succeed(config); + return config; } @Operation(summary = "根据子商户号查询配置") @GetMapping("/sub/{subMchId}") - public Result getConfigBySubMchId(@PathVariable String subMchId) { + public WechatConfig getConfigBySubMchId(@PathVariable String subMchId) { WechatConfig config = wechatConfigService.getConfigBySubMchId(subMchId); - return Result.succeed(config); + return config; } @Operation(summary = "获取指定服务商下的所有子商户配置") @GetMapping("/submerchants/{serviceMchId}") - public Result> getSubMerchantConfigs(@PathVariable String serviceMchId) { + public java.util.List getSubMerchantConfigs(@PathVariable String serviceMchId) { java.util.List configs = wechatConfigService.getSubMerchantConfigs(serviceMchId); - return Result.succeed(configs); + return configs; } @Operation(summary = "保存服务商配置") diff --git a/zlt-commons/zlt-wechat-common-core/src/main/java/com/central/wechat/feign/WechatConfigService.java b/zlt-commons/zlt-wechat-common-core/src/main/java/com/central/wechat/feign/WechatConfigService.java index ab921227..17ccb498 100644 --- a/zlt-commons/zlt-wechat-common-core/src/main/java/com/central/wechat/feign/WechatConfigService.java +++ b/zlt-commons/zlt-wechat-common-core/src/main/java/com/central/wechat/feign/WechatConfigService.java @@ -22,7 +22,7 @@ public interface WechatConfigService { * @param type * @return */ - @GetMapping(value = "/wechat/config/{type}") + @GetMapping(value = "/wechat/config/type/{type}") WechatConfig getConfig(@PathVariable("type") String type,@RequestParam("tenantId") String tenantId); @GetMapping(value = "/wechat/config/app/{id}") diff --git a/zlt-commons/zlt-wechat-common-core/src/main/java/com/central/wechat/feign/fallback/WechatConfigServiceFallbackFactory.java b/zlt-commons/zlt-wechat-common-core/src/main/java/com/central/wechat/feign/fallback/WechatConfigServiceFallbackFactory.java index 30f87b23..3e6db240 100644 --- a/zlt-commons/zlt-wechat-common-core/src/main/java/com/central/wechat/feign/fallback/WechatConfigServiceFallbackFactory.java +++ b/zlt-commons/zlt-wechat-common-core/src/main/java/com/central/wechat/feign/fallback/WechatConfigServiceFallbackFactory.java @@ -21,7 +21,7 @@ public class WechatConfigServiceFallbackFactory implements FallbackFactory { + const response = await fetch('/api-device/token/query?expires=3600'); + const data = await response.json(); + if (data.resp_code === 0) { + return data.data.result; + } + throw new Error('获取Token失败'); + } + + // 连接WebSocket + async connect(): Promise { + try { + this.token = await this.getToken(); + const wsUrl = `ws://119.45.169.13:8848/messaging/${this.token}`; + + this.ws = new WebSocket(wsUrl); + + this.ws.onopen = () => { + console.log('WebSocket连接已建立'); + this.startHeartbeat(); + this.subscribeToMessages(); + }; + + this.ws.onmessage = (event) => { + const data = JSON.parse(event.data); + this.handleMessage(data); + }; + + this.ws.onclose = () => { + console.log('WebSocket连接已关闭'); + this.scheduleReconnect(); + }; + + this.ws.onerror = (error) => { + console.error('WebSocket错误:', error); + }; + } catch (error) { + console.error('连接失败:', error); + this.scheduleReconnect(); + } + } + + // 发送消息 + sendMessage(message: any): void { + if (this.ws && this.ws.readyState === WebSocket.OPEN) { + this.ws.send(JSON.stringify(message)); + } + } + + // 订阅消息 + subscribeToMessages(): void { + const subscriptions = [ + { + type: 'sub', + topic: '/device/*/*/message/property/report', + id: `sub_property_${Date.now()}` + }, + { + type: 'sub', + topic: '/device/*/*/online', + id: `sub_online_${Date.now()}` + } + ]; + + subscriptions.forEach(sub => this.sendMessage(sub)); + } + + // 发送控制指令 + sendControlCommand(deviceSn: string, method: string, data: any = {}): void { + const message = { + type: 'sub', + topic: `/device-message-sender/D-Dock2/${deviceSn}`, + parameter: { + messageType: 'WRITE_PROPERTY', + properties: { method, data }, + headers: { async: false } + }, + id: `control_${method}_${deviceSn}_${Date.now()}` + }; + + this.sendMessage(message); + } + + // 心跳检测 + startHeartbeat(): void { + this.heartbeatTimer = setInterval(() => { + this.sendMessage({ + type: 'ping', + timestamp: Date.now() + }); + }, 30000); + } + + // 重连机制 + scheduleReconnect(): void { + if (this.reconnectTimer) { + clearTimeout(this.reconnectTimer); + } + + this.reconnectTimer = setTimeout(() => { + console.log('尝试重新连接...'); + this.connect(); + }, 5000); + } + + // 处理消息 + handleMessage(data: any): void { + switch (data.type) { + case 'result': + this.handleResultMessage(data); + break; + case 'pong': + console.log('收到心跳响应'); + break; + case 'error': + console.error('收到错误消息:', data.error); + break; + default: + console.log('收到未知消息:', data); + } + } + + // 处理结果消息 + handleResultMessage(data: any): void { + const { topic, payload } = data; + + if (topic.includes('/message/property/report')) { + console.log('设备属性上报:', payload); + } else if (topic.includes('/online')) { + console.log('设备上线:', payload); + } else if (topic.includes('/offline')) { + console.log('设备离线:', payload); + } + } + + // 关闭连接 + disconnect(): void { + if (this.heartbeatTimer) { + clearInterval(this.heartbeatTimer); + } + if (this.reconnectTimer) { + clearTimeout(this.reconnectTimer); + } + if (this.ws) { + this.ws.close(); + } + } +} + +// 使用示例 +const wsClient = new WebSocketClient(); +wsClient.connect(); + +// 发送控制指令 +wsClient.sendControlCommand('DEVICE001', 'stick_control', { + roll: 1024, + pitch: 1024, + throttle: 1024, + yaw: 1024 +}); + +// 页面卸载时关闭连接 +window.addEventListener('beforeunload', () => { + wsClient.disconnect(); +}); +``` + +## 注意事项 + +1. **Token管理**: Token有过期时间,需要定期刷新 +2. **连接稳定性**: 实现自动重连和心跳机制 +3. **消息处理**: 正确处理各种类型的消息 +4. **错误处理**: 完善的错误处理机制 +5. **资源清理**: 及时清理定时器和连接 +6. **安全性**: 确保Token的安全性,不要在客户端存储敏感信息 + +## 更新日志 + +- **v1.0.0**: 初始版本,包含基本的连接、订阅、控制功能 +- **v1.1.0**: 添加心跳机制和自动重连 +- **v1.2.0**: 完善错误处理和消息格式 +- **v1.3.0**: 添加设备状态监控和事件处理 \ No newline at end of file diff --git a/zlt-web/react-web/src/main/frontend/config/proxy.ts b/zlt-web/react-web/src/main/frontend/config/proxy.ts index 61b5280f..2b8d0a36 100644 --- a/zlt-web/react-web/src/main/frontend/config/proxy.ts +++ b/zlt-web/react-web/src/main/frontend/config/proxy.ts @@ -9,43 +9,43 @@ export default { dev: { '/api-uaa/': { - target: 'http://119.45.169.13:9900', - // target: 'http://127.0.0.1:9900', + // target: 'http://119.45.169.13:9900', + target: 'http://127.0.0.1:9900', changeOrigin: true, }, '/api-user/': { - target: 'http://119.45.169.13:9900', - // target: 'http://127.0.0.1:9900', + // target: 'http://119.45.169.13:9900', + target: 'http://127.0.0.1:9900', changeOrigin: true, }, '/api-log/': { - target: 'http://119.45.169.13:9900', - // target: 'http://127.0.0.1:9900', + // target: 'http://119.45.169.13:9900', + target: 'http://127.0.0.1:9900', changeOrigin: true, }, '/api-search/': { - target: 'http://119.45.169.13:9900', - // target: 'http://127.0.0.1:9900', + // target: 'http://119.45.169.13:9900', + target: 'http://127.0.0.1:9900', changeOrigin: true, }, '/api-generator/': { - target: 'http://119.45.169.13:9900', - // target: 'http://127.0.0.1:9900', + // target: 'http://119.45.169.13:9900', + target: 'http://127.0.0.1:9900', changeOrigin: true, }, '/api-file/': { - target: 'http://119.45.169.13:9900', - // target: 'http://127.0.0.1:9900', + // target: 'http://119.45.169.13:9900', + target: 'http://127.0.0.1:9900', changeOrigin: true, }, '/api-order/': { - target: 'http://119.45.169.13:9900', - // target: 'http://127.0.0.1:9900', + // target: 'http://119.45.169.13:9900', + target: 'http://127.0.0.1:9900', changeOrigin: true, }, '/api-device/': { - target: 'http://119.45.169.13:9900', - // target: 'http://127.0.0.1:9900', + // target: 'http://119.45.169.13:9900', + target: 'http://127.0.0.1:9900', changeOrigin: true, }, },