网站推广.NET

网站推广.NET

深度剖析:微信小程序详细说明蓝牙API使用情

来源:互联网

使用mpvue开发小程序微信小程序蓝牙连接过程的简要介绍在蓝牙连接过程中,一些API需要在1到2秒的计时器延迟后执行,为什么我不这样做?不知道为什么,小程序有这样的要求1.首先是初始化蓝牙:openBluetoothAdapter()

if (wx.openBluetoothAdapter) { wx.openBluetoothAdapter({ success: function(res) { /* 获取本机的蓝牙状态 */ setTimeout(() => { getBluetoothAdapterState() }, 1000) }, fail: function(err) { // 初始化失败 } })} else {}

2.检查本机的蓝牙是否可用:在成功初始化蓝牙之后,应在回调中调用它。

getBluetoothAdapterState() { var that = this; that.toastTitle = '检查蓝牙状态' wx.getBluetoothAdapterState({ success: function(res) { startBluetoothdevicesDiscovery() }, fail(res) { console.log(res) } })}

3.开始搜索蓝牙设备:

startBluetoothDevicesDiscovery() { var that = this; setTimeout(() => { wx.startBluetoothDevicesDiscovery({ success: function(res) { /* 获取蓝牙设备列表 */ that.getBluetoothDevices() }, fail(res) { } }) }, 1000)}

4.获取搜索到的蓝牙设备的列表/ that.deviceName是获得的蓝牙设备的名称,因为Android和Apple手机上显示的蓝牙设备的蓝牙地址不同,因此根据设备名称匹配蓝牙/

getBluetoothDevices() { var that = this; setTimeout(() => { wx.getBluetoothDevices({ services: [], allowDuplicatesKey: false, interval: 0, success: function(res) { if (res.devices.length > 0) { if (JSON.stringify(res.devices).indexOf(that.deviceName) !== -1) { for (let i = 0; i < res.devices.length; i++) { if (that.deviceName === res.devices[i].name) { /* 根据指定的蓝牙设备名称匹配到deviceId */ that.deviceId = that.devices[i].deviceId; setTimeout(() => { that.connectTO(); }, 2000); }; }; } else { } } else { } }, fail(res) { console.log(res, '获取蓝牙设备列表失败=====') } }) }, 2000)},

5.连接到与蓝牙匹配的蓝牙设备ID,并发送连接到蓝牙的请求。连接成功后,应断开蓝牙搜索API,然后获取连接的蓝牙设备的服务

connectTO() { wx.createBLEConnection({ deviceId: deviceId, success: function(res) { that.connectedDeviceId = deviceId; /* 4.获取连接设备的service服务 */ that.getBLEDeviceServices(); wx.stopBluetoothDevicesDiscovery({ success: function(res) { console.log(res, '停止搜索') }, fail(res) { } }) }, fail: function(res) { } })}

6.获得蓝牙设备的服务。获得了多个serviceId。尝试连接并最终确定哪个是该服务的稳定版本。获取服务后获取设备特征值。

getBLEDeviceServices() { setTimeout(() => { wx.getBLEDeviceServices({ deviceId: that.connectedDeviceId, success: function(res) { that.services = res.services /* 获取连接设备的所有特征值 */ that.getBLEDeviceCharacteristics() }, fail: (res) => { } }) }, 2000)},

7.获取蓝牙设备的特征值。特征值有多个,最后可以使用的内容是特征值id,它可以被读取,写入和监听。

getBLEDeviceCharacteristics() { setTimeout(() => { wx.getBLEDeviceCharacteristics({ deviceId: connectedDeviceId, serviceId: services[2].uuid, success: function(res) { for (var i = 0; i < res.characteristics.length; i++) { if ((res.characteristics[i].properties.notify || res.characteristics[i].properties.indicate) && (res.characteristics[i].properties.read && res.characteristics[i].properties.write)) { console.log(res.characteristics[i].uuid, '蓝牙特征值 ==========') /* 获取蓝牙特征值 */ that.notifyCharacteristicsId = res.characteristics[i].uuid // 启用低功耗蓝牙设备特征值变化时的 notify 功能 that.notifyBLECharacteristicValueChange() } } }, fail: function(res) { } }) }, 1000) },

8.启动通知蓝牙监视功能,然后使用wx.onBLECharacteristicValueChange监视蓝牙设备传输的数据。接收的数据和发送的数据必须是辅助数据,并且显示时需要转换页面

notifyBLECharacteristicValueChange() { // 启用低功耗蓝牙设备特征值变化时的 notify 功能 var that = this; console.log('6.启用低功耗蓝牙设备特征值变化时的 notify 功能') wx.notifyBLECharacteristicValueChange({ state: true, deviceId: that.connectedDeviceId, serviceId: that.notifyServicweId, characteristicId: that.notifyCharacteristicsId, complete(res) { /*用来监听手机蓝牙设备的数据变化*/ wx.onBLECharacteristicValueChange(function(res) { /**/ that.balanceData += that.buf2string(res.value) that.hexstr += that.receiveData(res.value) }) }, fail(res) { console.log(res, '启用低功耗蓝牙设备监听失败') that.measuringTip(res) } }) }, /*转换成需要的格式*/ buf2string(buffer) { var arr = Array.prototype.map.call(new Uint8Array(buffer), x => x) return arr.map((char, i) => { return String.fromCharCode(char); }).join(''); }, receiveData(buf) { return this.hexCharCodeToStr(this.ab2hex(buf)) }, /*转成二进制*/ ab2hex (buffer) { var hexArr = Array.prototype.map.call( new Uint8Array(buffer), function (bit) { return ('00' + bit.toString(16)).slice(-2) } ) return hexArr.join('') }, /*转成可展会的文字*/ hexCharCodeToStr(hexCharCodeStr) { var trimedStr = hexCharCodeStr.trim(); var rawStr = trimedStr.substr(0, 2).toLowerCase() === '0x' ? trimedStr.substr(2) : trimedStr; var len = rawStr.length; var curCharCode; var resultStr = []; for (var i = 0; i < len; i = i + 2) { curCharCode = parseInt(rawStr.substr(i, 2), 16); resultStr.push(String.fromCharCode(curCharCode)); } return resultStr.join(''); },

将数据发送到蓝牙设备

sendData(str) { let that = this; let dataBuffer = new ArrayBuffer(str.length) let dataView = new DataView(dataBuffer) for (var i = 0; i < str.length; i++) { dataView.setUint8(i, str.charAt(i).charCodeAt()) } let dataHex = that.ab2hex(dataBuffer); this.writeDatas = that.hexCharCodeToStr(dataHex); wx.writeBLECharacteristicValue({ deviceId: that.connectedDeviceId, serviceId: that.notifyServicweId, characteristicId: that.notifyCharacteristicsId, value: dataBuffer, success: function (res) { console.log('发送的数据:' + that.writeDatas) console.log('message发送成功') }, fail: function (res) { }, complete: function (res) { } }) },

当您不需要连接蓝牙时,请关闭蓝牙并关闭蓝牙模块

// 断开设备连接closeConnect() { if (that.connectedDeviceId) { wx.closeBLEConnection({ deviceId: that.connectedDeviceId, success: function(res) { that.closeBluetoothAdapter() }, fail(res) { } }) } else { that.closeBluetoothAdapter() }},// 关闭蓝牙模块closeBluetoothAdapter() { wx.closeBluetoothAdapter({ success: function(res) { }, fail: function(err) { } })},

在向蓝牙设备传输数据和从蓝牙设备接收数据的过程中,未使用读取的API。我不知道是否有潜在的问题。当前的在线操作是查找任何问题。今天的蓝牙使用心已过去,谢谢