feat: 完成wifi锁配网与绑定相关逻辑

This commit is contained in:
范鹏 2025-04-08 15:33:12 +08:00
parent 1c93dc914b
commit ed76f58db0
11 changed files with 372 additions and 276 deletions

View File

@ -8,7 +8,8 @@ module.exports = {
globals: {
uni: 'writable',
getApp: 'writable',
wx: 'writable'
wx: 'writable',
getCurrentPages: 'writable'
},
// 指定如何解析语法
parser: 'vue-eslint-parser',
@ -41,17 +42,15 @@ module.exports = {
'no-var': 'error', // 要求使用 let 或 const 而不是 var
'no-multiple-empty-lines': ['error', { max: 1 }], // 不允许多个空行
'prefer-const': 'off', // 使用 let 关键字声明但在初始分配后从未重新分配的变量,要求使用 const
'no-use-before-define': 'error', // 禁止在 函数/类/变量 定义之前使用它们
'no-use-before-define': 'off', // 禁止在 函数/类/变量 定义之前使用它们
'no-irregular-whitespace': 'off', // 禁止不规则的空白
'no-undef': 'error', // 禁止使用未声明的变量
'vue/script-setup-uses-vars': 'off', // 关闭此规则因为它可能会干扰no-undef的检测
'no-unused-vars': 'error', // 禁止出现未使用过的变量
'vue/script-setup-uses-vars': 'error', // 确保script setup中的变量必须正确定义
'vue/no-undef-components': 'off', // 关闭组件未定义的检查
'vue/no-undef-properties': [
'error',
{
ignore: ['getDeviceInfo', 'getBluetoothDevices', 'stopGetBluetoothDevices']
}
], // 忽略特定方法的未定义检查
'vue/no-undef-properties': 'off', // 关闭属性未定义的检查
'vue/no-unused-vars': 'error', // 禁止Vue组件中出现未使用的变量
'import/no-unused-modules': 'off', // 关闭模块导出检查
'import/no-cycle': 0,
'no-nested-ternary': 0,
'import/prefer-default-export': 0,

View File

@ -9,14 +9,17 @@ uni.getSystemInfo({
const DEV = {
name: 'dev',
baseUrl: 'https://dev.lock.star-lock.cn/api',
webviewBaseUrl: 'https://dev.lock.star-lock.cn',
appName: '星星锁Lite',
baseUrl: 'https://lock.dev.star-lock.cn/api',
webviewBaseUrl: 'https://lock.dev.star-lock.cn',
version,
buildNumber
}
const PRE = {
name: 'pre',
baseUrl: 'https://pre.lock.star-lock.cn/api',
appName: '星星锁Lite',
baseUrl: 'https://lock.pre.star-lock.cn/api',
webviewBaseUrl: 'https://lock.xhjcn.ltd',
version,
buildNumber
@ -24,6 +27,7 @@ const PRE = {
const XHJ = {
name: 'xhj',
appName: '星星锁Lite',
baseUrl: 'https://lock.xhjcn.ltd/api',
webviewBaseUrl: 'https://lock.xhjcn.ltd',
version,
@ -32,6 +36,7 @@ const XHJ = {
const SKY = {
name: 'sky',
appName: '星星锁Lite',
baseUrl: 'https://lock.skychip.top/api',
webviewBaseUrl: 'https://lock.skychip.top',
version,
@ -40,6 +45,7 @@ const SKY = {
const GE = {
name: 'ge',
appName: '星星锁Lite',
baseUrl: 'http://lock.ge.star-lock.cn/api',
webviewBaseUrl: 'http://lock.ge.star-lock.cn',
version,

View File

@ -12,10 +12,10 @@
</template>
<script setup>
import { useBluetoothStore } from '@/stores/bluetooth'
import { useBasicStore } from '@/stores/basic'
import { onLoad } from '@dcloudio/uni-app'
import { ref } from 'vue'
import { useBluetoothStore } from '@/stores/bluetooth'
import { useBasicStore } from '@/stores/basic'
const bluetoothStore = useBluetoothStore()
const basicStore = useBasicStore()

View File

@ -134,6 +134,9 @@
address: this.currentLockInfo.position.address
}
}
if (this.currentLockInfo.tencentYunLock) {
params.tencentYunLock = this.currentLockInfo.tencentYunLock
}
const { code, message } = await bindLockAdmin(params)
console.log('添加锁返回', code, message)
if (code === 0) {

View File

@ -1,212 +1,163 @@
<template>
<view>
<view class="mt-4">
<up-steps :current="current" activeColor="#63b8af" class="custom-steps">
<up-steps-item title="设置WiFi" :itemStyle="{ fontSize: '48rpx' }"> </up-steps-item>
<up-steps-item title="连接设备蓝牙" :itemStyle="{ fontSize: '48rpx' }"></up-steps-item>
<up-steps-item title="开始配网" :itemStyle="{ fontSize: '48rpx' }"></up-steps-item>
</up-steps>
<view class="mt-8 mx-8 flex flex-col h-[calc(100vh-300rpx)]">
<view v-if="current === 0">
<view class="text-lg font-bold mb-4">请选择WiFi并输入密码</view>
<view class="pt-2 pb-3 border-b-2 border-b-solid border-gray-200">
<picker
mode="selector"
:range="wifiList"
:value="wifiIndex"
@change="changeWifi"
range-key="SSID"
>
<view class="flex items-center">
<view class="mr-4">WiFi</view>
<view>{{ wifiList[wifiIndex]?.SSID ?? '加载中...' }}</view>
<view class="ml-a">
<up-icon name="arrow-right" size="24rpx"></up-icon>
</view>
</view>
</picker>
</view>
<view class="py-2 border-b-2 border-b-solid border-gray-200 flex items-center">
<view>密码</view>
<view class="flex-1">
<!-- <up-input
:customStyle="{
padding: '0 28rpx',
outline: 'none',
height: '80rpx',
backgroundColor: '#FFFFFF',
border: 0
}"
placeholder-class="!text-base !line-height-[80rpx]"
v-model="password"
placeholder="请输入密码"
:type="showPassword ? 'text' : 'password'"
>
<template #suffix>
<up-icon
:name="showPassword ? 'eye-fill' : 'eye-off'"
size="42rpx"
@click="togglePassword"
></up-icon>
</template>
</up-input> -->
</view>
</view>
</view>
<view v-if="current === 1" class="flex flex-col h-[calc(100vh-230rpx)]">
<view class="text-lg font-bold mb-2">请连接设备蓝牙</view>
<view class="text-[#999999]">已发现设备如下</view>
<scroll-view scroll-y class="flex-1 mt-4 overflow-hidden">
<view
v-for="item in deviceList"
:key="item.deviceId"
@click="connectDevice(item)"
class="bg-[#efedf1] rounded-xl py-4 px-3 mt-2 flex justify-between"
>
<view>{{ item.name }}</view>
<view class="text-[#63b8af]">连接</view>
</view>
</scroll-view>
<view class="flex justify-center items-center mt-2">
<up-loading-icon
size="70rpx"
text="搜索中"
:vertical="true"
textSize="28rpx"
></up-loading-icon>
</view>
</view>
<view v-if="current === 2">
<view class="flex justify-center mt-10">
<image
src="https://oss-lock.xhjcn.ltd/mp/cloud_server.png"
mode="aspectFill"
class="w-200rpx h-200rpx p-4"
></image>
</view>
<view
v-for="(item, index) in stepList"
:key="item"
class="flex items-center mt-4 justify-center w-full"
<view class="mt-18 mx-8 flex flex-col">
<view class="text-lg font-bold mb-4">请选择WiFi并输入密码</view>
<view class="pt-2 pb-3 border-b-2 border-b-solid border-gray-200">
<picker
mode="selector"
:range="wifiList"
:value="wifiIndex"
@change="changeWifi"
range-key="SSID"
>
<view class="flex items-center justify-start w-400rpx">
<up-loading-icon mode="circle" v-if="step < index + 1" size="36rpx"></up-loading-icon>
<up-icon name="checkbox-mark" color="#63b8af" size="36rpx" v-else></up-icon>
<view class="ml-3">{{ item }}</view>
<view class="flex items-center">
<view class="mr-4">WiFi</view>
<view>{{ wifiList[wifiIndex]?.SSID ?? '搜索中...' }}</view>
<view class="ml-a">
<up-icon name="arrow-right" size="24rpx"></up-icon>
</view>
</view>
</picker>
</view>
<view class="py-2 border-b-2 border-b-solid border-gray-200 flex items-center">
<view>密码</view>
<view class="flex-1">
<up-input
:customStyle="{
padding: '0 28rpx',
outline: 'none',
height: '80rpx',
backgroundColor: '#FFFFFF',
border: 0
}"
:maxlength="20"
placeholder-class="!text-base !line-height-[80rpx]"
placeholder="请输入密码"
:type="showPassword ? 'text' : 'password'"
@change="handleInput"
>
<template #suffix>
<up-icon
:name="showPassword ? 'eye-fill' : 'eye-off'"
size="42rpx"
@click="togglePassword"
></up-icon>
</template>
</up-input>
</view>
</view>
</view>
<view
v-if="current === 0"
class="fixed bottom-[calc(env(safe-area-inset-bottom)+32rpx)] w-686rpx mx-4 h-88rpx text-center text-white bg-[#63b8af] leading-[88rpx] rounded-44rpx font-bold"
@click="handleNext"
>下一步</view
@click="connectWifi"
>
连接
</view>
</view>
</view>
</template>
<script setup>
import { onMounted, ref } from 'vue'
import { onMounted, onUnmounted, ref } from 'vue'
import { useBluetoothStore } from '@/stores/bluetooth'
// import { useUserStore } from '@/stores/user'
import { useBasicStore } from '@/stores/basic'
import { passthrough } from '@/api/sdk'
const $bluetooth = useBluetoothStore()
// const $user = useUserStore()
const $basic = useBasicStore()
const current = ref(0)
const wifiList = ref([])
const wifiIndex = ref()
const password = ref('')
const step = ref(1)
const deviceList = ref([])
const showPassword = ref(false)
const stepList = ref([
'手机与设备连接成功',
'向设备发送信息成功',
'设备连接云端成功',
'初始化成功'
])
const pending = ref(false)
const wifiInfo = ref({
SSID: '',
password: ''
onMounted(async () => {
uni.showLoading({
title: '搜索中'
})
// const result = await $bluetooth.getWifiList({
// uid: $user.userInfo.uid.toString()
// })
// if (result.code !== 0) {
// uni.showModal({
// title: '',
// content: '',
// showCancel: false,
// success: () => {
// uni.navigateBack()
// }
// })
// }
listenEvent()
setTimeout(() => {
uni.hideLoading()
wifiList.value = [
{
SSID: '测试1',
rssi: 10
},
{
SSID: '测试2',
rssi: 20
},
{
SSID: '测试3',
rssi: 30
}
]
wifiIndex.value = 0
}, 2000)
})
const deviceInfo = $basic.deviceInfo
onUnmounted(() => {
uni.$off('wifiList')
uni.$off('distributionNetworkResult')
})
onMounted(() => {
if (deviceInfo.platform !== 'android' && deviceInfo.platform !== 'ios') {
uni.showToast({
title: '当前设备不支持WiFi功能',
icon: 'none'
})
return
}
uni.authorize({
scope: 'scope.userLocation',
success: () => {
const getWifiListFn = () => {
uni.getWifiList({
success: () => {
uni.onGetWifiList(res => {
const uniqueWifiList = res.wifiList
.filter(wifi => wifi.SSID && wifi.SSID.trim() !== '')
.reduce((acc, current) => {
const exists = acc.find(item => item.SSID === current.SSID)
if (!exists) {
acc.push(current)
}
return acc
}, [])
wifiList.value = uniqueWifiList
wifiIndex.value = 0
})
},
fail: err => {
console.error('获取WiFi列表失败', err)
uni.showToast({
title: '获取WiFi列表失败',
icon: 'none'
})
}
})
}
if (deviceInfo.platform === 'android') {
uni.startWifi({
success: () => {
getWifiListFn()
},
fail: err => {
console.error('初始化WiFi失败', err)
uni.showToast({
title: '初始化WiFi失败',
icon: 'none'
})
}
})
} else {
getWifiListFn()
}
},
fail: () => {
const listenEvent = () => {
uni.$on('wifiList', async data => {
if (data.status === 0) {
wifiList.value = data.wifiList
uni.hideLoading()
} else {
uni.showModal({
title: '提示',
content: '需要获取位置权限才能使用WiFi功能',
success: res => {
if (res.confirm) {
uni.openSetting()
}
content: '搜索失败,请返回重试',
showCancel: false,
success: () => {
uni.navigateBack()
}
})
}
})
})
uni.$on('distributionNetworkResult', async data => {
uni.hideLoading()
pending.value = false
if (data.status === 0) {
$basic.routeJump({
type: 'redirectTo',
name: 'selectAddress'
})
setTimeout(() => {
uni.showToast({
title: '连接成功',
icon: 'none'
})
}, 1000)
} else {
uni.showToast({
title: '连接失败,请重试',
icon: 'none'
})
}
})
}
const togglePassword = () => {
showPassword.value = !showPassword.value
@ -216,62 +167,7 @@
wifiIndex.value = e.detail.value
}
function bleComboConfigure() {}
const connectDevice = async device => {
// try {
// const deviceAdapter = await bluetoothAdapter.connectDevice(device)
// console.log(1111, deviceAdapter)
// bleComboConfigure({
// token: '1234567890',
// wifiInfo: wifiInfo.value,
// familyId: 'default',
// roomId: 'default',
// deviceAdapter
// })
// current.value++
// } catch (err) {
// console.error('', err)
// }
}
const searchDevice = async () => {
// try {
// await bluetoothAdapter.startSearch({
// onError: error => {
// console.log('', error)
// bluetoothAdapter.stopSearch()
// },
// onSearch: devices => {
// if (devices.length > 0) {
// console.log('', devices)
// deviceList.value = devices
// }
// },
// timeout: 1.4 * 15 * 1000
// })
// } catch (error) {
// console.log('1', error)
// }
}
const handleNext = () => {
current.value++
searchDevice()
if (wifiIndex.value === undefined) {
uni.showToast({
title: '请选择WiFi',
icon: 'none'
})
return
}
if (password.value === '') {
uni.showToast({
title: '请输入密码',
icon: 'none'
})
return
}
const connectWifi = async () => {
if (password.value.length < 8) {
uni.showToast({
title: '密码长度不能小于8位',
@ -280,25 +176,59 @@
return
}
wifiInfo.value = {
SSID: wifiList.value[wifiIndex.value].SSID,
password: password.value
}
if (pending.value) return
pending.value = true
uni.showLoading({
title: '连接中...'
})
uni.offGetWifiList()
if (deviceInfo.platform === 'android') {
uni.stopWifi()
}
current.value++
const result = await passthrough({
request_method: 'GET',
request_uri: '/api/v1/tencentYun/getTencentTriple',
post_args: {
serialNum0: $bluetooth.currentLockInfo.lockConfig.serialNum0
}
})
if (result.code === 0) {
$bluetooth.updateCurrentLockInfo({
...$bluetooth.currentLockInfo,
tencentYunLock: {
productId: result.data.productId,
deviceName: result.data.deviceName,
devicePsk: result.data.devicePsk
}
})
// const result = await $bluetooth.distributionNetwork({
// SSID: wifiList.value[wifiIndex.value].SSID,
// password: password.value,
// json: JSON.stringify({
// productId: result.data.productId,
// deviceName: result.data.deviceName,
// devicePsk: result.data.devicePsk
// })
// })
// if (result.code !== 0) {
// uni.showToast({
// title: '',
// icon: 'none'
// })
// }
searchDevice()
setTimeout(() => {
$basic.routeJump({
type: 'redirectTo',
name: 'selectAddress'
})
}, 3000)
} else {
uni.showToast({
title: result.message,
icon: 'none'
})
}
}
const handleInput = e => {
password.value = e
}
</script>
<style lang="scss" scoped>
.custom-steps {
:deep(.u-text__value) {
font-size: 28rpx !important;
}
}
</style>

View File

@ -139,7 +139,7 @@
}
this.routeJump({
type: 'redirectTo',
name: 'selectAddress'
name: false ? 'selectAddress' : 'distributionNetwork'
})
} else {
uni.hideLoading()

View File

@ -13,12 +13,12 @@
</template>
<script setup>
import { ref, onMounted } from 'vue'
import SwitchLoading from '@/components/SwitchLoading/SwitchLoading.vue'
import { useBluetoothStore } from '@/stores/bluetooth'
import { useBasicStore } from '@/stores/basic'
import { useUserStore } from '@/stores/user'
import { getLockDetailRequest, getLockNetTokenRequest } from '@/api/lock'
import { ref, onMounted } from 'vue'
const $bluetooth = useBluetoothStore()
const $basic = useBasicStore()
@ -32,7 +32,7 @@
const onlineToken = ref('0')
const lockId = ref(19335)
const lockId = ref(2712)
const time = ref(0)
@ -42,6 +42,12 @@
})
if (code === 0) {
lockInfo.value = data
$bluetooth.updateCurrentLockInfo({
...lockInfo.value,
name: lockInfo.value.lockName,
deviceId: lockInfo.value.lockName,
commKey: lockInfo.value.privateKey
})
} else {
uni.showToast({
title: message,
@ -84,7 +90,7 @@
const openMode = lockInfo.value.appUnlockOnline ? 1 : 0
const { code } = await $bluetooth.openDoor({
name: lockInfo.value.name,
name: lockInfo.value.lockName,
uid: $user.userInfo.uid.toString(),
openMode,
openTime: parseInt(new Date().getTime() / 1000, 10) + time.value,

View File

@ -28,9 +28,10 @@
<script setup>
import { onShow } from '@dcloudio/uni-app'
import { passthrough } from '@/api/sdk'
import { ref } from 'vue'
import { passthrough } from '@/api/sdk'
import { useBluetoothStore } from '@/stores/bluetooth'
import env from '@/config/env'
const $bluetooth = useBluetoothStore()
@ -53,9 +54,7 @@
if (res.list.length > 0) {
const result = await getInfo()
if (result.code === 0) {
const data = list.value.find(
item => item.model_id === result.data.WXIoTDeviceInfo.ModelId
)
const data = list.value.find(item => item.sn === result.data.WXIoTDeviceInfo.SN)
if (data) {
if (data.status === 1) {
reject.value = false
@ -116,7 +115,7 @@
sn: result.data.WXIoTDeviceInfo.SN,
snTicket: result.data.WXIoTDeviceInfo.SNTicket,
modelId: result.data.WXIoTDeviceInfo.ModelId,
deviceName: '智能',
deviceName: await env[await getApp().globalData.getEnvConfig()].appName,
success() {
isAuthorized.value = true
uni.hideLoading()

View File

@ -119,10 +119,10 @@
</template>
<script setup>
import { useBluetoothStore } from '@/stores/bluetooth'
import { useBasicStore } from '@/stores/basic'
import { onMounted, ref } from 'vue'
import { onUnload } from '@dcloudio/uni-app'
import { useBluetoothStore } from '@/stores/bluetooth'
import { useBasicStore } from '@/stores/basic'
import { passthrough } from '@/api/sdk'
const $bluetooth = useBluetoothStore()

View File

@ -9,7 +9,7 @@
? catEyeMode[
$bluetooth.currentLockSetting.lockSettingInfo.catEyeConfig[0]?.catEyeMode
].name
: ""
: ''
}}
</view>
<up-icon name="arrow-right"></up-icon>

View File

@ -56,7 +56,15 @@ const cmdIds = {
// 锁遥控列表
lockRemoteList: 0x3026,
// 锁设置列表
lockSettingList: 0x302a
lockSettingList: 0x302a,
// 获取Wi-Fi列表
getWifiList: 0x30f6,
// Wi-Fi列表
wifiList: 0x30f7,
// 配网
distributionNetwork: 0x30f4,
// 配网结果
distributionNetworkResult: 0x30f5
}
// 子命令ID
@ -396,6 +404,34 @@ export const useBluetoothStore = defineStore('ble', {
})
}
break
case cmdIds.getWifiList:
characteristicValueCallback({
code: decrypted[2]
})
break
case cmdIds.wifiList:
const wifiList = []
for (let i = 0; i < decrypted[3]; i++) {
wifiList.push({
SSID: that.uint8ArrayToString(decrypted.slice(4 + 33 * i, 4 + 33 * i + 32)),
rssi: decrypted[33 + 33 * i]
})
}
uni.$emit('wifiList', {
status: decrypted[2],
wifiList
})
break
case cmdIds.distributionNetwork:
characteristicValueCallback({
code: decrypted[2]
})
break
case cmdIds.distributionNetworkResult:
uni.$emit('distributionNetworkResult', {
status: decrypted[2]
})
break
case cmdIds.addUser:
that.updateCurrentLockInfo({
...that.currentLockInfo,
@ -1558,6 +1594,123 @@ export const useBluetoothStore = defineStore('ble', {
return this.getWriteResult(this.getLockStatus, data)
},
// 获取Wi-Fi列表
async getWifiList(data) {
// 确认蓝牙状态正常
if (this.bluetoothStatus !== 0) {
console.log('写入未执行', this.bluetoothStatus)
this.getBluetoothStatus()
return {
code: -1
}
}
// 确认设备连接正常
if (!this.currentLockInfo.connected) {
const searchResult = await this.searchAndConnectDevice()
if (searchResult.code !== 0) {
return searchResult
}
this.updateCurrentLockInfo({
...this.currentLockInfo,
deviceId: searchResult.data.deviceId
})
console.log('设备ID', this.currentLockInfo.deviceId)
const result = await this.connectBluetoothDevice()
console.log('连接结果', result)
if (!result) {
return {
code: -1
}
}
}
const { uid } = data
const length = 2 + 20
const headArray = this.createPackageHeader(3, length)
const contentArray = new Uint8Array(length)
contentArray[0] = cmdIds.getWifiList / 256
contentArray[1] = cmdIds.getWifiList % 256
for (let i = 0; i < uid.length; i++) {
contentArray[i + 2] = uid.charCodeAt(i)
}
const cebArray = sm4.encrypt(contentArray, this.currentLockInfo.commKey, {
mode: 'ecb',
output: 'array'
})
const packageArray = this.createPackageEnd(headArray, cebArray)
await this.writeBLECharacteristicValue(packageArray)
return this.getWriteResult(this.getWifiList, data)
},
// 配网
async distributionNetwork(data) {
// 确认蓝牙状态正常
if (this.bluetoothStatus !== 0) {
console.log('写入未执行', this.bluetoothStatus)
this.getBluetoothStatus()
return {
code: -1
}
}
// 确认设备连接正常
if (!this.currentLockInfo.connected) {
const searchResult = await this.searchAndConnectDevice()
if (searchResult.code !== 0) {
return searchResult
}
this.updateCurrentLockInfo({
...this.currentLockInfo,
deviceId: searchResult.data.deviceId
})
console.log('设备ID', this.currentLockInfo.deviceId)
const result = await this.connectBluetoothDevice()
console.log('连接结果', result)
if (!result) {
return {
code: -1
}
}
}
const { SSID, password, json } = data
const length = 2 + 30 + 20 + json.length
const headArray = this.createPackageHeader(3, length)
const contentArray = new Uint8Array(length)
contentArray[0] = cmdIds.distributionNetwork / 256
contentArray[1] = cmdIds.distributionNetwork % 256
for (let i = 0; i < SSID.length; i++) {
contentArray[i + 2] = SSID.charCodeAt(i)
}
for (let i = 0; i < password.length; i++) {
contentArray[i + 32] = password.charCodeAt(i)
}
contentArray[52] = json.length / 256
contentArray[53] = json.length % 256
for (let i = 0; i < json.length; i++) {
contentArray[i + 54] = json.charCodeAt(i)
}
const cebArray = sm4.encrypt(contentArray, this.currentLockInfo.commKey, {
mode: 'ecb',
output: 'array'
})
const packageArray = this.createPackageEnd(headArray, cebArray)
await this.writeBLECharacteristicValue(packageArray)
return this.getWriteResult(this.distributionNetwork, data)
},
// 时间戳转二进制
timestampToArray(timestamp) {
const array = new Uint8Array(4)
@ -2732,12 +2885,12 @@ export const useBluetoothStore = defineStore('ble', {
const md5Array = this.md5Encrypte(
uid + keyId,
this.currentLockInfo.token || new Uint8Array([0, 0, 0, 0]),
this.currentLockInfo.bluetooth.publicKey
this.currentLockInfo.publicKey
)
contentArray.set(md5Array, 75)
const cebArray = sm4.encrypt(contentArray, this.currentLockInfo.bluetooth.privateKey, {
const cebArray = sm4.encrypt(contentArray, this.currentLockInfo.commKey, {
mode: 'ecb',
output: 'array'
})