3v324v23 commited on
Commit
aacd740
·
0 Parent(s):

Initial commit with enhancements

Browse files
Dockerfile ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.11-slim
2
+
3
+ WORKDIR /app
4
+
5
+ COPY requirements.txt .
6
+ RUN pip install --no-cache-dir -r requirements.txt
7
+
8
+ COPY . .
9
+
10
+ # Create a non-root user
11
+ RUN useradd -m -u 1000 user
12
+ USER user
13
+ ENV HOME=/home/user \
14
+ PATH=/home/user/.local/bin:$PATH
15
+
16
+ EXPOSE 7860
17
+
18
+ CMD ["gunicorn", "-b", "0.0.0.0:7860", "app:app"]
README.md ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: Clawbot Control Agent
3
+ emoji: 🤖
4
+ colorFrom: blue
5
+ colorTo: gray
6
+ sdk: docker
7
+ app_port: 7860
8
+ short_description: 工业级机械臂AI操控与资产管理终端
9
+ ---
10
+
11
+ # Clawbot Control Agent (机械臂操控代理)
12
+
13
+ **Clawbot Control Agent** 是一个专为工业自动化设计的具身智能(Embodied AI)操控终端。它结合了 SiliconFlow 的大模型能力与实时数字孪生技术,允许用户通过自然语言指令控制机械臂,并积累高价值的“动作资产”(Motion Assets)。
14
+
15
+ ## 核心功能 (Key Features)
16
+
17
+ 1. **AI 意图控制 (Intent Control)**:
18
+ - 集成 SiliconFlow API (DeepSeek/Qwen),将自然语言指令(如“抓取左侧红色工件”)实时转化为精确的 4自由度 (4-DOF) 关节坐标。
19
+ - 支持复杂逻辑判断与路径规划解释。
20
+
21
+ 2. **实时数字孪生 (Digital Twin)**:
22
+ - 基于 Canvas 的 2D 侧视实时仿真,可视化机械臂姿态。
23
+ - ECharts 实时监控电机温度与负载(模拟数据),确保系统可靠性。
24
+
25
+ 3. **资产积累 (Asset Accumulation)**:
26
+ - **动作资产库**: 用户可以将调试好的完美动作序列保存为“标准资产”,供后续自动化任务调用。
27
+ - 支持 SQLite 持久化存储,构建企业级自动化知识库。
28
+
29
+ 4. **商业化设计 (Commercial Ready)**:
30
+ - 移动端优先 (Mobile-First) 的响应式设计。
31
+ - 清晰的“生产力工具”风格界面。
32
+
33
+ ## 技术栈 (Tech Stack)
34
+
35
+ - **Backend**: Python Flask 3.0, SQLite (Data Persistence)
36
+ - **Frontend**: Vue 3 (Composition API), Tailwind CSS, ECharts 5
37
+ - **AI Integration**: SiliconFlow API (OpenAI Compatible)
38
+ - **Deployment**: Docker (Production Grade)
39
+
40
+ ## 快速开始 (Quick Start)
41
+
42
+ 1. **安装依赖**:
43
+ ```bash
44
+ pip install -r requirements.txt
45
+ ```
46
+
47
+ 2. **设置 API Key**:
48
+ 在环境变量中设置 `SILICONFLOW_API_KEY`,或在 `app.py` 中配置。
49
+
50
+ 3. **启动服务**:
51
+ ```bash
52
+ python app.py
53
+ ```
54
+ 访问 `http://localhost:7860`。
55
+
56
+ ## Docker 部署
57
+
58
+ ```bash
59
+ docker build -t clawbot-agent .
60
+ docker run -p 7860:7860 clawbot-agent
61
+ ```
62
+
63
+ ## 资产价值 (Value Proposition)
64
+
65
+ 本项目不仅仅是一个控制器,更是一个**工业自动化数据的采集器**。随着用户的使用,系统会积累大量的“动作-意图”对数据,这些数据是训练下一代具身智能大模型(VLA Models)的宝贵资产。
__pycache__/app.cpython-314.pyc ADDED
Binary file (10.3 kB). View file
 
