init: 第一个版本
这个提交包含在:
430
DESIGN.MD
普通文件
430
DESIGN.MD
普通文件
@ -0,0 +1,430 @@
|
||||
# 机械臂控制助手 - 完整设计方案
|
||||
|
||||
## 1. 项目概述
|
||||
|
||||
机械臂控制助手是一个基于Web的实时机械臂控制与可视化工具。系统由Vue3前端控制界面和Python模拟后端组成,通过WebSocket实现双向通信,提供直观的3D可视化控制体验。
|
||||
|
||||
## 2. 技术栈选型
|
||||
|
||||
### 前端
|
||||
- **框架**: Vite + Vue3 (组合式API)
|
||||
- **3D渲染**: Three.js (r128+)
|
||||
- **UI组件**: Naive UI / Element Plus (滑块组件)
|
||||
- **WebSocket**: 原生WebSocket + 重连机制
|
||||
- **状态管理**: Pinia
|
||||
- **HTTP请求**: Axios
|
||||
|
||||
### 后端
|
||||
- **框架**: FastAPI / Flask + WebSocket
|
||||
- **模拟数据**: 预定义机械臂配置
|
||||
- **跨域**: CORS中间件
|
||||
|
||||
## 3. 系统架构
|
||||
|
||||
```
|
||||
┌─────────────────┐ WebSocket ┌─────────────────┐
|
||||
│ │ ◄──────────────► │ │
|
||||
│ Vue3前端应用 │ JSON协议 │ Python模拟后端 │
|
||||
│ │ │ │
|
||||
└────────┬────────┘ └─────────────────┘
|
||||
│
|
||||
┌────┴────┐
|
||||
│ Three.js│
|
||||
│ 3D场景 │
|
||||
└─────────┘
|
||||
```
|
||||
|
||||
## 4. 前端详细设计
|
||||
|
||||
### 4.1 目录结构
|
||||
```
|
||||
src/
|
||||
├── components/
|
||||
│ ├── ControlPanel.vue # 控制面板
|
||||
│ ├── ThreeViewer.vue # 3D可视化组件
|
||||
│ ├── JointSlider.vue # 关节滑块组件
|
||||
│ └── ConnectionBar.vue # 连接状态栏
|
||||
├── composables/
|
||||
│ └── useWebSocket.ts # WebSocket组合式函数
|
||||
├── stores/
|
||||
│ └── robotStore.ts # Pinia状态管理
|
||||
├── types/
|
||||
│ └── ws.d.ts # TypeScript类型定义
|
||||
├── utils/
|
||||
│ ├── robotBuilder.ts # 机械臂模型构建
|
||||
│ └── kinematics.ts # 运动学计算
|
||||
└── App.vue
|
||||
```
|
||||
|
||||
### 4.2 核心状态管理 (robotStore.ts)
|
||||
|
||||
```typescript
|
||||
import { defineStore } from 'pinia'
|
||||
import type { InitResponse, Joint, MoveRequest } from '@/types/ws'
|
||||
|
||||
interface RobotState {
|
||||
robotId: string | null
|
||||
joints: Map<string, Joint & { currentAngle: number }>
|
||||
connectionStatus: 'disconnected' | 'connecting' | 'connected'
|
||||
selectedJoint: string | null
|
||||
}
|
||||
|
||||
export const useRobotStore = defineStore('robot', {
|
||||
state: (): RobotState => ({
|
||||
robotId: null,
|
||||
joints: new Map(),
|
||||
connectionStatus: 'disconnected',
|
||||
selectedJoint: null
|
||||
}),
|
||||
|
||||
getters: {
|
||||
jointList: (state) => Array.from(state.joints.values()),
|
||||
jointCount: (state) => state.joints.size
|
||||
},
|
||||
|
||||
actions: {
|
||||
updateJointAngle(jointId: string, angle: number) {
|
||||
const joint = this.joints.get(jointId)
|
||||
if (joint) {
|
||||
joint.currentAngle = this.clampAngle(angle, joint.range)
|
||||
}
|
||||
},
|
||||
|
||||
clampAngle(angle: number, range: number[]): number {
|
||||
return Math.min(Math.max(angle, range[0]), range[1])
|
||||
}
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
### 4.3 WebSocket通信封装 (useWebSocket.ts)
|
||||
|
||||
```typescript
|
||||
import { ref } from 'vue'
|
||||
import type { InitResponse, MoveRequest } from '@/types/ws'
|
||||
|
||||
export function useWebSocket() {
|
||||
const ws = ref<WebSocket | null>(null)
|
||||
const isConnected = ref(false)
|
||||
const error = ref<string | null>(null)
|
||||
|
||||
const connect = (url: string) => {
|
||||
ws.value = new WebSocket(url)
|
||||
|
||||
ws.value.onopen = () => {
|
||||
isConnected.value = true
|
||||
error.value = null
|
||||
}
|
||||
|
||||
ws.value.onmessage = (event) => {
|
||||
try {
|
||||
const data: InitResponse = JSON.parse(event.data)
|
||||
handleInitMessage(data)
|
||||
} catch (e) {
|
||||
error.value = '消息解析失败'
|
||||
}
|
||||
}
|
||||
|
||||
ws.value.onclose = () => {
|
||||
isConnected.value = false
|
||||
// 自动重连逻辑
|
||||
setTimeout(() => reconnect(url), 3000)
|
||||
}
|
||||
}
|
||||
|
||||
const sendMoveCommand = (jointId: string, angle: number) => {
|
||||
if (ws.value?.readyState === WebSocket.OPEN) {
|
||||
const command: MoveRequest = { id: jointId, angel: angle }
|
||||
ws.value.send(JSON.stringify(command))
|
||||
}
|
||||
}
|
||||
|
||||
return { connect, sendMoveCommand, isConnected, error }
|
||||
}
|
||||
```
|
||||
|
||||
### 4.4 3D可视化实现
|
||||
|
||||
#### 关节类型映射
|
||||
- **flex_w (水平旋转底座)**: 绕Y轴旋转的圆柱体
|
||||
- **flex_v (垂直旋转底座)**: 绕X/Z轴旋转的立方体
|
||||
- **joint (一般关节)**: 带旋转范围的连杆
|
||||
- **gripper (夹爪)**: 两个可开合的夹持部件
|
||||
|
||||
#### 坐标系统
|
||||
- 使用右手坐标系,Y轴向上
|
||||
- 每个关节基于前一个关节的末端位置构建
|
||||
- 通过`next`属性构建关节链
|
||||
|
||||
## 5. 后端模拟服务 (Python)
|
||||
|
||||
### 5.1 项目结构
|
||||
```
|
||||
mock-server/
|
||||
├── main.py # 主服务入口
|
||||
├── robot_config.py # 预定义机械臂配置
|
||||
├── websocket_handler.py # WebSocket处理
|
||||
└── requirements.txt # 依赖
|
||||
```
|
||||
|
||||
### 5.2 预定义机械臂配置 (robot_config.py)
|
||||
|
||||
```python
|
||||
from typing import List, Dict, Any
|
||||
|
||||
# 6轴工业机械臂示例配置
|
||||
SIX_AXIS_ROBOT = {
|
||||
"id": "robot_6dof_001",
|
||||
"joints": [
|
||||
{
|
||||
"id": "base",
|
||||
"range": [-180, 180],
|
||||
"default": 0,
|
||||
"type": "flex_w",
|
||||
"next": "shoulder"
|
||||
},
|
||||
{
|
||||
"id": "shoulder",
|
||||
"range": [-90, 90],
|
||||
"default": 45,
|
||||
"type": "joint",
|
||||
"next": "elbow"
|
||||
},
|
||||
{
|
||||
"id": "elbow",
|
||||
"range": [-135, 135],
|
||||
"default": -30,
|
||||
"type": "joint",
|
||||
"next": "wrist1"
|
||||
},
|
||||
{
|
||||
"id": "wrist1",
|
||||
"range": [-180, 180],
|
||||
"default": 0,
|
||||
"type": "flex_v",
|
||||
"next": "wrist2"
|
||||
},
|
||||
{
|
||||
"id": "wrist2",
|
||||
"range": [-90, 90],
|
||||
"default": 0,
|
||||
"type": "flex_v",
|
||||
"next": "gripper"
|
||||
},
|
||||
{
|
||||
"id": "gripper",
|
||||
"range": [0, 100],
|
||||
"default": 50,
|
||||
"type": "gripper",
|
||||
"next": None
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
# SCARA机器人示例配置
|
||||
SCARA_ROBOT = {
|
||||
"id": "scara_001",
|
||||
"joints": [
|
||||
{
|
||||
"id": "waist",
|
||||
"range": [-170, 170],
|
||||
"default": 0,
|
||||
"type": "flex_w",
|
||||
"next": "arm1"
|
||||
},
|
||||
{
|
||||
"id": "arm1",
|
||||
"range": [-150, 150],
|
||||
"default": 30,
|
||||
"type": "joint",
|
||||
"next": "arm2"
|
||||
},
|
||||
{
|
||||
"id": "arm2",
|
||||
"range": [-150, 150],
|
||||
"default": -45,
|
||||
"type": "joint",
|
||||
"next": "wrist"
|
||||
},
|
||||
{
|
||||
"id": "wrist",
|
||||
"range": [-360, 360],
|
||||
"default": 0,
|
||||
"type": "flex_v",
|
||||
"next": "gripper"
|
||||
},
|
||||
{
|
||||
"id": "gripper",
|
||||
"range": [0, 100],
|
||||
"default": 30,
|
||||
"type": "gripper",
|
||||
"next": None
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
### 5.3 WebSocket服务实现 (main.py)
|
||||
|
||||
```python
|
||||
from fastapi import FastAPI, WebSocket, WebSocketDisconnect
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
import asyncio
|
||||
import json
|
||||
import random
|
||||
from robot_config import SIX_AXIS_ROBOT, SCARA_ROBOT
|
||||
|
||||
app = FastAPI()
|
||||
|
||||
# 配置CORS
|
||||
app.add_middleware(
|
||||
CORSMiddleware,
|
||||
allow_origins=["*"],
|
||||
allow_credentials=True,
|
||||
allow_methods=["*"],
|
||||
allow_headers=["*"],
|
||||
)
|
||||
|
||||
# 存储当前连接的机械臂配置
|
||||
active_robots = {}
|
||||
|
||||
@app.websocket("/ws/{robot_type}")
|
||||
async def websocket_endpoint(websocket: WebSocket, robot_type: str = "six_axis"):
|
||||
await websocket.accept()
|
||||
|
||||
# 根据请求类型选择机械臂配置
|
||||
if robot_type == "scara":
|
||||
robot_config = SCARA_ROBOT
|
||||
else:
|
||||
robot_config = SIX_AXIS_ROBOT
|
||||
|
||||
# 发送初始化配置
|
||||
await websocket.send_json(robot_config)
|
||||
|
||||
# 记录当前关节状态
|
||||
joint_states = {joint["id"]: joint["default"]
|
||||
for joint in robot_config["joints"]}
|
||||
|
||||
try:
|
||||
while True:
|
||||
# 接收前端消息
|
||||
message = await websocket.receive_text()
|
||||
data = json.loads(message)
|
||||
|
||||
# 处理移动请求
|
||||
if "id" in data and "angel" in data:
|
||||
joint_id = data["id"]
|
||||
target_angle = data["angel"]
|
||||
|
||||
# 验证关节是否存在
|
||||
if joint_id in joint_states:
|
||||
joint_states[joint_id] = target_angle
|
||||
|
||||
# 模拟响应(可选:发送确认)
|
||||
await websocket.send_json({
|
||||
"type": "move_ack",
|
||||
"joint": joint_id,
|
||||
"angle": target_angle,
|
||||
"status": "success"
|
||||
})
|
||||
|
||||
except WebSocketDisconnect:
|
||||
print(f"Client disconnected for robot: {robot_type}")
|
||||
except Exception as e:
|
||||
print(f"Error: {e}")
|
||||
|
||||
@app.get("/api/robots")
|
||||
async def get_robot_list():
|
||||
"""返回可用的机械臂类型列表"""
|
||||
return {
|
||||
"robots": [
|
||||
{"id": "six_axis", "name": "6轴工业机械臂"},
|
||||
{"id": "scara", "name": "SCARA机器人"}
|
||||
]
|
||||
}
|
||||
|
||||
if __name__ == "__main__":
|
||||
import uvicorn
|
||||
uvicorn.run(app, host="0.0.0.0", port=8000)
|
||||
```
|
||||
|
||||
### 5.4 依赖文件 (requirements.txt)
|
||||
|
||||
```
|
||||
fastapi==0.104.1
|
||||
uvicorn[standard]==0.24.0
|
||||
websockets==12.0
|
||||
python-multipart==0.0.6
|
||||
```
|
||||
|
||||
## 6. 界面布局设计
|
||||
|
||||
### 控制区 (左侧/顶部)
|
||||
- **连接栏**: WebSocket URL输入框 + 连接/断开按钮
|
||||
- **状态指示**: 连接状态、机器人ID
|
||||
- **关节控制面板**:
|
||||
- 按关节类型分组显示
|
||||
- 滑块组件显示当前角度/范围
|
||||
- 数值输入框
|
||||
- 复位按钮
|
||||
- 夹爪控制特殊样式
|
||||
|
||||
### 演示区 (右侧/主要区域)
|
||||
- **3D画布**: 全尺寸Three.js渲染
|
||||
- **辅助工具**:
|
||||
- 坐标系显示
|
||||
- 网格地面
|
||||
- 视角控制(旋转/缩放/平移)
|
||||
- 关节高亮选择
|
||||
|
||||
## 7. 实现要点
|
||||
|
||||
### 7.1 关节树构建
|
||||
```typescript
|
||||
// 根据joints数组和next关系构建树状结构
|
||||
function buildJointTree(joints: Joint[]): JointNode {
|
||||
const jointMap = new Map(joints.map(j => [j.id, j]))
|
||||
// 找到根节点(没有其他节点指向的节点)
|
||||
// 构建层级关系
|
||||
}
|
||||
```
|
||||
|
||||
### 7.2 运动学模拟
|
||||
- 使用DH参数法进行正向运动学计算
|
||||
- 可视化时采用递推变换矩阵
|
||||
- 夹爪单独处理开合动画
|
||||
|
||||
### 7.3 性能优化
|
||||
- 使用requestAnimationFrame进行动画更新
|
||||
- 滑块防抖处理,避免频繁发送WebSocket消息
|
||||
- Three.js模型复用和实例化
|
||||
|
||||
## 8. 启动与部署
|
||||
|
||||
### 前端启动
|
||||
```bash
|
||||
yarn install
|
||||
yarn run dev
|
||||
```
|
||||
|
||||
### 后端启动
|
||||
```bash
|
||||
cd mock-server
|
||||
pip install -r requirements.txt
|
||||
python main.py
|
||||
# 服务运行在 http://localhost:8000
|
||||
```
|
||||
|
||||
### 访问应用
|
||||
- 前端: http://localhost:5173
|
||||
- WebSocket连接地址: ws://localhost:8000/ws/six_axis 或 ws://localhost:8000/ws/scara
|
||||
|
||||
## 9. 扩展可能性
|
||||
|
||||
1. **MoveAction响应**: 添加真实的运动学计算库
|
||||
2. **多机械臂支持**: 同时连接和控制多个机械臂
|
||||
3. **轨迹录制**: 记录和回放关节运动序列
|
||||
4. **碰撞检测**: 添加简单的自碰撞检测
|
||||
5. **导出配置**: 将当前关节状态导出为配置文件
|
||||
|
||||
这个设计方案提供了一个完整的机械臂控制助手实现框架,前后端分离,便于开发和测试。模拟后端支持多种机械臂配置,无需真实硬件即可演示完整的控制流程。
|
||||
145
README.md
普通文件
145
README.md
普通文件
@ -0,0 +1,145 @@
|
||||
# 机械臂控制助手
|
||||
|
||||
基于Web的实时机械臂控制与可视化工具,使用Vue3 + Three.js前端和FastAPI模拟后端。
|
||||
|
||||
## 功能特性
|
||||
|
||||
- 🎮 实时机械臂控制界面
|
||||
- 🎯 3D可视化机械臂模型
|
||||
- 🔗 WebSocket双向通信
|
||||
- 📊 关节角度精确控制
|
||||
- 🎨 直观的用户界面
|
||||
- 🔄 自动重连机制
|
||||
|
||||
## 技术栈
|
||||
|
||||
### 前端
|
||||
- Vue 3 (组合式API)
|
||||
- TypeScript
|
||||
- Three.js (3D渲染)
|
||||
- Pinia (状态管理)
|
||||
- Vite (构建工具)
|
||||
|
||||
### 后端
|
||||
- FastAPI (WebSocket服务)
|
||||
- Python 3.8+
|
||||
|
||||
## 项目结构
|
||||
|
||||
```
|
||||
WSRobotClient/
|
||||
├── frontend/ # Vue3前端应用
|
||||
│ ├── src/
|
||||
│ │ ├── components/ # Vue组件
|
||||
│ │ ├── composables/ # 组合式函数
|
||||
│ │ ├── stores/ # Pinia状态管理
|
||||
│ │ ├── types/ # TypeScript类型定义
|
||||
│ │ └── App.vue # 主应用组件
|
||||
│ └── package.json
|
||||
├── mock-server/ # Python模拟后端
|
||||
│ ├── main.py # FastAPI服务
|
||||
│ ├── robot_config.py # 机械臂配置
|
||||
│ └── requirements.txt # Python依赖
|
||||
├── DESIGN.MD # 详细设计方案
|
||||
└── README.md # 项目说明
|
||||
```
|
||||
|
||||
## 快速开始
|
||||
|
||||
### 1. 启动后端服务
|
||||
|
||||
```bash
|
||||
cd mock-server
|
||||
pip install -r requirements.txt
|
||||
python main.py
|
||||
```
|
||||
|
||||
后端服务将在 http://localhost:8000 启动。
|
||||
|
||||
### 2. 启动前端应用
|
||||
|
||||
```bash
|
||||
cd frontend
|
||||
npm install
|
||||
npm run dev
|
||||
```
|
||||
|
||||
前端应用将在 http://localhost:5173 启动。
|
||||
|
||||
### 3. 访问应用
|
||||
|
||||
1. 打开浏览器访问 http://localhost:5173
|
||||
2. 在连接栏输入WebSocket URL: `ws://localhost:8000/ws/six_axis`
|
||||
3. 点击"连接"按钮
|
||||
4. 开始控制机械臂
|
||||
|
||||
## 使用说明
|
||||
|
||||
### 连接设置
|
||||
- **WebSocket URL**: 后端WebSocket服务地址
|
||||
- **机械臂类型**: 选择6轴工业机械臂或SCARA机器人
|
||||
|
||||
### 控制面板
|
||||
- **关节控制**: 每个关节都有滑块和数值输入
|
||||
- **关节类型**:
|
||||
- 水平旋转底座 (flex_w)
|
||||
- 垂直旋转底座 (flex_v)
|
||||
- 一般关节 (joint)
|
||||
- 夹爪 (gripper)
|
||||
- **复位功能**: 可将关节角度重置为默认值
|
||||
|
||||
### 3D可视化
|
||||
- **交互控制**: 鼠标拖拽旋转视角,滚轮缩放
|
||||
- **关节选择**: 点击控制面板中的关节可高亮显示
|
||||
- **实时更新**: 关节角度变化实时反映在3D模型中
|
||||
|
||||
## 机械臂配置
|
||||
|
||||
### 6轴工业机械臂
|
||||
- base: 底座水平旋转 (-180° ~ 180°)
|
||||
- shoulder: 肩关节 (-90° ~ 90°)
|
||||
- elbow: 肘关节 (-135° ~ 135°)
|
||||
- wrist1: 腕关节1 (-180° ~ 180°)
|
||||
- wrist2: 腕关节2 (-90° ~ 90°)
|
||||
- gripper: 夹爪 (0 ~ 100%)
|
||||
|
||||
### SCARA机器人
|
||||
- waist: 腰部旋转 (-170° ~ 170°)
|
||||
- arm1: 臂1关节 (-150° ~ 150°)
|
||||
- arm2: 臂2关节 (-150° ~ 150°)
|
||||
- wrist: 腕关节 (-360° ~ 360°)
|
||||
- gripper: 夹爪 (0 ~ 100%)
|
||||
|
||||
## 开发指南
|
||||
|
||||
### 前端开发
|
||||
```bash
|
||||
cd frontend
|
||||
npm run dev # 开发模式
|
||||
npm run build # 生产构建
|
||||
npm run preview # 预览构建结果
|
||||
```
|
||||
|
||||
### 后端开发
|
||||
```bash
|
||||
cd mock-server
|
||||
python main.py # 启动开发服务器
|
||||
```
|
||||
|
||||
### 添加新的机械臂配置
|
||||
1. 在 `mock-server/robot_config.py` 中添加新的配置
|
||||
2. 更新 `mock-server/main.py` 中的机器人类型映射
|
||||
3. 在前端 `ConnectionBar.vue` 中添加对应的选项
|
||||
|
||||
## 扩展功能
|
||||
|
||||
计划中的扩展功能:
|
||||
1. **轨迹录制**: 记录和回放关节运动序列
|
||||
2. **碰撞检测**: 添加简单的自碰撞检测
|
||||
3. **多机械臂支持**: 同时控制多个机械臂
|
||||
4. **导出配置**: 将当前状态导出为配置文件
|
||||
5. **真实硬件对接**: 支持真实机械臂控制
|
||||
|
||||
## 许可证
|
||||
|
||||
MIT License
|
||||
39
frontend/.gitignore
vendored
普通文件
39
frontend/.gitignore
vendored
普通文件
@ -0,0 +1,39 @@
|
||||
# Logs
|
||||
logs
|
||||
*.log
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
pnpm-debug.log*
|
||||
lerna-debug.log*
|
||||
|
||||
node_modules
|
||||
.DS_Store
|
||||
dist
|
||||
dist-ssr
|
||||
coverage
|
||||
*.local
|
||||
|
||||
# Editor directories and files
|
||||
.vscode/*
|
||||
!.vscode/extensions.json
|
||||
.idea
|
||||
*.suo
|
||||
*.ntvs*
|
||||
*.njsproj
|
||||
*.sln
|
||||
*.sw?
|
||||
|
||||
*.tsbuildinfo
|
||||
|
||||
.eslintcache
|
||||
|
||||
# Cypress
|
||||
/cypress/videos/
|
||||
/cypress/screenshots/
|
||||
|
||||
# Vitest
|
||||
__screenshots__/
|
||||
|
||||
# Vite
|
||||
*.timestamp-*-*.mjs
|
||||
3
frontend/.vscode/extensions.json
vendored
普通文件
3
frontend/.vscode/extensions.json
vendored
普通文件
@ -0,0 +1,3 @@
|
||||
{
|
||||
"recommendations": ["Vue.volar"]
|
||||
}
|
||||
42
frontend/README.md
普通文件
42
frontend/README.md
普通文件
@ -0,0 +1,42 @@
|
||||
# frontend
|
||||
|
||||
This template should help get you started developing with Vue 3 in Vite.
|
||||
|
||||
## Recommended IDE Setup
|
||||
|
||||
[VS Code](https://code.visualstudio.com/) + [Vue (Official)](https://marketplace.visualstudio.com/items?itemName=Vue.volar) (and disable Vetur).
|
||||
|
||||
## Recommended Browser Setup
|
||||
|
||||
- Chromium-based browsers (Chrome, Edge, Brave, etc.):
|
||||
- [Vue.js devtools](https://chromewebstore.google.com/detail/vuejs-devtools/nhdogjmejiglipccpnnnanhbledajbpd)
|
||||
- [Turn on Custom Object Formatter in Chrome DevTools](http://bit.ly/object-formatters)
|
||||
- Firefox:
|
||||
- [Vue.js devtools](https://addons.mozilla.org/en-US/firefox/addon/vue-js-devtools/)
|
||||
- [Turn on Custom Object Formatter in Firefox DevTools](https://fxdx.dev/firefox-devtools-custom-object-formatters/)
|
||||
|
||||
## Type Support for `.vue` Imports in TS
|
||||
|
||||
TypeScript cannot handle type information for `.vue` imports by default, so we replace the `tsc` CLI with `vue-tsc` for type checking. In editors, we need [Volar](https://marketplace.visualstudio.com/items?itemName=Vue.volar) to make the TypeScript language service aware of `.vue` types.
|
||||
|
||||
## Customize configuration
|
||||
|
||||
See [Vite Configuration Reference](https://vite.dev/config/).
|
||||
|
||||
## Project Setup
|
||||
|
||||
```sh
|
||||
npm install
|
||||
```
|
||||
|
||||
### Compile and Hot-Reload for Development
|
||||
|
||||
```sh
|
||||
npm run dev
|
||||
```
|
||||
|
||||
### Type-Check, Compile and Minify for Production
|
||||
|
||||
```sh
|
||||
npm run build
|
||||
```
|
||||
1
frontend/env.d.ts
vendored
普通文件
1
frontend/env.d.ts
vendored
普通文件
@ -0,0 +1 @@
|
||||
/// <reference types="vite/client" />
|
||||
13
frontend/index.html
普通文件
13
frontend/index.html
普通文件
@ -0,0 +1,13 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<link rel="icon" href="/favicon.ico">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Vite App</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
<script type="module" src="/src/main.ts"></script>
|
||||
</body>
|
||||
</html>
|
||||
4020
frontend/package-lock.json
自动生成的
普通文件
4020
frontend/package-lock.json
自动生成的
普通文件
文件差异内容过多而无法显示
加载差异
37
frontend/package.json
普通文件
37
frontend/package.json
普通文件
@ -0,0 +1,37 @@
|
||||
{
|
||||
"name": "frontend",
|
||||
"version": "0.0.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "run-p type-check \"build-only {@}\" --",
|
||||
"preview": "vite preview",
|
||||
"build-only": "vite build",
|
||||
"type-check": "vue-tsc --build"
|
||||
},
|
||||
"dependencies": {
|
||||
"@types/three": "^0.183.1",
|
||||
"axios": "^1.13.6",
|
||||
"element-plus": "^2.13.5",
|
||||
"naive-ui": "^2.44.1",
|
||||
"pinia": "^3.0.4",
|
||||
"three": "^0.183.2",
|
||||
"vue": "^3.5.29",
|
||||
"vue-router": "^5.0.3"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@tsconfig/node24": "^24.0.4",
|
||||
"@types/node": "^24.11.0",
|
||||
"@vitejs/plugin-vue": "^6.0.4",
|
||||
"@vue/tsconfig": "^0.8.1",
|
||||
"npm-run-all2": "^8.0.4",
|
||||
"typescript": "~5.9.3",
|
||||
"vite": "^7.3.1",
|
||||
"vite-plugin-vue-devtools": "^8.0.6",
|
||||
"vue-tsc": "^3.2.5"
|
||||
},
|
||||
"engines": {
|
||||
"node": "^20.19.0 || >=22.12.0"
|
||||
}
|
||||
}
|
||||
二进制
frontend/public/favicon.ico
普通文件
二进制
frontend/public/favicon.ico
普通文件
二进制文件未显示。
|
之后 宽度: | 高度: | 大小: 4.2 KiB |
59
frontend/src/App.vue
普通文件
59
frontend/src/App.vue
普通文件
@ -0,0 +1,59 @@
|
||||
<script setup lang="ts">
|
||||
import { onMounted } from 'vue'
|
||||
import ConnectionBar from './components/ConnectionBar.vue'
|
||||
import ControlPanel from './components/ControlPanel.vue'
|
||||
import ThreeViewer from './components/ThreeViewer.vue'
|
||||
import { useWebSocket } from './composables/useWebSocket'
|
||||
import { useRobotStore } from './stores/robot'
|
||||
|
||||
// 初始化WebSocket和store的集成
|
||||
const { sendMoveCommand, isConnected } = useWebSocket()
|
||||
const robotStore = useRobotStore()
|
||||
|
||||
// 将WebSocket功能注入到store中
|
||||
onMounted(() => {
|
||||
robotStore.setWebSocketFunctions({
|
||||
sendMoveCommand,
|
||||
isConnected
|
||||
})
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="app">
|
||||
<ConnectionBar class="connection-bar" />
|
||||
|
||||
<div class="main-content">
|
||||
<ControlPanel class="control-panel" />
|
||||
<ThreeViewer class="three-viewer" />
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.app {
|
||||
height: 100vh;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
background: #f5f5f5;
|
||||
}
|
||||
|
||||
.connection-bar {
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.main-content {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.control-panel {
|
||||
width: 320px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.three-viewer {
|
||||
flex: 1;
|
||||
}
|
||||
</style>
|
||||
86
frontend/src/assets/base.css
普通文件
86
frontend/src/assets/base.css
普通文件
@ -0,0 +1,86 @@
|
||||
/* color palette from <https://github.com/vuejs/theme> */
|
||||
:root {
|
||||
--vt-c-white: #ffffff;
|
||||
--vt-c-white-soft: #f8f8f8;
|
||||
--vt-c-white-mute: #f2f2f2;
|
||||
|
||||
--vt-c-black: #181818;
|
||||
--vt-c-black-soft: #222222;
|
||||
--vt-c-black-mute: #282828;
|
||||
|
||||
--vt-c-indigo: #2c3e50;
|
||||
|
||||
--vt-c-divider-light-1: rgba(60, 60, 60, 0.29);
|
||||
--vt-c-divider-light-2: rgba(60, 60, 60, 0.12);
|
||||
--vt-c-divider-dark-1: rgba(84, 84, 84, 0.65);
|
||||
--vt-c-divider-dark-2: rgba(84, 84, 84, 0.48);
|
||||
|
||||
--vt-c-text-light-1: var(--vt-c-indigo);
|
||||
--vt-c-text-light-2: rgba(60, 60, 60, 0.66);
|
||||
--vt-c-text-dark-1: var(--vt-c-white);
|
||||
--vt-c-text-dark-2: rgba(235, 235, 235, 0.64);
|
||||
}
|
||||
|
||||
/* semantic color variables for this project */
|
||||
:root {
|
||||
--color-background: var(--vt-c-white);
|
||||
--color-background-soft: var(--vt-c-white-soft);
|
||||
--color-background-mute: var(--vt-c-white-mute);
|
||||
|
||||
--color-border: var(--vt-c-divider-light-2);
|
||||
--color-border-hover: var(--vt-c-divider-light-1);
|
||||
|
||||
--color-heading: var(--vt-c-text-light-1);
|
||||
--color-text: var(--vt-c-text-light-1);
|
||||
|
||||
--section-gap: 160px;
|
||||
}
|
||||
|
||||
@media (prefers-color-scheme: dark) {
|
||||
:root {
|
||||
--color-background: var(--vt-c-black);
|
||||
--color-background-soft: var(--vt-c-black-soft);
|
||||
--color-background-mute: var(--vt-c-black-mute);
|
||||
|
||||
--color-border: var(--vt-c-divider-dark-2);
|
||||
--color-border-hover: var(--vt-c-divider-dark-1);
|
||||
|
||||
--color-heading: var(--vt-c-text-dark-1);
|
||||
--color-text: var(--vt-c-text-dark-2);
|
||||
}
|
||||
}
|
||||
|
||||
*,
|
||||
*::before,
|
||||
*::after {
|
||||
box-sizing: border-box;
|
||||
margin: 0;
|
||||
font-weight: normal;
|
||||
}
|
||||
|
||||
body {
|
||||
min-height: 100vh;
|
||||
color: var(--color-text);
|
||||
background: var(--color-background);
|
||||
transition:
|
||||
color 0.5s,
|
||||
background-color 0.5s;
|
||||
line-height: 1.6;
|
||||
font-family:
|
||||
Inter,
|
||||
-apple-system,
|
||||
BlinkMacSystemFont,
|
||||
'Segoe UI',
|
||||
Roboto,
|
||||
Oxygen,
|
||||
Ubuntu,
|
||||
Cantarell,
|
||||
'Fira Sans',
|
||||
'Droid Sans',
|
||||
'Helvetica Neue',
|
||||
sans-serif;
|
||||
font-size: 15px;
|
||||
text-rendering: optimizeLegibility;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
-moz-osx-font-smoothing: grayscale;
|
||||
}
|
||||
1
frontend/src/assets/logo.svg
普通文件
1
frontend/src/assets/logo.svg
普通文件
@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 261.76 226.69"><path d="M161.096.001l-30.225 52.351L100.647.001H-.005l130.877 226.688L261.749.001z" fill="#41b883"/><path d="M161.096.001l-30.225 52.351L100.647.001H52.346l78.526 136.01L209.398.001z" fill="#34495e"/></svg>
|
||||
|
之后 宽度: | 高度: | 大小: 276 B |
50
frontend/src/assets/main.css
普通文件
50
frontend/src/assets/main.css
普通文件
@ -0,0 +1,50 @@
|
||||
@import './base.css';
|
||||
|
||||
* {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
body {
|
||||
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;
|
||||
font-size: 14px;
|
||||
line-height: 1.5;
|
||||
color: #333;
|
||||
background: #f5f5f5;
|
||||
}
|
||||
|
||||
#app {
|
||||
height: 100vh;
|
||||
width: 100vw;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
button {
|
||||
cursor: pointer;
|
||||
font-family: inherit;
|
||||
}
|
||||
|
||||
input, select {
|
||||
font-family: inherit;
|
||||
font-size: inherit;
|
||||
}
|
||||
|
||||
::-webkit-scrollbar {
|
||||
width: 8px;
|
||||
height: 8px;
|
||||
}
|
||||
|
||||
::-webkit-scrollbar-track {
|
||||
background: #f1f1f1;
|
||||
border-radius: 4px;
|
||||
}
|
||||
|
||||
::-webkit-scrollbar-thumb {
|
||||
background: #c1c1c1;
|
||||
border-radius: 4px;
|
||||
}
|
||||
|
||||
::-webkit-scrollbar-thumb:hover {
|
||||
background: #a8a8a8;
|
||||
}
|
||||
@ -0,0 +1,204 @@
|
||||
<template>
|
||||
<div class="connection-bar">
|
||||
<div class="url-input-group">
|
||||
<label for="ws-url">WebSocket URL:</label>
|
||||
<input
|
||||
id="ws-url"
|
||||
type="text"
|
||||
v-model="wsUrl"
|
||||
placeholder="ws://localhost:8000/ws/six_axis"
|
||||
:disabled="isConnected"
|
||||
class="url-input"
|
||||
/>
|
||||
<select v-model="robotType" :disabled="isConnected" class="robot-select">
|
||||
<option value="six_axis">6轴工业机械臂</option>
|
||||
<option value="scara">SCARA机器人</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div class="connection-controls">
|
||||
<button
|
||||
@click="connect"
|
||||
:disabled="isConnecting || isConnected"
|
||||
class="connect-btn"
|
||||
>
|
||||
{{ isConnecting ? '连接中...' : '连接' }}
|
||||
</button>
|
||||
|
||||
<button
|
||||
@click="disconnect"
|
||||
:disabled="!isConnected"
|
||||
class="disconnect-btn"
|
||||
>
|
||||
断开
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div v-if="error" class="error-message">
|
||||
{{ error }}
|
||||
</div>
|
||||
|
||||
<div v-if="isConnecting" class="connecting-indicator">
|
||||
连接中...
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, computed, watch } from 'vue'
|
||||
import { useWebSocket } from '@/composables/useWebSocket'
|
||||
import { useRobotStore } from '@/stores/robot'
|
||||
|
||||
const wsUrl = ref('ws://localhost:8000/ws/six_axis')
|
||||
const robotType = ref('six_axis')
|
||||
const { connect: wsConnect, sendMoveCommand, disconnect: wsDisconnect, resetConnection, isConnected, error } = useWebSocket()
|
||||
const robotStore = useRobotStore()
|
||||
|
||||
const isConnecting = computed(() => robotStore.connectionStatus === 'connecting')
|
||||
|
||||
const updateWsUrl = () => {
|
||||
const baseUrl = wsUrl.value.split('/ws/')[0] || 'ws://localhost:8000'
|
||||
wsUrl.value = `${baseUrl}/ws/${robotType.value}`
|
||||
}
|
||||
|
||||
const connect = () => {
|
||||
updateWsUrl()
|
||||
wsConnect(wsUrl.value)
|
||||
}
|
||||
|
||||
const disconnect = () => {
|
||||
console.log('用户点击断开连接')
|
||||
|
||||
// 先重置连接状态,确保完全清理
|
||||
resetConnection()
|
||||
|
||||
// 然后断开连接
|
||||
wsDisconnect()
|
||||
|
||||
// 清理store状态
|
||||
robotStore.clearRobot()
|
||||
|
||||
console.log('连接已完全断开并重置')
|
||||
}
|
||||
|
||||
watch(robotType, updateWsUrl)
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.connection-bar {
|
||||
padding: 12px 16px;
|
||||
background: white;
|
||||
border-bottom: 1px solid #e0e0e0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 16px;
|
||||
}
|
||||
|
||||
.url-input-group {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.url-input-group label {
|
||||
font-size: 14px;
|
||||
color: #333;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.url-input {
|
||||
flex: 1;
|
||||
padding: 8px 12px;
|
||||
border: 1px solid #ddd;
|
||||
border-radius: 4px;
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.url-input:disabled {
|
||||
background: #f5f5f5;
|
||||
color: #999;
|
||||
}
|
||||
|
||||
.robot-select {
|
||||
padding: 8px 12px;
|
||||
border: 1px solid #ddd;
|
||||
border-radius: 4px;
|
||||
font-size: 14px;
|
||||
background: white;
|
||||
min-width: 140px;
|
||||
}
|
||||
|
||||
.robot-select:disabled {
|
||||
background: #f5f5f5;
|
||||
color: #999;
|
||||
}
|
||||
|
||||
.connection-controls {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.connect-btn, .disconnect-btn {
|
||||
padding: 8px 16px;
|
||||
border: none;
|
||||
border-radius: 4px;
|
||||
font-size: 14px;
|
||||
cursor: pointer;
|
||||
transition: background-color 0.2s;
|
||||
min-width: 80px;
|
||||
}
|
||||
|
||||
.connect-btn {
|
||||
background: #2ecc71;
|
||||
color: white;
|
||||
}
|
||||
|
||||
.connect-btn:hover:not(:disabled) {
|
||||
background: #27ae60;
|
||||
}
|
||||
|
||||
.connect-btn:disabled {
|
||||
background: #bdc3c7;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
.disconnect-btn {
|
||||
background: #e74c3c;
|
||||
color: white;
|
||||
}
|
||||
|
||||
.disconnect-btn:hover:not(:disabled) {
|
||||
background: #c0392b;
|
||||
}
|
||||
|
||||
.disconnect-btn:disabled {
|
||||
background: #f5b7b1;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
.error-message {
|
||||
color: #e74c3c;
|
||||
font-size: 12px;
|
||||
margin-top: 4px;
|
||||
position: absolute;
|
||||
bottom: -20px;
|
||||
left: 16px;
|
||||
}
|
||||
|
||||
.connecting-indicator {
|
||||
color: #f39c12;
|
||||
font-size: 12px;
|
||||
margin-left: 12px;
|
||||
animation: pulse 1.5s infinite;
|
||||
}
|
||||
|
||||
@keyframes pulse {
|
||||
0%, 100% {
|
||||
opacity: 1;
|
||||
}
|
||||
50% {
|
||||
opacity: 0.5;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@ -0,0 +1,226 @@
|
||||
<template>
|
||||
<div class="control-panel">
|
||||
<div class="panel-header">
|
||||
<h3>机械臂控制</h3>
|
||||
<div class="robot-info" v-if="robotStore.robotId">
|
||||
<span class="robot-id">ID: {{ robotStore.robotId }}</span>
|
||||
<span class="joint-count">{{ robotStore.jointCount }} 个关节</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="connection-status" :class="connectionStatusClass">
|
||||
<span class="status-dot"></span>
|
||||
<span class="status-text">{{ connectionStatusText }}</span>
|
||||
<span v-if="robotStore.connectionStatus === 'connected' && robotStore.robotId" class="connection-info">
|
||||
({{ robotStore.robotId }})
|
||||
</span>
|
||||
<span v-else-if="robotStore.connectionStatus === 'connecting'" class="connection-info">
|
||||
(连接中...)
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div class="joints-list" v-if="robotStore.jointList.length > 0">
|
||||
<JointSlider
|
||||
v-for="joint in robotStore.jointList"
|
||||
:key="joint.id"
|
||||
:joint="joint"
|
||||
@angle-change="onJointAngleChange"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div v-else class="empty-state">
|
||||
<p>未连接机械臂</p>
|
||||
<p class="hint">请先连接到WebSocket服务器</p>
|
||||
</div>
|
||||
|
||||
<div class="global-actions" v-if="robotStore.jointList.length > 0">
|
||||
<button @click="resetAllJoints" class="global-btn reset-all">
|
||||
全部复位
|
||||
</button>
|
||||
<button @click="deselectJoint" class="global-btn deselect" :disabled="!robotStore.selectedJoint">
|
||||
取消选择关节
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue'
|
||||
import { useRobotStore } from '@/stores/robot'
|
||||
import JointSlider from './JointSlider.vue'
|
||||
|
||||
const robotStore = useRobotStore()
|
||||
|
||||
const connectionStatusClass = computed(() => {
|
||||
return `status-${robotStore.connectionStatus}`
|
||||
})
|
||||
|
||||
const connectionStatusText = computed(() => {
|
||||
const texts: Record<string, string> = {
|
||||
'disconnected': '未连接',
|
||||
'connecting': '连接中...',
|
||||
'connected': '已连接'
|
||||
}
|
||||
return texts[robotStore.connectionStatus]
|
||||
})
|
||||
|
||||
const onJointAngleChange = (jointId: string, angle: number) => {
|
||||
robotStore.updateJointAngle(jointId, angle)
|
||||
}
|
||||
|
||||
const resetAllJoints = () => {
|
||||
robotStore.resetAllJoints()
|
||||
}
|
||||
|
||||
const deselectJoint = () => {
|
||||
robotStore.selectJoint(null)
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.control-panel {
|
||||
height: 100%;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
background: white;
|
||||
border-right: 1px solid #e0e0e0;
|
||||
}
|
||||
|
||||
.panel-header {
|
||||
padding: 16px;
|
||||
border-bottom: 1px solid #e0e0e0;
|
||||
}
|
||||
|
||||
.panel-header h3 {
|
||||
margin: 0 0 8px 0;
|
||||
font-size: 18px;
|
||||
color: #333;
|
||||
}
|
||||
|
||||
.robot-info {
|
||||
display: flex;
|
||||
gap: 12px;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.robot-id {
|
||||
color: #3498db;
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.joint-count {
|
||||
color: #666;
|
||||
}
|
||||
|
||||
.connection-status {
|
||||
padding: 12px 16px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
border-bottom: 1px solid #e0e0e0;
|
||||
}
|
||||
|
||||
.status-dot {
|
||||
width: 8px;
|
||||
height: 8px;
|
||||
border-radius: 50%;
|
||||
}
|
||||
|
||||
.status-disconnected .status-dot {
|
||||
background: #e74c3c;
|
||||
}
|
||||
|
||||
.status-connecting .status-dot {
|
||||
background: #f39c12;
|
||||
animation: pulse 1.5s infinite;
|
||||
}
|
||||
|
||||
.status-connected .status-dot {
|
||||
background: #2ecc71;
|
||||
}
|
||||
|
||||
.status-text {
|
||||
font-size: 14px;
|
||||
color: #333;
|
||||
}
|
||||
|
||||
.connection-info {
|
||||
font-size: 12px;
|
||||
color: #666;
|
||||
margin-left: 4px;
|
||||
}
|
||||
|
||||
.joints-list {
|
||||
flex: 1;
|
||||
overflow-y: auto;
|
||||
padding: 16px;
|
||||
}
|
||||
|
||||
.empty-state {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
color: #999;
|
||||
padding: 40px 20px;
|
||||
}
|
||||
|
||||
.empty-state p {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.empty-state .hint {
|
||||
font-size: 12px;
|
||||
margin-top: 8px;
|
||||
}
|
||||
|
||||
.global-actions {
|
||||
padding: 16px;
|
||||
border-top: 1px solid #e0e0e0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.global-btn {
|
||||
padding: 10px 16px;
|
||||
border: none;
|
||||
border-radius: 6px;
|
||||
font-size: 14px;
|
||||
cursor: pointer;
|
||||
transition: all 0.2s;
|
||||
}
|
||||
|
||||
.reset-all {
|
||||
background: #3498db;
|
||||
color: white;
|
||||
}
|
||||
|
||||
.reset-all:hover {
|
||||
background: #2980b9;
|
||||
}
|
||||
|
||||
.deselect {
|
||||
background: #f5f5f5;
|
||||
color: #666;
|
||||
}
|
||||
|
||||
.deselect:hover:not(:disabled) {
|
||||
background: #e0e0e0;
|
||||
}
|
||||
|
||||
.deselect:disabled {
|
||||
opacity: 0.5;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
@keyframes pulse {
|
||||
0%, 100% {
|
||||
opacity: 1;
|
||||
}
|
||||
50% {
|
||||
opacity: 0.5;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@ -0,0 +1,41 @@
|
||||
<script setup lang="ts">
|
||||
defineProps<{
|
||||
msg: string
|
||||
}>()
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="greetings">
|
||||
<h1 class="green">{{ msg }}</h1>
|
||||
<h3>
|
||||
You’ve successfully created a project with
|
||||
<a href="https://vite.dev/" target="_blank" rel="noopener">Vite</a> +
|
||||
<a href="https://vuejs.org/" target="_blank" rel="noopener">Vue 3</a>. What's next?
|
||||
</h3>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
h1 {
|
||||
font-weight: 500;
|
||||
font-size: 2.6rem;
|
||||
position: relative;
|
||||
top: -10px;
|
||||
}
|
||||
|
||||
h3 {
|
||||
font-size: 1.2rem;
|
||||
}
|
||||
|
||||
.greetings h1,
|
||||
.greetings h3 {
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
@media (min-width: 1024px) {
|
||||
.greetings h1,
|
||||
.greetings h3 {
|
||||
text-align: left;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@ -0,0 +1,239 @@
|
||||
<template>
|
||||
<div class="joint-slider" :class="{ selected: isSelected }" @click="selectJoint">
|
||||
<div class="joint-header">
|
||||
<h4>{{ joint.id }}</h4>
|
||||
<span class="joint-type">{{ typeName }}</span>
|
||||
</div>
|
||||
|
||||
<div class="slider-container">
|
||||
<div class="range-labels">
|
||||
<span>{{ joint.range[0] }}°</span>
|
||||
<span>{{ joint.range[1] }}°</span>
|
||||
</div>
|
||||
|
||||
<input
|
||||
type="range"
|
||||
:min="joint.range[0]"
|
||||
:max="joint.range[1]"
|
||||
:step="1"
|
||||
:value="joint.currentAngle"
|
||||
@input="onSliderChange"
|
||||
class="slider"
|
||||
/>
|
||||
|
||||
<div class="angle-display">
|
||||
<input
|
||||
type="number"
|
||||
:min="joint.range[0]"
|
||||
:max="joint.range[1]"
|
||||
:value="joint.currentAngle"
|
||||
@change="onInputChange"
|
||||
class="angle-input"
|
||||
/>
|
||||
<span>°</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="joint-actions">
|
||||
<button @click="resetToDefault" class="reset-btn">复位</button>
|
||||
<button v-if="joint.type === 'gripper'" @click="toggleGripper" class="toggle-btn">
|
||||
{{ joint.currentAngle > 50 ? '关闭' : '打开' }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue'
|
||||
import { useRobotStore } from '@/stores/robot'
|
||||
import type { JointState } from '@/types/ws'
|
||||
|
||||
const props = defineProps<{
|
||||
joint: JointState
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
angleChange: [jointId: string, angle: number]
|
||||
}>()
|
||||
|
||||
const robotStore = useRobotStore()
|
||||
|
||||
const typeName = computed(() => {
|
||||
const names = {
|
||||
'joint': '关节',
|
||||
'flex_w': '水平旋转',
|
||||
'flex_v': '垂直旋转',
|
||||
'gripper': '夹爪'
|
||||
}
|
||||
return names[props.joint.type] || props.joint.type
|
||||
})
|
||||
|
||||
const isSelected = computed(() => robotStore.selectedJoint === props.joint.id)
|
||||
|
||||
const onSliderChange = (event: Event) => {
|
||||
const target = event.target as HTMLInputElement
|
||||
const angle = parseFloat(target.value)
|
||||
emit('angleChange', props.joint.id, angle)
|
||||
}
|
||||
|
||||
const onInputChange = (event: Event) => {
|
||||
const target = event.target as HTMLInputElement
|
||||
const angle = parseFloat(target.value)
|
||||
const clampedAngle = robotStore.clampAngle(angle, props.joint.range)
|
||||
emit('angleChange', props.joint.id, clampedAngle)
|
||||
}
|
||||
|
||||
const resetToDefault = () => {
|
||||
emit('angleChange', props.joint.id, props.joint.default)
|
||||
}
|
||||
|
||||
const toggleGripper = () => {
|
||||
const newAngle = props.joint.currentAngle > 50 ? 0 : 100
|
||||
emit('angleChange', props.joint.id, newAngle)
|
||||
}
|
||||
|
||||
const selectJoint = () => {
|
||||
robotStore.selectJoint(props.joint.id)
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.joint-slider {
|
||||
padding: 12px;
|
||||
border: 1px solid #e0e0e0;
|
||||
border-radius: 8px;
|
||||
background: white;
|
||||
margin-bottom: 12px;
|
||||
cursor: pointer;
|
||||
transition: all 0.2s ease;
|
||||
}
|
||||
|
||||
.joint-slider:hover {
|
||||
border-color: #3498db;
|
||||
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
|
||||
}
|
||||
|
||||
.joint-slider.selected {
|
||||
border-color: #f1c40f;
|
||||
background-color: #fffde7;
|
||||
}
|
||||
|
||||
.joint-header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
|
||||
.joint-header h4 {
|
||||
margin: 0;
|
||||
font-size: 14px;
|
||||
font-weight: 600;
|
||||
color: #333;
|
||||
}
|
||||
|
||||
.joint-type {
|
||||
font-size: 12px;
|
||||
color: #666;
|
||||
background: #f5f5f5;
|
||||
padding: 2px 8px;
|
||||
border-radius: 12px;
|
||||
}
|
||||
|
||||
.slider-container {
|
||||
margin: 12px 0;
|
||||
}
|
||||
|
||||
.range-labels {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
font-size: 12px;
|
||||
color: #666;
|
||||
margin-bottom: 4px;
|
||||
}
|
||||
|
||||
.slider {
|
||||
width: 100%;
|
||||
height: 6px;
|
||||
border-radius: 3px;
|
||||
background: #e0e0e0;
|
||||
outline: none;
|
||||
-webkit-appearance: none;
|
||||
}
|
||||
|
||||
.slider::-webkit-slider-thumb {
|
||||
-webkit-appearance: none;
|
||||
width: 20px;
|
||||
height: 20px;
|
||||
border-radius: 50%;
|
||||
background: #3498db;
|
||||
cursor: pointer;
|
||||
border: 2px solid white;
|
||||
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
|
||||
}
|
||||
|
||||
.slider::-moz-range-thumb {
|
||||
width: 20px;
|
||||
height: 20px;
|
||||
border-radius: 50%;
|
||||
background: #3498db;
|
||||
cursor: pointer;
|
||||
border: 2px solid white;
|
||||
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
|
||||
}
|
||||
|
||||
.angle-display {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
margin-top: 8px;
|
||||
}
|
||||
|
||||
.angle-input {
|
||||
width: 60px;
|
||||
padding: 4px 8px;
|
||||
border: 1px solid #ddd;
|
||||
border-radius: 4px;
|
||||
text-align: center;
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.angle-display span {
|
||||
margin-left: 4px;
|
||||
color: #666;
|
||||
}
|
||||
|
||||
.joint-actions {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
margin-top: 12px;
|
||||
}
|
||||
|
||||
.reset-btn, .toggle-btn {
|
||||
flex: 1;
|
||||
padding: 6px 12px;
|
||||
border: none;
|
||||
border-radius: 4px;
|
||||
font-size: 12px;
|
||||
cursor: pointer;
|
||||
transition: background-color 0.2s;
|
||||
}
|
||||
|
||||
.reset-btn {
|
||||
background: #f5f5f5;
|
||||
color: #333;
|
||||
}
|
||||
|
||||
.reset-btn:hover {
|
||||
background: #e0e0e0;
|
||||
}
|
||||
|
||||
.toggle-btn {
|
||||
background: #f39c12;
|
||||
color: white;
|
||||
}
|
||||
|
||||
.toggle-btn:hover {
|
||||
background: #e67e22;
|
||||
}
|
||||
</style>
|
||||
@ -0,0 +1,95 @@
|
||||
<script setup lang="ts">
|
||||
import WelcomeItem from './WelcomeItem.vue'
|
||||
import DocumentationIcon from './icons/IconDocumentation.vue'
|
||||
import ToolingIcon from './icons/IconTooling.vue'
|
||||
import EcosystemIcon from './icons/IconEcosystem.vue'
|
||||
import CommunityIcon from './icons/IconCommunity.vue'
|
||||
import SupportIcon from './icons/IconSupport.vue'
|
||||
|
||||
const openReadmeInEditor = () => fetch('/__open-in-editor?file=README.md')
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<WelcomeItem>
|
||||
<template #icon>
|
||||
<DocumentationIcon />
|
||||
</template>
|
||||
<template #heading>Documentation</template>
|
||||
|
||||
Vue’s
|
||||
<a href="https://vuejs.org/" target="_blank" rel="noopener">official documentation</a>
|
||||
provides you with all information you need to get started.
|
||||
</WelcomeItem>
|
||||
|
||||
<WelcomeItem>
|
||||
<template #icon>
|
||||
<ToolingIcon />
|
||||
</template>
|
||||
<template #heading>Tooling</template>
|
||||
|
||||
This project is served and bundled with
|
||||
<a href="https://vite.dev/guide/features.html" target="_blank" rel="noopener">Vite</a>. The
|
||||
recommended IDE setup is
|
||||
<a href="https://code.visualstudio.com/" target="_blank" rel="noopener">VSCode</a>
|
||||
+
|
||||
<a href="https://github.com/vuejs/language-tools" target="_blank" rel="noopener"
|
||||
>Vue - Official</a
|
||||
>. If you need to test your components and web pages, check out
|
||||
<a href="https://vitest.dev/" target="_blank" rel="noopener">Vitest</a>
|
||||
and
|
||||
<a href="https://www.cypress.io/" target="_blank" rel="noopener">Cypress</a>
|
||||
/
|
||||
<a href="https://playwright.dev/" target="_blank" rel="noopener">Playwright</a>.
|
||||
|
||||
<br />
|
||||
|
||||
More instructions are available in
|
||||
<a href="javascript:void(0)" @click="openReadmeInEditor"><code>README.md</code></a
|
||||
>.
|
||||
</WelcomeItem>
|
||||
|
||||
<WelcomeItem>
|
||||
<template #icon>
|
||||
<EcosystemIcon />
|
||||
</template>
|
||||
<template #heading>Ecosystem</template>
|
||||
|
||||
Get official tools and libraries for your project:
|
||||
<a href="https://pinia.vuejs.org/" target="_blank" rel="noopener">Pinia</a>,
|
||||
<a href="https://router.vuejs.org/" target="_blank" rel="noopener">Vue Router</a>,
|
||||
<a href="https://test-utils.vuejs.org/" target="_blank" rel="noopener">Vue Test Utils</a>, and
|
||||
<a href="https://github.com/vuejs/devtools" target="_blank" rel="noopener">Vue Dev Tools</a>. If
|
||||
you need more resources, we suggest paying
|
||||
<a href="https://github.com/vuejs/awesome-vue" target="_blank" rel="noopener">Awesome Vue</a>
|
||||
a visit.
|
||||
</WelcomeItem>
|
||||
|
||||
<WelcomeItem>
|
||||
<template #icon>
|
||||
<CommunityIcon />
|
||||
</template>
|
||||
<template #heading>Community</template>
|
||||
|
||||
Got stuck? Ask your question on
|
||||
<a href="https://chat.vuejs.org" target="_blank" rel="noopener">Vue Land</a>
|
||||
(our official Discord server), or
|
||||
<a href="https://stackoverflow.com/questions/tagged/vue.js" target="_blank" rel="noopener"
|
||||
>StackOverflow</a
|
||||
>. You should also follow the official
|
||||
<a href="https://bsky.app/profile/vuejs.org" target="_blank" rel="noopener">@vuejs.org</a>
|
||||
Bluesky account or the
|
||||
<a href="https://x.com/vuejs" target="_blank" rel="noopener">@vuejs</a>
|
||||
X account for latest news in the Vue world.
|
||||
</WelcomeItem>
|
||||
|
||||
<WelcomeItem>
|
||||
<template #icon>
|
||||
<SupportIcon />
|
||||
</template>
|
||||
<template #heading>Support Vue</template>
|
||||
|
||||
As an independent project, Vue relies on community backing for its sustainability. You can help
|
||||
us by
|
||||
<a href="https://vuejs.org/sponsor/" target="_blank" rel="noopener">becoming a sponsor</a>.
|
||||
</WelcomeItem>
|
||||
</template>
|
||||
@ -0,0 +1,377 @@
|
||||
<template>
|
||||
<div ref="container" class="three-viewer"></div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, onMounted, onUnmounted, watch } from 'vue'
|
||||
import * as THREE from 'three'
|
||||
import { OrbitControls } from 'three/addons/controls/OrbitControls.js'
|
||||
import { useRobotStore } from '@/stores/robot'
|
||||
|
||||
const container = ref<HTMLDivElement>()
|
||||
const robotStore = useRobotStore()
|
||||
|
||||
let scene: THREE.Scene
|
||||
let camera: THREE.PerspectiveCamera
|
||||
let renderer: THREE.WebGLRenderer
|
||||
let controls: OrbitControls
|
||||
let animationFrameId: number
|
||||
|
||||
const jointObjects = new Map<string, THREE.Object3D>()
|
||||
const gripperObjects = new Map<string, THREE.Object3D[]>()
|
||||
|
||||
const initThree = () => {
|
||||
if (!container.value) return
|
||||
|
||||
scene = new THREE.Scene()
|
||||
scene.background = new THREE.Color(0xf0f0f0)
|
||||
|
||||
camera = new THREE.PerspectiveCamera(
|
||||
75,
|
||||
container.value.clientWidth / container.value.clientHeight,
|
||||
0.1,
|
||||
1000
|
||||
)
|
||||
camera.position.set(5, 5, 5)
|
||||
|
||||
renderer = new THREE.WebGLRenderer({ antialias: true })
|
||||
renderer.setSize(container.value.clientWidth, container.value.clientHeight)
|
||||
renderer.shadowMap.enabled = true
|
||||
renderer.shadowMap.type = THREE.PCFSoftShadowMap
|
||||
container.value.appendChild(renderer.domElement)
|
||||
|
||||
controls = new OrbitControls(camera, renderer.domElement)
|
||||
controls.enableDamping = true
|
||||
controls.dampingFactor = 0.05
|
||||
|
||||
addLights()
|
||||
addGrid()
|
||||
addAxes()
|
||||
|
||||
animate()
|
||||
}
|
||||
|
||||
const addLights = () => {
|
||||
const ambientLight = new THREE.AmbientLight(0xffffff, 0.6)
|
||||
scene.add(ambientLight)
|
||||
|
||||
const directionalLight = new THREE.DirectionalLight(0xffffff, 0.8)
|
||||
directionalLight.position.set(10, 20, 10)
|
||||
directionalLight.castShadow = true
|
||||
scene.add(directionalLight)
|
||||
}
|
||||
|
||||
const addGrid = () => {
|
||||
const gridHelper = new THREE.GridHelper(20, 20, 0x888888, 0x444444)
|
||||
scene.add(gridHelper)
|
||||
}
|
||||
|
||||
const addAxes = () => {
|
||||
const axesHelper = new THREE.AxesHelper(5)
|
||||
scene.add(axesHelper)
|
||||
}
|
||||
|
||||
const createJointGeometry = (type: string) => {
|
||||
switch (type) {
|
||||
case 'flex_w':
|
||||
return new THREE.CylinderGeometry(0.5, 0.5, 0.2, 16)
|
||||
case 'flex_v':
|
||||
return new THREE.BoxGeometry(0.6, 0.6, 0.6)
|
||||
case 'gripper':
|
||||
return new THREE.BoxGeometry(0.3, 0.6, 0.3)
|
||||
default:
|
||||
return new THREE.CylinderGeometry(0.3, 0.3, 1, 8)
|
||||
}
|
||||
}
|
||||
|
||||
const createJointMaterial = (type: string, isSelected: boolean = false) => {
|
||||
let color = 0x3498db
|
||||
|
||||
switch (type) {
|
||||
case 'flex_w':
|
||||
color = 0xe74c3c
|
||||
break
|
||||
case 'flex_v':
|
||||
color = 0x2ecc71
|
||||
break
|
||||
case 'gripper':
|
||||
color = 0xf39c12
|
||||
break
|
||||
}
|
||||
|
||||
if (isSelected) {
|
||||
color = 0xf1c40f
|
||||
}
|
||||
|
||||
return new THREE.MeshPhongMaterial({
|
||||
color,
|
||||
shininess: 30
|
||||
})
|
||||
}
|
||||
|
||||
const buildRobot = () => {
|
||||
// 确保在构建前完全清理
|
||||
clearRobotFromScene()
|
||||
|
||||
if (robotStore.jointList.length === 0) {
|
||||
console.warn('尝试构建机器人但关节列表为空')
|
||||
return
|
||||
}
|
||||
|
||||
const jointMap = new Map(robotStore.jointList.map((j: any) => [j.id, j]))
|
||||
const rootJoints = robotStore.jointList.filter((j: any) => !robotStore.jointList.some((other: any) => other.next === j.id))
|
||||
|
||||
if (rootJoints.length === 0) {
|
||||
console.warn('未找到根关节,无法构建机器人')
|
||||
return
|
||||
}
|
||||
|
||||
rootJoints.forEach(joint => {
|
||||
buildJointChain(joint, jointMap, new THREE.Vector3(0, 0, 0))
|
||||
})
|
||||
|
||||
console.log(`机器人构建完成,关节数: ${robotStore.jointList.length}`)
|
||||
}
|
||||
|
||||
const buildJointChain = (joint: any, jointMap: Map<string, any>, position: THREE.Vector3, parent?: THREE.Object3D) => {
|
||||
const geometry = createJointGeometry(joint.type)
|
||||
const material = createJointMaterial(joint.type, joint.id === robotStore.selectedJoint)
|
||||
const mesh = new THREE.Mesh(geometry, material)
|
||||
|
||||
mesh.position.copy(position)
|
||||
mesh.castShadow = true
|
||||
|
||||
if (parent) {
|
||||
parent.add(mesh)
|
||||
} else {
|
||||
scene.add(mesh)
|
||||
}
|
||||
|
||||
jointObjects.set(joint.id, mesh)
|
||||
|
||||
if (joint.type === 'gripper') {
|
||||
createGripper(mesh, joint)
|
||||
}
|
||||
|
||||
if (joint.next) {
|
||||
const nextJoint = jointMap.get(joint.next)
|
||||
if (nextJoint) {
|
||||
const nextPosition = new THREE.Vector3(0, 1.2, 0)
|
||||
buildJointChain(nextJoint, jointMap, nextPosition, mesh)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const createGripper = (parent: THREE.Object3D, joint: any) => {
|
||||
const leftGeometry = new THREE.BoxGeometry(0.1, 0.4, 0.3)
|
||||
const rightGeometry = new THREE.BoxGeometry(0.1, 0.4, 0.3)
|
||||
const material = createJointMaterial('gripper')
|
||||
|
||||
const leftGripper = new THREE.Mesh(leftGeometry, material)
|
||||
const rightGripper = new THREE.Mesh(rightGeometry, material)
|
||||
|
||||
leftGripper.position.set(-0.2, 0.5, 0)
|
||||
rightGripper.position.set(0.2, 0.5, 0)
|
||||
|
||||
leftGripper.castShadow = true
|
||||
rightGripper.castShadow = true
|
||||
|
||||
parent.add(leftGripper)
|
||||
parent.add(rightGripper)
|
||||
|
||||
gripperObjects.set(joint.id, [leftGripper, rightGripper])
|
||||
}
|
||||
|
||||
const updateRobot = () => {
|
||||
robotStore.jointList.forEach((joint: any) => {
|
||||
const jointObj = jointObjects.get(joint.id)
|
||||
if (jointObj) {
|
||||
switch (joint.type) {
|
||||
case 'flex_w':
|
||||
jointObj.rotation.y = THREE.MathUtils.degToRad(joint.currentAngle)
|
||||
break
|
||||
case 'flex_v':
|
||||
jointObj.rotation.x = THREE.MathUtils.degToRad(joint.currentAngle)
|
||||
break
|
||||
case 'gripper':
|
||||
updateGripper(joint.id, joint.currentAngle)
|
||||
break
|
||||
default:
|
||||
jointObj.rotation.z = THREE.MathUtils.degToRad(joint.currentAngle)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
const updateGripper = (jointId: string, angle: number) => {
|
||||
const grippers = gripperObjects.get(jointId)
|
||||
if (grippers && grippers.length >= 2) {
|
||||
const left = grippers[0] as THREE.Mesh
|
||||
const right = grippers[1] as THREE.Mesh
|
||||
const openAmount = angle / 100 * 0.3
|
||||
|
||||
left.position.x = -0.2 - openAmount
|
||||
right.position.x = 0.2 + openAmount
|
||||
}
|
||||
}
|
||||
|
||||
// 清理场景中的机器人模型
|
||||
const clearRobotFromScene = () => {
|
||||
// 递归清理Three.js对象及其资源
|
||||
const cleanupObject = (obj: THREE.Object3D) => {
|
||||
// 递归清理所有子对象
|
||||
while (obj.children.length > 0) {
|
||||
const child = obj.children[0]
|
||||
if (child) {
|
||||
cleanupObject(child)
|
||||
obj.remove(child)
|
||||
} else {
|
||||
// 如果child是undefined,直接移除
|
||||
obj.children.shift()
|
||||
}
|
||||
}
|
||||
|
||||
// 从父对象中移除
|
||||
if (obj.parent) {
|
||||
obj.parent.remove(obj)
|
||||
} else if (scene) {
|
||||
scene.remove(obj)
|
||||
}
|
||||
|
||||
// 清理几何体和材质(释放GPU内存)
|
||||
if (obj instanceof THREE.Mesh) {
|
||||
if (obj.geometry) {
|
||||
obj.geometry.dispose()
|
||||
}
|
||||
if (obj.material) {
|
||||
if (Array.isArray(obj.material)) {
|
||||
obj.material.forEach(material => material.dispose())
|
||||
} else {
|
||||
obj.material.dispose()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 清理所有关节对象
|
||||
jointObjects.forEach(obj => {
|
||||
cleanupObject(obj)
|
||||
})
|
||||
|
||||
// 清理夹爪对象
|
||||
gripperObjects.forEach(grippers => {
|
||||
grippers.forEach(gripper => {
|
||||
cleanupObject(gripper)
|
||||
})
|
||||
})
|
||||
|
||||
// 清空Map
|
||||
jointObjects.clear()
|
||||
gripperObjects.clear()
|
||||
}
|
||||
|
||||
const animate = () => {
|
||||
animationFrameId = requestAnimationFrame(animate)
|
||||
|
||||
if (controls) {
|
||||
controls.update()
|
||||
}
|
||||
|
||||
updateRobot()
|
||||
|
||||
if (renderer && scene && camera) {
|
||||
renderer.render(scene, camera)
|
||||
}
|
||||
}
|
||||
|
||||
const onResize = () => {
|
||||
if (!container.value || !camera || !renderer) return
|
||||
|
||||
camera.aspect = container.value.clientWidth / container.value.clientHeight
|
||||
camera.updateProjectionMatrix()
|
||||
renderer.setSize(container.value.clientWidth, container.value.clientHeight)
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
initThree()
|
||||
window.addEventListener('resize', onResize)
|
||||
|
||||
// 添加构建状态锁,防止重复构建
|
||||
let isBuilding = false
|
||||
|
||||
// 单一监听器处理机器人状态变化
|
||||
watch(() => ({
|
||||
robotId: robotStore.robotId,
|
||||
jointCount: robotStore.jointList.length
|
||||
}), ({ robotId, jointCount }, oldValues) => {
|
||||
const oldRobotId = oldValues?.robotId
|
||||
const oldJointCount = oldValues?.jointCount || 0
|
||||
|
||||
// 机器人被清除(断开连接)
|
||||
if (oldRobotId && !robotId) {
|
||||
clearRobotFromScene()
|
||||
isBuilding = false
|
||||
return
|
||||
}
|
||||
|
||||
// 新机器人连接
|
||||
if (robotId && !oldRobotId && jointCount > 0) {
|
||||
if (!isBuilding) {
|
||||
isBuilding = true
|
||||
buildRobot()
|
||||
// 构建完成后重置状态锁
|
||||
setTimeout(() => {
|
||||
isBuilding = false
|
||||
}, 100)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// 关节数量变化(重新连接或配置更新)
|
||||
if (robotId && oldRobotId === robotId) {
|
||||
if (jointCount > 0 && oldJointCount === 0) {
|
||||
// 从无关节到有关节(重新连接)
|
||||
if (!isBuilding) {
|
||||
isBuilding = true
|
||||
clearRobotFromScene()
|
||||
buildRobot()
|
||||
setTimeout(() => {
|
||||
isBuilding = false
|
||||
}, 100)
|
||||
}
|
||||
} else if (jointCount === 0 && oldJointCount > 0) {
|
||||
// 从有关节到无关节(连接丢失但robotId还在)
|
||||
clearRobotFromScene()
|
||||
isBuilding = false
|
||||
}
|
||||
}
|
||||
}, { deep: true })
|
||||
|
||||
watch(() => robotStore.selectedJoint, () => {
|
||||
robotStore.jointList.forEach((joint: any) => {
|
||||
const jointObj = jointObjects.get(joint.id)
|
||||
if (jointObj && jointObj instanceof THREE.Mesh) {
|
||||
jointObj.material = createJointMaterial(joint.type, joint.id === robotStore.selectedJoint)
|
||||
}
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
onUnmounted(() => {
|
||||
window.removeEventListener('resize', onResize)
|
||||
if (animationFrameId) {
|
||||
cancelAnimationFrame(animationFrameId)
|
||||
}
|
||||
if (renderer) {
|
||||
renderer.dispose()
|
||||
}
|
||||
})
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.three-viewer {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
position: relative;
|
||||
}
|
||||
</style>
|
||||
@ -0,0 +1,87 @@
|
||||
<template>
|
||||
<div class="item">
|
||||
<i>
|
||||
<slot name="icon"></slot>
|
||||
</i>
|
||||
<div class="details">
|
||||
<h3>
|
||||
<slot name="heading"></slot>
|
||||
</h3>
|
||||
<slot></slot>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.item {
|
||||
margin-top: 2rem;
|
||||
display: flex;
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.details {
|
||||
flex: 1;
|
||||
margin-left: 1rem;
|
||||
}
|
||||
|
||||
i {
|
||||
display: flex;
|
||||
place-items: center;
|
||||
place-content: center;
|
||||
width: 32px;
|
||||
height: 32px;
|
||||
|
||||
color: var(--color-text);
|
||||
}
|
||||
|
||||
h3 {
|
||||
font-size: 1.2rem;
|
||||
font-weight: 500;
|
||||
margin-bottom: 0.4rem;
|
||||
color: var(--color-heading);
|
||||
}
|
||||
|
||||
@media (min-width: 1024px) {
|
||||
.item {
|
||||
margin-top: 0;
|
||||
padding: 0.4rem 0 1rem calc(var(--section-gap) / 2);
|
||||
}
|
||||
|
||||
i {
|
||||
top: calc(50% - 25px);
|
||||
left: -26px;
|
||||
position: absolute;
|
||||
border: 1px solid var(--color-border);
|
||||
background: var(--color-background);
|
||||
border-radius: 8px;
|
||||
width: 50px;
|
||||
height: 50px;
|
||||
}
|
||||
|
||||
.item:before {
|
||||
content: ' ';
|
||||
border-left: 1px solid var(--color-border);
|
||||
position: absolute;
|
||||
left: 0;
|
||||
bottom: calc(50% + 25px);
|
||||
height: calc(50% - 25px);
|
||||
}
|
||||
|
||||
.item:after {
|
||||
content: ' ';
|
||||
border-left: 1px solid var(--color-border);
|
||||
position: absolute;
|
||||
left: 0;
|
||||
top: calc(50% + 25px);
|
||||
height: calc(50% - 25px);
|
||||
}
|
||||
|
||||
.item:first-of-type:before {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.item:last-of-type:after {
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@ -0,0 +1,7 @@
|
||||
<template>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" fill="currentColor">
|
||||
<path
|
||||
d="M15 4a1 1 0 1 0 0 2V4zm0 11v-1a1 1 0 0 0-1 1h1zm0 4l-.707.707A1 1 0 0 0 16 19h-1zm-4-4l.707-.707A1 1 0 0 0 11 14v1zm-4.707-1.293a1 1 0 0 0-1.414 1.414l1.414-1.414zm-.707.707l-.707-.707.707.707zM9 11v-1a1 1 0 0 0-.707.293L9 11zm-4 0h1a1 1 0 0 0-1-1v1zm0 4H4a1 1 0 0 0 1.707.707L5 15zm10-9h2V4h-2v2zm2 0a1 1 0 0 1 1 1h2a3 3 0 0 0-3-3v2zm1 1v6h2V7h-2zm0 6a1 1 0 0 1-1 1v2a3 3 0 0 0 3-3h-2zm-1 1h-2v2h2v-2zm-3 1v4h2v-4h-2zm1.707 3.293l-4-4-1.414 1.414 4 4 1.414-1.414zM11 14H7v2h4v-2zm-4 0c-.276 0-.525-.111-.707-.293l-1.414 1.414C5.42 15.663 6.172 16 7 16v-2zm-.707 1.121l3.414-3.414-1.414-1.414-3.414 3.414 1.414 1.414zM9 12h4v-2H9v2zm4 0a3 3 0 0 0 3-3h-2a1 1 0 0 1-1 1v2zm3-3V3h-2v6h2zm0-6a3 3 0 0 0-3-3v2a1 1 0 0 1 1 1h2zm-3-3H3v2h10V0zM3 0a3 3 0 0 0-3 3h2a1 1 0 0 1 1-1V0zM0 3v6h2V3H0zm0 6a3 3 0 0 0 3 3v-2a1 1 0 0 1-1-1H0zm3 3h2v-2H3v2zm1-1v4h2v-4H4zm1.707 4.707l.586-.586-1.414-1.414-.586.586 1.414 1.414z"
|
||||
/>
|
||||
</svg>
|
||||
</template>
|
||||
@ -0,0 +1,7 @@
|
||||
<template>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="17" fill="currentColor">
|
||||
<path
|
||||
d="M11 2.253a1 1 0 1 0-2 0h2zm-2 13a1 1 0 1 0 2 0H9zm.447-12.167a1 1 0 1 0 1.107-1.666L9.447 3.086zM1 2.253L.447 1.42A1 1 0 0 0 0 2.253h1zm0 13H0a1 1 0 0 0 1.553.833L1 15.253zm8.447.833a1 1 0 1 0 1.107-1.666l-1.107 1.666zm0-14.666a1 1 0 1 0 1.107 1.666L9.447 1.42zM19 2.253h1a1 1 0 0 0-.447-.833L19 2.253zm0 13l-.553.833A1 1 0 0 0 20 15.253h-1zm-9.553-.833a1 1 0 1 0 1.107 1.666L9.447 14.42zM9 2.253v13h2v-13H9zm1.553-.833C9.203.523 7.42 0 5.5 0v2c1.572 0 2.961.431 3.947 1.086l1.107-1.666zM5.5 0C3.58 0 1.797.523.447 1.42l1.107 1.666C2.539 2.431 3.928 2 5.5 2V0zM0 2.253v13h2v-13H0zm1.553 13.833C2.539 15.431 3.928 15 5.5 15v-2c-1.92 0-3.703.523-5.053 1.42l1.107 1.666zM5.5 15c1.572 0 2.961.431 3.947 1.086l1.107-1.666C9.203 13.523 7.42 13 5.5 13v2zm5.053-11.914C11.539 2.431 12.928 2 14.5 2V0c-1.92 0-3.703.523-5.053 1.42l1.107 1.666zM14.5 2c1.573 0 2.961.431 3.947 1.086l1.107-1.666C18.203.523 16.421 0 14.5 0v2zm3.5.253v13h2v-13h-2zm1.553 12.167C18.203 13.523 16.421 13 14.5 13v2c1.573 0 2.961.431 3.947 1.086l1.107-1.666zM14.5 13c-1.92 0-3.703.523-5.053 1.42l1.107 1.666C11.539 15.431 12.928 15 14.5 15v-2z"
|
||||
/>
|
||||
</svg>
|
||||
</template>
|
||||
@ -0,0 +1,7 @@
|
||||
<template>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="18" height="20" fill="currentColor">
|
||||
<path
|
||||
d="M11.447 8.894a1 1 0 1 0-.894-1.789l.894 1.789zm-2.894-.789a1 1 0 1 0 .894 1.789l-.894-1.789zm0 1.789a1 1 0 1 0 .894-1.789l-.894 1.789zM7.447 7.106a1 1 0 1 0-.894 1.789l.894-1.789zM10 9a1 1 0 1 0-2 0h2zm-2 2.5a1 1 0 1 0 2 0H8zm9.447-5.606a1 1 0 1 0-.894-1.789l.894 1.789zm-2.894-.789a1 1 0 1 0 .894 1.789l-.894-1.789zm2 .789a1 1 0 1 0 .894-1.789l-.894 1.789zm-1.106-2.789a1 1 0 1 0-.894 1.789l.894-1.789zM18 5a1 1 0 1 0-2 0h2zm-2 2.5a1 1 0 1 0 2 0h-2zm-5.447-4.606a1 1 0 1 0 .894-1.789l-.894 1.789zM9 1l.447-.894a1 1 0 0 0-.894 0L9 1zm-2.447.106a1 1 0 1 0 .894 1.789l-.894-1.789zm-6 3a1 1 0 1 0 .894 1.789L.553 4.106zm2.894.789a1 1 0 1 0-.894-1.789l.894 1.789zm-2-.789a1 1 0 1 0-.894 1.789l.894-1.789zm1.106 2.789a1 1 0 1 0 .894-1.789l-.894 1.789zM2 5a1 1 0 1 0-2 0h2zM0 7.5a1 1 0 1 0 2 0H0zm8.553 12.394a1 1 0 1 0 .894-1.789l-.894 1.789zm-1.106-2.789a1 1 0 1 0-.894 1.789l.894-1.789zm1.106 1a1 1 0 1 0 .894 1.789l-.894-1.789zm2.894.789a1 1 0 1 0-.894-1.789l.894 1.789zM8 19a1 1 0 1 0 2 0H8zm2-2.5a1 1 0 1 0-2 0h2zm-7.447.394a1 1 0 1 0 .894-1.789l-.894 1.789zM1 15H0a1 1 0 0 0 .553.894L1 15zm1-2.5a1 1 0 1 0-2 0h2zm12.553 2.606a1 1 0 1 0 .894 1.789l-.894-1.789zM17 15l.447.894A1 1 0 0 0 18 15h-1zm1-2.5a1 1 0 1 0-2 0h2zm-7.447-5.394l-2 1 .894 1.789 2-1-.894-1.789zm-1.106 1l-2-1-.894 1.789 2 1 .894-1.789zM8 9v2.5h2V9H8zm8.553-4.894l-2 1 .894 1.789 2-1-.894-1.789zm.894 0l-2-1-.894 1.789 2 1 .894-1.789zM16 5v2.5h2V5h-2zm-4.553-3.894l-2-1-.894 1.789 2 1 .894-1.789zm-2.894-1l-2 1 .894 1.789 2-1L8.553.106zM1.447 5.894l2-1-.894-1.789-2 1 .894 1.789zm-.894 0l2 1 .894-1.789-2-1-.894 1.789zM0 5v2.5h2V5H0zm9.447 13.106l-2-1-.894 1.789 2 1 .894-1.789zm0 1.789l2-1-.894-1.789-2 1 .894 1.789zM10 19v-2.5H8V19h2zm-6.553-3.894l-2-1-.894 1.789 2 1 .894-1.789zM2 15v-2.5H0V15h2zm13.447 1.894l2-1-.894-1.789-2 1 .894 1.789zM18 15v-2.5h-2V15h2z"
|
||||
/>
|
||||
</svg>
|
||||
</template>
|
||||
@ -0,0 +1,7 @@
|
||||
<template>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" fill="currentColor">
|
||||
<path
|
||||
d="M10 3.22l-.61-.6a5.5 5.5 0 0 0-7.666.105 5.5 5.5 0 0 0-.114 7.665L10 18.78l8.39-8.4a5.5 5.5 0 0 0-.114-7.665 5.5 5.5 0 0 0-7.666-.105l-.61.61z"
|
||||
/>
|
||||
</svg>
|
||||
</template>
|
||||
@ -0,0 +1,19 @@
|
||||
<!-- This icon is from <https://github.com/Templarian/MaterialDesign>, distributed under Apache 2.0 (https://www.apache.org/licenses/LICENSE-2.0) license-->
|
||||
<template>
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
xmlns:xlink="http://www.w3.org/1999/xlink"
|
||||
aria-hidden="true"
|
||||
role="img"
|
||||
class="iconify iconify--mdi"
|
||||
width="24"
|
||||
height="24"
|
||||
preserveAspectRatio="xMidYMid meet"
|
||||
viewBox="0 0 24 24"
|
||||
>
|
||||
<path
|
||||
d="M20 18v-4h-3v1h-2v-1H9v1H7v-1H4v4h16M6.33 8l-1.74 4H7v-1h2v1h6v-1h2v1h2.41l-1.74-4H6.33M9 5v1h6V5H9m12.84 7.61c.1.22.16.48.16.8V18c0 .53-.21 1-.6 1.41c-.4.4-.85.59-1.4.59H4c-.55 0-1-.19-1.4-.59C2.21 19 2 18.53 2 18v-4.59c0-.32.06-.58.16-.8L4.5 7.22C4.84 6.41 5.45 6 6.33 6H7V5c0-.55.18-1 .57-1.41C7.96 3.2 8.44 3 9 3h6c.56 0 1.04.2 1.43.59c.39.41.57.86.57 1.41v1h.67c.88 0 1.49.41 1.83 1.22l2.34 5.39z"
|
||||
fill="currentColor"
|
||||
></path>
|
||||
</svg>
|
||||
</template>
|
||||
@ -0,0 +1,341 @@
|
||||
import { ref, onUnmounted } from 'vue'
|
||||
import { useRobotStore } from '@/stores/robot'
|
||||
import type { InitResponse, MoveRequest, MoveAck } from '@/types/ws'
|
||||
|
||||
export function useWebSocket() {
|
||||
const ws = ref<WebSocket | null>(null)
|
||||
const isConnected = ref(false)
|
||||
const error = ref<string | null>(null)
|
||||
const robotStore = useRobotStore()
|
||||
|
||||
let reconnectTimeout: number | null = null
|
||||
let reconnectAttempts = 0
|
||||
const MAX_RECONNECT_ATTEMPTS = 5
|
||||
|
||||
// 连接状态管理
|
||||
let isManualDisconnect = false
|
||||
let currentConnectionId: string | null = null
|
||||
let currentConnectionUrl: string | null = null
|
||||
|
||||
// 心跳机制
|
||||
let heartbeatInterval: number | null = null
|
||||
let lastPongTime: number = Date.now()
|
||||
const HEARTBEAT_INTERVAL = 30000 // 30秒
|
||||
const PONG_TIMEOUT = 45000 // 45秒
|
||||
|
||||
const connect = (url: string) => {
|
||||
// 生成唯一连接ID
|
||||
const connectionId = Date.now().toString()
|
||||
currentConnectionId = connectionId
|
||||
currentConnectionUrl = url
|
||||
|
||||
// 清理之前的连接
|
||||
cleanupPreviousConnection()
|
||||
|
||||
console.log(`开始连接 [${connectionId}] -> ${url}`)
|
||||
updateConnectionStatus('connecting', connectionId)
|
||||
ws.value = new WebSocket(url)
|
||||
|
||||
ws.value.onopen = () => {
|
||||
// 检查是否是当前活跃连接
|
||||
if (currentConnectionId !== connectionId) {
|
||||
console.log(`忽略旧连接 [${connectionId}] 的onopen事件,当前活跃连接: [${currentConnectionId}]`)
|
||||
try {
|
||||
ws.value?.close(1000, '连接已切换')
|
||||
} catch (e) {
|
||||
// 忽略错误
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
error.value = null
|
||||
reconnectAttempts = 0
|
||||
lastPongTime = Date.now()
|
||||
updateConnectionStatus('connected', connectionId)
|
||||
startHeartbeat()
|
||||
console.log(`WebSocket连接成功 [${connectionId}]`)
|
||||
}
|
||||
|
||||
ws.value.onmessage = (event) => {
|
||||
// 检查是否是当前活跃连接
|
||||
if (currentConnectionId !== connectionId) {
|
||||
console.log(`忽略旧连接 [${connectionId}] 的消息,当前活跃连接: [${currentConnectionId}]`)
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
const data = JSON.parse(event.data)
|
||||
|
||||
if ('id' in data && 'joints' in data) {
|
||||
handleInitMessage(data as InitResponse)
|
||||
} else if ('type' in data && data.type === 'move_ack') {
|
||||
handleMoveAck(data as MoveAck)
|
||||
} else if ('type' in data && data.type === 'pong') {
|
||||
handlePong(data.timestamp || Date.now())
|
||||
} else {
|
||||
console.log(`收到未知消息类型 [${connectionId}]:`, data)
|
||||
}
|
||||
} catch (e) {
|
||||
console.error(`消息解析失败 [${connectionId}]:`, e, '原始数据:', event.data)
|
||||
error.value = '消息解析失败'
|
||||
}
|
||||
}
|
||||
|
||||
ws.value.onerror = (event) => {
|
||||
// 检查是否是当前活跃连接
|
||||
if (currentConnectionId !== connectionId) {
|
||||
console.log(`忽略旧连接 [${connectionId}] 的错误事件`)
|
||||
return
|
||||
}
|
||||
|
||||
error.value = 'WebSocket连接错误'
|
||||
updateConnectionStatus('disconnected', connectionId)
|
||||
console.error(`WebSocket连接错误 [${connectionId}]`)
|
||||
}
|
||||
|
||||
ws.value.onclose = (event) => {
|
||||
stopHeartbeat()
|
||||
updateConnectionStatus('disconnected', connectionId)
|
||||
console.log(`WebSocket连接关闭 [${connectionId}],代码: ${event.code}, 原因: ${event.reason}`)
|
||||
|
||||
// 检查是否是当前活跃连接(防止旧连接事件干扰)
|
||||
if (currentConnectionId !== connectionId) {
|
||||
console.log(`忽略旧连接 [${connectionId}] 的关闭事件,当前活跃连接: [${currentConnectionId}]`)
|
||||
return
|
||||
}
|
||||
|
||||
// 如果是用户主动断开,不进行重连
|
||||
if (isManualDisconnect) {
|
||||
console.log(`用户主动断开连接 [${connectionId}],不进行重连`)
|
||||
isManualDisconnect = false
|
||||
currentConnectionId = null
|
||||
currentConnectionUrl = null
|
||||
return
|
||||
}
|
||||
|
||||
// 意外断开,使用指数退避策略重连
|
||||
if (reconnectAttempts < MAX_RECONNECT_ATTEMPTS) {
|
||||
const delay = Math.min(3000 * Math.pow(1.5, reconnectAttempts), 30000)
|
||||
reconnectTimeout = setTimeout(() => {
|
||||
// 再次检查连接ID是否匹配
|
||||
if (currentConnectionId !== connectionId) {
|
||||
console.log(`连接已切换 [${connectionId}] -> [${currentConnectionId}],停止重连`)
|
||||
return
|
||||
}
|
||||
|
||||
reconnectAttempts++
|
||||
console.log(`第${reconnectAttempts}次重连尝试 [${connectionId}],延迟: ${delay}ms`)
|
||||
reconnect(url)
|
||||
}, delay) as unknown as number
|
||||
} else {
|
||||
console.log(`达到最大重连次数 [${connectionId}],停止重连`)
|
||||
currentConnectionId = null
|
||||
currentConnectionUrl = null
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const handleInitMessage = (data: InitResponse) => {
|
||||
robotStore.initRobot(data.id, data.joints)
|
||||
}
|
||||
|
||||
const handleMoveAck = (data: MoveAck) => {
|
||||
if (data.status === 'success') {
|
||||
console.log(`服务器确认关节 ${data.joint} 角度: ${data.angle}°`)
|
||||
// 服务器确认,不需要再发送到服务器
|
||||
// 注意:这里需要先移除状态锁,然后更新角度
|
||||
const store = robotStore as any
|
||||
if (store.sendingCommands) {
|
||||
store.sendingCommands.delete(data.joint)
|
||||
}
|
||||
robotStore.updateJointAngle(data.joint, data.angle, false)
|
||||
} else {
|
||||
console.error(`服务器拒绝关节 ${data.joint} 角度: ${data.angle}°`)
|
||||
// 服务器拒绝,也需要移除状态锁
|
||||
const store = robotStore as any
|
||||
if (store.sendingCommands) {
|
||||
store.sendingCommands.delete(data.joint)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 心跳相关函数
|
||||
const startHeartbeat = () => {
|
||||
stopHeartbeat()
|
||||
|
||||
heartbeatInterval = setInterval(() => {
|
||||
if (ws.value?.readyState === WebSocket.OPEN) {
|
||||
// 检查上次pong响应是否超时
|
||||
const now = Date.now()
|
||||
if (now - lastPongTime > PONG_TIMEOUT) {
|
||||
console.warn('心跳超时,重新连接')
|
||||
disconnect()
|
||||
return
|
||||
}
|
||||
|
||||
// 发送ping消息
|
||||
try {
|
||||
ws.value.send(JSON.stringify({ type: 'ping', timestamp: now }))
|
||||
} catch (e) {
|
||||
console.error('发送心跳失败:', e)
|
||||
}
|
||||
}
|
||||
}, HEARTBEAT_INTERVAL) as unknown as number
|
||||
}
|
||||
|
||||
const stopHeartbeat = () => {
|
||||
if (heartbeatInterval) {
|
||||
clearInterval(heartbeatInterval)
|
||||
heartbeatInterval = null
|
||||
}
|
||||
}
|
||||
|
||||
const handlePong = (timestamp: number) => {
|
||||
lastPongTime = Date.now()
|
||||
console.log(`收到pong响应,延迟: ${lastPongTime - timestamp}ms`)
|
||||
}
|
||||
|
||||
// 统一更新连接状态
|
||||
const updateConnectionStatus = (status: 'disconnected' | 'connecting' | 'connected', connectionId?: string) => {
|
||||
// 检查连接ID是否匹配(如果提供了connectionId)
|
||||
if (connectionId && currentConnectionId !== connectionId) {
|
||||
console.log(`忽略旧连接 [${connectionId}] 的状态更新,当前活跃连接: [${currentConnectionId}]`)
|
||||
return
|
||||
}
|
||||
|
||||
isConnected.value = status === 'connected'
|
||||
robotStore.setConnectionStatus(status)
|
||||
|
||||
// 清理错误状态
|
||||
if (status !== 'disconnected') {
|
||||
error.value = null
|
||||
}
|
||||
|
||||
console.log(`连接状态更新 [${currentConnectionId || 'none'}]: ${status}`)
|
||||
}
|
||||
|
||||
// 清理之前的连接
|
||||
const cleanupPreviousConnection = () => {
|
||||
console.log('清理之前的连接状态')
|
||||
|
||||
// 停止心跳
|
||||
stopHeartbeat()
|
||||
|
||||
// 清除重连定时器
|
||||
if (reconnectTimeout) {
|
||||
clearTimeout(reconnectTimeout)
|
||||
reconnectTimeout = null
|
||||
}
|
||||
|
||||
// 重置重连尝试计数
|
||||
reconnectAttempts = 0
|
||||
|
||||
// 关闭现有的WebSocket连接
|
||||
if (ws.value) {
|
||||
try {
|
||||
// 不设置isManualDisconnect,因为这是连接切换,不是用户主动断开
|
||||
ws.value.close(1000, '连接切换')
|
||||
} catch (e) {
|
||||
// 忽略关闭错误
|
||||
}
|
||||
ws.value = null
|
||||
}
|
||||
|
||||
// 更新连接状态
|
||||
updateConnectionStatus('disconnected')
|
||||
}
|
||||
|
||||
const reconnect = (url: string) => {
|
||||
if (reconnectTimeout) {
|
||||
clearTimeout(reconnectTimeout)
|
||||
reconnectTimeout = null
|
||||
}
|
||||
|
||||
// 检查当前连接URL是否匹配
|
||||
if (currentConnectionUrl !== url) {
|
||||
console.log(`重连URL不匹配: 当前 ${currentConnectionUrl}, 目标 ${url}`)
|
||||
return
|
||||
}
|
||||
|
||||
connect(url)
|
||||
}
|
||||
|
||||
const sendMoveCommand = (jointId: string, angle: number) => {
|
||||
if (ws.value?.readyState === WebSocket.OPEN) {
|
||||
const command: MoveRequest = { id: jointId, angel: angle }
|
||||
ws.value.send(JSON.stringify(command))
|
||||
}
|
||||
}
|
||||
|
||||
const disconnect = () => {
|
||||
console.log(`用户主动断开连接 [${currentConnectionId}]`)
|
||||
isManualDisconnect = true
|
||||
|
||||
stopHeartbeat()
|
||||
|
||||
if (reconnectTimeout) {
|
||||
clearTimeout(reconnectTimeout)
|
||||
reconnectTimeout = null
|
||||
}
|
||||
|
||||
if (ws.value) {
|
||||
try {
|
||||
ws.value.close(1000, '用户主动断开')
|
||||
} catch (e) {
|
||||
console.error('关闭WebSocket时出错:', e)
|
||||
}
|
||||
ws.value = null
|
||||
}
|
||||
|
||||
updateConnectionStatus('disconnected')
|
||||
console.log('WebSocket已断开')
|
||||
}
|
||||
|
||||
// 完全重置连接状态
|
||||
const resetConnection = () => {
|
||||
console.log('完全重置连接状态')
|
||||
|
||||
// 重置所有状态变量
|
||||
isManualDisconnect = false
|
||||
currentConnectionId = null
|
||||
currentConnectionUrl = null
|
||||
reconnectAttempts = 0
|
||||
|
||||
// 停止所有定时器
|
||||
stopHeartbeat()
|
||||
|
||||
if (reconnectTimeout) {
|
||||
clearTimeout(reconnectTimeout)
|
||||
reconnectTimeout = null
|
||||
}
|
||||
|
||||
// 关闭WebSocket
|
||||
if (ws.value) {
|
||||
try {
|
||||
ws.value.close(1000, '连接重置')
|
||||
} catch (e) {
|
||||
// 忽略错误
|
||||
}
|
||||
ws.value = null
|
||||
}
|
||||
|
||||
// 更新状态
|
||||
updateConnectionStatus('disconnected')
|
||||
error.value = null
|
||||
|
||||
console.log('连接状态已完全重置')
|
||||
}
|
||||
|
||||
onUnmounted(() => {
|
||||
disconnect()
|
||||
})
|
||||
|
||||
return {
|
||||
connect,
|
||||
sendMoveCommand,
|
||||
disconnect,
|
||||
resetConnection,
|
||||
isConnected,
|
||||
error
|
||||
}
|
||||
}
|
||||
12
frontend/src/main.ts
普通文件
12
frontend/src/main.ts
普通文件
@ -0,0 +1,12 @@
|
||||
import './assets/main.css'
|
||||
|
||||
import { createApp } from 'vue'
|
||||
import { createPinia } from 'pinia'
|
||||
|
||||
import App from './App.vue'
|
||||
|
||||
const app = createApp(App)
|
||||
|
||||
app.use(createPinia())
|
||||
|
||||
app.mount('#app')
|
||||
23
frontend/src/router/index.ts
普通文件
23
frontend/src/router/index.ts
普通文件
@ -0,0 +1,23 @@
|
||||
import { createRouter, createWebHistory } from 'vue-router'
|
||||
import HomeView from '../views/HomeView.vue'
|
||||
|
||||
const router = createRouter({
|
||||
history: createWebHistory(import.meta.env.BASE_URL),
|
||||
routes: [
|
||||
{
|
||||
path: '/',
|
||||
name: 'home',
|
||||
component: HomeView,
|
||||
},
|
||||
{
|
||||
path: '/about',
|
||||
name: 'about',
|
||||
// route level code-splitting
|
||||
// this generates a separate chunk (About.[hash].js) for this route
|
||||
// which is lazy-loaded when the route is visited.
|
||||
component: () => import('../views/AboutView.vue'),
|
||||
},
|
||||
],
|
||||
})
|
||||
|
||||
export default router
|
||||
12
frontend/src/stores/counter.ts
普通文件
12
frontend/src/stores/counter.ts
普通文件
@ -0,0 +1,12 @@
|
||||
import { ref, computed } from 'vue'
|
||||
import { defineStore } from 'pinia'
|
||||
|
||||
export const useCounterStore = defineStore('counter', () => {
|
||||
const count = ref(0)
|
||||
const doubleCount = computed(() => count.value * 2)
|
||||
function increment() {
|
||||
count.value++
|
||||
}
|
||||
|
||||
return { count, doubleCount, increment }
|
||||
})
|
||||
143
frontend/src/stores/robot.ts
普通文件
143
frontend/src/stores/robot.ts
普通文件
@ -0,0 +1,143 @@
|
||||
import { defineStore } from 'pinia'
|
||||
import type { Joint, JointState } from '@/types/ws'
|
||||
import { debounceWithImmediate } from '@/utils/debounce'
|
||||
|
||||
// WebSocket功能接口
|
||||
interface WebSocketFunctions {
|
||||
sendMoveCommand: (jointId: string, angle: number) => void
|
||||
isConnected: { value: boolean }
|
||||
}
|
||||
|
||||
let webSocketFunctions: WebSocketFunctions | null = null
|
||||
|
||||
// 防抖发送函数缓存
|
||||
const debouncedSendCommands = new Map<string, ReturnType<typeof debounceWithImmediate>>()
|
||||
|
||||
// 状态锁:跟踪正在发送命令的关节,防止在发送过程中更新本地状态
|
||||
const sendingCommands = new Set<string>()
|
||||
|
||||
export const useRobotStore = defineStore('robot', {
|
||||
state: () => ({
|
||||
robotId: null as string | null,
|
||||
joints: new Map<string, JointState>(),
|
||||
connectionStatus: 'disconnected' as 'disconnected' | 'connecting' | 'connected',
|
||||
selectedJoint: null as string | null
|
||||
}),
|
||||
|
||||
getters: {
|
||||
jointList: (state) => Array.from(state.joints.values()),
|
||||
jointCount: (state) => state.joints.size,
|
||||
selectedJointState: (state) => {
|
||||
if (!state.selectedJoint) return null
|
||||
return state.joints.get(state.selectedJoint) || null
|
||||
},
|
||||
isWebSocketAvailable: () => webSocketFunctions !== null
|
||||
},
|
||||
|
||||
actions: {
|
||||
// 注入WebSocket功能
|
||||
setWebSocketFunctions(functions: WebSocketFunctions) {
|
||||
webSocketFunctions = functions
|
||||
},
|
||||
|
||||
initRobot(robotId: string, joints: Joint[]) {
|
||||
this.robotId = robotId
|
||||
this.joints.clear()
|
||||
|
||||
joints.forEach(joint => {
|
||||
this.joints.set(joint.id, {
|
||||
...joint,
|
||||
currentAngle: joint.default
|
||||
})
|
||||
})
|
||||
},
|
||||
|
||||
updateJointAngle(jointId: string, angle: number, sendToServer: boolean = true) {
|
||||
const joint = this.joints.get(jointId)
|
||||
if (joint) {
|
||||
const clampedAngle = this.clampAngle(angle, joint.range)
|
||||
|
||||
// 如果正在向服务器发送命令,跳过本地更新(等待服务器确认)
|
||||
if (sendingCommands.has(jointId)) {
|
||||
console.log(`关节 ${jointId} 正在发送命令,跳过本地更新`)
|
||||
return
|
||||
}
|
||||
|
||||
joint.currentAngle = clampedAngle
|
||||
|
||||
// 自动发送到服务器(如果WebSocket可用且已连接,且需要发送)
|
||||
if (sendToServer && webSocketFunctions?.isConnected.value) {
|
||||
sendingCommands.add(jointId)
|
||||
this.sendDebouncedCommand(jointId, clampedAngle)
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
// 防抖发送命令
|
||||
sendDebouncedCommand(jointId: string, angle: number) {
|
||||
if (!webSocketFunctions) {
|
||||
sendingCommands.delete(jointId)
|
||||
return
|
||||
}
|
||||
|
||||
// 为每个关节创建或获取防抖函数
|
||||
let debouncedSend = debouncedSendCommands.get(jointId)
|
||||
if (!debouncedSend) {
|
||||
debouncedSend = debounceWithImmediate(
|
||||
(id: string, ang: number) => {
|
||||
console.log(`发送关节 ${id} 角度: ${ang}°`)
|
||||
webSocketFunctions!.sendMoveCommand(id, ang)
|
||||
// 命令已发送,但需要等待服务器确认后才能移除锁
|
||||
// 锁将在服务器确认后由handleMoveAck移除
|
||||
},
|
||||
150, // 150ms防抖延迟,避免快速操作冲突
|
||||
true // 立即执行第一次
|
||||
)
|
||||
debouncedSendCommands.set(jointId, debouncedSend)
|
||||
}
|
||||
|
||||
// 调用防抖函数
|
||||
debouncedSend(jointId, angle)
|
||||
},
|
||||
|
||||
resetAllJoints() {
|
||||
this.joints.forEach((joint: JointState) => {
|
||||
const defaultAngle = joint.default
|
||||
// 使用updateJointAngle自动发送到服务器
|
||||
this.updateJointAngle(joint.id, defaultAngle, true)
|
||||
})
|
||||
},
|
||||
|
||||
clampAngle(angle: number, range: [number, number]): number {
|
||||
return Math.min(Math.max(angle, range[0]), range[1])
|
||||
},
|
||||
|
||||
setConnectionStatus(status: 'disconnected' | 'connecting' | 'connected') {
|
||||
this.connectionStatus = status
|
||||
},
|
||||
|
||||
selectJoint(jointId: string | null) {
|
||||
this.selectedJoint = jointId
|
||||
},
|
||||
|
||||
// 清理机器人状态
|
||||
clearRobot() {
|
||||
this.robotId = null
|
||||
this.joints.clear()
|
||||
this.selectedJoint = null
|
||||
this.connectionStatus = 'disconnected'
|
||||
|
||||
// 清除防抖缓存和状态锁
|
||||
debouncedSendCommands.clear()
|
||||
sendingCommands.clear()
|
||||
|
||||
console.log('机器人状态已清理')
|
||||
},
|
||||
|
||||
// 强制更新连接状态(用于状态同步)
|
||||
forceConnectionStatus(status: 'disconnected' | 'connecting' | 'connected') {
|
||||
this.connectionStatus = status
|
||||
console.log(`强制更新连接状态: ${status}`)
|
||||
}
|
||||
}
|
||||
})
|
||||
30
frontend/src/types/ws.ts
普通文件
30
frontend/src/types/ws.ts
普通文件
@ -0,0 +1,30 @@
|
||||
export interface Joint {
|
||||
id: string
|
||||
range: [number, number]
|
||||
default: number
|
||||
type: "joint" | "flex_w" | "flex_v" | "gripper"
|
||||
next?: string
|
||||
}
|
||||
|
||||
export interface InitResponse {
|
||||
id: string
|
||||
joints: Joint[]
|
||||
}
|
||||
|
||||
export interface MoveRequest {
|
||||
id: string
|
||||
angel: number
|
||||
}
|
||||
|
||||
export interface MoveAck {
|
||||
type: "move_ack"
|
||||
joint: string
|
||||
angle: number
|
||||
status: "success" | "error"
|
||||
}
|
||||
|
||||
export type WebSocketMessage = InitResponse | MoveAck
|
||||
|
||||
export interface JointState extends Joint {
|
||||
currentAngle: number
|
||||
}
|
||||
95
frontend/src/utils/debounce.ts
普通文件
95
frontend/src/utils/debounce.ts
普通文件
@ -0,0 +1,95 @@
|
||||
/**
|
||||
* 防抖函数
|
||||
* @param fn 要执行的函数
|
||||
* @param delay 延迟时间(毫秒)
|
||||
* @returns 防抖后的函数
|
||||
*/
|
||||
export function debounce<T extends (...args: any[]) => any>(
|
||||
fn: T,
|
||||
delay: number
|
||||
): (...args: Parameters<T>) => void {
|
||||
let timeoutId: number | null = null
|
||||
|
||||
return (...args: Parameters<T>) => {
|
||||
if (timeoutId) {
|
||||
clearTimeout(timeoutId)
|
||||
}
|
||||
|
||||
timeoutId = setTimeout(() => {
|
||||
fn(...args)
|
||||
timeoutId = null
|
||||
}, delay)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 带立即执行选项的防抖函数
|
||||
* @param fn 要执行的函数
|
||||
* @param delay 延迟时间(毫秒)
|
||||
* @param immediate 是否立即执行
|
||||
* @returns 防抖后的函数
|
||||
*/
|
||||
export function debounceWithImmediate<T extends (...args: any[]) => any>(
|
||||
fn: T,
|
||||
delay: number,
|
||||
immediate: boolean = false
|
||||
): (...args: Parameters<T>) => void {
|
||||
let timeoutId: number | null = null
|
||||
let lastCallTime: number = 0
|
||||
let lastArgs: Parameters<T> | null = null
|
||||
|
||||
return (...args: Parameters<T>) => {
|
||||
const now = Date.now()
|
||||
lastArgs = args
|
||||
|
||||
if (immediate && (!lastCallTime || now - lastCallTime > delay)) {
|
||||
// 立即执行
|
||||
fn(...args)
|
||||
lastCallTime = now
|
||||
} else {
|
||||
// 延迟执行
|
||||
if (timeoutId) {
|
||||
clearTimeout(timeoutId)
|
||||
}
|
||||
|
||||
timeoutId = setTimeout(() => {
|
||||
if (lastArgs) {
|
||||
fn(...lastArgs)
|
||||
lastArgs = null
|
||||
}
|
||||
timeoutId = null
|
||||
lastCallTime = Date.now()
|
||||
}, delay)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 优化的防抖函数,确保最后一次调用总是被执行
|
||||
* @param fn 要执行的函数
|
||||
* @param delay 延迟时间(毫秒)
|
||||
* @returns 防抖后的函数
|
||||
*/
|
||||
export function debounceTrailing<T extends (...args: any[]) => any>(
|
||||
fn: T,
|
||||
delay: number
|
||||
): (...args: Parameters<T>) => void {
|
||||
let timeoutId: number | null = null
|
||||
let lastArgs: Parameters<T> | null = null
|
||||
|
||||
return (...args: Parameters<T>) => {
|
||||
lastArgs = args
|
||||
|
||||
if (timeoutId) {
|
||||
clearTimeout(timeoutId)
|
||||
}
|
||||
|
||||
timeoutId = setTimeout(() => {
|
||||
if (lastArgs) {
|
||||
fn(...lastArgs)
|
||||
lastArgs = null
|
||||
}
|
||||
timeoutId = null
|
||||
}, delay)
|
||||
}
|
||||
}
|
||||
15
frontend/src/views/AboutView.vue
普通文件
15
frontend/src/views/AboutView.vue
普通文件
@ -0,0 +1,15 @@
|
||||
<template>
|
||||
<div class="about">
|
||||
<h1>This is an about page</h1>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style>
|
||||
@media (min-width: 1024px) {
|
||||
.about {
|
||||
min-height: 100vh;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@ -0,0 +1,9 @@
|
||||
<script setup lang="ts">
|
||||
import TheWelcome from '../components/TheWelcome.vue'
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<main>
|
||||
<TheWelcome />
|
||||
</main>
|
||||
</template>
|
||||
18
frontend/tsconfig.app.json
普通文件
18
frontend/tsconfig.app.json
普通文件
@ -0,0 +1,18 @@
|
||||
{
|
||||
"extends": "@vue/tsconfig/tsconfig.dom.json",
|
||||
"include": ["env.d.ts", "src/**/*", "src/**/*.vue"],
|
||||
"exclude": ["src/**/__tests__/*"],
|
||||
"compilerOptions": {
|
||||
// Extra safety for array and object lookups, but may have false positives.
|
||||
"noUncheckedIndexedAccess": true,
|
||||
|
||||
// Path mapping for cleaner imports.
|
||||
"paths": {
|
||||
"@/*": ["./src/*"]
|
||||
},
|
||||
|
||||
// `vue-tsc --build` produces a .tsbuildinfo file for incremental type-checking.
|
||||
// Specified here to keep it out of the root directory.
|
||||
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo"
|
||||
}
|
||||
}
|
||||
11
frontend/tsconfig.json
普通文件
11
frontend/tsconfig.json
普通文件
@ -0,0 +1,11 @@
|
||||
{
|
||||
"files": [],
|
||||
"references": [
|
||||
{
|
||||
"path": "./tsconfig.node.json"
|
||||
},
|
||||
{
|
||||
"path": "./tsconfig.app.json"
|
||||
}
|
||||
]
|
||||
}
|
||||
28
frontend/tsconfig.node.json
普通文件
28
frontend/tsconfig.node.json
普通文件
@ -0,0 +1,28 @@
|
||||
// TSConfig for modules that run in Node.js environment via either transpilation or type-stripping.
|
||||
{
|
||||
"extends": "@tsconfig/node24/tsconfig.json",
|
||||
"include": [
|
||||
"vite.config.*",
|
||||
"vitest.config.*",
|
||||
"cypress.config.*",
|
||||
"nightwatch.conf.*",
|
||||
"playwright.config.*",
|
||||
"eslint.config.*"
|
||||
],
|
||||
"compilerOptions": {
|
||||
// Most tools use transpilation instead of Node.js's native type-stripping.
|
||||
// Bundler mode provides a smoother developer experience.
|
||||
"module": "preserve",
|
||||
"moduleResolution": "bundler",
|
||||
|
||||
// Include Node.js types and avoid accidentally including other `@types/*` packages.
|
||||
"types": ["node"],
|
||||
|
||||
// Disable emitting output during `vue-tsc --build`, which is used for type-checking only.
|
||||
"noEmit": true,
|
||||
|
||||
// `vue-tsc --build` produces a .tsbuildinfo file for incremental type-checking.
|
||||
// Specified here to keep it out of the root directory.
|
||||
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo"
|
||||
}
|
||||
}
|
||||
18
frontend/vite.config.ts
普通文件
18
frontend/vite.config.ts
普通文件
@ -0,0 +1,18 @@
|
||||
import { fileURLToPath, URL } from 'node:url'
|
||||
|
||||
import { defineConfig } from 'vite'
|
||||
import vue from '@vitejs/plugin-vue'
|
||||
import vueDevTools from 'vite-plugin-vue-devtools'
|
||||
|
||||
// https://vite.dev/config/
|
||||
export default defineConfig({
|
||||
plugins: [
|
||||
vue(),
|
||||
vueDevTools(),
|
||||
],
|
||||
resolve: {
|
||||
alias: {
|
||||
'@': fileURLToPath(new URL('./src', import.meta.url))
|
||||
},
|
||||
},
|
||||
})
|
||||
二进制文件未显示。
79
mock-server/main.py
普通文件
79
mock-server/main.py
普通文件
@ -0,0 +1,79 @@
|
||||
from fastapi import FastAPI, WebSocket, WebSocketDisconnect
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
import json
|
||||
from robot_config import SIX_AXIS_ROBOT, SCARA_ROBOT
|
||||
|
||||
app = FastAPI()
|
||||
|
||||
app.add_middleware(
|
||||
CORSMiddleware,
|
||||
allow_origins=["*"],
|
||||
allow_credentials=True,
|
||||
allow_methods=["*"],
|
||||
allow_headers=["*"],
|
||||
)
|
||||
|
||||
|
||||
@app.websocket("/ws/{robot_type}")
|
||||
async def websocket_endpoint(websocket: WebSocket, robot_type: str = "six_axis"):
|
||||
await websocket.accept()
|
||||
|
||||
if robot_type == "scara":
|
||||
robot_config = SCARA_ROBOT
|
||||
else:
|
||||
robot_config = SIX_AXIS_ROBOT
|
||||
|
||||
await websocket.send_json(robot_config)
|
||||
|
||||
joint_states = {joint["id"]: joint["default"] for joint in robot_config["joints"]}
|
||||
|
||||
try:
|
||||
while True:
|
||||
message = await websocket.receive_text()
|
||||
data = json.loads(message)
|
||||
|
||||
if "id" in data and "angel" in data:
|
||||
joint_id = data["id"]
|
||||
target_angle = data["angel"]
|
||||
|
||||
if joint_id in joint_states:
|
||||
joint_states[joint_id] = target_angle
|
||||
|
||||
await websocket.send_json(
|
||||
{
|
||||
"type": "move_ack",
|
||||
"joint": joint_id,
|
||||
"angle": target_angle,
|
||||
"status": "success",
|
||||
}
|
||||
)
|
||||
elif "type" in data and data["type"] == "ping":
|
||||
# 响应心跳消息
|
||||
await websocket.send_json(
|
||||
{"type": "pong", "timestamp": data.get("timestamp", 0)}
|
||||
)
|
||||
else:
|
||||
print(f"收到未知消息: {data}")
|
||||
|
||||
except WebSocketDisconnect:
|
||||
print(f"Client disconnected for robot: {robot_type}")
|
||||
except json.JSONDecodeError as e:
|
||||
print(f"JSON解析错误: {e}")
|
||||
except Exception as e:
|
||||
print(f"错误: {e}")
|
||||
|
||||
|
||||
@app.get("/api/robots")
|
||||
async def get_robot_list():
|
||||
return {
|
||||
"robots": [
|
||||
{"id": "six_axis", "name": "6轴工业机械臂"},
|
||||
{"id": "scara", "name": "SCARA机器人"},
|
||||
]
|
||||
}
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
import uvicorn
|
||||
|
||||
uvicorn.run(app, host="0.0.0.0", port=8000)
|
||||
3
mock-server/requirements.txt
普通文件
3
mock-server/requirements.txt
普通文件
@ -0,0 +1,3 @@
|
||||
fastapi==0.104.1
|
||||
uvicorn[standard]==0.24.0
|
||||
websockets==12.0
|
||||
90
mock-server/robot_config.py
普通文件
90
mock-server/robot_config.py
普通文件
@ -0,0 +1,90 @@
|
||||
from typing import List, Dict, Any
|
||||
|
||||
SIX_AXIS_ROBOT = {
|
||||
"id": "robot_6dof_001",
|
||||
"joints": [
|
||||
{
|
||||
"id": "base",
|
||||
"range": [-180, 180],
|
||||
"default": 0,
|
||||
"type": "flex_w",
|
||||
"next": "shoulder",
|
||||
},
|
||||
{
|
||||
"id": "shoulder",
|
||||
"range": [-90, 90],
|
||||
"default": 45,
|
||||
"type": "joint",
|
||||
"next": "elbow",
|
||||
},
|
||||
{
|
||||
"id": "elbow",
|
||||
"range": [-135, 135],
|
||||
"default": -30,
|
||||
"type": "joint",
|
||||
"next": "wrist1",
|
||||
},
|
||||
{
|
||||
"id": "wrist1",
|
||||
"range": [-180, 180],
|
||||
"default": 0,
|
||||
"type": "flex_v",
|
||||
"next": "wrist2",
|
||||
},
|
||||
{
|
||||
"id": "wrist2",
|
||||
"range": [-90, 90],
|
||||
"default": 0,
|
||||
"type": "flex_v",
|
||||
"next": "gripper",
|
||||
},
|
||||
{
|
||||
"id": "gripper",
|
||||
"range": [0, 100],
|
||||
"default": 50,
|
||||
"type": "gripper",
|
||||
"next": None,
|
||||
},
|
||||
],
|
||||
}
|
||||
|
||||
SCARA_ROBOT = {
|
||||
"id": "scara_001",
|
||||
"joints": [
|
||||
{
|
||||
"id": "waist",
|
||||
"range": [-170, 170],
|
||||
"default": 0,
|
||||
"type": "flex_w",
|
||||
"next": "arm1",
|
||||
},
|
||||
{
|
||||
"id": "arm1",
|
||||
"range": [-150, 150],
|
||||
"default": 30,
|
||||
"type": "joint",
|
||||
"next": "arm2",
|
||||
},
|
||||
{
|
||||
"id": "arm2",
|
||||
"range": [-150, 150],
|
||||
"default": -45,
|
||||
"type": "joint",
|
||||
"next": "wrist",
|
||||
},
|
||||
{
|
||||
"id": "wrist",
|
||||
"range": [-360, 360],
|
||||
"default": 0,
|
||||
"type": "flex_v",
|
||||
"next": "gripper",
|
||||
},
|
||||
{
|
||||
"id": "gripper",
|
||||
"range": [0, 100],
|
||||
"default": 30,
|
||||
"type": "gripper",
|
||||
"next": None,
|
||||
},
|
||||
],
|
||||
}
|
||||
46
start.sh
可执行文件
46
start.sh
可执行文件
@ -0,0 +1,46 @@
|
||||
#!/bin/bash
|
||||
|
||||
echo "启动机械臂控制助手..."
|
||||
|
||||
# 检查是否在后端目录
|
||||
if [ ! -f "mock-server/main.py" ]; then
|
||||
echo "错误:请在项目根目录运行此脚本"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# 启动后端服务
|
||||
echo "启动后端服务..."
|
||||
cd mock-server
|
||||
python3 -m venv venv 2>/dev/null || echo "虚拟环境已存在"
|
||||
source venv/bin/activate
|
||||
pip install -r requirements.txt > /dev/null 2>&1
|
||||
python main.py &
|
||||
BACKEND_PID=$!
|
||||
|
||||
# 等待后端启动
|
||||
echo "等待后端服务启动..."
|
||||
sleep 3
|
||||
|
||||
# 启动前端服务
|
||||
echo "启动前端服务..."
|
||||
cd ../frontend
|
||||
npm run dev &
|
||||
FRONTEND_PID=$!
|
||||
|
||||
echo ""
|
||||
echo "========================================"
|
||||
echo "机械臂控制助手已启动!"
|
||||
echo ""
|
||||
echo "前端应用:http://localhost:5173"
|
||||
echo "后端服务:http://localhost:8000"
|
||||
echo ""
|
||||
echo "WebSocket连接地址:"
|
||||
echo "- 6轴工业机械臂:ws://localhost:8000/ws/six_axis"
|
||||
echo "- SCARA机器人:ws://localhost:8000/ws/scara"
|
||||
echo ""
|
||||
echo "按 Ctrl+C 停止所有服务"
|
||||
echo "========================================"
|
||||
|
||||
# 等待用户中断
|
||||
trap "kill $BACKEND_PID $FRONTEND_PID 2>/dev/null; echo '服务已停止'; exit" INT
|
||||
wait
|
||||
71
test_connection_fixes.sh
可执行文件
71
test_connection_fixes.sh
可执行文件
@ -0,0 +1,71 @@
|
||||
#!/bin/bash
|
||||
|
||||
echo "=== 连接状态管理修复测试 ==="
|
||||
echo ""
|
||||
|
||||
# 停止可能正在运行的服务
|
||||
echo "1. 停止现有服务..."
|
||||
pkill -f "python main.py" 2>/dev/null
|
||||
pkill -f "vite" 2>/dev/null
|
||||
sleep 2
|
||||
|
||||
# 启动后端服务
|
||||
echo "2. 启动后端服务..."
|
||||
cd mock-server
|
||||
python main.py &
|
||||
BACKEND_PID=$!
|
||||
sleep 3
|
||||
|
||||
echo "后端服务已启动 (PID: $BACKEND_PID)"
|
||||
echo "监听端口: 8000"
|
||||
echo ""
|
||||
|
||||
# 启动前端服务
|
||||
echo "3. 启动前端服务..."
|
||||
cd ../frontend
|
||||
npm run dev &
|
||||
FRONTEND_PID=$!
|
||||
sleep 5
|
||||
|
||||
echo "前端服务已启动 (PID: $FRONTEND_PID)"
|
||||
echo "监听端口: 5173"
|
||||
echo ""
|
||||
|
||||
echo "=== 测试步骤 ==="
|
||||
echo ""
|
||||
echo "1. 打开浏览器访问: http://localhost:5173"
|
||||
echo "2. 打开浏览器开发者工具控制台"
|
||||
echo ""
|
||||
echo "3. 测试自动重连问题修复:"
|
||||
echo " - 连接WebSocket: ws://localhost:8000/ws/six_axis"
|
||||
echo " - 等待连接成功"
|
||||
echo " - 点击'断开'按钮"
|
||||
echo " - 检查控制台: 应该看到'用户主动断开连接,不进行重连'"
|
||||
echo " - 验证: 连接不应该自动重新建立"
|
||||
echo ""
|
||||
echo "4. 测试连接会话切换问题修复:"
|
||||
echo " - 连接6轴机械臂: ws://localhost:8000/ws/six_axis"
|
||||
echo " - 点击'断开'按钮"
|
||||
echo " - 连接SCARA机器人: 切换选择框到'SCARA机器人',点击'连接'"
|
||||
echo " - 检查控制台: 应该看到连接ID变化,旧连接事件被忽略"
|
||||
echo " - 验证: 应该只有SCARA机器人的连接活跃,不会出现交替连接"
|
||||
echo ""
|
||||
echo "5. 测试快速切换连接:"
|
||||
echo " - 快速在两种机械臂类型间切换连接"
|
||||
echo " - 检查控制台: 应该看到连接ID正确管理,旧连接被清理"
|
||||
echo " - 验证: 连接状态应该稳定,不会出现多个连接竞争"
|
||||
echo ""
|
||||
echo "6. 测试意外断开重连:"
|
||||
echo " - 保持连接状态"
|
||||
echo " - 手动停止后端服务: kill $BACKEND_PID"
|
||||
echo " - 检查控制台: 应该看到重连尝试(指数退避)"
|
||||
echo " - 重新启动后端: cd mock-server && python main.py &"
|
||||
echo " - 验证: 应该自动重连成功"
|
||||
echo ""
|
||||
|
||||
echo "按 Ctrl+C 停止测试"
|
||||
echo ""
|
||||
|
||||
# 等待用户中断
|
||||
trap "echo ''; echo '停止服务...'; kill $BACKEND_PID $FRONTEND_PID 2>/dev/null; echo '测试完成'; exit" INT
|
||||
wait
|
||||
41
test_fix.sh
可执行文件
41
test_fix.sh
可执行文件
@ -0,0 +1,41 @@
|
||||
#!/bin/bash
|
||||
|
||||
echo "=== 机械臂控制助手修复测试 ==="
|
||||
echo ""
|
||||
|
||||
# 启动后端服务
|
||||
echo "1. 启动后端服务..."
|
||||
cd mock-server
|
||||
python main.py &
|
||||
BACKEND_PID=$!
|
||||
sleep 3
|
||||
|
||||
echo "后端服务已启动 (PID: $BACKEND_PID)"
|
||||
echo ""
|
||||
|
||||
# 启动前端服务
|
||||
echo "2. 启动前端服务..."
|
||||
cd ../frontend
|
||||
npm run dev &
|
||||
FRONTEND_PID=$!
|
||||
sleep 5
|
||||
|
||||
echo "前端服务已启动 (PID: $FRONTEND_PID)"
|
||||
echo ""
|
||||
|
||||
echo "=== 测试说明 ==="
|
||||
echo "1. 打开浏览器访问: http://localhost:5173"
|
||||
echo "2. 连接WebSocket: ws://localhost:8000/ws/six_axis"
|
||||
echo "3. 测试以下功能:"
|
||||
echo " - 连接/断开连接"
|
||||
echo " - 拖动关节滑块,观察3D模型变化"
|
||||
echo " - 检查控制台是否有WebSocket消息发送"
|
||||
echo " - 断开后重新连接,检查3D模型是否清理"
|
||||
echo ""
|
||||
|
||||
echo "按 Ctrl+C 停止测试"
|
||||
echo ""
|
||||
|
||||
# 等待用户中断
|
||||
trap "echo ''; echo '停止服务...'; kill $BACKEND_PID $FRONTEND_PID 2>/dev/null; echo '测试完成'; exit" INT
|
||||
wait
|
||||
65
test_fixes.sh
可执行文件
65
test_fixes.sh
可执行文件
@ -0,0 +1,65 @@
|
||||
#!/bin/bash
|
||||
|
||||
echo "=== 机械臂控制助手修复测试 ==="
|
||||
echo ""
|
||||
|
||||
# 停止可能正在运行的服务
|
||||
echo "1. 停止现有服务..."
|
||||
pkill -f "python main.py" 2>/dev/null
|
||||
pkill -f "vite" 2>/dev/null
|
||||
sleep 2
|
||||
|
||||
# 启动后端服务
|
||||
echo "2. 启动后端服务..."
|
||||
cd mock-server
|
||||
python main.py &
|
||||
BACKEND_PID=$!
|
||||
sleep 3
|
||||
|
||||
echo "后端服务已启动 (PID: $BACKEND_PID)"
|
||||
echo "监听端口: 8000"
|
||||
echo ""
|
||||
|
||||
# 启动前端服务
|
||||
echo "3. 启动前端服务..."
|
||||
cd ../frontend
|
||||
npm run dev &
|
||||
FRONTEND_PID=$!
|
||||
sleep 5
|
||||
|
||||
echo "前端服务已启动 (PID: $FRONTEND_PID)"
|
||||
echo "监听端口: 5173"
|
||||
echo ""
|
||||
|
||||
echo "=== 测试步骤 ==="
|
||||
echo ""
|
||||
echo "1. 打开浏览器访问: http://localhost:5173"
|
||||
echo "2. 连接WebSocket: ws://localhost:8000/ws/six_axis"
|
||||
echo "3. 测试以下功能:"
|
||||
echo ""
|
||||
echo " A. 两个模型问题测试:"
|
||||
echo " - 连接后应该只显示一个3D机械臂模型"
|
||||
echo " - 断开连接后重新连接,应该只显示一个新模型"
|
||||
echo ""
|
||||
echo " B. 角度重置问题测试:"
|
||||
echo " - 拖动一个关节的滑块,观察角度变化"
|
||||
echo " - 然后拖动另一个关节的滑块"
|
||||
echo " - 检查第一个关节的角度是否保持稳定,不会重置"
|
||||
echo ""
|
||||
echo " C. 连接稳定性测试:"
|
||||
echo " - 连续操作多个关节"
|
||||
echo " - 观察控制台是否有频繁断开连接的消息"
|
||||
echo " - 检查心跳机制是否正常工作"
|
||||
echo ""
|
||||
echo "4. 打开浏览器开发者工具,查看控制台输出:"
|
||||
echo " - 应该看到连接成功的消息"
|
||||
echo " - 应该看到关节角度发送和确认的消息"
|
||||
echo " - 应该看到心跳消息(每30秒)"
|
||||
echo ""
|
||||
|
||||
echo "按 Ctrl+C 停止测试"
|
||||
echo ""
|
||||
|
||||
# 等待用户中断
|
||||
trap "echo ''; echo '停止服务...'; kill $BACKEND_PID $FRONTEND_PID 2>/dev/null; echo '测试完成'; exit" INT
|
||||
wait
|
||||
121
verify_connection_fixes.py
普通文件
121
verify_connection_fixes.py
普通文件
@ -0,0 +1,121 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
验证连接状态管理的关键修复
|
||||
"""
|
||||
|
||||
import os
|
||||
import re
|
||||
|
||||
|
||||
def check_file(filepath, patterns):
|
||||
"""检查文件中是否包含特定模式"""
|
||||
if not os.path.exists(filepath):
|
||||
print(f"❌ 文件不存在: {filepath}")
|
||||
return False
|
||||
|
||||
with open(filepath, "r", encoding="utf-8") as f:
|
||||
content = f.read()
|
||||
|
||||
all_found = True
|
||||
for pattern_name, pattern in patterns.items():
|
||||
if re.search(pattern, content, re.MULTILINE | re.DOTALL):
|
||||
print(f" ✓ {pattern_name}")
|
||||
else:
|
||||
print(f" ✗ {pattern_name}")
|
||||
all_found = False
|
||||
|
||||
return all_found
|
||||
|
||||
|
||||
def main():
|
||||
print("=== 验证连接状态管理修复 ===")
|
||||
print()
|
||||
|
||||
# 检查关键修复
|
||||
checks = {
|
||||
"1. 用户主动断开标识": {
|
||||
"file": "frontend/src/composables/useWebSocket.ts",
|
||||
"patterns": {
|
||||
"isManualDisconnect标志": r"let isManualDisconnect = false",
|
||||
"disconnect中设置标志": r"isManualDisconnect = true",
|
||||
"onclose中检查标志": r"if \(isManualDisconnect\)",
|
||||
"重置标志": r"isManualDisconnect = false",
|
||||
},
|
||||
},
|
||||
"2. 连接ID管理": {
|
||||
"file": "frontend/src/composables/useWebSocket.ts",
|
||||
"patterns": {
|
||||
"currentConnectionId": r"let currentConnectionId: string \| null = null",
|
||||
"生成连接ID": r"const connectionId = Date\.now\(\)\.toString\(\)",
|
||||
"连接ID检查": r"if \(currentConnectionId !== connectionId\)",
|
||||
"清理旧连接": r"cleanupPreviousConnection",
|
||||
},
|
||||
},
|
||||
"3. 统一状态管理": {
|
||||
"file": "frontend/src/composables/useWebSocket.ts",
|
||||
"patterns": {
|
||||
"updateConnectionStatus函数": r"const updateConnectionStatus = \(status:",
|
||||
"状态同步": r"isConnected\.value = status === 'connected'",
|
||||
"robotStore状态更新": r"robotStore\.setConnectionStatus\(status\)",
|
||||
},
|
||||
},
|
||||
"4. 连接清理逻辑": {
|
||||
"file": "frontend/src/composables/useWebSocket.ts",
|
||||
"patterns": {
|
||||
"resetConnection函数": r"const resetConnection = \(\) =>",
|
||||
"重置所有状态": r"currentConnectionId = null",
|
||||
"停止定时器": r"stopHeartbeat\(\)",
|
||||
"清除重连定时器": r"if \(reconnectTimeout\)",
|
||||
},
|
||||
},
|
||||
"5. ConnectionBar优化": {
|
||||
"file": "frontend/src/components/ConnectionBar.vue",
|
||||
"patterns": {
|
||||
"使用resetConnection": r"resetConnection\(\)",
|
||||
"完全断开逻辑": r"console\.log\('连接已完全断开并重置'\)",
|
||||
"连接中指示器": r"connecting-indicator",
|
||||
},
|
||||
},
|
||||
"6. Store状态管理": {
|
||||
"file": "frontend/src/stores/robot.ts",
|
||||
"patterns": {
|
||||
"forceConnectionStatus": r"forceConnectionStatus\(status:",
|
||||
"状态清理": r"clearRobot\(\)",
|
||||
"连接状态重置": r"this\.connectionStatus = 'disconnected'",
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
all_passed = True
|
||||
for check_name, check_info in checks.items():
|
||||
print(f"{check_name}:")
|
||||
filepath = check_info["file"]
|
||||
patterns = check_info["patterns"]
|
||||
|
||||
if check_file(filepath, patterns):
|
||||
print(f" ✅ 通过")
|
||||
else:
|
||||
print(f" ❌ 失败")
|
||||
all_passed = False
|
||||
print()
|
||||
|
||||
if all_passed:
|
||||
print("✅ 所有关键修复都已实施")
|
||||
print()
|
||||
print("测试建议:")
|
||||
print("1. 运行 ./test_connection_fixes.sh 启动服务")
|
||||
print("2. 访问 http://localhost:5173")
|
||||
print("3. 按照测试步骤验证修复效果")
|
||||
print()
|
||||
print("预期行为:")
|
||||
print("- 用户断开连接后不会自动重连")
|
||||
print("- 切换机械臂时不会出现连接交替")
|
||||
print("- 连接状态同步一致")
|
||||
print("- 快速操作时连接稳定")
|
||||
else:
|
||||
print("❌ 部分修复未完全实施")
|
||||
print("请检查上述失败的项目")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
106
verify_fixes.py
普通文件
106
verify_fixes.py
普通文件
@ -0,0 +1,106 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
验证机械臂控制助手的关键修复
|
||||
"""
|
||||
|
||||
import os
|
||||
import re
|
||||
|
||||
|
||||
def check_file(filepath, patterns):
|
||||
"""检查文件中是否包含特定模式"""
|
||||
if not os.path.exists(filepath):
|
||||
print(f"❌ 文件不存在: {filepath}")
|
||||
return False
|
||||
|
||||
with open(filepath, "r", encoding="utf-8") as f:
|
||||
content = f.read()
|
||||
|
||||
all_found = True
|
||||
for pattern_name, pattern in patterns.items():
|
||||
if re.search(pattern, content, re.MULTILINE | re.DOTALL):
|
||||
print(f" ✓ {pattern_name}")
|
||||
else:
|
||||
print(f" ✗ {pattern_name}")
|
||||
all_found = False
|
||||
|
||||
return all_found
|
||||
|
||||
|
||||
def main():
|
||||
print("=== 验证机械臂控制助手修复 ===")
|
||||
print()
|
||||
|
||||
# 检查关键修复
|
||||
checks = {
|
||||
"1. ThreeViewer场景清理修复": {
|
||||
"file": "frontend/src/components/ThreeViewer.vue",
|
||||
"patterns": {
|
||||
"递归清理函数": r"const cleanupObject = \(obj: THREE\.Object3D\) => {",
|
||||
"几何体清理": r"obj\.geometry\.dispose\(\)",
|
||||
"材质清理": r"obj\.material\.dispose\(\)",
|
||||
"构建状态锁": r"let isBuilding = false",
|
||||
},
|
||||
},
|
||||
"2. Store状态锁修复": {
|
||||
"file": "frontend/src/stores/robot.ts",
|
||||
"patterns": {
|
||||
"状态锁集合": r"const sendingCommands = new Set<string>\(\)",
|
||||
"发送命令检查": r"sendingCommands\.has\(jointId\)",
|
||||
"添加状态锁": r"sendingCommands\.add\(jointId\)",
|
||||
"移除状态锁": r"sendingCommands\.delete\([^)]+\)",
|
||||
},
|
||||
},
|
||||
"3. WebSocket心跳机制": {
|
||||
"file": "frontend/src/composables/useWebSocket.ts",
|
||||
"patterns": {
|
||||
"心跳间隔": r"const HEARTBEAT_INTERVAL = 30000",
|
||||
"启动心跳": r"const startHeartbeat = \(\) => {",
|
||||
"停止心跳": r"const stopHeartbeat = \(\) => {",
|
||||
"处理pong": r"const handlePong = \(timestamp: number\) => {",
|
||||
},
|
||||
},
|
||||
"4. 后端ping/pong支持": {
|
||||
"file": "mock-server/main.py",
|
||||
"patterns": {
|
||||
"ping消息处理": r'"type" in data and data\["type"\] == "ping"',
|
||||
"pong响应": r'"type": "pong"',
|
||||
},
|
||||
},
|
||||
"5. 防抖优化": {
|
||||
"file": "frontend/src/utils/debounce.ts",
|
||||
"patterns": {
|
||||
"带立即执行的防抖": r"debounceWithImmediate",
|
||||
"尾随防抖": r"debounceTrailing",
|
||||
"保存最后参数": r"let lastArgs: Parameters<T> \| null = null",
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
all_passed = True
|
||||
for check_name, check_info in checks.items():
|
||||
print(f"{check_name}:")
|
||||
filepath = check_info["file"]
|
||||
patterns = check_info["patterns"]
|
||||
|
||||
if check_file(filepath, patterns):
|
||||
print(f" ✅ 通过")
|
||||
else:
|
||||
print(f" ❌ 失败")
|
||||
all_passed = False
|
||||
print()
|
||||
|
||||
if all_passed:
|
||||
print("✅ 所有关键修复都已实施")
|
||||
print()
|
||||
print("测试建议:")
|
||||
print("1. 运行 ./test_fixes.sh 启动服务")
|
||||
print("2. 访问 http://localhost:5173")
|
||||
print("3. 测试两个模型、角度重置和连接稳定性问题")
|
||||
else:
|
||||
print("❌ 部分修复未完全实施")
|
||||
print("请检查上述失败的项目")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
28
ws.d.ts
vendored
普通文件
28
ws.d.ts
vendored
普通文件
@ -0,0 +1,28 @@
|
||||
/**
|
||||
* 关节配置
|
||||
* 在实现上,继承或实现了这个Joint的接口或类应该能维持并记录当前的角度,但是这个不在配置文件中体现
|
||||
*/
|
||||
declare interface Joint{
|
||||
id: string, // 关节id
|
||||
range: number[], // 长度为2的数组,角度最小值与最大值
|
||||
default: number // 复位时的关节默认角度
|
||||
type: "joint"|"flex_w"|"flex_v"|"gripper" // 一般关节、水平轴旋转底座、垂直轴旋转底座、夹爪
|
||||
next?: string // 在设计上连接的下一个关节
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 机械臂端下发的配置文件包
|
||||
*/
|
||||
declare interface InitResponse{
|
||||
id: string, // 机械臂id
|
||||
joints: Joint[]
|
||||
}
|
||||
|
||||
/**
|
||||
* 浏览器端上传的关节角度调整请求
|
||||
*/
|
||||
declare interface MoveRequest{
|
||||
id: string, // 关节id
|
||||
angel: number // 角度
|
||||
}
|
||||
在新工单中引用
屏蔽一个用户