其他分享
首页 > 其他分享> > UNI-APP实现物联网中BLE蓝牙的数据交互

UNI-APP实现物联网中BLE蓝牙的数据交互

作者:互联网

前言:UNI-APP是一个使用 Vue.js 开发所有前端应用的框架,开发者编写一套代码,可发布到iOS、Android、Web(响应式)、以及各种小程序(微信/支付宝/百度/头条/飞书/QQ/快手/钉钉/淘宝)、快应用等多个平台。即使你不需要发布到那么多的平台,UNI-APP也是一个不错的微信小程序的开发框架

UNI-APP的官网

了解蓝牙API返回的报错

错误码错误信息说明
0ok正常
10000not init未初始化蓝牙适配器
10001not available当前蓝牙适配器不可用
10002no device没有找到指定设备
10003connection fail连接失败
10004no service没有找到指定服务
10005no characteristic没有找到指定特征值
10006no connection当前连接已断开
10007property not support当前特征值不支持此操作
10008system error其余所有系统上报的异常
10009system not supportAndroid 系统特有,系统版本低于 4.3 不支持 BLE
10012operate time out连接超时
10013invalid_data连接 deviceId 为空或者是格式不正确

初始化蓝牙模块

uni.openBluetoothAdapter(OBJECT)

示例代码

uni.openBluetoothAdapter({
	success: (res) => {
		if (res.errMsg == 'openBluetoothAdapter:ok') {}
	}
})

监听蓝牙状态变化事件

uni.onBluetoothAdapterStateChange(CALLBACK)
CALLBACK 返回参数

属性类型说明
availableboolean蓝牙适配器是否可用
discoveringboolean蓝牙适配器是否处于搜索状态

示例代码

uni.onBLEConnectionStateChange((res) => {
	if (res.connected == false) {
		this.cut = true
		uni.showModal({
			title: "蓝牙连接断开",
			content: "是否重新搜索",
			success: (res) => {
				if (res.confirm) this.search()
			}
		})
	}
})

搜索周围的蓝牙

uni.startBluetoothDevicesDiscovery(OBJECT)

OBJECT 参数说明

属性类型默认值必填说明
servicesArray要搜索但蓝牙设备主 service 的 uuid 列表。某些蓝牙设备会广播自己的主 service 的 uuid。如果设置此参数,则只搜索广播包有对应 uuid 的主服务的蓝牙设备。建议主要通过该参数过滤掉周边不需要处理的其他蓝牙设备。
allowDuplicatesKeybooleanfalse是否允许重复上报同一设备。如果允许重复上报,则 uni.onBlueToothDeviceFound 方法会多次上报同一设备,但是 RSSI 值会有不同。
intervalnumber0上报设备的间隔。0 表示找到新设备立即上报,其他数值根据传入的间隔上报。
successfunction接口调用成功的回调函数
failfunction接口调用失败的回调函数
completefunction接口调用结束的回调函数(调用成功、失败都会执行)

示例代码

uni.startBluetoothDevicesDiscovery({
	allowDuplicatesKey: true, //是否允许重复上报同一设备
	interval: 0, //搜索间隔
	success: (res2) => {
		if (res2.errMsg == 'startBluetoothDevicesDiscovery:ok') {
			this.monitor()
		}
	}
})

监听寻找到新设备的事件

uni.onBluetoothDeviceFound(CALLBACK)

CALLBACK 返回参数

属性类型说明
devicesArray新搜索到的设备列表

devices 的结构

属性类型说明
namestring蓝牙设备名称,某些设备可能没有
deviceIdstring用于区分设备的 id
RSSInumber当前蓝牙设备的信号强度
advertisDataArrayBuffer当前蓝牙设备的广播数据段中的 ManufacturerData 数据段
advertisServiceUUIDsArray当前蓝牙设备的广播数据段中的 ServiceUUIDs 数据段
localNamestring当前蓝牙设备的广播数据段中的 LocalName 数据段
serviceDataObject当前蓝牙设备的广播数据段中的 ServiceData 数据段

示例代码

uni.onBluetoothDeviceFound((res) => {
	res.devices.forEach(result => {
		if ((result.name != '') && (result.localName != '')) {
			let idx = util.inArray(this.booth.list, 'deviceId', result.deviceId)
			if (idx === -1) {
				this.booth.list.push(result)
			} else {
				this.booth.list[idx] = result
			}
		}
	})
})

停止搜寻附近的蓝牙外围设备

uni.stopBluetoothDevicesDiscovery(OBJECT)

OBJECT 参数说明

属性类型说明
successfunction接口调用成功的回调函数
failfunction接口调用失败的回调函数
completefunction接口调用结束的回调函数(调用成功、失败都会执行)

示例代码

stopSearch() {
	uni.stopBluetoothDevicesDiscovery()
}

连接低功耗蓝牙设备

uni.createBLEConnection(OBJECT)

OBJECT 参数说明

属性类型必填说明
deviceIdstring用于区分设备的 id
timeoutnumber超时时间,单位ms,不填表示不会超时
successfunction接口调用成功的回调函数
failfunction接口调用失败的回调函数
completefunction接口调用结束的回调函数(调用成功、失败都会执行)

示例代码

uni.createBLEConnection({
	deviceId: this.uuid.deviceId,
	success: (res) => {
		if (res.errMsg == 'createBLEConnection:ok') {
			setTimeout(() => {
				this.Service()
				this.BLEChange()
			}, 2000)
		}
	}
})

获取蓝牙设备所有服务

uni.getBLEDeviceServices(OBJECT)

OBJECT 参数说明

