This commit is contained in:
aihe 2024-05-14 18:42:55 +08:00
parent 2891f0fe92
commit 405b874df3
2 changed files with 813 additions and 0 deletions

View File

@ -0,0 +1,454 @@
/**
* html 5+ 串口蓝牙操作
* 2021.04.23 uni-app版本
* @auth boolTrue
*/
/**
* 初始化参数
*/
//#ifdef APP-PLUS
let BluetoothAdapter = plus.android.importClass("android.bluetooth.BluetoothAdapter");
let Intent = plus.android.importClass("android.content.Intent");
let IntentFilter = plus.android.importClass("android.content.IntentFilter");
let BluetoothDevice = plus.android.importClass("android.bluetooth.BluetoothDevice");
let UUID = plus.android.importClass("java.util.UUID");
let Toast = plus.android.importClass("android.widget.Toast");
//连接串口设备的 UUID
let MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
let invoke = plus.android.invoke;
let btAdapter = BluetoothAdapter.getDefaultAdapter();
let activity = plus.android.runtimeMainActivity();
let btSocket = null;
let btInStream = null;
let btOutStream = null;
let setIntervalId = 0;
let btFindReceiver = null; //蓝牙搜索广播接收器
let btStatusReceiver = null; //蓝牙状态监听广播
//#endif
/**
* 构造对象
*/
var blueToothTool = {
state : {
bluetoothEnable: false, //蓝牙是否开启
bluetoothState: "", //当前蓝牙状态
discoveryDeviceState: false, //是否正在搜索蓝牙设备
readThreadState: false, //数据读取线程状态
},
options : {
/**
* 监听蓝牙状态回调
* @param {String} state
*/
listenBTStatusCallback: function(state) {},
/**
* 搜索到新的蓝牙设备回调
* @param {Device} newDevice
*/
discoveryDeviceCallback: function(newDevice) {},
/**
* 蓝牙搜索完成回调
*/
discoveryFinishedCallback: function() {},
/**
* 接收到数据回调
* @param {Array} dataByteArr
*/
readDataCallback: function(dataByteArr) {},
/**
* 蓝牙连接中断回调
* @param {Exception} e
*/
connExceptionCallback: function(e) {}
},
init(setOptions) {
Object.assign(this.options, setOptions);
this.state.bluetoothEnable = this.getBluetoothStatus();
this.listenBluetoothStatus();
},
shortToast(msg) {
Toast.makeText(activity, msg, Toast.LENGTH_SHORT).show();
},
/**
* 是否支持蓝牙
* @return {boolean}
*/
isSupportBluetooth() {
if(btAdapter != null) {
return true;
}
return false;
},
/**
* 获取蓝牙的状态
* @return {boolean} 是否已开启
*/
getBluetoothStatus() {
if(btAdapter != null) {
return btAdapter.isEnabled();
}
return false;
},
/**
* 打开蓝牙
* @param activity
* @param requestCode
*/
turnOnBluetooth() {
if(btAdapter == null) {
shortToast("没有蓝牙");
return;
}
if(!btAdapter.isEnabled()) {
if(activity == null) {
shortToast("未获取到activity");
return;
} else {
let intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
let requestCode = 1;
activity.startActivityForResult(intent, requestCode);
return;
}
} else {
shortToast("蓝牙已经打开");
}
},
/**
* 关闭蓝牙
*/
turnOffBluetooth() {
if(btAdapter != null && btAdapter.isEnabled()) {
btAdapter.disable();
}
if(btFindReceiver != null) {
try {
activity.unregisterReceiver(btFindReceiver);
} catch(e) {
}
btFindReceiver = null;
}
this.state.bluetoothEnable = false;
this.cancelDiscovery();
closeBtSocket();
if(btAdapter != null && btAdapter.isEnabled()) {
btAdapter.disable();
shortToast("蓝牙关闭成功");
} else {
shortToast("蓝牙已经关闭");
}
},
/**
* 获取已经配对的设备
* @return {Array} connetedDevices
*/
getPairedDevices() {
let pairedDevices = [];
//蓝牙连接android原生对象,是一个set集合
let pairedDevicesAndroid = null;
if(btAdapter != null && btAdapter.isEnabled()) {
pairedDevicesAndroid = btAdapter.getBondedDevices();
} else {
shortToast("蓝牙未开启");
}
if(!pairedDevicesAndroid) {
return pairedDevices;
}
//遍历连接设备的set集合,转换为js数组
let it = invoke(pairedDevicesAndroid, "iterator");
while(invoke(it, "hasNext")) {
let device = invoke(it, "next");
pairedDevices.push({
"name": invoke(device, "getName"),
"address": invoke(device, "getAddress")
});
}
return pairedDevices;
},
/**
* 发现设备
*/
discoveryNewDevice() {
if(btFindReceiver != null) {
try {
activity.unregisterReceiver(btFindReceiver);
} catch(e) {
console.error(e);
}
btFindReceiver = null;
this.cancelDiscovery();
}
let Build = plus.android.importClass("android.os.Build");
//6.0以后的如果需要利用本机查找周围的wifi和蓝牙设备, 申请权限
if(Build.VERSION.SDK_INT >= 6.0){
}
let options = this.options
btFindReceiver = plus.android.implements("io.dcloud.android.content.BroadcastReceiver", {
"onReceive": function(context, intent) {
console.log("btFindReceiver onReceive")
plus.android.importClass(context);
plus.android.importClass(intent);
let action = intent.getAction();
if(BluetoothDevice.ACTION_FOUND == action) { // 找到设备
let device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
let newDevice = {
"name": plus.android.invoke(device, "getName"),
"address": plus.android.invoke(device, "getAddress")
}
options.discoveryDeviceCallback && options.discoveryDeviceCallback(newDevice);
}
if(BluetoothAdapter.ACTION_DISCOVERY_FINISHED == action) { // 搜索完成
cancelDiscovery();
options.discoveryFinishedCallback && options.discoveryFinishedCallback();
}
}
});
let filter = new IntentFilter();
filter.addAction(BluetoothDevice.ACTION_FOUND);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
activity.registerReceiver(btFindReceiver, filter);
btAdapter.startDiscovery(); //开启搜索
console.log("btAdapter.startDiscovery")
this.state.discoveryDeviceState = true;
},
/**
* 蓝牙状态监听
* @param {Activity} activity
*/
listenBluetoothStatus() {
if(btStatusReceiver != null) {
try {
activity.unregisterReceiver(btStatusReceiver);
} catch(e) {
console.error(e);
}
btStatusReceiver = null;
}
btStatusReceiver = plus.android.implements("io.dcloud.android.content.BroadcastReceiver", {
"onReceive": (context, intent)=> {
plus.android.importClass(context);
plus.android.importClass(intent);
let action = intent.getAction();
switch(action) {
case BluetoothAdapter.ACTION_STATE_CHANGED:
let blueState = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, 0);
let stateStr = "";
switch(blueState) {
case BluetoothAdapter.STATE_TURNING_ON:
stateStr = "STATE_TURNING_ON";
break;
case BluetoothAdapter.STATE_ON:
this.state.bluetoothEnable = true;
stateStr = "STATE_ON";
break;
case BluetoothAdapter.STATE_TURNING_OFF:
stateStr = "STATE_TURNING_OFF";
break;
case BluetoothAdapter.STATE_OFF:
stateStr = "STATE_OFF";
this.state.bluetoothEnable = false;
break;
}
this.state.bluetoothState = stateStr;
this.options.listenBTStatusCallback && this.options.listenBTStatusCallback(stateStr);
break;
}
}
});
let filter = new IntentFilter();
filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
activity.registerReceiver(btStatusReceiver, filter);
// 首次连接 状态回调
if(this.state.bluetoothEnable) {
this.options.listenBTStatusCallback && this.options.listenBTStatusCallback('STATE_ON');
}
},
/**
* 根据蓝牙地址,连接设备
* @param {Stirng} address
* @return {Boolean}
*/
connDevice(address, callback) {
let InputStream = plus.android.importClass("java.io.InputStream");
let OutputStream = plus.android.importClass("java.io.OutputStream");
let BluetoothSocket = plus.android.importClass("android.bluetooth.BluetoothSocket");
this.cancelDiscovery();
if(btSocket != null) {
this.closeBtSocket();
}
this.state.readThreadState = false;
try {
let device = invoke(btAdapter, "getRemoteDevice", address);
btSocket = invoke(device, "createRfcommSocketToServiceRecord", MY_UUID);
} catch(e) {
console.error(e);
shortToast("连接失败,获取Socket失败!");
callback(false)
return false;
}
try {
invoke(btSocket, "connect");
this.readData(); //读数据
this.shortToast("连接成功");
callback(true)
} catch(e) {
console.error(e);
this.shortToast("连接失败");
callback(false)
try {
btSocket.close();
btSocket = null;
} catch(e1) {
console.error(e1);
}
return false;
}
return true;
},
/**
* 断开连接设备
* @param {Object} address
* @return {Boolean}
*/
disConnDevice() {
if(btSocket != null) {
this.closeBtSocket();
}
this.state.readThreadState = false;
this.shortToast("断开连接成功");
},
/**
* 断开连接设备
* @param {Object} address
* @return {Boolean}
*/
closeBtSocket() {
this.state.readThreadState = false;
if(!btSocket) {
return;
}
try {
btSocket.close();
} catch(e) {
console.error(e);
btSocket = null;
}
},
/**
* 取消发现
*/
cancelDiscovery() {
if(btAdapter.isDiscovering()) {
btAdapter.cancelDiscovery();
}
if(btFindReceiver != null) {
activity.unregisterReceiver(btFindReceiver);
btFindReceiver = null;
}
this.state.discoveryDeviceState = false;
},
/**
* 读取数据
* @param {Object} activity
* @param {Function} callback
* @return {Boolean}
*/
readData() {
if(!btSocket) {
this.shortToast("请先连接蓝牙设备!");
return false;
}
try {
btInStream = invoke(btSocket, "getInputStream");
btOutStream = invoke(btSocket, "getOutputStream");
} catch(e) {
console.error(e);
this.shortToast("创建输入输出流失败!");
this.closeBtSocket();
return false;
}
this.read();
this.state.readThreadState = true;
return true;
},
/**
* 模拟java多线程读取数据
*/
read() {
let setTimeCount = 0;
clearInterval(setIntervalId);
setIntervalId = setInterval(()=> {
setTimeCount++;
if(this.state.readThreadState) {
let t = new Date().getTime();
//心跳检测
if(setTimeCount % 20 == 0) {
try {
btOutStream.write([0b00]);
} catch(e) {
this.state.readThreadState = false;
this.options.connExceptionCallback && this.options.connExceptionCallback(e);
}
}
let dataArr = [];
while(invoke(btInStream, "available") !== 0) {
let data = invoke(btInStream, "read");
dataArr.push(data);
let ct = new Date().getTime();
if(ct - t > 20) {
break;
}
}
if(dataArr.length > 0) {
this.options.readDataCallback && this.options.readDataCallback(dataArr);
}
}
}, 40);
},
/**
* 发送数据
* @param {String} dataStr
* @return {Boolean}
*/
sendData(dataStr) {
if(!btOutStream) {
this.shortToast("创建输出流失败!");
return;
}
let bytes = invoke(dataStr, 'getBytes', 'gbk');
try {
btOutStream.write(bytes);
} catch(e) {
return false;
}
return true;
},
sendByteData(byteData) {
if(!btOutStream) {
this.shortToast("创建输出流失败!");
return;
}
try {
btOutStream.write(byteData);
} catch(e) {
return false;
}
return true;
}
}
export default blueToothTool