app.py ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import json
3
+ import sqlite3
4
+ import datetime
5
+ import requests
6
+ from flask import Flask, render_template, request, jsonify, g
7
+ from flask_cors import CORS
8
+
9
+ app = Flask(__name__)
10
+ CORS(app)
11
+
12
+ # Configuration
13
+ app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024 # 16MB max upload
14
+ SILICONFLOW_API_KEY = os.environ.get("SILICONFLOW_API_KEY", "sk-vimuseiptfbomzegyuvmebjzooncsqbyjtlddrfodzcdskgi")
15
+ DB_NAME = "clawbot_assets.db"
16
+
17
+ # Ensure instance folder exists
18
+ os.makedirs(app.instance_path, exist_ok=True)
19
+ DB_PATH = os.path.join(app.instance_path, DB_NAME)
20
+
21
+ def get_db():
22
+ db = getattr(g, '_database', None)
23
+ if db is None:
24
+ db = g._database = sqlite3.connect(DB_PATH)
25
+ db.row_factory = sqlite3.Row
26
+ return db
27
+
28
+ @app.teardown_appcontext
29
+ def close_connection(exception):
30
+ db = getattr(g, '_database', None)
31
+ if db is not None:
32
+ db.close()
33
+
34
+ def init_db():
35
+ with app.app_context():
36
+ db = get_db()
37
+ cursor = db.cursor()
38
+ cursor.execute('''
39
+ CREATE TABLE IF NOT EXISTS motions (
40
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
41
+ name TEXT NOT NULL,
42
+ description TEXT,
43
+ joints TEXT NOT NULL, -- JSON string: {base, shoulder, elbow, claw}
44
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
45
+ )
46
+ ''')
47
+ # Add some demo data if empty
48
+ cursor.execute('SELECT count(*) FROM motions')
49
+ if cursor.fetchone()[0] == 0:
50
+ demos = [
51
+ ('Home Position', 'Reset to safe start', json.dumps({'base': 90, 'shoulder': 90, 'elbow': 90, 'claw': 0})),
52
+ ('Grab Low', 'Pick up object from floor', json.dumps({'base': 90, 'shoulder': 45, 'elbow': 135, 'claw': 100})),
53
+ ('Inspect High', 'Lift object for inspection', json.dumps({'base': 90, 'shoulder': 135, 'elbow': 45, 'claw': 100}))
54
+ ]
55
+ cursor.executemany('INSERT INTO motions (name, description, joints) VALUES (?, ?, ?)', demos)
56
+ db.commit()
57
+
58
+ @app.route('/')
59
+ def index():
60
+ return render_template('index.html')
61
+
62
+ @app.route('/api/status')
63
+ def status():
64
+ # Mock telemetry for "Reliability" monitoring
65
+ import random
66
+ return jsonify({
67
+ 'motor_temp': [random.randint(40, 65) for _ in range(4)],
68
+ 'power_draw': random.randint(120, 200),
69
+ 'connection': 'ONLINE',
70
+ 'uptime': '48h 12m'
71
+ })
72
+
73
+ @app.route('/api/motions', methods=['GET', 'POST'])
74
+ def handle_motions():
75
+ db = get_db()
76
+ if request.method == 'POST':
77
+ data = request.json
78
+ name = data.get('name', 'Untitled Motion')
79
+ desc = data.get('description', '')
80
+ joints = json.dumps(data.get('joints', {}))
81
+
82
+ cursor = db.cursor()
83
+ cursor.execute('INSERT INTO motions (name, description, joints) VALUES (?, ?, ?)', (name, desc, joints))
84
+ db.commit()
85
+ return jsonify({'status': 'success', 'id': cursor.lastrowid})
86
+ else:
87
+ cursor = db.cursor()
88
+ cursor.execute('SELECT * FROM motions ORDER BY created_at DESC')
89
+ rows = cursor.fetchall()
90
+ return jsonify([dict(row) for row in rows])
91
+
92
+ @app.route('/api/upload', methods=['POST'])
93
+ def upload_file():
94
+ if 'file' not in request.files:
95
+ return jsonify({'error': 'No file part'}), 400
96
+ file = request.files['file']
97
+ if file.filename == '':
98
+ return jsonify({'error': 'No selected file'}), 400
99
+
100
+ try:
101
+ if file.filename.endswith('.json'):
102
+ content = json.load(file)
103
+ if isinstance(content, list):
104
+ db = get_db()
105
+ cursor = db.cursor()
106
+ for item in content:
107
+ name = item.get('name', 'Imported Motion')
108
+ desc = item.get('description', '')
109
+ # Handle if joints is dict or string
110
+ joints_val = item.get('joints', {})
111
+ if isinstance(joints_val, dict):
112
+ joints = json.dumps(joints_val)
113
+ else:
114
+ joints = joints_val
115
+
116
+ cursor.execute('INSERT INTO motions (name, description, joints) VALUES (?, ?, ?)', (name, desc, joints))
117
+ db.commit()
118
+ return jsonify({'status': 'success', 'count': len(content)})
119
+ else:
120
+ return jsonify({'error': 'Invalid JSON format, expected list'}), 400
121
+ return jsonify({'error': 'Unsupported file type'}), 400
122
+ except Exception as e:
123
+ return jsonify({'error': str(e)}), 500
124
+
125
+ @app.route('/api/export', methods=['GET'])
126
+ def export_data():
127
+ db = get_db()
128
+ cursor = db.cursor()
129
+ cursor.execute('SELECT name, description, joints, created_at FROM motions')
130
+ rows = cursor.fetchall()
131
+ data = []
132
+ for row in rows:
133
+ d = dict(row)
134
+ # Ensure joints is parsed back to dict for JSON export, or keep as string?
135
+ # Better to keep as valid JSON object
136
+ try:
137
+ d['joints'] = json.loads(d['joints'])
138
+ except:
139
+ pass
140
+ data.append(d)
141
+
142
+ return jsonify(data)
143
+
144
+ @app.route('/api/analyze', methods=['POST'])
145
+ def analyze_command():
146
+ data = request.json
147
+ command = data.get('command', '')
148
+
149
+ if not command:
150
+ return jsonify({'error': 'No command provided'}), 400
151
+
152
+ # Call SiliconFlow
153
+ headers = {
154
+ "Authorization": f"Bearer {SILICONFLOW_API_KEY}",
155
+ "Content-Type": "application/json"
156
+ }
157
+
158
+ system_prompt = """
159
+ You are the Kinematic Controller for a 4-DOF Robot Arm.
160
+ Joint Limits:
161
+ - Base: 0-180 (0=Left, 180=Right, 90=Center)
162
+ - Shoulder: 0-180 (0=Down, 180=Up)
163
+ - Elbow: 0-180 (0=Folded, 180=Extended)
164
+ - Claw: 0-100 (0=Open, 100=Closed)
165
+
166
+ Output JSON ONLY containing these 4 keys and an 'explanation'.
167
+ Example: {"base": 90, "shoulder": 45, "elbow": 120, "claw": 100, "explanation": "Moving to lower center to grab."}
168
+ """
169
+
170
+ payload = {
171
+ "model": "Qwen/Qwen2.5-7B-Instruct",
172
+ "messages": [
173
+ {"role": "system", "content": system_prompt},
174
+ {"role": "user", "content": f"Command: {command}"}
175
+ ],
176
+ "response_format": {"type": "json_object"}
177
+ }
178
+
179
+ try:
180
+ response = requests.post(
181
+ "https://api.siliconflow.cn/v1/chat/completions",
182
+ json=payload,
183
+ headers=headers,
184
+ timeout=10
185
+ )
186
+ response.raise_for_status()
187
+ result = response.json()
188
+ content = result['choices'][0]['message']['content']
189
+ parsed = json.loads(content)
190
+ return jsonify(parsed)
191
+ except Exception as e:
192
+ print(f"AI Error: {e}")
193
+ # Fallback Mock if AI fails
194
+ return jsonify({
195
+ 'base': 90, 'shoulder': 90, 'elbow': 90, 'claw': 0,
196
+ 'explanation': f"AI Connection Failed. Resetting to Home. Error: {str(e)}"
197
+ })
198
+
199
+ if __name__ == '__main__':
200
+ init_db()
201
+ app.run(host='0.0.0.0', port=7860, debug=True)
instance/clawbot_assets.db ADDED
Binary file (12.3 kB). View file
 
