update:新增ota

This commit is contained in:
2026-09-21 14:56:43 +08:00
parent b060d8f987
commit 4bd7599cc0
11 changed files with 652 additions and 410 deletions
+22 -9
View File
@@ -28,7 +28,8 @@ try {
const ADDONS_BASE_URL = BASE_URL.replace(/\/api\/shoot$/, "/api/shoot"); const ADDONS_BASE_URL = BASE_URL.replace(/\/api\/shoot$/, "/api/shoot");
const API_ROOT_URL = BASE_URL.replace(/\/api\/shoot$/, ""); const API_ROOT_URL = BASE_URL.replace(/\/api\/shoot$/, "");
// 统一处理业务接口请求,包含登录态、业务错误和特定接口空响应兼容。 // 统一处理业务接口请求,包含登录态、业务错误和特定接口空响应兼容。
function request(method, url, data = {}, baseUrl = BASE_URL, successCodes = [0]) { function request(method, url, data = {}, baseUrl = BASE_URL, successCodes = [0], options = {}) {
const {timeout = 10000, showErrorToast = true} = options;
const token = uni.getStorageSync( const token = uni.getStorageSync(
`${uni.getAccountInfoSync().miniProgram.envVersion}_token` `${uni.getAccountInfoSync().miniProgram.envVersion}_token`
); );
@@ -40,8 +41,16 @@ function request(method, url, data = {}, baseUrl = BASE_URL, successCodes = [0])
method, method,
header, header,
data, data,
timeout: 10000, timeout,
success: (res) => { success: (res) => {
if (
url === "/user/hardwareBox/connectWifi" &&
res.statusCode === 200 &&
typeof res.data?.success === "boolean"
) {
resolve(res.data);
return;
}
const acceptsEmptyResponse = [ const acceptsEmptyResponse = [
"/user/hardwareBox/connectWifi", "/user/hardwareBox/connectWifi",
"/user/device/unbindByQrcodeId", "/user/device/unbindByQrcodeId",
@@ -111,10 +120,12 @@ function request(method, url, data = {}, baseUrl = BASE_URL, successCodes = [0])
icon: "none", icon: "none",
}); });
} }
if (showErrorToast) {
uni.showToast({ uni.showToast({
title: message, title: message,
icon: "none", icon: "none",
}); });
}
reject(error); reject(error);
return; return;
} }
@@ -122,7 +133,7 @@ function request(method, url, data = {}, baseUrl = BASE_URL, successCodes = [0])
} }
}, },
fail: (err) => { fail: (err) => {
handleRequestError(err, url); if (showErrorToast) handleRequestError(err, url);
reject(err); reject(err);
}, },
}); });
@@ -571,7 +582,14 @@ export const laserCloseAPI = async () => {
// 设备连接指定 WiFi,只下发 WiFi 凭证,不触发 OTA 升级。 // 设备连接指定 WiFi,只下发 WiFi 凭证,不触发 OTA 升级。
export const connectDeviceWifiAPI = async (ssid, password) => { export const connectDeviceWifiAPI = async (ssid, password) => {
return request("POST", "/user/hardwareBox/connectWifi", {ssid, password}); return request(
"POST",
"/user/hardwareBox/connectWifi",
{ssid, password},
BASE_URL,
[0],
{timeout: 20000, showErrorToast: false}
);
}; };
// 获取硬件盒子版本信息,用于判断当前设备是否需要 OTA 升级。 // 获取硬件盒子版本信息,用于判断当前设备是否需要 OTA 升级。
@@ -584,11 +602,6 @@ export const sendHardwareBoxUpdateAPI = async (data) => {
return request("POST", "/user/hardwareBox/sendUpdate", data); return request("POST", "/user/hardwareBox/sendUpdate", data);
}; };
// 根据任务 ID 获取硬件盒子 OTA 更新状态。
export const getHardwareBoxTaskStatusAPI = async (taskId) => {
return request("GET", `/user/hardwareBox/taskStatus?taskId=${taskId}`);
};
export const addNoteAPI = async (id, remark) => { export const addNoteAPI = async (id, remark) => {
return request("POST", "/user/score/sheet/remark", {id, remark}); return request("POST", "/user/score/sheet/remark", {id, remark});
}; };
+37
View File
@@ -1,4 +1,6 @@
<script setup> <script setup>
import IconButton from "./IconButton.vue";
const props = defineProps({ const props = defineProps({
show: { show: {
type: Boolean, type: Boolean,
@@ -28,6 +30,14 @@ const props = defineProps({
type: Boolean, type: Boolean,
default: true, default: true,
}, },
confirmDisabled: {
type: Boolean,
default: false,
},
showClose: {
type: Boolean,
default: false,
},
onCancel: { onCancel: {
type: Function, type: Function,
default: null, default: null,
@@ -36,6 +46,10 @@ const props = defineProps({
type: Function, type: Function,
default: null, default: null,
}, },
onClose: {
type: Function,
default: null,
},
}); });
const handleCancel = () => { const handleCancel = () => {
@@ -43,8 +57,13 @@ const handleCancel = () => {
}; };
const handleConfirm = () => { const handleConfirm = () => {
if (props.confirmDisabled) return;
props.onConfirm?.(); props.onConfirm?.();
}; };
const handleClose = () => {
props.onClose?.();
};
</script> </script>
<template> <template>
@@ -89,6 +108,7 @@ const handleConfirm = () => {
<view <view
v-if="showConfirm" v-if="showConfirm"
class="dialog-button confirm" class="dialog-button confirm"
:class="{ disabled: confirmDisabled }"
@click="handleConfirm" @click="handleConfirm"
> >
<text>{{ confirmText }}</text> <text>{{ confirmText }}</text>
@@ -96,6 +116,13 @@ const handleConfirm = () => {
</view> </view>
</view> </view>
<view v-if="showClose" class="dialog-close">
<IconButton
src="../static/close-gold-outline.png"
:width="30"
:onClick="handleClose"
/>
</view>
</view> </view>
</view> </view>
</template> </template>
@@ -108,6 +135,7 @@ const handleConfirm = () => {
top: 0; top: 0;
left: 0; left: 0;
background-color: rgba(0, 0, 0, 0.62); background-color: rgba(0, 0, 0, 0.62);
flex-direction: column;
justify-content: center; justify-content: center;
align-items: center; align-items: center;
z-index: 999; z-index: 999;
@@ -116,6 +144,7 @@ const handleConfirm = () => {
.modal-wrap { .modal-wrap {
position: relative; position: relative;
display: flex; display: flex;
flex-direction: column;
width: 549rpx; width: 549rpx;
min-height: 318rpx;; min-height: 318rpx;;
padding-top: 168rpx; padding-top: 168rpx;
@@ -222,6 +251,14 @@ const handleConfirm = () => {
background-color: #ffda3f; background-color: #ffda3f;
} }
.dialog-button.confirm.disabled {
opacity: 0.62;
}
.dialog-close {
margin-top: 28rpx;
}
@keyframes rotateLight { @keyframes rotateLight {
from { from {
transform: translateX(-50%) rotate(0deg); transform: translateX(-50%) rotate(0deg);
+36 -3
View File
@@ -24,6 +24,10 @@ const props = defineProps({
type: Number, type: Number,
default: 40, default: 40,
}, },
phase: {
type: String,
default: "",
},
// 副标题:如“新版本将优化智能弓体验” // 副标题:如“新版本将优化智能弓体验”
description: { description: {
type: String, type: String,
@@ -48,6 +52,14 @@ const isSuccess = computed(() => props.state === "update_success");
const isFailure = computed(() => props.state === "update_failure"); const isFailure = computed(() => props.state === "update_failure");
// Clamp progress to keep the progress bar width within its container. // Clamp progress to keep the progress bar width within its container.
const progressValue = computed(() => Math.min(100, Math.max(0, Number(props.progress) || 0))); const progressValue = computed(() => Math.min(100, Math.max(0, Number(props.progress) || 0)));
const progressPhaseText = computed(() => {
const phaseText = {
started: "正在准备固件更新",
downloading: "正在下载固件",
installing: "正在安装固件",
};
return phaseText[props.phase] || "正在进行固件更新";
});
// 点击立即更新前先校验设备在线状态。 // 点击立即更新前先校验设备在线状态。
const handleUpdateClick = () => { const handleUpdateClick = () => {
@@ -127,10 +139,10 @@ const handleUpdateClick = () => {
<!-- 更新成功图片左边距 34rpx文案左边距 44rpx按钮浮动底部居中 --> <!-- 更新成功图片左边距 34rpx文案左边距 44rpx按钮浮动底部居中 -->
<block v-else-if="isSuccess"> <block v-else-if="isSuccess">
<image src="https://static.shelingxingqiu.com/shootmini/static/ota/update-ok.png" mode="aspectFit" class="result-title-img" style="width: 220rpx; height: 62rpx;" /> <image src="https://static.shelingxingqiu.com/shootmini/static/ota/update-ok.png" mode="aspectFit" class="result-title-img" style="width: 220rpx; height: 62rpx;" />
<text class="dialog-desc">请关机并重启智能弓</text> <text class="dialog-desc">固件更新已完成</text>
<view class="btn-group-result"> <view class="btn-group-result">
<view class="primary-btn" @click="emit('done')"> <view class="primary-btn" @click="emit('done')">
<text class="primary-btn-text">完成</text> <text class="primary-btn-text">关闭</text>
</view> </view>
</view> </view>
</block> </block>
@@ -139,6 +151,10 @@ const handleUpdateClick = () => {
<block v-else-if="isProgress"> <block v-else-if="isProgress">
<image src="https://static.shelingxingqiu.com/shootmini/static/ota/update_progress.png" mode="aspectFit" class="result-title-img" style="width: 220rpx; height: 62rpx;" /> <image src="https://static.shelingxingqiu.com/shootmini/static/ota/update_progress.png" mode="aspectFit" class="result-title-img" style="width: 220rpx; height: 62rpx;" />
<view class="progress-wrap"> <view class="progress-wrap">
<view class="progress-meta">
<text class="progress-phase">{{ progressPhaseText }}</text>
<text class="progress-value">{{ Math.floor(progressValue) }}%</text>
</view>
<view class="progress-track"> <view class="progress-track">
<view class="progress-fill" :style="{ width: `${progressValue}%` }"></view> <view class="progress-fill" :style="{ width: `${progressValue}%` }"></view>
</view> </view>
@@ -391,9 +407,26 @@ const handleUpdateClick = () => {
} }
.progress-wrap { .progress-wrap {
width: 394rpx; width: 394rpx;
margin-top: 40rpx; margin-top: 28rpx;
margin-left: 44rpx; margin-left: 44rpx;
} }
.progress-meta {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 16rpx;
color: #ffffff;
font-size: 24rpx;
line-height: 34rpx;
}
.progress-phase {
flex: 1;
}
.progress-value {
flex-shrink: 0;
margin-left: 16rpx;
color: #fed847;
}
.progress-track { .progress-track {
width: 100%; width: 100%;
height: 18rpx; height: 18rpx;
@@ -22,7 +22,13 @@ export function useDeviceStatus({
const isDeviceOnline = computed( const isDeviceOnline = computed(
() => deviceStatus.value.online === true || online.value === true () => deviceStatus.value.online === true || online.value === true
); );
const statusText = computed(() => (isDeviceOnline.value ? "已连接" : "未连接")); const isDeviceCharging = computed(
() => isDeviceOnline.value && deviceStatus.value.charging === true
);
const statusText = computed(() => {
if (!isDeviceOnline.value) return "未连接";
return isDeviceCharging.value ? "已连接(充电中)" : "已连接";
});
const statusClass = computed(() => const statusClass = computed(() =>
isDeviceOnline.value ? "device-status--online" : "device-status--offline" isDeviceOnline.value ? "device-status--online" : "device-status--offline"
); );
@@ -186,6 +192,7 @@ export function useDeviceStatus({
deviceDetails, deviceDetails,
deviceRows, deviceRows,
getDeviceNameOverrides, getDeviceNameOverrides,
isDeviceCharging,
isDeviceOnline, isDeviceOnline,
maskedDeviceId, maskedDeviceId,
networkText, networkText,
@@ -0,0 +1,188 @@
import { computed, onUnmounted, ref } from "vue";
import { sendHardwareBoxUpdateAPI } from "@/apis";
import useStore from "@/store";
import { storeToRefs } from "pinia";
const OTA_PROGRESS_EVENT = "/addons/shoot/otaProgress";
const OTA_RESULT_EVENT = "/addons/shoot/otaResult";
const UPDATE_TIMEOUT = 10 * 60 * 1000;
const phaseTextMap = {
started: "正在准备固件更新",
downloading: "正在下载固件",
installing: "正在安装固件",
};
export const useOtaUpdate = () => {
const store = useStore();
const { device } = storeToRefs(store);
const updating = ref(false);
const progress = ref(0);
const phase = ref("started");
const resultVisible = ref(false);
const resultStatus = ref("");
const resultReason = ref("");
let updateRunId = 0;
let targetVersion = "";
let timeoutTimer = null;
let successCallback = null;
let socketListening = false;
const phaseText = computed(
() => phaseTextMap[phase.value] || "正在进行固件更新"
);
const resultTitle = computed(() =>
resultStatus.value === "success" ? "固件更新完成" : "固件更新失败"
);
const resultContent = computed(() => {
if (resultStatus.value === "success") return "固件更新已完成";
return resultReason.value || "更新失败,请检查设备及网络后重试";
});
const clearTimers = () => {
clearTimeout(timeoutTimer);
timeoutTimer = null;
};
const stopSocketListening = () => {
if (!socketListening) return;
uni.$off("socket-inbox", handleSocketMessage);
socketListening = false;
};
const resetActiveUpdate = () => {
clearTimers();
stopSocketListening();
successCallback = null;
};
const finishUpdate = (status, reason = "", runId = updateRunId) => {
if (runId !== updateRunId || !updating.value) return;
const onSuccess = successCallback;
resetActiveUpdate();
updating.value = false;
resultStatus.value = status;
resultReason.value = reason;
if (status === "success") {
progress.value = 100;
phase.value = "installing";
onSuccess?.();
}
resultVisible.value = true;
};
const isCurrentUpdateMessage = (data) => {
const messageDeviceId = String(data?.deviceId || "");
const currentDeviceId = String(device.value?.deviceId || "");
if (messageDeviceId && currentDeviceId && messageDeviceId !== currentDeviceId) {
return false;
}
const messageVersion = String(data?.versionNumber || "");
return !messageVersion || !targetVersion || messageVersion === targetVersion;
};
function handleSocketMessage(message) {
if (!updating.value || Number(message?.code ?? 0) !== 0) return;
if (![OTA_PROGRESS_EVENT, OTA_RESULT_EVENT].includes(message?.event)) return;
if (!isCurrentUpdateMessage(message.data)) return;
if (message.event === OTA_PROGRESS_EVENT) {
const nextProgress = Math.min(
100,
Math.max(0, Number(message.data?.progress) || 0)
);
progress.value = Math.max(progress.value, nextProgress);
if (phaseTextMap[message.data?.phase]) {
phase.value = message.data.phase;
}
return;
}
if (message.data?.status === "success") {
finishUpdate("success");
return;
}
if (message.data?.status === "failed") {
finishUpdate("failed", message.data?.reason || "");
}
}
const startSocketListening = () => {
if (socketListening) return;
uni.$on("socket-inbox", handleSocketMessage);
socketListening = true;
};
const startUpdate = async ({
versionNumber,
resourceUrl,
wifiSsid = "",
wifiPassword = "",
onSuccess,
}) => {
if (updating.value) return false;
updateRunId += 1;
const runId = updateRunId;
targetVersion = String(versionNumber || "");
successCallback = onSuccess || null;
resultVisible.value = false;
resultStatus.value = "";
resultReason.value = "";
progress.value = 0;
phase.value = "started";
updating.value = true;
startSocketListening();
timeoutTimer = setTimeout(() => {
finishUpdate("failed", "固件更新超时,请稍后重试", runId);
}, UPDATE_TIMEOUT);
try {
const updateResult = await sendHardwareBoxUpdateAPI({
versionNumber: targetVersion,
wifiSsid,
wifiPassword,
resourceUrl,
});
if (runId !== updateRunId || !updating.value) return false;
if (!updateResult?.taskId) {
finishUpdate("failed", "固件更新任务创建失败,请稍后重试", runId);
return false;
}
return true;
} catch (error) {
if (runId === updateRunId) {
finishUpdate(
"failed",
error?.message || "固件更新请求失败,请稍后重试",
runId
);
}
return false;
}
};
const closeResult = () => {
resultVisible.value = false;
};
onUnmounted(() => {
updateRunId += 1;
resetActiveUpdate();
});
return {
updating,
progress,
phase,
phaseText,
resultVisible,
resultStatus,
resultTitle,
resultContent,
startUpdate,
closeResult,
};
};
+178 -24
View File
@@ -5,6 +5,7 @@ import Container from "@/components/Container.vue";
import Header from "@/components/Header.vue"; import Header from "@/components/Header.vue";
import ScreenHint from "@/components/ScreenHint.vue"; import ScreenHint from "@/components/ScreenHint.vue";
import ModalDialog from "@/components/ModalDialog.vue"; import ModalDialog from "@/components/ModalDialog.vue";
import OtaModal from "@/components/OtaModal.vue";
import { import {
getHardwareBoxVersionAPI, getHardwareBoxVersionAPI,
laserAimAPI, laserAimAPI,
@@ -17,10 +18,12 @@ import {
DEVICE_NAME_STORAGE_KEY, DEVICE_NAME_STORAGE_KEY,
useDeviceStatus, useDeviceStatus,
} from "./composables/useDeviceStatus"; } from "./composables/useDeviceStatus";
import { useOtaUpdate } from "./composables/useOtaUpdate";
const store = useStore(); const store = useStore();
const { updateDevice, clearDevice } = store; const { updateDevice, clearDevice } = store;
const { user, device, deviceStatus, online } = storeToRefs(store); const { user, device, deviceStatus, online } = storeToRefs(store);
const DEVICE_NAME_MAX_LENGTH = 10;
const formatBindingDate = (value) => { const formatBindingDate = (value) => {
if (!value) return "--"; if (!value) return "--";
@@ -56,11 +59,26 @@ const retryScanOnShow = ref(false);
const calibration = ref(false); const calibration = ref(false);
const showDeviceId = ref(false); const showDeviceId = ref(false);
const latestVersionDialogVisible = ref(false); const latestVersionDialogVisible = ref(false);
const firmwareConfirmVisible = ref(false);
const wifiRequiredVisible = ref(false);
const otaNeedUpdate = ref(false); const otaNeedUpdate = ref(false);
const firmwareActionPending = ref(false); const firmwareActionPending = ref(false);
const pendingOtaInfo = ref(null);
let otaCheckPromise = null; let otaCheckPromise = null;
let otaCheckRequestVersion = 0; let otaCheckRequestVersion = 0;
const {
updating: otaUpdating,
progress: otaProgress,
phase: otaPhase,
resultVisible: otaResultVisible,
resultStatus: otaResultStatus,
resultTitle: otaResultTitle,
resultContent: otaResultContent,
startUpdate: startOtaUpdate,
closeResult: closeOtaResult,
} = useOtaUpdate();
const { const {
batteryText, batteryText,
deviceDetails, deviceDetails,
@@ -94,8 +112,8 @@ const bindingDateText = computed(() =>
); );
const deviceIdText = computed(() => const deviceIdText = computed(() =>
showDeviceId.value && device.value.deviceId showDeviceId.value && device.value.deviceName
? device.value.deviceId ? device.value.deviceName
: maskedDeviceId.value : maskedDeviceId.value
); );
@@ -107,7 +125,9 @@ const designDeviceStats = computed(() => [
}, },
{ {
label: "剩余电量", label: "剩余电量",
value: batteryText.value === "暂无数据" || !isDeviceOnline.value value: !isDeviceOnline.value
? "设备离线"
: batteryText.value === "暂无数据"
? "--" ? "--"
: batteryText.value, : batteryText.value,
}, },
@@ -150,6 +170,14 @@ const closeNameEditor = () => {
nameEditorVisible.value = false; nameEditorVisible.value = false;
}; };
const editingNameLength = computed(() =>
Array.from(String(editingName.value || "")).length
);
const isEditingNameTooLong = computed(
() => editingNameLength.value > DEVICE_NAME_MAX_LENGTH
);
const toggleDeviceId = () => { const toggleDeviceId = () => {
if (device.value.deviceId) showDeviceId.value = !showDeviceId.value; if (device.value.deviceId) showDeviceId.value = !showDeviceId.value;
}; };
@@ -162,8 +190,15 @@ const confirmName = async () => {
uni.showToast({ title: "请输入设备名", icon: "none" }); uni.showToast({ title: "请输入设备名", icon: "none" });
return; return;
} }
if (name.length > 10 || !/^[\u4e00-\u9fa5A-Za-z0-9_-]+$/.test(name)) { if (Array.from(name).length > DEVICE_NAME_MAX_LENGTH) {
uni.showToast({ title: "设备名格式不正确", icon: "none" }); uni.showToast({ title: "设备名最多支持10个字符", icon: "none" });
return;
}
if (!/^[\u4e00-\u9fa5A-Za-z0-9_-]+$/.test(name)) {
uni.showToast({
title: "仅支持中文、英文、数字、下划线和减号",
icon: "none",
});
return; return;
} }
@@ -206,7 +241,7 @@ const toDeviceIntroPage = () => {
const joinWifi = () => { const joinWifi = () => {
if (!isDeviceOnline.value) { if (!isDeviceOnline.value) {
uni.showToast({ title: "请先开启智能弓", icon: "none" }); uni.showToast({ title: "请先开启智能弓", icon: "none" });
return; return;
} }
uni.navigateTo({ url: "/pages/device/ota-wifi" }); uni.navigateTo({ url: "/pages/device/ota-wifi" });
@@ -277,6 +312,52 @@ const closeLatestVersionDialog = () => {
latestVersionDialogVisible.value = false; latestVersionDialogVisible.value = false;
}; };
const closeFirmwareConfirm = () => {
firmwareConfirmVisible.value = false;
};
const runFirmwareUpdate = () => {
const versionInfo = pendingOtaInfo.value;
if (!versionInfo) return;
void startOtaUpdate({
versionNumber: versionInfo.versionNumber,
resourceUrl: versionInfo.resourceUrl,
onSuccess: () => {
otaNeedUpdate.value = false;
},
});
};
const confirmFirmwareUpdate = () => {
firmwareConfirmVisible.value = false;
if (!isDeviceOnline.value) {
uni.showToast({ title: "请先开启智能弓", icon: "none" });
return;
}
if (String(networkType.value || "").toLowerCase() === "wifi") {
runFirmwareUpdate();
return;
}
wifiRequiredVisible.value = true;
};
const goWifiForFirmwareUpdate = () => {
const versionInfo = pendingOtaInfo.value;
if (!versionInfo) return;
wifiRequiredVisible.value = false;
const query = [
"source=firmware-update",
`versionNumber=${encodeURIComponent(versionInfo.versionNumber)}`,
`resourceUrl=${encodeURIComponent(versionInfo.resourceUrl)}`,
].join("&");
uni.navigateTo({ url: `/pages/device/ota-wifi?${query}` });
};
const handleOtaResultClose = () => {
closeOtaResult();
void refreshOtaUpdateState();
};
const goFirmwareUpdate = async () => { const goFirmwareUpdate = async () => {
if (firmwareActionPending.value) return; if (firmwareActionPending.value) return;
if (!isDeviceOnline.value) { if (!isDeviceOnline.value) {
@@ -293,11 +374,8 @@ const goFirmwareUpdate = async () => {
return; return;
} }
const query = [ pendingOtaInfo.value = versionInfo;
`versionNumber=${encodeURIComponent(versionInfo.versionNumber)}`, firmwareConfirmVisible.value = true;
`resourceUrl=${encodeURIComponent(versionInfo.resourceUrl)}`,
].join("&");
uni.navigateTo({ url: `/pages/device/ota-wifi?${query}` });
} catch (error) { } catch (error) {
uni.showToast({ title: "获取更新版本失败,请重试", icon: "none" }); uni.showToast({ title: "获取更新版本失败,请重试", icon: "none" });
} finally { } finally {
@@ -307,7 +385,7 @@ const goFirmwareUpdate = async () => {
const goCalibration = async () => { const goCalibration = async () => {
if (!isDeviceOnline.value) { if (!isDeviceOnline.value) {
uni.showToast({ title: "请先开启智能弓", icon: "none" }); uni.showToast({ title: "请先开启智能弓", icon: "none" });
return; return;
} }
try { try {
@@ -546,10 +624,16 @@ onShow(async () => {
</view> </view>
</view> </view>
<ScreenHint mode="square" :show="showTip" :onClose="closeTip"> <ModalDialog
:show="showTip"
:showCancel="false"
:showConfirm="false"
:showClose="true"
:onClose="closeTip"
>
<view class="scan-tips"> <view class="scan-tips">
<text class="scan-tips-title">扫码绑定射灵弓箭</text> <text class="scan-tips-title">扫码绑定射灵弓箭</text>
<text class="scan-tips-subtitle">设备底部二维码样例</text> <text class="scan-tips-subtitle">配套令牌样例</text>
<image <image
class="scan-tips-qr" class="scan-tips-qr"
src="../../static/device-assets/my-device-unbound-qr-sample.png" src="../../static/device-assets/my-device-unbound-qr-sample.png"
@@ -561,7 +645,7 @@ onShow(async () => {
<button hover-class="none" @click="copyEmail">shelingxingqiu@163.com</button> <button hover-class="none" @click="copyEmail">shelingxingqiu@163.com</button>
</view> </view>
</view> </view>
</ScreenHint> </ModalDialog>
<ScreenHint :show="confirmBindTip" :onClose="closeConfirmBindTip"> <ScreenHint :show="confirmBindTip" :onClose="closeConfirmBindTip">
<view class="confirm-bind"> <view class="confirm-bind">
@@ -598,6 +682,47 @@ onShow(async () => {
:onConfirm="closeLatestVersionDialog" :onConfirm="closeLatestVersionDialog"
></ModalDialog> ></ModalDialog>
<ModalDialog
:show="firmwareConfirmVisible"
title="固件更新"
content="是否现在进行固件更新?"
cancelText="取消"
confirmText="确定"
:onCancel="closeFirmwareConfirm"
:onConfirm="confirmFirmwareUpdate"
></ModalDialog>
<ModalDialog
:show="wifiRequiredVisible"
title="固件更新"
content="请在WiFi网络下更新"
confirmText="连接WiFi"
:showCancel="false"
:onConfirm="goWifiForFirmwareUpdate"
></ModalDialog>
<OtaModal
:visible="otaUpdating"
state="update_progress"
:progress="otaProgress"
:phase="otaPhase"
/>
<OtaModal
:visible="otaResultVisible && otaResultStatus === 'success'"
state="update_success"
@done="handleOtaResultClose"
/>
<ModalDialog
:show="otaResultVisible && otaResultStatus === 'failed'"
:title="otaResultTitle"
:content="otaResultContent"
confirmText="关闭"
:showCancel="false"
:onConfirm="handleOtaResultClose"
></ModalDialog>
<view v-if="nameEditorVisible" class="name-mask" @click="closeNameEditor"> <view v-if="nameEditorVisible" class="name-mask" @click="closeNameEditor">
<view class="name-panel" @click.stop> <view class="name-panel" @click.stop>
<image <image
@@ -613,9 +738,9 @@ onShow(async () => {
focus focus
:cursor-spacing="24" :cursor-spacing="24"
:disabled="renaming" :disabled="renaming"
maxlength="10" :maxlength="-1"
confirm-type="done" confirm-type="done"
placeholder="请输入设备名(最长10个汉字)" placeholder="请输入设备名"
placeholder-class="name-placeholder" placeholder-class="name-placeholder"
@confirm="confirmName" @confirm="confirmName"
/> />
@@ -631,7 +756,13 @@ onShow(async () => {
/> />
</view> </view>
</view> </view>
<view class="name-meta">
<text class="name-helper">仅支持中文英文数字下划线减号</text> <text class="name-helper">仅支持中文英文数字下划线减号</text>
<text
class="name-count"
:class="{ 'name-count--exceeded': isEditingNameTooLong }"
>{{ editingNameLength }}/{{ DEVICE_NAME_MAX_LENGTH }}</text>
</view>
</view> </view>
</view> </view>
</view> </view>
@@ -661,7 +792,7 @@ onShow(async () => {
.device-nav .device-status { .device-nav .device-status {
position: absolute; position: absolute;
top: calc(100% + 28rpx); top: calc(100% + 0);
left: 50%; left: 50%;
white-space: nowrap; white-space: nowrap;
transform: translateX(-50%); transform: translateX(-50%);
@@ -851,7 +982,7 @@ onShow(async () => {
display: flex; display: flex;
align-items: center; align-items: center;
color: rgba(255, 255, 255, 0.9); color: rgba(255, 255, 255, 0.9);
font-size: 24rpx; font-size: 18rpx;
line-height: 30rpx; line-height: 30rpx;
} }
@@ -1120,12 +1251,13 @@ onShow(async () => {
.scan-tips { .scan-tips {
display: flex; display: flex;
width: 90%; width: 100%;
box-sizing: border-box; box-sizing: border-box;
flex-direction: column; flex-direction: column;
margin-top: 20%; align-items: flex-start;
color: #ffffff; color: #ffffff;
font-size: 24rpx; font-size: 24rpx;
text-align: left;
} }
.scan-tips-title { .scan-tips-title {
@@ -1276,12 +1408,34 @@ onShow(async () => {
opacity: 0.6; opacity: 0.6;
} }
.name-helper { .name-meta {
display: block; display: flex;
width: 100%;
max-width: 620rpx;
align-items: flex-start;
justify-content: space-between;
margin-top: 22rpx; margin-top: 22rpx;
margin-right: auto;
margin-left: auto;
gap: 20rpx;
}
.name-helper,
.name-count {
color: rgba(255, 255, 255, 0.62); color: rgba(255, 255, 255, 0.62);
font-size: 24rpx; font-size: 24rpx;
line-height: 34rpx; line-height: 34rpx;
text-align: center; }
.name-helper {
flex: 1;
}
.name-count {
flex-shrink: 0;
}
.name-count--exceeded {
color: #fed847;
} }
</style> </style>
+110 -293
View File
@@ -1,28 +1,21 @@
<script setup> <script setup>
import { ref, computed, onMounted, onUnmounted, watch } from "vue"; import { ref, computed, onMounted, onUnmounted } from "vue";
import { onLoad, onShow } from "@dcloudio/uni-app"; import { onLoad, onShow } from "@dcloudio/uni-app";
import Container from "@/components/Container.vue"; import Container from "@/components/Container.vue";
import ScreenHint from "@/components/ScreenHint.vue"; import ScreenHint from "@/components/ScreenHint.vue";
import ModalDialog from "@/components/ModalDialog.vue";
import OtaModal from "@/components/OtaModal.vue";
import { import {
connectDeviceWifiAPI, connectDeviceWifiAPI,
getHardwareBoxTaskStatusAPI,
getHardwareBoxVersionAPI, getHardwareBoxVersionAPI,
sendHardwareBoxUpdateAPI,
} from "@/apis"; } from "@/apis";
import useStore from "@/store"; import { useOtaUpdate } from "./composables/useOtaUpdate";
import { storeToRefs } from "pinia";
const store = useStore();
const { deviceStatus } = storeToRefs(store);
const STATES = { const STATES = {
SCANNING: "SCANNING", SCANNING: "SCANNING",
LIST: "LIST", LIST: "LIST",
CONNECTING: "CONNECTING", CONNECTING: "CONNECTING",
CONNECTED: "CONNECTED", CONNECTED: "CONNECTED",
UPDATING: "UPDATING",
DONE: "DONE",
FAILED: "FAILED",
}; };
const isIOS = uni.getDeviceInfo().osName === "ios"; const isIOS = uni.getDeviceInfo().osName === "ios";
@@ -42,26 +35,37 @@ const keyboardHeight = ref(0);
const showPassword = ref(false); const showPassword = ref(false);
// 刷新防抖标志:扫描进行中为 true,禁止重复点击;扫描结束(成功/失败)后重置为 false。 // 刷新防抖标志:扫描进行中为 true,禁止重复点击;扫描结束(成功/失败)后重置为 false。
const isRefreshing = ref(false); const isRefreshing = ref(false);
const isStartingUpdate = ref(false); const fromFirmwareUpdate = ref(false);
const routeOtaInfo = ref({ const routeOtaInfo = ref({
versionNumber: "", versionNumber: "",
resourceUrl: "", resourceUrl: "",
}); });
const countdownVisible = ref(false);
const progress = ref(0); const countdownSeconds = ref(3);
let progressTimer = null; const firmwareMessageVisible = ref(false);
let timeoutTimer = null; const firmwareMessage = ref("");
let statusTimer = null; let countdownTimer = null;
let wifiConnectTimeoutTimer = null;
let stopWifiStatusWatcher = null;
let settleWifiConnectWaiting = null;
let wifiConnectRequestId = 0; let wifiConnectRequestId = 0;
const WIFI_CONNECT_TIMEOUT = 60000;
const DEVICE_STATUS_STALE_TIME = 6000;
const WIFI_CONNECT_FAILED_TEXT = "连接失败,请检查WiFi密码或WiFi状态"; const WIFI_CONNECT_FAILED_TEXT = "连接失败,请检查WiFi密码或WiFi状态";
// 控制授权拒绝弹窗显示/隐藏 // 控制授权拒绝弹窗显示/隐藏
const wifiAuthDeniedVisible = ref(false); const wifiAuthDeniedVisible = ref(false);
const {
updating: otaUpdating,
progress: otaProgress,
phase: otaPhase,
resultVisible: otaResultVisible,
resultStatus: otaResultStatus,
resultTitle: otaResultTitle,
resultContent: otaResultContent,
startUpdate: startOtaUpdate,
closeResult: closeOtaResult,
} = useOtaUpdate();
const countdownButtonText = computed(
() => `${Math.max(1, countdownSeconds.value)}秒后开始`
);
// 判断 WiFi 列表失败是否由用户拒绝授权引起(兼容 errno:103 及各平台 errMsg 变体)。 // 判断 WiFi 列表失败是否由用户拒绝授权引起(兼容 errno:103 及各平台 errMsg 变体)。
const isWifiPermissionDenied = (err) => { const isWifiPermissionDenied = (err) => {
if (err?.errno === 103) return true; if (err?.errno === 103) return true;
@@ -260,84 +264,30 @@ const wifiListScrollHeight = computed(() => {
return `${Math.min(itemCount * 92, maxHeight)}rpx`; return `${Math.min(itemCount * 92, maxHeight)}rpx`;
}); });
// 清理本次 WiFi 连接状态监听和超时计时器 // 取消当前 WiFi 连接请求的页面等待状态,并忽略可能迟到的响应
const clearWifiConnectWatcher = () => {
clearTimeout(wifiConnectTimeoutTimer);
wifiConnectTimeoutTimer = null;
if (stopWifiStatusWatcher) {
stopWifiStatusWatcher();
stopWifiStatusWatcher = null;
}
};
// 取消当前 WiFi 连接确认,并恢复弹窗提交状态。
const cancelWifiConnectWaiting = () => { const cancelWifiConnectWaiting = () => {
wifiConnectRequestId += 1; wifiConnectRequestId += 1;
if (settleWifiConnectWaiting) {
settleWifiConnectWaiting(false);
}
clearWifiConnectWatcher();
connectStatusText.value = ""; connectStatusText.value = "";
isSubmittingWifi.value = false; isSubmittingWifi.value = false;
uni.hideLoading(); uni.hideLoading();
}; };
// 根据实时推送的 online/netType 判断设备是否已通过 WiFi 在线 // 把接口失败和传输异常转换为连接弹窗内的用户提示
// 返回值含义:true → WiFi 在线成功;"net_fail" → 设备走 4g 失败;false → 未就绪。 const getWifiConnectErrorText = (error) => {
const isDeviceConnectedByWifi = (deviceStatus) => { const message = error?.message || "";
// online 不为 true → 设备尚未在线,继续等待推送 if (message.includes("请先开启智能弓")) return "请先开启智能弓";
if (deviceStatus?.online !== true) return false; if (message.includes("超时") || error?.errMsg?.includes("timeout")) {
const netType = String(deviceStatus?.netType || "").toLowerCase(); return "等待设备响应超时,请重试";
// online:true + netType:4g → 设备已切 4gWiFi 连接失败 }
if (netType === "4g") return "net_fail"; if (error?.errMsg) return "网络异常,请检查网络后重试";
// online:true + netType:wifi → WiFi 连接成功 return message || WIFI_CONNECT_FAILED_TEXT;
// online:true + netType:"" → 设备在线但 netType 暂未上报,继续等待推送
return netType === "wifi";
}; };
// 等待提交配置后的新 WS 状态;忽略提交前的旧状态,超时后按连接失败处理 // 提交 WiFi 配置,并以接口返回的设备最终连接结果更新页面
const waitForDeviceWifiConnected = (requestId, receivedAfter) => {
return new Promise((resolve) => {
let settled = false;
const finish = (result) => {
if (settled) return;
settled = true;
clearWifiConnectWatcher();
settleWifiConnectWaiting = null;
resolve(result);
};
settleWifiConnectWaiting = finish;
stopWifiStatusWatcher = watch(
deviceStatus,
(status) => {
if (requestId !== wifiConnectRequestId) {
finish(false);
return;
}
if (Number(status?.receivedAt) <= receivedAfter) return;
const connResult = isDeviceConnectedByWifi(status);
if (connResult === true) {
finish(true);
} else if (connResult === "net_fail") {
finish(false);
}
}
);
wifiConnectTimeoutTimer = setTimeout(
() => finish(false),
WIFI_CONNECT_TIMEOUT
);
});
};
// 提交 WiFi 配置给游戏设备,并通过 WS 确认设备真实连上 WiFi 后再展示成功。
const submitDeviceWifiConfig = async ({ ssid, password }) => { const submitDeviceWifiConfig = async ({ ssid, password }) => {
if (isSubmittingWifi.value) return; if (isSubmittingWifi.value) return;
wifiConnectRequestId += 1; wifiConnectRequestId += 1;
const requestId = wifiConnectRequestId; const requestId = wifiConnectRequestId;
clearWifiConnectWatcher();
isSubmittingWifi.value = true; isSubmittingWifi.value = true;
connectStatusText.value = "WiFi连接中..."; connectStatusText.value = "WiFi连接中...";
uni.showLoading({ uni.showLoading({
@@ -345,11 +295,9 @@ const submitDeviceWifiConfig = async ({ ssid, password }) => {
mask: true, mask: true,
}); });
try { try {
await connectDeviceWifiAPI(ssid, password); const connectResult = await connectDeviceWifiAPI(ssid, password);
if (requestId !== wifiConnectRequestId) return; if (requestId !== wifiConnectRequestId) return;
const isConnected = await waitForDeviceWifiConnected(requestId, Date.now()); if (connectResult?.success !== true) {
if (requestId !== wifiConnectRequestId) return;
if (!isConnected) {
connectError.value = WIFI_CONNECT_FAILED_TEXT; connectError.value = WIFI_CONNECT_FAILED_TEXT;
return; return;
} }
@@ -361,14 +309,15 @@ const submitDeviceWifiConfig = async ({ ssid, password }) => {
}; };
connectError.value = ""; connectError.value = "";
currentState.value = STATES.CONNECTED; currentState.value = STATES.CONNECTED;
if (fromFirmwareUpdate.value) {
openFirmwareCountdown();
}
} catch (err) { } catch (err) {
if (requestId === wifiConnectRequestId) { if (requestId === wifiConnectRequestId) {
connectError.value = connectError.value = getWifiConnectErrorText(err);
err?.code === -1 && err?.message ? err.message : WIFI_CONNECT_FAILED_TEXT;
} }
} finally { } finally {
if (requestId === wifiConnectRequestId) { if (requestId === wifiConnectRequestId) {
clearWifiConnectWatcher();
connectStatusText.value = ""; connectStatusText.value = "";
isSubmittingWifi.value = false; isSubmittingWifi.value = false;
uni.hideLoading(); uni.hideLoading();
@@ -386,83 +335,7 @@ const joinNetwork = () => {
submitDeviceWifiConfig({ ssid, password }); submitDeviceWifiConfig({ ssid, password });
}; };
// 清理 OTA 更新相关定时器,避免页面退出或状态结束后继续执行 // 获取 OTA 更新版本信息,正常使用入口传参,缺失时再请求后端兜底
const clearUpdateTimers = () => {
clearInterval(progressTimer);
clearTimeout(timeoutTimer);
clearTimeout(statusTimer);
progressTimer = null;
timeoutTimer = null;
statusTimer = null;
};
// 启动本地进度条动画,真实完成状态以后端任务轮询结果为准。
const startProgressAnimation = () => {
clearInterval(progressTimer);
progressTimer = setInterval(() => {
if (progress.value >= 90) {
clearInterval(progressTimer);
return;
}
const increment = Math.max(0.5, 2 - progress.value / 60);
progress.value = Math.min(90, progress.value + increment);
}, 500);
};
// 将 OTA 更新流程标记为失败并切换到失败页面。
const failUpdate = () => {
clearUpdateTimers();
isStartingUpdate.value = false;
currentState.value = STATES.FAILED;
};
// 将 OTA 更新流程标记为成功,进度补到 100% 后进入完成页面。
const completeUpdate = () => {
clearUpdateTimers();
isStartingUpdate.value = false;
progress.value = 100;
setTimeout(() => {
currentState.value = STATES.DONE;
}, 300);
};
// 轮询 OTA 更新任务状态,状态为处理中则继续轮询,成功或失败则结束流程。
const pollUpdateTaskStatus = (taskId) => {
clearTimeout(statusTimer);
statusTimer = setTimeout(async () => {
try {
const taskStatus = await getHardwareBoxTaskStatusAPI(taskId);
const status = Number(taskStatus?.status);
if (status === 2) {
completeUpdate();
return;
}
if (status === 3) {
failUpdate();
return;
}
if (status === 0 || status === 1) {
pollUpdateTaskStatus(taskId);
return;
}
failUpdate();
} catch (err) {
failUpdate();
}
}, 3000);
};
// 判断设备是否满足 OTA 更新条件,不满足时返回精确提示文案。
const getUpdateDisabledReason = (deviceStatus) => {
if (deviceStatus?.online !== true) return "请先开启智能弓";
if (Date.now() - Number(deviceStatus?.receivedAt || 0) > DEVICE_STATUS_STALE_TIME) {
return "设备状态同步中,请稍后重试";
}
if (String(deviceStatus?.netType || "").toLowerCase() !== "wifi") return "设备当前未连接 WiFi,请先连接 WiFi 后再更新";
return "";
};
// 获取 OTA 更新版本信息,优先使用首页跳转传入的数据,没有传参时再请求后端版本接口。
const getOtaVersionInfo = async () => { const getOtaVersionInfo = async () => {
if (routeOtaInfo.value.versionNumber && routeOtaInfo.value.resourceUrl) { if (routeOtaInfo.value.versionNumber && routeOtaInfo.value.resourceUrl) {
return { return {
@@ -474,100 +347,43 @@ const getOtaVersionInfo = async () => {
return getHardwareBoxVersionAPI(); return getHardwareBoxVersionAPI();
}; };
// 点击开始更新时先判断设备状态和版本信息,满足条件才发送 OTA 指令并开始轮询任务状态。 const startFirmwareUpdate = async () => {
const startUpdate = async () => { if (!fromFirmwareUpdate.value || !connectedWifi.value || otaUpdating.value) return;
if (isStartingUpdate.value) return;
if (!connectedWifi.value) return;
isStartingUpdate.value = true;
try { try {
const disabledReason = getUpdateDisabledReason(deviceStatus.value); const versionInfo = await getOtaVersionInfo();
if (disabledReason) {
isStartingUpdate.value = false;
uni.showToast({
title: disabledReason,
icon: "none",
});
return;
}
let versionInfo;
try {
versionInfo = await getOtaVersionInfo();
} catch (err) {
isStartingUpdate.value = false;
uni.showToast({
title: "获取更新版本失败,请重试",
icon: "none",
});
return;
}
if (!versionInfo?.needUpdate) { if (!versionInfo?.needUpdate) {
isStartingUpdate.value = false; firmwareMessage.value = "当前已是最新版本";
uni.showToast({ firmwareMessageVisible.value = true;
title: "当前已是最新版本",
icon: "none",
});
return; return;
} }
await startOtaUpdate({
currentState.value = STATES.UPDATING;
progress.value = 0;
startProgressAnimation();
timeoutTimer = setTimeout(() => {
if (currentState.value === STATES.UPDATING) {
failUpdate();
}
}, 5 * 60 * 1000);
const updateResult = await sendHardwareBoxUpdateAPI({
versionNumber: versionInfo.versionNumber, versionNumber: versionInfo.versionNumber,
wifiSsid: connectedWifi.value.SSID, wifiSsid: connectedWifi.value.SSID,
wifiPassword: connectedWifi.value.password || "", wifiPassword: connectedWifi.value.password || "",
resourceUrl: versionInfo.resourceUrl, resourceUrl: versionInfo.resourceUrl,
}); });
if (!updateResult?.taskId) { } catch (error) {
failUpdate(); firmwareMessage.value = "获取更新版本失败,请重试";
return; firmwareMessageVisible.value = true;
}
pollUpdateTaskStatus(updateResult.taskId);
} catch (err) {
failUpdate();
} }
}; };
// WebSocket 成功回调保留兜底能力,触发后直接按更新完成处理。 const clearFirmwareCountdown = () => {
const handleWsDone = () => { clearInterval(countdownTimer);
completeUpdate(); countdownTimer = null;
}; };
// WebSocket 失败回调保留兜底能力,触发后直接按更新失败处理。 const openFirmwareCountdown = () => {
const handleWsFail = () => { clearFirmwareCountdown();
failUpdate(); countdownSeconds.value = 3;
}; countdownVisible.value = true;
countdownTimer = setInterval(() => {
// 处理更新完成返回,兼容首页 OTA 弹窗入口和设备页普通入口。 countdownSeconds.value -= 1;
const handleDone = () => { if (countdownSeconds.value > 0) return;
const pages = getCurrentPages(); clearFirmwareCountdown();
const prevPage = pages[pages.length - 2]; countdownVisible.value = false;
const prevVm = prevPage?.$vm; void startFirmwareUpdate();
}, 1000);
if (prevVm && "otaState" in prevVm && "otaVisible" in prevVm) {
prevVm.otaState = "update_success";
prevVm.otaVisible = true;
}
uni.navigateBack({ delta: 1 });
};
const handleRetry = () => {
if (connectedWifi.value) {
currentState.value = STATES.CONNECTED;
} else {
startScanning();
}
}; };
// 监听系统输入法高度,用于让底部弹窗避开键盘遮挡。 // 监听系统输入法高度,用于让底部弹窗避开键盘遮挡。
@@ -585,8 +401,9 @@ const togglePasswordVisibility = () => {
}); });
}; };
// 页面加载时接收首页传入的 OTA 版本号和固件地址 // 页面加载时识别普通 WiFi 入口和固件更新入口
onLoad((options = {}) => { onLoad((options = {}) => {
fromFirmwareUpdate.value = options.source === "firmware-update";
routeOtaInfo.value = { routeOtaInfo.value = {
versionNumber: decodeURIComponent(options.versionNumber || ""), versionNumber: decodeURIComponent(options.versionNumber || ""),
resourceUrl: decodeURIComponent(options.resourceUrl || ""), resourceUrl: decodeURIComponent(options.resourceUrl || ""),
@@ -613,7 +430,7 @@ onUnmounted(() => {
uni.offKeyboardHeightChange(handleKeyboardHeightChange); uni.offKeyboardHeightChange(handleKeyboardHeightChange);
} }
cancelWifiConnectWaiting(); cancelWifiConnectWaiting();
clearUpdateTimers(); clearFirmwareCountdown();
wx.offGetWifiList && wx.offGetWifiList(); wx.offGetWifiList && wx.offGetWifiList();
}); });
</script> </script>
@@ -711,46 +528,6 @@ onUnmounted(() => {
</block> </block>
</scroll-view> </scroll-view>
<!-- CONNECTED开始更新按钮 -->
<view v-if="currentState === 'CONNECTED'" class="bottom-btn-area connected-bottom-btn-area">
<view class="primary-btn update-btn" @click="startUpdate">
<text class="primary-btn-text">开始更新</text>
</view>
</view>
</view>
<!-- UPDATING -->
<view v-else-if="currentState === 'UPDATING'" class="center-page">
<image src="https://static.shelingxingqiu.com/shootmini/static/ota/target-char.png" mode="aspectFit" style="width: 194rpx; height: 164rpx;" />
<text class="page-title" style="margin-top: 24rpx;">更新中,请稍等片刻...</text>
<view class="progress-wrap">
<view class="progress-track">
<view class="progress-fill" :style="{ width: progress + '%' }"></view>
</view>
<text class="progress-pct">{{ Math.floor(progress) }}%</text>
</view>
</view>
<!-- DONE -->
<view v-else-if="currentState === 'DONE'" class="center-page">
<image src="https://static.shelingxingqiu.com/shootmini/static/ota/check-char.png" mode="aspectFit" style="width: 194rpx; height: 166rpx;" />
<text class="page-title" style="margin-top: 24rpx;">更新完成</text>
<text class="page-desc-white">请关机并重启智能弓</text>
<view class="primary-btn done-btn" style="margin-top:20px" @click="handleDone">
<text class="primary-btn-text">完成</text>
</view>
</view>
<!-- FAILED -->
<view v-else-if="currentState === 'FAILED'" class="center-page">
<image src="https://static.shelingxingqiu.com/shootmini/static/ota/close-char.png" mode="aspectFit" style="width: 194rpx; height: 164rpx;" />
<text class="page-title fail-title" style="margin-top: 24rpx;">更新失败</text>
<text class="page-desc-white">请确保</text>
<text class="page-desc-white">1智能弓已开启</text>
<text class="page-desc-white">2网路连接稳定</text>
<view class="primary-btn done-btn" style="margin-top: 40rpx;" @click="handleRetry">
<text class="primary-btn-text">重试</text>
</view>
</view> </view>
<!-- CONNECTING 底部弹窗 --> <!-- CONNECTING 底部弹窗 -->
@@ -883,6 +660,46 @@ onUnmounted(() => {
</view> </view>
</view> </view>
</ScreenHint> </ScreenHint>
<ModalDialog
:show="countdownVisible"
title="WiFi连接成功"
content="3秒后将自动开始更新"
:confirmText="countdownButtonText"
:showCancel="false"
:confirmDisabled="true"
></ModalDialog>
<OtaModal
:visible="otaUpdating"
state="update_progress"
:progress="otaProgress"
:phase="otaPhase"
/>
<OtaModal
:visible="otaResultVisible && otaResultStatus === 'success'"
state="update_success"
@done="closeOtaResult"
/>
<ModalDialog
:show="otaResultVisible && otaResultStatus === 'failed'"
:title="otaResultTitle"
:content="otaResultContent"
confirmText="关闭"
:showCancel="false"
:onConfirm="closeOtaResult"
></ModalDialog>
<ModalDialog
:show="firmwareMessageVisible"
title="固件更新"
:content="firmwareMessage"
confirmText="关闭"
:showCancel="false"
:onConfirm="() => (firmwareMessageVisible = false)"
></ModalDialog>
</Container> </Container>
</template> </template>
+56 -70
View File
@@ -6,12 +6,12 @@ import AppFooter from "@/components/AppFooter.vue";
import UserHeader from "@/components/UserHeader.vue"; import UserHeader from "@/components/UserHeader.vue";
import Signin from "@/components/Signin.vue"; import Signin from "@/components/Signin.vue";
import BubbleTip from "@/components/BubbleTip.vue"; import BubbleTip from "@/components/BubbleTip.vue";
import ModalDialog from "@/components/ModalDialog.vue";
import OtaModal from "@/components/OtaModal.vue"; import OtaModal from "@/components/OtaModal.vue";
import { import {
checkUserBindAPI, checkUserBindAPI,
getAppConfig, getAppConfig,
getHardwareBoxTaskStatusAPI,
getHardwareBoxVersionAPI, getHardwareBoxVersionAPI,
getHomeData, getHomeData,
getMyDevicesAPI, getMyDevicesAPI,
@@ -69,8 +69,10 @@ const deviceCardAsset = computed(() => deviceCardAssets[deviceCardState.value]);
// OTA 相关 // OTA 相关
const otaVisible = ref(false); const otaVisible = ref(false);
const wifiRequiredVisible = ref(false);
const otaState = ref("new_version"); const otaState = ref("new_version");
const otaProgress = ref(0); const otaProgress = ref(0);
const otaPhase = ref("started");
const otaInfo = ref({ const otaInfo = ref({
versionNumber: "", versionNumber: "",
versionInfo: "", versionInfo: "",
@@ -81,31 +83,19 @@ const otaInfo = ref({
const isStartingOta = ref(false); const isStartingOta = ref(false);
let isCheckingOta = false; let isCheckingOta = false;
let otaCheckQueuedForOnline = false; let otaCheckQueuedForOnline = false;
let otaProgressTimer = null;
let otaStatusTimer = null;
let otaTimeoutTimer = null; let otaTimeoutTimer = null;
let otaResultTimer = null;
let otaStatusPollCount = 0;
let otaUpdateRunId = 0; let otaUpdateRunId = 0;
// 首页 OTA 轮询采用请求次数和总时长双重兜底,避免更新中状态长期卡住。 const OTA_UPDATE_TIMEOUT = 10 * 60 * 1000;
const OTA_TASK_STATUS_POLL_INTERVAL = 2000; const OTA_PROGRESS_EVENT = "/addons/shoot/otaProgress";
const OTA_TASK_STATUS_MAX_POLL_COUNT = 15; const OTA_RESULT_EVENT = "/addons/shoot/otaResult";
const OTA_TASK_STATUS_TIMEOUT = 30000;
// 清理首页 OTA 更新定时器,避免弹窗关闭或页面卸载后继续轮询 // 清理首页 OTA 更新超时计时器
const clearOtaUpdateTimers = () => { const clearOtaUpdateTimers = () => {
clearInterval(otaProgressTimer);
clearTimeout(otaStatusTimer);
clearTimeout(otaTimeoutTimer); clearTimeout(otaTimeoutTimer);
clearTimeout(otaResultTimer);
otaProgressTimer = null;
otaStatusTimer = null;
otaTimeoutTimer = null; otaTimeoutTimer = null;
otaResultTimer = null;
otaStatusPollCount = 0;
}; };
// 使当前 OTA 运行失效,确保旧请求返回后不会继续轮询或覆盖新状态。 // 使当前 OTA 运行失效,确保旧请求返回后不会覆盖新状态。
const invalidateOtaUpdateRun = () => { const invalidateOtaUpdateRun = () => {
otaUpdateRunId += 1; otaUpdateRunId += 1;
clearOtaUpdateTimers(); clearOtaUpdateTimers();
@@ -114,19 +104,6 @@ const invalidateOtaUpdateRun = () => {
const isOtaUpdateRunActive = (runId) => const isOtaUpdateRunActive = (runId) =>
runId === otaUpdateRunId && otaState.value === "update_progress"; runId === otaUpdateRunId && otaState.value === "update_progress";
// 启动首页 OTA 本地进度动画,最终成功失败以后端任务状态为准。
const startOtaProgressAnimation = () => {
clearInterval(otaProgressTimer);
otaProgressTimer = setInterval(() => {
if (otaProgress.value >= 90) {
clearInterval(otaProgressTimer);
return;
}
const increment = Math.max(0.5, 2 - otaProgress.value / 60);
otaProgress.value = Math.min(90, otaProgress.value + increment);
}, 500);
};
// 获取并保存后端返回的 OTA 版本信息,供弹窗展示和更新接口使用。 // 获取并保存后端返回的 OTA 版本信息,供弹窗展示和更新接口使用。
const applyOtaVersionInfo = (versionInfo) => { const applyOtaVersionInfo = (versionInfo) => {
otaInfo.value = { otaInfo.value = {
@@ -186,6 +163,7 @@ watch(online, (nextOnline, previousOnline) => {
const getOtaWifiUrl = () => { const getOtaWifiUrl = () => {
const { versionNumber, resourceUrl } = otaInfo.value; const { versionNumber, resourceUrl } = otaInfo.value;
const query = [ const query = [
"source=firmware-update",
`versionNumber=${encodeURIComponent(versionNumber)}`, `versionNumber=${encodeURIComponent(versionNumber)}`,
`resourceUrl=${encodeURIComponent(resourceUrl)}`, `resourceUrl=${encodeURIComponent(resourceUrl)}`,
].join("&"); ].join("&");
@@ -215,48 +193,40 @@ const completeHomeOtaUpdate = (runId) => {
isStartingOta.value = false; isStartingOta.value = false;
otaInfo.value = {...otaInfo.value, needUpdate: false}; otaInfo.value = {...otaInfo.value, needUpdate: false};
otaProgress.value = 100; otaProgress.value = 100;
const completedRunId = otaUpdateRunId; otaPhase.value = "installing";
otaResultTimer = setTimeout(() => {
otaResultTimer = null;
if (completedRunId !== otaUpdateRunId) return;
otaState.value = "update_success"; otaState.value = "update_success";
otaVisible.value = true; otaVisible.value = true;
}, 300);
}; };
// 轮询首页直接发起的 OTA 更新任务状态 // 首页只处理当前设备、当前目标版本的 OTA WebSocket 消息
const pollHomeOtaTaskStatus = async (taskId, runId) => { const handleHomeOtaSocketMessage = (message) => {
if (!isOtaUpdateRunActive(runId)) return; const runId = otaUpdateRunId;
if (!isOtaUpdateRunActive(runId) || Number(message?.code ?? 0) !== 0) return;
if (![OTA_PROGRESS_EVENT, OTA_RESULT_EVENT].includes(message?.event)) return;
otaStatusPollCount += 1; const messageDeviceId = String(message.data?.deviceId || "");
try { const currentDeviceId = String(device.value?.deviceId || "");
const taskStatus = await getHardwareBoxTaskStatusAPI(taskId); if (messageDeviceId && currentDeviceId && messageDeviceId !== currentDeviceId) return;
if (!isOtaUpdateRunActive(runId)) return;
const status = Number(taskStatus?.status); const messageVersion = String(message.data?.versionNumber || "");
if (status === 2) { const currentVersion = String(otaInfo.value.versionNumber || "");
if (messageVersion && currentVersion && messageVersion !== currentVersion) return;
if (message.event === OTA_PROGRESS_EVENT) {
const nextProgress = Math.min(
100,
Math.max(0, Number(message.data?.progress) || 0)
);
otaProgress.value = Math.max(otaProgress.value, nextProgress);
if (["started", "downloading", "installing"].includes(message.data?.phase)) {
otaPhase.value = message.data.phase;
}
return;
}
if (message.data?.status === "success") {
completeHomeOtaUpdate(runId); completeHomeOtaUpdate(runId);
return; } else if (message.data?.status === "failed") {
}
if (status === 3) {
failHomeOtaUpdate(runId);
return;
}
if (status === 0 || status === 1) {
if (otaStatusPollCount >= OTA_TASK_STATUS_MAX_POLL_COUNT) {
failHomeOtaUpdate(runId);
return;
}
otaStatusTimer = setTimeout(() => {
otaStatusTimer = null;
if (!isOtaUpdateRunActive(runId)) return;
void pollHomeOtaTaskStatus(taskId, runId);
}, OTA_TASK_STATUS_POLL_INTERVAL);
return;
}
failHomeOtaUpdate(runId);
} catch (err) {
if (!isOtaUpdateRunActive(runId)) return;
failHomeOtaUpdate(runId); failHomeOtaUpdate(runId);
} }
}; };
@@ -268,11 +238,11 @@ const startHomeOtaUpdate = async () => {
otaState.value = "update_progress"; otaState.value = "update_progress";
otaVisible.value = true; otaVisible.value = true;
otaProgress.value = 0; otaProgress.value = 0;
startOtaProgressAnimation(); otaPhase.value = "started";
otaTimeoutTimer = setTimeout(() => { otaTimeoutTimer = setTimeout(() => {
if (!isOtaUpdateRunActive(runId)) return; if (!isOtaUpdateRunActive(runId)) return;
failHomeOtaUpdate(runId); failHomeOtaUpdate(runId);
}, OTA_TASK_STATUS_TIMEOUT); }, OTA_UPDATE_TIMEOUT);
try { try {
const updateResult = await sendHardwareBoxUpdateAPI({ const updateResult = await sendHardwareBoxUpdateAPI({
@@ -286,14 +256,13 @@ const startHomeOtaUpdate = async () => {
failHomeOtaUpdate(runId); failHomeOtaUpdate(runId);
return; return;
} }
void pollHomeOtaTaskStatus(updateResult.taskId, runId);
} catch (err) { } catch (err) {
if (!isOtaUpdateRunActive(runId)) return; if (!isOtaUpdateRunActive(runId)) return;
failHomeOtaUpdate(runId); failHomeOtaUpdate(runId);
} }
}; };
// 点击立即更新时先判断设备是否在线并已通过 WiFi 联网,联网则首页直接更新,否则跳转 WiFi 页面 // 点击立即更新时先判断设备是否在线并已通过 WiFi 联网,联网时先展示连接引导
const handleOtaUpdate = async () => { const handleOtaUpdate = async () => {
if (isStartingOta.value) return; if (isStartingOta.value) return;
isStartingOta.value = true; isStartingOta.value = true;
@@ -327,6 +296,12 @@ const handleOtaUpdate = async () => {
isStartingOta.value = false; isStartingOta.value = false;
otaVisible.value = false; otaVisible.value = false;
wifiRequiredVisible.value = true;
};
// 从首页固件更新提示进入 WiFi 配置页,并继续沿用当前版本信息。
const goWifiForOtaUpdate = () => {
wifiRequiredVisible.value = false;
uni.navigateTo({ url: getOtaWifiUrl() }); uni.navigateTo({ url: getOtaWifiUrl() });
}; };
@@ -480,12 +455,14 @@ onShow(async (options) => {
}); });
onMounted(async () => { onMounted(async () => {
uni.$on("socket-inbox", handleHomeOtaSocketMessage);
const config = await getAppConfig(); const config = await getAppConfig();
updateConfig(config); updateConfig(config);
console.log("全局配置:", config); console.log("全局配置:", config);
}); });
onUnmounted(() => { onUnmounted(() => {
uni.$off("socket-inbox", handleHomeOtaSocketMessage);
invalidateOtaUpdateRun(); invalidateOtaUpdateRun();
}); });
@@ -515,6 +492,7 @@ onShareTimeline(() => {
:state="otaState" :state="otaState"
:version="otaInfo.versionNumber" :version="otaInfo.versionNumber"
:progress="otaProgress" :progress="otaProgress"
:phase="otaPhase"
:description="''" :description="''"
:changelog="otaInfo.versionInfo" :changelog="otaInfo.versionInfo"
:forceUpdate="otaInfo.forceUpdate" :forceUpdate="otaInfo.forceUpdate"
@@ -524,6 +502,14 @@ onShareTimeline(() => {
@done="handleOtaDone" @done="handleOtaDone"
@retry="handleOtaRetry" @retry="handleOtaRetry"
/> />
<ModalDialog
:show="wifiRequiredVisible"
title="固件更新"
content="请在WiFi网络下更新"
confirmText="连接WiFi"
:showCancel="false"
:onConfirm="goWifiForOtaUpdate"
/>
<view class="container"> <view class="container">
<view class="top-theme"> <view class="top-theme">
<!-- <image <!-- <image
Binary file not shown.

Before

Width:  |  Height:  |  Size: 90 KiB

After

Width:  |  Height:  |  Size: 21 KiB

+2
View File
@@ -19,6 +19,7 @@ const getDefaultDevice = () => ({
const getDefaultDeviceStatus = () => ({ const getDefaultDeviceStatus = () => ({
battery: null, battery: null,
charging: false,
version: "", version: "",
online: false, online: false,
netType: "", netType: "",
@@ -168,6 +169,7 @@ export default defineStore("store", {
battery: Number.isFinite(battery) battery: Number.isFinite(battery)
? Math.min(100, Math.max(0, battery)) ? Math.min(100, Math.max(0, battery))
: null, : null,
charging: status.charging === true,
version: String(status.version ?? "").trim(), version: String(status.version ?? "").trim(),
online, online,
netType: String(status.netType ?? "").trim().toLowerCase(), netType: String(status.netType ?? "").trim().toLowerCase(),
+6 -1
View File
@@ -87,7 +87,12 @@ function createWebSocket(token, onMessage) {
const { data, event, code, timestamp } = response || {}; const { data, event, code, timestamp } = response || {};
if (event === "pong") return; if (event === "pong") return;
if (event === "/addons/shoot/battery") { const passthroughEvents = [
"/addons/shoot/battery",
"/addons/shoot/otaProgress",
"/addons/shoot/otaResult",
];
if (passthroughEvents.includes(event)) {
if ((code == null || Number(code) === 0) && onMessage && data && typeof data === "object") { if ((code == null || Number(code) === 0) && onMessage && data && typeof data === "object") {
onMessage({ event, data, code, timestamp }); onMessage({ event, data, code, timestamp });
} }