View File

@ -0,0 +1,359 @@
<template>
<tpx-layout v-if="showConnectPage">
<template v-slot:header>
<view class="blcok-white" style="margin-top: 0;">
<view >
<u-row custom-style="gap: 10rpx;">
<u-button @click="discoveryPrinter">
{{searchLoading?'搜索中...':'搜索周边设备'}}
</u-button>
<u-button @click="stopDiscoveryPrinter">停止搜索</u-button>
<slot name="button"></slot>
</u-row>
</view>
<view class="">
<view class="pt-10 pb-10">连接信息</view>
<u-steps activeColor="#969799" :current="curTab" direction="column" dot="true">
<u-steps-item v-for="(item, index) in conInfos">
<template v-slot:title>
<view @click="changeTab(index)" :class="`${index == curTab ? 'clr-prm' : 'clr-sub'} pl-20`">{{item.title}}</view>
</template>
<template v-slot:desc>
<view @click="changeTab(index)" class="mt-10 pl-20">{{item.desc}}</view>
</template>
</u-steps-item>
</u-steps>
</view>
</view>
</template>
<template v-slot:body>
<view class="blcok-white">
<view v-if="curTab == 0">
<view class="pb-10">蓝牙设备列表</view>
<template v-for="(item, index) in devices">
<view @click="handleAutoSelectAllData(item)" v-if="item.name.length>0"
:key="index" :class="`list-item ${item.deviceId == deviceId?'list-item-active':''}`"
>
<u-row justify="between">
<view class="font-weight">{{item.name }}</view>
</u-row>
<view>
<text class="clr-sub">信号强度:</text> {{item.RSSI}}dBm ({{Math.max(100+item.RSSI,0)}}%)
</view>
<view>
<text class="clr-sub">deviceId:</text>{{item.deviceId}}
</view>
<view >
<text class="clr-sub">Service数量:</text> {{item.advertisServiceUUIDs.length || 0}}
</view>
</view>
</template>
</view>
<view v-if="curTab == 1">
<view class="pb-10">服务列表</view>
<template v-for="(item, index) in serverList" :key="index">
<view @click="handleSelectService(item)"
:class="`list-item ${item.uuid == serviceId?'list-item-active':''}`"
>
<view>
<text class="clr-sub">uuid:</text> {{item.uuid}}
</view>
</view>
</template>
</view>
<view v-if="curTab == 2">
<view class="pb-10">特征值列表</view>
<template v-for="(item, index) in characteristics" :key="index">
<view @click="handleSelectChara(item)"
:class="`list-item ${item.uuid == characteristicId?'list-item-active':''}`"
>
<view>
<text class="clr-sub">uuid:</text> {{item.uuid}}
</view>
<template v-if="item.properties">
<view>
<text class="clr-sub">write:</text> {{item.properties.write}}
</view>
<view>
<text class="clr-sub">notify:</text> {{item.properties.notify}}
</view>
<view>
<text class="clr-sub">indicate:</text> {{item.properties.indicate}}
</view>
</template>
</view>
</template>
</view>
<slot name="content"></slot>
</view>
</template>
</tpx-layout>
</template>
<script>
import { showLoading, showToast, hideLoading, uniPromiseApi, promiseTimeout } from "@/common/untool"
import { getSessionBluetoothInfo, setSessionBluetoothInfo } from "@/session"
export default {
computed: {
conInfos() {
let ary = [
{ title: '蓝牙设备', desc: this.deviceId || '-' },
{ title: '服务', desc: this.serviceId || '-' },
{ title: '特征值', desc: this.characteristicId || '-' }
]
return ary
},
},
watch: {
deviceId(val){
this.updateBlueSessionInfo()
},
serviceId(val){
this.updateBlueSessionInfo()
},
characteristicId(val){
this.updateBlueSessionInfo()
}
},
props:{
},
data () {
let { deviceId, serviceId, characteristicId } = getSessionBluetoothInfo()
return {
showConnectPage: true,
canvasId: 'shareCanvas',
canvas_width: 240,
canvas_height: 240,
curTab: 0,
searchLoading: false,
devices: [],
deviceId,
serverList: [],
serviceId,
characteristics: [],
characteristicId,
}
},
async mounted () {
// 初始化蓝牙模块
await this.openBluetoothAdapter()
// this.autoConnect()
},
unmounted() {
this.stopDiscoveryPrinter()
// this.closeBluetoothAdapter()
},
methods: {
updateBlueSessionInfo() {
let { deviceId, serviceId, characteristicId } = this
setSessionBluetoothInfo({ deviceId, serviceId, characteristicId })
},
// 自动连接历史蓝牙配置
async autoConnect() {
console.log("autoConnect start===========")
let { characteristicId, serviceId, deviceId } = this
let conSta = false
const _this = this
// 判断是否有历史连接
if(deviceId) {
await this.handleAutoSelectAllData({ deviceId })
conSta = !!_this.characteristicId // 判断是否有选中 characteristicId
}
console.log("=========当前蓝牙连接状态=======", conSta)
// 连接不成功,打开蓝牙配置页面
if(!conSta) {
this.showConnectPage = true
// this.discoveryPrinter()
} else {
this.stopDiscoveryPrinter()
}
return conSta
},
changeTab(type) {
this.curTab = type
},
async openBluetoothAdapter () {
var _this = this
const { res, err } = await uniPromiseApi('openBluetoothAdapter', { })
if(err) {
if (err.errCode == 10001) {
showToast('请打开手机蓝牙')
} else {
showToast(err.errMsg)
}
}
},
// 开始搜寻附近的蓝牙外围设备
async discoveryPrinter () {
var _this = this
_this.devices = []
_this.searchLoading = true
_this.curTab = 0
const { res, err } = await uniPromiseApi('startBluetoothDevicesDiscovery', { })
if(res) {
// 打开搜索后,监听设备回调信息
uni.onBluetoothDeviceFound(devices => {
console.log("========devices=====", devices)
let curDvs = devices?.devices?.[0] || {}
// 过滤已经搜到的设备
if(curDvs.deviceId && _this.devices.map(t=> t.deviceId).indexOf(curDvs.deviceId) == -1) {
_this.devices.push(curDvs)
}
})
}
return { res, err }
},
// 停止搜寻附近的蓝牙外围设备
async stopDiscoveryPrinter () {
this.searchLoading = false
return uniPromiseApi('stopBluetoothDevicesDiscovery')
},
// 断开蓝牙
async closeBluetoothAdapter () {
this.searchLoading = false
return uniPromiseApi('closeBluetoothAdapter')
},
async handleSelectDeviceId (item) {
this.deviceId = item.deviceId
this.serviceId = ''
this.serverList = []
this.characteristics = []
this.characteristicId = ''
//连接蓝牙
await this.connect()
if(this.serverList?.length > 0) {
this.curTab = 1
this.stopDiscoveryPrinter()
} else {
showToast('该设备无服务,请检查配置或换一个设备连接')
}
},
handleSelectService (item) {
this.serviceId = item.uuid
this.characteristics = []
this.characteristicId = ''
// 获取蓝牙特征值
setTimeout(async () =>{
await this.getBLEDeviceCharacteristics()
if(this.characteristics?.length > 0) {
this.curTab = 2
} else {
showToast('该服务无特征值,请检查配置或换一个服务')
}
}, 500);
},
handleSelectChara (item) {
this.characteristicId = item.uuid
},
async connect () {
var _this = this
console.log("连接蓝牙=====deviceId", _this.deviceId)
showLoading('正在连接蓝牙')
let { res, err } = await uniPromiseApi('createBLEConnection', { deviceId: _this.deviceId })
hideLoading()
if(res || err?.code == -1) {
// code: -1 已连接
res = res || err
err = undefined
}
if(res) {
showToast(`蓝牙连接成功`)
await promiseTimeout(1500)
// 获取蓝牙设备所有服务(service)。
await _this.getBLEDeviceServices()
}
if(err) {
showToast(`连接设备失败:${err.errMsg}`)
}
return { res, err }
},
async getBLEDeviceServices() {
var _this = this
let { res, err } = await uniPromiseApi('getBLEDeviceServices', {
// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
deviceId: _this.deviceId,
})
if(res) {
_this.serverList = res.services
console.log('serverId:', _this.serviceId)
}
if(err) {
this.serverList = []
showToast(`设备服务获取失败:${err.errMsg}`)
}
return { res, err }
},
async getBLEDeviceCharacteristics () {
var _this = this
let { res, err } = await uniPromiseApi('getBLEDeviceCharacteristics', {
// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
deviceId: _this.deviceId,
// 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
serviceId:_this.serviceId,
})
if(res) {
_this.characteristics = res.characteristics
}
return { res, err }
},
// 根据选择的deviceId自动匹配 serviceId, characteristicId
async handleAutoSelectAllData(item) {
console.log("handleAutoSelectAllData :item======", item)
const _this = this
await this.handleSelectDeviceId(item)
if(this.serverList?.length > 0) {
for(let i=0; i<_this.serverList?.length; i++) {
let _serviceId = _this.serverList[i].uuid
let charPms = await uniPromiseApi('getBLEDeviceCharacteristics', {
deviceId: _this.deviceId,
serviceId: _serviceId,
})
let { res, err } = charPms
if(res) {
let charItem = res.characteristics.filter(t=> {
let { notify, indicate, write } = t.properties || {}
// return write
return (notify || indicate) && write
})[0]
if(charItem) {
_this.serviceId = _serviceId
_this.characteristicId = charItem.uuid
break
}
}
}
}
},
getConData() {
return { deviceId: this.deviceId, serviceId: this.serviceId, characteristicId: this.characteristicId }
}
}
}
</script>
<style scoped lang="scss">
.list-item {
font-size: 26rpx;
margin-bottom: 20rpx;
border-radius: 10rpx;
border: 2rpx solid #ddd;
padding: 20rpx;
background-color: #F6F6F6;
}
.list-item-active{
border-color: #B12D29;
&:last-child{
margin-bottom: 0;
}
}
</style>