B站鏈接https://www.bilibili.com/read/cv5678982
只需要把下面第二個文件復制到項目里面,然后引入就可以了
主要流程:
1.初始化藍牙適配器openBluetoothAdapter,如果不成功就onBluetoothAdapterStateChange監聽藍牙適配器狀態變化事件
2.startBluetoothDevicesDiscovery開始搜尋附近的藍牙外圍設備
3.onBluetoothDeviceFound監聽尋找到新設備的事件,在這里你可以用代碼匹配設備
4.createBLEConnection創建藍牙連接,順便在stopBluetoothDevicesDiscovery關閉搜尋附近的藍牙外圍設備
5.getBLEDeviceServices獲取藍牙設備所有服務
6.getBLEDeviceCharacteristics獲取藍牙設備某個服務中所有特征值
7.onBLECharacteristicValueChange監聽藍牙設備發送給你的數據
8.writeBLECharacteristicValue向藍牙設備發送一個0x00的16進制數據或者writeBLECharacteristicValueString發送字符串
<template>
<view>
</view>
</template>
<script>
import bt from '../../utils/bluetooth.vue';
export default {
data() {
return {
}
},
methods: {
},
onLoad(opt) {
bt.openBluetoothAdapter("DEMO1");
}
}
</script>
<style>
</style>
<template>
<view></view>
</template>
<script>
var _discoveryStarted = false;
var _deviceId = null;
var _serviceId = null;
var _characteristicId = null;
var chs = [];
var btvalue = null;
function inArray(arr, key, val) {
for (let i = 0; i < arr.length; i++) {
if (arr[i][key] === val) {
return i;
}
}
return -1;
}
// ArrayBuffer轉16進度字符串示例
function ab2hex(buffer) {
var hexArr = Array.prototype.map.call(
new Uint8Array(buffer),
function (bit) {
return ('00' + bit.toString(16)).slice(-2)
}
)
return hexArr.join('');
}
//准備開始掃描
function $openBluetoothAdapter(devicename){
//初始化藍牙模塊
uni.openBluetoothAdapter({
success: (res) => {
console.log('openBluetoothAdapter success', res);
$startBluetoothDevicesDiscovery(devicename);
},
fail: (res) => {
uni.showToast({
title: '請打開藍牙',
duration: 1000
});
if (res.errCode === 10001) {
//監聽藍牙適配器狀態變化事件
uni.onBluetoothAdapterStateChange(function(res){
console.log('onBluetoothAdapterStateChange', res);
if (res.available) {
//開始掃描
$startBluetoothDevicesDiscovery(devicename)
}
})
}
}
})
}
function $startBluetoothDevicesDiscovery(devicename){
if (_discoveryStarted) {
return;
}
_discoveryStarted = true;
//開始搜尋附近的藍牙外圍設備
uni.startBluetoothDevicesDiscovery({
allowDuplicatesKey: true,
success: (res) => {
console.log('startBluetoothDevicesDiscovery success', res);
//監聽尋找到新設備的事件
$onBluetoothDeviceFound(devicename)
},
})
}
function $onBluetoothDeviceFound(devicename) {
//監聽尋找到新設備的事件
uni.onBluetoothDeviceFound(function(res){
res.devices.forEach(device => {
if (!device.name && !device.localName) {
return;
}
console.log(device);
//如果名字相同連接設備
if(device.name == devicename){
$createBLEConnection(device.deviceId);
}
})
})
}
function $createBLEConnection(deviceId){
//創建連接
uni.createBLEConnection({
deviceId:deviceId,
success: (res) => {
console.log(res);
$getBLEDeviceServices(deviceId);
},
fail: (err) =>{
console.log(err);
}
});
$stopBluetoothDevicesDiscovery();
}
function $getBLEDeviceServices(deviceId) {
//獲取藍牙設備所有服務(service)
uni.getBLEDeviceServices({
deviceId,
success: (res) => {
for (let i = 0; i < res.services.length; i++) {
if (res.services[i].isPrimary) {
$getBLEDeviceCharacteristics(deviceId, res.services[i].uuid);
return;
}
}
}
});
}
function $getBLEDeviceCharacteristics(deviceId, serviceId){
//獲取藍牙設備某個服務中所有特征值(characteristic)。
uni.getBLEDeviceCharacteristics({
deviceId,
serviceId,
success: (res) => {
console.log('getBLEDeviceCharacteristics success', res.characteristics);
for (let i = 0; i < res.characteristics.length; i++) {
let item = res.characteristics[i]
if (item.properties.read) {
//讀取低功耗藍牙設備的特征值的二進制數據值。1
uni.readBLECharacteristicValue({
deviceId,
serviceId,
characteristicId: item.uuid,
})
}
if (item.properties.write) {
_deviceId = deviceId;
_serviceId = serviceId;
_characteristicId = item.uuid;
$writeBLECharacteristicValue();
}
if (item.properties.notify || item.properties.indicate) {
//啟用低功耗藍牙設備特征值變化時的 notify 功能,訂閱特征值。
uni.notifyBLECharacteristicValueChange({
deviceId,
serviceId,
characteristicId: item.uuid,
state: true,
});
}
}
},
fail(res) {
console.error('getBLEDeviceCharacteristics', res)
}
})
//監聽數據
// 操作之前先監聽,保證第一時間獲取數據
uni.onBLECharacteristicValueChange(function(characteristic){
const idx = inArray(chs, 'uuid', characteristic.characteristicId)
const data = {}
if (idx === -1) {
data[`chs[${chs.length}]`] = {
uuid: characteristic.characteristicId,
value: ab2hex(characteristic.value)
}
} else {
data[`chs[${idx}]`] = {
uuid: characteristic.characteristicId,
value: ab2hex(characteristic.value)
}
}
console.log(data);
btvalue = data;
})
}
function $writeBLECharacteristicValue() {
// 向藍牙設備發送一個0x00的16進制數據
let buffer = new ArrayBuffer(1)
let dataView = new DataView(buffer)
dataView.setUint8(0, 0x61 | 0);
uni.writeBLECharacteristicValue({
deviceId: _deviceId,
serviceId: "0000FFE0-0000-1000-8000-00805F9B34FB",
characteristicId: _characteristicId,
value: buffer,
success: function(res){
console.log(res);
},
fail: function(res){
console.log(res);
}
})
};
function $writeBLECharacteristicValueString(str) {
// 向藍牙設備發送16進制數據
let buffer = new ArrayBuffer(str.length);
let dataView = new DataView(buffer);
for (let i in str) {
dataView.setUint8(i, str[i].charCodeAt() | 0);
}
uni.writeBLECharacteristicValue({
deviceId: _deviceId,
serviceId: "0000FFE0-0000-1000-8000-00805F9B34FB",
characteristicId: _characteristicId,
value: buffer,
success: function(res){
console.log(res);
},
fail: function(res){
console.log(res);
}
})
};
function $stopBluetoothDevicesDiscovery(){
//關閉搜索
uni.stopBluetoothDevicesDiscovery({
success(res) {
console.log(res);
}
})
}
export default {
data() {
return {
}
},
methods: {
},
openBluetoothAdapter: $openBluetoothAdapter,
writeBLECharacteristicValue: $writeBLECharacteristicValue,
writeBLECharacteristicValueString: $writeBLECharacteristicValueString
}
</script>
<style>
</style>