uniapp 低功耗藍牙使用(經典藍牙用native.js)


<template>
<view>
<view class="jfh" :style="{ height: iStatusBarHeight + dh + 'px' }">
<view class="jfh0" @tap="fanhui">

</view>
<view class="jfh2">

</view>
<image src="../../static/zuob.png"
style="height: 20px;width: 20px;position: absolute;left: 2%;bottom: 12px;z-index: 66666;" @tap="fanhui">
</image>
<view class="jfh1"> BLE </view>

</view>
<view class="ge" :style="{ height: iStatusBarHeight + dh + 'px' }"></view>


<view class="h" @tap="sousuo" v-if="0">
搜索附近藍牙

</view>

<view class="yuan" @tap="cs" v-if="lyzt!='藍牙已關閉'">
<view class="yuan1" v-if="arrsb.length>0&&islj==0">
AYKSOS
</view>
<view class="yuan1" v-if="arrsb.length>0&&islj==1&&dianliang==''">
AYKSOS
</view>
<view class="yuan1" v-if="arrsb.length>0&&islj==1&&dianliang!=''">
電量{{dianliang}}%
</view>
<view class="yuan1" v-if="arrsb.length==0" style="font-size: 18px;">
藍牙搜索中
</view>
<view class="yuan2" v-if="islj==0">
{{strljz}}
</view>
<view class="yuan2" v-if="islj==1" style="padding: 0;text-align: center;">
已連接
</view>

</view>
<view class="yuan" v-if="lyzt=='藍牙已關閉'">
<view class="yuan1" style="font-size: 18px;">
藍牙已關閉
</view>
<view class="yuan2" style="padding: 0;text-align: center;">
請打開藍牙
</view>
</view>



</view>
</template>

