init: 第一个版本

这个提交包含在:
2026-03-12 12:56:36 +08:00
当前提交 00fbd43b92
共有 50 个文件被更改,包括 7647 次插入 和 0 次删除

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 普通文件
查看文件

@ -0,0 +1,3 @@
{
"recommendations": ["Vue.volar"]
}

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 普通文件
查看文件

@ -0,0 +1 @@
/// <reference types="vite/client" />

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 自动生成的 普通文件

文件差异内容过多而无法显示 加载差异

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 普通文件

二进制文件未显示。

之后

宽度:  |  高度:  |  大小: 4.2 KiB

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>

查看文件

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

查看文件

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

查看文件

@ -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 普通文件
查看文件

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

查看文件

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

查看文件

@ -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 普通文件
查看文件

@ -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 普通文件
查看文件

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

查看文件

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

查看文件

@ -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 普通文件
查看文件

@ -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 普通文件
查看文件

@ -0,0 +1,11 @@
{
"files": [],
"references": [
{
"path": "./tsconfig.node.json"
},
{
"path": "./tsconfig.app.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 普通文件
查看文件

@ -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))
},
},
})