初始化藍(lán)牙模塊
openBluetoothAdapter() {
uni.openBluetoothAdapter({
success: e => {
// console.log('初始化藍(lán)牙成功:' + e.errMsg);
this.onBluetoothDeviceFound()
//獲取本機(jī)藍(lán)牙適配器狀態(tài)。
uni.getBluetoothAdapterState({
success: function(res) {
// 初始化完畢開(kāi)始搜索
if (res.available) {
if (res.discovering) {
// console.log('停止連接');
this.closeBluetooth()
}
uni.startBluetoothDevicesDiscovery({
success: res => {
},
fail: res => {
onsole.log("查找設(shè)備失敗!");
uni.showToast({
icon: "none",
title: "查找設(shè)備失??!",
duration: 3000,
})
}
})
} else {
console.log('本機(jī)藍(lán)牙不可用')
}
}
})
},
fail: e => {
if (e.errCode == 10001) {
uni.showModal({
title: "提示",
content: "您的藍(lán)牙沒(méi)有打開(kāi),請(qǐng)打開(kāi)藍(lán)牙",
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('初始化藍(lán)牙失敗,錯(cuò)誤碼:' + (e.errCode || e.errMsg));
}
});
},
//發(fā)現(xiàn)外圍設(shè)備
onBluetoothDeviceFound() {
// console.log("監(jiān)聽(tīng)尋找新設(shè)備");
uni.onBluetoothDeviceFound(devices => {
// console.log('開(kāi)始監(jiān)聽(tīng)尋找到新設(shè)備的事件');
// console.log(devices.length);
this.getBluetoothDevices();
});
},
//獲取在藍(lán)牙模塊生效期間所有已發(fā)現(xiàn)的藍(lán)牙設(shè)備。包括已經(jīng)和本機(jī)處于連接狀態(tài)的設(shè)備。
getBluetoothDevices() {
// console.log("獲取藍(lán)牙設(shè)備");
uni.getBluetoothDevices({
success: res => {
// console.log('獲取藍(lán)牙設(shè)備');
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)
}
}
}
});
},
//連接低功耗藍(lán)牙設(shè)備。
createBLEConnection(deviceIds) {
console.log("連接藍(lán)牙---------------" + deviceIds)
// setTimeout(function(){
//? ? that.closeBLEConnection();
//? ? that.createBLEConnection(deviceIds)
// },5000)
uni.createBLEConnection({
deviceId: deviceIds.toString(),
success: (res) => {
console.log('藍(lán)牙連接成功');
// 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('藍(lán)牙連接失?。? + res.errCode)
that.closeBLEConnection();
that.createBLEConnection(deviceIds)
},
});
},
//iOS端獲取ServicesID
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: "獲取設(shè)備服務(wù)信息失敗,請(qǐng)重新獲取",
showCancel: false,
success(res) {
uni.navigateBack({
url: '../uploadImg/uploadImg'
})
}
})
}
},
//安卓獲取Servicesid
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
//這個(gè)比對(duì)serviceId,設(shè)備廠家會(huì)告訴,因?yàn)榘沧揩@取特征值都是不可寫(xiě)入的,iOS 的可以寫(xiě)入的,所以安卓直接判斷serviceId是不是廠家發(fā)的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)
}
})
},
// 啟用 notify 功能
一定要調(diào)用這個(gè)方法,否則無(wú)法監(jiān)聽(tīng)設(shè)備返回的數(shù)據(jù),之前一直以為在uni.writeBLECharacteristicValue的回調(diào)里能得到返回的值,這個(gè)方法沒(méi)有用,結(jié)果試了幾天都不行,
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就是設(shè)備上返回的數(shù)據(jù),根據(jù)設(shè)備不同,獲取的設(shè)備格式也就不同,自己篩選吧
}
})
},
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)
}
})
},
//字符串轉(zhuǎn)arraybuffer
string2buffer: function(str) {
// 首先將字符串轉(zhuǎn)為16進(jìn)制
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進(jìn)制轉(zhuǎn)化為ArrayBuffer
return new Uint8Array(val.match(/[\da-f]{2}/gi).map(function(h) {
return parseInt(h, 16)
})).buffer
},
//arraybuffer 轉(zhuǎn)字符串
bufferString: function(str) {
// ArrayBuffer轉(zhuǎn)16進(jìn)度字符串示例
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進(jìn)制
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)
},
//監(jiān)聽(tīng)低功耗藍(lán)牙連接狀態(tài)的改變事件
onBLEConnectionStateChange() {
uni.onBLEConnectionStateChange(function(res) {
if (!res.connected) {
// console.log('藍(lán)牙斷開(kāi)鏈接')
this.closeBluetooth()
}
})
},
stopBluetooth() {
uni.stopBluetoothDevicesDiscovery({
success: e => {
// console.log('停止搜索藍(lán)牙設(shè)備:' + e.errMsg);
},
fail: e => {
// console.log('停止搜索藍(lán)牙設(shè)備失敗,錯(cuò)誤碼:' + e.errCode);
}
});
},
//關(guān)閉藍(lán)牙模塊
closeBluetooth() {
uni.closeBluetoothAdapter({
success(res) {
console.log(res)
}
})
}
},