<script>
export default {
data() {
return {

lyzt: '',
arrsb: [],
lanuuid: '',
ylj: {
name: '',
id: '',
uuid: '',
uuid2: '',
},
tzarr: [],
tzuuid0: "",
tzuuid1: "",
tzuuid2: "",
tzuuid3: "",
dsq:'',
strljz:'連接中.',
islj:0,
}
},
onLoad() {

var that = this;
setInterval(function(){
if(that.strljz=='連接中.'){
that.strljz='連接中..'
}else if(that.strljz=='連接中..'){
that.strljz='連接中...'
}else{
that.strljz='連接中.'
}

},500)
that.lan()


if (uni.getStorageSync('tzarr') && uni.getStorageSync('tzarr').length > 0) {
that.tzarr = uni.getStorageSync('tzarr')
console.log(that.tzarr)
//41594b54454348
}
uni.getLocation({
type: 'gcj02',
// type: 'wgs84',
geocode:true,
success: function (res) {
console.log('當前位置的經度:' + res.longitude);
console.log('當前位置的緯度:' + res.latitude);
console.log(res)
},
fail: function (res) {
}
});
},
onUnload(){
uni.closeBluetoothAdapter({
success(res) {
console.log('關閉藍牙')
console.log(res)
}
})
var that=this;
if(that.dsq){
clearTimeout(that.dsq)
}
},
methods: {

cs(){
return
//uni.setStorageSync('aykarr', arr);
this.lianjie2(uni.getStorageSync('aykarr')[0].deviceId)
},
duqu() {
//暫時沒用
var that = this

uni.readBLECharacteristicValue({
// 這里的 deviceId 需要已經通過 createBLEConnection 與對應設備建立鏈接
deviceId: that.ylj.id,
// 這里的 serviceId 需要在 getBLEDeviceServices 接口中獲取
serviceId: that.tzuuid0,
characteristicId: that.tzuuid1,
success(restu) {
console.log(restu)
//that.tzuuid0=res.characteristics
},
fail(sbe) {
console.log(sbe)
}
})
},
jjtt() {
var that = this;
console.log('notify')
console.log(that.tzuuid1)
uni.notifyBLECharacteristicValueChange({
state: true, // 啟用 notify 功能
// 這里的 deviceId 需要已經通過 createBLEConnection 與對應設備建立鏈接
deviceId: that.ylj.id,
// 這里的 serviceId 需要在 getBLEDeviceServices 接口中獲取
serviceId: that.tzuuid0,
characteristicId: that.tzuuid1,
success(restu) {
setTimeout(function() {
console.log('阻止5')
uni.hideLoading();
}, 2000)
that.islj=1
uni.showToast({
duration: 2000,
title: "連接成功",
icon: 'none'
});
if(that.dsq){
clearTimeout(that.dsq)
}
console.log(restu)
//that.tzuuid0=res.characteristics
uni.onBLECharacteristicValueChange(function(res) {
console.log(res)
console.log(that.ab2hex(res.value))
var sbh=''
uni.getSystemInfo({
success: function (res) {
sbh=res.brand+'['+res.model+']'+'['+res.deviceId+']'
}
});

if (that.ab2hex(res.value) == '04') {
uni.showToast({
duration: 2000,
image: '../../static/sos.png',
title: "呼救!!"
// icon:'success'
});



// 調用startActivity方法撥打電話
main.startActivity( call );
uni.getLocation({
type: 'gcj02',
// type: 'wgs84',
geocode:true,
success: function (res) {
console.log('當前位置的經度:' + res.longitude);
console.log('當前位置的緯度:' + res.latitude);
console.log(res)



uniCloud.callFunction({
name: 'hujiu',
data: {
zb:res.latitude+'^^'+res.longitude,
wz:(res.address.province+res.address.city+res.address.district+res.address.street+res.address.streetNum+res.address.poiName).replace('undefined',''),
n:uni.getStorageSync('phone'),
xh:sbh,
time:that.timeStamp2(new Date()/1000),
str:'呼救!!'
},
success(res){
//console.log(res);
},
fail: () => {

},
complete: () => {


}
});

},
fail: function (res) {
uniCloud.callFunction({
name: 'hujiu',
data: {
zb:'',
wz:'',
xh:sbh,
n:uni.getStorageSync('phone'),
time:that.timeStamp2(new Date()/1000),
str:JSON.stringify(res)
},
success(res){
//console.log(res);
},
fail: () => {

},
complete: () => {


}
});
}
});
}
if (that.ab2hex(res.value) == "02") {
uni.showToast({
duration: 2000,
image: '../../static/sos.png',
title: "緊急呼救!!"
// icon:'success'
});

uni.getLocation({
type: 'gcj02',
// type: 'wgs84',
geocode:true,
success: function (res) {
console.log('當前位置的經度:' + res.longitude);
console.log('當前位置的緯度:' + res.latitude);
console.log(res)

uniCloud.callFunction({
name: 'hujiu',
data: {
zb:res.latitude+'^^'+res.longitude,
wz:(res.address.province+res.address.city+res.address.district+res.address.street+res.address.streetNum+res.address.poiName).replace('undefined',''),
n:uni.getStorageSync('phone'),
xh:sbh,
time:that.timeStamp2(new Date()/1000),
str:'緊急呼救!!'
},
success(res){
//console.log(res);
},
fail: () => {

},
complete: () => {


}
});

},
fail: function (res) {
uniCloud.callFunction({
name: 'hujiu',
data: {
zb:'',
wz:'',
xh:sbh,
n:uni.getStorageSync('phone'),
time:that.timeStamp2(new Date()/1000),
str:JSON.stringify(res)
},
success(res){
//console.log(res);
},
fail: () => {

},
complete: () => {


}
});
}
});
}
})
},
fail(sbe) {
setTimeout(function() {
console.log('阻止6')
uni.hideLoading();
}, 2000)
uni.showToast({
duration: 2000,
title: "連接失敗",
icon: 'none'
});
console.log(sbe)
}
})
},
hqjttz() {
console.log("開始獲取特征")
var that = this
that.tzuuid0 = that.tzarr[3].uuid
console.log(that.tzarr[3].uuid)
if(uni.getStorageSync('tzuuid1')){
that.tzuuid1 = uni.getStorageSync('tzuuid1')
that.jjtt()
return
}else{

}
//1 的indicate可用
setTimeout(function() {
uni.getBLEDeviceCharacteristics({
// 這里的 deviceId 需要已經通過 createBLEConnection 與對應設備建立鏈接
deviceId: that.ylj.id,
// 這里的 serviceId 需要在 getBLEDeviceServices 接口中獲取
serviceId: that.tzuuid0,
success(restu) {
console.log(restu)
that.tzuuid1 = restu.characteristics[3].uuid
uni.setStorageSync('tzuuid1', that.tzuuid1);
that.jjtt()
},
fail(sbe) {
console.log(sbe)
}
})
}, 100)

},


sousuo() {
var that = this
console.log('開始搜索')

uni.startBluetoothDevicesDiscovery({
allowDuplicatesKey: false,
services: ["0000180A-0000-1000-8000-00805F9B34FB",
"EDFEC62E-9910-0BAC-5241-020BB800025C"],
success(res) {
// console.log('sousuo')
// console.log(res)
},
fail(e) {
// console.log(e)
}
})

},

lan() {
var that = this;
uni.openBluetoothAdapter({

success(res) {
console.log(res)
console.log('初始化成功')
if(uni.getStorageSync('aykarr') && uni.getStorageSync('aykarr').length > 0){
that.arrsb=uni.getStorageSync('aykarr')
setTimeout(function(){
that.lianjie2(uni.getStorageSync('aykarr')[0].deviceId)
},10)
}else{
var ppdd = 1
uni.getBluetoothDevices({
success(res4) {
console.log(res4)
//console.log(res.devices.length)
for (var i = 0; i < res4.devices.length; i++) {
if (res4.devices[i].name == 'AYKBLESOS') {
var arr = []
arr.push(res4.devices[i])
that.arrsb = arr
uni.setStorageSync('aykarr', arr);
ppdd = 2
that.sousuo()
}


}

}
})
setTimeout(function() {
if (ppdd == 1) {
that.sousuo()
}
}, 1000)
}

},
fail: (res) => {
console.log("初始化藍牙失敗:" + res.code)
uni.showToast({
duration: 5000,
title: "請打開手機藍牙",
icon: 'none',
})
that.lyzt = '藍牙已關閉'
}

})
uni.onBluetoothDeviceFound(function(xinsb) {
// console.log(xinsb)
// that.sblb()
/* 搜索過程中如果搜索到需要的設備 */
if (xinsb.devices[0].name == 'AYKBLESOS') {
console.log(xinsb)
uni.stopBluetoothDevicesDiscovery({
success() {
// uni.hideLoading();
console.log('停止搜索成功')
}
})
that.arrsb = xinsb.devices
that.lianjie2(xinsb.devices[0].deviceId)
if(that.dsq){
clearTimeout(that.dsq)
}
}


})

// that.sousuo()
uni.getBluetoothAdapterState({
success(res2) {
console.log(res2)
if (res2.available) {
that.lyzt = '藍牙已打開'
} else {
that.lyzt = '藍牙已關閉'
}
}
})
uni.onBluetoothAdapterStateChange(function(res3) {
// console.log( res)
if (res3.available) {
/*uni.showToast({
title: '藍牙已打開',
duration: 2000,
icon: 'none'
});*/

if(that.lyzt =='藍牙已關閉'){
that.lan()
}


that.lyzt = '藍牙已打開'
} else {
/*uni.showToast({
title: '藍牙已關閉',
duration: 2000,
icon: 'none'
});*/
that.lyzt = '藍牙已關閉'
}
})
},
lianjie2(e) {
//return
console.log('嘗試連接');

var that = this
uni.createBLEConnection({
// 這里的 deviceId 需要已經通過 createBLEConnection 與對應設備建立鏈接
deviceId: e,
timeout: 60000,
success(res) {
console.log('藍牙連接成功');
console.log(res)
that.ylj = {
name: that.arrsb[0].name,
id: that.arrsb[0].deviceId,
uuid: that.arrsb[0].advertisServiceUUIDs[0]
}

that.hqtz()

 

},
fail(e) {
console.log(e)
setTimeout(function() {
console.log('阻止1')
uni.hideLoading();
}, 2000)
if(that.dsq){
clearTimeout(that.dsq)
}
uni.showToast({
duration: 2000,
title: "連接藍牙失敗",
icon: 'none'
});
}
})
},

hqtz(e) {
var that = this;
console.log("開始獲取服務")
console.log(that.ylj.id)
/*if(uni.getStorageSync('tzarr') && uni.getStorageSync('tzarr').length > 0){
that.tzarr = uni.getStorageSync('tzarr')
that.hqjttz()
return
}else{

}*/
setTimeout(function() {
uni.getBLEDeviceServices({
// 這里的 deviceId 需要已經通過 createBLEConnection 與對應設備建立鏈接
deviceId: that.ylj.id,
success(ress) {
console.log(ress)

if (ress.services.length > 0) {
that.tzarr = ress.services
uni.setStorageSync('tzarr', ress.services);
that.hqjttz()
}else{
setTimeout(function() {
console.log('阻止2')
uni.hideLoading();
uni.closeBluetoothAdapter({
success(res) {
console.log('關閉藍牙')
console.log(res)
that.lan()
}
})

}, 2000)
uni.showToast({
duration: 2000,
title: "獲取服務失敗,正在嘗試重新獲取",
icon: 'none'
});
}

},
fail(e) {
console.log(e)
setTimeout(function() {
console.log('阻止3')
uni.hideLoading();
uni.closeBluetoothAdapter({
success(res) {
console.log('關閉藍牙')
console.log(res)
that.lan()
}
})

}, 2000)
uni.showToast({
duration: 2000,
title: "獲取服務失敗",
icon: 'none'
});
}
})
}, 3000)

},

ab2hex(buffer) {
const hexArr = Array.prototype.map.call(
new Uint8Array(buffer),
function(bit) {
return ('00' + bit.toString(16)).slice(-2)
}
)
return hexArr.join('')
},


}
}
</script>

