[feat] download logic can work!

This commit is contained in:
Gary 2025-12-09 20:31:50 +08:00
parent cd2efb5dfd
commit 5af12dc168
4 changed files with 361 additions and 7 deletions

1
.gitignore vendored
View file

@ -171,6 +171,7 @@ main/manager-api/.vscode
# Ignore webpack cache directory
main/manager-web/.webpack_cache/
main/xiaozhi-server/mysql
main/xiaozhi-server/assets_fw
uploadfile
*.json
.vscode

View file

@ -116,10 +116,10 @@
<div class="result-item">生成时间: {{ generationTime }}</div>
</div>
<div class="action-buttons column">
<el-button type="primary" @click="downloadFile" :disabled="!generatedBlob" class="action-btn">
<el-button type="primary" @click="downloadFile" :disabled="!generatedBlob" class="action-btn full">
下载 assets.bin
</el-button>
<el-button @click="startOnlineFlash" :disabled="!generatedBlob" class="action-btn secondary">
<el-button type="primary" plain @click="startOnlineFlash" :disabled="!generatedBlob" class="action-btn secondary full">
在线烧录到设备
</el-button>
</div>
@ -142,6 +142,7 @@
</template>
<script>
import Api from '@/apis/api';
// 延迟导入 AssetsBuilder,避免组件加载时出错
let AssetsBuilder = null;
const loadAssetsBuilder = async () => {
@ -163,6 +164,14 @@ export default {
type: Boolean,
default: false
},
device: {
type: Object,
default: null
},
agentId: {
type: [String, Number],
default: ''
},
config: {
type: Object,
default: () => ({
@ -525,13 +534,290 @@ export default {
document.body.removeChild(a);
URL.revokeObjectURL(url);
},
startOnlineFlash() {
// 占位实现:只提示,后续按需求接入真正烧录流程
async startOnlineFlash() {
if (!this.generatedBlob) {
this.$message.error('请先生成文件');
return;
}
this.$message.info('在线烧录功能待接入设备联调');
const online = await this.checkDeviceOnline();
if (!online) return;
try {
// 先上传 assets.bin 到 8003
const downloadUrl = await this.uploadAssetsBin();
await this.sendSetDownloadUrl(downloadUrl);
await this.sendRebootCommand();
this.$message.success('下载URL已下发,重启命令已发送');
} catch (e) {
console.error('[Flash] 烧录流程失败', e);
this.$message.error('烧录流程失败: ' + (e.message || e));
}
},
async uploadAssetsBin() {
if (!this.generatedBlob) throw new Error('没有生成好的 assets.bin');
const url = `${window.location.protocol}//${window.location.hostname}:8003/xiaozhi/trans/upload`;
const form = new FormData();
form.append('file', this.generatedBlob, 'assets.bin');
const res = await fetch(url, { method: 'POST', body: form });
if (!res.ok) {
throw new Error(`上传失败 HTTP ${res.status}`);
}
return `${window.location.protocol}//${window.location.hostname}:8003/xiaozhi/trans/assets.bin`;
},
buildClientId(device) {
const mac = (device && device.macAddress) ? device.macAddress : '';
const model = (device && device.model) ? device.model : 'esp32';
const macUnderscore = mac.replace(/:/g, '_');
return `${model}@@@${macUnderscore}@@@${macUnderscore}`;
},
getGatewayBaseCandidates() {
const params = new URLSearchParams(window.location.search || '');
const override = params.get('mqttGatewayUrl');
const bases = [];
if (override) bases.push(override.replace(/\/$/, ''));
bases.push(`${window.location.protocol}//${window.location.hostname}:8007`); // 与脚本一致
bases.push(window.location.origin); // 若有同源反代可避开 CORS
return bases;
},
computeToken(dateStr, key) {
return crypto.subtle && window.TextEncoder
? null // will handle async in list builder
: btoa(dateStr + key).slice(0, 64);
},
async buildSha256(content) {
const buf = await window.crypto.subtle.digest('SHA-256', new TextEncoder().encode(content));
return Array.from(new Uint8Array(buf)).map(b => b.toString(16).padStart(2, '0')).join('');
},
async getGatewayTokensList() {
const params = new URLSearchParams(window.location.search || '');
// 多渠道覆盖 token,优先已算好的值,避免浏览器计算差异
const tokenFromUrl = params.get('mqttToken') || params.get('token');
const list = [];
if (tokenFromUrl) list.push(tokenFromUrl);
const tokenFromLS = typeof localStorage !== 'undefined' ? localStorage.getItem('mqttToken') : '';
if (tokenFromLS) list.push(tokenFromLS);
if (window.__MQTT_TOKEN__) list.push(window.__MQTT_TOKEN__);
const key =
params.get('mqttKey') ||
window.__MQTT_SIGNATURE_KEY__ ||
process.env.VUE_APP_MQTT_SIGNATURE_KEY ||
'Jiangli.2014';
const dateOverride =
params.get('mqttDate') ||
params.get('date') ||
window.__MQTT_DATE__;
const dates = [];
const makeDateStr = (d) => {
const y = d.getFullYear();
const m = String(d.getMonth() + 1).padStart(2, '0');
const day = String(d.getDate()).padStart(2, '0');
return `${y}-${m}-${day}`;
};
if (dateOverride) {
dates.push(dateOverride);
} else {
const today = new Date();
const yesterday = new Date(Date.now() - 24 * 60 * 60 * 1000);
const tomorrow = new Date(Date.now() + 24 * 60 * 60 * 1000);
dates.push(makeDateStr(today), makeDateStr(yesterday), makeDateStr(tomorrow));
}
for (const ds of dates) {
if (window.crypto && window.crypto.subtle && window.TextEncoder) {
list.push(await this.buildSha256(ds + key));
} else {
list.push(btoa(ds + key).slice(0, 64));
}
}
// 去重
return Array.from(new Set(list)).filter(Boolean);
},
async checkDeviceOnline() {
const dev = this.device || (this.$parent && this.$parent.selectedDeviceForTheme);
if (!dev) {
console.warn('[Flash] 无设备信息,无法查询在线状态');
this.$message.error('缺少设备信息,无法查询在线状态');
return false;
}
const agentId = this.agentId || (this.$route && this.$route.query && this.$route.query.agentId) || '';
if (!agentId) {
this.$message.error('缺少 agentId,无法查询在线状态');
console.warn('[Flash] 缺少 agentId');
return false;
}
const clientId = this.buildClientId(dev);
try {
const data = await new Promise((resolve, reject) => {
Api.device.getDeviceStatus(agentId, ({ data }) => resolve(data), reject);
});
if (data.code === 0) {
const statusData = JSON.parse(data.data || '{}');
const status = statusData[clientId];
let isOnline = false;
if (status) {
if (status.isAlive === true) isOnline = true;
else if (status.isAlive === false) isOnline = false;
else if (status.isAlive === null && status.exists === true) isOnline = true;
}
this.deviceOnline = isOnline;
dev.deviceStatus = isOnline ? 'online' : 'offline';
console.log('[Flash] 设备在线查询(同设备管理接口)', { agentId, clientId, status, online: isOnline });
if (isOnline) {
this.$message.success('设备在线,可以开始烧录');
} else {
this.$message.error('设备不在线,无法烧录');
}
return isOnline;
}
this.$message.error(data.msg || '查询设备在线状态失败');
console.error('[Flash] 查询设备在线失败', data);
} catch (e) {
console.error('[Flash] 查询设备在线失败', e);
this.$message.error('查询设备在线状态失败');
}
return false;
},
buildDownloadUrl() {
const params = new URLSearchParams(window.location.search || '');
return params.get('downloadUrl') ||
`${window.location.protocol}//${window.location.hostname}:8003/xiaozhi/trans/assets.bin`;
},
async sendSetDownloadUrl(downloadUrl) {
const dev = this.device || (this.$parent && this.$parent.selectedDeviceForTheme);
const clientId = this.buildClientId(dev);
const topic = `devices/p2p/${clientId.split('@@@')[1]}`;
const tokens = await this.getGatewayTokensList();
const params = new URLSearchParams(window.location.search || '');
const override = params.get('mqttGatewayUrl') || params.get('gateway');
const useGatewayOnly = params.get('useGatewayOnly') !== 'false'; // 默认只尝试网关
const bases = [];
if (override) bases.push(override.replace(/\/$/, ''));
bases.push(`${window.location.protocol}//${window.location.hostname}:8007`); // 脚本默认
if (!useGatewayOnly) bases.push(window.location.origin); // 显式允许再试同源
const payload = {
type: 'mcp',
payload: {
jsonrpc: '2.0',
method: 'tools/call',
id: Date.now(),
params: {
name: 'self.assets.set_download_url',
arguments: { url: downloadUrl }
}
}
};
let lastErr = '';
for (const base of bases) {
try {
// 先尝试 Bearer,再尝试裸 Authorization,避免自定义 token 头触发 CORS 拒绝
let ok = false;
for (const token of tokens) {
const headerVariants = [
{ Authorization: `Bearer ${token}` },
{ Authorization: token }
];
for (const headers of headerVariants) {
const res = await fetch(`${base}/api/messages/publish`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
...headers
},
body: JSON.stringify({
topic,
clientId,
message: JSON.stringify(payload),
qos: 1
})
});
if (res.ok || res.type === 'opaque') {
ok = true;
break;
}
lastErr = `HTTP ${res.status}`;
}
if (ok) break;
}
if (ok) {
console.log('[Flash] set_download_url 下发成功', { base, topic, clientId, downloadUrl });
return;
}
} catch (e) {
lastErr = e.message || String(e);
}
}
throw new Error('下发下载URL失败: ' + lastErr);
},
async sendRebootCommand() {
const dev = this.device || (this.$parent && this.$parent.selectedDeviceForTheme);
const clientId = this.buildClientId(dev);
const topic = `devices/p2p/${clientId.split('@@@')[1]}`;
const tokens = await this.getGatewayTokensList();
const params = new URLSearchParams(window.location.search || '');
const override = params.get('mqttGatewayUrl') || params.get('gateway');
const useGatewayOnly = params.get('useGatewayOnly') !== 'false';
const bases = [];
if (override) bases.push(override.replace(/\/$/, ''));
bases.push(`${window.location.protocol}//${window.location.hostname}:8007`);
if (!useGatewayOnly) bases.push(window.location.origin);
const payload = {
type: 'mcp',
payload: {
jsonrpc: '2.0',
method: 'tools/call',
id: Date.now(),
params: {
name: 'self.reboot',
arguments: {}
}
}
};
let lastErr = '';
for (const base of bases) {
try {
let ok = false;
for (const token of tokens) {
const headerVariants = [
{ Authorization: `Bearer ${token}` },
{ Authorization: token }
];
for (const headers of headerVariants) {
const res = await fetch(`${base}/api/messages/publish`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
...headers
},
body: JSON.stringify({
topic,
clientId,
message: JSON.stringify(payload),
qos: 1
})
});
if (res.ok || res.type === 'opaque') {
ok = true;
break;
}
lastErr = `HTTP ${res.status}`;
}
if (ok) break;
}
if (ok) {
console.log('[Flash] reboot 下发成功', { base, topic, clientId });
return;
}
} catch (e) {
lastErr = e.message || String(e);
}
}
throw new Error('下发重启失败: ' + lastErr);
}
}
};
@ -749,10 +1035,11 @@ export default {
align-items: stretch;
}
.action-btn {
.action-btn.full {
width: 100%;
height: 40px;
font-size: 14px;
justify-content: center;
}
.action-btn.secondary {

View file

@ -135,6 +135,8 @@
:is="generateModalComponent"
:visible.sync="showGenerateModal"
:config="generateConfig"
:device="selectedDeviceForTheme"
:agent-id="currentAgentId"
/>
</div>

View file

@ -1,4 +1,5 @@
import asyncio
from pathlib import Path
from aiohttp import web
from config.logger import setup_logging
from core.api.ota_handler import OTAHandler
@ -13,6 +14,10 @@ class SimpleHttpServer:
self.logger = setup_logging()
self.ota_handler = OTAHandler(config)
self.vision_handler = VisionHandler(config)
# assets.bin 存放目录(默认放在项目 assets_fw 下)
base_dir = Path(__file__).resolve().parents[1]
self.assets_dir = base_dir / "assets_fw"
self.assets_file = self.assets_dir / "assets.bin"
def _get_websocket_url(self, local_ip: str, port: int) -> str:
"""获取websocket地址
@ -39,7 +44,7 @@ class SimpleHttpServer:
port = int(server_config.get("http_port", 8003))
if port:
app = web.Application()
app = web.Application(middlewares=[self.cors_middleware])
if not read_config_from_api:
# 如果没有开启智控台,只是单模块运行,就需要再添加简单OTA接口,用于下发websocket接口
@ -56,6 +61,10 @@ class SimpleHttpServer:
web.get("/mcp/vision/explain", self.vision_handler.handle_get),
web.post("/mcp/vision/explain", self.vision_handler.handle_post),
web.options("/mcp/vision/explain", self.vision_handler.handle_post),
# assets.bin 下载/上传
web.get("/xiaozhi/trans/assets.bin", self.handle_assets_download),
web.post("/xiaozhi/trans/upload", self.handle_assets_upload),
web.options("/xiaozhi/trans/upload", self.handle_assets_upload),
]
)
@ -68,3 +77,58 @@ class SimpleHttpServer:
# 保持服务运行
while True:
await asyncio.sleep(3600) # 每隔 1 小时检查一次
@web.middleware
async def cors_middleware(self, request, handler):
"""简单 CORS 处理,允许前端 8001 访问"""
allowed_origin = f"http://{request.host.split(':')[0]}:8001"
try:
resp = await handler(request)
except web.HTTPException as ex:
resp = ex
if isinstance(resp, web.StreamResponse):
resp.headers["Access-Control-Allow-Origin"] = allowed_origin
resp.headers["Access-Control-Allow-Methods"] = "GET,POST,OPTIONS"
resp.headers["Access-Control-Allow-Headers"] = "Content-Type, Authorization"
return resp
async def handle_assets_download(self, request: web.Request) -> web.StreamResponse:
"""提供 assets.bin 下载"""
self.assets_dir.mkdir(parents=True, exist_ok=True)
if not self.assets_file.exists():
return web.Response(status=404, text="assets.bin not found")
return web.FileResponse(path=self.assets_file)
async def handle_assets_upload(self, request: web.Request) -> web.Response:
"""接收上传的 assets.bin 并保存到本地"""
if request.method == "OPTIONS":
return web.Response(status=200)
self.assets_dir.mkdir(parents=True, exist_ok=True)
# 每次上传前先删除旧的,确保是最新文件
if self.assets_file.exists():
try:
self.assets_file.unlink()
except Exception:
# 忽略删除异常,继续后续写入
pass
reader = await request.multipart()
field = await reader.next()
if not field or field.name not in ("file", "asset", "upload"):
return web.json_response({"success": False, "message": "missing file field"}, status=400)
filename = field.filename or "assets.bin"
data = await field.read(decode=True)
try:
self.assets_dir.mkdir(parents=True, exist_ok=True)
with open(self.assets_file, "wb") as f:
f.write(data)
except Exception as e:
return web.json_response({"success": False, "message": f"save failed: {e}"}, status=500)
return web.json_response(
{
"success": True,
"message": "uploaded",
"filename": filename,
"size": len(data),
"path": str(self.assets_file),
}
)