藍(lán)牙連接并通信方法封裝大致步驟。
- 初始化藍(lán)牙并搜索;
- 獲取并啟用service服務(wù);
- 數(shù)據(jù)讀取和監(jiān)聽(tīng)設(shè)備返回?cái)?shù)據(jù)
需要使用uniapp官方提供api:
// 關(guān)閉藍(lán)牙
uni.closeBluetoothAdapter({})
// 打開(kāi)藍(lán)牙
uni.openBluetoothAdapter({})
// 搜索附近的藍(lán)牙
uni.startBluetoothDevicesDiscovery({})
// 停止搜索
uni.stopBluetoothDevicesDiscovery({})
// 連接低功耗BLE藍(lán)牙
uni.createBLEConnection({})
// 獲取藍(lán)牙設(shè)備所有服務(wù)(service)
uni.getBLEDeviceServices({})
// 獲取藍(lán)牙特征值
uni.getBLEDeviceCharacteristics({})
// 啟用低功耗藍(lán)牙設(shè)備特征值變化時(shí)的 notify 功能,訂閱特征值
uni.notifyBLECharacteristicValueChange({})
// 監(jiān)聽(tīng)低功耗藍(lán)牙設(shè)備的特征值變化事件
uni.onBLECharacteristicValueChange({})
// 讀取低功耗藍(lán)牙設(shè)備的特征值的二進(jìn)制數(shù)據(jù)值
uni.readBLECharacteristicValue({})
1、開(kāi)啟藍(lán)牙適配器初始化藍(lán)牙模塊,獲取手機(jī)藍(lán)牙是否打開(kāi)
const getBluetoothState = () => {
return new Promise((resolve, reject) => {
uni.openBluetoothAdapter({
mode: 'central', // 主機(jī)模式
success: (r) => {
console.log("藍(lán)牙初始化成功");
// 獲取藍(lán)牙的匹配狀態(tài)
uni.getBluetoothAdapterState({
success: function(row) {
console.log('藍(lán)牙狀態(tài):', row.available);
if (row.available) {
// 藍(lán)牙連接成功,開(kāi)啟藍(lán)牙設(shè)備搜索
resolve();
} else {
// 請(qǐng)開(kāi)啟藍(lán)牙
uni.showToast({
title: "請(qǐng)開(kāi)啟藍(lán)牙",
icon: 'none',
duration: 2000
});
reject();
}
},
fail: function(err) {
// 請(qǐng)開(kāi)啟藍(lán)牙
uni.showToast({
title: "請(qǐng)開(kāi)啟藍(lán)牙",
icon: 'none',
duration: 2000
});
reject();
}
})
},
fail: () => {
// 請(qǐng)開(kāi)啟藍(lán)牙
uni.showToast({
title: "請(qǐng)開(kāi)啟藍(lán)牙",
icon: 'none',
duration: 2000
});
reject();
}
});
});
}
2、開(kāi)啟藍(lán)牙設(shè)備搜索
const discoveryBluetooth = () => {
return new Promise((resolve) => {
uni.startBluetoothDevicesDiscovery({
success(res) {
uni.showLoading({
title: "正在搜索設(shè)備",
icon:"none",
duration: 2000
});
console.log('搜索藍(lán)牙外圍設(shè)備完成', res)
setTimeout(() => {
// 監(jiān)聽(tīng)尋找到的藍(lán)牙設(shè)備
resolve();
}, 2000);
}
});
});
}
3、獲取搜索到的設(shè)備信息
const getBluetoothDevices = () => {
return new Promise((resolve, reject) => {
uni.getBluetoothDevices({
success(res) {
// 過(guò)濾掉name為空或者未知設(shè)備的設(shè)備
let devices = res.devices.filter(function(obj) {
return obj.name !== "" && obj.name !== "未知設(shè)備"
});
devices && devices.forEach(item => {
// 獲取指定連接deviceId
if(item.name && item.name.substring(0, 5) === 'aaaa-'){
// aaaa-*********藍(lán)牙設(shè)備型號(hào),根據(jù)需求選擇設(shè)備型號(hào)
// item.deviceId;
}
});
},
fail: function() {
console.log('搜索藍(lán)牙設(shè)備失敗');
reject();
},
complete: function() {
console.log("藍(lán)牙搜索完成");
resolve();
}
});
});
}
4、關(guān)閉藍(lán)牙搜索
const stopDiscoveryBluetooth = () => {
uni.stopBluetoothDevicesDiscovery({
success(r) {
console.log("停止搜索藍(lán)牙設(shè)備", r);
}
});
};
5、連接藍(lán)牙
const connectBluetooth = () => {
return new Promise((resolve, reject) => {
uni.createBLEConnection({
deviceId: deviceId, // 設(shè)備id
success() {
// 藍(lán)牙連接成功后關(guān)閉藍(lán)牙搜索并獲取服務(wù)id
stopDiscoveryBluetooth();
resolve();
// 獲取服務(wù)id
getServiceId();
},
fail() {
console.log("藍(lán)牙連接失敗");
reject();
}
});
});
};
6、獲取服務(wù)id
const getServiceId = () => {
uni.getBLEDeviceServices({
deviceId: deviceId,
success(res) {
console.log("獲取服務(wù)Id", res)
// serviceId固定,獲取藍(lán)牙設(shè)備某個(gè)服務(wù)中的所有特征值【讀寫(xiě)屬性】
let model = res.services[0];
serviceId = model.uuid;
// 調(diào)用藍(lán)牙監(jiān)聽(tīng)和寫(xiě)入功能
getCharacteId();
},
fail(err){
console.log('獲取服務(wù)失敗', err);
}
})
};
7、獲取藍(lán)牙低功耗設(shè)備某個(gè)服務(wù)中所有特征
const getCharacteId = () => {
uni.getBLEDeviceCharacteristics({
deviceId: deviceId, // 藍(lán)牙設(shè)備id
serviceId: serviceId, // 藍(lán)牙服務(wù)UUID
success(res) {
console.log('數(shù)據(jù)監(jiān)聽(tīng)', res);
res.characteristics.forEach(item => {
// 003
if (item.properties.notify === true) {
// 監(jiān)聽(tīng)
notify = item.uuid;
}
// 002
if (item.properties.write === true) {
// 寫(xiě)入
let writeId = item.uuid;
}
});
},
fail(err) {
console.log("數(shù)據(jù)監(jiān)聽(tīng)失敗", err)
}
})
};
8、監(jiān)聽(tīng)設(shè)備返回?cái)?shù)據(jù),啟用低功耗藍(lán)牙設(shè)備特征值變化時(shí)的notify功能文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-758478.html
const startNotice = () => {
uni.notifyBLECharacteristicValueChange({
characteristicId: notify,
deviceId: deviceId,
serviceId: serviceId,
state: true,
success(res) {
// 監(jiān)聽(tīng)低功耗藍(lán)牙設(shè)備的特征值變化
uni.onBLECharacteristicValueChange(result => {
console.log("監(jiān)聽(tīng)低功耗藍(lán)牙設(shè)備的特征值變化", result);
if (result.value) {
console.log('設(shè)備返回?cái)?shù)據(jù)', result.value)
}
})
}
});
};
9、向藍(lán)牙設(shè)備發(fā)送數(shù)據(jù)文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-758478.html
const writeData = (buffer) => {
return new Promise((resolve, reject) => {
uni.writeBLECharacteristicValue({
characteristicId: uni.getStorageSync("writeId"),
deviceId: deviceId,
serviceId: serviceId,
value: buffer,
success(res) {
console.log("writeBLECharacteristicValue success", res);
resolve();
},
fail(err) {
console.log("報(bào)錯(cuò)了", err);
reject();
}
});
});
};
封裝完整方法:
import { TextDecoder } from 'text-encoding-utf-8';
let bluetoothOpen = false; // 手機(jī)藍(lán)牙是否打開(kāi)
let bluetoothConnect = false; // 設(shè)備和藍(lán)牙是否連接
let isHaveDevice = false; // 是否查找到設(shè)備
let deviceId = null; // 設(shè)備id
let serviceId = null; // 服務(wù)id
let notify = null; // 監(jiān)聽(tīng)uuid
let writeId = null; // 寫(xiě)入uuid
/**
* 獲取手機(jī)藍(lán)牙是否打開(kāi)
*/
const getBluetoothState = () => {
// 主機(jī)模式
return new Promise((resolve, reject) => {
uni.openBluetoothAdapter({
mode: 'central',
success: (r) => {
console.log("藍(lán)牙初始化成功");
// 獲取藍(lán)牙的匹配狀態(tài)
uni.getBluetoothAdapterState({
success: function(row) {
console.log('藍(lán)牙狀態(tài):', row.available);
if (row.available) {
bluetoothOpen = true;
resolve();
} else {
// 請(qǐng)開(kāi)啟藍(lán)牙
bluetoothOpen = false;
bluetoothConnect = false;
reject();
}
},
fail: function(err) {
// 請(qǐng)開(kāi)啟藍(lán)牙
bluetoothOpen = false;
bluetoothConnect = false;
reject();
}
})
},
fail: () => {
// 請(qǐng)開(kāi)啟藍(lán)牙
bluetoothOpen = false;
bluetoothConnect = false;
reject();
}
});
});
};
/**
* 開(kāi)始搜索藍(lán)牙設(shè)備
*/
const discoveryBluetooth = () => {
return new Promise((resolve) => {
uni.startBluetoothDevicesDiscovery({
success(res) {
console.log('搜索藍(lán)牙外圍設(shè)備完成', res)
setTimeout(() => {
resolve();
}, 2000);
}
});
})
};
// 關(guān)閉藍(lán)牙搜索
const stopDiscoveryBluetooth = () => {
uni.stopBluetoothDevicesDiscovery({
success(r) {
console.log("停止搜索藍(lán)牙設(shè)備", r);
}
});
};
/**
* 獲取搜索到的設(shè)備信息
*/
const getBluetoothDevices = () => {
return new Promise((resolve, reject) => {
uni.getBluetoothDevices({
success(res) {
bluetoothConnect = false;
// 過(guò)濾掉name為空或者未知設(shè)備的設(shè)備
let devices = res.devices.filter(function(obj) {
return obj.name !== "" && obj.name !== "未知設(shè)備"
});
devices && devices.forEach(item => {
if(item.name && item.name.substring(0, 5) === 'aaaa-'){
deviceId = item.deviceId;
}
});
},
fail: function() {
console.log('搜索藍(lán)牙設(shè)備失敗');
bluetoothConnect = false;
reject();
},
complete: function() {
console.log("藍(lán)牙搜索完成");
// 是否具有當(dāng)前設(shè)備
if (deviceId) {
isHaveDevice = true;
} else {
isHaveDevice = false;
}
resolve(isHaveDevice);
}
});
});
}
/**
* 連接藍(lán)牙
* deviceId 藍(lán)牙設(shè)備id
*/
const connectBluetooth = () => {
return new Promise((resolve, reject) => {
uni.createBLEConnection({
deviceId: deviceId, // 設(shè)備id
success() {
bluetoothConnect = true;
// 藍(lán)牙連接成功后關(guān)閉藍(lán)牙搜索
stopDiscoveryBluetooth();
resolve();
// 獲取服務(wù)id
getServiceId();
},
fail() {
bluetoothConnect = false;
console.log("藍(lán)牙連接失敗");
reject();
}
});
});
};
// 獲取服務(wù)id
const getServiceId = () => {
uni.getBLEDeviceServices({
deviceId: deviceId,
success(res) {
console.log("獲取服務(wù)Id", res)
let model = res.services[0];
serviceId = model.uuid;
// 調(diào)用藍(lán)牙監(jiān)聽(tīng)和寫(xiě)入功能
getCharacteId();
}
})
};
// 獲取藍(lán)牙低功耗設(shè)備某個(gè)服務(wù)中所有特征
const getCharacteId = () => {
uni.getBLEDeviceCharacteristics({
deviceId: deviceId, // 藍(lán)牙設(shè)備id
serviceId: serviceId, // 藍(lán)牙服務(wù)UUID
success(res) {
console.log('數(shù)據(jù)監(jiān)聽(tīng)', res);
res.characteristics.forEach(item => {
// 003
if (item.properties.notify === true) {
// 監(jiān)聽(tīng)
notify = item.uuid;
startNotice();
}
// 002
if (item.properties.write === true) {
// 寫(xiě)入
let writeId = item.uuid;
uni.setStorageSync("writeId", item.uuid);
}
});
},
fail(err) {
console.log("數(shù)據(jù)監(jiān)聽(tīng)失敗", err)
}
})
};
// 啟用低功耗藍(lán)牙設(shè)備特征值變化時(shí)的notify功能
const startNotice = () => {
uni.notifyBLECharacteristicValueChange({
characteristicId: notify,
deviceId: deviceId,
serviceId: serviceId,
state: true,
success(res) {
// 監(jiān)聽(tīng)低功耗藍(lán)牙設(shè)備的特征值變化
uni.onBLECharacteristicValueChange(result => {
console.log("監(jiān)聽(tīng)低功耗藍(lán)牙設(shè)備的特征值變化", result);
if (result.value) {
let decoder = new TextDecoder('utf-8');
let data = decoder.decode(result.value);
console.log('帽子返回?cái)?shù)據(jù)', data)
}
})
}
});
};
// 藍(lán)牙發(fā)送數(shù)據(jù)
const writeData = (buffer) => {
return new Promise((resolve, reject) => {
uni.writeBLECharacteristicValue({
characteristicId: uni.getStorageSync("writeId"),
deviceId: deviceId,
serviceId: serviceId,
value: buffer,
success(res) {
console.log("writeBLECharacteristicValue success", res);
resolve();
},
fail(err) {
console.log("報(bào)錯(cuò)了", err);
reject();
}
});
});
};
export default {
getBluetoothState,
discoveryBluetooth,
stopDiscoveryBluetooth,
getBluetoothDevices,
connectBluetooth,
getServiceId,
getCharacteId,
startNotice,
writeData
};
使用案例:
<template>
<view class="device_container">
</view>
</template>
<script>
import bluetooth from '../bluetooth.js';
export default {
data() {
return {
bluetoothStatus: false, // 藍(lán)牙連接狀態(tài)
}
},
methods: {
// 獲取藍(lán)牙和設(shè)備是否已連接
initBluetooth() {
let _this = this;
// 初始化藍(lán)牙
bluetooth.getBluetoothState().then(() => {
// 搜索外圍藍(lán)牙設(shè)備
bluetooth.discoveryBluetooth().then(() => {
this.discoveryLoading = true;
// 獲取藍(lán)牙設(shè)備
bluetooth.getBluetoothDevices().then((isHaveDevice) => {
if (isHaveDevice) {
// 搜索到指定設(shè)備,連接藍(lán)牙
bluetooth.connectBluetooth().then(() => {
_this.bluetoothStatus = true;
}, () => {
_this.bluetoothStatus = false;
});
} else {
// 未搜到設(shè)備
_this.bluetoothStatus = false;
}
}, () => {
// 藍(lán)牙搜索失敗
_this.bluetoothStatus = false;
});
});
}, () => {
// 未開(kāi)啟藍(lán)牙
_this.bluetoothStatus = false;
});
},
// 向設(shè)備發(fā)送數(shù)據(jù)
writeBlueData() {
let obj = {
cmd: 3,
freq: 430125,
speakable: 1
};
let objStr = JSON.stringify(obj);
let buffer = new ArrayBuffer(objStr.length); // 每個(gè)字符占用2個(gè)字節(jié)
let bufView = new Uint8Array(buffer);
for (let i = 0; i < objStr.length; i++) {
bufView[i] = objStr.charCodeAt(i);
}
bluetooth.writeData(buffer);
}
},
onShow() {
// 獲取藍(lán)牙和設(shè)備連接狀態(tài)
this.initBluetooth();
},
}
</script>
<style lang="scss">
page {
height: 100%;
}
</style>
到了這里,關(guān)于uniapp微信小程序藍(lán)牙連接與設(shè)備數(shù)據(jù)對(duì)接的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!