requirements.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ Flask==3.0.0
2
+ flask-cors==4.0.0
3
+ requests==2.31.0
4
+ gunicorn==21.2.0
5
+ python-dotenv==1.0.0
templates/index.html ADDED
@@ -0,0 +1,370 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!DOCTYPE html>
2
+ <html lang="zh-CN">
3
+ <head>
4
+ <meta charset="UTF-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
+ <title>Clawbot Control Agent - 工业级机械臂操控终端</title>
7
+ <script src="https://cdn.tailwindcss.com"></script>
8
+ <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
9
+ <script src="https://cdn.jsdelivr.net/npm/echarts@5.4.3/dist/echarts.min.js"></script>
10
+ <style>
11
+ body { font-family: 'Inter', system-ui, sans-serif; background-color: #f3f4f6; }
12
+ .slider-thumb::-webkit-slider-thumb { -webkit-appearance: none; appearance: none; width: 16px; height: 16px; background: #3b82f6; border-radius: 50%; cursor: pointer; }
13
+ .glass-panel { background: rgba(255, 255, 255, 0.9); backdrop-filter: blur(10px); border: 1px solid rgba(255, 255, 255, 0.5); }
14
+ [v-cloak] { display: none; }
15
+ </style>
16
+ </head>
17
+ <body class="text-gray-800 h-screen flex flex-col overflow-hidden">
18
+
19
+ <div id="app" class="h-full flex flex-col" v-cloak>
20
+ <!-- Header -->
21
+ <header class="bg-white border-b border-gray-200 px-6 py-3 flex justify-between items-center shadow-sm z-10">
22
+ <div class="flex items-center gap-3">
23
+ <div class="w-8 h-8 bg-blue-600 rounded-lg flex items-center justify-center text-white font-bold">C</div>
24
+ <h1 class="text-xl font-bold tracking-tight">Clawbot 机械臂控制终端 <span class="text-xs bg-blue-100 text-blue-800 px-2 py-0.5 rounded ml-2">企业版</span></h1>
25
+ </div>
26
+ <div class="flex items-center gap-4 text-sm">
27
+ <div class="flex items-center gap-2">
28
+ <span class="w-2 h-2 rounded-full" :class="connectionStatus === 'ONLINE' ? 'bg-green-500' : 'bg-red-500'"></span>
29
+ <span>${ connectionStatus === 'ONLINE' ? '在线' : '离线' }</span>
30
+ </div>
31
+ <div class="text-gray-500">运行时间: ${ telemetry.uptime }</div>
32
+ </div>
33
+ </header>
34
+
35
+ <!-- Main Content -->
36
+ <main class="flex-1 flex overflow-hidden">
37
+
38
+ <!-- Left Column: Visualization & Telemetry -->
39
+ <div class="w-1/2 p-6 flex flex-col gap-6 overflow-y-auto border-r border-gray-200 bg-gray-50">
40
+
41
+ <!-- Simulation View -->
42
+ <div class="bg-white rounded-xl shadow-sm p-4 border border-gray-200 flex-1 min-h-[400px] flex flex-col">
43
+ <h2 class="text-sm font-semibold text-gray-500 mb-4 uppercase tracking-wider">实时孪生仿真 (Digital Twin)</h2>
44
+ <div class="flex-1 relative border border-gray-100 rounded-lg bg-slate-50 overflow-hidden flex justify-center items-end pb-10" id="sim-container">
45
+ <!-- Canvas for Side View -->
46
+ <canvas ref="sideViewCanvas" width="400" height="300" class="absolute bottom-0"></canvas>
47
+
48
+ <!-- Base Rotation Indicator (Top Down hint) -->
49
+ <div class="absolute top-4 right-4 bg-white p-2 rounded shadow text-xs">
50
+ <div>Base Angle: ${ joints.base }°</div>
51
+ <div class="w-16 h-16 rounded-full border-2 border-gray-200 mt-1 relative flex items-center justify-center">
52
+ <div class="w-0.5 h-8 bg-blue-500 origin-bottom absolute bottom-1/2 transition-all duration-300" :style="{ transform: 'rotate(' + (joints.base - 90) + 'deg)' }"></div>
53
+ </div>
54
+ </div>
55
+ </div>
56
+ </div>
57
+
58
+ <!-- Telemetry Charts -->
59
+ <div class="bg-white rounded-xl shadow-sm p-4 border border-gray-200 h-48">
60
+ <h2 class="text-sm font-semibold text-gray-500 mb-2 uppercase tracking-wider">电机负载监控 (Motor Load)</h2>
61
+ <div ref="chartContainer" class="w-full h-full"></div>
62
+ </div>
63
+ </div>
64
+
65
+ <!-- Right Column: Controls & Assets -->
66
+ <div class="w-1/2 flex flex-col bg-white">
67
+
68
+ <!-- Manual Controls -->
69
+ <div class="p-6 border-b border-gray-100">
70
+ <div class="flex justify-between items-center mb-4">
71
+ <h2 class="text-lg font-bold">手动控制模式 (Manual Override)</h2>
72
+ <button @click="resetHome" class="text-xs bg-gray-100 hover:bg-gray-200 px-3 py-1 rounded transition">复位 (Reset)</button>
73
+ </div>
74
+
75
+ <div class="grid grid-cols-2 gap-6">
76
+ <div v-for="(val, key) in joints" :key="key" class="space-y-1">
77
+ <div class="flex justify-between text-xs font-medium text-gray-600 uppercase">
78
+ <span>${ key }</span>
79
+ <span>${ val }</span>
80
+ </div>
81
+ <input type="range" v-model.number="joints[key]" min="0" :max="key === 'claw' ? 100 : 180" class="w-full h-2 bg-gray-200 rounded-lg appearance-none cursor-pointer">
82
+ </div>
83
+ </div>
84
+ </div>
85
+
86
+ <!-- AI Command Center -->
87
+ <div class="p-6 border-b border-gray-100 bg-blue-50/50">
88
+ <h2 class="text-lg font-bold mb-3 flex items-center gap-2">
89
+ <svg class="w-5 h-5 text-blue-600" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 10V3L4 14h7v7l9-11h-7z"></path></svg>
90
+ AI 意图控制 (Intent Control)
91
+ </h2>
92
+ <div class="flex gap-2">
93
+ <input v-model="aiCommand" @keyup.enter="executeAI" type="text" placeholder="输入指令 (e.g., 'Grab the box on the left')" class="flex-1 border border-gray-300 rounded-lg px-4 py-2 focus:ring-2 focus:ring-blue-500 focus:outline-none">
94
+ <button @click="executeAI" :disabled="aiLoading" class="bg-blue-600 hover:bg-blue-700 text-white px-6 py-2 rounded-lg font-medium transition flex items-center gap-2">
95
+ <span v-if="aiLoading" class="animate-spin">↻</span>
96
+ <span>执行</span>
97
+ </button>
98
+ </div>
99
+ <div v-if="aiExplanation" class="mt-2 text-sm text-blue-700 bg-blue-100 p-2 rounded border border-blue-200">
100
+ AI: "${ aiExplanation }"
101
+ </div>
102
+ </div>
103
+
104
+ <!-- Asset Library -->
105
+ <div class="flex-1 p-6 overflow-hidden flex flex-col">
106
+ <div class="flex justify-between items-center mb-4">
107
+ <h2 class="text-lg font-bold">动作资产库 (Motion Library)</h2>
108
+ <div class="flex gap-2">
109
+ <input type="file" ref="fileInput" @change="handleFileUpload" class="hidden" accept=".json">
110
+ <button @click="triggerUpload" class="text-sm bg-blue-100 text-blue-700 hover:bg-blue-200 px-3 py-1.5 rounded transition">导入 (Import)</button>
111
+ <button @click="exportMotions" class="text-sm bg-gray-100 text-gray-700 hover:bg-gray-200 px-3 py-1.5 rounded transition">导出 (Export)</button>
112
+ <button @click="saveCurrentMotion" class="text-sm bg-green-600 hover:bg-green-700 text-white px-3 py-1.5 rounded transition shadow-sm">+ 保存当前 (Save)</button>
113
+ </div>
114
+ </div>
115
+
116
+ <div class="flex-1 overflow-y-auto space-y-2 pr-2">
117
+ <div v-for="motion in motions" :key="motion.id" class="group bg-gray-50 hover:bg-white border border-gray-200 hover:border-blue-300 p-3 rounded-lg cursor-pointer transition flex justify-between items-center" @click="loadMotion(motion)">
118
+ <div>
119
+ <div class="font-medium text-gray-900">${ motion.name }</div>
120
+ <div class="text-xs text-gray-500">${ motion.description || '无描述' }</div>
121
+ </div>
122
+ <div class="text-xs text-gray-400 font-mono bg-gray-100 px-2 py-1 rounded">
123
+ ID: ${ motion.id }
124
+ </div>
125
+ </div>
126
+ </div>
127
+ </div>
128
+
129
+ </div>
130
+ </main>
131
+ </div>
132
+
133
+ <script>
134
+ const { createApp, ref, onMounted, watch } = Vue;
135
+
136
+ createApp({
137
+ delimiters: ['${', '}'],
138
+ setup() {
139
+ const joints = ref({ base: 90, shoulder: 90, elbow: 90, claw: 0 });
140
+ const telemetry = ref({ uptime: '-', motor_temp: [0,0,0,0] });
141
+ const connectionStatus = ref('OFFLINE');
142
+ const aiCommand = ref('');
143
+ const aiExplanation = ref('');
144
+ const aiLoading = ref(false);
145
+ const motions = ref([]);
146
+ const sideViewCanvas = ref(null);
147
+ const chartContainer = ref(null);
148
+ const fileInput = ref(null);
149
+ let chartInstance = null;
150
+
151
+ // Canvas Drawing Logic
152
+ const drawArm = () => {
153
+ const ctx = sideViewCanvas.value.getContext('2d');
154
+ const w = sideViewCanvas.value.width;
155
+ const h = sideViewCanvas.value.height;
156
+
157
+ ctx.clearRect(0, 0, w, h);
158
+
159
+ // Config
160
+ const originX = w / 2;
161
+ const originY = h - 20;
162
+ const link1Len = 100;
163
+ const link2Len = 80;
164
+
165
+ // Angles to Radians (Correcting for canvas coord system where Y is down)
166
+ // Shoulder: 0 is horizontal right? Let's say 90 is straight up.
167
+ // Input 0-180. 90=Up.
168
+ const radShoulder = (180 - joints.value.shoulder) * Math.PI / 180;
169
+
170
+ // Elbow: Relative to shoulder? Or absolute?
171
+ // Let's assume standard servo absolute for simplicity of viz.
172
+ // 90 = Straight relative to link1? Let's do absolute for viz simplicity.
173
+ // Actually 4-DOF usually relative.
174
+ // Let's simple map:
175
+ const x1 = originX + Math.cos(radShoulder) * link1Len; // Wrong, 90 is up.
176
+ // Correct:
177
+ // Angle 90 -> -90 deg in canvas (Up).
178
+ // Angle 0 -> 0 deg (Right).
179
+ // Let's map 0->Right, 90->Up, 180->Left.
180
+ const theta1 = -1 * (joints.value.shoulder * Math.PI / 180);
181
+
182
+ const j1x = originX + Math.cos(theta1) * link1Len;
183
+ const j1y = originY + Math.sin(theta1) * link1Len;
184
+
185
+ // Elbow
186
+ const theta2 = theta1 + -1 * ((joints.value.elbow - 90) * Math.PI / 180); // Relative offset
187
+ const j2x = j1x + Math.cos(theta2) * link2Len;
188
+ const j2y = j1y + Math.sin(theta2) * link2Len;
189
+
190
+ // Draw Base
191
+ ctx.fillStyle = '#374151';
192
+ ctx.fillRect(originX - 20, originY, 40, 10);
193
+
194
+ // Draw Link 1
195
+ ctx.beginPath();
196
+ ctx.moveTo(originX, originY);
197
+ ctx.lineTo(j1x, j1y);
198
+ ctx.lineWidth = 12;
199
+ ctx.strokeStyle = '#60a5fa'; // blue-400
200
+ ctx.lineCap = 'round';
201
+ ctx.stroke();
202
+
203
+ // Draw Link 2
204
+ ctx.beginPath();
205
+ ctx.moveTo(j1x, j1y);
206
+ ctx.lineTo(j2x, j2y);
207
+ ctx.lineWidth = 10;
208
+ ctx.strokeStyle = '#93c5fd'; // blue-300
209
+ ctx.stroke();
210
+
211
+ // Draw Joints
212
+ ctx.fillStyle = '#1e3a8a';
213
+ ctx.beginPath(); ctx.arc(originX, originY, 8, 0, Math.PI*2); ctx.fill();
214
+ ctx.beginPath(); ctx.arc(j1x, j1y, 6, 0, Math.PI*2); ctx.fill();
215
+
216
+ // Draw Claw
217
+ ctx.fillStyle = joints.value.claw > 50 ? '#ef4444' : '#10b981'; // Red=Closed, Green=Open
218
+ ctx.beginPath(); ctx.arc(j2x, j2y, 5 + (joints.value.claw/20), 0, Math.PI*2); ctx.fill();
219
+ };
220
+
221
+ const fetchStatus = async () => {
222
+ try {
223
+ const res = await fetch('/api/status');
224
+ const data = await res.json();
225
+ telemetry.value = data;
226
+ connectionStatus.value = data.connection;
227
+ updateChart(data.motor_temp);
228
+ } catch (e) {
229
+ connectionStatus.value = 'OFFLINE';
230
+ }
231
+ };
232
+
233
+ const fetchMotions = async () => {
234
+ const res = await fetch('/api/motions');
235
+ motions.value = await res.json();
236
+ };
237
+
238
+ const executeAI = async () => {
239
+ if (!aiCommand.value) return;
240
+ aiLoading.value = true;
241
+ aiExplanation.value = '';
242
+ try {
243
+ const res = await fetch('/api/analyze', {
244
+ method: 'POST',
245
+ headers: {'Content-Type': 'application/json'},
246
+ body: JSON.stringify({ command: aiCommand.value })
247
+ });
248
+ const data = await res.json();
249
+ if (data.explanation) aiExplanation.value = data.explanation;
250
+
251
+ // Animate transition? Just set for now.
252
+ joints.value = {
253
+ base: data.base ?? joints.value.base,
254
+ shoulder: data.shoulder ?? joints.value.shoulder,
255
+ elbow: data.elbow ?? joints.value.elbow,
256
+ claw: data.claw ?? joints.value.claw
257
+ };
258
+ } catch (e) {
259
+ alert('AI Execution Failed');
260
+ } finally {
261
+ aiLoading.value = false;
262
+ }
263
+ };
264
+
265
+ const saveCurrentMotion = async () => {
266
+ const name = prompt('动作名称 (Motion Name):', `Motion ${motions.value.length + 1}`);
267
+ if (!name) return;
268
+ const desc = prompt('描述 (Description):', '用户创建的动作');
269
+
270
+ await fetch('/api/motions', {
271
+ method: 'POST',
272
+ headers: {'Content-Type': 'application/json'},
273
+ body: JSON.stringify({
274
+ name,
275
+ description: desc,
276
+ joints: joints.value
277
+ })
278
+ });
279
+ fetchMotions();
280
+ };
281
+
282
+ const triggerUpload = () => {
283
+ fileInput.value.click();
284
+ };
285
+
286
+ const handleFileUpload = async (event) => {
287
+ const file = event.target.files[0];
288
+ if (!file) return;
289
+
290
+ const formData = new FormData();
291
+ formData.append('file', file);
292
+
293
+ try {
294
+ const res = await fetch('/api/upload', {
295
+ method: 'POST',
296
+ body: formData
297
+ });
298
+ const data = await res.json();
299
+ if (data.status === 'success') {
300
+ alert(`成功导入 ${data.count} 个动作`);
301
+ fetchMotions();
302
+ } else {
303
+ alert('导入失败: ' + data.error);
304
+ }
305
+ } catch (e) {
306
+ alert('导入出错');
307
+ }
308
+ // Reset file input
309
+ event.target.value = '';
310
+ };
311
+
312
+ const exportMotions = async () => {
313
+ window.open('/api/export', '_blank');
314
+ };
315
+
316
+ const loadMotion = (m) => {
317
+ const j = JSON.parse(m.joints);
318
+ joints.value = j;
319
+ };
320
+
321
+ const resetHome = () => {
322
+ joints.value = { base: 90, shoulder: 90, elbow: 90, claw: 0 };
323
+ };
324
+
325
+ // ECharts
326
+ const initChart = () => {
327
+ chartInstance = echarts.init(chartContainer.value);
328
+ chartInstance.setOption({
329
+ grid: { top: 10, bottom: 20, left: 40, right: 10 },
330
+ xAxis: { type: 'category', data: ['Base', 'Shoulder', 'Elbow', 'Claw'] },
331
+ yAxis: { type: 'value', max: 100 },
332
+ series: [{
333
+ type: 'bar',
334
+ data: [0, 0, 0, 0],
335
+ itemStyle: { color: '#3b82f6' }
336
+ }]
337
+ });
338
+ };
339
+
340
+ const updateChart = (temps) => {
341
+ if (chartInstance) {
342
+ chartInstance.setOption({
343
+ series: [{ data: temps }]
344
+ });
345
+ }
346
+ };
347
+
348
+ onMounted(() => {
349
+ initChart();
350
+ drawArm();
351
+ fetchStatus();
352
+ fetchMotions();
353
+ setInterval(fetchStatus, 3000);
354
+ });
355
+
356
+ watch(joints, () => {
357
+ drawArm();
358
+ }, { deep: true });
359
+
360
+ return {
361
+ joints, telemetry, connectionStatus, aiCommand, aiExplanation,
362
+ aiLoading, motions, sideViewCanvas, chartContainer, fileInput,
363
+ executeAI, saveCurrentMotion, loadMotion, resetHome,
364
+ triggerUpload, handleFileUpload, exportMotions
365
+ };
366
+ }
367
+ }).mount('#app');
368
+ </script>
369
+ </body>
370
+ </html>