[fix] fix mqtt download error

This commit is contained in:
Gary 2025-12-10 20:10:55 +08:00
parent fa61faf395
commit 2322c8d179
6 changed files with 191 additions and 47 deletions

View file

@ -92,6 +92,7 @@ export default {
custom: { images: {} }
},
skin: {
defaultMode: 'light',
light: { backgroundType: 'color', backgroundColor: '#ffffff', textColor: '#000000', backgroundImage: '' },
dark: { backgroundType: 'color', backgroundColor: '#121212', textColor: '#ffffff', backgroundImage: '' }
}

View file

@ -572,7 +572,10 @@ export default {
},
getGatewayBaseCandidates() {
const params = new URLSearchParams(window.location.search || '');
const override = params.get('mqttGatewayUrl');
const override = params.get('mqttGatewayUrl') ||
(typeof localStorage !== 'undefined' ? localStorage.getItem('mqttGatewayUrl') : '') ||
(window.__MQTT_GATEWAY_URL__ || '') ||
(process.env.VUE_APP_MQTT_GATEWAY_URL || '');
const bases = [];
if (override) bases.push(override.replace(/\/$/, ''));
bases.push(`${window.location.protocol}//${window.location.hostname}:8007`); // 与脚本一致
@ -580,33 +583,121 @@ export default {
return bases;
},
computeToken(dateStr, key) {
return crypto.subtle && window.TextEncoder
? null // will handle async in list builder
: btoa(dateStr + key).slice(0, 64);
return this.buildSha256(dateStr + key);
},
formatDateTz(date, tz) {
if (tz && Intl && Intl.DateTimeFormat) {
const parts = new Intl.DateTimeFormat('zh-CN', {
timeZone: tz,
year: 'numeric',
month: '2-digit',
day: '2-digit'
}).formatToParts(date);
const y = parts.find(p => p.type === 'year')?.value;
const m = parts.find(p => p.type === 'month')?.value;
const d = parts.find(p => p.type === 'day')?.value;
if (y && m && d) return `${y}-${m}-${d}`;
}
const y = date.getFullYear();
const m = String(date.getMonth() + 1).padStart(2, '0');
const d = String(date.getDate()).padStart(2, '0');
return `${y}-${m}-${d}`;
},
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('');
if (window.crypto && window.crypto.subtle && window.TextEncoder) {
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('');
}
return this.sha256Fallback(content);
},
sha256Fallback(ascii) {
function rightRotate(value, amount) {
return (value >>> amount) | (value << (32 - amount));
}
const mathPow = Math.pow;
const maxWord = mathPow(2, 32);
let result = '';
const words = [];
const asciiBitLength = ascii.length * 8;
const hash = [];
const k = [];
let primeCounter = 0;
const isPrime = (n) => {
for (let i = 2, sqrtN = Math.sqrt(n); i <= sqrtN; i++) {
if (!(n % i)) return false;
}
return n > 1;
};
const getFractionalBits = (n) => ((n - (n | 0)) * maxWord) | 0;
for (let candidate = 2; primeCounter < 64; candidate++) {
if (isPrime(candidate)) {
if (primeCounter < 8) hash[primeCounter] = getFractionalBits(Math.pow(candidate, 1 / 2));
k[primeCounter] = getFractionalBits(Math.pow(candidate, 1 / 3));
primeCounter++;
}
}
ascii += '\x80';
while ((ascii.length % 64) - 56) ascii += '\x00';
for (let i = 0; i < ascii.length; i++) {
const j = ascii.charCodeAt(i);
if (j >> 8) return;
words[i >> 2] = words[i >> 2] || 0;
words[i >> 2] |= j << ((3 - i) % 4) * 8;
}
words[words.length] = (asciiBitLength / maxWord) | 0;
words[words.length] = asciiBitLength;
for (let j = 0; j < words.length;) {
const w = words.slice(j, j += 16);
const oldHash = hash.slice(0);
for (let i = 0; i < 64; i++) {
const w15 = w[i - 15], w2 = w[i - 2];
const a = hash[0], e = hash[4];
const temp1 = hash[7]
+ (rightRotate(e, 6) ^ rightRotate(e, 11) ^ rightRotate(e, 25))
+ ((e & hash[5]) ^ ((~e) & hash[6]))
+ k[i]
+ (w[i] = (i < 16) ? w[i] : (
w[i - 16]
+ (rightRotate(w15, 7) ^ rightRotate(w15, 18) ^ (w15 >>> 3))
+ w[i - 7]
+ (rightRotate(w2, 17) ^ rightRotate(w2, 19) ^ (w2 >>> 10))
) | 0);
const temp2 = (rightRotate(a, 2) ^ rightRotate(a, 13) ^ rightRotate(a, 22))
+ ((a & hash[1]) ^ (a & hash[2]) ^ (hash[1] & hash[2]));
hash[7] = hash[6];
hash[6] = hash[5];
hash[5] = hash[4];
hash[4] = (hash[3] + temp1) | 0;
hash[3] = hash[2];
hash[2] = hash[1];
hash[1] = hash[0];
hash[0] = (temp1 + temp2) | 0;
}
for (let i = 0; i < 8; i++) {
hash[i] = (hash[i] + oldHash[i]) | 0;
}
}
for (let i = 0; i < 8; i++) {
for (let j = 3; j + 1; j--) {
const b = (hash[i] >> (j * 8)) & 255;
result += ((b < 16) ? 0 : '') + b.toString(16);
}
}
return result;
},
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 tokenFromGlobal = window.__MQTT_TOKEN__;
// —— 2. 计算来源(严格对齐 test_mqtt_reboot.py:sha256(yyyy-MM-dd + key),以本地时间为准,含前/后一天)
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') ||
@ -621,22 +712,34 @@ export default {
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));
const now = new Date();
dates.push(
makeDateStr(now),
makeDateStr(new Date(now.getTime() - 24 * 60 * 60 * 1000)),
makeDateStr(new Date(now.getTime() + 24 * 60 * 60 * 1000))
);
}
const calcTokens = [];
for (const ds of dates) {
calcTokens.push(await this.buildSha256(ds + key));
}
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));
}
}
// —— 3. 合并优先级:URL > localStorage > 全局变量 > 计算
const list = [];
if (tokenFromUrl) list.push(tokenFromUrl);
if (tokenFromLS) list.push(tokenFromLS);
if (tokenFromGlobal) list.push(tokenFromGlobal);
list.push(...calcTokens);
// 去重
return Array.from(new Set(list)).filter(Boolean);
const deduped = Array.from(new Set(list)).filter(Boolean);
// 仅缓存计算出的第一个值,避免错误外部 token 覆盖本地
if (typeof localStorage !== 'undefined' && calcTokens[0]) {
localStorage.setItem('mqttToken', calcTokens[0]);
}
return deduped;
},
async checkDeviceOnline() {
const dev = this.device || (this.$parent && this.$parent.selectedDeviceForTheme);
@ -667,7 +770,6 @@ export default {
}
this.deviceOnline = isOnline;
dev.deviceStatus = isOnline ? 'online' : 'offline';
console.log('[Flash] 设备在线查询(同设备管理接口)', { agentId, clientId, status, online: isOnline });
if (isOnline) {
this.$message.success('设备在线,可以开始烧录');
} else {
@ -746,7 +848,6 @@ export default {
if (ok) break;
}
if (ok) {
console.log('[Flash] set_download_url 下发成功', { base, topic, clientId, downloadUrl });
return;
}
} catch (e) {
@ -811,7 +912,6 @@ export default {
if (ok) break;
}
if (ok) {
console.log('[Flash] reboot 下发成功', { base, topic, clientId });
return;
}
} catch (e) {

View file

@ -144,7 +144,7 @@ export default {
return {
previewText: 'Hi,我是你的好朋友小智!',
currentEmoji: '',
themeMode: 'light',
themeMode: (this.config && this.config.theme && this.config.theme.skin && this.config.theme.skin.defaultMode) || 'light',
fontLoaded: true, // 简化处理
availableEmotions: [
{ key: 'neutral', name: '默认', emoji: '😶' },
@ -180,6 +180,32 @@ export default {
}
},
watch: {
themeMode(val) {
// 同步用户选择为默认皮肤模式,便于打包到 assets.bin
if (this.config && this.config.theme && this.config.theme.skin) {
this.$set(this.config.theme.skin, 'defaultMode', val);
}
},
displayedEmotions: {
handler(list) {
if (list.length > 0) {
if (!list.find((e) => e.key === this.currentEmoji)) {
this.currentEmoji = list[0].key;
}
} else {
this.currentEmoji = '';
}
},
immediate: true
}
},
watch: {
themeMode(val) {
// 同步用户选择为默认皮肤模式,便于打包到 assets.bin
if (this.config && this.config.theme && this.config.theme.skin) {
this.$set(this.config.theme.skin, 'defaultMode', val);
}
},
displayedEmotions: {
handler(list) {
if (list.length > 0) {

View file

@ -393,6 +393,11 @@ class AssetsBuilder {
const skin = this.config.theme.skin
const result = {}
// 默认模式(由前端选择,light/dark)
if (skin.defaultMode) {
result.default_mode = skin.defaultMode
}
// 处理浅色模式
if (skin.light) {
result.light = {
@ -543,24 +548,24 @@ class AssetsBuilder {
// 优先使用保存的 File 对象,否则使用 URL
const source = skin.light.backgroundImageFile || skin.light.backgroundImage
if (source) {
resources.files.push({
type: 'background',
filename: 'background_light.raw',
resources.files.push({
type: 'background',
filename: 'background_light.raw',
source: source,
mode: 'light'
})
}
mode: 'light'
})
}
}
if (skin?.dark?.backgroundType === 'image') {
// 优先使用保存的 File 对象,否则使用 URL
const source = skin.dark.backgroundImageFile || skin.dark.backgroundImage
if (source) {
resources.files.push({
type: 'background',
filename: 'background_dark.raw',
resources.files.push({
type: 'background',
filename: 'background_dark.raw',
source: source,
mode: 'dark'
})
mode: 'dark'
})
}
}

View file

@ -71,10 +71,10 @@ class WakenetModelPacker {
} else {
// Wakenet 模型 (例如: wn9s_nihaoxiaozhi)
modelFiles = [
'_MODEL_INFO_',
'wn9_data',
'wn9_index'
]
'_MODEL_INFO_',
'wn9_data',
'wn9_index'
]
}
let loadedFiles = 0

View file

@ -11,7 +11,7 @@ const { InjectManifest } = require('workbox-webpack-plugin');
// 引入 path 模块
const path = require('path')
function resolve(dir) {
return path.join(__dirname, dir)
}
@ -38,10 +38,15 @@ const cdnResources = {
// 判断是否使用CDN
const useCDN = process.env.VUE_APP_USE_CDN === 'true';
// DevServer 主机/端口配置(避免默认 localhost 造成 WS 连接失败的日志)
const devHost = process.env.DEV_SERVER_HOST || process.env.HOST || '0.0.0.0';
const devPort = Number(process.env.DEV_SERVER_PORT || process.env.PORT || 8001);
module.exports = defineConfig({
productionSourceMap: process.env.NODE_ENV !=='production', // 生产环境不生成 source map
devServer: {
port: 8001, // 指定端口为 8001
host: devHost,
port: devPort,
proxy: {
'/xiaozhi': {
target: 'http://127.0.0.1:8002',
@ -50,6 +55,13 @@ module.exports = defineConfig({
},
client: {
overlay: false, // 不显示 webpack 错误覆盖层
// 显式指定 WS 连接地址,避免默认 localhost 触发“ws://localhost:8001/ws failed”日志
webSocketURL: {
protocol: 'ws',
hostname: devHost,
port: devPort,
pathname: '/ws'
}
},
},
publicPath: process.env.VUE_APP_PUBLIC_PATH || "/",