<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; 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 {
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;
100%;
;
}
.jfh0 {
color: #fff;
height: 44px;
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;
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;
90%;
line-height: 44px;
text-align: center;
position: absolute;
left: 5%;
bottom: 0;
font-size: 16px;
}
.yuan{
position: relative;
height: 160px;
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;
100%;
height: 30px;
line-height: 30px;
font-size: 26px;
color: white;
top: 50px;
left: 0;
text-align: center;
}
.yuan2{
position: absolute;
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); //注册监听
} ,