This commit is contained in:
aihe 2024-05-13 16:03:12 +08:00
parent 8ebe91b021
commit 64670054fd
3 changed files with 118 additions and 136 deletions

View File

@ -199,6 +199,39 @@ const canvasGetImageData = (params = {})=> {
}) })
} }
const uniPromiseApi = (name, options = {}, extObj = { })=> {
return new Promise((resolve, reject)=> {
if(!(uni?.[name])) {
console.error(`uni.${name} api不存在 `)
return reject(`uni.${name} api不存在`)
}
uni?.[name]?.({
...options,
success(res){
console.error(`uni.${name} -execResult:success====`, res)
resolve({ res })
if(extObj.successText) {
showToast(successText)
}
},
fail(err){
console.error(`uni.${name} -execResult:fail====`, err)
resolve({ err })
if(extObj.failText) {
showToast(failText)
}
}
})
})
}
const promiseTimeout = (time) => {
return new Promise((resolve, reject)=> {
setTimeout(()=> {
resolve()
}, time)
})
}
export { export {
reLaunch, reLaunch,
@ -216,5 +249,7 @@ export {
saveFile, saveFile,
getImageTempFilePath, getImageTempFilePath,
canvasGetImageData, canvasGetImageData,
getImageInfo getImageInfo,
uniPromiseApi,
promiseTimeout,
} }

View File

@ -179,6 +179,7 @@ const textDecoder = (input)=> {
return decodeURIComponent(escape(String.fromCharCode(...[input]))); return decodeURIComponent(escape(String.fromCharCode(...[input])));
} }
export { export {
getAddressDetail, getAddressDetail,
setAddresModalParam, setAddresModalParam,
@ -190,5 +191,5 @@ export {
debounce, debounce,
throttle, throttle,
textEncoder, textEncoder,
textDecoder textDecoder,
} }

View File

@ -98,7 +98,7 @@
</template> </template>
<script> <script>
import { showLoading, showToast, hideLoading } from "@/common/untool" import { showLoading, showToast, hideLoading, uniPromiseApi, promiseTimeout } from "@/common/untool"
import { getSessionBluetoothInfo, setSessionBluetoothInfo } from "@/session" import { getSessionBluetoothInfo, setSessionBluetoothInfo } from "@/session"
export default { export default {
@ -163,76 +163,59 @@ export default {
let conSta = false let conSta = false
// 判断是否有历史连接 // 判断是否有历史连接
if(characteristicId) { if(characteristicId) {
conSta = await this.connect() let { res, err } = await this.connect()
conSta = !!res
} }
// 连接不成功,打开蓝牙配置页面 // 连接不成功,打开蓝牙配置页面
if(!conSta) { if(!conSta) {
this.showConnectPage = true this.showConnectPage = true
this.discoveryPrinter() this.discoveryPrinter()
} }
return bl return conSta
}, },
changeTab(type) { changeTab(type) {
this.curTab = type this.curTab = type
}, },
openBluetoothAdapter () { async openBluetoothAdapter () {
var _this = this var _this = this
return new Promise((resolve, reject)=> { const { res, err } = await uniPromiseApi('openBluetoothAdapter', { })
uni?.openBluetoothAdapter?.({ if(err) {
complete (e) { if (err.errCode == 10001) {
console.log(e);
if (!e.errCode) {
resolve()
console.log('初始化完成')
} else if (e.errCode == 10001) {
reject(e)
showToast('请打开手机蓝牙') showToast('请打开手机蓝牙')
} else { } else {
reject(e) showToast(err.errMsg)
console.log('openBluetoothAdapter:error=========', e.errMsg)
showToast(e.errMsg)
} }
} }
})
})
}, },
// 开始搜寻附近的蓝牙外围设备 // 开始搜寻附近的蓝牙外围设备
discoveryPrinter () { async discoveryPrinter () {
var _this = this var _this = this
_this.devices = [] _this.devices = []
_this.searchLoading = true _this.searchLoading = true
_this.curTab = 0 _this.curTab = 0
return new Promise((resolve, reject)=> { const { res, err } = await uniPromiseApi('startBluetoothDevicesDiscovery', { })
uni?.startBluetoothDevicesDiscovery?.({ if(res) {
complete (e) { // 打开搜索后,监听设备回调信息
console.log(e)
if (e.errMsg == "startBluetoothDevicesDiscovery:ok") {
resolve()
// ArrayBuffer转16进度字符串示例
uni.onBluetoothDeviceFound(devices => { uni.onBluetoothDeviceFound(devices => {
console.log("========devices=====", devices) console.log("========devices=====", devices)
let curDvs = devices?.devices?.[0] || {} let curDvs = devices?.devices?.[0] || {}
// 过滤重复的 // 过滤已经搜到的设备
if(curDvs.deviceId && _this.devices.map(t=> t.deviceId).indexOf(curDvs.deviceId) == -1) { if(curDvs.deviceId && _this.devices.map(t=> t.deviceId).indexOf(curDvs.deviceId) == -1) {
_this.devices.push(curDvs) _this.devices.push(curDvs)
} }
}) })
} else {
reject()
} }
} return { res, err }
})
})
}, },
// 停止搜寻附近的蓝牙外围设备 // 停止搜寻附近的蓝牙外围设备
async stopDiscoveryPrinter () { async stopDiscoveryPrinter () {
this.searchLoading = false this.searchLoading = false
uni?.stopBluetoothDevicesDiscovery?.() return uniPromiseApi('stopBluetoothDevicesDiscovery')
}, },
// 断开蓝牙 // 断开蓝牙
async closeBluetoothAdapter () { async closeBluetoothAdapter () {
this.searchLoading = false this.searchLoading = false
uni?.closeBluetoothAdapter?.() return uniPromiseApi('closeBluetoothAdapter')
}, },
async handleSelectDeviceId (item) { async handleSelectDeviceId (item) {
this.deviceId = item.deviceId this.deviceId = item.deviceId
@ -266,116 +249,79 @@ export default {
handleSelectChara (item) { handleSelectChara (item) {
this.characteristicId = item.uuid this.characteristicId = item.uuid
}, },
connect () { async connect () {
var _this = this var _this = this
console.log("连接蓝牙=====deviceId", _this.deviceId) console.log("连接蓝牙=====deviceId", _this.deviceId)
showLoading('正在连接蓝牙') showLoading('正在连接蓝牙')
return new Promise((resolve)=> { let { res, err } = await uniPromiseApi('createBLEConnection', { deviceId: _this.deviceId })
uni.createBLEConnection({
deviceId: _this.deviceId,
complete (e) {
hideLoading() hideLoading()
console.log("蓝牙连接回调=====", e) if( res) {
if (e.errMsg == "createBLEConnection:ok") {
showToast(`蓝牙连接成功`) showToast(`蓝牙连接成功`)
//获取蓝牙设备所有服务(service)。 await promiseTimeout(1000)
setTimeout(async()=> { // 获取蓝牙设备所有服务(service)。
await _this.getBLEDeviceServices() await _this.getBLEDeviceServices()
resolve(true)
}, 2000)
} else {
resolve(false)
showToast(`连接设备失败:${e.errMsg}`)
} }
if(err) {
showToast(`连接设备失败:${err.errMsg}`)
} }
}) return { res, err }
})
}, },
getBLEDeviceServices(){ async getBLEDeviceServices() {
var _this = this var _this = this
return new Promise((resolve)=> { let { res, err } = await uniPromiseApi('getBLEDeviceServices', {
showLoading('正在搜索服务')
uni.getBLEDeviceServices({
// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接 // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
deviceId: _this.deviceId, deviceId: _this.deviceId,
success:(res)=>{ })
hideLoading() if(res) {
resolve()
console.log('device services:', res)
_this.serverList = res.services _this.serverList = res.services
// _this.serviceId = res.services[0].uuid; // _this.serviceId = res.services[0].uuid;
console.log('serverId:', _this.serviceId) console.log('serverId:', _this.serviceId)
},
fail:(e) =>{
hideLoading()
resolve()
this.serverList = []
showToast(`设备服务获取失败:${e.errMsg}`)
console.log("getBLEDeviceServices - fail==============", e)
} }
}) if(err) {
}) this.serverList = []
showToast(`设备服务获取失败:${err.errMsg}`)
}
return { res, err }
}, },
getBLEDeviceCharacteristics () { async getBLEDeviceCharacteristics () {
var _this = this var _this = this
return new Promise((resolve, reject)=> { let { res, err } = await uniPromiseApi('getBLEDeviceCharacteristics', {
showLoading('正在搜索特征值')
uni.getBLEDeviceCharacteristics({
// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接 // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
deviceId: _this.deviceId, deviceId: _this.deviceId,
// 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取 // 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
serviceId:_this.serviceId, serviceId:_this.serviceId,
success:(res)=>{ })
hideLoading() if(res) {
console.log('getBLEDeviceCharacteristics', res)
_this.characteristics = res.characteristics _this.characteristics = res.characteristics
resolve()
// _this.characteristicId = res.characteristics[0].uuid
},
fail:(res)=>{
hideLoading()
reject()
console.log(res)
} }
}) return { res, err }
})
}, },
// 根据选择的deviceId自动匹配 serviceId, characteristicId // 根据选择的deviceId自动匹配 serviceId, characteristicId
async handleAutoSelectAllData(item) { async handleAutoSelectAllData(item) {
console.log("============测试==1111111")
const _this = this const _this = this
this.deviceId = item.deviceId await this.handleSelectDeviceId(item)
this.serviceId = ''
this.serverList = []
this.characteristics = []
this.characteristicId = ''
await this.connect()
if(this.serverList?.length > 0) { if(this.serverList?.length > 0) {
for(let i=0; i<_this.serverList?.length; i++) { for(let i=0; i<_this.serverList?.length; i++) {
let _serviceId = _this.serverList[i].uuid let _serviceId = _this.serverList[i].uuid
let charRes = await new Promise((resolve, reject) => { let charApi = await uniPromiseApi('getBLEDeviceCharacteristics', {
uni.getBLEDeviceCharacteristics({
deviceId: _this.deviceId, deviceId: _this.deviceId,
serviceId: _serviceId, serviceId: _serviceId,
success:(res)=>{ })
let { res, err } = charApi
if(res) {
let charItem = res.characteristics.filter(t=> { let charItem = res.characteristics.filter(t=> {
let { notify, indicate, write } = t.properties || {} let { notify, indicate, write } = t.properties || {}
return (notify || indicate) && write return (notify || indicate) && write
})[0] })[0]
resolve(charItem) if(charItem) {
},
fail:(res)=>{
resolve()
}
})
})
if(charRes) {
_this.serviceId = _serviceId _this.serviceId = _serviceId
_this.characteristicId = charRes.uuid _this.characteristicId = charRes.uuid
break break
} }
} }
} }
}
}, },
getInstance() { getInstance() {
return this return this