Spaces:
Sleeping
Sleeping
Trae Assistant commited on
Commit ·
c9710d1
0
Parent(s):
Initial commit
Browse files- .gitignore +5 -0
- Dockerfile +18 -0
- README.md +34 -0
- app.py +267 -0
- requirements.txt +4 -0
- templates/index.html +407 -0
.gitignore
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
__pycache__/
|
| 2 |
+
*.pyc
|
| 3 |
+
fleet.db
|
| 4 |
+
uploads/
|
| 5 |
+
.DS_Store
|
Dockerfile
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
FROM python:3.9-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 for security (recommended for HF Spaces)
|
| 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 ["python", "app.py"]
|
README.md
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
title: Fleet Commander Agent
|
| 3 |
+
emoji: 🚁
|
| 4 |
+
colorFrom: blue
|
| 5 |
+
colorTo: indigo
|
| 6 |
+
sdk: docker
|
| 7 |
+
app_port: 7860
|
| 8 |
+
short_description: 智能机队指挥与调度系统
|
| 9 |
+
---
|
| 10 |
+
|
| 11 |
+
# 智能机队指挥官 (Fleet Commander Agent)
|
| 12 |
+
|
| 13 |
+
这是一个基于具身智能(Embodied AI)概念的机队管理 SaaS 演示项目。
|
| 14 |
+
它模拟了一个能够自主监控、调度和优化机器人/无人机机队的 AI 代理。
|
| 15 |
+
|
| 16 |
+
## 功能特点
|
| 17 |
+
|
| 18 |
+
- **实时遥测监控**: 可视化展示机队位置、电量和状态。
|
| 19 |
+
- **智能异常检测**: AI 自动识别低电量或故障设备并触发警报。
|
| 20 |
+
- **自主任务调度**: 模拟任务分配与路径规划。
|
| 21 |
+
- **移动端适配**: 响应式设计,支持手机/平板访问。
|
| 22 |
+
|
| 23 |
+
## 技术栈
|
| 24 |
+
|
| 25 |
+
- Backend: Python Flask
|
| 26 |
+
- Frontend: Vue.js 3, Tailwind CSS, ECharts
|
| 27 |
+
- Deployment: Docker
|
| 28 |
+
|
| 29 |
+
## 运行方式
|
| 30 |
+
|
| 31 |
+
```bash
|
| 32 |
+
docker build -t fleet-agent .
|
| 33 |
+
docker run -p 7860:7860 fleet-agent
|
| 34 |
+
```
|
app.py
ADDED
|
@@ -0,0 +1,267 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import time
|
| 3 |
+
import random
|
| 4 |
+
import json
|
| 5 |
+
import sqlite3
|
| 6 |
+
import threading
|
| 7 |
+
from flask import Flask, render_template, jsonify, request
|
| 8 |
+
from flask_cors import CORS
|
| 9 |
+
from openai import OpenAI
|
| 10 |
+
from werkzeug.utils import secure_filename
|
| 11 |
+
|
| 12 |
+
app = Flask(__name__)
|
| 13 |
+
CORS(app)
|
| 14 |
+
|
| 15 |
+
# 配置
|
| 16 |
+
app.config['SECRET_KEY'] = 'fleet-commander-secret'
|
| 17 |
+
app.config['UPLOAD_FOLDER'] = 'uploads'
|
| 18 |
+
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024 # 16MB limit
|
| 19 |
+
app.config['ALLOWED_EXTENSIONS'] = {'txt', 'json', 'csv', 'log', 'md'}
|
| 20 |
+
|
| 21 |
+
# SiliconFlow API Configuration
|
| 22 |
+
SILICONFLOW_API_KEY = "sk-vimuseiptfbomzegyuvmebjzooncsqbyjtlddrfodzcdskgi"
|
| 23 |
+
SILICONFLOW_BASE_URL = "https://api.siliconflow.cn/v1"
|
| 24 |
+
|
| 25 |
+
# Ensure upload directory exists
|
| 26 |
+
os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True)
|
| 27 |
+
|
| 28 |
+
# Database Setup
|
| 29 |
+
DB_PATH = 'fleet.db'
|
| 30 |
+
|
| 31 |
+
def init_db():
|
| 32 |
+
conn = sqlite3.connect(DB_PATH)
|
| 33 |
+
c = conn.cursor()
|
| 34 |
+
c.execute('''CREATE TABLE IF NOT EXISTS robots
|
| 35 |
+
(id TEXT PRIMARY KEY, type TEXT, status TEXT, battery REAL, x REAL, y REAL, load REAL)''')
|
| 36 |
+
c.execute('''CREATE TABLE IF NOT EXISTS alerts
|
| 37 |
+
(id INTEGER PRIMARY KEY AUTOINCREMENT, time TEXT, message TEXT, level TEXT)''')
|
| 38 |
+
c.execute('''CREATE TABLE IF NOT EXISTS tasks
|
| 39 |
+
(id TEXT PRIMARY KEY, bot_id TEXT, description TEXT, status TEXT)''')
|
| 40 |
+
|
| 41 |
+
# Check if robots exist, if not, initialize
|
| 42 |
+
c.execute("SELECT count(*) FROM robots")
|
| 43 |
+
if c.fetchone()[0] == 0:
|
| 44 |
+
for i in range(1, 11):
|
| 45 |
+
bot_id = f'BOT-{i:03d}'
|
| 46 |
+
bot_type = 'Drone' if i <= 5 else 'AMR'
|
| 47 |
+
c.execute("INSERT INTO robots VALUES (?, ?, ?, ?, ?, ?, ?)",
|
| 48 |
+
(bot_id, bot_type, 'idle', random.randint(60, 100), random.uniform(10, 90), random.uniform(10, 90), 0))
|
| 49 |
+
|
| 50 |
+
conn.commit()
|
| 51 |
+
conn.close()
|
| 52 |
+
|
| 53 |
+
init_db()
|
| 54 |
+
|
| 55 |
+
def get_db_connection():
|
| 56 |
+
conn = sqlite3.connect(DB_PATH)
|
| 57 |
+
conn.row_factory = sqlite3.Row
|
| 58 |
+
return conn
|
| 59 |
+
|
| 60 |
+
# Fleet State Management (Hybrid: In-memory for speed, DB for persistence)
|
| 61 |
+
class FleetState:
|
| 62 |
+
def __init__(self):
|
| 63 |
+
self.last_update = time.time()
|
| 64 |
+
self.lock = threading.Lock()
|
| 65 |
+
|
| 66 |
+
def update(self):
|
| 67 |
+
with self.lock:
|
| 68 |
+
current_time = time.time()
|
| 69 |
+
raw_dt = current_time - self.last_update
|
| 70 |
+
self.last_update = current_time
|
| 71 |
+
dt = min(raw_dt, 1.0)
|
| 72 |
+
|
| 73 |
+
conn = get_db_connection()
|
| 74 |
+
c = conn.cursor()
|
| 75 |
+
|
| 76 |
+
# Fetch all robots
|
| 77 |
+
robots = [dict(row) for row in conn.execute("SELECT * FROM robots").fetchall()]
|
| 78 |
+
|
| 79 |
+
for bot in robots:
|
| 80 |
+
# Logic (same as before)
|
| 81 |
+
if bot['status'] == 'active':
|
| 82 |
+
bot['x'] += random.uniform(-1, 1) * 10 * dt
|
| 83 |
+
bot['y'] += random.uniform(-1, 1) * 10 * dt
|
| 84 |
+
bot['x'] = max(0, min(100, bot['x']))
|
| 85 |
+
bot['y'] = max(0, min(100, bot['y']))
|
| 86 |
+
bot['battery'] -= 0.5 * dt
|
| 87 |
+
elif bot['status'] == 'idle':
|
| 88 |
+
bot['battery'] -= 0.05 * dt
|
| 89 |
+
elif bot['status'] == 'charging':
|
| 90 |
+
bot['battery'] += 5 * dt
|
| 91 |
+
|
| 92 |
+
# Mock AI Logic
|
| 93 |
+
if bot['battery'] < 20 and bot['status'] != 'charging':
|
| 94 |
+
bot['status'] = 'charging'
|
| 95 |
+
self.add_alert(conn, f"警告: {bot['id']} 电量过低,自动返回充电。", "warning")
|
| 96 |
+
elif bot['battery'] > 95 and bot['status'] == 'charging':
|
| 97 |
+
bot['status'] = 'idle'
|
| 98 |
+
self.add_alert(conn, f"通知: {bot['id']} 充电完成,等待任务。", "success")
|
| 99 |
+
|
| 100 |
+
if bot['status'] != 'error' and random.random() < 0.0005: # Reduced probability
|
| 101 |
+
bot['status'] = 'error'
|
| 102 |
+
self.add_alert(conn, f"紧急: {bot['id']} 发生传感器故障!", "error")
|
| 103 |
+
|
| 104 |
+
bot['battery'] = max(0, min(100, bot['battery']))
|
| 105 |
+
|
| 106 |
+
# Update DB
|
| 107 |
+
c.execute("UPDATE robots SET status=?, battery=?, x=?, y=? WHERE id=?",
|
| 108 |
+
(bot['status'], bot['battery'], bot['x'], bot['y'], bot['id']))
|
| 109 |
+
|
| 110 |
+
conn.commit()
|
| 111 |
+
conn.close()
|
| 112 |
+
|
| 113 |
+
def add_alert(self, conn, message, level):
|
| 114 |
+
conn.execute("INSERT INTO alerts (time, message, level) VALUES (?, ?, ?)",
|
| 115 |
+
(time.strftime('%H:%M:%S'), message, level))
|
| 116 |
+
# Keep only last 50
|
| 117 |
+
conn.execute("DELETE FROM alerts WHERE id NOT IN (SELECT id FROM alerts ORDER BY id DESC LIMIT 50)")
|
| 118 |
+
|
| 119 |
+
def assign_task(self, task_desc):
|
| 120 |
+
with self.lock:
|
| 121 |
+
conn = get_db_connection()
|
| 122 |
+
# Find idle bot
|
| 123 |
+
bot_row = conn.execute("SELECT * FROM robots WHERE status='idle' ORDER BY RANDOM() LIMIT 1").fetchone()
|
| 124 |
+
if not bot_row:
|
| 125 |
+
conn.close()
|
| 126 |
+
return False, "没有可用的空闲机器��"
|
| 127 |
+
|
| 128 |
+
bot = dict(bot_row)
|
| 129 |
+
bot_id = bot['id']
|
| 130 |
+
task_id = f'TASK-{int(time.time())}'
|
| 131 |
+
|
| 132 |
+
conn.execute("UPDATE robots SET status='active' WHERE id=?", (bot_id,))
|
| 133 |
+
conn.execute("INSERT INTO tasks (id, bot_id, description, status) VALUES (?, ?, ?, ?)",
|
| 134 |
+
(task_id, bot_id, task_desc, 'in_progress'))
|
| 135 |
+
|
| 136 |
+
self.add_alert(conn, f"任务: 已分配任务 '{task_desc}' 给 {bot_id}", "info")
|
| 137 |
+
conn.commit()
|
| 138 |
+
conn.close()
|
| 139 |
+
return True, f"任务已分配给 {bot_id}"
|
| 140 |
+
|
| 141 |
+
def fix_bot(self, bot_id):
|
| 142 |
+
with self.lock:
|
| 143 |
+
conn = get_db_connection()
|
| 144 |
+
bot = conn.execute("SELECT * FROM robots WHERE id=?", (bot_id,)).fetchone()
|
| 145 |
+
if bot and bot['status'] == 'error':
|
| 146 |
+
conn.execute("UPDATE robots SET status='idle' WHERE id=?", (bot_id,))
|
| 147 |
+
self.add_alert(conn, f"修复: {bot_id} 远程修复成功,恢复待命。", "success")
|
| 148 |
+
conn.commit()
|
| 149 |
+
conn.close()
|
| 150 |
+
return True
|
| 151 |
+
conn.close()
|
| 152 |
+
return False
|
| 153 |
+
|
| 154 |
+
fleet = FleetState()
|
| 155 |
+
|
| 156 |
+
@app.route('/')
|
| 157 |
+
def index():
|
| 158 |
+
return render_template('index.html')
|
| 159 |
+
|
| 160 |
+
@app.route('/api/telemetry')
|
| 161 |
+
def get_telemetry():
|
| 162 |
+
fleet.update()
|
| 163 |
+
conn = get_db_connection()
|
| 164 |
+
robots = [dict(row) for row in conn.execute("SELECT * FROM robots").fetchall()]
|
| 165 |
+
alerts = [dict(row) for row in conn.execute("SELECT * FROM alerts ORDER BY id DESC LIMIT 50").fetchall()]
|
| 166 |
+
conn.close()
|
| 167 |
+
|
| 168 |
+
return jsonify({
|
| 169 |
+
'robots': robots,
|
| 170 |
+
'alerts': alerts,
|
| 171 |
+
'stats': {
|
| 172 |
+
'total': len(robots),
|
| 173 |
+
'active': len([r for r in robots if r['status'] == 'active']),
|
| 174 |
+
'charging': len([r for r in robots if r['status'] == 'charging']),
|
| 175 |
+
'error': len([r for r in robots if r['status'] == 'error'])
|
| 176 |
+
}
|
| 177 |
+
})
|
| 178 |
+
|
| 179 |
+
@app.route('/api/command', methods=['POST'])
|
| 180 |
+
def send_command():
|
| 181 |
+
data = request.json
|
| 182 |
+
cmd_type = data.get('type')
|
| 183 |
+
|
| 184 |
+
if cmd_type == 'task':
|
| 185 |
+
success, msg = fleet.assign_task(data.get('description', '巡逻任务'))
|
| 186 |
+
elif cmd_type == 'fix':
|
| 187 |
+
success = fleet.fix_bot(data.get('bot_id'))
|
| 188 |
+
msg = "修复指令已发送" if success else "修复失败或机器人未故障"
|
| 189 |
+
else:
|
| 190 |
+
success = False
|
| 191 |
+
msg = "未知指令"
|
| 192 |
+
|
| 193 |
+
return jsonify({'success': success, 'message': msg})
|
| 194 |
+
|
| 195 |
+
def allowed_file(filename):
|
| 196 |
+
return '.' in filename and filename.rsplit('.', 1)[1].lower() in app.config['ALLOWED_EXTENSIONS']
|
| 197 |
+
|
| 198 |
+
@app.route('/api/upload', methods=['POST'])
|
| 199 |
+
def upload_file():
|
| 200 |
+
if 'file' not in request.files:
|
| 201 |
+
return jsonify({'success': False, 'message': '没有文件部分'})
|
| 202 |
+
file = request.files['file']
|
| 203 |
+
if file.filename == '':
|
| 204 |
+
return jsonify({'success': False, 'message': '未选择文件'})
|
| 205 |
+
if file and allowed_file(file.filename):
|
| 206 |
+
filename = secure_filename(file.filename)
|
| 207 |
+
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
|
| 208 |
+
|
| 209 |
+
# 简单解析逻辑 (如果是 mission.json,自动下发任务)
|
| 210 |
+
if filename.endswith('.json'):
|
| 211 |
+
try:
|
| 212 |
+
with open(os.path.join(app.config['UPLOAD_FOLDER'], filename), 'r') as f:
|
| 213 |
+
content = json.load(f)
|
| 214 |
+
if isinstance(content, list):
|
| 215 |
+
count = 0
|
| 216 |
+
for item in content:
|
| 217 |
+
if 'task' in item:
|
| 218 |
+
fleet.assign_task(item['task'])
|
| 219 |
+
count += 1
|
| 220 |
+
return jsonify({'success': True, 'message': f'文件上传成功,已自动解析并下发 {count} 个任务'})
|
| 221 |
+
except Exception as e:
|
| 222 |
+
return jsonify({'success': True, 'message': f'文件上传成功,但解析失败: {str(e)}'})
|
| 223 |
+
|
| 224 |
+
return jsonify({'success': True, 'message': f'文件 {filename} 上传成功'})
|
| 225 |
+
return jsonify({'success': False, 'message': '不支持的文件类型'})
|
| 226 |
+
|
| 227 |
+
@app.route('/api/chat', methods=['POST'])
|
| 228 |
+
def chat_ai():
|
| 229 |
+
data = request.json
|
| 230 |
+
user_message = data.get('message', '')
|
| 231 |
+
|
| 232 |
+
# 获取当前状态作为上下文
|
| 233 |
+
conn = get_db_connection()
|
| 234 |
+
robots = [dict(row) for row in conn.execute("SELECT * FROM robots").fetchall()]
|
| 235 |
+
conn.close()
|
| 236 |
+
|
| 237 |
+
system_prompt = f"""
|
| 238 |
+
你是一个智能机队指挥官助手。当前机队状态如下:
|
| 239 |
+
总数: {len(robots)}
|
| 240 |
+
活跃: {len([r for r in robots if r['status'] == 'active'])}
|
| 241 |
+
充电: {len([r for r in robots if r['status'] == 'charging'])}
|
| 242 |
+
故障: {len([r for r in robots if r['status'] == 'error'])}
|
| 243 |
+
|
| 244 |
+
详细列表: {json.dumps(robots[:5])} (仅显示前5个)
|
| 245 |
+
|
| 246 |
+
请根据以上信息回答用户问题。如果是下发任务的请求,请建议用户使用左侧的任务下发面板,或者告诉我你希望我如何协助。请用中文回答,简练专业。
|
| 247 |
+
"""
|
| 248 |
+
|
| 249 |
+
try:
|
| 250 |
+
client = OpenAI(api_key=SILICONFLOW_API_KEY, base_url=SILICONFLOW_BASE_URL)
|
| 251 |
+
response = client.chat.completions.create(
|
| 252 |
+
model="deepseek-ai/DeepSeek-V3", # 尝试使用 DeepSeek V3,如果不行可以换 Qwen
|
| 253 |
+
messages=[
|
| 254 |
+
{"role": "system", "content": system_prompt},
|
| 255 |
+
{"role": "user", "content": user_message}
|
| 256 |
+
],
|
| 257 |
+
stream=False
|
| 258 |
+
)
|
| 259 |
+
ai_reply = response.choices[0].message.content
|
| 260 |
+
return jsonify({'success': True, 'reply': ai_reply})
|
| 261 |
+
except Exception as e:
|
| 262 |
+
print(f"SiliconFlow API Error: {e}")
|
| 263 |
+
return jsonify({'success': False, 'reply': "抱歉,AI 通信暂时中断,请检查网络或 Key 配置。"})
|
| 264 |
+
|
| 265 |
+
if __name__ == '__main__':
|
| 266 |
+
# 确保 app.run 在主线程
|
| 267 |
+
app.run(host='0.0.0.0', port=7860, debug=False) # Hugging Face usually expects port 7860
|
requirements.txt
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
flask
|
| 2 |
+
flask-cors
|
| 3 |
+
requests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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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>智能机队指挥官 | Fleet Commander</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 |
+
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
|
| 11 |
+
<style>
|
| 12 |
+
[v-cloak] { display: none; }
|
| 13 |
+
.scrollbar-hide::-webkit-scrollbar { display: none; }
|
| 14 |
+
.scrollbar-hide { -ms-overflow-style: none; scrollbar-width: none; }
|
| 15 |
+
.chat-msg { max-width: 80%; word-wrap: break-word; }
|
| 16 |
+
</style>
|
| 17 |
+
</head>
|
| 18 |
+
<body class="bg-slate-100 text-slate-800">
|
| 19 |
+
<div id="app" v-cloak class="h-screen flex flex-col">
|
| 20 |
+
<!-- Header -->
|
| 21 |
+
<header class="bg-white shadow-sm p-4 flex justify-between items-center z-20 border-b">
|
| 22 |
+
<div class="flex items-center gap-3">
|
| 23 |
+
<div class="bg-indigo-600 text-white p-2 rounded-lg">
|
| 24 |
+
<i class="fas fa-helicopter text-xl"></i>
|
| 25 |
+
</div>
|
| 26 |
+
<div>
|
| 27 |
+
<h1 class="text-xl font-bold text-slate-800 leading-tight">智能机队指挥官</h1>
|
| 28 |
+
<div class="text-xs text-slate-500">Fleet Commander Agent <span class="bg-green-100 text-green-700 px-1 rounded ml-1">v2.0</span></div>
|
| 29 |
+
</div>
|
| 30 |
+
</div>
|
| 31 |
+
<div class="flex gap-4 text-sm text-slate-600 items-center">
|
| 32 |
+
<div class="hidden md:flex items-center gap-2 px-3 py-1 bg-slate-50 rounded-full border">
|
| 33 |
+
<div class="w-2 h-2 rounded-full bg-green-500 animate-pulse"></div>
|
| 34 |
+
<span>系统在线</span>
|
| 35 |
+
</div>
|
| 36 |
+
<div class="hidden md:block">CPU: 12%</div>
|
| 37 |
+
</div>
|
| 38 |
+
</header>
|
| 39 |
+
|
| 40 |
+
<!-- Main Content -->
|
| 41 |
+
<main class="flex-1 flex overflow-hidden flex-col md:flex-row">
|
| 42 |
+
<!-- Left: Map Area -->
|
| 43 |
+
<div class="flex-1 relative bg-slate-200 flex flex-col" id="map-container">
|
| 44 |
+
<div id="fleet-map" class="flex-1 w-full h-full min-h-[300px]"></div>
|
| 45 |
+
|
| 46 |
+
<!-- Map Overlay Stats -->
|
| 47 |
+
<div class="absolute top-4 left-4 bg-white/90 p-4 rounded-xl shadow-lg backdrop-blur-sm z-10 border border-white/50">
|
| 48 |
+
<div class="text-xs text-slate-500 mb-1 font-medium uppercase tracking-wider">活跃单位</div>
|
| 49 |
+
<div class="text-3xl font-black text-indigo-600 flex items-baseline gap-1">
|
| 50 |
+
${ stats.active }
|
| 51 |
+
<span class="text-sm font-normal text-slate-400">/ ${ stats.total }</span>
|
| 52 |
+
</div>
|
| 53 |
+
</div>
|
| 54 |
+
|
| 55 |
+
<!-- Alert Overlay (Bottom Left) -->
|
| 56 |
+
<div class="absolute bottom-4 left-4 right-4 md:right-auto md:w-96 max-h-48 overflow-y-auto bg-black/70 text-white p-3 rounded-lg shadow-lg z-10 backdrop-blur-md text-xs font-mono">
|
| 57 |
+
<div v-for="(alert, i) in alerts.slice(0, 5)" :key="i" class="mb-1.5 flex gap-2">
|
| 58 |
+
<span class="opacity-50 text-cyan-400">[${ alert.time }]</span>
|
| 59 |
+
<span :class="{'text-red-400': alert.level==='error', 'text-yellow-400': alert.level==='warning', 'text-green-400': alert.level==='success'}">
|
| 60 |
+
${ alert.message }
|
| 61 |
+
</span>
|
| 62 |
+
</div>
|
| 63 |
+
<div v-if="alerts.length === 0" class="opacity-50 italic">暂无警报数据...</div>
|
| 64 |
+
</div>
|
| 65 |
+
</div>
|
| 66 |
+
|
| 67 |
+
<!-- Right: Sidebar Control Panel -->
|
| 68 |
+
<aside class="w-full md:w-[400px] bg-white shadow-2xl z-20 flex flex-col border-l border-slate-200 h-[60%] md:h-auto">
|
| 69 |
+
<!-- Tabs -->
|
| 70 |
+
<div class="flex border-b text-sm font-medium">
|
| 71 |
+
<button @click="currentTab = 'control'" :class="{'text-indigo-600 border-b-2 border-indigo-600 bg-indigo-50': currentTab === 'control'}" class="flex-1 py-3 hover:bg-slate-50 transition-colors">
|
| 72 |
+
<i class="fas fa-gamepad mr-1"></i> 控制
|
| 73 |
+
</button>
|
| 74 |
+
<button @click="currentTab = 'fleet'" :class="{'text-indigo-600 border-b-2 border-indigo-600 bg-indigo-50': currentTab === 'fleet'}" class="flex-1 py-3 hover:bg-slate-50 transition-colors">
|
| 75 |
+
<i class="fas fa-robot mr-1"></i> 机队
|
| 76 |
+
</button>
|
| 77 |
+
<button @click="currentTab = 'ai'" :class="{'text-indigo-600 border-b-2 border-indigo-600 bg-indigo-50': currentTab === 'ai'}" class="flex-1 py-3 hover:bg-slate-50 transition-colors">
|
| 78 |
+
<i class="fas fa-brain mr-1"></i> AI 助手
|
| 79 |
+
</button>
|
| 80 |
+
</div>
|
| 81 |
+
|
| 82 |
+
<!-- Content Area -->
|
| 83 |
+
<div class="flex-1 overflow-hidden relative bg-slate-50">
|
| 84 |
+
|
| 85 |
+
<!-- Tab: Control -->
|
| 86 |
+
<div v-if="currentTab === 'control'" class="h-full overflow-y-auto p-4 space-y-4">
|
| 87 |
+
<!-- Quick Stats -->
|
| 88 |
+
<div class="grid grid-cols-3 gap-3">
|
| 89 |
+
<div class="bg-white p-3 rounded-lg shadow-sm border border-slate-100 text-center">
|
| 90 |
+
<div class="text-xs text-slate-500">总数</div>
|
| 91 |
+
<div class="text-xl font-bold text-slate-700">${ stats.total }</div>
|
| 92 |
+
</div>
|
| 93 |
+
<div class="bg-white p-3 rounded-lg shadow-sm border border-slate-100 text-center">
|
| 94 |
+
<div class="text-xs text-green-600">充电中</div>
|
| 95 |
+
<div class="text-xl font-bold text-green-600">${ stats.charging }</div>
|
| 96 |
+
</div>
|
| 97 |
+
<div class="bg-white p-3 rounded-lg shadow-sm border border-slate-100 text-center">
|
| 98 |
+
<div class="text-xs text-red-600">故障</div>
|
| 99 |
+
<div class="text-xl font-bold text-red-600">${ stats.error }</div>
|
| 100 |
+
</div>
|
| 101 |
+
</div>
|
| 102 |
+
|
| 103 |
+
<!-- Manual Task -->
|
| 104 |
+
<div class="bg-white p-4 rounded-lg shadow-sm border border-slate-200">
|
| 105 |
+
<h3 class="text-sm font-bold mb-3 text-slate-700 flex items-center gap-2">
|
| 106 |
+
<i class="fas fa-tasks text-indigo-500"></i> 手动任务
|
| 107 |
+
</h3>
|
| 108 |
+
<div class="flex gap-2">
|
| 109 |
+
<input v-model="newTask" @keyup.enter="assignTask" type="text" placeholder="输入任务指令 (如: 巡逻 A 区)" class="flex-1 border rounded-md px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-indigo-500">
|
| 110 |
+
<button @click="assignTask" class="bg-indigo-600 text-white px-4 py-2 rounded-md text-sm hover:bg-indigo-700 transition-colors">
|
| 111 |
+
<i class="fas fa-paper-plane"></i>
|
| 112 |
+
</button>
|
| 113 |
+
</div>
|
| 114 |
+
</div>
|
| 115 |
+
|
| 116 |
+
<!-- File Upload -->
|
| 117 |
+
<div class="bg-white p-4 rounded-lg shadow-sm border border-slate-200">
|
| 118 |
+
<h3 class="text-sm font-bold mb-3 text-slate-700 flex items-center gap-2">
|
| 119 |
+
<i class="fas fa-file-upload text-indigo-500"></i> 任务文件上传
|
| 120 |
+
</h3>
|
| 121 |
+
<div class="border-2 border-dashed border-slate-300 rounded-lg p-4 text-center hover:bg-slate-50 transition-colors cursor-pointer relative">
|
| 122 |
+
<input type="file" @change="handleFileUpload" class="absolute inset-0 opacity-0 cursor-pointer">
|
| 123 |
+
<div v-if="!uploading">
|
| 124 |
+
<i class="fas fa-cloud-upload-alt text-2xl text-slate-400 mb-2"></i>
|
| 125 |
+
<p class="text-xs text-slate-500">点击或拖拽上传 JSON/TXT 任务文件</p>
|
| 126 |
+
</div>
|
| 127 |
+
<div v-else class="text-indigo-600">
|
| 128 |
+
<i class="fas fa-spinner fa-spin"></i> 上传解析中...
|
| 129 |
+
</div>
|
| 130 |
+
</div>
|
| 131 |
+
</div>
|
| 132 |
+
</div>
|
| 133 |
+
|
| 134 |
+
<!-- Tab: Fleet -->
|
| 135 |
+
<div v-if="currentTab === 'fleet'" class="h-full overflow-y-auto p-4 space-y-2">
|
| 136 |
+
<div v-for="bot in robots" :key="bot.id" class="bg-white p-3 rounded-lg shadow-sm border border-slate-200 flex items-center justify-between hover:shadow-md transition-shadow">
|
| 137 |
+
<div>
|
| 138 |
+
<div class="flex items-center gap-2 mb-1">
|
| 139 |
+
<span class="font-bold text-sm text-slate-700">${ bot.id }</span>
|
| 140 |
+
<span class="text-[10px] px-1.5 py-0.5 rounded-full bg-slate-100 text-slate-500 border">${ bot.type }</span>
|
| 141 |
+
</div>
|
| 142 |
+
<div class="flex items-center gap-3 text-xs text-slate-500">
|
| 143 |
+
<span :class="{'text-green-500': bot.battery > 20, 'text-red-500': bot.battery <= 20}">
|
| 144 |
+
<i class="fas fa-battery-three-quarters"></i> ${ Math.round(bot.battery) }%
|
| 145 |
+
</span>
|
| 146 |
+
<span class="flex items-center gap-1">
|
| 147 |
+
<div class="w-1.5 h-1.5 rounded-full" :class="getStatusColorBg(bot.status)"></div>
|
| 148 |
+
${ getStatusText(bot.status) }
|
| 149 |
+
</span>
|
| 150 |
+
</div>
|
| 151 |
+
</div>
|
| 152 |
+
<button v-if="bot.status === 'error'" @click="fixBot(bot.id)" class="bg-red-50 text-red-600 border border-red-200 text-xs px-3 py-1.5 rounded-md hover:bg-red-100 transition-colors">
|
| 153 |
+
<i class="fas fa-wrench mr-1"></i> 修复
|
| 154 |
+
</button>
|
| 155 |
+
</div>
|
| 156 |
+
</div>
|
| 157 |
+
|
| 158 |
+
<!-- Tab: AI Assistant -->
|
| 159 |
+
<div v-if="currentTab === 'ai'" class="h-full flex flex-col bg-white">
|
| 160 |
+
<div class="flex-1 overflow-y-auto p-4 space-y-3 bg-slate-50" ref="chatContainer">
|
| 161 |
+
<div v-for="(msg, i) in chatHistory" :key="i" class="flex" :class="msg.role === 'user' ? 'justify-end' : 'justify-start'">
|
| 162 |
+
<div class="chat-msg p-3 rounded-lg text-sm shadow-sm"
|
| 163 |
+
:class="msg.role === 'user' ? 'bg-indigo-600 text-white rounded-br-none' : 'bg-white border border-slate-200 text-slate-700 rounded-bl-none'">
|
| 164 |
+
<div v-if="msg.role === 'assistant'" class="text-xs text-indigo-500 font-bold mb-1 flex items-center gap-1">
|
| 165 |
+
<i class="fas fa-robot"></i> 指挥官助手
|
| 166 |
+
</div>
|
| 167 |
+
<div class="whitespace-pre-wrap">${ msg.content }</div>
|
| 168 |
+
</div>
|
| 169 |
+
</div>
|
| 170 |
+
<div v-if="isThinking" class="flex justify-start">
|
| 171 |
+
<div class="chat-msg p-3 rounded-lg text-sm bg-white border border-slate-200 text-slate-500 rounded-bl-none">
|
| 172 |
+
<i class="fas fa-circle-notch fa-spin mr-1"></i> 思考中...
|
| 173 |
+
</div>
|
| 174 |
+
</div>
|
| 175 |
+
</div>
|
| 176 |
+
<div class="p-3 border-t bg-white">
|
| 177 |
+
<div class="flex gap-2">
|
| 178 |
+
<input v-model="chatInput" @keyup.enter="sendChat" type="text" placeholder="询问机队状态或寻求建议..." class="flex-1 border rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-indigo-500 bg-slate-50">
|
| 179 |
+
<button @click="sendChat" :disabled="isThinking" class="bg-indigo-600 text-white px-4 py-2 rounded-lg text-sm hover:bg-indigo-700 transition-colors disabled:opacity-50">
|
| 180 |
+
<i class="fas fa-paper-plane"></i>
|
| 181 |
+
</button>
|
| 182 |
+
</div>
|
| 183 |
+
</div>
|
| 184 |
+
</div>
|
| 185 |
+
|
| 186 |
+
</div>
|
| 187 |
+
</aside>
|
| 188 |
+
</main>
|
| 189 |
+
</div>
|
| 190 |
+
|
| 191 |
+
<script>
|
| 192 |
+
const { createApp, ref, onMounted, nextTick, watch } = Vue;
|
| 193 |
+
|
| 194 |
+
createApp({
|
| 195 |
+
delimiters: ['${', '}'],
|
| 196 |
+
setup() {
|
| 197 |
+
const robots = ref([]);
|
| 198 |
+
const alerts = ref([]);
|
| 199 |
+
const stats = ref({ total: 0, active: 0, charging: 0, error: 0 });
|
| 200 |
+
const newTask = ref('');
|
| 201 |
+
const currentTab = ref('control');
|
| 202 |
+
const chatInput = ref('');
|
| 203 |
+
const chatHistory = ref([
|
| 204 |
+
{ role: 'assistant', content: '指挥官您好!我是您的智能机队助手。您可以询问我关于机队状态的问题,或者让我协助分析异常。' }
|
| 205 |
+
]);
|
| 206 |
+
const isThinking = ref(false);
|
| 207 |
+
const uploading = ref(false);
|
| 208 |
+
const chatContainer = ref(null);
|
| 209 |
+
|
| 210 |
+
let mapChart = null;
|
| 211 |
+
|
| 212 |
+
// --- Map Logic ---
|
| 213 |
+
const initMap = () => {
|
| 214 |
+
const el = document.getElementById('fleet-map');
|
| 215 |
+
if (!el) return;
|
| 216 |
+
mapChart = echarts.init(el);
|
| 217 |
+
const option = {
|
| 218 |
+
backgroundColor: 'transparent',
|
| 219 |
+
tooltip: {
|
| 220 |
+
trigger: 'item',
|
| 221 |
+
formatter: (params) => {
|
| 222 |
+
const bot = params.data.bot;
|
| 223 |
+
return `
|
| 224 |
+
<div class="font-bold">${bot.id}</div>
|
| 225 |
+
<div>状态: ${getStatusText(bot.status)}</div>
|
| 226 |
+
<div>电量: ${Math.round(bot.battery)}%</div>
|
| 227 |
+
<div>坐标: (${Math.round(bot.x)}, ${Math.round(bot.y)})</div>
|
| 228 |
+
`;
|
| 229 |
+
}
|
| 230 |
+
},
|
| 231 |
+
grid: { top: 20, bottom: 20, left: 20, right: 20 },
|
| 232 |
+
xAxis: { min: 0, max: 100, show: false },
|
| 233 |
+
yAxis: { min: 0, max: 100, show: false },
|
| 234 |
+
series: [{
|
| 235 |
+
type: 'scatter',
|
| 236 |
+
symbolSize: 30,
|
| 237 |
+
data: [],
|
| 238 |
+
itemStyle: {
|
| 239 |
+
color: (params) => {
|
| 240 |
+
const status = params.data.status;
|
| 241 |
+
if (status === 'error') return '#ef4444';
|
| 242 |
+
if (status === 'charging') return '#22c55e';
|
| 243 |
+
if (status === 'active') return '#4f46e5';
|
| 244 |
+
return '#94a3b8';
|
| 245 |
+
},
|
| 246 |
+
shadowBlur: 10,
|
| 247 |
+
shadowColor: 'rgba(0,0,0,0.2)'
|
| 248 |
+
},
|
| 249 |
+
label: {
|
| 250 |
+
show: true,
|
| 251 |
+
formatter: '{b}',
|
| 252 |
+
position: 'top',
|
| 253 |
+
color: '#333',
|
| 254 |
+
fontSize: 11,
|
| 255 |
+
fontWeight: 'bold'
|
| 256 |
+
}
|
| 257 |
+
}]
|
| 258 |
+
};
|
| 259 |
+
mapChart.setOption(option);
|
| 260 |
+
window.addEventListener('resize', () => mapChart.resize());
|
| 261 |
+
};
|
| 262 |
+
|
| 263 |
+
const updateMap = () => {
|
| 264 |
+
if (!mapChart) return;
|
| 265 |
+
const data = robots.value.map(bot => ({
|
| 266 |
+
name: bot.id,
|
| 267 |
+
value: [bot.x, bot.y],
|
| 268 |
+
status: bot.status,
|
| 269 |
+
bot: bot
|
| 270 |
+
}));
|
| 271 |
+
mapChart.setOption({
|
| 272 |
+
series: [{ data }]
|
| 273 |
+
});
|
| 274 |
+
};
|
| 275 |
+
|
| 276 |
+
// --- API Logic ---
|
| 277 |
+
const fetchTelemetry = async () => {
|
| 278 |
+
try {
|
| 279 |
+
const res = await fetch('/api/telemetry');
|
| 280 |
+
const data = await res.json();
|
| 281 |
+
robots.value = data.robots;
|
| 282 |
+
alerts.value = data.alerts;
|
| 283 |
+
stats.value = data.stats;
|
| 284 |
+
updateMap();
|
| 285 |
+
} catch (e) {
|
| 286 |
+
console.error("Telemetry error:", e);
|
| 287 |
+
}
|
| 288 |
+
};
|
| 289 |
+
|
| 290 |
+
const assignTask = async () => {
|
| 291 |
+
if (!newTask.value) return;
|
| 292 |
+
try {
|
| 293 |
+
await fetch('/api/command', {
|
| 294 |
+
method: 'POST',
|
| 295 |
+
headers: { 'Content-Type': 'application/json' },
|
| 296 |
+
body: JSON.stringify({ type: 'task', description: newTask.value })
|
| 297 |
+
});
|
| 298 |
+
newTask.value = '';
|
| 299 |
+
fetchTelemetry();
|
| 300 |
+
} catch (e) {
|
| 301 |
+
alert("任务下发失败: " + e.message);
|
| 302 |
+
}
|
| 303 |
+
};
|
| 304 |
+
|
| 305 |
+
const fixBot = async (botId) => {
|
| 306 |
+
try {
|
| 307 |
+
await fetch('/api/command', {
|
| 308 |
+
method: 'POST',
|
| 309 |
+
headers: { 'Content-Type': 'application/json' },
|
| 310 |
+
body: JSON.stringify({ type: 'fix', bot_id: botId })
|
| 311 |
+
});
|
| 312 |
+
fetchTelemetry();
|
| 313 |
+
} catch (e) {
|
| 314 |
+
alert("修复指令失败: " + e.message);
|
| 315 |
+
}
|
| 316 |
+
};
|
| 317 |
+
|
| 318 |
+
const handleFileUpload = async (event) => {
|
| 319 |
+
const file = event.target.files[0];
|
| 320 |
+
if (!file) return;
|
| 321 |
+
|
| 322 |
+
uploading.value = true;
|
| 323 |
+
const formData = new FormData();
|
| 324 |
+
formData.append('file', file);
|
| 325 |
+
|
| 326 |
+
try {
|
| 327 |
+
const res = await fetch('/api/upload', {
|
| 328 |
+
method: 'POST',
|
| 329 |
+
body: formData
|
| 330 |
+
});
|
| 331 |
+
const data = await res.json();
|
| 332 |
+
alert(data.message);
|
| 333 |
+
} catch (e) {
|
| 334 |
+
alert("上传失败: " + e.message);
|
| 335 |
+
} finally {
|
| 336 |
+
uploading.value = false;
|
| 337 |
+
event.target.value = ''; // Reset input
|
| 338 |
+
}
|
| 339 |
+
};
|
| 340 |
+
|
| 341 |
+
const sendChat = async () => {
|
| 342 |
+
if (!chatInput.value.trim() || isThinking.value) return;
|
| 343 |
+
|
| 344 |
+
const msg = chatInput.value;
|
| 345 |
+
chatHistory.value.push({ role: 'user', content: msg });
|
| 346 |
+
chatInput.value = '';
|
| 347 |
+
isThinking.value = true;
|
| 348 |
+
scrollToBottom();
|
| 349 |
+
|
| 350 |
+
try {
|
| 351 |
+
const res = await fetch('/api/chat', {
|
| 352 |
+
method: 'POST',
|
| 353 |
+
headers: { 'Content-Type': 'application/json' },
|
| 354 |
+
body: JSON.stringify({ message: msg })
|
| 355 |
+
});
|
| 356 |
+
const data = await res.json();
|
| 357 |
+
if (data.success) {
|
| 358 |
+
chatHistory.value.push({ role: 'assistant', content: data.reply });
|
| 359 |
+
} else {
|
| 360 |
+
chatHistory.value.push({ role: 'assistant', content: "API 错误: " + data.reply });
|
| 361 |
+
}
|
| 362 |
+
} catch (e) {
|
| 363 |
+
chatHistory.value.push({ role: 'assistant', content: "网络错误,请稍后再试。" });
|
| 364 |
+
} finally {
|
| 365 |
+
isThinking.value = false;
|
| 366 |
+
scrollToBottom();
|
| 367 |
+
}
|
| 368 |
+
};
|
| 369 |
+
|
| 370 |
+
const scrollToBottom = () => {
|
| 371 |
+
nextTick(() => {
|
| 372 |
+
if (chatContainer.value) {
|
| 373 |
+
chatContainer.value.scrollTop = chatContainer.value.scrollHeight;
|
| 374 |
+
}
|
| 375 |
+
});
|
| 376 |
+
};
|
| 377 |
+
|
| 378 |
+
// --- Helpers ---
|
| 379 |
+
const getStatusText = (status) => {
|
| 380 |
+
const map = { 'idle': '待命', 'active': '任务中', 'charging': '充电中', 'error': '故障' };
|
| 381 |
+
return map[status] || status;
|
| 382 |
+
};
|
| 383 |
+
|
| 384 |
+
const getStatusColorBg = (status) => {
|
| 385 |
+
if (status === 'error') return 'bg-red-500';
|
| 386 |
+
if (status === 'charging') return 'bg-green-500';
|
| 387 |
+
if (status === 'active') return 'bg-indigo-500';
|
| 388 |
+
return 'bg-slate-400';
|
| 389 |
+
};
|
| 390 |
+
|
| 391 |
+
onMounted(() => {
|
| 392 |
+
initMap();
|
| 393 |
+
fetchTelemetry();
|
| 394 |
+
setInterval(fetchTelemetry, 1000); // Poll every second
|
| 395 |
+
});
|
| 396 |
+
|
| 397 |
+
return {
|
| 398 |
+
robots, alerts, stats, newTask, currentTab,
|
| 399 |
+
chatInput, chatHistory, isThinking, uploading, chatContainer,
|
| 400 |
+
assignTask, fixBot, handleFileUpload, sendChat,
|
| 401 |
+
getStatusText, getStatusColorBg
|
| 402 |
+
};
|
| 403 |
+
}
|
| 404 |
+
}).mount('#app');
|
| 405 |
+
</script>
|
| 406 |
+
</body>
|
| 407 |
+
</html>
|