微信小程序蓝牙连接 uniApp蓝牙连接设备

蓝牙列表期待效果

代码

javascript 复制代码
<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,

javascript 复制代码
<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 = this
				that.bluetoothList = [];
				uni.startBluetoothDevicesDiscovery({
					success(res) {
						//蓝牙设备监听 uni.onBluetoothDeviceFound
						uni.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.getBluetoothDevices
							uni.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 = this
				let {
					services: list,
					serviceId: num,
					writeCharacter: write,
					readCharacter: read,
					notifyCharacter: notify
				} = that;
				// uni.getBLEDeviceCharacteristics
				uni.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].properties
							var item = res.characteristics[i].uuid
							if (!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.writeBLECharacteristicValue
							uni.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>
css 复制代码
<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>
相关推荐
刘婉晴6 小时前
【信息安全工程师备考笔记】第三章 密码学基本理论
笔记·安全·密码学
晓数8 小时前
【硬核干货】JetBrains AI Assistant 干货笔记
人工智能·笔记·jetbrains·ai assistant
我的golang之路果然有问题8 小时前
速成GO访问sql,个人笔记
经验分享·笔记·后端·sql·golang·go·database
lwewan9 小时前
26考研——存储系统(3)
c语言·笔记·考研
搞机小能手9 小时前
六个能够白嫖学习资料的网站
笔记·学习·分类
nongcunqq10 小时前
爬虫练习 js 逆向
笔记·爬虫
汐汐咯10 小时前
终端运行java出现???
笔记
无敌小茶12 小时前
Linux学习笔记之环境变量
linux·笔记
帅云毅12 小时前
Web3.0的认知补充(去中心化)
笔记·学习·web3·去中心化·区块链
豆豆12 小时前
day32 学习笔记
图像处理·笔记·opencv·学习·计算机视觉