微信小程序蓝牙连接 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>
相关推荐
Purple Coder14 分钟前
第6章 图论
笔记
胡西风_foxww1 小时前
【ES6复习笔记】数值扩展(16)
前端·笔记·es6·扩展·数值
Somnus陳2 小时前
软考架构师笔记-计算机系统组成-1
笔记·系统架构
LuH11244 小时前
【论文阅读笔记】IC-Light
论文阅读·笔记
是小菜呀!4 小时前
实验四 触发器
笔记
悲伤小伞4 小时前
C++_数据结构_详解二叉搜索树
c语言·数据结构·c++·笔记·算法
灰太狼不爱写代码7 小时前
CUDA11.4版本的Pytorch下载
人工智能·pytorch·笔记·python·学习
Aileen_0v012 小时前
【AI驱动的数据结构:包装类的艺术与科学】
linux·数据结构·人工智能·笔记·网络协议·tcp/ip·whisper
Rinai_R14 小时前
计算机组成原理的学习笔记(7)-- 存储器·其二 容量扩展/多模块存储系统/外存/Cache/虚拟存储器
笔记·物联网·学习
吃着火锅x唱着歌14 小时前
PHP7内核剖析 学习笔记 第四章 内存管理(1)
android·笔记·学习