蓝牙列表期待效果
代码
<template><view class="bluetooth-list"><view class="align-items option" style="justify-content: space-between;" v-for="item in bluetoothList" :key="item.deviceId"><view class=""><view class="title">{{item.name || item.localName}}</view><view class="desc">{{item.deviceId}}</view></view><view class="bind-btn" @click="onBind(item)">绑定设备</view></view></view>
</template>
js里面注意getBLEDeviceCharacteristics获取特征值的时候,极个别设备参数write,read,notify是乱来的,需要自己打单独处理,通过对应write,read,notify 为true的时候拿到对应的uuid,
<script>export default {data() {return {bluetoothObj:{},bluetoothList:[],services: [],serviceId: 0,writeCharacter: false,readCharacter: false,notifyCharacter: false};},onLoad() {this.init()},onUnload() {//停止搜索蓝牙设备if (this.isSearching) {uni.stopBluetoothDevicesDiscovery();}},methods: {// 初始化init(){let that = this;uni.openBluetoothAdapter({success(res) {uni.getBluetoothAdapterState({success(res2) {if (res2.available) {if (res2.discovering) {uni.showToast({title: '正在搜索附近打印机设备',icon: "none"})return;}//获取蓝牙设备信息that.getBluetoothDevices()} else {uni.showModal({title: '提示',content: '本机蓝牙不可用',})}}});},fail() {uni.showModal({title: '提示',content: '蓝牙初始化失败,请打开蓝牙',})}})},//获取蓝牙设备信息getBluetoothDevices() {let that = thisthat.bluetoothList = [];uni.startBluetoothDevicesDiscovery({success(res) {//蓝牙设备监听 uni.onBluetoothDeviceFounduni.onBluetoothDeviceFound((result) => {let arr = that.bluetoothList;let devices = [];let list = result.devices;for (let i = 0; i < list.length; ++i) {if (list[i].name && list[i].name != "未知设备") {let arrNew = arr.filter((item) => {return item.deviceId == list[i].deviceId;});// console.log('arrNew:',arrNew.length)if (arrNew.length == 0) {devices.push(list[i]);}}}that.bluetoothList = arr.concat(devices);console.log("bluetoothList",that.bluetoothList)});that.time = setTimeout(() => {// uni.getBluetoothDevicesuni.getBluetoothDevices({success(res2) {let devices = [];let list = res2.devices;for (let i = 0; i < list.length; ++i) {if (list[i].name && list[i].name != "未知设备") {devices.push(list[i]);}}that.bluetoothList = devices;},})clearTimeout(that.time);}, 3000);}});},// 绑定蓝牙onBind(item){uni.stopBluetoothDevicesDiscovery();let that = this;let { deviceId } = item;console.log('item',item)that.bluetoothObj.deviceId = deviceId;that.serviceId = 0;that.writeCharacter = false;that.readCharacter = false;that.notifyCharacter = false;// uni.showLoading({// title: '正在连接',// })uni.openBluetoothAdapter({success: function () {uni.createBLEConnection({deviceId,success(res) {console.log('createBLEConnection success', res)uni.hideLoading()that.getSeviceId()},fail(e) {console.log('createBLEConnection fail', e)uni.hideLoading()}})},fail: function (error) {console.log("openBluetoothAdapter")}})},//获取蓝牙设备所有服务(service)。getSeviceId() {let that = this;let t=setTimeout(()=>{uni.getBLEDeviceServices({deviceId: that.bluetoothObj.deviceId,success(res) {console.log('getBLEDeviceServices success', res)that.services = res.services;that.getCharacteristics()},fail: function(e) {}})clearTimeout(t);},1500)},getCharacteristics() {var that = thislet {services: list,serviceId: num,writeCharacter: write,readCharacter: read,notifyCharacter: notify} = that;// uni.getBLEDeviceCharacteristicsuni.getBLEDeviceCharacteristics({deviceId: that.bluetoothObj.deviceId,serviceId: list[num].uuid,success(res) {console.log('getBLEDeviceCharacteristics success', res)// console.log(res)for (var i = 0; i < res.characteristics.length; ++i) {var properties = res.characteristics[i].propertiesvar item = res.characteristics[i].uuidif (!notify) {if (properties.notify) {that.bluetoothObj.notifyCharaterId = item;that.bluetoothObj.notifyServiceId = list[num].uuid;notify = true}}if (!write) {if (properties.write) {that.bluetoothObj.writeCharaterId = item;that.bluetoothObj.writeServiceId = list[num].uuid;write = true}}if (!read) {if (properties.read) {that.bluetoothObj.readCharaterId = item;that.bluetoothObj.readServiceId = list[num].uuid;read = true}}}if (!write || !notify || !read) {num++that.writeCharacter = write;that.readCharacter = read;that.notifyCharacter = notify;that.serviceId = num;if (num == list.length) {uni.showModal({title: '提示',content: '找不到该读写的特征值',})} else {that.getCharacteristics()}} else {// ok // wx.writeBLECharacteristicValueuni.notifyBLECharacteristicValueChange({state: true, // 启用 notify 功能// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接deviceId:that.bluetoothObj.deviceId,// 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取serviceId:that.bluetoothObj.serviceId,// 这里的 characteristicId 需要在 getBLEDeviceCharacteristics 接口中获取characteristicId:that.bluetoothObj.notifyServiceId,success (res) {console.log('notifyBLECharacteristicValueChange success', res.errMsg)uni.onBLECharacteristicValueChange(function (e) {/**对设备发送过来的参数进行解密 */let str = that.ab2hex(e.value);console.log("解密str",str)})}})console.log("that.bluetoothObj",that.bluetoothObj)uni.setStorageSync("bluetoothObj", that.bluetoothObj)uni.showToast({icon:"none",title:"绑定成功"})setTimeout(()=>{uni.navigateBack({delta:1})},1000)}},fail: function(e) {console.log("getBLEDeviceCharacteristics fail:",e);}})},ab2hex: (buffer) => {const hexArr = Array.prototype.map.call(new Uint8Array(buffer),function (bit) {return ('00' + bit.toString(16)).slice(-2)})return hexArr.join('')},str2ab:(str) => {var buf = new ArrayBuffer(str.length / 2);var bufView = new Uint8Array(buf);for (var i = 0, strLen = str.length; i < strLen; i++) {bufView[i] = parseInt(str.slice(i * 2, i * 2 + 2), 16);}return buf;}}}
</script>
<style lang="less" scoped>.bluetooth-list{background-color: #F3F3F3;.option{margin: 20rpx;padding: 20rpx 32rpx;background-color: #fff;border-radius: 20rpx;.title{font-weight: 600;font-size: 32rpx;}.desc{font-size: 28rpx;color: #999;margin-top: 12rpx;}.bind-btn{background-color: #3F96DB;color: #fff;width: 200rpx;height: 70rpx;line-height: 70rpx;border-radius: 35rpx;text-align: center;font-size: 30rpx;}}}
</style>