From fb5e9fe2a093de3630d212ee4582867f0110feb2 Mon Sep 17 00:00:00 2001 From: rahulpscraftech360 Date: Sat, 23 Aug 2025 13:10:15 +0530 Subject: [PATCH 1/3] started on frmware and ota --- main/FIRMWARE_DICTIONARY_SETUP.md | 92 ++++++++ main/manager-mobile/README.md | 222 +++++++++--------- .../src/components/AddDeviceDialog.vue | 16 +- .../src/components/AddWisdomBodyDialog.vue | 14 +- .../src/components/ManualAddDeviceDialog.vue | 34 +-- main/manager-web/src/router/index.js | 2 +- .../src/views/DeviceManagement.vue | 87 +++---- .../providers/tools/device_mcp/mcp_handler.py | 60 ++++- 8 files changed, 337 insertions(+), 190 deletions(-) create mode 100644 main/FIRMWARE_DICTIONARY_SETUP.md diff --git a/main/FIRMWARE_DICTIONARY_SETUP.md b/main/FIRMWARE_DICTIONARY_SETUP.md new file mode 100644 index 000000000..0be24028e --- /dev/null +++ b/main/FIRMWARE_DICTIONARY_SETUP.md @@ -0,0 +1,92 @@ +# Firmware Dictionary Setup Guide + +## Adding Firmware Types to Dictionary Management + +To properly display firmware information for your devices, you need to add the following dictionary entries in the web dashboard: + +### Step 1: Access Dictionary Management +1. Login to your web dashboard +2. Navigate to **Dictionary Management** section + +### Step 2: Find or Create FIRMWARE_TYPE Dictionary Type +1. Look for "FIRMWARE_TYPE" in the left panel +2. If it doesn't exist, click "Add Dictionary Type" and create: + - Dictionary Type Name: `Firmware Type` + - Dictionary Type Code: `FIRMWARE_TYPE` + +### Step 3: Add Device Model Entries +Click on FIRMWARE_TYPE and add the following dictionary data entries: + +#### Entry 1: DOIT AI Kit +- **Dictionary Label**: `DOIT AI-01 Kit` +- **Dictionary Value**: `doit-ai-01-kit` +- **Sort**: `1` + +#### Entry 2: ESP32 Generic +- **Dictionary Label**: `ESP32 Generic` +- **Dictionary Value**: `esp32-generic` +- **Sort**: `2` + +#### Entry 3: ESP32-S3 DevKit +- **Dictionary Label**: `ESP32-S3 DevKit` +- **Dictionary Value**: `esp32s3-devkit` +- **Sort**: `3` + +#### Entry 4: XIAO ESP32S3 +- **Dictionary Label**: `XIAO ESP32S3` +- **Dictionary Value**: `xiao-esp32s3` +- **Sort**: `4` + +#### Entry 5: M5Stack Core +- **Dictionary Label**: `M5Stack Core` +- **Dictionary Value**: `m5stack-core` +- **Sort**: `5` + +## Current Device Information from Logs + +Your connected device is reporting: +- **Device Name**: doit-ai-01-kit +- **Firmware Version**: 1.7.6 +- **Protocol Version**: 2024-11-05 +- **MAC Address**: 68:25:DD:BB:4D:44 + +## Firmware Management Display + +After adding these dictionary entries, the Firmware Management and Device Management pages will properly display: +- Device model names (instead of raw codes) +- Firmware versions +- Device capabilities + +## Verification Steps + +1. After adding dictionary entries, go to **Device Management** +2. You should see "DOIT AI-01 Kit" instead of "doit-ai-01-kit" +3. The firmware version "1.7.6" should be displayed in the table +4. In **Firmware Management**, you can now add OTA updates for these device types + +## Backend Integration + +The system is already configured to: +1. Log firmware details when devices connect via MCP protocol +2. Store firmware version in the database (appVersion field) +3. Display firmware info in Device Management table + +The enhanced logging shows: +``` +============================================================ +DEVICE CONNECTED - Firmware Details: + Device Name: doit-ai-01-kit + Firmware Version: 1.7.6 + Protocol Version: 2024-11-05 + Device ID: 68_25_dd_bb_4d_44 + MAC Address: 68:25:DD:BB:4D:44 + Capabilities: ['tools'] +============================================================ +``` + +## Next Steps + +1. Add the dictionary entries as described above +2. Verify device display in Device Management +3. Upload firmware files in Firmware Management for OTA updates +4. Configure auto-update settings per device if needed \ No newline at end of file diff --git a/main/manager-mobile/README.md b/main/manager-mobile/README.md index 3a4f33a38..2b7e7fef2 100644 --- a/main/manager-mobile/README.md +++ b/main/manager-mobile/README.md @@ -1,51 +1,51 @@ -## 智控台移动版(manager-mobile) -基于 uni-app v3 + Vue 3 + Vite 的跨端移动管理端,支持 App(Android & iOS)和微信小程序。 +## Smart Control Panel Mobile (manager-mobile) +Cross-platform mobile management application based on uni-app v3 + Vue 3 + Vite, supporting App (Android & iOS) and WeChat Mini Program. -### 平台兼容性 +### Platform Compatibility -| H5 | iOS | Android | 微信小程序 | -| -- | --- | ------- | ---------- | -| √ | √ | √ | √ | +| H5 | iOS | Android | WeChat Mini Program | +| -- | --- | ------- | ------------------- | +| √ | √ | √ | √ | -提示:不同 UI 组件在不同平台的适配度略有差异,请以对应组件库文档为准。 +Note: Different UI components may have slight compatibility differences across platforms. Please refer to the respective component library documentation. -### 开发环境要求 +### Development Environment Requirements - Node >= 18 -- pnpm >= 7.30(建议使用项目中声明的 `pnpm@10.x`) -- 可选:HBuilderX(App 调试/打包)、微信开发者工具(微信小程序) +- pnpm >= 7.30 (recommended to use `pnpm@10.x` as declared in the project) +- Optional: HBuilderX (for App debugging/packaging), WeChat Developer Tools (for WeChat Mini Program) -### 快速开始 -1) 配置环境变量 - - 复制 `env/.env.example` 为 `env/.env.development` - - 根据实际情况修改配置项(特别是 `VITE_SERVER_BASEURL`、`VITE_UNI_APPID`、`VITE_WX_APPID`) +### Quick Start +1) Configure environment variables + - Copy `env/.env.example` to `env/.env.development` + - Modify configuration items according to your needs (especially `VITE_SERVER_BASEURL`, `VITE_UNI_APPID`, `VITE_WX_APPID`) -2) 安装依赖 +2) Install dependencies ```bash pnpm i ``` -3) 本地开发(热更新) -- h5: `pnpm dev:h5`,然后观察启动日志显示的ip端口号 -- 微信小程序:`pnpm dev:mp` 或 `pnpm dev:mp-weixin`,然后用微信开发者工具导入 `dist/dev/mp-weixin` -- App:用 HBuilderX 导入 `manager-mobile`,然后参考下面的教程就能运行了 +3) Local development (hot reload) +- H5: `pnpm dev:h5`, then check the IP and port displayed in the startup logs +- WeChat Mini Program: `pnpm dev:mp` or `pnpm dev:mp-weixin`, then import `dist/dev/mp-weixin` in WeChat Developer Tools +- App: Import `manager-mobile` in HBuilderX, then follow the tutorial below to run -### 环境变量与配置 -项目使用自定义 `env` 目录存放环境文件,按 Vite 规范命名:`.env.development`、`.env.production` 等。 +### Environment Variables and Configuration +The project uses a custom `env` directory for environment files, named according to Vite conventions: `.env.development`, `.env.production`, etc. -关键变量(部分): -- VITE_APP_TITLE:应用名称(写入 `manifest.config.ts`) -- VITE_UNI_APPID:uni-app 应用 appid(App) -- VITE_WX_APPID:微信小程序 appid(mp-weixin) -- VITE_FALLBACK_LOCALE:默认语言,如 `zh-Hans` -- VITE_SERVER_BASEURL:服务端基础地址(HTTP 请求 baseURL) -- VITE_DELETE_CONSOLE:构建时是否移除 console(`true`/`false`) -- VITE_SHOW_SOURCEMAP:是否生成 sourcemap(默认关闭) -- VITE_LOGIN_URL:未登录跳转的登录页路径(路由拦截器使用) +Key variables (partial): +- VITE_APP_TITLE: Application name (written to `manifest.config.ts`) +- VITE_UNI_APPID: uni-app application appid (App) +- VITE_WX_APPID: WeChat Mini Program appid (mp-weixin) +- VITE_FALLBACK_LOCALE: Default language, e.g., `zh-Hans` +- VITE_SERVER_BASEURL: Server base URL (HTTP request baseURL) +- VITE_DELETE_CONSOLE: Whether to remove console during build (`true`/`false`) +- VITE_SHOW_SOURCEMAP: Whether to generate sourcemap (disabled by default) +- VITE_LOGIN_URL: Login page path for redirect when not logged in (used by route interceptor) -示例(`env/.env.development`): +Example (`env/.env.development`): ```env -VITE_APP_TITLE=小智 +VITE_APP_TITLE=XiaoZhi VITE_FALLBACK_LOCALE=zh-Hans VITE_UNI_APPID= VITE_WX_APPID= @@ -57,114 +57,114 @@ VITE_SHOW_SOURCEMAP=false VITE_LOGIN_URL=/pages/login/index ``` -说明: -- `manifest.config.ts` 会从 `env` 读取标题、appid、语言等配置。 +Note: +- `manifest.config.ts` reads title, appid, language and other configurations from `env`. -### 重要注意事项 -⚠️ **部署前必须修改的配置项:** +### Important Notes +⚠️ **Configuration items that must be modified before deployment:** -1. **应用 ID 配置** - - `VITE_UNI_APPID`:需要在 [DCloud 开发者中心](https://dev.dcloud.net.cn/) 创建应用并获取 AppID - - `VITE_WX_APPID`:需要在 [微信公众平台](https://mp.weixin.qq.com/) 注册小程序并获取 AppID +1. **Application ID Configuration** + - `VITE_UNI_APPID`: Need to create an application in [DCloud Developer Center](https://dev.dcloud.net.cn/) and obtain AppID + - `VITE_WX_APPID`: Need to register a Mini Program in [WeChat Public Platform](https://mp.weixin.qq.com/) and obtain AppID -2. **服务端地址** - - `VITE_SERVER_BASEURL`:修改为您的实际服务端地址 +2. **Server Address** + - `VITE_SERVER_BASEURL`: Modify to your actual server address -3. **应用信息** - - `VITE_APP_TITLE`:修改为您的应用名称 - - 更新 `src/static/logo.png` 等图标资源 +3. **Application Information** + - `VITE_APP_TITLE`: Modify to your application name + - Update icon resources like `src/static/logo.png` -4. **其他配置** - - 检查 `manifest.config.ts` 中的应用配置信息 - - 根据需要修改 `src/layouts/fg-tabbar/tabbarList.ts` 中的 tabbar 配置 +4. **Other Configurations** + - Check application configuration in `manifest.config.ts` + - Modify tabbar configuration in `src/layouts/fg-tabbar/tabbarList.ts` as needed -### 详细操作指南 +### Detailed Operation Guide -#### 1. 获取 uni-app AppID -![生成AppID](../../docs/images/manager-mobile/生成appid.png) -- 复制生成的 AppID 到环境变量 `VITE_UNI_APPID` 中 +#### 1. Get uni-app AppID +![Generate AppID](../../docs/images/manager-mobile/生成appid.png) +- Copy the generated AppID to environment variable `VITE_UNI_APPID` -#### 2. 本地运行步骤 -![本地运行](../../docs/images/manager-mobile/本地运行.png) +#### 2. Local Run Steps +![Local Run](../../docs/images/manager-mobile/本地运行.png) -**App 本地调试:** -1. 用 HBuilderX 导入 `manager-mobile` 目录 -2. 重新识别项目 -3. 连接手机或使用模拟器进行真机调试 +**App Local Debugging:** +1. Import `manager-mobile` directory in HBuilderX +2. Re-identify the project +3. Connect phone or use emulator for real device debugging -**项目识别问题解决:** -![重新识别项目](../../docs/images/manager-mobile/重新识别项目.png) +**Project Recognition Issue Resolution:** +![Re-identify Project](../../docs/images/manager-mobile/重新识别项目.png) -如果 HBuilderX 无法正确识别项目类型: -- 在项目根目录右键选择"重新识别项目类型" -- 确保项目被识别为 "uni-app" 项目 +If HBuilderX cannot correctly identify the project type: +- Right-click in project root directory and select "Re-identify Project Type" +- Ensure the project is recognized as a "uni-app" project -### 路由与鉴权 -- 在 `src/main.ts` 中注册了路由拦截插件 `routeInterceptor`。 -- 黑名单拦截:仅对配置为需要登录的页面进行校验(来源 `@/utils` 的 `getNeedLoginPages`)。 -- 登录判断:基于用户信息(`pinia` 的 `useUserStore`),未登录将跳转到 `VITE_LOGIN_URL`,并附带重定向回原页面的参数。 +### Routing and Authentication +- Route interceptor plugin `routeInterceptor` is registered in `src/main.ts`. +- Blacklist interception: Only validates pages configured as requiring login (from `getNeedLoginPages` in `@/utils`). +- Login check: Based on user information (`useUserStore` from `pinia`), redirects to `VITE_LOGIN_URL` when not logged in, with redirect parameter to return to original page. -### 网络请求 -- 基于 `alova` + `@alova/adapter-uniapp`,统一在 `src/http/request/alova.ts` 创建实例。 -- `baseURL` 读取环境配置(`getEnvBaseUrl`),可通过 `method.config.meta.domain` 动态切换域名。 -- 认证:默认从本地 `token`(`uni.getStorageSync('token')`)注入 `Authorization` 头,缺失则重定向登录。 -- 响应:统一处理 `statusCode !== 200` 的 HTTP 错误与业务 `code !== 0` 的错误;`401` 会清除 token 并跳转登录。 +### Network Requests +- Based on `alova` + `@alova/adapter-uniapp`, instance created uniformly in `src/http/request/alova.ts`. +- `baseURL` reads environment configuration (`getEnvBaseUrl`), can dynamically switch domains via `method.config.meta.domain`. +- Authentication: Defaults to injecting `Authorization` header from local `token` (`uni.getStorageSync('token')`), redirects to login if missing. +- Response: Unified handling of HTTP errors with `statusCode !== 200` and business errors with `code !== 0`; `401` clears token and redirects to login. -### 构建与发布 +### Build and Release -**微信小程序:** -1. 确保已配置正确的 `VITE_WX_APPID` -2. 运行 `pnpm build:mp`,产物在 `dist/build/mp-weixin` -3. 用微信开发者工具导入项目目录,并上传代码 -4. 在微信公众平台提交审核 +**WeChat Mini Program:** +1. Ensure correct `VITE_WX_APPID` is configured +2. Run `pnpm build:mp`, output in `dist/build/mp-weixin` +3. Import project directory in WeChat Developer Tools and upload code +4. Submit for review in WeChat Public Platform -**Android & iOS App:** +**Android & iOS App:** -#### 3. App 打包发行步骤 +#### 3. App Packaging and Release Steps -**步骤一:准备打包** -![打包发行步骤1](../../docs/images/manager-mobile/打包发行步骤1.png) +**Step 1: Prepare for Packaging** +![Packaging Release Step 1](../../docs/images/manager-mobile/打包发行步骤1.png) -1. 确保已配置正确的 `VITE_UNI_APPID` -2. 运行 `pnpm build:app`,产物在 `dist/build/app` -3. 用 HBuilderX 导入项目目录 -4. 在 HBuilderX 中点击"发行" → "原生App-云打包" +1. Ensure correct `VITE_UNI_APPID` is configured +2. Run `pnpm build:app`, output in `dist/build/app` +3. Import project directory in HBuilderX +4. Click "Release" → "Native App-Cloud Packaging" in HBuilderX -**步骤二:配置打包参数** -![打包发行步骤2](../../docs/images/manager-mobile/打包发行步骤2.png) +**Step 2: Configure Packaging Parameters** +![Packaging Release Step 2](../../docs/images/manager-mobile/打包发行步骤2.png) -1. **应用图标和启动图**:上传应用图标和启动页面图片 -2. **应用版本号**:设置版本号和版本名称 -3. **签名证书**: - - Android:上传 keystore 证书文件 - - iOS:配置开发者证书和描述文件 -4. **包名配置**:设置应用的包名(Bundle ID) -5. **打包类型**:选择测试包或正式包 -6. 点击"打包"开始云打包流程 +1. **App Icon and Launch Screen**: Upload app icon and launch screen images +2. **App Version Number**: Set version number and version name +3. **Signing Certificate**: + - Android: Upload keystore certificate file + - iOS: Configure developer certificate and provisioning profile +4. **Package Name Configuration**: Set app package name (Bundle ID) +5. **Package Type**: Choose test package or release package +6. Click "Package" to start cloud packaging process -**发布到应用商店:** -- **Android**:将生成的 APK 文件上传到各大 Android 应用市场 -- **iOS**:将生成的 IPA 文件通过 App Store Connect 上传到 App Store(需要 Apple 开发者账号) +**Publish to App Stores:** +- **Android**: Upload generated APK file to various Android app markets +- **iOS**: Upload generated IPA file to App Store via App Store Connect (requires Apple Developer account) -### 约定与工程化 -- 页面与分包:由 `@uni-helper/vite-plugin-uni-pages` 与 `pages.config.ts` 统一生成;tabbar 配置在 `src/layouts/fg-tabbar/tabbarList.ts`。 -- 组件与 hooks 自动导入:见 `vite.config.ts` 中 `unplugin-auto-import` 与 `@uni-helper/vite-plugin-uni-components`。 -- 样式:使用 UnoCSS 与 `src/style/index.scss`。 -- 状态管理:`pinia` + `pinia-plugin-persistedstate`。 -- 代码规范:内置 `eslint`、`husky`、`lint-staged`,提交前自动格式化(`lint-staged`)。 +### Conventions and Engineering +- Pages and subpackages: Generated uniformly by `@uni-helper/vite-plugin-uni-pages` and `pages.config.ts`; tabbar configuration in `src/layouts/fg-tabbar/tabbarList.ts`. +- Auto-import of components and hooks: See `unplugin-auto-import` and `@uni-helper/vite-plugin-uni-components` in `vite.config.ts`. +- Styling: Uses UnoCSS and `src/style/index.scss`. +- State management: `pinia` + `pinia-plugin-persistedstate`. +- Code standards: Built-in `eslint`, `husky`, `lint-staged`, auto-format before commit (`lint-staged`). -### 常用脚本 +### Common Scripts ```bash -# 开发 -pnpm dev:mp # 等价 dev:mp-weixin +# Development +pnpm dev:mp # Equivalent to dev:mp-weixin -# 构建 -pnpm build:mp # 等价 build:mp-weixin +# Build +pnpm build:mp # Equivalent to build:mp-weixin -# 其他 +# Others pnpm type-check pnpm lint && pnpm lint:fix ``` ### License -MIT +MIT \ No newline at end of file diff --git a/main/manager-web/src/components/AddDeviceDialog.vue b/main/manager-web/src/components/AddDeviceDialog.vue index b273a8dcb..d7052fef2 100644 --- a/main/manager-web/src/components/AddDeviceDialog.vue +++ b/main/manager-web/src/components/AddDeviceDialog.vue @@ -6,24 +6,24 @@ style="width: 40px;height: 40px;border-radius: 50%;background: #5778ff;display: flex;align-items: center;justify-content: center;"> - 添加设备 + Add Device
*
- 验证码: + Verification Code:
- +
- 确定 + Confirm
- 取消 + Cancel
@@ -47,7 +47,7 @@ export default { methods: { confirm() { if (!/^\d{6}$/.test(this.deviceCode)) { - this.$message.error('请输入6位数字验证码'); + this.$message.error('Please enter a 6-digit verification code'); return; } this.loading = true; @@ -58,13 +58,13 @@ export default { if (data.code === 0) { this.$emit('refresh'); this.$message.success({ - message: '设备绑定成功', + message: 'Device bound successfully', showClose: true }); this.closeDialog(); } else { this.$message.error({ - message: data.msg || '绑定失败', + message: data.msg || 'Binding failed', showClose: true }); } diff --git a/main/manager-web/src/components/AddWisdomBodyDialog.vue b/main/manager-web/src/components/AddWisdomBodyDialog.vue index a0c441f29..92ed6db78 100644 --- a/main/manager-web/src/components/AddWisdomBodyDialog.vue +++ b/main/manager-web/src/components/AddWisdomBodyDialog.vue @@ -6,23 +6,23 @@ style="width: 40px;height: 40px;border-radius: 50%;background: #5778ff;display: flex;align-items: center;justify-content: center;">
- 添加智能体 + Add Agent
-
*
智能体名称: +
*
Agent Name:
- +
- 确定 + Confirm
- 取消 + Cancel
@@ -50,12 +50,12 @@ export default { }, confirm() { if (!this.wisdomBodyName.trim()) { - this.$message.error('请输入智能体名称'); + this.$message.error('Please enter agent name'); return; } Api.agent.addAgent(this.wisdomBodyName, (res) => { this.$message.success({ - message: '添加成功', + message: 'Added successfully', showClose: true }); this.$emit('confirm', res); diff --git a/main/manager-web/src/components/ManualAddDeviceDialog.vue b/main/manager-web/src/components/ManualAddDeviceDialog.vue index b6060ff59..3896ed88d 100644 --- a/main/manager-web/src/components/ManualAddDeviceDialog.vue +++ b/main/manager-web/src/components/ManualAddDeviceDialog.vue @@ -1,9 +1,9 @@ @@ -41,9 +41,9 @@ export default { const validateMac = (rule, value, callback) => { const macRegex = /^([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})$/; if (!value) { - callback(new Error('请输入Mac地址')); + callback(new Error('Please enter MAC address')); } else if (!macRegex.test(value)) { - callback(new Error('请输入正确的Mac地址格式,例如:00:1A:2B:3C:4D:5E')); + callback(new Error('Please enter correct MAC address format, e.g.: 00:1A:2B:3C:4D:5E')); } else { callback(); } @@ -58,10 +58,10 @@ export default { firmwareTypes: [], rules: { board: [ - { required: true, message: '请选择设备型号', trigger: 'change' } + { required: true, message: 'Please select device model', trigger: 'change' } ], appVersion: [ - { required: true, message: '请输入固件版本', trigger: 'blur' } + { required: true, message: 'Please enter firmware version', trigger: 'blur' } ], macAddress: [ { required: true, validator: validateMac, trigger: 'blur' } @@ -78,8 +78,8 @@ export default { const res = await Api.dict.getDictDataByType('FIRMWARE_TYPE'); this.firmwareTypes = res.data; } catch (error) { - console.error('获取固件类型失败:', error); - this.$message.error(error.message || '获取固件类型失败'); + console.error('Failed to get firmware types:', error); + this.$message.error(error.message || 'Failed to get firmware types'); } }, submitForm() { @@ -97,11 +97,11 @@ export default { Api.device.manualAddDevice(params, ({ data }) => { if (data.code === 0) { - this.$message.success('设备添加成功'); + this.$message.success('Device added successfully'); this.$emit('refresh'); this.closeDialog(); } else { - this.$message.error(data.msg || '添加失败'); + this.$message.error(data.msg || 'Failed to add device'); } }); }, diff --git a/main/manager-web/src/router/index.js b/main/manager-web/src/router/index.js index a93330733..0b7cdab1b 100644 --- a/main/manager-web/src/router/index.js +++ b/main/manager-web/src/router/index.js @@ -73,7 +73,7 @@ const routes = [ path: '/model-config', name: 'ModelConfig', component: function () { - return import('../views/modelConfig.vue') + return import('../views/ModelConfig.vue') } }, { diff --git a/main/manager-web/src/views/DeviceManagement.vue b/main/manager-web/src/views/DeviceManagement.vue index 03e9a2a3c..2673866be 100644 --- a/main/manager-web/src/views/DeviceManagement.vue +++ b/main/manager-web/src/views/DeviceManagement.vue @@ -5,9 +5,9 @@

Device Management

- - 搜索 + Search
@@ -17,23 +17,23 @@ - + - + - - - - - + + + + + - + - + +
- {{ isCurrentPageAllSelected ? '取消全选' : '全选' }} + {{ isCurrentPageAllSelected ? 'Deselect All' : 'Select All' }} - 验证码绑定 + Bind with Code - 手动添加 + Manual Add - 解绑 + Unbind
- + - - + + - - 共{{ deviceList.length }}条记录 + + Total {{ deviceList.length }} records
@@ -194,8 +197,8 @@ export default { const res = await Api.dict.getDictDataByType('FIRMWARE_TYPE') this.firmwareTypes = res.data } catch (error) { - console.error('获取固件类型失败:', error) - this.$message.error(error.message || '获取固件类型失败') + console.error('Failed to get firmware types:', error) + this.$message.error(error.message || 'Failed to get firmware types') } }, handlePageSizeChange(val) { @@ -218,15 +221,15 @@ export default { const selectedDevices = this.paginatedDeviceList.filter(device => device.selected); if (selectedDevices.length === 0) { this.$message.warning({ - message: '请至少选择一条记录', + message: 'Please select at least one record', showClose: true }); return; } - this.$confirm(`确认要解绑选中的 ${selectedDevices.length} 台设备吗?`, '警告', { - confirmButtonText: '确定', - cancelButtonText: '取消', + this.$confirm(`Are you sure you want to unbind ${selectedDevices.length} selected device(s)?`, 'Warning', { + confirmButtonText: 'Confirm', + cancelButtonText: 'Cancel', type: 'warning' }).then(() => { const deviceIds = selectedDevices.map(device => device.device_id); @@ -240,7 +243,7 @@ export default { if (data.code === 0) { resolve(); } else { - reject(data.msg || '解绑失败'); + reject(data.msg || 'Unbind failed'); } }); }); @@ -248,14 +251,14 @@ export default { Promise.all(promises) .then(() => { this.$message.success({ - message: `成功解绑 ${deviceIds.length} 台设备`, + message: `Successfully unbound ${deviceIds.length} device(s)`, showClose: true }); this.fetchBindDevices(this.currentAgentId); }) .catch(error => { this.$message.error({ - message: error || '批量解绑过程中出现错误', + message: error || 'Error occurred during batch unbinding', showClose: true }); }); @@ -271,7 +274,7 @@ export default { const text = (row.remark || '').trim(); if (text.length > 64) { - this.$message.warning('备注不能超过 64 字符'); + this.$message.warning('Remark cannot exceed 64 characters'); return; } if (text === row._originalRemark) { @@ -282,10 +285,10 @@ export default { this.updateDeviceInfo(row.device_id, { alias: text }, (ok, resp) => { if (ok) { row._originalRemark = text; - this.$message.success('备注已保存'); + this.$message.success('Remark saved'); } else { row.remark = row._originalRemark; - this.$message.error(resp.msg || '备注保存失败'); + this.$message.error(resp.msg || 'Failed to save remark'); } row._submitting = false; }); @@ -303,21 +306,21 @@ export default { this.submitRemark(row); }, handleUnbind(device_id) { - this.$confirm('确认要解绑该设备吗?', '警告', { - confirmButtonText: '确定', - cancelButtonText: '取消', + this.$confirm('Are you sure you want to unbind this device?', 'Warning', { + confirmButtonText: 'Confirm', + cancelButtonText: 'Cancel', type: 'warning' }).then(() => { Api.device.unbindDevice(device_id, ({data}) => { if (data.code === 0) { this.$message.success({ - message: '设备解绑成功', + message: 'Device unbound successfully', showClose: true }); this.fetchBindDevices(this.$route.query.agentId); } else { this.$message.error({ - message: data.msg || '设备解绑失败', + message: data.msg || 'Failed to unbind device', showClose: true }); } @@ -363,7 +366,7 @@ export default { this.activeSearchKeyword = ""; this.searchKeyword = ""; } else { - this.$message.error(data.msg || '获取设备列表失败'); + this.$message.error(data.msg || 'Failed to get device list'); } }); }, @@ -385,11 +388,11 @@ export default { handleOtaSwitchChange(row) { this.updateDeviceInfo(row.device_id, {autoUpdate: row.otaSwitch ? 1 : 0}, (result, {msg}) => { if (result) { - this.$message.success(row.otaSwitch ? '已设置成自动升级' : '已关闭自动升级'); + this.$message.success(row.otaSwitch ? 'Auto-upgrade enabled' : 'Auto-upgrade disabled'); return; } row.otaSwitch = !row.otaSwitch - this.$message.error(msg || '操作失败') + this.$message.error(msg || 'Operation failed') }) }, } diff --git a/main/xiaozhi-server/core/providers/tools/device_mcp/mcp_handler.py b/main/xiaozhi-server/core/providers/tools/device_mcp/mcp_handler.py index da4b311ed..b0d4c2261 100644 --- a/main/xiaozhi-server/core/providers/tools/device_mcp/mcp_handler.py +++ b/main/xiaozhi-server/core/providers/tools/device_mcp/mcp_handler.py @@ -30,6 +30,14 @@ async def send_mcp_message(conn, payload: dict): async def handle_mcp_message(conn, mcp_client, payload: dict): """Handle MCP messages, including initialization, tool list and tool call responses""" logger.bind(tag=TAG).info(f"Handling MCP message: {str(payload)[:100]}") + + # Log device initialization request details + if "method" in payload and payload["method"] == "initialize": + params = payload.get("params", {}) + client_info = params.get("clientInfo", {}) + logger.bind(tag=TAG).info( + f"Device initialization request received - Client: {client_info.get('name', 'unknown')} v{client_info.get('version', 'unknown')}" + ) if not isinstance(payload, dict): logger.bind(tag=TAG).error( @@ -51,12 +59,56 @@ async def handle_mcp_message(conn, mcp_client, payload: dict): if msg_id == 1: # mcpInitializeID logger.bind(tag=TAG).debug("Received MCP initialization response") - server_info = result.get("serverInfo") + + # Extract all relevant information + protocol_version = result.get("protocolVersion", "unknown") + capabilities = result.get("capabilities", {}) + server_info = result.get("serverInfo", {}) + if isinstance(server_info, dict): - name = server_info.get("name") - version = server_info.get("version") + name = server_info.get("name", "unknown") + version = server_info.get("version", "unknown") + + # Store firmware info in connection object for later use + conn.device_firmware_info = { + 'name': name, + 'version': version, + 'protocol_version': protocol_version, + 'capabilities': capabilities, + 'timestamp': asyncio.get_event_loop().time() + } + + # Enhanced logging with more prominent firmware version display logger.bind(tag=TAG).info( - f"Client MCP server info: name={name}, version={version}" + f"="*60 + ) + logger.bind(tag=TAG).info( + f"DEVICE CONNECTED - Firmware Details:" + ) + logger.bind(tag=TAG).info( + f" Device Name: {name}" + ) + logger.bind(tag=TAG).info( + f" Firmware Version: {version}" + ) + logger.bind(tag=TAG).info( + f" Protocol Version: {protocol_version}" + ) + logger.bind(tag=TAG).info( + f" Device ID: {conn.headers.get('device-id', 'unknown')}" + ) + logger.bind(tag=TAG).info( + f" MAC Address: {conn.headers.get('device-id', 'unknown').replace('_', ':').upper()}" + ) + logger.bind(tag=TAG).info( + f" Capabilities: {list(capabilities.keys()) if capabilities else 'none'}" + ) + logger.bind(tag=TAG).info( + f"="*60 + ) + else: + logger.bind(tag=TAG).warning( + f"Device initialization response missing serverInfo: {result}" ) return From 8ff30a0215735d16758254f9eb6e928d3563cc73 Mon Sep 17 00:00:00 2001 From: rahulpscraftech360 Date: Sat, 23 Aug 2025 16:12:14 +0530 Subject: [PATCH 2/3] device activation working --- main/xiaozhi-server/core/api/ota_handler.py | 1 + main/xiaozhi-server/test_ota_activation.py | 95 +++++++++++++++++++++ 2 files changed, 96 insertions(+) create mode 100644 main/xiaozhi-server/test_ota_activation.py diff --git a/main/xiaozhi-server/core/api/ota_handler.py b/main/xiaozhi-server/core/api/ota_handler.py index cbabbdd30..79449658a 100644 --- a/main/xiaozhi-server/core/api/ota_handler.py +++ b/main/xiaozhi-server/core/api/ota_handler.py @@ -5,6 +5,7 @@ import base64 import hmac import hashlib import os +import aiohttp from aiohttp import web from core.utils.util import get_local_ip from core.api.base_handler import BaseHandler diff --git a/main/xiaozhi-server/test_ota_activation.py b/main/xiaozhi-server/test_ota_activation.py new file mode 100644 index 000000000..a6228d494 --- /dev/null +++ b/main/xiaozhi-server/test_ota_activation.py @@ -0,0 +1,95 @@ +#!/usr/bin/env python3 +""" +Test script to verify OTA activation code generation +""" + +import json +import asyncio +import httpx + +async def test_ota_endpoint(): + """Test the OTA endpoint with a sample device""" + + # Sample device data (similar to what your ESP32 sends) + device_data = { + "version": 176, + "flash_size": 4194304, + "minimum_free_heap_size": 186020, + "mac_address": "68:25:dd:bb:4d:44", + "uuid": "848fc4d1-3db0-42e5-a0e6-e60a9b4477d8", + "chip_model_name": "ESP32", + "chip_info": { + "model": 1, + "cores": 2, + "revision": 301, + "features": 62 + }, + "application": { + "name": "Xiaozhi_ESP32", + "version": "1.7.6", + "compile_time": "2025-08-23T10:00:00Z", + "idf_version": "v5.2.1", + "elf_sha256": "d4e77c78a2f8a0b4b2e1c4e77c78a2f8a0b4b2e1" + }, + "partition_table": [], + "ota": { + "label": "ota_0" + }, + "board": { + "type": "doit-ai-01-kit", + "ssid": "TestWiFi", + "rssi": -45, + "channel": 6, + "ip": "192.168.1.74", + "mac": "68:25:dd:bb:4d:44" + } + } + + # OTA endpoint URL + ota_url = "http://192.168.1.105:8003/xiaozhi/ota/" + + # Headers that the device sends + headers = { + "device-id": "68:25:dd:bb:4d:44", + "Content-Type": "application/json" + } + + print(f"Testing OTA endpoint: {ota_url}") + print(f"Device ID: {headers['device-id']}") + print(f"Device firmware: {device_data['application']['version']}") + print("-" * 50) + + try: + async with httpx.AsyncClient() as client: + response = await client.post( + ota_url, + headers=headers, + json=device_data, + timeout=10.0 + ) + + print(f"Response status: {response.status_code}") + + if response.status_code == 200: + result = response.json() + print(f"Response data: {json.dumps(result, indent=2)}") + + # Check if activation code is present + if "activation" in result: + activation = result["activation"] + print("\n" + "=" * 50) + print("ACTIVATION CODE RECEIVED!") + print(f"Code: {activation.get('code')}") + print(f"Message: {activation.get('message')}") + print("=" * 50) + else: + print("\nNo activation code in response") + + else: + print(f"Error response: {response.text}") + + except Exception as e: + print(f"Error testing OTA endpoint: {e}") + +if __name__ == "__main__": + asyncio.run(test_ota_endpoint()) \ No newline at end of file From 4cfe44be018457ed07f353525ea636c8c41ca7af Mon Sep 17 00:00:00 2001 From: rahulpscraftech360 Date: Sat, 23 Aug 2025 16:15:39 +0530 Subject: [PATCH 3/3] added connected device section --- DEVICE_CONNECTIVITY_GUIDE.md | 441 ++++++++++++++++++ .../device/dto/DeviceReportRespDTO.java | 25 + .../service/impl/DeviceServiceImpl.java | 93 ++++ main/manager-web/src/views/OtaManagement.vue | 114 +++++ 4 files changed, 673 insertions(+) create mode 100644 DEVICE_CONNECTIVITY_GUIDE.md diff --git a/DEVICE_CONNECTIVITY_GUIDE.md b/DEVICE_CONNECTIVITY_GUIDE.md new file mode 100644 index 000000000..a1e924c8d --- /dev/null +++ b/DEVICE_CONNECTIVITY_GUIDE.md @@ -0,0 +1,441 @@ +# Xiaozhi ESP32 Device Connectivity Guide + +## Table of Contents +- [Overview](#overview) +- [Device Activation Process](#device-activation-process) +- [MQTT Communication](#mqtt-communication) +- [UDP Communication](#udp-communication) +- [WebSocket Communication](#websocket-communication) +- [Network Architecture](#network-architecture) +- [Troubleshooting](#troubleshooting) + +## Overview + +The Xiaozhi ESP32 Server supports multiple communication protocols for device connectivity: +- **HTTP/HTTPS**: For OTA updates and initial device registration +- **MQTT**: For real-time bidirectional communication +- **UDP**: For low-latency audio streaming +- **WebSocket**: For persistent real-time connections + +## Device Activation Process + +### 1. Initial Connection Flow + +```mermaid +sequenceDiagram + participant ESP32 as ESP32 Device + participant OTA as OTA Endpoint (8002) + participant Redis as Redis Cache + participant Web as Web Dashboard + participant User as User + + ESP32->>OTA: POST /xiaozhi/ota + Note over ESP32,OTA: Headers: device-id (MAC address) + Note over ESP32,OTA: Body: firmware info, board type + + OTA->>Redis: Check if device registered + alt Device Not Registered + OTA->>Redis: Generate 6-digit code + Redis-->>OTA: Store activation code + OTA-->>ESP32: Return activation code + MQTT credentials + ESP32->>ESP32: Display code on screen/log + User->>Web: Enter activation code + Web->>Redis: Validate code + Web->>Web: Register device to user + else Device Registered + OTA-->>ESP32: Return MQTT credentials + config + end +``` + +### 2. Activation Code Generation + +**Location**: `DeviceServiceImpl.java:buildActivation()` + +The activation process works as follows: + +1. **Device Makes OTA Request**: + ```http + POST http://192.168.1.105:8002/xiaozhi/ota + Headers: + device-id: AA:BB:CC:DD:EE:FF + Body: + { + "application": {"version": "1.0.0"}, + "board": {"type": "esp32s3"}, + "chip_model_name": "ESP32-S3" + } + ``` + +2. **Server Generates Activation Code**: + ```java + // 6-digit random code + String newCode = RandomUtil.randomNumbers(6); + + // Store in Redis with two keys: + // 1. Device data key + String dataKey = "ota:device:" + deviceId; + redisUtils.set(dataKey, deviceData); + + // 2. Code lookup key (for validation) + String codeKey = "ota:activation:code:" + newCode; + redisUtils.set(codeKey, deviceId); + ``` + +3. **Response to Device**: + ```json + { + "activation": { + "code": "141966", + "message": "http://dashboard.url\n141966", + "challenge": "AA:BB:CC:DD:EE:FF" + }, + "mqtt": { + "endpoint": "192.168.1.105:1883", + "client_id": "GID_test@@@AA_BB_CC_DD_EE_FF@@@uuid", + "username": "base64_encoded_user_data", + "password": "hmac_sha256_signature", + "publish_topic": "device-server", + "subscribe_topic": "null" + } + } + ``` + +4. **User Activation**: + - User sees code on device display/logs + - Opens web dashboard + - Enters 6-digit code + - Device is bound to user account + +## MQTT Communication + +### MQTT Configuration + +**Default Settings**: +- **Broker**: 192.168.1.105 (configurable) +- **Port**: 1883 +- **Protocol**: MQTT 3.1.1 + +### MQTT Credential Generation + +**Location**: `DeviceServiceImpl.java:buildMqttCredentials()` + +The MQTT authentication uses a secure HMAC-SHA256 signature: + +```java +// Client ID Format +String clientId = "GID_test@@@{mac_address}@@@{uuid}"; +// Example: GID_test@@@AA_BB_CC_DD_EE_FF@@@550e8400-e29b-41d4-a716-446655440000 + +// Username (Base64 encoded JSON) +String userData = {"ip": "client_ip_address"}; +String username = Base64.encode(userData); + +// Password (HMAC-SHA256 signature) +String content = clientId + "|" + username; +String password = Base64.encode( + HMAC_SHA256(content, signature_key) +); +``` + +### MQTT Topics + +- **Device to Server**: `device-server` +- **Server to Device**: Device subscribes to personalized topics +- **Message Format**: JSON payloads + +### MQTT Message Flow + +```mermaid +graph LR + A[ESP32 Device] -->|Publish| B[device-server topic] + B --> C[MQTT Broker] + C --> D[Xiaozhi Server] + D -->|Process & Respond| E[Device-specific topic] + E --> C + C -->|Subscribe| A +``` + +## UDP Communication + +### UDP Audio Streaming + +**Configuration**: +- **Port**: 8884 +- **Purpose**: Real-time audio streaming +- **Protocol**: Custom binary protocol + +### UDP Packet Structure + +``` ++------------------+------------------+------------------+ +| Device ID (6B) | Sequence (4B) | Audio Data (nB) | ++------------------+------------------+------------------+ +``` + +### Audio Parameters +```yaml +audio_params: + format: opus # Audio codec + sample_rate: 16000 # Hz + channels: 1 # Mono + frame_duration: 60 # ms +``` + +### UDP Flow for Audio + +1. **Device captures audio** from microphone +2. **Encodes with Opus** codec +3. **Sends UDP packets** to server:8884 +4. **Server processes** audio (ASR/Speech recognition) +5. **Response sent** via MQTT or WebSocket + +## WebSocket Communication + +### WebSocket Endpoint + +**URL Format**: `ws://{server_ip}:{port}/xiaozhi/v1/` + +### Connection Flow + +```javascript +// Client connection example +const ws = new WebSocket('ws://192.168.1.105:8000/xiaozhi/v1/'); + +ws.onopen = () => { + // Send authentication + ws.send(JSON.stringify({ + type: 'auth', + device_id: 'AA:BB:CC:DD:EE:FF', + token: 'device_token' + })); +}; + +ws.onmessage = (event) => { + const data = JSON.parse(event.data); + // Handle server messages +}; +``` + +## Network Architecture + +### Complete System Architecture + +```mermaid +graph TB + subgraph "ESP32 Devices" + D1[Device 1] + D2[Device 2] + D3[Device N] + end + + subgraph "Communication Layer" + HTTP[HTTP/8002
OTA & Activation] + WS[WebSocket/8000
Real-time Control] + MQTT[MQTT/1883
Commands & Status] + UDP[UDP/8884
Audio Stream] + end + + subgraph "Backend Services" + JAVA[Manager API
Port 8002] + PY[Xiaozhi Server
Port 8000/8003] + REDIS[Redis Cache
Activation Codes] + DB[(PostgreSQL
Device Registry)] + end + + subgraph "Frontend" + WEB[Web Dashboard
Device Management] + MOBILE[Mobile App
Device Control] + end + + D1 & D2 & D3 -.->|Initial Setup| HTTP + D1 & D2 & D3 -->|Status Updates| MQTT + D1 & D2 & D3 -->|Audio Stream| UDP + D1 & D2 & D3 <-->|Control| WS + + HTTP --> JAVA + WS --> PY + MQTT --> PY + UDP --> PY + + JAVA <--> REDIS + JAVA <--> DB + PY <--> REDIS + PY <--> DB + + WEB --> JAVA + MOBILE --> JAVA +``` + +### Port Summary + +| Service | Port | Protocol | Purpose | +|---------|------|----------|---------| +| Manager API | 8002 | HTTP | Device OTA, Activation | +| Xiaozhi Server WS | 8000 | WebSocket | Real-time communication | +| Xiaozhi Server HTTP | 8003 | HTTP | API endpoints, MCP | +| MQTT Broker | 1883 | MQTT | Message broker | +| UDP Audio | 8884 | UDP | Audio streaming | +| Web Dashboard | 3000 | HTTP | User interface | + +## Configuration Files + +### 1. Server Configuration (`config.yaml`) + +```yaml +server: + ip: 0.0.0.0 + port: 8000 # WebSocket port + http_port: 8003 # HTTP API port + mqtt_gateway: + enabled: true + broker: 192.168.1.105 + port: 1883 + udp_port: 8884 +``` + +### 2. Manager API Configuration + +```yaml +manager-api: + url: http://192.168.1.105:8002/xiaozhi + secret: your-secret-key +``` + +## Troubleshooting + +### Common Issues and Solutions + +#### 1. Device Not Receiving Activation Code + +**Symptom**: Device connects but no activation code generated + +**Check**: +- Verify device is calling correct OTA endpoint (port 8002, not 8003) +- Check Redis is running and accessible +- Verify device-id header is present in request + +**Solution**: +```bash +# Check Redis for activation codes +redis-cli +> KEYS ota:activation:code:* +> GET ota:device:AA:BB:CC:DD:EE:FF +``` + +#### 2. MQTT Connection Failed + +**Symptom**: Device cannot connect to MQTT broker + +**Check**: +- MQTT broker is running on port 1883 +- Firewall allows MQTT traffic +- Credentials are correctly generated + +**Debug**: +```bash +# Test MQTT connection +mosquitto_sub -h 192.168.1.105 -p 1883 -t "device-server" -v + +# Check MQTT logs +tail -f /var/log/mosquitto/mosquitto.log +``` + +#### 3. UDP Audio Not Working + +**Symptom**: Audio from device not received + +**Check**: +- UDP port 8884 is open +- Audio format matches configuration (Opus, 16kHz, mono) +- Network allows UDP traffic + +**Test**: +```python +# Simple UDP listener test +import socket +sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) +sock.bind(('0.0.0.0', 8884)) +while True: + data, addr = sock.recvfrom(4096) + print(f"Received {len(data)} bytes from {addr}") +``` + +#### 4. WebSocket Connection Drops + +**Symptom**: WebSocket disconnects frequently + +**Check**: +- Keepalive/ping-pong implemented +- Proxy/load balancer timeout settings +- Network stability + +**Configuration**: +```javascript +// Client-side keepalive +setInterval(() => { + if (ws.readyState === WebSocket.OPEN) { + ws.send(JSON.stringify({type: 'ping'})); + } +}, 30000); // Every 30 seconds +``` + +### Debug Logs + +Enable debug logging for different components: + +```yaml +log: + log_level: DEBUG + module_levels: + OTA: DEBUG + MQTT: DEBUG + UDP: DEBUG + WebSocket: DEBUG +``` + +### Testing Tools + +1. **Test OTA Endpoint**: +```bash +curl -X POST http://192.168.1.105:8002/xiaozhi/ota \ + -H "device-id: AA:BB:CC:DD:EE:FF" \ + -H "Content-Type: application/json" \ + -d '{"application":{"version":"1.0.0"}}' +``` + +2. **Test MQTT Publish**: +```bash +mosquitto_pub -h 192.168.1.105 -p 1883 \ + -t "device-server" \ + -m '{"device_id":"AA:BB:CC:DD:EE:FF","message":"test"}' +``` + +3. **Monitor WebSocket**: +```javascript +// Browser console +const ws = new WebSocket('ws://192.168.1.105:8000/xiaozhi/v1/'); +ws.onmessage = (e) => console.log('Received:', e.data); +ws.onerror = (e) => console.error('Error:', e); +``` + +## Security Considerations + +1. **MQTT Authentication**: Uses HMAC-SHA256 signatures +2. **Activation Codes**: 6-digit codes with Redis TTL +3. **Device IDs**: MAC addresses as unique identifiers +4. **Network Security**: Consider using TLS/SSL for production +5. **API Keys**: Stored securely in environment variables + +## Performance Optimization + +1. **MQTT QoS**: Use QoS 0 for audio commands, QoS 1 for critical messages +2. **UDP Buffer**: Increase system UDP buffer for audio streaming +3. **WebSocket**: Implement connection pooling for multiple devices +4. **Redis**: Set appropriate TTL for activation codes (default: 5 minutes) + +## Contact & Support + +For issues or questions: +- GitHub Issues: [your-repo-url] +- Documentation: This guide +- Logs: Check `/tmp/xiaozhi-server.log` for detailed debugging \ No newline at end of file diff --git a/main/manager-api/src/main/java/xiaozhi/modules/device/dto/DeviceReportRespDTO.java b/main/manager-api/src/main/java/xiaozhi/modules/device/dto/DeviceReportRespDTO.java index f938001e0..d8f193cd5 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/device/dto/DeviceReportRespDTO.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/device/dto/DeviceReportRespDTO.java @@ -22,6 +22,9 @@ public class DeviceReportRespDTO { @Schema(description = "WebSocket配置") private Websocket websocket; + + @Schema(description = "MQTT配置") + private Mqtt mqtt; @Getter @Setter @@ -70,4 +73,26 @@ public class DeviceReportRespDTO { @Schema(description = "WebSocket服务器地址") private String url; } + + @Getter + @Setter + public static class Mqtt { + @Schema(description = "MQTT服务器端点") + private String endpoint; + + @Schema(description = "MQTT客户端ID") + private String client_id; + + @Schema(description = "MQTT用户名") + private String username; + + @Schema(description = "MQTT密码") + private String password; + + @Schema(description = "发布主题") + private String publish_topic; + + @Schema(description = "订阅主题") + private String subscribe_topic; + } } diff --git a/main/manager-api/src/main/java/xiaozhi/modules/device/service/impl/DeviceServiceImpl.java b/main/manager-api/src/main/java/xiaozhi/modules/device/service/impl/DeviceServiceImpl.java index 4e9e262b1..67406a19f 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/device/service/impl/DeviceServiceImpl.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/device/service/impl/DeviceServiceImpl.java @@ -1,12 +1,16 @@ package xiaozhi.modules.device.service.impl; +import java.nio.charset.StandardCharsets; import java.time.Instant; +import java.util.Base64; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.TimeZone; import java.util.UUID; +import javax.crypto.Mac; +import javax.crypto.spec.SecretKeySpec; import org.apache.commons.lang3.StringUtils; import org.springframework.aop.framework.AopContext; @@ -175,6 +179,13 @@ public class DeviceServiceImpl extends BaseServiceImpl } response.setWebsocket(websocket); + + // Always include MQTT credentials for all devices (both registered and unregistered) + DeviceReportRespDTO.Mqtt mqttCredentials = buildMqttCredentials(macAddress); + if (mqttCredentials != null) { + response.setMqtt(mqttCredentials); + log.info("Added MQTT credentials to response for device: {}", macAddress); + } if (deviceById != null) { // 如果设备存在,则异步更新上次连接时间和版本信息 @@ -349,6 +360,88 @@ public class DeviceServiceImpl extends BaseServiceImpl } return code; } + + private DeviceReportRespDTO.Mqtt buildMqttCredentials(String deviceId) { + try { + DeviceReportRespDTO.Mqtt mqtt = new DeviceReportRespDTO.Mqtt(); + + // Get MQTT configuration from system parameters + String mqttBroker = sysParamsService.getValue("mqtt.broker", true); + String mqttPort = sysParamsService.getValue("mqtt.port", true); + String mqttSignatureKey = sysParamsService.getValue("mqtt.signature_key", true); + + // Use defaults if not configured + if (StringUtils.isBlank(mqttBroker)) { + mqttBroker = "192.168.1.105"; // Default to local IP + } + if (StringUtils.isBlank(mqttPort)) { + mqttPort = "1883"; + } + if (StringUtils.isBlank(mqttSignatureKey)) { + mqttSignatureKey = "test-signature-key-12345"; + } + + // Convert MAC address format (remove colons, use underscores) + String macAddress = deviceId.replace(":", "_"); + + // Generate UUID for this session + String clientUuid = UUID.randomUUID().toString(); + + // Create client ID in format: GID_test@@@mac_address@@@uuid + String groupId = "GID_test"; + String clientId = groupId + "@@@" + macAddress + "@@@" + clientUuid; + + // Get client IP from request + String clientIp = "127.0.0.1"; + try { + ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); + if (attributes != null) { + HttpServletRequest request = attributes.getRequest(); + clientIp = request.getRemoteAddr(); + String forwardedFor = request.getHeader("X-Forwarded-For"); + if (StringUtils.isNotBlank(forwardedFor)) { + clientIp = forwardedFor.split(",")[0].trim(); + } else { + String realIp = request.getHeader("X-Real-IP"); + if (StringUtils.isNotBlank(realIp)) { + clientIp = realIp; + } + } + } + } catch (Exception e) { + log.warn("Failed to get client IP: {}", e.getMessage()); + } + + // Create user data and encode as base64 JSON + Map userData = new HashMap<>(); + userData.put("ip", clientIp); + String userDataJson = "{\"ip\":\"" + clientIp + "\"}"; + String username = Base64.getEncoder().encodeToString(userDataJson.getBytes(StandardCharsets.UTF_8)); + + // Generate password signature using HMAC-SHA256 + String content = clientId + "|" + username; + Mac mac = Mac.getInstance("HmacSHA256"); + SecretKeySpec secretKeySpec = new SecretKeySpec(mqttSignatureKey.getBytes(StandardCharsets.UTF_8), "HmacSHA256"); + mac.init(secretKeySpec); + byte[] signature = mac.doFinal(content.getBytes(StandardCharsets.UTF_8)); + String password = Base64.getEncoder().encodeToString(signature); + + // Set MQTT credentials + mqtt.setEndpoint(mqttBroker + ":" + mqttPort); + mqtt.setClient_id(clientId); + mqtt.setUsername(username); + mqtt.setPassword(password); + mqtt.setPublish_topic("device-server"); + mqtt.setSubscribe_topic("null"); + + log.info("Generated MQTT credentials for device {}: clientId={}", deviceId, clientId); + + return mqtt; + } catch (Exception e) { + log.error("Failed to generate MQTT credentials for device {}: {}", deviceId, e.getMessage(), e); + return null; + } + } private DeviceReportRespDTO.Firmware buildFirmwareInfo(String type, String currentVersion) { if (StringUtils.isBlank(type)) { diff --git a/main/manager-web/src/views/OtaManagement.vue b/main/manager-web/src/views/OtaManagement.vue index aedcaa67d..7bb378e89 100644 --- a/main/manager-web/src/views/OtaManagement.vue +++ b/main/manager-web/src/views/OtaManagement.vue @@ -14,6 +14,45 @@
+ + +
+ Connected Devices Overview + + Refresh + +
+
+ + +
+
{{ connectedDevices.total || 0 }}
+
Total Devices
+
+
+ +
+
{{ connectedDevices.activeToday || 0 }}
+
Active Today
+
+
+ +
+
Firmware Versions in Use:
+
+ + {{ version }} ({{ count }} devices) + +
+
+
+
+
+
+ item.key === type) return firmwareType ? firmwareType.name : type }, + fetchConnectedDevices() { + // Fetch connected devices statistics + // This would call an API endpoint to get device statistics + // For now, we'll use the device management API to get device info + const currentAgentId = localStorage.getItem('agentId') || this.$route.query.agentId; + if (currentAgentId) { + Api.device.getAgentBindDevices(currentAgentId, ({data}) => { + if (data.code === 0 && data.data) { + const devices = data.data; + this.connectedDevices.total = devices.length; + + // Count devices active today + const today = new Date(); + today.setHours(0, 0, 0, 0); + this.connectedDevices.activeToday = devices.filter(device => { + const lastConnected = new Date(device.lastConnectedAt); + return lastConnected >= today; + }).length; + + // Calculate version distribution + const versionMap = {}; + devices.forEach(device => { + const version = device.appVersion || 'Unknown'; + versionMap[version] = (versionMap[version] || 0) + 1; + }); + this.connectedDevices.versionDistribution = versionMap; + } + }); + } + }, }, }; @@ -481,6 +556,45 @@ export default { flex-direction: column; } +.device-summary-card { + background: white; + border: none; + box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08); + + ::v-deep .el-card__header { + background: linear-gradient(135deg, #f5f7fa 0%, #f0f3f8 100%); + padding: 12px 20px; + border-bottom: 1px solid #e4e7ed; + } + + .device-stats { + padding: 10px 0; + + .stat-item { + text-align: center; + padding: 10px; + + .stat-value { + font-size: 28px; + font-weight: bold; + color: #409eff; + margin-bottom: 5px; + } + + .stat-label { + font-size: 14px; + color: #606266; + margin-bottom: 8px; + } + + .version-list { + margin-top: 8px; + text-align: left; + } + } + } +} + .params-card { background: white; flex: 1;