SEC_Warehouse/pages/device/config.vue

848 lines
19 KiB
Vue
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<template>
<view class="page">
<view class="top-nav top-nav-base">
<text class="back" @click="goBack"></text>
<text class="title">设备配置</text>
</view>
<view class="search-wrap">
<view class="search-btn" :class="{ 'is-searching': isSearching }" @click="toggleSearch">
<text>{{ searchBtnText }}</text>
</view>
</view>
<view class="tip-row">
*手机需开启蓝牙功能Android手机还需开启定位功能
</view>
<view class="list-header">
<text class="list-title">搜索到的设备列表</text>
</view>
<view class="list-body">
<view v-if="!deviceList.length" class="empty-row">暂无搜索结果</view>
<view v-for="device in deviceList" :key="device.deviceId" class="device-card">
<view class="device-icon"></view>
<view class="device-main">
<view class="device-name-row">
<text class="device-name">{{ device.showName }}</text>
<text v-if="device.hasTargetService" class="device-tag">00F4</text>
<text v-else-if="device.matchedByName || device.matchedByPayload" class="device-tag name-tag">名称匹配
</text>
</view>
<text class="device-id">{{ device.deviceId }}</text>
<view class="device-actions">
<view class="action-btn" :class="{ disabled: isDevicePreparing(device.deviceId) }"
@click.stop="openWifiPanel(device.deviceId)">
{{ isDevicePreparing(device.deviceId) ? '鉴权中' : '网络配置' }}
</view>
<view class="action-btn">参数配置</view>
<view class="action-btn">服务器配置</view>
</view>
</view>
</view>
</view>
<view v-if="wifiPanelVisible" class="wifi-mask" @click="closeWifiPanel">
<view class="wifi-dialog" @click.stop>
<view class="wifi-dialog-header">
<text class="wifi-dialog-title">设备网络设置</text>
<text class="wifi-dialog-close" @click="closeWifiPanel">×</text>
</view>
<view class="wifi-device-row">
<text class="wifi-device-label">设备</text>
<text class="wifi-device-value">{{ selectedDeviceName }}</text>
</view>
<view class="wifi-row wifi-row-ssid">
<text class="wifi-label">
<text class="wifi-required">*</text>
WiFi名称
</text>
<input
v-model.trim="wifiForm.ssid"
class="wifi-input wifi-input-ssid"
placeholder="请输入 WiFi 名称"
:maxlength="32"
confirm-type="done"
/>
<view class="wifi-current-btn" :class="{ disabled: fetchingCurrentWifi }" @click.stop="fetchCurrentWifiSsid">
{{ fetchingCurrentWifi ? '获取中...' : '一键获取当前连接WiFi' }}
</view>
</view>
<view class="wifi-row">
<text class="wifi-label">
<text class="wifi-required">*</text>
WiFi密码
</text>
<input
v-model.trim="wifiForm.password"
class="wifi-input"
placeholder="请输入密码"
password
:maxlength="63"
confirm-type="done"
/>
</view>
<view class="wifi-import-row" @click="importLastWifiConfig">
一键导入上次 WiFi 配置
</view>
<view class="wifi-submit-btn" :class="{ disabled: wifiSending }" @click="confirmWifiSettings">
{{ wifiSending ? '发送中...' : '发送' }}
</view>
</view>
</view>
</view>
</template>
<script>
import { createBluetoothDiscovery } from '@/hooks/useBluetoothDiscovery'
import { navigateBack } from '@/utils/navigation'
import { showToast } from '@/utils/toast'
const WIFI_HISTORY_STORAGE_KEY = 'SMARTHOME_LAST_WIFI_CONFIG'
const WIFI_STATE_MESSAGES = Object.freeze({
1: 'WiFi 参数校验失败,请检查名称与密码',
2: '设备连接该 WiFi 失败,请确认密码是否正确',
3: 'WiFi 配置成功',
4: '设备正在连接 WiFi请稍候'
})
function getErrorMessage(error) {
if (!error) {
return '操作失败,请重试'
}
if (typeof error === 'string') {
return error
}
return error.message || error.errMsg || '操作失败,请重试'
}
function promisifyUniApi(apiName, params = {}) {
return new Promise((resolve, reject) => {
if (typeof uni[apiName] !== 'function') {
reject(new Error(`当前环境不支持 ${apiName}`))
return
}
uni[apiName]({
...params,
success: (res) => resolve(res),
fail: (err) => reject(err)
})
})
}
export default {
data() {
return {
isSearching: false,
deviceList: [],
deviceMap: {},
discoveryController: null,
// WiFi 弹层状态。
wifiPanelVisible: false,
wifiPreparing: false,
activePreparingDeviceId: '',
wifiSending: false,
fetchingCurrentWifi: false,
wifiPrepared: false,
devicePreparingMap: {},
selectedWifiDevice: null,
wifiForm: {
ssid: '',
password: ''
}
}
},
computed: {
searchBtnText() {
return this.isSearching ? '搜索中' : '搜索'
},
selectedDeviceName() {
if (!this.selectedWifiDevice) {
return '未选择设备'
}
return this.selectedWifiDevice.showName || this.selectedWifiDevice.deviceId || '未命名设备'
}
},
created() {
/**
* 蓝牙搜索控制器统一处理设备发现、连接、鉴权、WiFi 发送等流程。
*/
this.discoveryController = createBluetoothDiscovery({
onSearchingChange: (value) => {
this.isSearching = value
},
onDeviceMapChange: (value) => {
this.deviceMap = value
},
onDeviceListChange: (value) => {
this.deviceList = value
}
})
},
onHide() {
this.cleanupDiscovery()
},
onUnload() {
this.cleanupDiscovery()
},
methods: {
async safeDisconnect() {
if (!this.discoveryController) {
return
}
try {
await this.discoveryController.disconnectDevice()
} catch (error) {
}
},
cleanupWifiPanelState() {
this.wifiPanelVisible = false
this.wifiPrepared = false
this.wifiPreparing = false
this.activePreparingDeviceId = ''
this.fetchingCurrentWifi = false
this.selectedWifiDevice = null
this.resetWifiForm()
},
resetWifiForm() {
// 只清空当前弹层临时输入,不影响本地历史缓存。
this.wifiForm.ssid = ''
this.wifiForm.password = ''
},
setDevicePreparing(deviceId, preparing) {
const safeDeviceId = String(deviceId || '').trim()
if (!safeDeviceId) {
return
}
this.devicePreparingMap = {
...this.devicePreparingMap,
[safeDeviceId]: Boolean(preparing)
}
},
isDevicePreparing(deviceId) {
const safeDeviceId = String(deviceId || '').trim()
if (!safeDeviceId) {
return false
}
return Boolean(this.devicePreparingMap[safeDeviceId])
},
getDeviceById(deviceId) {
const safeDeviceId = String(deviceId || '').trim()
if (!safeDeviceId) {
return null
}
const mapDevice = this.deviceMap[safeDeviceId]
if (mapDevice) {
return mapDevice
}
return this.deviceList.find((item) => item.deviceId === safeDeviceId) || null
},
cleanupDiscovery() {
if (!this.discoveryController) {
return
}
this.devicePreparingMap = {}
this.cleanupWifiPanelState()
this.discoveryController.cleanupDiscovery()
},
goBack() {
this.cleanupDiscovery()
navigateBack(1)
},
async toggleSearch() {
if (!this.discoveryController) {
return
}
if (this.isSearching) {
await this.discoveryController.stopSearch(false)
return
}
try {
await this.discoveryController.startSearch()
} catch (error) {
}
},
async openWifiPanel(deviceId) {
if (this.wifiPreparing || this.wifiSending) {
return
}
if (!this.discoveryController) {
return
}
const targetDeviceId = String(deviceId || '').trim()
if (!targetDeviceId) {
showToast('未选择可配置设备')
return
}
if (this.activePreparingDeviceId && this.activePreparingDeviceId !== targetDeviceId) {
showToast('正在为其他设备鉴权,请稍候')
return
}
const targetDevice = this.getDeviceById(targetDeviceId)
if (!targetDevice) {
showToast('设备已失效,请重新搜索')
return
}
this.wifiPreparing = true
this.activePreparingDeviceId = targetDeviceId
this.wifiPrepared = false
this.selectedWifiDevice = targetDevice
this.setDevicePreparing(targetDeviceId, true)
uni.showLoading({
title: '密钥鉴权中',
mask: true
})
try {
/**
* 先按项目固定已知密钥规则MAC+0000完成鉴权成功后再允许进入 WiFi 弹层。
*/
await this.discoveryController.prepareWifiConfig(targetDeviceId, {
suffix: '0000',
timeout: 8000,
msgTimeout: 4000
})
this.wifiPrepared = true
this.wifiPanelVisible = true
// 确保 Vue 完成 DOM 更新后再调原生 toast避免原生层覆盖 Vue 弹层
await this.$nextTick()
showToast('密钥鉴权成功请填写WiFi信息')
} catch (error) {
showToast(getErrorMessage(error))
await this.safeDisconnect()
} finally {
this.setDevicePreparing(targetDeviceId, false)
this.activePreparingDeviceId = ''
this.wifiPreparing = false
uni.hideLoading()
}
},
async closeWifiPanel(force = false) {
if (!force && (this.wifiSending || this.wifiPreparing)) {
return
}
this.cleanupWifiPanelState()
await this.safeDisconnect()
},
async fetchCurrentWifiSsid() {
if (this.fetchingCurrentWifi) {
return
}
this.fetchingCurrentWifi = true
try {
// 启动 WiFi 模块(部分端调用 getConnectedWifi 前必须先 startWifi
if (typeof uni.startWifi === 'function') {
try {
await promisifyUniApi('startWifi')
} catch (error) {
// 已启动等非致命错误忽略,继续尝试读取当前连接。
}
}
const result = await promisifyUniApi('getConnectedWifi')
const ssid = String(result?.wifi?.SSID || result?.wifi?.ssid || result?.SSID || '').trim()
if (!ssid || ssid.toLowerCase().includes('unknown')) {
throw new Error('未获取到当前连接 WiFi 名称')
}
this.wifiForm.ssid = ssid
showToast('已填入当前连接WiFi')
} catch (error) {
showToast(getErrorMessage(error))
} finally {
this.fetchingCurrentWifi = false
}
},
importLastWifiConfig() {
try {
const cached = uni.getStorageSync(WIFI_HISTORY_STORAGE_KEY)
if (!cached || typeof cached !== 'object') {
showToast('暂无上次 WiFi 配置')
return
}
const ssid = String(cached.ssid || '').trim()
const password = String(cached.password || '').trim()
if (!ssid || !password) {
showToast('暂无可用的历史 WiFi 配置')
return
}
this.wifiForm.ssid = ssid
this.wifiForm.password = password
showToast('已导入上次 WiFi 配置')
} catch (error) {
showToast('读取历史 WiFi 配置失败')
}
},
cacheWifiConfig(ssid, password) {
try {
uni.setStorageSync(WIFI_HISTORY_STORAGE_KEY, {
ssid,
password,
updatedAt: Date.now()
})
} catch (error) {
}
},
getWifiStateMessage(stateCode) {
return WIFI_STATE_MESSAGES[stateCode] || `WiFi 状态码异常: ${stateCode}`
},
async confirmWifiSettings() {
if (this.wifiSending) {
return
}
if (!this.wifiPrepared) {
showToast('请先完成密钥鉴权')
return
}
const ssid = String(this.wifiForm.ssid || '').trim()
const password = String(this.wifiForm.password || '').trim()
if (!ssid) {
showToast('请输入 WiFi 名称')
return
}
if (!password) {
showToast('请输入 WiFi 密码')
return
}
this.wifiSending = true
let needAutoClose = false
let needCacheWifi = false
let tipMessage = ''
try {
/**
* 发送后必须等待设备通过 UUID_STATE 返回最终结果1/2/3
* 才进行提示并自动关闭弹层。
*/
const wifiResult = await this.discoveryController.configureWifi(ssid, password, {
timeout: 12000
})
const stateMessage = this.getWifiStateMessage(wifiResult.stateCode)
tipMessage = stateMessage
needAutoClose = true
needCacheWifi = Boolean(wifiResult.success)
} catch (error) {
// 超时/异常场景表示尚未拿到有效设备结果,保持弹层打开。
tipMessage = getErrorMessage(error)
} finally {
this.wifiSending = false
if (tipMessage) {
showToast(tipMessage)
}
if (needCacheWifi) {
this.cacheWifiConfig(ssid, password)
}
if (needAutoClose) {
await this.closeWifiPanel(true)
}
}
}
}
}
</script>
<style>
@import '@/styles/common.css';
.page {
min-height: 100vh;
background: #e9eaed;
}
.top-nav {
border-bottom: 1rpx solid #ececec;
}
.back {
position: absolute;
left: 24rpx;
top: 30rpx;
font-size: 64rpx;
color: #111111;
width: 64rpx;
line-height: 64rpx;
text-align: center;
}
.title {
font-size: 50rpx;
font-weight: 700;
color: #2a2d33;
}
.search-wrap {
height: 500rpx;
background: #ffffff;
display: flex;
justify-content: center;
align-items: center;
}
.search-btn {
width: 260rpx;
height: 260rpx;
border-radius: 130rpx;
background: #43c996;
color: #ffffff;
font-size: 56rpx;
font-weight: 600;
display: flex;
align-items: center;
justify-content: center;
transition: transform 0.2s ease;
}
.search-btn:active {
transform: scale(0.97);
}
.search-btn.is-searching {
animation: searchPulse 1.2s ease-in-out infinite;
}
@keyframes searchPulse {
0% {
transform: scale(1);
box-shadow: 0 0 0 0 rgba(67, 201, 150, 0.42);
}
70% {
transform: scale(1.04);
box-shadow: 0 0 0 30rpx rgba(67, 201, 150, 0);
}
100% {
transform: scale(1);
box-shadow: 0 0 0 0 rgba(67, 201, 150, 0);
}
}
.tip-row {
min-height: 78rpx;
padding: 12rpx 16rpx;
background: #efeff1;
color: #ff0000;
font-size: 34rpx;
font-weight: 600;
display: flex;
align-items: center;
}
.list-header {
height: 116rpx;
background: #ffffff;
display: flex;
align-items: center;
padding: 0 38rpx;
}
.list-title {
font-size: 52rpx;
color: #101217;
font-weight: 700;
}
.list-body {
min-height: calc(100vh - 814rpx);
background: #e9eaed;
padding-bottom: 30rpx;
}
.empty-row {
padding: 36rpx;
text-align: center;
color: #8c9097;
font-size: 30rpx;
}
.device-card {
background: #ffffff;
margin-top: 12rpx;
padding: 24rpx;
display: flex;
gap: 20rpx;
}
.device-icon {
width: 92rpx;
height: 92rpx;
border-radius: 46rpx;
border: 2rpx solid #d8d8d8;
box-shadow: inset 0 0 0 10rpx #f1f1f1;
flex-shrink: 0;
}
.device-main {
flex: 1;
min-width: 0;
}
.device-name-row {
display: flex;
align-items: center;
gap: 12rpx;
}
.device-name {
flex: 1;
min-width: 0;
font-size: 38rpx;
color: #30343a;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.device-tag {
font-size: 22rpx;
color: #17b474;
border: 1rpx solid #17b474;
border-radius: 20rpx;
padding: 2rpx 10rpx;
}
.name-tag {
color: #2f7de1;
border-color: #2f7de1;
}
.device-id {
display: block;
margin-top: 8rpx;
font-size: 30rpx;
color: #8a8f98;
word-break: break-all;
}
.device-actions {
display: flex;
gap: 10rpx;
margin-top: 16rpx;
}
.action-btn {
padding: 8rpx 16rpx;
border: 2rpx solid #42c995;
color: #22b47a;
font-size: 30rpx;
border-radius: 6rpx;
background: #f8fffc;
}
.action-btn.disabled {
border-color: #9fdcc3;
color: #7db89e;
background: #f5faf7;
}
.wifi-mask {
position: fixed;
inset: 0;
background: rgba(0, 0, 0, 0.48);
display: flex;
align-items: flex-end;
justify-content: center;
z-index: 999;
}
.wifi-dialog {
width: 100%;
background: #ffffff;
border-radius: 28rpx 28rpx 0 0;
overflow: hidden;
}
.wifi-dialog-header {
height: 108rpx;
border-bottom: 1rpx solid #efefef;
position: relative;
display: flex;
justify-content: center;
align-items: center;
}
.wifi-dialog-title {
font-size: 42rpx;
color: #2d2f33;
font-weight: 700;
}
.wifi-dialog-close {
position: absolute;
right: 26rpx;
top: 18rpx;
width: 72rpx;
height: 72rpx;
text-align: center;
line-height: 72rpx;
font-size: 56rpx;
color: #b8bcc3;
}
.wifi-device-row {
min-height: 74rpx;
display: flex;
align-items: center;
gap: 14rpx;
padding: 0 30rpx;
border-bottom: 1rpx solid #f4f4f4;
}
.wifi-device-label {
font-size: 28rpx;
color: #8a8f98;
}
.wifi-device-value {
flex: 1;
min-width: 0;
font-size: 27rpx;
color: #4a4f56;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.wifi-row {
min-height: 102rpx;
border-bottom: 1rpx solid #f2f2f2;
display: flex;
align-items: center;
padding: 0 30rpx;
gap: 20rpx;
}
.wifi-row-ssid {
align-items: center;
}
.wifi-label {
width: 170rpx;
font-size: 34rpx;
color: #363b45;
}
.wifi-required {
color: #ff4f4f;
margin-right: 8rpx;
}
.wifi-input {
flex: 1;
min-width: 0;
height: 80rpx;
font-size: 32rpx;
color: #1f2329;
}
.wifi-input-ssid {
max-width: 260rpx;
}
.wifi-current-btn {
flex-shrink: 0;
min-width: 190rpx;
height: 62rpx;
line-height: 62rpx;
border: 1rpx solid #74dcb2;
border-radius: 8rpx;
color: #24b478;
background: #effcf5;
text-align: center;
font-size: 24rpx;
padding: 0 12rpx;
}
.wifi-current-btn.disabled {
border-color: #b8d8ca;
color: #9bbbae;
background: #f3f6f4;
}
.wifi-import-row {
min-height: 100rpx;
border-bottom: 1rpx solid #f2f2f2;
font-size: 34rpx;
color: #3bc58d;
display: flex;
align-items: center;
justify-content: center;
}
.wifi-submit-btn {
height: 100rpx;
background: #11c462;
color: #ffffff;
font-size: 36rpx;
font-weight: 600;
display: flex;
align-items: center;
justify-content: center;
}
.wifi-submit-btn.disabled {
background: #8edcae;
}
</style>