android 获取蓝牙设备id_小程序中,iOS设备获取蓝牙设备的Mac地址

本文介绍了在Android和iOS设备上如何获取蓝牙设备的Mac地址。在Android中,deviceId即为Mac地址,而在iOS中,需要通过180A服务id的2A23特征值来获取。文中提供了一个JavaScript函数array2String用于将获取到的值转换为Mac地址格式,并展示了相关代码示例。
摘要由CSDN通过智能技术生成

遇到的问题

在使用蓝牙的过程中,我们需要获取蓝牙设备的Mac地址。在Android设备上,onBluetoothDeviceFound方法中,deviceId是蓝牙设备的Mac地址。而在 iOS设备上,deviceId则是蓝牙设备的uuid。我们想要在iOS设备上获取Mac地址,就需要自己想办法。

7f825e2ad363c8f0781c8c0dd83cf072.png

解决的方法

通过查阅一些相关资料,发现有些蓝牙设备有180A这个服务id,该服务id中的2A23特征值可以获取蓝牙设备的Mac地址。具体操作参考下面的代码:

function array2String(buffer) {

let hexArr = Array.prototype.map.call(

new Uint8Array(buffer),

function (bit) {

return ('00' + bit.toString(16)).slice(-2)

}

)

return `${hexArr[7]}:${hexArr[6]}:${hexArr[5]}:${hexArr[2]}:${hexArr[1]}:${hexArr[0]}`

}

// 连接蓝牙

wx.createBLEConnection({

deviceId,

success: res => {

// 获取服务id

wx.getBLEDeviceServices({

deviceId,

success: res => {

let serviceId = ''

for (let i = 0, len = res.services.length; i < len; i++) {

// 使用包含 180A 的服务id

if (~res.services[i].uuid.indexOf('180A')) {

serviceId = res.services[i].uuid

// 获取对应的特征值

wx.getBLEDeviceCharacteristics({

deviceId,

serviceId,

success: res => {

let characteristicId = ''

for (let i = 0, len = res.characteristics.length; i < len; i++) {

// 使用含有 2A23 对应的特征值

if (~res.characteristics[i].uuid.indexOf('2A23')) {

characteristicId = res.characteristics[i].uuid

}

}

wx.readBLECharacteristicValue({

deviceId,

serviceId,

characteristicId,

success: res => {

console.log('mac read ----------', res)

}

})

wx.notifyBLECharacteristicValueChange({

deviceId,

serviceId,

characteristicId,

state: true,

})

wx.onBLECharacteristicValueChange(function (characteristic) {

// 当特征值是查询 Mac 地址时

if (~characteristic.characteristicId.indexOf('2A23')) {

let macInfo = (array2String(characteristic.value)).toUpperCase()

console.log('mac info -----------', macInfo)

}

})

}

})

}

}

}

})

}

})

后续

当获取到蓝牙设备Mac地址后,我们一般还是要继续使用蓝牙的。这个时候需要重新获取蓝牙设备的服务id,以及新的特征值。

wx.getBLEDeviceCharacteristics({

deviceId,

// 新的服务id, 通过 getBLEDeviceServices 获取

serviceId: newServiceId,

success: res => {

wx.notifyBLECharacteristicValueChange({

state: true,

deviceId,

serviceId: newServiceId,

// 新的特征值

characteristicId: newCharacteristicId

})

// 监听低功耗蓝牙连接的错误事件

wx.onBLEConnectionStateChange(res => { })

}

})

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值