<style>
.ge {
width: 100%;
height: 44px;
position: relative;
}

.jfh {
position: fixed;
left: 0;
top: 0;
height: 44px;
line-height: 44px;
font-size: 18px;
text-align: center;
color: #fff;
background: linear-gradient(to right, #4DA5FE, #2D83F4);
z-index: 10;
width: 100%;
;
}

.jfh0 {
color: #fff;
height: 44px;
width: 44px;
line-height: 44px;
text-align: center;
position: absolute;
left: 2%;
margin-left: 15px;
bottom: 0;
font-size: 14px;
z-index: 11;
}

.jfh2 {
color: #fff;
height: 44px;
width: 100px;
line-height: 44px;
text-align: center;
position: absolute;
right: 2%;
margin-right: 5px;
text-align: right;
margin-left: 0px;
bottom: 0;
font-size: 14px;
z-index: 11;
}

.jfh1 {
color: #fff;
height: 44px;
width: 90%;
line-height: 44px;
text-align: center;
position: absolute;
left: 5%;
bottom: 0;
font-size: 16px;
}


.yuan{
position: relative;
height: 160px;
width: 160px;
border-radius: 50%;
text-align: center;
color: #fff;
background: linear-gradient(to right, #4DA5FE, #2D83F4);
margin: 80px auto;
border: 4px solid rgba(255,255,255,0.5);
}
.yuan1{
position: absolute;
width: 100%;
height: 30px;
line-height: 30px;
font-size: 26px;
color: white;
top: 50px;
left: 0;
text-align: center;
}
.yuan2{
position: absolute;
width: 100%;
height: 30px;
line-height: 30px;
font-size: 14px;
color: white;
top: 90px;
left: 0;
text-align: center;
}
</style>

 

經典藍牙

sblb(){

//獲取已配對藍牙
var that=this;
var main = plus.android.runtimeMainActivity();
var Context = plus.android.importClass("android.content.Context");
var BManager = main.getSystemService(Context.BLUETOOTH_SERVICE);
plus.android.importClass(BManager); //引入相關的method函數
var BAdapter = BManager.getAdapter();
plus.android.importClass(BAdapter);//引入相關的method函數,這樣之后才會有isEna
var lists = BAdapter.getBondedDevices();
plus.android.importClass(lists);
// var resultDiv = document.getElementById('bluetooth_list');
var iterator = lists.iterator();
plus.android.importClass(iterator);
var arr=[]
while(iterator.hasNext()) {
var d = iterator.next();
plus.android.importClass(d);
console.log("名稱:"+d.getName()+",地址:"+d.getAddress());
arr.push({
id:d.getAddress(),
name:d.getName()
})
}
that.arr2=arr

}

//獲取未配對藍牙(這里面也有已配對,但是不好使)

searchDevices(address) {
var that=this
//注冊類
var main = plus.android.runtimeMainActivity();
var IntentFilter = plus.android.importClass('android.content.IntentFilter');
var BluetoothAdapter = plus.android.importClass("android.bluetooth.BluetoothAdapter");
var BluetoothDevice = plus.android.importClass("android.bluetooth.BluetoothDevice");
var BAdapter = BluetoothAdapter.getDefaultAdapter();
console.log("開始搜索設備");
uni.showLoading({
//title: '加載中'
});
var filter = new IntentFilter();
var bdevice = new BluetoothDevice();
var on = null;
var un = null;
/* var vlist1 = document.getElementById('list1'); //注冊容器用來顯示未配對設備
vlist1.innerHTML = ''; //清空容器
var vlist2 = document.getElementById('list2'); //注冊容器用來顯示未配對設備
vlist2.innerHTML = ''; //清空容器 */
that.arr1=[]
that.arr2=[]
// var button1 = document.getElementById('bt1');
// button1.disabled=true;
// button1.value='正在搜索請稍候';
BAdapter.startDiscovery(); //開啟搜索
var receiver;
receiver = plus.android.implements('io.dcloud.android.content.BroadcastReceiver', {
onReceive: function(context, intent) { //實現onReceiver回調函數
plus.android.importClass(intent); //通過intent實例引入intent類,方便以后的‘.’操作
console.log(intent.getAction()); //獲取action
if(intent.getAction() == "android.bluetooth.adapter.action.DISCOVERY_FINISHED"){
main.unregisterReceiver(receiver);//取消監聽
// button1.disabled=false;
// button1.value='搜索設備';
console.log("搜索結束")
uni.hideLoading();
}else{


var BleDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
//判斷是否配對
console.log(BleDevice.getBondState())
if (BleDevice.getBondState() == bdevice.BOND_NONE) {
console.log("未配對藍牙設備:" + BleDevice.getName() + ' ' + BleDevice.getAddress());
//參數如果跟取得的mac地址一樣就配對
if (address == BleDevice.getAddress()) {
if (BleDevice.createBond()) { //配對命令.createBond()
console.log("配對成功");
/* var li2 = document.createElement('li'); //注冊
li2.setAttribute('id', BleDevice.getAddress()); //打印機mac地址
li2.setAttribute('onclick', 'print(id)'); //注冊click點擊列表進行打印
li2.innerText = BleDevice.getName();
vlist2.appendChild(li2); */
that.arr2.push({
name:BleDevice.getName(),
id: BleDevice.getAddress()
})
}

} else {
if(BleDevice.getName() != on ){ //判斷防止重復添加
/* var li1 = document.createElement('li'); //注冊
li1.setAttribute('id', BleDevice.getAddress()); //打印機mac地址
li1.setAttribute('onclick', 'searchDevices(id)'); //注冊click點擊列表進行配對
on = BleDevice.getName();
li1.innerText = on;
vlist1.appendChild(li1); */
console.log(111)
that.arr1.push({
name:BleDevice.getName(),
id: BleDevice.getAddress()
})

}

}
} else {


if(BleDevice.getName() != un ){ //判斷防止重復添加

console.log("已配對藍牙設備:" + BleDevice.getName() + ' ' + BleDevice.getAddress());
/*var li2 = document.createElement('li'); //注冊
li2.setAttribute('id', BleDevice.getAddress()); //打印機mac地址
li2.setAttribute('onclick', 'print(id)'); //注冊click點擊列表進行打印
un = BleDevice.getName();
li2.innerText = un;
vlist2.appendChild(li2);*/
var un = BleDevice.getName();
that.arr2.push({
name:BleDevice.getName(),
id: BleDevice.getAddress()
})
}
}}

}
});

filter.addAction(bdevice.ACTION_FOUND);
filter.addAction(BAdapter.ACTION_DISCOVERY_STARTED);
filter.addAction(BAdapter.ACTION_DISCOVERY_FINISHED);
filter.addAction(BAdapter.ACTION_STATE_CHANGED);

main.registerReceiver(receiver, filter); //注冊監聽
} ,


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM