feat: 加入动作录制和回放机制

这个提交包含在:
2026-03-12 16:53:31 +08:00
父节点 00fbd43b92
当前提交 34f5276a1f
共有 15 个文件被更改,包括 2753 次插入 和 10 次删除

481
AGENTS.md 普通文件
查看文件

@ -0,0 +1,481 @@
# WSRobotClient - 智能编码代理指南
本文档为在WSRobotClient项目中工作的智能编码代理提供指导,包括构建命令、代码检查、测试命令和代码风格规范。
## 项目概述
WSRobotClient是一个基于Web的实时机械臂控制与可视化工具,包含:
- **前端**: Vue 3 + TypeScript + Three.js + Pinia + Vite
- **后端**: FastAPI + Python WebSocket模拟服务
## 构建/代码检查/测试命令
### 前端 (Vue 3 + TypeScript)
#### 开发环境
```bash
cd frontend
npm install # 安装依赖
npm run dev # 启动开发服务器 (http://localhost:5173)
```
#### 构建和类型检查
```bash
cd frontend
npm run build # 生产构建(同时运行类型检查)
npm run build-only # 仅构建(不运行类型检查)
npm run type-check # 仅运行TypeScript类型检查
npm run preview # 预览生产构建结果
```
#### 代码质量检查
```bash
# TypeScript类型检查(推荐在提交前运行)
cd frontend && npm run type-check
# 检查Vue组件语法
cd frontend && npx vue-tsc --noEmit
```
### 后端 (FastAPI + Python)
#### 开发环境
```bash
cd mock-server
pip install -r requirements.txt # 安装Python依赖
python main.py # 启动开发服务器 (http://localhost:8000)
```
#### 代码质量检查
```bash
# Python代码格式化(使用ruff)
cd mock-server
ruff format . # 格式化代码
ruff check . # 检查代码质量
ruff check --fix . # 自动修复可修复的问题
```
### 完整项目启动
```bash
# 使用项目根目录的启动脚本
./start.sh
```
## 代码风格指南
### 总体原则
1. **一致性优先**: 遵循现有代码的约定和模式
2. **类型安全**: 充分利用TypeScript的类型系统
3. **可维护性**: 编写清晰、自解释的代码
4. **错误处理**: 优雅地处理边界情况和错误
### 前端代码规范 (Vue 3 + TypeScript)
#### 文件结构
```
frontend/src/
├── components/ # Vue组件(PascalCase命名)
├── composables/ # 组合式函数(use前缀,camelCase)
├── stores/ # Pinia状态管理(camelCase)
├── types/ # TypeScript类型定义(PascalCase)
├── router/ # 路由配置
└── views/ # 页面组件(PascalCase)
```
#### Vue组件规范
```vue
<!-- 组件命名: PascalCase -->
<!-- 模板: 使用kebab-case属性 -->
<template>
<div class="component-name">
<ChildComponent
:prop-name="value"
@event-name="handler"
/>
</div>
</template>
<!-- 脚本: 使用组合式API,严格类型 -->
<script setup lang="ts">
// 导入顺序: 1. Vue/框架API 2. 第三方库 3. 本地模块
import { ref, computed, onMounted } from 'vue'
import { useStore } from '@/stores/store'
import type { User } from '@/types/user'
// Props定义(使用defineProps)
const props = defineProps<{
userId: number
userName?: string
}>()
// Emits定义(使用defineEmits)
const emit = defineEmits<{
(e: 'update:name', value: string): void
(e: 'delete'): void
}>()
// 响应式状态(使用ref/reactive)
const count = ref(0)
const user = reactive({ name: '', age: 0 })
// 计算属性(使用computed)
const fullName = computed(() => `${user.name} (${user.age})`)
// 方法(camelCase命名)
const handleClick = () => {
// 业务逻辑
}
// 生命周期
onMounted(() => {
// 初始化逻辑
})
</script>
<!-- 样式: 使用scoped CSS -->
<style scoped>
.component-name {
/* 组件样式 */
}
</style>
```
#### TypeScript类型规范
```typescript
// 类型定义使用PascalCase
interface RobotJoint {
id: string
name: string
type: 'flex_w' | 'flex_v' | 'joint' | 'gripper'
min: number
max: number
default: number
current: number
}
// 使用类型别名
type JointType = 'flex_w' | 'flex_v' | 'joint' | 'gripper'
// 枚举使用PascalCase
enum ConnectionStatus {
Disconnected = 'disconnected',
Connecting = 'connecting',
Connected = 'connected'
}
// 函数类型定义
type MoveCommand = (jointId: string, angle: number) => void
// 泛型使用
function createStore<T>(initialState: T): Store<T> {
// 实现
}
```
#### 命名约定
- **组件**: `PascalCase` (如 `ControlPanel.vue`, `ThreeViewer.vue`)
- **组合式函数**: `useCamelCase` (如 `useWebSocket.ts`)
- **工具函数**: `camelCase` (如 `formatAngle.ts`)
- **常量**: `UPPER_SNAKE_CASE` (如 `MAX_RECONNECT_ATTEMPTS`)
- **接口/类型**: `PascalCase` (如 `RobotConfig`, `JointState`)
- **变量**: `camelCase` (如 `jointAngle`, `connectionStatus`)
- **CSS类**: `kebab-case` (如 `.control-panel`, `.joint-slider`)
#### 导入规范
```typescript
// 1. Vue/框架导入
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
// 2. 第三方库导入
import axios from 'axios'
import * as THREE from 'three'
// 3. 类型导入(使用import type)
import type { RobotJoint } from '@/types/robot'
// 4. 本地模块导入(使用@别名)
import { useRobotStore } from '@/stores/robot'
import ControlPanel from '@/components/ControlPanel.vue'
// 5. 样式导入(如果需要)
import './styles.css'
```
#### 错误处理
```typescript
// WebSocket错误处理示例(参考useWebSocket.ts)
try {
const data = JSON.parse(event.data)
// 处理数据
} catch (error) {
console.error('消息解析失败:', error, '原始数据:', event.data)
error.value = '消息解析失败'
// 提供用户友好的错误信息
}
// 异步操作错误处理
const fetchData = async () => {
try {
const response = await axios.get('/api/data')
return response.data
} catch (error) {
console.error('获取数据失败:', error)
// 返回默认值或抛出特定错误
throw new Error('数据获取失败')
}
}
```
### 后端代码规范 (Python + FastAPI)
#### 文件结构
```
mock-server/
├── main.py # FastAPI主应用
├── robot_config.py # 机械臂配置
├── requirements.txt # Python依赖
└── venv/ # 虚拟环境(不提交)
```
#### Python代码规范
```python
# 导入顺序: 1. 标准库 2. 第三方库 3. 本地模块
import json
from typing import Dict, List, Optional
from fastapi import FastAPI, WebSocket, WebSocketDisconnect
from robot_config import SIX_AXIS_ROBOT, SCARA_ROBOT
# 常量使用UPPER_SNAKE_CASE
MAX_CONNECTIONS = 100
HEARTBEAT_INTERVAL = 30
# 函数使用snake_case
async def handle_websocket_message(websocket: WebSocket, data: Dict):
"""处理WebSocket消息
Args:
websocket: WebSocket连接对象
data: 解析后的消息数据
Returns:
bool: 处理是否成功
"""
try:
# 业务逻辑
return True
except Exception as e:
print(f"处理消息失败: {e}")
return False
# 类使用PascalCase
class RobotManager:
"""机械臂管理器"""
def __init__(self):
self.connections: Dict[str, WebSocket] = {}
async def add_connection(self, robot_id: str, websocket: WebSocket):
"""添加机械臂连接"""
self.connections[robot_id] = websocket
```
#### 类型提示
```python
from typing import Dict, List, Optional, Union
# 使用类型提示
def calculate_angle(
current: float,
target: float,
speed: float = 1.0
) -> float:
"""计算目标角度
Args:
current: 当前角度
target: 目标角度
speed: 移动速度系数
Returns:
计算后的角度
"""
return current + (target - current) * speed
# 复杂类型使用TypeDict或dataclass
from typing import TypedDict
class JointConfig(TypedDict):
id: str
name: str
min: float
max: float
default: float
```
### 通用开发规范
#### 提交消息规范
```
类型(范围): 简短描述
详细描述(可选)
- 功能变更说明
- 修复的问题
- 破坏性变更说明
关联问题: #123
```
类型包括:
- `feat`: 新功能
- `fix`: 修复bug
- `docs`: 文档更新
- `style`: 代码格式调整
- `refactor`: 代码重构
- `test`: 测试相关
- `chore`: 构建过程或辅助工具变更
#### 代码审查要点
1. **功能正确性**: 代码是否按预期工作
2. **类型安全**: TypeScript/Python类型是否正确使用
3. **错误处理**: 是否妥善处理边界情况和错误
4. **性能考虑**: 是否有潜在的性能问题
5. **可读性**: 代码是否清晰易懂
6. **测试覆盖**: 是否有相应的测试
7. **文档更新**: 相关文档是否同步更新
#### 调试技巧
```bash
# 前端调试
cd frontend && npm run dev
# 打开浏览器开发者工具查看控制台日志
# 后端调试
cd mock-server && python -m pdb main.py
# 或使用print调试
# WebSocket调试
# 使用浏览器WebSocket工具或wscat
```
## 扩展开发指南
### 添加新的机械臂类型
1. 在 `mock-server/robot_config.py` 中添加配置
2. 更新 `mock-server/main.py` 中的机器人类型映射
3. 在前端 `ConnectionBar.vue` 中添加选项
4. 更新前端类型定义
### 添加新功能组件
1. 在 `frontend/src/components/` 创建Vue组件
2. 遵循现有组件的结构和命名约定
3. 添加TypeScript类型定义
4. 更新路由(如果需要)
5. 添加样式
### 动作录制功能开发指南
动作录制功能已实现,包含以下组件和模块:
#### 文件结构
```
frontend/src/
├── components/
│ ├── RecordingPanel.vue # 录制控制面板
│ └── PlaybackControls.vue # 回放控制组件
├── composables/
│ └── useRecording.ts # 录制和回放逻辑
├── stores/
│ ├── recording.ts # 录制状态管理
│ └── ui.ts # 界面状态管理(新增)
├── types/
│ └── recording.ts # 录制相关类型定义
└── utils/
└── recordingUtils.ts # 录制工具函数
```
#### 核心功能
1. **录制**: 50ms采样间隔记录关节角度
2. **回放**: 支持播放、暂停、停止、循环播放
3. **管理**: 录制列表、重命名、删除、导入导出
4. **持久化**: localStorage存储录制数据
5. **可折叠界面**: 录制和回放面板可展开/收起
#### 使用示例
```typescript
// 开始录制
recording.startRecording()
// 暂停录制
recording.pauseRecording()
// 停止录制
recording.stopRecording()
// 开始回放
recording.startPlayback(recordingId)
// 导出录制
recording.exportRecording(recordingId)
// 导入录制
await recording.importRecording(file)
```
#### 数据格式
```json
{
"id": "rec_1741766400000_abc123",
"name": "录制名称",
"robotId": "six_axis_robot",
"createdAt": 1741766400000,
"duration": 5000,
"frames": [
{
"timestamp": 0,
"joints": {
"base": 0,
"shoulder": 0,
"elbow": 0
}
}
],
"metadata": {
"description": "录制描述",
"tags": ["tag1", "tag2"],
"version": "1.0.0"
}
}
```
### 状态管理最佳实践
1. 使用Pinia进行状态管理
2. 将业务逻辑放在stores中
3. 组件只负责UI渲染和用户交互
4. 使用组合式函数复用逻辑
## 故障排除
### 常见问题
1. **TypeScript编译错误**: 运行 `npm run type-check` 查看详细错误
2. **Vue组件导入错误**: 检查路径别名和文件扩展名
3. **WebSocket连接失败**: 检查后端服务是否运行,CORS配置
4. **Python依赖问题**: 使用虚拟环境,确保requirements.txt正确
### 性能优化建议
1. 使用Vue的响应式系统高效更新UI
2. Three.js渲染优化:减少draw calls,使用instanced mesh
3. WebSocket消息优化:避免频繁发送小消息
4. 组件懒加载:使用Vue Router的懒加载
## 相关资源
- [Vue 3文档](https://vuejs.org/)
- [TypeScript文档](https://www.typescriptlang.org/)
- [Three.js文档](https://threejs.org/docs/)
- [FastAPI文档](https://fastapi.tiangolo.com/)
- [Pinia文档](https://pinia.vuejs.org/)
- [Vite文档](https://vitejs.dev/)

查看文件

@ -3,20 +3,16 @@ import { onMounted } from 'vue'
import ConnectionBar from './components/ConnectionBar.vue' import ConnectionBar from './components/ConnectionBar.vue'
import ControlPanel from './components/ControlPanel.vue' import ControlPanel from './components/ControlPanel.vue'
import ThreeViewer from './components/ThreeViewer.vue' import ThreeViewer from './components/ThreeViewer.vue'
import RecordingPanel from './components/RecordingPanel.vue'
import PlaybackControls from './components/PlaybackControls.vue'
import { useWebSocket } from './composables/useWebSocket' import { useWebSocket } from './composables/useWebSocket'
import { useRobotStore } from './stores/robot' import { useRobotStore } from '@/stores/robot'
import { useUIStore } from '@/stores/ui'
// 初始化WebSocket和store的集成 // 初始化WebSocket和store的集成
const { sendMoveCommand, isConnected } = useWebSocket() const { sendMoveCommand, isConnected } = useWebSocket()
const robotStore = useRobotStore() const robotStore = useRobotStore()
const uiStore = useUIStore()
// 将WebSocket功能注入到store中
onMounted(() => {
robotStore.setWebSocketFunctions({
sendMoveCommand,
isConnected
})
})
</script> </script>
<template> <template>
@ -26,6 +22,52 @@ onMounted(() => {
<div class="main-content"> <div class="main-content">
<ControlPanel class="control-panel" /> <ControlPanel class="control-panel" />
<ThreeViewer class="three-viewer" /> <ThreeViewer class="three-viewer" />
<!-- 录制面板区域 -->
<div class="panel-container recording-panel-container">
<!-- 录制面板展开/收起按钮 -->
<button
class="panel-toggle-btn recording-toggle"
:class="{ expanded: uiStore.isRecordingPanelVisible }"
@click="uiStore.toggleRecordingPanel"
:title="uiStore.isRecordingPanelVisible ? '收起录制面板' : '展开录制面板'"
>
<span class="toggle-icon">🎬</span>
<span class="toggle-text">录制</span>
<span class="toggle-arrow">{{ uiStore.isRecordingPanelVisible ? '◀' : '▶' }}</span>
</button>
<!-- 录制面板内容 -->
<div
class="panel-content recording-panel-content"
:class="{ expanded: uiStore.isRecordingPanelVisible }"
>
<RecordingPanel />
</div>
</div>
</div>
<!-- 回放控制面板区域 -->
<div class="panel-container playback-panel-container">
<!-- 回放面板展开/收起按钮 -->
<button
class="panel-toggle-btn playback-toggle"
:class="{ expanded: uiStore.isPlaybackPanelVisible }"
@click="uiStore.togglePlaybackPanel"
:title="uiStore.isPlaybackPanelVisible ? '收起回放面板' : '展开回放面板'"
>
<span class="toggle-icon">🎵</span>
<span class="toggle-text">回放</span>
<span class="toggle-arrow">{{ uiStore.isPlaybackPanelVisible ? '▼' : '▲' }}</span>
</button>
<!-- 回放面板内容 -->
<div
class="panel-content playback-panel-content"
:class="{ expanded: uiStore.isPlaybackPanelVisible }"
>
<PlaybackControls />
</div>
</div> </div>
</div> </div>
</template> </template>
@ -46,6 +88,7 @@ onMounted(() => {
flex: 1; flex: 1;
display: flex; display: flex;
overflow: hidden; overflow: hidden;
position: relative;
} }
.control-panel { .control-panel {
@ -55,5 +98,111 @@ onMounted(() => {
.three-viewer { .three-viewer {
flex: 1; flex: 1;
transition: margin-right 0.3s ease;
}
/* 录制面板容器 */
.recording-panel-container {
position: absolute;
right: 0;
top: 0;
bottom: 0;
display: flex;
z-index: 10;
}
/* 回放面板容器 */
.playback-panel-container {
position: relative;
display: flex;
flex-direction: column;
z-index: 10;
}
/* 面板切换按钮 */
.panel-toggle-btn {
display: flex;
align-items: center;
justify-content: center;
gap: 6px;
padding: 8px 12px;
border: none;
background: #3498db;
color: white;
cursor: pointer;
transition: all 0.2s;
font-size: 13px;
font-weight: 500;
z-index: 20;
}
.panel-toggle-btn:hover {
background: #2980b9;
}
.panel-toggle-btn.expanded {
background: #2980b9;
}
/* 录制面板切换按钮 */
.recording-toggle {
border-radius: 6px 0 0 6px;
margin-top: 80px;
height: 36px;
box-shadow: -2px 0 4px rgba(0, 0, 0, 0.1);
}
/* 回放面板切换按钮 */
.playback-toggle {
border-radius: 6px 6px 0 0;
width: 80px;
align-self: center;
box-shadow: 0 -2px 4px rgba(0, 0, 0, 0.1);
}
/* 面板内容 */
.panel-content {
overflow: hidden;
transition: all 0.3s ease;
background: white;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
/* 录制面板内容 */
.recording-panel-content {
width: 0;
opacity: 0;
border-left: 1px solid #e0e0e0;
}
.recording-panel-content.expanded {
width: 320px;
opacity: 1;
}
/* 回放面板内容 */
.playback-panel-content {
height: 0;
opacity: 0;
border-top: 1px solid #e0e0e0;
}
.playback-panel-content.expanded {
height: fit-content;
opacity: 1;
}
/* 切换按钮图标和文字 */
.toggle-icon {
font-size: 14px;
}
.toggle-text {
font-size: 12px;
}
.toggle-arrow {
font-size: 10px;
margin-left: 4px;
} }
</style> </style>

查看文件

@ -0,0 +1,590 @@
<template>
<div class="playback-controls">
<div class="playback-header">
<h4>回放控制</h4>
<div class="playback-status" :class="playbackStatusClass">
<span class="status-icon">
<span v-if="recordingStore.isPlaying" class="playing-icon">▶️</span>
<span v-else-if="recordingStore.playbackState.status === 'paused'" class="paused-icon">⏸️</span>
<span v-else class="idle-icon">●</span>
</span>
<span class="status-text">{{ playbackStatusText }}</span>
</div>
</div>
<div class="selected-recording" v-if="recordingStore.selectedRecording">
<div class="recording-info">
<div class="recording-name">{{ recordingStore.selectedRecording.name }}</div>
<div class="recording-duration">
{{ formatDuration(recordingStore.selectedRecording.duration) }}
</div>
</div>
</div>
<div class="no-selection" v-else>
<p>请选择一个录制进行回放</p>
</div>
<div class="playback-progress">
<div class="progress-bar" @click="handleProgressClick" ref="progressBar">
<div class="progress-track"></div>
<div
class="progress-fill"
:style="{ width: progressPercentage + '%' }"
></div>
<div
class="progress-thumb"
:style="{ left: progressPercentage + '%' }"
></div>
</div>
<div class="time-display">
<span class="current-time">{{ formatDuration(recordingStore.playbackState.currentTime) }}</span>
<span class="total-time" v-if="recordingStore.selectedRecording">
/ {{ formatDuration(recordingStore.selectedRecording.duration) }}
</span>
</div>
</div>
<div class="control-buttons">
<button
@click="startPlayback"
class="control-btn play-btn"
:disabled="!recordingStore.selectedRecording || recordingStore.isPlaying"
title="开始回放"
>
<span class="btn-icon">▶️</span>
<span class="btn-text">播放</span>
</button>
<button
@click="pausePlayback"
class="control-btn pause-btn"
:disabled="!recordingStore.isPlaying"
title="暂停回放"
>
<span class="btn-icon">⏸️</span>
<span class="btn-text">暂停</span>
</button>
<button
@click="stopPlayback"
class="control-btn stop-btn"
:disabled="recordingStore.playbackState.status === 'idle'"
title="停止回放"
>
<span class="btn-icon">■</span>
<span class="btn-text">停止</span>
</button>
<button
@click="toggleLoop"
class="control-btn loop-btn"
:class="{ active: recordingStore.playbackState.loop }"
title="循环播放"
>
<span class="btn-icon">🔁</span>
<span class="btn-text">循环</span>
</button>
</div>
<div class="speed-control">
<label class="speed-label">播放速度:</label>
<div class="speed-buttons">
<button
v-for="speed in speedOptions"
:key="speed"
@click="setPlaybackSpeed(speed)"
class="speed-btn"
:class="{ active: recordingStore.playbackState.playbackSpeed === speed }"
>
{{ speed }}x
</button>
</div>
</div>
<div class="playback-actions">
<button
@click="jumpToStart"
class="action-btn jump-btn"
:disabled="!recordingStore.selectedRecording"
title="跳转到开始"
>
<span class="action-icon">⏮️</span>
<span class="action-text">开始</span>
</button>
<button
@click="jumpToEnd"
class="action-btn jump-btn"
:disabled="!recordingStore.selectedRecording"
title="跳转到结束"
>
<span class="action-icon">⏭️</span>
<span class="action-text">结束</span>
</button>
<button
@click="stepBackward"
class="action-btn step-btn"
:disabled="!recordingStore.selectedRecording || recordingStore.isPlaying"
title="后退一帧"
>
<span class="action-icon">◀️</span>
<span class="action-text">后退</span>
</button>
<button
@click="stepForward"
class="action-btn step-btn"
:disabled="!recordingStore.selectedRecording || recordingStore.isPlaying"
title="前进一帧"
>
<span class="action-icon">▶️</span>
<span class="action-text">前进</span>
</button>
</div>
</div>
</template>
<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useRecordingStore } from '@/stores/recording'
import { useRecording } from '@/composables/useRecording'
import { formatDuration } from '@/utils/recordingUtils'
const recordingStore = useRecordingStore()
const recording = useRecording()
const progressBar = ref<HTMLDivElement | null>(null)
const speedOptions = [0.25, 0.5, 0.75, 1.0, 1.5, 2.0, 3.0, 5.0]
const playbackStatusClass = computed(() => {
if (recordingStore.isPlaying) return 'status-playing'
if (recordingStore.playbackState.status === 'paused') return 'status-paused'
return 'status-idle'
})
const playbackStatusText = computed(() => {
if (recordingStore.isPlaying) return '回放中'
if (recordingStore.playbackState.status === 'paused') return '已暂停'
return '准备回放'
})
const progressPercentage = computed(() => {
if (!recordingStore.selectedRecording || recordingStore.selectedRecording.duration === 0) {
return 0
}
const percentage = (recordingStore.playbackState.currentTime / recordingStore.selectedRecording.duration) * 100
return Math.min(100, Math.max(0, percentage))
})
const startPlayback = () => {
if (!recordingStore.selectedRecording) return
recording.startPlayback(recordingStore.selectedRecording.id)
}
const pausePlayback = () => {
recording.pausePlayback()
}
const stopPlayback = () => {
recording.stopPlayback()
}
const toggleLoop = () => {
recordingStore.toggleLoop()
}
const setPlaybackSpeed = (speed: number) => {
recordingStore.setPlaybackSpeed(speed)
}
const jumpToStart = () => {
recordingStore.setPlaybackTime(0)
}
const jumpToEnd = () => {
if (recordingStore.selectedRecording) {
recordingStore.setPlaybackTime(recordingStore.selectedRecording.duration)
}
}
const stepBackward = () => {
if (!recordingStore.selectedRecording) return
const frame = recordingStore.getCurrentPlaybackFrame()
if (!frame) return
const frames = recordingStore.selectedRecording.frames
if (frames.length === 0) return
let targetIndex = 0
for (let i = frames.length - 1; i >= 0; i--) {
const frame = frames[i]
if (frame && frame.timestamp < recordingStore.playbackState.currentTime) {
targetIndex = i
break
}
}
const targetFrame = frames[targetIndex]
if (targetFrame) {
recordingStore.setPlaybackTime(targetFrame.timestamp)
}
}
const stepForward = () => {
if (!recordingStore.selectedRecording) return
const frames = recordingStore.selectedRecording.frames
if (frames.length === 0) return
let targetIndex = frames.length - 1
for (let i = 0; i < frames.length; i++) {
const frame = frames[i]
if (frame && frame.timestamp > recordingStore.playbackState.currentTime) {
targetIndex = i
break
}
}
const targetFrame = frames[targetIndex]
if (targetFrame) {
recordingStore.setPlaybackTime(targetFrame.timestamp)
}
}
const handleProgressClick = (event: MouseEvent) => {
if (!progressBar.value || !recordingStore.selectedRecording) return
const rect = progressBar.value.getBoundingClientRect()
const clickX = event.clientX - rect.left
const percentage = (clickX / rect.width) * 100
const newTime = (percentage / 100) * recordingStore.selectedRecording.duration
recordingStore.setPlaybackTime(newTime)
}
onMounted(() => {
// 确保在组件挂载时停止任何正在进行的回放
if (recordingStore.isPlaying) {
recording.stopPlayback()
}
})
onUnmounted(() => {
// 组件卸载时停止回放
if (recordingStore.isPlaying) {
recording.stopPlayback()
}
})
</script>
<style scoped>
.playback-controls {
padding: 16px;
height: 100%;
overflow-y: auto;
}
.playback-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 16px;
}
.playback-header h4 {
margin: 0;
font-size: 14px;
color: #333;
}
.playback-status {
display: flex;
align-items: center;
gap: 6px;
padding: 4px 8px;
border-radius: 4px;
font-size: 12px;
}
.status-playing {
background: #d4edda;
color: #155724;
}
.status-paused {
background: #fff3cd;
color: #856404;
}
.status-idle {
background: #f8f9fa;
color: #6c757d;
}
.status-icon {
font-size: 10px;
}
.status-text {
font-weight: 500;
}
.selected-recording {
padding: 12px;
background: #f8f9fa;
border-radius: 6px;
margin-bottom: 16px;
}
.recording-info {
display: flex;
justify-content: space-between;
align-items: center;
}
.recording-name {
font-size: 14px;
font-weight: 500;
color: #333;
}
.recording-duration {
font-size: 12px;
color: #666;
font-family: monospace;
}
.no-selection {
padding: 12px;
background: #f8f9fa;
border-radius: 6px;
margin-bottom: 16px;
text-align: center;
color: #999;
font-size: 13px;
}
.playback-progress {
margin-bottom: 16px;
}
.progress-bar {
position: relative;
height: 6px;
background: #e9ecef;
border-radius: 3px;
cursor: pointer;
margin-bottom: 8px;
}
.progress-track {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
border-radius: 3px;
}
.progress-fill {
position: absolute;
top: 0;
left: 0;
height: 100%;
background: #3498db;
border-radius: 3px;
transition: width 0.1s linear;
}
.progress-thumb {
position: absolute;
top: 50%;
transform: translate(-50%, -50%);
width: 12px;
height: 12px;
background: #3498db;
border-radius: 50%;
border: 2px solid white;
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.2);
}
.time-display {
display: flex;
justify-content: space-between;
font-size: 11px;
color: #666;
}
.current-time {
font-family: monospace;
}
.total-time {
font-family: monospace;
color: #999;
}
.control-buttons {
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 8px;
margin-bottom: 16px;
}
.control-btn {
padding: 8px 12px;
border: none;
border-radius: 6px;
font-size: 13px;
cursor: pointer;
transition: all 0.2s;
display: flex;
align-items: center;
justify-content: center;
gap: 6px;
}
.control-btn:disabled {
opacity: 0.5;
cursor: not-allowed;
}
.play-btn {
background: #2ecc71;
color: white;
}
.play-btn:hover:not(:disabled) {
background: #27ae60;
}
.pause-btn {
background: #f39c12;
color: white;
}
.pause-btn:hover:not(:disabled) {
background: #d68910;
}
.stop-btn {
background: #e74c3c;
color: white;
}
.stop-btn:hover:not(:disabled) {
background: #c0392b;
}
.loop-btn {
background: #f8f9fa;
color: #666;
border: 1px solid #dee2e6;
}
.loop-btn:hover:not(:disabled) {
background: #e9ecef;
}
.loop-btn.active {
background: #3498db;
color: white;
border-color: #3498db;
}
.btn-icon {
font-size: 11px;
}
.btn-text {
font-size: 12px;
}
.speed-control {
margin-bottom: 16px;
}
.speed-label {
display: block;
margin-bottom: 8px;
font-size: 12px;
color: #666;
}
.speed-buttons {
display: flex;
flex-wrap: wrap;
gap: 4px;
}
.speed-btn {
padding: 4px 8px;
border: 1px solid #dee2e6;
border-radius: 4px;
background: white;
color: #666;
font-size: 11px;
cursor: pointer;
transition: all 0.2s;
}
.speed-btn:hover {
background: #f8f9fa;
}
.speed-btn.active {
background: #3498db;
color: white;
border-color: #3498db;
}
.playback-actions {
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 8px;
}
.action-btn {
padding: 6px 10px;
border: 1px solid #dee2e6;
border-radius: 4px;
background: white;
color: #666;
font-size: 11px;
cursor: pointer;
transition: all 0.2s;
display: flex;
align-items: center;
justify-content: center;
gap: 4px;
}
.action-btn:disabled {
opacity: 0.5;
cursor: not-allowed;
}
.action-btn:hover:not(:disabled) {
background: #f8f9fa;
}
.jump-btn {
background: #f8f9fa;
}
.step-btn {
background: #f8f9fa;
}
.action-icon {
font-size: 10px;
}
.action-text {
font-size: 11px;
}
</style>

查看文件

@ -0,0 +1,651 @@
<template>
<div class="recording-panel">
<div class="panel-header">
<h3>动作录制</h3>
<div class="connection-status" v-if="robotStore.robotId">
<span class="status-dot connected"></span>
<span class="status-text">已连接: {{ robotStore.robotId }}</span>
</div>
<div class="connection-status" v-else>
<span class="status-dot disconnected"></span>
<span class="status-text">未连接机器人</span>
</div>
</div>
<div class="recording-controls">
<div class="recording-status" :class="recordingStatusClass">
<span class="status-icon">
<span v-if="recordingStore.isRecording" class="recording-dot"></span>
<span v-else-if="recordingStore.isPaused" class="paused-icon">⏸️</span>
<span v-else class="idle-icon">●</span>
</span>
<span class="status-text">{{ recordingStatusText }}</span>
<span class="duration" v-if="recordingStore.isRecording || recordingStore.isPaused">
{{ formatDuration(recordingStore.recordingDuration) }}
</span>
</div>
<div class="control-buttons">
<button
@click="startRecording"
class="control-btn record-btn"
:disabled="!robotStore.robotId || recordingStore.isRecording || recordingStore.isPaused"
title="开始录制"
>
<span class="btn-icon">●</span>
<span class="btn-text">录制</span>
</button>
<button
@click="pauseRecording"
class="control-btn pause-btn"
:disabled="!recordingStore.isRecording"
title="暂停录制"
>
<span class="btn-icon">⏸️</span>
<span class="btn-text">暂停</span>
</button>
<button
@click="resumeRecording"
class="control-btn resume-btn"
:disabled="!recordingStore.isPaused"
title="继续录制"
>
<span class="btn-icon">▶️</span>
<span class="btn-text">继续</span>
</button>
<button
@click="stopRecording"
class="control-btn stop-btn"
:disabled="!recordingStore.isRecording && !recordingStore.isPaused"
title="停止录制"
>
<span class="btn-icon">■</span>
<span class="btn-text">停止</span>
</button>
</div>
</div>
<div class="recordings-list" v-if="recordingStore.hasRecordings">
<div class="list-header">
<h4>录制列表</h4>
<button
@click="clearAllRecordings"
class="clear-btn"
title="清空所有录制"
:disabled="recordingStore.isRecording || recordingStore.isPlaying"
>
清空
</button>
</div>
<div class="recordings-container">
<div
v-for="recording in recordingStore.recordings"
:key="recording.id"
class="recording-item"
:class="{ selected: recordingStore.selectedRecordingId === recording.id }"
@click="selectRecording(recording.id)"
>
<div class="recording-info">
<div class="recording-name">{{ recording.name }}</div>
<div class="recording-details">
<span class="detail-item">
<span class="detail-icon">🤖</span>
{{ recording.robotId }}
</span>
<span class="detail-item">
<span class="detail-icon">⏱️</span>
{{ formatDuration(recording.duration) }}
</span>
<span class="detail-item">
<span class="detail-icon">📅</span>
{{ formatTime(recording.createdAt) }}
</span>
</div>
</div>
<div class="recording-actions">
<button
@click.stop="exportRecording(recording.id)"
class="action-btn export-btn"
title="导出为JSON"
>
<span class="action-icon">📥</span>
<span class="action-text">导出</span>
</button>
<button
@click.stop="deleteRecording(recording.id)"
class="action-btn delete-btn"
title="删除录制"
:disabled="recordingStore.isRecording || recordingStore.isPlaying"
>
<span class="action-icon">🗑️</span>
<span class="action-text">删除</span>
</button>
</div>
</div>
</div>
</div>
<div class="empty-state" v-else>
<div class="empty-icon">📁</div>
<p class="empty-text">暂无录制</p>
<p class="empty-hint">开始录制后,您的动作将显示在这里</p>
</div>
<div class="import-section">
<input
type="file"
ref="fileInput"
@change="handleFileImport"
accept=".json"
style="display: none"
/>
<button
@click="triggerFileImport"
class="import-btn"
:disabled="recordingStore.isRecording || recordingStore.isPlaying"
>
<span class="import-icon">📤</span>
<span class="import-text">导入录制文件</span>
</button>
<p class="import-hint">支持JSON格式的录制文件</p>
</div>
</div>
</template>
<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRobotStore } from '@/stores/robot'
import { useRecordingStore } from '@/stores/recording'
import { useRecording } from '@/composables/useRecording'
import { formatDuration, formatTime } from '@/utils/recordingUtils'
const robotStore = useRobotStore()
const recordingStore = useRecordingStore()
const recording = useRecording()
const fileInput = ref<HTMLInputElement | null>(null)
onMounted(() => {
recordingStore.loadRecordings()
})
const recordingStatusClass = computed(() => {
if (recordingStore.isRecording) return 'status-recording'
if (recordingStore.isPaused) return 'status-paused'
return 'status-idle'
})
const recordingStatusText = computed(() => {
if (recordingStore.isRecording) return '录制中'
if (recordingStore.isPaused) return '已暂停'
return '准备录制'
})
const startRecording = () => {
if (!robotStore.robotId) {
alert('请先连接到机器人')
return
}
recording.startRecording()
}
const pauseRecording = () => {
recording.pauseRecording()
}
const resumeRecording = () => {
recording.resumeRecording()
}
const stopRecording = () => {
recording.stopRecording()
}
const selectRecording = (recordingId: string) => {
recordingStore.selectRecording(recordingId)
}
const exportRecording = (recordingId: string) => {
recording.exportRecording(recordingId)
}
const deleteRecording = (recordingId: string) => {
if (confirm('确定要删除这个录制吗?')) {
recordingStore.deleteRecording(recordingId)
}
}
const clearAllRecordings = () => {
if (confirm('确定要清空所有录制吗?此操作不可恢复。')) {
recordingStore.clearAllRecordings()
}
}
const triggerFileImport = () => {
if (fileInput.value) {
fileInput.value.click()
}
}
const handleFileImport = async (event: Event) => {
const input = event.target as HTMLInputElement
if (!input.files || input.files.length === 0) return
const file = input.files[0]
if (!file) return
try {
await recording.importRecording(file)
alert('录制文件导入成功!')
} catch (error) {
console.error('导入失败:', error)
alert('导入失败: ' + (error as Error).message)
}
input.value = ''
}
</script>
<style scoped>
.recording-panel {
height: 100%;
display: flex;
flex-direction: column;
}
.panel-header {
padding: 16px;
border-bottom: 1px solid #e0e0e0;
background: #f8f9fa;
}
.panel-header h3 {
margin: 0 0 8px 0;
font-size: 18px;
color: #333;
}
.connection-status {
display: flex;
align-items: center;
gap: 8px;
font-size: 12px;
}
.status-dot {
width: 8px;
height: 8px;
border-radius: 50%;
}
.status-dot.connected {
background: #2ecc71;
}
.status-dot.disconnected {
background: #e74c3c;
}
.status-text {
color: #666;
}
.recording-controls {
padding: 16px;
border-bottom: 1px solid #e0e0e0;
}
.recording-status {
display: flex;
align-items: center;
gap: 8px;
margin-bottom: 16px;
padding: 8px 12px;
border-radius: 6px;
background: #f8f9fa;
}
.status-recording {
background: #ffeaea;
border-left: 4px solid #e74c3c;
}
.status-paused {
background: #fff3cd;
border-left: 4px solid #f39c12;
}
.status-idle {
background: #f8f9fa;
border-left: 4px solid #95a5a6;
}
.status-icon {
font-size: 14px;
}
.recording-dot {
display: inline-block;
width: 10px;
height: 10px;
background: #e74c3c;
border-radius: 50%;
animation: pulse 1.5s infinite;
}
.paused-icon, .idle-icon {
font-size: 12px;
}
.status-text {
flex: 1;
font-size: 14px;
font-weight: 500;
}
.duration {
font-size: 12px;
color: #666;
font-family: monospace;
}
.control-buttons {
display: grid;
grid-template-columns: repeat(2, 1fr);
gap: 8px;
}
.control-btn {
padding: 10px 12px;
border: none;
border-radius: 6px;
font-size: 14px;
cursor: pointer;
transition: all 0.2s;
display: flex;
align-items: center;
justify-content: center;
gap: 6px;
}
.control-btn:disabled {
opacity: 0.5;
cursor: not-allowed;
}
.record-btn {
background: #e74c3c;
color: white;
}
.record-btn:hover:not(:disabled) {
background: #c0392b;
}
.pause-btn {
background: #f39c12;
color: white;
}
.pause-btn:hover:not(:disabled) {
background: #d68910;
}
.resume-btn {
background: #2ecc71;
color: white;
}
.resume-btn:hover:not(:disabled) {
background: #27ae60;
}
.stop-btn {
background: #34495e;
color: white;
}
.stop-btn:hover:not(:disabled) {
background: #2c3e50;
}
.btn-icon {
font-size: 12px;
}
.btn-text {
font-size: 13px;
}
.recordings-list {
flex: 1;
display: flex;
flex-direction: column;
overflow: hidden;
}
.list-header {
padding: 12px 16px;
border-bottom: 1px solid #e0e0e0;
display: flex;
justify-content: space-between;
align-items: center;
}
.list-header h4 {
margin: 0;
font-size: 14px;
color: #333;
}
.clear-btn {
padding: 4px 8px;
border: 1px solid #e74c3c;
border-radius: 4px;
background: white;
color: #e74c3c;
font-size: 12px;
cursor: pointer;
transition: all 0.2s;
}
.clear-btn:hover:not(:disabled) {
background: #e74c3c;
color: white;
}
.clear-btn:disabled {
opacity: 0.5;
cursor: not-allowed;
}
.recordings-container {
flex: 1;
overflow-y: auto;
padding: 8px;
}
.recording-item {
padding: 12px;
margin-bottom: 8px;
border: 1px solid #e0e0e0;
border-radius: 6px;
cursor: pointer;
transition: all 0.2s;
}
.recording-item:hover {
background: #f8f9fa;
border-color: #3498db;
}
.recording-item.selected {
background: #ebf5fb;
border-color: #3498db;
border-left: 4px solid #3498db;
}
.recording-info {
margin-bottom: 8px;
}
.recording-name {
font-size: 14px;
font-weight: 500;
color: #333;
margin-bottom: 4px;
}
.recording-details {
display: flex;
flex-wrap: wrap;
gap: 12px;
font-size: 11px;
color: #666;
}
.detail-item {
display: flex;
align-items: center;
gap: 4px;
}
.detail-icon {
font-size: 10px;
}
.recording-actions {
display: flex;
gap: 8px;
}
.action-btn {
padding: 4px 8px;
border: none;
border-radius: 4px;
font-size: 11px;
cursor: pointer;
transition: all 0.2s;
display: flex;
align-items: center;
gap: 4px;
}
.export-btn {
background: #3498db;
color: white;
}
.export-btn:hover {
background: #2980b9;
}
.delete-btn {
background: #e74c3c;
color: white;
}
.delete-btn:hover:not(:disabled) {
background: #c0392b;
}
.delete-btn:disabled {
opacity: 0.5;
cursor: not-allowed;
}
.action-icon {
font-size: 10px;
}
.action-text {
font-size: 11px;
}
.empty-state {
flex: 1;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
padding: 40px 20px;
color: #999;
}
.empty-icon {
font-size: 48px;
margin-bottom: 16px;
opacity: 0.5;
}
.empty-text {
margin: 0 0 8px 0;
font-size: 14px;
}
.empty-hint {
margin: 0;
font-size: 12px;
text-align: center;
max-width: 200px;
}
.import-section {
padding: 16px;
border-top: 1px solid #e0e0e0;
text-align: center;
}
.import-btn {
padding: 10px 16px;
border: 2px dashed #3498db;
border-radius: 6px;
background: white;
color: #3498db;
font-size: 14px;
cursor: pointer;
transition: all 0.2s;
display: inline-flex;
align-items: center;
gap: 8px;
}
.import-btn:hover:not(:disabled) {
background: #ebf5fb;
border-color: #2980b9;
}
.import-btn:disabled {
opacity: 0.5;
cursor: not-allowed;
}
.import-icon {
font-size: 16px;
}
.import-text {
font-size: 13px;
}
.import-hint {
margin: 8px 0 0 0;
font-size: 11px;
color: #666;
}
@keyframes pulse {
0%, 100% {
opacity: 1;
}
50% {
opacity: 0.5;
}
}
</style>

查看文件

@ -0,0 +1,267 @@
import { ref, onUnmounted, watch } from 'vue'
import { useRobotStore } from '@/stores/robot'
import { useRecordingStore } from '@/stores/recording'
import { useUIStore } from '@/stores/ui'
import type { RecordingFrame } from '@/types/recording'
const SAMPLING_INTERVAL = 50 // 50ms采样间隔
export function useRecording() {
const robotStore = useRobotStore()
const recordingStore = useRecordingStore()
const uiStore = useUIStore()
const samplingTimer = ref<number | null>(null)
const playbackTimer = ref<number | null>(null)
const lastPlaybackTime = ref<number>(0)
const startSampling = () => {
if (samplingTimer.value) return
samplingTimer.value = setInterval(() => {
if (recordingStore.isRecording && robotStore.robotId) {
const joints: Record<string, number> = {}
robotStore.jointList.forEach(joint => {
joints[joint.id] = joint.currentAngle
})
recordingStore.addRecordingFrame(joints)
}
}, SAMPLING_INTERVAL) as unknown as number
}
const stopSampling = () => {
if (samplingTimer.value) {
clearInterval(samplingTimer.value)
samplingTimer.value = null
}
}
const startPlaybackLoop = () => {
if (playbackTimer.value) return
lastPlaybackTime.value = Date.now()
const updatePlayback = () => {
if (!recordingStore.isPlaying || !recordingStore.playbackState.currentRecordingId) {
stopPlaybackLoop()
return
}
const now = Date.now()
const delta = now - lastPlaybackTime.value
lastPlaybackTime.value = now
const recording = recordingStore.recordings.find(
r => r.id === recordingStore.playbackState.currentRecordingId
)
if (!recording) {
stopPlaybackLoop()
return
}
const speed = recordingStore.playbackState.playbackSpeed
const newTime = recordingStore.playbackState.currentTime + delta * speed
if (newTime >= recording.duration) {
if (recordingStore.playbackState.loop) {
recordingStore.setPlaybackTime(0)
} else {
recordingStore.stopPlayback()
stopPlaybackLoop()
return
}
} else {
recordingStore.setPlaybackTime(newTime)
}
const frame = recordingStore.getCurrentPlaybackFrame()
if (frame) {
applyFrameToRobot(frame)
}
playbackTimer.value = requestAnimationFrame(updatePlayback) as unknown as number
}
playbackTimer.value = requestAnimationFrame(updatePlayback) as unknown as number
}
const stopPlaybackLoop = () => {
if (playbackTimer.value) {
cancelAnimationFrame(playbackTimer.value)
playbackTimer.value = null
}
}
const applyFrameToRobot = (frame: RecordingFrame) => {
Object.entries(frame.joints).forEach(([jointId, angle]) => {
robotStore.updateJointAngle(jointId, angle, false)
})
}
const startRecording = () => {
if (!robotStore.robotId) {
console.error('无法开始录制: 未连接机器人')
return
}
recordingStore.startRecording(robotStore.robotId)
startSampling()
// 自动展开录制面板
uiStore.showRecordingPanel()
}
const pauseRecording = () => {
recordingStore.pauseRecording()
stopSampling()
}
const resumeRecording = () => {
recordingStore.resumeRecording()
startSampling()
}
const stopRecording = () => {
recordingStore.stopRecording()
stopSampling()
}
const startPlayback = (recordingId: string) => {
recordingStore.startPlayback(recordingId)
startPlaybackLoop()
// 自动展开回放面板
uiStore.showPlaybackPanel()
}
const pausePlayback = () => {
recordingStore.pausePlayback()
stopPlaybackLoop()
}
const resumePlayback = () => {
recordingStore.resumePlayback()
startPlaybackLoop()
}
const stopPlayback = () => {
recordingStore.stopPlayback()
stopPlaybackLoop()
}
const exportRecording = (recordingId: string) => {
const jsonData = recordingStore.exportRecording(recordingId)
if (jsonData) {
const recording = recordingStore.recordings.find(r => r.id === recordingId)
if (recording) {
const blob = new Blob([jsonData], { type: 'application/json' })
const url = URL.createObjectURL(blob)
const link = document.createElement('a')
link.href = url
link.download = `${recording.name}_${new Date(recording.createdAt).toISOString().split('T')[0]}.json`
document.body.appendChild(link)
link.click()
document.body.removeChild(link)
URL.revokeObjectURL(url)
}
}
}
const importRecording = (file: File) => {
return new Promise((resolve, reject) => {
const reader = new FileReader()
reader.onload = (event) => {
try {
const jsonData = event.target?.result as string
const recording = recordingStore.importRecording(jsonData)
resolve(recording)
} catch (error) {
reject(error)
}
}
reader.onerror = () => {
reject(new Error('文件读取失败'))
}
reader.readAsText(file)
})
}
watch(
() => recordingStore.isRecording,
(isRecording) => {
if (isRecording) {
startSampling()
} else {
stopSampling()
}
}
)
watch(
() => recordingStore.isPlaying,
(isPlaying) => {
if (isPlaying) {
startPlaybackLoop()
} else {
stopPlaybackLoop()
}
}
)
watch(
() => robotStore.connectionStatus,
(status) => {
if (status === 'disconnected') {
if (recordingStore.isRecording) {
stopRecording()
}
if (recordingStore.isPlaying) {
stopPlayback()
}
}
}
)
onUnmounted(() => {
stopSampling()
stopPlaybackLoop()
if (recordingStore.isRecording) {
stopRecording()
}
if (recordingStore.isPlaying) {
stopPlayback()
}
})
return {
startRecording,
pauseRecording,
resumeRecording,
stopRecording,
startPlayback,
pausePlayback,
resumePlayback,
stopPlayback,
exportRecording,
importRecording,
isRecording: () => recordingStore.isRecording,
isPlaying: () => recordingStore.isPlaying,
isPaused: () => recordingStore.isPaused,
currentRecording: () => recordingStore.currentRecording,
selectedRecording: () => recordingStore.selectedRecording,
recordings: () => recordingStore.recordings,
recordingDuration: () => recordingStore.recordingDuration,
playbackState: () => recordingStore.playbackState
}
}

查看文件

@ -0,0 +1,307 @@
import { defineStore } from 'pinia'
import type { Recording, RecordingState, PlaybackState, RecordingStoreState, RecordingStatus } from '@/types/recording'
import { generateRecordingId, formatDuration, exportRecordingToJson, importRecordingFromJson } from '@/utils/recordingUtils'
const STORAGE_KEY = 'robot_recordings'
export const useRecordingStore = defineStore('recording', {
state: (): RecordingStoreState => ({
recordings: [],
recordingState: {
status: 'idle',
currentRecordingId: null,
startTime: null,
pauseTime: null,
recordedFrames: []
},
playbackState: {
status: 'idle',
currentRecordingId: null,
currentTime: 0,
playbackSpeed: 1.0,
loop: false
},
selectedRecordingId: null
}),
getters: {
isRecording: (state) => state.recordingState.status === 'recording',
isPaused: (state) => state.recordingState.status === 'paused',
isPlaying: (state) => state.playbackState.status === 'playing',
currentRecording: (state) => {
if (!state.recordingState.currentRecordingId) return null
return state.recordings.find(r => r.id === state.recordingState.currentRecordingId) || null
},
selectedRecording: (state) => {
if (!state.selectedRecordingId) return null
return state.recordings.find(r => r.id === state.selectedRecordingId) || null
},
recordingDuration: (state) => {
if (state.recordingState.recordedFrames.length === 0) return 0
const lastFrame = state.recordingState.recordedFrames[state.recordingState.recordedFrames.length - 1]
return lastFrame?.timestamp || 0
},
hasRecordings: (state) => state.recordings.length > 0
},
actions: {
loadRecordings() {
try {
const stored = localStorage.getItem(STORAGE_KEY)
if (stored) {
const data = JSON.parse(stored)
this.recordings = data.recordings || []
}
} catch (error) {
console.error('加载录制数据失败:', error)
this.recordings = []
}
},
saveRecordings() {
try {
const data = {
recordings: this.recordings,
version: '1.0.0',
savedAt: Date.now()
}
localStorage.setItem(STORAGE_KEY, JSON.stringify(data))
} catch (error) {
console.error('保存录制数据失败:', error)
}
},
createRecording(name: string, robotId: string) {
const recording: Recording = {
id: generateRecordingId(),
name,
robotId,
createdAt: Date.now(),
duration: 0,
frames: [],
metadata: {
description: '',
tags: [],
version: '1.0.0'
}
}
this.recordings.push(recording)
this.selectedRecordingId = recording.id
this.saveRecordings()
return recording
},
updateRecording(recordingId: string, updates: Partial<Omit<Recording, 'id'>>) {
const index = this.recordings.findIndex(r => r.id === recordingId)
if (index !== -1) {
// 确保不会覆盖id字段
const { id, ...safeUpdates } = updates as any
this.recordings[index] = { ...this.recordings[index], ...safeUpdates }
this.saveRecordings()
}
},
deleteRecording(recordingId: string) {
const index = this.recordings.findIndex(r => r.id === recordingId)
if (index !== -1) {
this.recordings.splice(index, 1)
if (this.selectedRecordingId === recordingId) {
this.selectedRecordingId = null
}
if (this.recordingState.currentRecordingId === recordingId) {
this.stopRecording()
}
if (this.playbackState.currentRecordingId === recordingId) {
this.stopPlayback()
}
this.saveRecordings()
}
},
selectRecording(recordingId: string | null) {
this.selectedRecordingId = recordingId
},
startRecording(robotId: string) {
if (this.isRecording) return
const name = `录制_${new Date().toLocaleTimeString()}`
const recording = this.createRecording(name, robotId)
this.recordingState = {
status: 'recording',
currentRecordingId: recording.id,
startTime: Date.now(),
pauseTime: null,
recordedFrames: []
}
},
pauseRecording() {
if (this.recordingState.status !== 'recording') return
this.recordingState.status = 'paused'
this.recordingState.pauseTime = Date.now()
},
resumeRecording() {
if (this.recordingState.status !== 'paused') return
const pauseDuration = Date.now() - (this.recordingState.pauseTime || Date.now())
this.recordingState.status = 'recording'
this.recordingState.pauseTime = null
this.recordingState.recordedFrames = this.recordingState.recordedFrames.map(frame => ({
...frame,
timestamp: frame.timestamp + pauseDuration
}))
},
stopRecording() {
if (this.recordingState.status === 'idle') return
const recording = this.currentRecording
if (recording) {
recording.duration = this.recordingDuration
recording.frames = [...this.recordingState.recordedFrames]
this.saveRecordings()
}
this.recordingState = {
status: 'idle',
currentRecordingId: null,
startTime: null,
pauseTime: null,
recordedFrames: []
}
},
addRecordingFrame(joints: Record<string, number>) {
if (this.recordingState.status !== 'recording') return
const startTime = this.recordingState.startTime || Date.now()
const timestamp = Date.now() - startTime
this.recordingState.recordedFrames.push({
timestamp,
joints: { ...joints }
})
},
startPlayback(recordingId: string) {
const recording = this.recordings.find(r => r.id === recordingId)
if (!recording) return
this.playbackState = {
status: 'playing',
currentRecordingId: recordingId,
currentTime: 0,
playbackSpeed: 1.0,
loop: false
}
},
pausePlayback() {
if (this.playbackState.status !== 'playing') return
this.playbackState.status = 'paused'
},
resumePlayback() {
if (this.playbackState.status !== 'paused') return
this.playbackState.status = 'playing'
},
stopPlayback() {
this.playbackState = {
status: 'idle',
currentRecordingId: null,
currentTime: 0,
playbackSpeed: 1.0,
loop: false
}
},
setPlaybackTime(time: number) {
const recording = this.recordings.find(r => r.id === this.playbackState.currentRecordingId)
if (!recording) return
this.playbackState.currentTime = Math.max(0, Math.min(time, recording.duration))
},
setPlaybackSpeed(speed: number) {
this.playbackState.playbackSpeed = Math.max(0.1, Math.min(speed, 10.0))
},
toggleLoop() {
this.playbackState.loop = !this.playbackState.loop
},
getCurrentPlaybackFrame() {
const recording = this.recordings.find(r => r.id === this.playbackState.currentRecordingId)
if (!recording || recording.frames.length === 0) return null
const currentTime = this.playbackState.currentTime
if (currentTime <= 0) return recording.frames[0]
if (currentTime >= recording.duration) return recording.frames[recording.frames.length - 1]
for (let i = 0; i < recording.frames.length - 1; i++) {
const frame1 = recording.frames[i]
const frame2 = recording.frames[i + 1]
if (!frame1 || !frame2) continue
if (currentTime >= frame1.timestamp && currentTime <= frame2.timestamp) {
const ratio = (currentTime - frame1.timestamp) / (frame2.timestamp - frame1.timestamp)
const interpolatedJoints: Record<string, number> = {}
Object.keys(frame1.joints).forEach(jointId => {
const angle1 = frame1.joints[jointId] || 0
const angle2 = frame2.joints[jointId] || 0
interpolatedJoints[jointId] = angle1 + (angle2 - angle1) * ratio
})
return {
timestamp: currentTime,
joints: interpolatedJoints
}
}
}
return recording.frames[recording.frames.length - 1]
},
exportRecording(recordingId: string) {
const recording = this.recordings.find(r => r.id === recordingId)
if (!recording) return null
return exportRecordingToJson(recording)
},
importRecording(jsonData: string) {
try {
const recording = importRecordingFromJson(jsonData)
this.recordings.push(recording)
this.saveRecordings()
return recording
} catch (error) {
console.error('导入录制失败:', error)
throw error
}
},
clearAllRecordings() {
this.recordings = []
this.selectedRecordingId = null
this.stopRecording()
this.stopPlayback()
localStorage.removeItem(STORAGE_KEY)
}
}
})

查看文件

@ -31,7 +31,14 @@ export const useRobotStore = defineStore('robot', {
if (!state.selectedJoint) return null if (!state.selectedJoint) return null
return state.joints.get(state.selectedJoint) || null return state.joints.get(state.selectedJoint) || null
}, },
isWebSocketAvailable: () => webSocketFunctions !== null isWebSocketAvailable: () => webSocketFunctions !== null,
jointAngles: (state) => {
const angles: Record<string, number> = {}
state.joints.forEach((joint, id) => {
angles[id] = joint.currentAngle
})
return angles
}
}, },
actions: { actions: {

50
frontend/src/stores/ui.ts 普通文件
查看文件

@ -0,0 +1,50 @@
import { defineStore } from 'pinia'
export const useUIStore = defineStore('ui', {
state: () => ({
recordingPanelExpanded: false,
playbackPanelExpanded: false,
panelAnimationDuration: 300 // 毫秒
}),
getters: {
isRecordingPanelVisible: (state) => state.recordingPanelExpanded,
isPlaybackPanelVisible: (state) => state.playbackPanelExpanded,
recordingPanelWidth: (state) => state.recordingPanelExpanded ? 320 : 0,
playbackPanelHeight: (state) => state.playbackPanelExpanded ? 180 : 0
},
actions: {
toggleRecordingPanel() {
this.recordingPanelExpanded = !this.recordingPanelExpanded
},
togglePlaybackPanel() {
this.playbackPanelExpanded = !this.playbackPanelExpanded
},
showRecordingPanel() {
this.recordingPanelExpanded = true
},
hideRecordingPanel() {
this.recordingPanelExpanded = false
},
showPlaybackPanel() {
this.playbackPanelExpanded = true
},
hidePlaybackPanel() {
this.playbackPanelExpanded = false
},
setRecordingPanel(expanded: boolean) {
this.recordingPanelExpanded = expanded
},
setPlaybackPanel(expanded: boolean) {
this.playbackPanelExpanded = expanded
}
}
})

查看文件

@ -0,0 +1,43 @@
export interface RecordingFrame {
timestamp: number
joints: Record<string, number>
}
export interface Recording {
id: string
name: string
robotId: string
createdAt: number
duration: number
frames: RecordingFrame[]
metadata?: {
description?: string
tags?: string[]
version?: string
}
}
export type RecordingStatus = 'idle' | 'recording' | 'paused' | 'playing' | 'stopped'
export interface RecordingState {
status: RecordingStatus
currentRecordingId: string | null
startTime: number | null
pauseTime: number | null
recordedFrames: RecordingFrame[]
}
export interface PlaybackState {
status: 'idle' | 'playing' | 'paused'
currentRecordingId: string | null
currentTime: number
playbackSpeed: number
loop: boolean
}
export interface RecordingStoreState {
recordings: Recording[]
recordingState: RecordingState
playbackState: PlaybackState
selectedRecordingId: string | null
}

查看文件

@ -0,0 +1,198 @@
import type { Recording, RecordingFrame } from '@/types/recording'
export function generateRecordingId(): string {
return `rec_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`
}
export function formatDuration(ms: number): string {
const totalSeconds = Math.floor(ms / 1000)
const minutes = Math.floor(totalSeconds / 60)
const seconds = totalSeconds % 60
const milliseconds = ms % 1000
if (minutes > 0) {
return `${minutes}:${seconds.toString().padStart(2, '0')}.${Math.floor(milliseconds / 100).toString().padStart(1, '0')}`
} else {
return `${seconds}.${Math.floor(milliseconds / 10).toString().padStart(2, '0')}`
}
}
export function formatTime(timestamp: number): string {
const date = new Date(timestamp)
return date.toLocaleString('zh-CN', {
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
second: '2-digit'
})
}
export function compressFrames(frames: RecordingFrame[], threshold: number = 0.1): RecordingFrame[] {
if (frames.length <= 1) return frames
const firstFrame = frames[0]
if (!firstFrame) return frames
const compressed: RecordingFrame[] = [firstFrame]
for (let i = 1; i < frames.length; i++) {
const prevFrame = compressed[compressed.length - 1]
const currentFrame = frames[i]
if (!prevFrame || !currentFrame) continue
let hasSignificantChange = false
Object.keys(currentFrame.joints).forEach(jointId => {
const prevAngle = prevFrame.joints[jointId] || 0
const currentAngle = currentFrame.joints[jointId] || 0
if (Math.abs(currentAngle - prevAngle) > threshold) {
hasSignificantChange = true
}
})
if (hasSignificantChange || (currentFrame.timestamp - prevFrame.timestamp) > 1000) {
compressed.push(currentFrame)
}
}
return compressed
}
export function exportRecordingToJson(recording: Recording): string {
const exportData = {
...recording,
metadata: {
...recording.metadata,
exportVersion: '1.0.0',
exportedAt: Date.now()
}
}
return JSON.stringify(exportData, null, 2)
}
export function importRecordingFromJson(jsonData: string): Recording {
const data = JSON.parse(jsonData)
if (!data.id || !data.name || !data.robotId || !data.frames) {
throw new Error('无效的录制数据格式')
}
const recording: Recording = {
id: generateRecordingId(),
name: data.name,
robotId: data.robotId,
createdAt: data.createdAt || Date.now(),
duration: data.duration || 0,
frames: data.frames,
metadata: {
...data.metadata,
importedAt: Date.now(),
originalId: data.id
}
}
return recording
}
export function downloadRecording(recording: Recording, filename?: string) {
const jsonData = exportRecordingToJson(recording)
const blob = new Blob([jsonData], { type: 'application/json' })
const url = URL.createObjectURL(blob)
const link = document.createElement('a')
link.href = url
link.download = filename || `${recording.name}_${new Date(recording.createdAt).toISOString().split('T')[0]}.json`
document.body.appendChild(link)
link.click()
document.body.removeChild(link)
URL.revokeObjectURL(url)
}
export function readRecordingFile(file: File): Promise<Recording> {
return new Promise((resolve, reject) => {
const reader = new FileReader()
reader.onload = (event) => {
try {
const jsonData = event.target?.result as string
const recording = importRecordingFromJson(jsonData)
resolve(recording)
} catch (error) {
reject(new Error('文件解析失败: ' + error))
}
}
reader.onerror = () => {
reject(new Error('文件读取失败'))
}
reader.readAsText(file)
})
}
export function validateRecording(recording: Recording): { valid: boolean; errors: string[] } {
const errors: string[] = []
if (!recording.id) errors.push('缺少录制ID')
if (!recording.name) errors.push('缺少录制名称')
if (!recording.robotId) errors.push('缺少机器人ID')
if (!Array.isArray(recording.frames)) errors.push('帧数据格式错误')
if (recording.frames.length > 0) {
recording.frames.forEach((frame, index) => {
if (typeof frame.timestamp !== 'number') {
errors.push(`第${index + 1}帧: 时间戳格式错误`)
}
if (!frame.joints || typeof frame.joints !== 'object') {
errors.push(`第${index + 1}帧: 关节数据格式错误`)
}
})
}
return {
valid: errors.length === 0,
errors
}
}
export function calculateRecordingStats(recording: Recording) {
if (recording.frames.length === 0) {
return {
frameCount: 0,
duration: 0,
averageFrameInterval: 0,
jointCount: 0
}
}
const frameCount = recording.frames.length
const lastFrame = recording.frames[recording.frames.length - 1]
const duration = recording.duration || (lastFrame ? lastFrame.timestamp : 0)
const averageFrameInterval = duration / frameCount
const jointIds = new Set<string>()
recording.frames.forEach(frame => {
Object.keys(frame.joints).forEach(jointId => jointIds.add(jointId))
})
return {
frameCount,
duration,
averageFrameInterval,
jointCount: jointIds.size
}
}
export function createRecordingSnapshot(joints: Record<string, number>): RecordingFrame {
return {
timestamp: 0,
joints: { ...joints }
}
}