wx.closeBluetoothAdapter({
success: function(res) {
console.log('先关闭蓝牙连接')
_this.initBlue()
}
});
//初始化设备
initBlue:function(){
var that = this;
wx.openBluetoothAdapter({//调用微信小程序api 打开蓝牙适配器接口
success: function (res) {
wx.showToast({
title: '初始化成功',
icon: 'success',
duration: 800
})
console.log('初始化成功')
that.findBlue();//2.0
},
fail: function (res) {//如果手机上的蓝牙没有打开,可以提醒用户
wx.showToast({
title: '请开启蓝牙',
icon: 'fails',
duration: 1000
})
}
})
},
//搜索蓝牙设备
findBlue(){
var that = this
wx.startBluetoothDevicesDiscovery({
allowDuplicatesKey: false,
interval: 0,
success: function (res) {
wx.showLoading({
title: '正在搜索设备',
})
console.log('正在搜索设备')
setTimeout(()=>{
that.getBlue()//3.0
},1300)
},
fail: function (res) {//如果手机上的蓝牙没有打开,可以提醒用户
wx.showToast({
title: '请重新开启蓝牙',
icon: 'fails',
duration: 1000
})
}
})
},
//获取搜索到的设备信
getBlue(){
var that = this
wx.getBluetoothDevices({
success: function(res) {
for (var i = 0; i < res.devices.length; i++){
//that.data.inputValue:表示的是需要连接的蓝牙设备ID,简单点来说就是我想要连接这个蓝牙设备,所以我去遍历我搜索到的蓝牙设备中是否有这个ID
if (res.devices[i].name == that.data.inputValue || res.devices[i].localName == that.data.inputValue){
that.setData({
deviceId: res.devices[i].deviceId,
consoleLog: "设备:" + res.devices[i].deviceId,
})
wx.hideLoading();
console.log('配对成功'+"设备:" + res.devices[i].deviceId)
that.connetBlue(res.devices[i].deviceId);//4.0
return;
}
}
},
fail: function(){
wx.showToast({
title: '搜索失败,请开启设备蓝牙!',
icon: 'fails',
duration: 1000
})
}
})
},
//获取到设备之后连接蓝牙设备
connetBlue(deviceId){
var that = this;
wx.stopBluetoothDevicesDiscovery({
success: function (res) {
console.log('连接蓝牙时关闭蓝牙搜索');
}
})
wx.createBLEConnection({
// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
deviceId: deviceId,//设备id
success: function (res) {
wx.showToast({
title: '连接成功',
icon: 'fails',
duration: 800
})
console.log("连接蓝牙成功!")
// wx.stopBluetoothDevicesDiscovery({
// success: function (res) {
// console.log('连接蓝牙成功之后关闭蓝牙搜索');
// }
// })
that.getServiceId()//5.0
}
})
},
//连接上需要的蓝牙设备之后,获取这个蓝牙设备的服务uuid
getServiceId(){
var that = this
wx.getBLEDeviceServices({
// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
deviceId: that.data.deviceId,
success: function (res) {
var model = res.services[0]
that.setData({
services: model.uuid
})
that.getCharacteId()//6.0
}
})
},
//查看特征值
getCharacteId(){
var that = this
wx.getBLEDeviceCharacteristics({
// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
deviceId: that.data.deviceId,
// 这里的 serviceId 需要在上面的 getBLEDeviceServices 接口中获取uuid
serviceId: that.data.services,
success: function (res) {
var characteristics = res.characteristics; //获取到所有特征值
var characteristics_length = characteristics.length; //获取到特征值数组的长度
for (var i = 0; i < res.characteristics.length; i++) {//2个值
var model = res.characteristics[i]
if (model.properties.notify == true) {
that.setData({
notifyId: model.uuid//监听的值
})
that.startNotice(model.uuid)//7.0
}
if (model.properties.write == true){
that.setData({
writeId: model.uuid//用来写入的值
})
}
}
}
})
},
startNotice(uuid){
var that = this;
wx.notifyBLECharacteristicValueChange({
state: true, // 启用 notify 功能
// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
deviceId: that.data.deviceId,
// 这里的 serviceId 需要在上面的 getBLEDeviceServices 接口中获取
serviceId: that.data.services,
// 这里的 characteristicId 需要在上面的 getBLEDeviceCharacteristics 接口中获取
characteristicId: uuid, //第一步 开启监听 notityid 第二步发送指令 write
success: function (res) {
// 设备返回的方法
wx.onBLECharacteristicValueChange(function (res) {
// 此时可以拿到蓝牙设备返回来的数据是一个ArrayBuffer类型数据,所以需要通过一个方法转换成字符串
var nonceId = that.ab2hex(res.value)
var str=that.hexCharCodeToStr(nonceId);
console.log()
if(str.match(/p/g)){
var strCut = str.match(/temp:(\S*)/)[1]
var value = strCut.slice(0,2) +'.'+ strCut.slice(-1)
console.log(value)
that.setData({
temperatureVal: value
})
// 播放告警声音
// innerAudioContext = wx.createInnerAudioContext();
// innerAudioContext.loop = true;
// innerAudioContext.src = "/voice/dududu.mp3";
// innerAudioContext.play()
// setTimeout(function () {
// innerAudioContext.stop();
// innerAudioContext.destroy()
// }, 3000);
}
})
}
})
},
/**
* 将字符串转换成ArrayBufer
*/
string2buffer(str) {
let val = ""
if(!str) return;
let length = str.length;
let index = 0;
let array = []
while(index < length){
array.push(str.substring(index,index+2));
index = index + 2;
}
val = array.join(",");
// 将16进制转化为ArrayBuffer
return new Uint8Array(val.match(/[\da-f]{2}/gi).map(function (h) {
return parseInt(h, 16)
})).buffer
},
/**
* 将ArrayBuffer转换成字符串
*/
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;
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
resultStr.push(String.fromCharCode(curCharCode));
}
return resultStr.join("");
},
goCode(){
wx.closeBluetoothAdapter();
wx.hideLoading();
console.log('结束流程')
wx.reLaunch({
url: '/pages/index/index',
})