uniapp 通过蓝牙连接设备并发送命令

如题所述

第1个回答  2022-06-03
openBluetoothAdapter() {

uni.openBluetoothAdapter({

success: e => {

// console.log('初始化蓝牙成功:' + e.errMsg);

this.onBluetoothDeviceFound()

uni.getBluetoothAdapterState({

success: function(res) {

// 初始化完毕开始搜索

if (res.available) {

if (res.discovering) {

// console.log('停止连接');

this.closeBluetooth()

}

uni.startBluetoothDevicesDiscovery({

success: res => {

},

fail: res => {

onsole.log("查找设备失败!");

uni.showToast({

icon: "none",

title: "查找设备失败!",

duration: 3000,

})

}

})

} else {

console.log('本机蓝牙不可用')

}

}

})

},

fail: e => {

if (e.errCode == 10001) {

uni.showModal({

title: "提示",

content: "您的蓝牙没有打开,请打开蓝牙",

success: function(res) {

if (res.confirm == true) {

if (uni.getSystemInfoSync().platform == 'ios') {

} else if (uni.getSystemInfoSync().platform === 'android') {

}

} else {

uni.navigateBack({

url: '../../detail3/detail3'

})

}

},

});

}

console.log('初始化蓝牙失败,错误码:' + (e.errCode || e.errMsg));

}

});

},

onBluetoothDeviceFound() {

// console.log("监听寻找新设备");

uni.onBluetoothDeviceFound(devices => {

// console.log('开始监听寻找到新设备的事件');

// console.log(devices.length);

this.getBluetoothDevices();

});

},

getBluetoothDevices() {

// console.log("获取蓝牙设备");

uni.getBluetoothDevices({

success: res => {

// console.log('获取蓝牙设备');

this.resdic = res

// console.log(res)

// console.log('devices.length===='+this.resdic.devices.length);

for (let i = 0; i < this.resdic.devices.length; i++) {

let devicesDic = this.resdic.devices[i];

if (devicesDic.name && devicesDic.name == '<Dobiy>' && devicesDic.advertisServiceUUIDs) {

this.deviceIdStr = devicesDic.deviceId

this.stopBluetooth()

this.createBLEConnection(devicesDic.deviceId)

}

}

}

});

},

createBLEConnection(deviceIds) {

console.log("连接蓝牙---------------" + deviceIds)

// setTimeout(function(){

//    that.closeBLEConnection();

//    that.createBLEConnection(deviceIds)

// },5000)

uni.createBLEConnection({

deviceId: deviceIds.toString(),

success: (res) => {

console.log('蓝牙连接成功');

// this.getBLEDeviceServices(deviceIds)

this.stopBluetooth()

var that = this

uni.getSystemInfo({

success(res) {

if (res.platform == 'ios') {

setTimeout(() => {

that.getBLEDeviceServices(deviceIds)

}, 2000)

} else {

setTimeout(() => {

that.nogetBLEDeviceServices(deviceIds)

}, 3000)

}

},

fail(res) {

console.log(777777777777777)

}

})

},

fail: (res) => {

console.log('蓝牙连接失败:' + res.errCode)

that.closeBLEConnection();

that.createBLEConnection(deviceIds)

},

});

},

async getBLEDeviceServices(deviceIds) {

var that = this

let deviceServices = await uni.getBLEDeviceServices({

deviceId: deviceIds

})

if (deviceServices[0] == null) {

let services = deviceServices[1].services

if (services.length == 0) {

setTimeout(() => {

that.getBLEDeviceServices(deviceIds)

}, 1500)

} else {

console.log(services, 88888888888)

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

let serviceId = services[i].uuid

// console.log('serviceId====' + serviceId);

let characteristicsDic = await uni.getBLEDeviceCharacteristics({

deviceId: deviceIds,

serviceId: serviceId,

})

.then(data => {

// console.log(JSON.stringify(data))

if (data[0] == null) {

let characteristicsArr = data[1].characteristics

let properties = characteristicsArr[0].properties

console.log(properties)

if (properties.write == true) {

that.serviceIdStr = serviceId;

that.characteristicsIdStr = data[1].characteristics[0].uuid;

that.notifyBLECharacteristicValueChange(that.characteristicsIdStr)

// console.log(deviceIds)

// console.log(that.serviceIdStr)

// console.log(that.characteristicsIdStr)

that.writeBLECharacteristic(deviceIds, serviceId, that.characteristicsIdStr)

} else {

console.log('不可编辑', data[1].characteristics[0].uuid)

}

}

})

}

}

} else {

uni.showModal({

title: "提示",

content: "获取设备服务信息失败,请重新获取",

showCancel: false,

success(res) {

uni.navigateBack({

url: '../uploadImg/uploadImg'

})

}

})

}

},

