started on frmware and ota

This commit is contained in:
rahulpscraftech360 2025-08-23 13:10:15 +05:30
parent e6704657fd
commit fb5e9fe2a0
8 changed files with 337 additions and 190 deletions

View file

@ -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

View file

@ -1,51 +1,51 @@
## 智控台移动版(manager-mobile) ## Smart Control Panel Mobile (manager-mobile)
基于 uni-app v3 + Vue 3 + Vite 的跨端移动管理端,支持 App(Android & iOS)和微信小程序。 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 - Node >= 18
- pnpm >= 7.30(建议使用项目中声明的 `pnpm@10.x`) - pnpm >= 7.30 (recommended to use `pnpm@10.x` as declared in the project)
- 可选:HBuilderX(App 调试/打包)、微信开发者工具(微信小程序) - Optional: HBuilderX (for App debugging/packaging), WeChat Developer Tools (for WeChat Mini Program)
### 快速开始 ### Quick Start
1) 配置环境变量 1) Configure environment variables
- 复制 `env/.env.example` 为 `env/.env.development` - Copy `env/.env.example` to `env/.env.development`
- 根据实际情况修改配置项(特别是 `VITE_SERVER_BASEURL`、`VITE_UNI_APPID`、`VITE_WX_APPID`) - Modify configuration items according to your needs (especially `VITE_SERVER_BASEURL`, `VITE_UNI_APPID`, `VITE_WX_APPID`)
2) 安装依赖 2) Install dependencies
```bash ```bash
pnpm i pnpm i
``` ```
3) 本地开发(热更新) 3) Local development (hot reload)
- h5: `pnpm dev:h5`,然后观察启动日志显示的ip端口号 - H5: `pnpm dev:h5`, then check the IP and port displayed in the startup logs
- 微信小程序:`pnpm dev:mp` 或 `pnpm dev:mp-weixin`,然后用微信开发者工具导入 `dist/dev/mp-weixin` - WeChat Mini Program: `pnpm dev:mp` or `pnpm dev:mp-weixin`, then import `dist/dev/mp-weixin` in WeChat Developer Tools
- App:用 HBuilderX 导入 `manager-mobile`,然后参考下面的教程就能运行了 - App: Import `manager-mobile` in HBuilderX, then follow the tutorial below to run
### 环境变量与配置 ### Environment Variables and Configuration
项目使用自定义 `env` 目录存放环境文件,按 Vite 规范命名:`.env.development`、`.env.production` 等。 The project uses a custom `env` directory for environment files, named according to Vite conventions: `.env.development`, `.env.production`, etc.
关键变量(部分): Key variables (partial):
- VITE_APP_TITLE:应用名称(写入 `manifest.config.ts`) - VITE_APP_TITLE: Application name (written to `manifest.config.ts`)
- VITE_UNI_APPID:uni-app 应用 appid(App) - VITE_UNI_APPID: uni-app application appid (App)
- VITE_WX_APPID:微信小程序 appid(mp-weixin) - VITE_WX_APPID: WeChat Mini Program appid (mp-weixin)
- VITE_FALLBACK_LOCALE:默认语言,如 `zh-Hans` - VITE_FALLBACK_LOCALE: Default language, e.g., `zh-Hans`
- VITE_SERVER_BASEURL:服务端基础地址(HTTP 请求 baseURL) - VITE_SERVER_BASEURL: Server base URL (HTTP request baseURL)
- VITE_DELETE_CONSOLE:构建时是否移除 console(`true`/`false`) - VITE_DELETE_CONSOLE: Whether to remove console during build (`true`/`false`)
- VITE_SHOW_SOURCEMAP:是否生成 sourcemap(默认关闭) - VITE_SHOW_SOURCEMAP: Whether to generate sourcemap (disabled by default)
- VITE_LOGIN_URL:未登录跳转的登录页路径(路由拦截器使用) - VITE_LOGIN_URL: Login page path for redirect when not logged in (used by route interceptor)
示例(`env/.env.development`): Example (`env/.env.development`):
```env ```env
VITE_APP_TITLE=小智 VITE_APP_TITLE=XiaoZhi
VITE_FALLBACK_LOCALE=zh-Hans VITE_FALLBACK_LOCALE=zh-Hans
VITE_UNI_APPID= VITE_UNI_APPID=
VITE_WX_APPID= VITE_WX_APPID=
@ -57,114 +57,114 @@ VITE_SHOW_SOURCEMAP=false
VITE_LOGIN_URL=/pages/login/index VITE_LOGIN_URL=/pages/login/index
``` ```
说明: Note:
- `manifest.config.ts` 会从 `env` 读取标题、appid、语言等配置。 - `manifest.config.ts` reads title, appid, language and other configurations from `env`.
### 重要注意事项 ### Important Notes
⚠️ **部署前必须修改的配置项:** ⚠️ **Configuration items that must be modified before deployment:**
1. **应用 ID 配置** 1. **Application ID Configuration**
- `VITE_UNI_APPID`:需要在 [DCloud 开发者中心](https://dev.dcloud.net.cn/) 创建应用并获取 AppID - `VITE_UNI_APPID`: Need to create an application in [DCloud Developer Center](https://dev.dcloud.net.cn/) and obtain AppID
- `VITE_WX_APPID`:需要在 [微信公众平台](https://mp.weixin.qq.com/) 注册小程序并获取 AppID - `VITE_WX_APPID`: Need to register a Mini Program in [WeChat Public Platform](https://mp.weixin.qq.com/) and obtain AppID
2. **服务端地址** 2. **Server Address**
- `VITE_SERVER_BASEURL`:修改为您的实际服务端地址 - `VITE_SERVER_BASEURL`: Modify to your actual server address
3. **应用信息** 3. **Application Information**
- `VITE_APP_TITLE`:修改为您的应用名称 - `VITE_APP_TITLE`: Modify to your application name
- 更新 `src/static/logo.png` 等图标资源 - Update icon resources like `src/static/logo.png`
4. **其他配置** 4. **Other Configurations**
- 检查 `manifest.config.ts` 中的应用配置信息 - Check application configuration in `manifest.config.ts`
- 根据需要修改 `src/layouts/fg-tabbar/tabbarList.ts` 中的 tabbar 配置 - Modify tabbar configuration in `src/layouts/fg-tabbar/tabbarList.ts` as needed
### 详细操作指南 ### Detailed Operation Guide
#### 1. 获取 uni-app AppID #### 1. Get uni-app AppID
![生成AppID](../../docs/images/manager-mobile/生成appid.png) ![Generate AppID](../../docs/images/manager-mobile/生成appid.png)
- 复制生成的 AppID 到环境变量 `VITE_UNI_APPID` 中 - Copy the generated AppID to environment variable `VITE_UNI_APPID`
#### 2. 本地运行步骤 #### 2. Local Run Steps
![本地运行](../../docs/images/manager-mobile/本地运行.png) ![Local Run](../../docs/images/manager-mobile/本地运行.png)
**App 本地调试:** **App Local Debugging:**
1. 用 HBuilderX 导入 `manager-mobile` 目录 1. Import `manager-mobile` directory in HBuilderX
2. 重新识别项目 2. Re-identify the project
3. 连接手机或使用模拟器进行真机调试 3. Connect phone or use emulator for real device debugging
**项目识别问题解决:** **Project Recognition Issue Resolution:**
![重新识别项目](../../docs/images/manager-mobile/重新识别项目.png) ![Re-identify Project](../../docs/images/manager-mobile/重新识别项目.png)
如果 HBuilderX 无法正确识别项目类型: If HBuilderX cannot correctly identify the project type:
- 在项目根目录右键选择"重新识别项目类型" - Right-click in project root directory and select "Re-identify Project Type"
- 确保项目被识别为 "uni-app" 项目 - Ensure the project is recognized as a "uni-app" project
### 路由与鉴权 ### Routing and Authentication
- 在 `src/main.ts` 中注册了路由拦截插件 `routeInterceptor`。 - Route interceptor plugin `routeInterceptor` is registered in `src/main.ts`.
- 黑名单拦截:仅对配置为需要登录的页面进行校验(来源 `@/utils` 的 `getNeedLoginPages`)。 - Blacklist interception: Only validates pages configured as requiring login (from `getNeedLoginPages` in `@/utils`).
- 登录判断:基于用户信息(`pinia` 的 `useUserStore`),未登录将跳转到 `VITE_LOGIN_URL`,并附带重定向回原页面的参数。 - 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.
### 网络请求 ### Network Requests
- 基于 `alova` + `@alova/adapter-uniapp`,统一在 `src/http/request/alova.ts` 创建实例。 - Based on `alova` + `@alova/adapter-uniapp`, instance created uniformly in `src/http/request/alova.ts`.
- `baseURL` 读取环境配置(`getEnvBaseUrl`),可通过 `method.config.meta.domain` 动态切换域名。 - `baseURL` reads environment configuration (`getEnvBaseUrl`), can dynamically switch domains via `method.config.meta.domain`.
- 认证:默认从本地 `token`(`uni.getStorageSync('token')`)注入 `Authorization` 头,缺失则重定向登录。 - Authentication: Defaults to injecting `Authorization` header from local `token` (`uni.getStorageSync('token')`), redirects to login if missing.
- 响应:统一处理 `statusCode !== 200` 的 HTTP 错误与业务 `code !== 0` 的错误;`401` 会清除 token 并跳转登录。 - 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
**微信小程序:** **WeChat Mini Program:**
1. 确保已配置正确的 `VITE_WX_APPID` 1. Ensure correct `VITE_WX_APPID` is configured
2. 运行 `pnpm build:mp`,产物在 `dist/build/mp-weixin` 2. Run `pnpm build:mp`, output in `dist/build/mp-weixin`
3. 用微信开发者工具导入项目目录,并上传代码 3. Import project directory in WeChat Developer Tools and upload code
4. 在微信公众平台提交审核 4. Submit for review in WeChat Public Platform
**Android & iOS App:** **Android & iOS App:**
#### 3. App 打包发行步骤 #### 3. App Packaging and Release Steps
**步骤一:准备打包** **Step 1: Prepare for Packaging**
![打包发行步骤1](../../docs/images/manager-mobile/打包发行步骤1.png) ![Packaging Release Step 1](../../docs/images/manager-mobile/打包发行步骤1.png)
1. 确保已配置正确的 `VITE_UNI_APPID` 1. Ensure correct `VITE_UNI_APPID` is configured
2. 运行 `pnpm build:app`,产物在 `dist/build/app` 2. Run `pnpm build:app`, output in `dist/build/app`
3. 用 HBuilderX 导入项目目录 3. Import project directory in HBuilderX
4. 在 HBuilderX 中点击"发行" → "原生App-云打包" 4. Click "Release" → "Native App-Cloud Packaging" in HBuilderX
**步骤二:配置打包参数** **Step 2: Configure Packaging Parameters**
![打包发行步骤2](../../docs/images/manager-mobile/打包发行步骤2.png) ![Packaging Release Step 2](../../docs/images/manager-mobile/打包发行步骤2.png)
1. **应用图标和启动图**:上传应用图标和启动页面图片 1. **App Icon and Launch Screen**: Upload app icon and launch screen images
2. **应用版本号**:设置版本号和版本名称 2. **App Version Number**: Set version number and version name
3. **签名证书**: 3. **Signing Certificate**:
- Android:上传 keystore 证书文件 - Android: Upload keystore certificate file
- iOS:配置开发者证书和描述文件 - iOS: Configure developer certificate and provisioning profile
4. **包名配置**:设置应用的包名(Bundle ID) 4. **Package Name Configuration**: Set app package name (Bundle ID)
5. **打包类型**:选择测试包或正式包 5. **Package Type**: Choose test package or release package
6. 点击"打包"开始云打包流程 6. Click "Package" to start cloud packaging process
**发布到应用商店:** **Publish to App Stores:**
- **Android**:将生成的 APK 文件上传到各大 Android 应用市场 - **Android**: Upload generated APK file to various Android app markets
- **iOS**:将生成的 IPA 文件通过 App Store Connect 上传到 App Store(需要 Apple 开发者账号) - **iOS**: Upload generated IPA file to App Store via App Store Connect (requires Apple Developer account)
### 约定与工程化 ### Conventions and Engineering
- 页面与分包:由 `@uni-helper/vite-plugin-uni-pages` 与 `pages.config.ts` 统一生成;tabbar 配置在 `src/layouts/fg-tabbar/tabbarList.ts`。 - 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`.
- 组件与 hooks 自动导入:见 `vite.config.ts` 中 `unplugin-auto-import` 与 `@uni-helper/vite-plugin-uni-components`。 - Auto-import of components and hooks: See `unplugin-auto-import` and `@uni-helper/vite-plugin-uni-components` in `vite.config.ts`.
- 样式:使用 UnoCSS 与 `src/style/index.scss`。 - Styling: Uses UnoCSS and `src/style/index.scss`.
- 状态管理:`pinia` + `pinia-plugin-persistedstate`。 - State management: `pinia` + `pinia-plugin-persistedstate`.
- 代码规范:内置 `eslint`、`husky`、`lint-staged`,提交前自动格式化(`lint-staged`)。 - Code standards: Built-in `eslint`, `husky`, `lint-staged`, auto-format before commit (`lint-staged`).
### 常用脚本 ### Common Scripts
```bash ```bash
# 开发 # Development
pnpm dev:mp # 等价 dev:mp-weixin pnpm dev:mp # Equivalent to dev:mp-weixin
# 构建 # Build
pnpm build:mp # 等价 build:mp-weixin pnpm build:mp # Equivalent to build:mp-weixin
# 其他 # Others
pnpm type-check pnpm type-check
pnpm lint && pnpm lint:fix pnpm lint && pnpm lint:fix
``` ```
### License ### License
MIT MIT

View file

@ -6,24 +6,24 @@
style="width: 40px;height: 40px;border-radius: 50%;background: #5778ff;display: flex;align-items: center;justify-content: center;"> style="width: 40px;height: 40px;border-radius: 50%;background: #5778ff;display: flex;align-items: center;justify-content: center;">
<img src="@/assets/home/equipment.png" alt="" style="width: 18px;height: 15px;" /> <img src="@/assets/home/equipment.png" alt="" style="width: 18px;height: 15px;" />
</div> </div>
添加设备 Add Device
</div> </div>
<div style="height: 1px;background: #e8f0ff;" /> <div style="height: 1px;background: #e8f0ff;" />
<div style="margin: 22px 15px;"> <div style="margin: 22px 15px;">
<div style="font-weight: 400;font-size: 14px;text-align: left;color: #3d4566;"> <div style="font-weight: 400;font-size: 14px;text-align: left;color: #3d4566;">
<div style="color: red;display: inline-block;">*</div> <div style="color: red;display: inline-block;">*</div>
<span style="font-size: 11px"> 验证码:</span> <span style="font-size: 11px"> Verification Code:</span>
</div> </div>
<div class="input-46" style="margin-top: 12px;"> <div class="input-46" style="margin-top: 12px;">
<el-input placeholder="请输入设备播报的6位数验证码.." v-model="deviceCode" @keyup.enter.native="confirm" /> <el-input placeholder="Please enter the 6-digit code announced by the device.." v-model="deviceCode" @keyup.enter.native="confirm" />
</div> </div>
</div> </div>
<div style="display: flex;margin: 15px 15px;gap: 7px;"> <div style="display: flex;margin: 15px 15px;gap: 7px;">
<div class="dialog-btn" @click="confirm"> <div class="dialog-btn" @click="confirm">
确定 Confirm
</div> </div>
<div class="dialog-btn" style="background: #e6ebff;border: 1px solid #adbdff;color: #5778ff;" @click="cancel"> <div class="dialog-btn" style="background: #e6ebff;border: 1px solid #adbdff;color: #5778ff;" @click="cancel">
取消 Cancel
</div> </div>
</div> </div>
</el-dialog> </el-dialog>
@ -47,7 +47,7 @@ export default {
methods: { methods: {
confirm() { confirm() {
if (!/^\d{6}$/.test(this.deviceCode)) { if (!/^\d{6}$/.test(this.deviceCode)) {
this.$message.error('请输入6位数字验证码'); this.$message.error('Please enter a 6-digit verification code');
return; return;
} }
this.loading = true; this.loading = true;
@ -58,13 +58,13 @@ export default {
if (data.code === 0) { if (data.code === 0) {
this.$emit('refresh'); this.$emit('refresh');
this.$message.success({ this.$message.success({
message: '设备绑定成功', message: 'Device bound successfully',
showClose: true showClose: true
}); });
this.closeDialog(); this.closeDialog();
} else { } else {
this.$message.error({ this.$message.error({
message: data.msg || '绑定失败', message: data.msg || 'Binding failed',
showClose: true showClose: true
}); });
} }

View file

@ -6,23 +6,23 @@
style="width: 40px;height: 40px;border-radius: 50%;background: #5778ff;display: flex;align-items: center;justify-content: center;"> style="width: 40px;height: 40px;border-radius: 50%;background: #5778ff;display: flex;align-items: center;justify-content: center;">
<img loading="lazy" src="@/assets/home/equipment.png" alt="" style="width: 18px;height: 15px;" /> <img loading="lazy" src="@/assets/home/equipment.png" alt="" style="width: 18px;height: 15px;" />
</div> </div>
添加智能体 Add Agent
</div> </div>
<div style="height: 1px;background: #e8f0ff;" /> <div style="height: 1px;background: #e8f0ff;" />
<div style="margin: 22px 15px;"> <div style="margin: 22px 15px;">
<div style="font-weight: 400;text-align: left;color: #3d4566;"> <div style="font-weight: 400;text-align: left;color: #3d4566;">
<div style="color: red;display: inline-block;">*</div> 智能体名称: <div style="color: red;display: inline-block;">*</div> Agent Name:
</div> </div>
<div class="input-46" style="margin-top: 12px;"> <div class="input-46" style="margin-top: 12px;">
<el-input ref="inputRef" placeholder="请输入智能体名称.." v-model="wisdomBodyName" @keyup.enter.native="confirm" /> <el-input ref="inputRef" placeholder="Please enter agent name.." v-model="wisdomBodyName" @keyup.enter.native="confirm" />
</div> </div>
</div> </div>
<div style="display: flex;margin: 15px 15px;gap: 7px;"> <div style="display: flex;margin: 15px 15px;gap: 7px;">
<div class="dialog-btn" @click="confirm"> <div class="dialog-btn" @click="confirm">
确定 Confirm
</div> </div>
<div class="dialog-btn" style="background: #e6ebff;border: 1px solid #adbdff;color: #5778ff;" @click="cancel"> <div class="dialog-btn" style="background: #e6ebff;border: 1px solid #adbdff;color: #5778ff;" @click="cancel">
取消 Cancel
</div> </div>
</div> </div>
</el-dialog> </el-dialog>
@ -50,12 +50,12 @@ export default {
}, },
confirm() { confirm() {
if (!this.wisdomBodyName.trim()) { if (!this.wisdomBodyName.trim()) {
this.$message.error('请输入智能体名称'); this.$message.error('Please enter agent name');
return; return;
} }
Api.agent.addAgent(this.wisdomBodyName, (res) => { Api.agent.addAgent(this.wisdomBodyName, (res) => {
this.$message.success({ this.$message.success({
message: '添加成功', message: 'Added successfully',
showClose: true showClose: true
}); });
this.$emit('confirm', res); this.$emit('confirm', res);

View file

@ -1,9 +1,9 @@
<template> <template>
<el-dialog title="手动添加设备" :visible="visible" @close="handleClose" width="30%" center> <el-dialog title="Manual Add Device" :visible="visible" @close="handleClose" width="30%" center>
<div class="dialog-content"> <div class="dialog-content">
<el-form :model="deviceForm" :rules="rules" ref="deviceForm" label-width="100px"> <el-form :model="deviceForm" :rules="rules" ref="deviceForm" label-width="100px">
<el-form-item label="设备型号" prop="board"> <el-form-item label="Device Model" prop="board">
<el-select v-model="deviceForm.board" placeholder="请选择设备型号" style="width: 100%"> <el-select v-model="deviceForm.board" placeholder="Please select device model" style="width: 100%">
<el-option <el-option
v-for="item in firmwareTypes" v-for="item in firmwareTypes"
:key="item.key" :key="item.key"
@ -12,17 +12,17 @@
</el-option> </el-option>
</el-select> </el-select>
</el-form-item> </el-form-item>
<el-form-item label="固件版本" prop="appVersion"> <el-form-item label="Firmware Ver." prop="appVersion">
<el-input v-model="deviceForm.appVersion" placeholder="请输入固件版本"></el-input> <el-input v-model="deviceForm.appVersion" placeholder="Please enter firmware version"></el-input>
</el-form-item> </el-form-item>
<el-form-item label="Mac地址" prop="macAddress"> <el-form-item label="MAC Address" prop="macAddress">
<el-input v-model="deviceForm.macAddress" placeholder="请输入Mac地址"></el-input> <el-input v-model="deviceForm.macAddress" placeholder="Please enter MAC address"></el-input>
</el-form-item> </el-form-item>
</el-form> </el-form>
</div> </div>
<div style="display: flex;margin: 15px 15px;gap: 7px;"> <div style="display: flex;margin: 15px 15px;gap: 7px;">
<div class="dialog-btn" @click="submitForm">确定</div> <div class="dialog-btn" @click="submitForm">Confirm</div>
<div class="dialog-btn cancel-btn" @click="cancel">取消</div> <div class="dialog-btn cancel-btn" @click="cancel">Cancel</div>
</div> </div>
</el-dialog> </el-dialog>
</template> </template>
@ -41,9 +41,9 @@ export default {
const validateMac = (rule, value, callback) => { const validateMac = (rule, value, callback) => {
const macRegex = /^([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})$/; const macRegex = /^([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})$/;
if (!value) { if (!value) {
callback(new Error('请输入Mac地址')); callback(new Error('Please enter MAC address'));
} else if (!macRegex.test(value)) { } 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 { } else {
callback(); callback();
} }
@ -58,10 +58,10 @@ export default {
firmwareTypes: [], firmwareTypes: [],
rules: { rules: {
board: [ board: [
{ required: true, message: '请选择设备型号', trigger: 'change' } { required: true, message: 'Please select device model', trigger: 'change' }
], ],
appVersion: [ appVersion: [
{ required: true, message: '请输入固件版本', trigger: 'blur' } { required: true, message: 'Please enter firmware version', trigger: 'blur' }
], ],
macAddress: [ macAddress: [
{ required: true, validator: validateMac, trigger: 'blur' } { required: true, validator: validateMac, trigger: 'blur' }
@ -78,8 +78,8 @@ export default {
const res = await Api.dict.getDictDataByType('FIRMWARE_TYPE'); const res = await Api.dict.getDictDataByType('FIRMWARE_TYPE');
this.firmwareTypes = res.data; this.firmwareTypes = res.data;
} catch (error) { } catch (error) {
console.error('获取固件类型失败:', error); console.error('Failed to get firmware types:', error);
this.$message.error(error.message || '获取固件类型失败'); this.$message.error(error.message || 'Failed to get firmware types');
} }
}, },
submitForm() { submitForm() {
@ -97,11 +97,11 @@ export default {
Api.device.manualAddDevice(params, ({ data }) => { Api.device.manualAddDevice(params, ({ data }) => {
if (data.code === 0) { if (data.code === 0) {
this.$message.success('设备添加成功'); this.$message.success('Device added successfully');
this.$emit('refresh'); this.$emit('refresh');
this.closeDialog(); this.closeDialog();
} else { } else {
this.$message.error(data.msg || '添加失败'); this.$message.error(data.msg || 'Failed to add device');
} }
}); });
}, },

View file

@ -73,7 +73,7 @@ const routes = [
path: '/model-config', path: '/model-config',
name: 'ModelConfig', name: 'ModelConfig',
component: function () { component: function () {
return import('../views/modelConfig.vue') return import('../views/ModelConfig.vue')
} }
}, },
{ {

View file

@ -5,9 +5,9 @@
<div class="operation-bar"> <div class="operation-bar">
<h2 class="page-title">Device Management</h2> <h2 class="page-title">Device Management</h2>
<div class="right-operations"> <div class="right-operations">
<el-input placeholder="请输入设备型号或Mac地址查询" v-model="searchKeyword" class="search-input" <el-input placeholder="Enter device model or MAC address to search" v-model="searchKeyword" class="search-input"
@keyup.enter.native="handleSearch" clearable/> @keyup.enter.native="handleSearch" clearable/>
<el-button class="btn-search" @click="handleSearch">搜索</el-button> <el-button class="btn-search" @click="handleSearch">Search</el-button>
</div> </div>
</div> </div>
@ -17,23 +17,23 @@
<el-card class="device-card" shadow="never"> <el-card class="device-card" shadow="never">
<el-table ref="deviceTable" :data="paginatedDeviceList" class="transparent-table" <el-table ref="deviceTable" :data="paginatedDeviceList" class="transparent-table"
:header-cell-class-name="headerCellClassName" v-loading="loading" :header-cell-class-name="headerCellClassName" v-loading="loading"
element-loading-text="拼命加载中" element-loading-text="Loading..."
element-loading-spinner="el-icon-loading" element-loading-background="rgba(255, 255, 255, 0.7)"> element-loading-spinner="el-icon-loading" element-loading-background="rgba(255, 255, 255, 0.7)">
<el-table-column label="选择" align="center" width="120"> <el-table-column label="Select" align="center" width="120">
<template slot-scope="scope"> <template slot-scope="scope">
<el-checkbox v-model="scope.row.selected"></el-checkbox> <el-checkbox v-model="scope.row.selected"></el-checkbox>
</template> </template>
</el-table-column> </el-table-column>
<el-table-column label="设备型号" prop="model" align="center"> <el-table-column label="Device Model" prop="model" align="center">
<template slot-scope="scope"> <template slot-scope="scope">
{{ getFirmwareTypeName(scope.row.model) }} {{ getFirmwareTypeName(scope.row.model) }}
</template> </template>
</el-table-column> </el-table-column>
<el-table-column label="固件版本" prop="firmwareVersion" align="center"></el-table-column> <el-table-column label="Firmware Version" prop="firmwareVersion" align="center"></el-table-column>
<el-table-column label="Mac地址" prop="macAddress" align="center"></el-table-column> <el-table-column label="MAC Address" prop="macAddress" align="center"></el-table-column>
<el-table-column label="绑定时间" prop="bindTime" align="center"></el-table-column> <el-table-column label="Bind Time" prop="bindTime" align="center"></el-table-column>
<el-table-column label="最近对话" prop="lastConversation" align="center"></el-table-column> <el-table-column label="Last Conversation" prop="lastConversation" align="center"></el-table-column>
<el-table-column label="备注" align="center"> <el-table-column label="Remark" align="center">
<template #default="{ row }"> <template #default="{ row }">
<el-input <el-input
v-show="row.isEdit" v-show="row.isEdit"
@ -56,47 +56,50 @@
</span> </span>
</template> </template>
</el-table-column> </el-table-column>
<el-table-column label="OTA升级" align="center"> <el-table-column label="OTA Upgrade" align="center">
<template slot-scope="scope"> <template slot-scope="scope">
<el-switch v-model="scope.row.otaSwitch" size="mini" active-color="#13ce66" inactive-color="#ff4949" <el-switch v-model="scope.row.otaSwitch" size="mini" active-color="#13ce66" inactive-color="#ff4949"
@change="handleOtaSwitchChange(scope.row)"></el-switch> @change="handleOtaSwitchChange(scope.row)"></el-switch>
</template> </template>
</el-table-column> </el-table-column>
<el-table-column label="操作" align="center"> <el-table-column label="Actions" align="center">
<template slot-scope="scope"> <template slot-scope="scope">
<el-button size="mini" type="text" @click="handleUnbind(scope.row.device_id)"> <el-button size="mini" type="text" @click="handleUnbind(scope.row.device_id)">
解绑 Unbind
</el-button> </el-button>
</template> </template>
</el-table-column> </el-table-column>
<template slot="empty">
<span>No toys</span>
</template>
</el-table> </el-table>
<div class="table_bottom"> <div class="table_bottom">
<div class="ctrl_btn"> <div class="ctrl_btn">
<el-button size="mini" type="primary" class="select-all-btn" @click="handleSelectAll"> <el-button size="mini" type="primary" class="select-all-btn" @click="handleSelectAll">
{{ isCurrentPageAllSelected ? '取消全选' : '全选' }} {{ isCurrentPageAllSelected ? 'Deselect All' : 'Select All' }}
</el-button> </el-button>
<el-button type="success" size="mini" class="add-device-btn" @click="handleAddDevice"> <el-button type="success" size="mini" class="add-device-btn" @click="handleAddDevice">
验证码绑定 Bind with Code
</el-button> </el-button>
<el-button type="success" size="mini" class="add-device-btn" @click="handleManualAddDevice"> <el-button type="success" size="mini" class="add-device-btn" @click="handleManualAddDevice">
手动添加 Manual Add
</el-button> </el-button>
<el-button size="mini" type="danger" icon="el-icon-delete" @click="deleteSelected">解绑</el-button> <el-button size="mini" type="danger" icon="el-icon-delete" @click="deleteSelected">Unbind</el-button>
</div> </div>
<div class="custom-pagination"> <div class="custom-pagination">
<el-select v-model="pageSize" @change="handlePageSizeChange" class="page-size-select"> <el-select v-model="pageSize" @change="handlePageSizeChange" class="page-size-select">
<el-option v-for="item in pageSizeOptions" :key="item" :label="`${item}条/页`" :value="item"> <el-option v-for="item in pageSizeOptions" :key="item" :label="`${item} items/page`" :value="item">
</el-option> </el-option>
</el-select> </el-select>
<button class="pagination-btn" :disabled="currentPage === 1" @click="goFirst">首页</button> <button class="pagination-btn" :disabled="currentPage === 1" @click="goFirst">First</button>
<button class="pagination-btn" :disabled="currentPage === 1" @click="goPrev">上一页</button> <button class="pagination-btn" :disabled="currentPage === 1" @click="goPrev">Previous</button>
<button v-for="page in visiblePages" :key="page" class="pagination-btn" <button v-for="page in visiblePages" :key="page" class="pagination-btn"
:class="{ active: page === currentPage }" @click="goToPage(page)"> :class="{ active: page === currentPage }" @click="goToPage(page)">
{{ page }} {{ page }}
</button> </button>
<button class="pagination-btn" :disabled="currentPage === pageCount" @click="goNext">下一页</button> <button class="pagination-btn" :disabled="currentPage === pageCount" @click="goNext">Next</button>
<span class="total-text">共{{ deviceList.length }}条记录</span> <span class="total-text">Total {{ deviceList.length }} records</span>
</div> </div>
</div> </div>
</el-card> </el-card>
@ -194,8 +197,8 @@ export default {
const res = await Api.dict.getDictDataByType('FIRMWARE_TYPE') const res = await Api.dict.getDictDataByType('FIRMWARE_TYPE')
this.firmwareTypes = res.data this.firmwareTypes = res.data
} catch (error) { } catch (error) {
console.error('获取固件类型失败:', error) console.error('Failed to get firmware types:', error)
this.$message.error(error.message || '获取固件类型失败') this.$message.error(error.message || 'Failed to get firmware types')
} }
}, },
handlePageSizeChange(val) { handlePageSizeChange(val) {
@ -218,15 +221,15 @@ export default {
const selectedDevices = this.paginatedDeviceList.filter(device => device.selected); const selectedDevices = this.paginatedDeviceList.filter(device => device.selected);
if (selectedDevices.length === 0) { if (selectedDevices.length === 0) {
this.$message.warning({ this.$message.warning({
message: '请至少选择一条记录', message: 'Please select at least one record',
showClose: true showClose: true
}); });
return; return;
} }
this.$confirm(`确认要解绑选中的 ${selectedDevices.length} 台设备吗?`, '警告', { this.$confirm(`Are you sure you want to unbind ${selectedDevices.length} selected device(s)?`, 'Warning', {
confirmButtonText: '确定', confirmButtonText: 'Confirm',
cancelButtonText: '取消', cancelButtonText: 'Cancel',
type: 'warning' type: 'warning'
}).then(() => { }).then(() => {
const deviceIds = selectedDevices.map(device => device.device_id); const deviceIds = selectedDevices.map(device => device.device_id);
@ -240,7 +243,7 @@ export default {
if (data.code === 0) { if (data.code === 0) {
resolve(); resolve();
} else { } else {
reject(data.msg || '解绑失败'); reject(data.msg || 'Unbind failed');
} }
}); });
}); });
@ -248,14 +251,14 @@ export default {
Promise.all(promises) Promise.all(promises)
.then(() => { .then(() => {
this.$message.success({ this.$message.success({
message: `成功解绑 ${deviceIds.length} 台设备`, message: `Successfully unbound ${deviceIds.length} device(s)`,
showClose: true showClose: true
}); });
this.fetchBindDevices(this.currentAgentId); this.fetchBindDevices(this.currentAgentId);
}) })
.catch(error => { .catch(error => {
this.$message.error({ this.$message.error({
message: error || '批量解绑过程中出现错误', message: error || 'Error occurred during batch unbinding',
showClose: true showClose: true
}); });
}); });
@ -271,7 +274,7 @@ export default {
const text = (row.remark || '').trim(); const text = (row.remark || '').trim();
if (text.length > 64) { if (text.length > 64) {
this.$message.warning('备注不能超过 64 字符'); this.$message.warning('Remark cannot exceed 64 characters');
return; return;
} }
if (text === row._originalRemark) { if (text === row._originalRemark) {
@ -282,10 +285,10 @@ export default {
this.updateDeviceInfo(row.device_id, { alias: text }, (ok, resp) => { this.updateDeviceInfo(row.device_id, { alias: text }, (ok, resp) => {
if (ok) { if (ok) {
row._originalRemark = text; row._originalRemark = text;
this.$message.success('备注已保存'); this.$message.success('Remark saved');
} else { } else {
row.remark = row._originalRemark; row.remark = row._originalRemark;
this.$message.error(resp.msg || '备注保存失败'); this.$message.error(resp.msg || 'Failed to save remark');
} }
row._submitting = false; row._submitting = false;
}); });
@ -303,21 +306,21 @@ export default {
this.submitRemark(row); this.submitRemark(row);
}, },
handleUnbind(device_id) { handleUnbind(device_id) {
this.$confirm('确认要解绑该设备吗?', '警告', { this.$confirm('Are you sure you want to unbind this device?', 'Warning', {
confirmButtonText: '确定', confirmButtonText: 'Confirm',
cancelButtonText: '取消', cancelButtonText: 'Cancel',
type: 'warning' type: 'warning'
}).then(() => { }).then(() => {
Api.device.unbindDevice(device_id, ({data}) => { Api.device.unbindDevice(device_id, ({data}) => {
if (data.code === 0) { if (data.code === 0) {
this.$message.success({ this.$message.success({
message: '设备解绑成功', message: 'Device unbound successfully',
showClose: true showClose: true
}); });
this.fetchBindDevices(this.$route.query.agentId); this.fetchBindDevices(this.$route.query.agentId);
} else { } else {
this.$message.error({ this.$message.error({
message: data.msg || '设备解绑失败', message: data.msg || 'Failed to unbind device',
showClose: true showClose: true
}); });
} }
@ -363,7 +366,7 @@ export default {
this.activeSearchKeyword = ""; this.activeSearchKeyword = "";
this.searchKeyword = ""; this.searchKeyword = "";
} else { } else {
this.$message.error(data.msg || '获取设备列表失败'); this.$message.error(data.msg || 'Failed to get device list');
} }
}); });
}, },
@ -385,11 +388,11 @@ export default {
handleOtaSwitchChange(row) { handleOtaSwitchChange(row) {
this.updateDeviceInfo(row.device_id, {autoUpdate: row.otaSwitch ? 1 : 0}, (result, {msg}) => { this.updateDeviceInfo(row.device_id, {autoUpdate: row.otaSwitch ? 1 : 0}, (result, {msg}) => {
if (result) { if (result) {
this.$message.success(row.otaSwitch ? '已设置成自动升级' : '已关闭自动升级'); this.$message.success(row.otaSwitch ? 'Auto-upgrade enabled' : 'Auto-upgrade disabled');
return; return;
} }
row.otaSwitch = !row.otaSwitch row.otaSwitch = !row.otaSwitch
this.$message.error(msg || '操作失败') this.$message.error(msg || 'Operation failed')
}) })
}, },
} }

View file

@ -30,6 +30,14 @@ async def send_mcp_message(conn, payload: dict):
async def handle_mcp_message(conn, mcp_client, payload: dict): async def handle_mcp_message(conn, mcp_client, payload: dict):
"""Handle MCP messages, including initialization, tool list and tool call responses""" """Handle MCP messages, including initialization, tool list and tool call responses"""
logger.bind(tag=TAG).info(f"Handling MCP message: {str(payload)[:100]}") 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): if not isinstance(payload, dict):
logger.bind(tag=TAG).error( logger.bind(tag=TAG).error(
@ -51,12 +59,56 @@ async def handle_mcp_message(conn, mcp_client, payload: dict):
if msg_id == 1: # mcpInitializeID if msg_id == 1: # mcpInitializeID
logger.bind(tag=TAG).debug("Received MCP initialization response") 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): if isinstance(server_info, dict):
name = server_info.get("name") name = server_info.get("name", "unknown")
version = server_info.get("version") 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( 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 return