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

 蓝牙列表期待效果

 代码

<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 = 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>

<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>

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是微信小程序蓝牙连接设备的代码示例: 1. 开启蓝牙适配器 ```javascript wx.openBluetoothAdapter({ success: function (res) { console.log('蓝牙适配器已打开'); }, fail: function (res) { console.log('蓝牙适配器打开失败'); } }) ``` 2. 搜索附近的蓝牙设备 ```javascript wx.startBluetoothDevicesDiscovery({ allowDuplicatesKey: true, success: function (res) { console.log('搜索附近的蓝牙设备成功'); }, fail: function (res) { console.log('搜索附近的蓝牙设备失败'); } }) ``` 3. 建立蓝牙连接 ```javascript wx.createBLEConnection({ deviceId: deviceId, success: function (res) { console.log('蓝牙连接成功'); }, fail: function (res) { console.log('蓝牙连接失败'); } }) ``` 其中,deviceId为搜索到的设备的唯一标识符。 4. 监听蓝牙连接状态 ```javascript wx.onBLEConnectionStateChange(function (res) { console.log(`device ${res.deviceId} state has changed, connected: ${res.connected}`) }) ``` 5. 向设备写入数据 ```javascript wx.writeBLECharacteristicValue({ deviceId: deviceId, serviceId: serviceId, characteristicId: characteristicId, value: buffer, success: function (res) { console.log('数据写入成功'); }, fail: function (res) { console.log('数据写入失败'); } }) ``` 其中,serviceId和characteristicId是设备的服务和特征值的唯一标识符,buffer是要写入的数据。 以上是微信小程序蓝牙连接设备的简单示例代码,具体实现还需要根据实际情况进行调整。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值