uniapp 蓝牙模块封装

蓝牙模块封装代码

class BluetoothClass{
    
    
	constructor(deviceId,serviceId,notifyId,writeId){
    
    
		this.deivceList_find = []
		this.deviceId = deviceId
		this.serviceId = serviceId
		this.notifyId = notifyId
		this.writeId = writeId
	}
	//获取所有蓝牙设备列表
	GetDeviceList(){
    
    
		this.deivceList_find = []
		//初始化蓝牙模块
		uni.openBluetoothAdapter({
    
    
			success(res) {
    
    
				console.log(res)
			},
			fail(err) {
    
    
				console.log(err)
				console.log(初始化蓝牙模块)
			}
		})
		//开始搜素蓝牙模块
		setTimeout(() => {
    
    
			uni.startBluetoothDevicesDiscovery({
    
    
				success(res) {
    
    
					console.log(res)
				},
				fail(err) {
    
    
					console.log(err)
				},
				complete() {
    
    
					console.log('寻找蓝牙设备')
				}
			})
		}, 1000)
		uni.onBluetoothDeviceFound(function(devices) {
    
    
			// console.log('添加搜索到的名字不为空的设备')
			if (devices.devices[0].name != '') {
    
    
				console.log(devices)
				var flag = true
				this.deivceList_find.forEach(item => {
    
    
					if (item.name == devices.devices[0].name) {
    
    
						flag = false
					}
				})
				if (flag) {
    
    
					this.deivceList_find.push(devices.devices[0])
				}
			}
		})
	}
	//监听蓝牙设备
	Notify(){
    
    
		uni.stopBluetoothDevicesDiscovery({
    
    
		  success(res) {
    
    
			console.log('停止蓝牙搜索')
		    console.log(res)
		  }
		})
		
		uni.startBluetoothDevicesDiscovery({
    
    
			success(res) {
    
    
				console.log(res)
			},
			fail(err) {
    
    
				console.log(err)
			}
		})
		//创建蓝牙连接,需要延时2s~5s
		async function CreateBLEConnection() {
    
    
			return new Promise((resolve, reject) => {
    
    
				console.log('开始创建蓝牙连接')
				setTimeout(() => {
    
    
					uni.createBLEConnection({
    
    
						deviceId: this.deviceId,
						success(res) {
    
    
							console.log(res)
							resolve(res)
						},
						fail(err) {
    
    
							console.log(err)
							reject(err)
						},
						complete() {
    
    }
					})
				}, 1000)
			})
		}
		//获取所有蓝牙服务
		async function GetBLEDeviceServices() {
    
    
			return new Promise((resolve, reject) => {
    
    
				console.log('开始获取所有蓝牙服务')
				setTimeout(() => {
    
    
					uni.getBLEDeviceServices({
    
    
						deviceId: this.deviceId,
						success(res) {
    
    
							console.log(res)
							resolve(res)
						},
						fail(err) {
    
    
							console.log(err)
							reject(err)
						}
					})
				}, 5000)
			})
		}
		//获取蓝牙特征值
		async function GetBLEDeviceCharacteristics() {
    
    
			return new Promise((resolve, reject) => {
    
    
				console.log('开始获取蓝牙特征值')
				setTimeout(() => {
    
    
					uni.getBLEDeviceCharacteristics({
    
    
						deviceId: this.deviceId,
						serviceId: this.serviceId,
						success(res) {
    
    
							console.log(res)
							resolve(res)
						},
						fail(err) {
    
    
							console.log(err)
							reject(err)
						}
					})
				}, 1000)
			})
		}
		//开始蓝牙监听
		async function NotifyBLECharacteristicValueChange() {
    
    
			return new Promise((resolve, reject) => {
    
    
				console.log('开始蓝牙监听')
				uni.notifyBLECharacteristicValueChange({
    
    
					deviceId: this.deviceId,
					serviceId: this.serviceId,
					characteristicId: this.notifyId,
					success(res) {
    
    
						resolve(res)
						console.log(res)
						console.log('蓝牙连接成功!')
					},
					fail(err) {
    
    
						console.log(err)
						reject(err)
					}
				})
			})
		}
		async function BluetoothConnect() {
    
    
			console.log('开始异步连接通讯')
			await CreateBLEConnection()
			await GetBLEDeviceServices()
			await GetBLEDeviceCharacteristics()
			await NotifyBLECharacteristicValueChange().then(res => {
    
    })
		}
		BluetoothConnect()
	}
	//写入蓝牙通讯信息,maxCount用于记录蓝牙模块循环次数,因为蓝牙一次最大只能发送20字节的数据
	Write(sendMsg,maxCount){
    
    
		uni.stopBluetoothDevicesDiscovery({
    
    
		  success(res) {
    
    
			console.log('停止蓝牙搜索')
		    console.log(res)
		  }
		})
		async function writeBLECharacteristicValue(e) {
    
    
			var typedArray = new Uint8Array(e.match(/[\da-f]{2}/gi).map(function(h) {
    
    
				return parseInt(h, 16)
			}))
		
			var buffer = typedArray.buffer
			console.log('开始写入蓝牙')
			return new Promise((resolve, reject) => {
    
    
				setTimeout(() => {
    
    
					uni.writeBLECharacteristicValue({
    
    
						deviceId: this.deviceId,
						serviceId: this.serviceId,
						characteristicId: this.writeId,
						value: buffer,
						success(res) {
    
    
							console.log(res)
							resolve(res)
						},
						fail(err) {
    
    
							console.log(err)
							reject(err)
						}
					})
				}, 2000)
			})
		
		}
		async function write() {
    
    
			await writeBLECharacteristicValue(sendMsg).catch(err => {
    
    

			})
		}
		write()
		
		function ab2hex(buffer) {
    
    
			const hexArr = Array.prototype.map.call(
				new Uint8Array(buffer),
				function(bit) {
    
    
					return ('00' + bit.toString(16)).slice(-2)
				}
			)
			return hexArr.join('')
		}
		var count = 0
		//返回一个Promise对象,请用async和await进行异步
		return new Promise((rejects, resolve) => {
    
    
			uni.onBLECharacteristicValueChange(function(res) {
    
    
				console.log('接受到订阅值!')
				console.log(ab2hex(res.value))
				data += ab2hex(res.value)
				count++
				if (count == maxCount) {
    
    
					console.log('返回值为:' + data)
					rejects(data)
				}
			})
		})
	}
}

module.exports = BluetoothClass

代码介绍

实例化

//在js文件的开头引用
const BluetoothClass = require('@/utils/BluetoothHelper.js')

//实例化js对象
const _bluetoothClass = new BluetoothClass('84:C2:E4:40:86:47', '9ECADC24-0EE5-A9E0-93F3-A3B50100406E',
	'9ECADC24-0EE5-A9E0-93F3-A3B50300406E', '9ECADC24-0EE5-A9E0-93F3-A3B50200406E')

测试代码

		BluetoothTest(index) {
    
    
			switch (index) {
    
    
				case 1:
					//获取有名字的蓝牙设备列表
					_bluetoothClass.GetDeviceList()
					break
				case 2:
					//先监听
					_bluetoothClass.Notify()
					break
				case 3:
					//监听之后写入才有返回值
					_bluetoothClass.Write('AA0103009800940000', 2).then(res=>{
    
    
						console.log(res)
					})
					break
				case 4:
					//打印获取的蓝牙设备列表
					console.log(_bluetoothClass.deivceList_find)
					break
			}
		},

猜你喜欢

转载自blog.csdn.net/qq_44695769/article/details/131418048
今日推荐