nogetBLEDeviceServices(deviceIds) {

var that = this

console.log(777777)

uni.getBLEDeviceServices({

deviceId: deviceIds,

success(res) {

let services = res.services

console.log(services, 55555)

if (services.length == 0) {

setTimeout(() => {

that.nogetBLEDeviceServices(deviceIds)

}, 3000)

} else {

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

let serviceId = services[i].uuid

//这个比对serviceId,设备厂家会告诉,因为安卓获取特征值都是不可写入的,iOS 的可以写入的,所以安卓直接判断serviceId是不是厂家发的serviceId

if (serviceId == '') {

uni.getBLEDeviceCharacteristics({

deviceId: deviceIds,

serviceId: serviceId,

success(result) {

let propertiesDic = result.characteristics[0]

console.log(propertiesDic, 55555)

// if (propertiesDic.properties.write == true) {

that.serviceIdStr = serviceId;

that.characteristicsIdStr = propertiesDic.uuid;

that.notifyBLECharacteristicValueChange(that.characteristicsIdStr)

setTimeout(() =>{

that.writeBLECharacteristic(deviceIds, serviceId, that.characteristicsIdStr)

}, 2000)

// } else {

// console.log('不可编辑', propertiesDic.uuid)

// }

},

fail(result) {

console.log(result, 2222222)

}

})

}

}

}

},

fail(res) {

console.log(res, 8888888)

}

})

},

一定要调用这个方法,否则无法监听设备返回的数据,之前一直以为在uni.writeBLECharacteristicValue的回调里能得到返回的值,这个方法没有用,结果试了几天都不行,

notifyBLECharacteristicValueChange(characteristicId) {

console.log(characteristicId, 'characteristicId')

uni.notifyBLECharacteristicValueChange({

state: true, // 启用 notify 功能

deviceId: this.deviceIdStr,

serviceId: this.serviceIdStr,

characteristicId: this.characteristicsIdStr,

success: (res) => {

// console.log(res)

// console.log(this.characteristicId)

console.log('notifyBLECharacteristicValueChange success', res)

// that.writeBLECharacteristic(deviceIds, serviceId, that.characteristicsIdStr)             

this.onBLECharacteristicValue()

},

fail: (res) => {

console.log('notifyBLECharacteristicValueChange success2', res.errMsg)

}

})

},

onBLECharacteristicValue() {

var that = this

uni.onBLECharacteristicValueChange(function(res) {

// console.log(`characteristic ${res.characteristicId} has changed, now is ${res.value}`)

let resultStr = that.bufferString(res.value)

// console.log(resultStr,111)

if (resultStr && resultStr != '') {

//resultStr就是设备上返回的数据,根据设备不同,获取的设备格式也就不同,自己筛选吧

}

})

},

writeBLECharacteristic(deviceId, serviceId, characteristicId) {

var that = this

console.log(1111111111)

let sgInt = that.string2buffer('<sAg>')

// console.log(sgInt.byteLength)

uni.writeBLECharacteristicValue({

deviceId: that.deviceIdStr,

serviceId: that.serviceIdStr,

characteristicId: that.characteristicsIdStr,

value: sgInt,

success: function(res) {

console.log(typeof(res))

console.log('writeBLECharacteristicValue success', res.errMsg)

// that.closeBluetooth()

},

fail: function(res) {

console.log(typeof(res))

console.log('writeBLECharacteristicValue fail==', res.errCode, res.errMsg)

}

})

},

//字符串转arraybuffer

string2buffer: function(str) {

// 首先将字符串转为16进制

let val = ""

for (let i = 0; i < str.length; i++) {

if (val === '') {

val = str.charCodeAt(i).toString(16)

} else {

val += ',' + str.charCodeAt(i).toString(16)

}

}

// console.log(val)

// 将16进制转化为ArrayBuffer

return new Uint8Array(val.match(/[\da-f]{2}/gi).map(function(h) {

return parseInt(h, 16)

})).buffer

},

//arraybuffer 转字符串

bufferString: function(str) {

// ArrayBuffer转16进度字符串示例

function ab2hex(buffer) {

const hexArr = Array.prototype.map.call(

new Uint8Array(buffer),

function(bit) {

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

}

)

return hexArr.join('')

}

//16进制

let systemStr = ab2hex(str)

// console.log(hexCharCodeToStr(systemStr),99)

function hexCharCodeToStr(hexCharCodeStr) {

var trimedStr = hexCharCodeStr.trim();

var rawStr =

trimedStr.substr(0, 2).toLowerCase() === "0x" ?

trimedStr.substr(2) :

trimedStr;

var len = rawStr.length;

if (len % 2 !== 0) {

alert("Illegal Format ASCII Code!");

return "";

}

var curCharCode;

var resultStr = [];

for (var i = 0; i < len; i = i + 2) {

curCharCode = parseInt(rawStr.substr(i, 2), 16); // ASCII Code Value

let str5 = String.fromCharCode(curCharCode)

if (str5.startsWith('\n') == false) {

resultStr.push(String.fromCharCode(curCharCode));

}

}

return resultStr.join("");

}

// console.log(hexCharCodeToStr(systemStr),888)

return hexCharCodeToStr(systemStr)

},

//监听低功耗蓝牙连接状态的改变事件

onBLEConnectionStateChange() {

uni.onBLEConnectionStateChange(function(res) {

if (!res.connected) {

// console.log('蓝牙断开链接')

this.closeBluetooth()

}

})

},

stopBluetooth() {

uni.stopBluetoothDevicesDiscovery({

success: e => {

// console.log('停止搜索蓝牙设备:' + e.errMsg);

},

fail: e => {

// console.log('停止搜索蓝牙设备失败,错误码:' + e.errCode);

}

});

},

//关闭蓝牙模块

closeBluetooth() {

uni.closeBluetoothAdapter({

success(res) {

console.log(res)

}

})

}

},
相似回答