属性类型必填说明
deviceIdstring蓝牙设备 id
successfunction接口调用成功的回调函数
failfunction接口调用失败的回调函数
completefunction接口调用结束的回调函数(调用成功、失败都会执行)

success 返回参数说明

属性类型说明
servicesArray设备服务列表

res.services 的结构

属性类型说明
uuidstring蓝牙设备服务的 uuid
isPrimaryboolean该服务是否为主服务

示例代码

uni.getBLEDeviceServices({
	deviceId: this.uuid.deviceId,
	success: (res) => {
		if (res.services.length == 0) {
			util.showError("找不到服务")
		} else {
			let booth = true
			for (let i = 0; i < res.services.length; i++) {
				if (res.services[i].uuid == this.uuid.service) {
					booth = false
					this.Character()
					break;
				}
			}
			if (booth) util.showError("服务uuid错误")
		}
	}
})

获取蓝牙设备某个服务中所有特征值

uni.getBLEDeviceCharacteristics(OBJECT)

OBJECT 参数说明

属性类型必填说明
deviceIdstring蓝牙设备 id
serviceIdstring蓝牙服务 uuid,需要使用getBLEDeviceServices获取
successfunction接口调用成功的回调函数
failfunction接口调用失败的回调函数
completefunction接口调用结束的回调函数(调用成功、失败都会执行)

success 返回参数说明

属性类型说明
characteristicsArray设备服务列表

res.characteristics 的结构

属性类型说明
uuidstring蓝牙设备特征值的 uuid
propertiesObject该特征值支持的操作类型

properties 的结构

属性类型说明
uuidstring蓝牙设备特征值的 uuid
readboolean该特征值是否支持 read 操作
writeboolean该特征值是否支持 write 操作
notifyboolean该特征值是否支持 notify操作
indicateboolean该特征值是否支持 indicate操作

示例代码

				uni.getBLEDeviceServices({
					deviceId: this.uuid.deviceId,
					success: (res) => {
						if (res.services.length == 0) {
							util.showError("找不到服务")
						} else {
							let booth = true
							for (let i = 0; i < res.services.length; i++) {
								if (res.services[i].uuid == this.uuid.service) {
									booth = false
									this.Character()
									break;
								}
							}
							if (booth) util.showError("服务uuid错误")
						}
					}
				})

启用低功耗蓝牙设备特征值变化时的 notify 功能

uni.notifyBLECharacteristicValueChange(OBJECT)

OBJECT 参数说明

属性类型必填说明
deviceIdstring蓝牙设备 id
serviceIdstring蓝牙特征值对应服务的 uuid
characteristicIdstring蓝牙特征值的 uuid
stateboolean是否启用 notify
successfunction接口调用成功的回调函数
failfunction接口调用失败的回调函数
completefunction接口调用结束的回调函数(调用成功、失败都会执行)

示例代码

				uni.notifyBLECharacteristicValueChange({
					deviceId: this.uuid.deviceId,
					serviceId: this.uuid.service,
					characteristicId: this.uuid.character,
					state: true,
					success: (res) => {
						if (res.errMsg == 'notifyBLECharacteristicValueChange:ok') {
							uni.hideLoading();
							this.cut = false
							this.BLEValue()
						}
					}
				})

监听低功耗蓝牙设备的特征值变化事件(获取设备发送的信息)

uni.onBLECharacteristicValueChange(CALLBACK)

CALLBACK 返回参数

属性类型说明
deviceIdstring蓝牙设备 id
serviceIdstring蓝牙特征值对应服务的 uuid
characteristicIdstring蓝牙特征值的 uuid
valueArrayBuffer特征值最新的值

###示例代码

				uni.onBLECharacteristicValueChange((res) => {
					let caseoff = this.operation.Receive + util.ab2Str(res.value)
					let len = caseoff.length - 1
					let i = caseoff.charCodeAt(len)
					if (i < 127) {
						this.operation.Receive = ""
						caseoff = util.gbkStrToUtf16Str(caseoff)
						this.operation.receive += caseoff
					} else {
						if (caseoff.charCodeAt(len - 1) > 127) {
							this.operation.Receive = ""
							caseoff = util.gbkStrToUtf16Str(caseoff)
							this.operation.receive += caseoff
						} else {
							this.operation.Receive = caseoff
						}
					}
				})

向低功耗蓝牙写入数据

uni.writeBLECharacteristicValue(OBJECT)

OBJECT 参数说明

属性类型必填说明
deviceIdstring蓝牙设备 id
serviceIdstring蓝牙特征值对应服务的 uuid
characteristicIdstring蓝牙特征值的 uuid
valueArrayBuffer蓝牙设备特征值对应的二进制值
successfunction接口调用成功的回调函数
failfunction接口调用失败的回调函数
completefunction接口调用结束的回调函数(调用成功、失败都会执行)

示例代码

				let j = 0;
				for (let i = 0; i < SendStr.length / 20; i++) {
					setTimeout(() => {
						let setData = SendStr.substring(j, j + 20)
						setData = new Uint8Array(util.stringToBytes(setData)).buffer
						j = j + 20
						uni.writeBLECharacteristicValue({
							deviceId: this.uuid.deviceId,
							serviceId: this.uuid.service,
							characteristicId: this.uuid.write,
							value: setData,
							fail: (err) => {
								util.showError("发生错误")
							}
						})
					}, i * 300)
				}

以上就是UNI-APP连接蓝牙设备的内容了,如有不理解的地方或者需要码源的小伙可以联系我。

标签:调用,res,APP,蓝牙,接口,uni,BLE,UNI,设备
来源: https://blog.csdn.net/u011577355/article/details/122406708