feat: 1. 添加lint

This commit is contained in:
范鹏 2024-10-21 09:58:17 +08:00
parent f5358fea62
commit 8dbabbb073
5 changed files with 248 additions and 224 deletions

150
basic.js
View File

@ -13,7 +13,7 @@ export class Result {
NotRegisteredLock: 4,
NotTokenLock: 6,
NotMoreKeyLock: 12,
ReadyHasKeyLock: 15,
ReadyHasKeyLock: 15
}
static resultsMap = new Map([
@ -22,15 +22,24 @@ export class Result {
[Result.codes.NotAvailableBluetooth, { message: '蓝牙未开启', data: {} }],
[Result.codes.NotAvailableBluetoothPermission, { message: '小程序蓝牙权限被禁用', data: {} }],
[Result.codes.NotAvailableWeChatNearbyDevicesPermission, { message: '微信附近的设备权限被禁用', data: {} }],
[Result.codes.NotAvailableWeChatLocationPermission, { message: '微信定位权限被禁用', data: {} }],
[Result.codes.NotAvailableWeChatNearbyDevicesEmpty, { message: '微信附近的设备权限无法使用', data: {} }],
[
Result.codes.NotAvailableWeChatNearbyDevicesPermission,
{ message: '微信附近的设备权限被禁用', data: {} }
],
[
Result.codes.NotAvailableWeChatLocationPermission,
{ message: '微信定位权限被禁用', data: {} }
],
[
Result.codes.NotAvailableWeChatNearbyDevicesEmpty,
{ message: '微信附近的设备权限无法使用', data: {} }
],
[Result.codes.DeviceHasBeenReset, { message: '设备已被重置', data: {} }],
[Result.codes.NotRegisteredLock, { message: '用户在锁端未注册', data: {} }],
[Result.codes.NotTokenLock, { message: '用户在锁端token失效', data: {} }],
[Result.codes.NotMoreKeyLock, { message: '锁端钥匙数量已达上限', data: {} }],
[Result.codes.ReadyHasKeyLock, { message: '用户已是锁端用户', data: {} }],
[Result.codes.ReadyHasKeyLock, { message: '用户已是锁端用户', data: {} }]
])
constructor(code, data, message) {
@ -107,7 +116,6 @@ export class Result {
}
}
/**
* @typedef {Object} err
* @property {number} errno - 错误代码
@ -122,9 +130,9 @@ export function searchAndConnectDevice(name) {
// 超时计时器
let timeoutTimer
return new Promise(async (resolve) => {
return new Promise(async resolve => {
const result = await startBluetoothDevicesDiscovery()
if(result.code === Result.Success.code) {
if (result.code === Result.Success.code) {
let searchFlag = false
timeoutTimer = setTimeout(async () => {
await stopBluetoothDevicesDiscovery()
@ -137,7 +145,7 @@ export function searchAndConnectDevice(name) {
}, 10500)
timer = setInterval(async () => {
const queryResult = await getBluetoothDevices()
if(queryResult.code === Result.Success.code) {
if (queryResult.code === Result.Success.code) {
const deviceList = queryResult.data
if (searchFlag === false && deviceList.length > 0) {
searchFlag = true
@ -145,11 +153,11 @@ export function searchAndConnectDevice(name) {
for (let i = 0; i < deviceList.length; i++) {
if (deviceList[i]?.name === name) {
const uuid = deviceList[i]?.advertisServiceUUIDs[0]
if(uuid && uuid.slice(2, 8) === '758824') {
if (uuid && uuid.slice(2, 8) === '758824') {
await stopBluetoothDevicesDiscovery()
clearTimeout(timeoutTimer)
clearInterval(timer)
if(uuid.slice(30, 32) === '00') {
if (uuid.slice(30, 32) === '00') {
resolve(Result.DeviceHasBeenReset)
} else if (uuid.slice(30, 32) === '01') {
const connectResult = await createBLEConnection(deviceList[i].deviceId)
@ -172,37 +180,40 @@ export function searchAndConnectDevice(name) {
}
// 蓝牙操作报错处理
async function handleError (err, event) {
async function handleError(err, event) {
if (err.errCode === 10000) {
const result = await openBluetoothAdapter()
if (result.code === Result.Success.code) {
return await event()
} else {
return result
}
} else if (err.errCode === 10001) {
return Result.NotAvailableBluetooth
} else if (err.errno === 3) {
return Result.NotAvailableWeChatNearbyDevicesPermission
} else if (err.errno === 103) {
return Result.NotAvailableBluetoothPermission
} else if (err.errno === 1509008) {
return Result.NotAvailableWeChatLocationPermission
} else if (err.errMsg === 'openBluetoothAdapter:fail already opened') {
return Result.Success
} else {
return Result.Fail
return result
}
if (err.errCode === 10001) {
return Result.NotAvailableBluetooth
}
if (err.errno === 3) {
return Result.NotAvailableWeChatNearbyDevicesPermission
}
if (err.errno === 103) {
return Result.NotAvailableBluetoothPermission
}
if (err.errno === 1509008) {
return Result.NotAvailableWeChatLocationPermission
}
if (err.errMsg === 'openBluetoothAdapter:fail already opened') {
return Result.Success
}
return Result.Fail
}
// 初始化蓝牙模块
function openBluetoothAdapter() {
return new Promise((resolve) => {
return new Promise(resolve => {
uni.openBluetoothAdapter({
success() {
resolve(Result.Success)
},
async fail (err) {
async fail(err) {
resolve(await handleError(err))
}
})
@ -211,12 +222,12 @@ function openBluetoothAdapter() {
// 关闭蓝牙模块
function closeBluetoothAdapter() {
return new Promise((resolve) => {
return new Promise(resolve => {
uni.closeBluetoothAdapter({
success() {
resolve(Result.Success)
},
async fail (err) {
async fail(err) {
resolve(await handleError(err))
}
})
@ -230,19 +241,19 @@ function offBluetoothAdapterStateChange() {
// 监听蓝牙特征值改变
export function onBLECharacteristicValueChange(callback) {
uni.onBLECharacteristicValueChange((res) => {
uni.onBLECharacteristicValueChange(res => {
callback(res)
})
}
// 开始搜索附近的蓝牙设备
function startBluetoothDevicesDiscovery() {
return new Promise((resolve) => {
return new Promise(resolve => {
uni.startBluetoothDevicesDiscovery({
success() {
resolve(Result.Success)
},
async fail (err) {
async fail(err) {
resolve(await handleError(err, startBluetoothDevicesDiscovery))
}
})
@ -251,12 +262,12 @@ function startBluetoothDevicesDiscovery() {
// 获取所有已发现的蓝牙设备
function getBluetoothDevices() {
return new Promise((resolve) => {
return new Promise(resolve => {
uni.getBluetoothDevices({
success(res) {
resolve(new Result(Result.Success.code, res.devices))
},
async fail () {
async fail(err) {
resolve(await handleError(err, getBluetoothDevices))
}
})
@ -265,12 +276,12 @@ function getBluetoothDevices() {
// 停止搜索附近的蓝牙设备
function stopBluetoothDevicesDiscovery() {
return new Promise((resolve) => {
return new Promise(resolve => {
uni.stopBluetoothDevicesDiscovery({
success() {
resolve(Result.Success)
},
async fail () {
async fail(err) {
resolve(await handleError(err))
}
})
@ -279,19 +290,27 @@ function stopBluetoothDevicesDiscovery() {
// 连接低功耗蓝牙设备
function createBLEConnection(deviceId, reconnectNumber = 0) {
return new Promise((resolve) => {
return new Promise(resolve => {
uni.createBLEConnection({
deviceId,
timeout: 10000,
async success () {
async success() {
const res = await getBLEDeviceServicesAndCharacteristics(deviceId)
await notifyBLECharacteristicValueChange(deviceId, res.data.serviceId, res.data.notifyCharacteristicId)
await notifyBLECharacteristicValueChange(
deviceId,
res.data.serviceId,
res.data.notifyCharacteristicId
)
resolve(res)
},
async fail (err) {
async fail(err) {
if (err.errno === 1509007) {
const res = await getBLEDeviceServicesAndCharacteristics(deviceId)
await notifyBLECharacteristicValueChange(deviceId, res.data.serviceId, res.data.notifyCharacteristicId)
await notifyBLECharacteristicValueChange(
deviceId,
res.data.serviceId,
res.data.notifyCharacteristicId
)
resolve(res)
} else if (err.errno === 1509001 && reconnectNumber < 1) {
resolve(Result.Fail)
@ -306,7 +325,7 @@ function createBLEConnection(deviceId, reconnectNumber = 0) {
}
// 获取服务及对应特征值
async function getBLEDeviceServicesAndCharacteristics (deviceId) {
async function getBLEDeviceServicesAndCharacteristics(deviceId) {
const { code, data } = await getBLEDeviceServices(deviceId)
if (code === Result.Success.code) {
const { serviceId } = data
@ -315,28 +334,31 @@ async function getBLEDeviceServicesAndCharacteristics (deviceId) {
data: { notifyCharacteristicId, writeCharacteristicId }
} = await getBLEDeviceCharacteristics(deviceId, serviceId)
if (code === Result.Success.code) {
return new Result(Result.Success.code, { deviceId, serviceId, notifyCharacteristicId, writeCharacteristicId })
} else {
return Result.Fail
return new Result(Result.Success.code, {
deviceId,
serviceId,
notifyCharacteristicId,
writeCharacteristicId
})
}
} else {
return Result.Fail
}
return Result.Fail
}
// 获取设备的服务
function getBLEDeviceServices(deviceId) {
return new Promise((resolve) => {
return new Promise(resolve => {
uni.getBLEDeviceServices({
deviceId,
success(res) {
let serviceId
for(let i = 0; i < res.services.length; i++) {
if(res.services[i].uuid.indexOf('FFF0') !== -1) {
for (let i = 0; i < res.services.length; i++) {
if (res.services[i].uuid.indexOf('FFF0') !== -1) {
serviceId = res.services[i].uuid
}
}
if(!serviceId) {
if (!serviceId) {
resolve(Result.Fail)
return
}
@ -351,24 +373,26 @@ function getBLEDeviceServices(deviceId) {
// 获取服务的特征值
function getBLEDeviceCharacteristics(deviceId, serviceId) {
return new Promise((resolve) => {
return new Promise(resolve => {
uni.getBLEDeviceCharacteristics({
deviceId,
serviceId,
success(res) {
let notifyCharacteristicId
let writeCharacteristicId
for(let i = 0; i < res.characteristics.length; i++) {
for (let i = 0; i < res.characteristics.length; i++) {
const characteristic = res.characteristics[i]
if(characteristic.properties.notify) {
if (characteristic.properties.notify) {
notifyCharacteristicId = characteristic.uuid
}
if(characteristic.properties.write) {
if (characteristic.properties.write) {
writeCharacteristicId = characteristic.uuid
}
}
if(notifyCharacteristicId && writeCharacteristicId) {
resolve(new Result(Result.Success.code, { notifyCharacteristicId, writeCharacteristicId }))
if (notifyCharacteristicId && writeCharacteristicId) {
resolve(
new Result(Result.Success.code, { notifyCharacteristicId, writeCharacteristicId })
)
} else {
resolve(Result.Fail)
}
@ -382,7 +406,7 @@ function getBLEDeviceCharacteristics(deviceId, serviceId) {
// 订阅特征值
function notifyBLECharacteristicValueChange(deviceId, serviceId, characteristicId) {
return new Promise((resolve) => {
return new Promise(resolve => {
uni.notifyBLECharacteristicValueChange({
deviceId,
serviceId,
@ -400,7 +424,7 @@ function notifyBLECharacteristicValueChange(deviceId, serviceId, characteristicI
// 断开与低功耗蓝牙设备的连接
export function closeBLEConnection(deviceId) {
return new Promise((resolve) => {
return new Promise(resolve => {
uni.closeBLEConnection({
deviceId,
success() {
@ -417,11 +441,11 @@ export function closeBLEConnection(deviceId) {
// 写入特征值
export function writeBLECharacteristicValue(deviceId, serviceId, characteristicId, binaryData) {
return new Promise((resolve) => {
return new Promise(resolve => {
const count = Math.ceil(binaryData.length / 20)
let successCount = 0
for(let i = 0; i < count; i++) {
const writeData = binaryData.slice(i * 20, i === (count - 1) ? binaryData.length : (i + 1) * 20)
for (let i = 0; i < count; i++) {
const writeData = binaryData.slice(i * 20, i === count - 1 ? binaryData.length : (i + 1) * 20)
uni.writeBLECharacteristicValue({
deviceId,
serviceId,
@ -429,7 +453,7 @@ export function writeBLECharacteristicValue(deviceId, serviceId, characteristicI
value: writeData.buffer,
success() {
successCount++
if(successCount === count) {
if (successCount === count) {
resolve(Result.Success)
}
},

View File

@ -1,21 +1,18 @@
import {
md5
} from 'js-md5'
import { md5 } from 'js-md5'
import crc from 'crc'
// 周数组转换
export function convertWeekdaysToNumber(weekDay) {
let weekStr = '00000000'
// eslint-disable-next-line no-restricted-syntax
for (const day of weekDay) {
const index = day % 7 // 将周日的索引转换为0
const index = day % 7
weekStr = weekStr.substring(0, index) + '1' + weekStr.substring(index + 1)
}
// 倒序 weekStr
weekStr = weekStr.split('')
.reverse()
.join('')
weekStr = weekStr.split('').reverse().join('')
return parseInt(weekStr, 2)
}
@ -26,7 +23,7 @@ export function timestampToArray(timestamp) {
array[0] = (timestamp & 0xff000000) >> 24
array[1] = (timestamp & 0xff0000) >> 16
array[2] = (timestamp & 0xff00) >> 8
array[3] = (timestamp & 0xff)
array[3] = timestamp & 0xff
return array
}
@ -43,8 +40,7 @@ export function md5Encrypt(text, token, key) {
md5Array.set(key, text.length + 4)
const md5Text = md5(md5Array)
return new Uint8Array(md5Text.match(/.{1,2}/g)
.map(byte => parseInt(byte, 16)))
return new Uint8Array(md5Text.match(/.{1,2}/g).map(byte => parseInt(byte, 16)))
}
// 生成包尾 头部数据+内容数据

View File

@ -3,19 +3,19 @@ import { useStarCloudStore } from '@/starCloud/starCloud'
import { Result } from '@/starCloud/basic'
/*
* config
* baseUrl: 请求域名
* url: 请求路径
* method: 请求方法
* header: 请求头
* token: 请求token
* data: 请求参数
* */
* config
* baseUrl: 请求域名
* url: 请求路径
* method: 请求方法
* header: 请求头
* token: 请求token
* data: 请求参数
* */
const request = (config) => {
const request = config => {
const starCloud = useStarCloudStore()
let timer
return new Promise(async (resolve) => {
return new Promise(async resolve => {
const baseConfig = starCloud.getConfig()
const token = config?.token ? config.token : getStorage('starCloudToken')
@ -40,7 +40,7 @@ const request = (config) => {
// 超时处理
timer = setTimeout(() => {
resolve(new Result(Result.Fail.code, {},'网络访问失败,请检查网络是否正常'))
resolve(new Result(Result.Fail.code, {}, '网络访问失败,请检查网络是否正常'))
}, 3200)
uni.request({
@ -49,7 +49,7 @@ const request = (config) => {
header,
data,
timeout: 3000,
async success (res) {
async success(res) {
const { statusCode, data } = res
if (timer) {
clearTimeout(timer)
@ -64,7 +64,7 @@ const request = (config) => {
starCloud.accountInfo.username,
starCloud.accountInfo.password
)
if(code === Result.Success.code) {
if (code === Result.Success.code) {
resolve(await request(config))
}
} else {
@ -75,17 +75,17 @@ const request = (config) => {
})
}
} else {
resolve(new Result(Result.Fail.code, {},'网络访问失败,请检查网络是否正常'))
resolve(new Result(Result.Fail.code, {}, '网络访问失败,请检查网络是否正常'))
}
},
async fail (res) {
async fail(res) {
console.log('网络访问失败', res)
if (timer) {
clearTimeout(timer)
}
resolve(new Result(Result.Fail.code, {},'网络访问失败,请检查网络是否正常'))
resolve(new Result(Result.Fail.code, {}, '网络访问失败,请检查网络是否正常'))
},
async complete (res) {
async complete(res) {
console.log(URL.substring(baseConfig.baseUrl.length + 1), {
env: baseConfig.name,
url: URL.substring(baseConfig.baseUrl.length + 1),

View File

@ -1,4 +1,5 @@
import { defineStore } from 'pinia'
import { sm4 } from 'sm-crypto'
import { buildNumber, configs, version } from '@/starCloud/env'
import {
addCustomPassword,
@ -9,7 +10,8 @@ import {
getStarCloudToken,
getUserNoListRequest,
starCloudCreateUser,
updateLockUserNoRequest, updatePassword
updateLockUserNoRequest,
updatePassword
} from '@/starCloud/api'
import { getStorage, setStorage } from '@/starCloud/storage'
import {
@ -27,7 +29,6 @@ import {
timestampToArray,
uint8ArrayToString
} from '@/starCloud/format'
import { sm4 } from 'sm-crypto'
/**
* 锁信息
@ -103,7 +104,7 @@ const cmdIds = {
// 重置设备
resetDevice: 0x3004,
// 清理用户
cleanUser: 0x300C,
cleanUser: 0x300c,
// 扩展命令
expandCmd: 0x3030
}
@ -166,11 +167,7 @@ export const useStarCloudStore = defineStore('starCloud', {
},
// 注册星云
async register() {
const {
code,
data,
message
} = await starCloudCreateUser({
const { code, data, message } = await starCloudCreateUser({
clientId: this.clientId,
clientSecret: this.clientSecret
})
@ -188,8 +185,7 @@ export const useStarCloudStore = defineStore('starCloud', {
this.userInfo = getStorage('starCloudUser')
this.loginStarCloud = true
// 获取服务器时间
this.getServerTimestamp()
.then(() => {})
this.getServerTimestamp().then(() => {})
return Result.Success
}
console.log('登录星云', username, password)
@ -198,8 +194,8 @@ export const useStarCloudStore = defineStore('starCloud', {
data: userInfo,
message
} = await getStarCloudToken({
username: username,
password: password,
username,
password,
clientId: this.clientId,
clientSecret: this.clientSecret
})
@ -209,23 +205,18 @@ export const useStarCloudStore = defineStore('starCloud', {
setStorage('starCloudUser', userInfo)
this.loginStarCloud = true
// 获取服务器时间
this.getServerTimestamp()
.then(() => {})
this.getServerTimestamp().then(() => {})
}
return new Result(code, {}, message)
},
// 选择锁
async selectLock(lockId) {
const {
code,
data,
message
} = await getLockDetail({
const { code, data, message } = await getLockDetail({
lockId
})
if (code === Result.Success.code) {
const lockList = getStorage('lockList')
if(lockList) {
if (lockList) {
const index = lockList.findIndex(item => item.lockId === lockId)
if (index === -1) {
lockList.push(data)
@ -240,7 +231,7 @@ export const useStarCloudStore = defineStore('starCloud', {
} else {
const lockList = getStorage('lockList')
console.log('锁列表', lockList)
if(lockList) {
if (lockList) {
const index = lockList.findIndex(item => item.lockId === lockId)
if (index !== -1) {
this.lockInfo = lockList[index]
@ -260,12 +251,7 @@ export const useStarCloudStore = defineStore('starCloud', {
this.updateLockInfo(searchResult.data)
// 获取并处理锁信息
let {
uid: authUid,
keyId,
token,
bluetooth
} = this.lockInfo
let { uid: authUid, keyId, token, bluetooth } = this.lockInfo
let { uid } = this.userInfo
authUid = authUid.toString()
uid = uid.toString()
@ -273,10 +259,7 @@ export const useStarCloudStore = defineStore('starCloud', {
const name = bluetooth.bluetoothDeviceName
// 获取用户列表
const {
code: requestCode,
data: requestData
} = await getUserNoListRequest({
const { code: requestCode, data: requestData } = await getUserNoListRequest({
lockId: this.lockInfo.lockId
})
console.log('获取用户列表请求结果', requestCode, requestData)
@ -319,7 +302,11 @@ export const useStarCloudStore = defineStore('starCloud', {
contentArray[128 + userNoList.length] = 16
const md5Array = md5Encrypt(authUid + keyId, token || new Uint8Array([0, 0, 0, 0]), bluetooth.publicKey)
const md5Array = md5Encrypt(
authUid + keyId,
token || new Uint8Array([0, 0, 0, 0]),
bluetooth.publicKey
)
contentArray.set(md5Array, 129 + userNoList.length)
@ -330,8 +317,12 @@ export const useStarCloudStore = defineStore('starCloud', {
const packageArray = createPackageEnd(headArray, cebArray)
const writeResult = await writeBLECharacteristicValue(this.lockInfo.deviceId, this.lockInfo.serviceId,
this.lockInfo.writeCharacteristicId, packageArray)
const writeResult = await writeBLECharacteristicValue(
this.lockInfo.deviceId,
this.lockInfo.serviceId,
this.lockInfo.writeCharacteristicId,
packageArray
)
if (writeResult.code !== Result.Success.code) {
return writeResult
}
@ -339,6 +330,7 @@ export const useStarCloudStore = defineStore('starCloud', {
return this.getWriteResult(this.cleanLockUser, disconnect)
},
// 开门
// eslint-disable-next-line default-param-last
async openDoor(type = 'open', disconnect) {
// 确认设备连接正常
const searchResult = await searchAndConnectDevice(this.lockInfo.bluetooth.bluetoothDeviceName)
@ -374,8 +366,7 @@ export const useStarCloudStore = defineStore('starCloud', {
const name = this.lockInfo.bluetooth.bluetoothDeviceName
const uid = this.userInfo.uid.toString()
const openTime = Math.ceil(new Date()
.getTime() / 1000) + this.timeDifference
const openTime = Math.ceil(new Date().getTime() / 1000) + this.timeDifference
const length = 2 + 40 + 20 + 1 + 4 + 4 + 1 + 16 + 16
const headArray = this.createPackageHeader(3, length)
@ -402,8 +393,11 @@ export const useStarCloudStore = defineStore('starCloud', {
contentArray[71] = 16
const md5Array = md5Encrypt(name + uid, this.lockInfo.token || timestampToArray(openTime),
this.lockInfo.bluetooth.signKey)
const md5Array = md5Encrypt(
name + uid,
this.lockInfo.token || timestampToArray(openTime),
this.lockInfo.bluetooth.signKey
)
contentArray.set(md5Array, 72)
@ -418,8 +412,12 @@ export const useStarCloudStore = defineStore('starCloud', {
const packageArray = createPackageEnd(headArray, cebArray)
const writeResult = await writeBLECharacteristicValue(this.lockInfo.deviceId, this.lockInfo.serviceId,
this.lockInfo.writeCharacteristicId, packageArray)
const writeResult = await writeBLECharacteristicValue(
this.lockInfo.deviceId,
this.lockInfo.serviceId,
this.lockInfo.writeCharacteristicId,
packageArray
)
if (writeResult.code !== Result.Success.code) {
return writeResult
@ -455,12 +453,12 @@ export const useStarCloudStore = defineStore('starCloud', {
const uid = this.userInfo.uid.toString()
const keyId = this.lockInfo.keyId.toString()
const isAdmin = pwdRight
const userCountLimit = 0xFFFF
const userCountLimit = 0xffff
startDate = Math.floor(startDate / 1000)
endDate = Math.floor(endDate / 1000)
keyboardPwd = keyboardPwd.toString()
if(!pwdNo) {
if (!pwdNo) {
pwdNo = 0
}
@ -504,8 +502,11 @@ export const useStarCloudStore = defineStore('starCloud', {
contentArray[102] = 16
const md5Array = md5Encrypt(keyId + uid, this.lockInfo.token || new Uint8Array([0, 0, 0, 0]),
this.lockInfo.bluetooth.signKey)
const md5Array = md5Encrypt(
keyId + uid,
this.lockInfo.token || new Uint8Array([0, 0, 0, 0]),
this.lockInfo.bluetooth.signKey
)
contentArray.set(md5Array, 103)
@ -516,8 +517,12 @@ export const useStarCloudStore = defineStore('starCloud', {
const packageArray = createPackageEnd(headArray, cebArray)
const writeResult = await writeBLECharacteristicValue(this.lockInfo.deviceId, this.lockInfo.serviceId,
this.lockInfo.writeCharacteristicId, packageArray)
const writeResult = await writeBLECharacteristicValue(
this.lockInfo.deviceId,
this.lockInfo.serviceId,
this.lockInfo.writeCharacteristicId,
packageArray
)
if (writeResult.code !== Result.Success.code) {
return writeResult
@ -526,30 +531,19 @@ export const useStarCloudStore = defineStore('starCloud', {
return this.getWriteResult(this.customPassword, disconnect, password)
},
// 获取联网token
async getNetToken() {
const {
code,
data,
message
} = await getLockNetTokenRequest({
const { code, data, message } = await getLockNetTokenRequest({
lockId: this.lockInfo.lockId
})
return new Result(code, data, message)
},
// 获取服务器时间
async getServerTimestamp() {
const {
code,
data,
message
} = await getServerDatetime({})
const { code, data, message } = await getServerDatetime({})
if (code === Result.Success.code) {
this.serverTimestamp = Math.ceil(data.date / 1000)
this.timeDifference = Math.ceil((data.date - new Date()
.getTime()) / 1000)
this.timeDifference = Math.ceil((data.date - new Date().getTime()) / 1000)
}
return new Result(code, data, message)
},
@ -582,8 +576,8 @@ export const useStarCloudStore = defineStore('starCloud', {
password
} = data
const length = 2 + 40 + 20 + 40 + 20 + 1 + 1 + 4 + 4 + 2 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 20 + 4 +
1 + 16
const length =
2 + 40 + 20 + 40 + 20 + 1 + 1 + 4 + 4 + 2 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 20 + 4 + 1 + 16
const headArray = this.createPackageHeader(3, length)
const contentArray = new Uint8Array(length)
@ -631,8 +625,11 @@ export const useStarCloudStore = defineStore('starCloud', {
contentArray[165] = 16
const md5Array = md5Encrypt(authUid + keyId, this.lockInfo.token || timestampToArray(startDate),
this.lockInfo.bluetooth.publicKey)
const md5Array = md5Encrypt(
authUid + keyId,
this.lockInfo.token || timestampToArray(startDate),
this.lockInfo.bluetooth.publicKey
)
contentArray.set(md5Array, 166)
@ -642,8 +639,12 @@ export const useStarCloudStore = defineStore('starCloud', {
})
const packageArray = createPackageEnd(headArray, cebArray)
const writeResult = await writeBLECharacteristicValue(this.lockInfo.deviceId, this.lockInfo.serviceId,
this.lockInfo.writeCharacteristicId, packageArray)
const writeResult = await writeBLECharacteristicValue(
this.lockInfo.deviceId,
this.lockInfo.serviceId,
this.lockInfo.writeCharacteristicId,
packageArray
)
if (writeResult.code !== Result.Success.code) {
return writeResult
@ -651,12 +652,13 @@ export const useStarCloudStore = defineStore('starCloud', {
return this.getWriteResult(this.addLockUser, disconnect, data)
},
// 获取写入结果
// eslint-disable-next-line default-param-last
getWriteResult(request, disconnect = false, params) {
return new Promise(resolve => {
const getWriteResultTimer = setTimeout(() => {
resolve(Result.Fail)
}, 20000)
characteristicValueCallback = async (data) => {
characteristicValueCallback = async data => {
// code 6 token过期,重新获取
if (data.code === Result.NotTokenLock.code) {
resolve(await request(params))
@ -670,7 +672,7 @@ export const useStarCloudStore = defineStore('starCloud', {
}
} else {
clearTimeout(getWriteResultTimer)
if(disconnect) {
if (disconnect) {
await this.disconnectDevice()
}
console.log('写入结果', data, request, params)
@ -682,10 +684,8 @@ export const useStarCloudStore = defineStore('starCloud', {
// 检查是否已添加为用户
async checkLockUser(forceAdd = false) {
if (this.lockInfo.lockUserNo === 0 || forceAdd) {
const timestamp = Math.floor(new Date()
.getTime() / 1000)
const password = (Math.floor(Math.random() * 900000) + 100000)
.toString()
const timestamp = Math.floor(new Date().getTime() / 1000)
const password = (Math.floor(Math.random() * 900000) + 100000).toString()
console.log('用户未添加,开始添加用户')
const addUserParams = {
name: this.lockInfo.bluetooth.bluetoothDeviceName,
@ -694,55 +694,47 @@ export const useStarCloudStore = defineStore('starCloud', {
uid: this.userInfo.uid.toString(),
openMode: 1,
keyType: 0,
startDate: this.lockInfo.startDate === 0 ? timestamp : Math.floor(this.lockInfo.startDate /
1000),
expireDate: this.lockInfo.endDate === 0 ? 0xffffffff : Math.floor(this.lockInfo.endDate /
1000),
startDate:
this.lockInfo.startDate === 0 ? timestamp : Math.floor(this.lockInfo.startDate / 1000),
expireDate:
this.lockInfo.endDate === 0 ? 0xffffffff : Math.floor(this.lockInfo.endDate / 1000),
useCountLimit: this.lockInfo.keyType === 3 ? 1 : 0xffff,
isRound: this.lockInfo.keyType === 4 ? 1 : 0,
weekRound: this.lockInfo.keyType === 4 ? convertWeekdaysToNumber(this.lockInfo.weekDays) :
0,
startHour: this.lockInfo.keyType === 4 ? new Date(this.lockInfo.startDate)
.getHours() : 0,
startMin: this.lockInfo.keyType === 4 ? new Date(this.lockInfo.startDate)
.getMinutes() : 0,
endHour: this.lockInfo.keyType === 4 ? new Date(this.lockInfo.endDate)
.getHours() : 0,
endMin: this.lockInfo.keyType === 4 ? new Date(this.lockInfo.endDate)
.getMinutes() : 0,
weekRound:
this.lockInfo.keyType === 4 ? convertWeekdaysToNumber(this.lockInfo.weekDays) : 0,
startHour: this.lockInfo.keyType === 4 ? new Date(this.lockInfo.startDate).getHours() : 0,
startMin:
this.lockInfo.keyType === 4 ? new Date(this.lockInfo.startDate).getMinutes() : 0,
endHour: this.lockInfo.keyType === 4 ? new Date(this.lockInfo.endDate).getHours() : 0,
endMin: this.lockInfo.keyType === 4 ? new Date(this.lockInfo.endDate).getMinutes() : 0,
role: 0,
password
}
const addUserResult = await this.addLockUser(addUserParams)
console.log('添加用户蓝牙结果', addUserResult)
if (addUserResult.code === Result.Success.code) {
const {
code
} = await updateLockUserNoRequest({
const { code } = await updateLockUserNoRequest({
keyId: this.lockInfo.keyId,
lockUserNo: this.lockInfo.lockUserNo
})
console.log('添加用户请求结果', code)
return Result.Success
} else if (addUserResult.code === Result.NotMoreKeyLock.code) {
}
if (addUserResult.code === Result.NotMoreKeyLock.code) {
console.log('用户达上限,开始清理用户')
const {
code: cleanCode
} = await this.cleanLockUser()
const { code: cleanCode } = await this.cleanLockUser()
console.log('清理用户蓝牙结果', cleanCode)
if (cleanCode === Result.Success.code) {
return await this.checkLockUser()
} else {
return Result.Fail
}
} else if (addUserResult.code === Result.ReadyHasKeyLock.code) {
return Result.Success
} else {
return Result.Fail
}
} else {
return Result.Success
if (addUserResult.code === Result.ReadyHasKeyLock.code) {
return Result.Success
}
return Result.Fail
}
return Result.Success
},
// 更新锁信息
updateLockInfo(lockInfo) {
@ -755,30 +747,32 @@ export const useStarCloudStore = defineStore('starCloud', {
listenCharacteristicValue(res) {
if (res.deviceId === this.lockInfo.deviceId) {
let binaryData = new Uint8Array(res.value)
if (binaryData[0] === 0xEF && binaryData[1] === 0x01 && binaryData[2] === 0xEE && binaryData[3] ===
0x02) {
if (
binaryData[0] === 0xef &&
binaryData[1] === 0x01 &&
binaryData[2] === 0xee &&
binaryData[3] === 0x02
) {
length = binaryData[8] * 256 + binaryData[9]
if (length + 14 > binaryData.length) {
completeArray = binaryData
} else {
this.parsingCharacteristicValue(binaryData).then(() => {})
}
} else {
if (completeArray) {
const combinedArray = new Uint8Array(completeArray.length + binaryData.length)
combinedArray.set(completeArray, 0)
combinedArray.set(binaryData, completeArray.length)
completeArray = combinedArray
if (length + 14 === completeArray.length) {
this.parsingCharacteristicValue(completeArray).then(() => {})
completeArray = null
}
} else if (completeArray) {
const combinedArray = new Uint8Array(completeArray.length + binaryData.length)
combinedArray.set(completeArray, 0)
combinedArray.set(binaryData, completeArray.length)
completeArray = combinedArray
if (length + 14 === completeArray.length) {
this.parsingCharacteristicValue(completeArray).then(() => {})
completeArray = null
}
}
}
},
// 解析特征值
async parsingCharacteristicValue (binaryData) {
async parsingCharacteristicValue(binaryData) {
// 0x20 明文 0x22 SM4事先约定密钥 0x23 SM4设备指定密钥
if (binaryData[7] === 0x20) {
if (binaryData[12] * 256 + binaryData[13] === cmdIds.getPublicKey) {
@ -851,17 +845,19 @@ export const useStarCloudStore = defineStore('starCloud', {
icPartNo: uint8ArrayToString(decrypted.slice(140, 150)),
indate: arrayToTimestamp(decrypted.slice(150, 154)),
mac: uint8ArrayToString(decrypted.slice(154, 174)),
timezoneOffset: new Date()
.getTimezoneOffset() * 60
timezoneOffset: new Date().getTimezoneOffset() * 60
}
this.updateLockInfo({
featureValue: uint8ArrayToString(decrypted.slice(175, 175 + decrypted[
174])),
featureSettingValue: uint8ArrayToString(decrypted.slice(176 + decrypted[
174], 176 + decrypted[174] + decrypted[175 + decrypted[
174]])),
featureSettingParams: Array.from(decrypted.slice(176 + decrypted[174] +
decrypted[175 + decrypted[174]])),
featureValue: uint8ArrayToString(decrypted.slice(175, 175 + decrypted[174])),
featureSettingValue: uint8ArrayToString(
decrypted.slice(
176 + decrypted[174],
176 + decrypted[174] + decrypted[175 + decrypted[174]]
)
),
featureSettingParams: Array.from(
decrypted.slice(176 + decrypted[174] + decrypted[175 + decrypted[174]])
),
lockConfig
})
console.log('获取锁状态成功', this.lockInfo.lockConfig)
@ -894,7 +890,7 @@ export const useStarCloudStore = defineStore('starCloud', {
token: decrypted.slice(5, 9)
})
if (decrypted[2] === Result.Success.code) {
if(decrypted[11] === Result.Success.code) {
if (decrypted[11] === Result.Success.code) {
const pwdNo = decrypted[9] * 256 + decrypted[10]
if (requestParams.operate === 0) {
const addResult = await addCustomPassword({
@ -903,13 +899,17 @@ export const useStarCloudStore = defineStore('starCloud', {
lockId: this.lockInfo.lockId
})
if (addResult.code === Result.Success.code) {
characteristicValueCallback(new Result(addResult.code, {
pwdNo: pwdNo,
keyboardPwdId: addResult.data.keyboardPwdId,
keyboardPwd: addResult.data.keyboardPwd
}))
characteristicValueCallback(
new Result(addResult.code, {
pwdNo,
keyboardPwdId: addResult.data.keyboardPwdId,
keyboardPwd: addResult.data.keyboardPwd
})
)
} else {
characteristicValueCallback(new Result(addResult.code, addResult.data, addResult.message))
characteristicValueCallback(
new Result(addResult.code, addResult.data, addResult.message)
)
}
} else if (requestParams.operate === 1) {
const updateResult = await updatePassword({
@ -919,7 +919,9 @@ export const useStarCloudStore = defineStore('starCloud', {
if (updateResult.code === Result.Success.code) {
characteristicValueCallback(new Result(updateResult.code))
} else {
characteristicValueCallback(new Result(updateResult.code, updateResult.data, updateResult.message))
characteristicValueCallback(
new Result(updateResult.code, updateResult.data, updateResult.message)
)
}
}
} else {
@ -929,6 +931,8 @@ export const useStarCloudStore = defineStore('starCloud', {
characteristicValueCallback(new Result(decrypted[2]))
}
break
default:
break
}
break
case cmdIds.openDoor:
@ -967,9 +971,9 @@ export const useStarCloudStore = defineStore('starCloud', {
let headArray = new Uint8Array(12)
// 固定包头
headArray[0] = 0xEF
headArray[0] = 0xef
headArray[1] = 0x01
headArray[2] = 0xEE
headArray[2] = 0xee
headArray[3] = 0x02
// 包类型 发送
@ -1006,6 +1010,6 @@ export const useStarCloudStore = defineStore('starCloud', {
// 断开与设备的连接
async disconnectDevice() {
return await closeBLEConnection(this.lockInfo.deviceId)
},
}
}
})

View File

@ -14,5 +14,5 @@ export function removeStorage(key) {
function getPrefix() {
const starCloud = useStarCloudStore()
return `${ starCloud.envVersion }:`
return `${starCloud.envVersion}:`
}