? ? ? 本教程適用于使用 uni-app
+ Vue3 (script setup)
開發的跨平臺 App(支持微信小程序、H5、Android/iOS 等)
🎯 功能目標
- ? 獲取藍牙權限
- ? 掃描周圍藍牙設備
- ? 連接指定藍牙設備
- ? 獲取服務和特征值
- ? 向設備發送數據包(ArrayBuffer)
- ? 頁面 UI 展示設備列表 + 操作按鈕
項目結構概覽
/pages/bluetooth/
├── index.vue # 主頁面(本教程重點)
└── utils/Common.ts # 公共方法(獲取系統信息等)
?其中的公共方法代碼:
export async function getSystemInfo() {return await uni.getSystemInfo();
}
第一步:申請藍牙權限并初始化藍牙適配器
在 onShow()
生命周期中檢查并申請藍牙權限:
import { onShow } from "@dcloudio/uni-app";
import { ref } from "vue";let btOpenStatus = ref<boolean>(false);
let devicesList = ref<UniApp.BluetoothDeviceInfo[]>([]);onShow(() => {uni.authorize({scope: 'scope.bluetooth',success() {console.log('藍牙權限已授權');initBluetooth();},fail() {showToast('請開啟藍牙權限!');}});
});
初始化藍牙模塊
function initBluetooth() {uni.onBluetoothAdapterStateChange(function (res) {btOpenStatus.value = res.available;if (res.available) startBluetoothScan(); // 藍牙打開后開始掃描});uni.openBluetoothAdapter({success: () => {startBluetoothScan();},fail: (err) => {if (err.errCode == 10001) {btOpenStatus.value = false;showToast('藍牙未打開!');}}});
}
🔍 第二步:掃描藍牙設備
function startBluetoothScan() {uni.startBluetoothDevicesDiscovery({success: (res) => {console.log("開始掃描藍牙設備...", res);},fail: (err) => {console.error("啟動掃描失敗", err);showToast("啟動藍牙掃描失敗");}});uni.onBluetoothDeviceFound((res) => {res.devices.forEach((device) => {const exists = devicesList.value.some(d => d.deviceId === device.deviceId);if (!exists) devicesList.value.push(device);});});
}
🔗 第三步:連接藍牙設備
const connectedDevice = ref({serviceOrFeature: [] as Array<{ service: any, characteristics?: any }>,devicesInfo: {} as UniApp.BluetoothDeviceInfo
});async function createBLEConnection(device: UniApp.BluetoothDeviceInfo) {uni.showToast({duration: 30000,icon: "loading",title: '藍牙正在連接中!'});uni.createBLEConnection({deviceId: device.deviceId,success(connectionRes) {if (connectionRes.errCode === 0) {showToast('藍牙連接成功');connectedDevice.value.devicesInfo = device;getBLEDeviceServices(device.deviceId).then(res => {if (res.code === 200) console.log('藍牙服務初始化完成');});}},fail(connectionRes) {if (connectionRes.errCode === 10000) {showToast('請檢查藍牙是否開啟!');} else if (connectionRes.errCode === 10010 || connectionRes.errCode === -1) {console.log('已經連接');}},complete() {uni.hideToast();}});
}
?? 第四步:獲取服務與特征值
function getBLEDeviceServices(deviceId: string): Promise<{ code: number }> {return new Promise(ok => {uni.getBLEDeviceServices({deviceId,success: (res) => {res.services.forEach(async (item) => {let characteristicsRes = await getBLEDeviceCharacteristics(deviceId, item.uuid);if (characteristicsRes.code === 200) {connectedDevice.value.serviceOrFeature.push({service: item,characteristics: characteristicsRes.data});ok({ code: 200 });}});},fail: (err) => {ok({ code: 201 });}});});
}function getBLEDeviceCharacteristics(deviceId: string, serviceId: string): Promise<{ code: number, data?: any }> {return new Promise(ok => {uni.getBLEDeviceCharacteristics({deviceId,serviceId,success: (res) => {ok({ code: 200, data: res.characteristics });},fail: () => {ok({ code: 201 });}});});
}
💬 第五步:向藍牙設備發送數據
function getBluetoothServiceFeature(propertyName: string): { serviceUUID: string, feature: any } {let result = { serviceUUID: '', feature: {} };connectedDevice.value.serviceOrFeature.forEach(item => {let found = item.characteristics.find(f => f.properties[propertyName]);if (found) {result.serviceUUID = item.service.uuid;result.feature = found;}});return result;
}function sendMsg(msg: any, isBuffer?: boolean) {let writeFeature = getBluetoothServiceFeature('write');if (!writeFeature) {console.log('藍牙沒有對應的寫服務權限!');return;}uni.writeBLECharacteristicValue({deviceId: connectedDevice.value.devicesInfo.deviceId,serviceId: writeFeature.serviceUUID,characteristicId: writeFeature.feature.uuid,value: isBuffer ? msg : stringToArrayBuffer(msg),success(res) {console.log('消息發送成功', res);},fail(res) {console.log('消息發送失敗', res);}});
}function stringToArrayBuffer(str: string): ArrayBuffer {const buffer = new ArrayBuffer(str.length);const view = new Uint8Array(buffer);for (let i = 0; i < str.length; i++) {view[i] = str.charCodeAt(i);}return buffer;
}
完整代碼
<template><template><scroll-view scroll-y style="height: 100vh;background: #f9f9f9;" class="device-list"><!-- 設備列表 --><view v-for="device in devicesList" :key="device.deviceId" class="device-card"><!-- 設備信息 --><view class="device-info"><text class="name">{{ device.name || '未知設備' }}</text><text class="id">ID: {{ device.deviceId }}</text></view><!-- 操作按鈕 --><view class="actions"><text class="btn connect" @click.stop="createBLEConnection(device)">連接</text><text class="btn send" @click.stop="sendMsg('測試發送信息')">發送信息</text></view></view><!-- 空狀態提示 --><view v-if="devicesList.length === 0" class="empty-state">正在搜索附近的藍牙設備...</view></scroll-view></template>
</template><script setup lang="ts">import { onShow } from "@dcloudio/uni-app";import { ref , watch } from "vue";import { getSystemInfo } from "@/utils/Common";let systemInfo = ref(); let btOpenStatus = ref<boolean>();let devicesList = ref<UniApp.BluetoothDeviceInfo[]>([]); // 用于存儲搜索到的設備onShow( async () => {systemInfo.value = await getSystemInfo();uni.authorize({scope: 'scope.bluetooth',success() {console.log('藍牙權限已授權');initBluetooth();},fail() {showToast('請開啟藍牙權限!');}});});function initBluetooth() {uni.onBluetoothAdapterStateChange(function (res) {console.log(`藍牙狀態變化,用戶${res.available ? '打開' : '關閉'}藍牙!`);btOpenStatus.value = res.available;if(res.available) {startBluetoothScan();}});uni.openBluetoothAdapter({success: () => {console.log("藍牙適配器已打開!");startBluetoothScan(); // 開始掃描設備},fail: (err) => {if (err.errCode == 10001) {btOpenStatus.value = false;showToast('藍牙未打開!');}}});}function startBluetoothScan() {uni.startBluetoothDevicesDiscovery({success: (res) => {console.log("開始掃描藍牙設備...",res);},fail: (err) => {console.error("啟動掃描失敗", err);showToast("啟動藍牙掃描失敗");}});// 監聽新發現的設備uni.onBluetoothDeviceFound((res) => {// 遍歷發現的設備res.devices.forEach((device) => {// 去重:根據 deviceId 判斷是否已存在const exists = devicesList.value.some(d => d.deviceId === device.deviceId);if (!exists) {devicesList.value.push(device);}});});}const connectedDevice = ref({serviceOrFeature: [] as Array<{ service: any, characteristics ? : any }>,devicesInfo: {} as UniApp.BluetoothDeviceInfo});/*** 連接藍牙設備*/async function createBLEConnection(device: UniApp.BluetoothDeviceInfo) {await uni.getLocation({});if(devicesList.value.length <= 0) {showToast('正在搜索附近的藍牙設備');return;}uni.showToast({duration: 30000,icon: "loading",title: '藍牙正在連接中!'});console.log('選擇的藍牙設備:',device);if(device) {connectedDevice.value.devicesInfo = device;uni.createBLEConnection({deviceId: device.deviceId,async success(connectionRes) {if(connectionRes.errCode == 0) {console.log('連接成功!');showToast('藍牙連接成功');let servicesRes = await getBLEDeviceServices(device.deviceId);if(servicesRes.code == 200) {console.log('藍牙初始化服務完成');}}},fail(connectionRes) {if(connectionRes.errCode == 10000) {showToast('請檢查藍牙是否開啟!');}else if(connectionRes.errCode == 10000) {showToast('藍牙連接失敗,可以重試!');}else if(connectionRes.errCode == 10010 || connectionRes.errCode == -1) {console.log('已經連接');}},complete() {uni.hideToast();}});}}/*** 獲取藍牙設備的服務(service)*/function getBLEDeviceServices(deviceId: string) : Promise<{code : number}> {return new Promise( ok => {uni.getBLEDeviceServices({deviceId,success: (res) => {res.services.forEach(async (item) => {let characteristicsRes = await getBLEDeviceCharacteristics(deviceId,item.uuid);if(characteristicsRes.code == 200) {connectedDevice.value.serviceOrFeature.push({service: item,characteristics: characteristicsRes.data});ok({ code : 200 });}});},fail: (err) => {console.log("獲取服務失敗", err);ok({ code : 201 });}});});}/*** 獲取藍牙設備的特征值(characteristic)*/async function getBLEDeviceCharacteristics(deviceId: string, serviceId: string) : Promise<{ code : number , data ? : any }> {return new Promise( ok => {uni.getBLEDeviceCharacteristics({deviceId,serviceId,success: (res) => {ok({code: 200,data: res.characteristics});},fail: () => {ok({code : 201})}});});}/*** 獲取連接設備的寫特征值(wirteCharacteristic)*/function getBluetoothServiceFeature(propertyName: string): { serviceUUID: string, feature: any } {let serviceFeatureInfo: { serviceUUID: string, feature: any } = { serviceUUID: '', feature: {} };connectedDevice.value.serviceOrFeature.forEach(item => {let foundFeature = item.characteristics.find((feature: any) => feature.properties[propertyName]);if (foundFeature) {serviceFeatureInfo.serviceUUID = item.service.uuid;serviceFeatureInfo.feature = foundFeature;return;}});return serviceFeatureInfo;}// 向藍牙寫數據function sendMsg(msg: any, isBuffer ? : boolean ) {console.log('發送的信息:',msg); let writeServiceFeature = getBluetoothServiceFeature('write');if (!writeServiceFeature) {console.log('藍牙沒有對應的寫服務權限!');return;}uni.writeBLECharacteristicValue({deviceId: connectedDevice.value.devicesInfo.deviceId,serviceId: writeServiceFeature.serviceUUID,characteristicId: writeServiceFeature.feature.uuid, value: isBuffer ? msg : stringToArrayBuffer(msg) as any,writeType: systemInfo.value.osName == 'ios' ? 'write' : 'writeNoResponse',success(res) {console.log('消息發送成功', res);},fail(res) {console.log('消息發送失敗', res);}});}function stringToArrayBuffer(str: string): ArrayBuffer {const buffer = new ArrayBuffer(str.length);const view = new Uint8Array(buffer);for (let i = 0; i < str.length; i++) {view[i] = str.charCodeAt(i);}return buffer;}function showToast(title: string) {uni.showToast({icon: 'none',title});}</script><style lang="scss" scoped>.device-card {background-color: #fff;border-radius: 8px;padding: 16px;margin-bottom: 12px;box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);display: flex;flex-direction: column;gap: 10px;}.device-info {.name {font-weight: bold;font-size: 16px;color: #333;}.id {font-size: 14px;color: #888;display: block;margin-top: 4px;}}.actions {display: flex;gap: 10px;.btn {flex: 1;text-align: center;padding: 8px 0;border-radius: 4px;font-size: 14px;}.connect {color: #fff;background-color: #6659E5;}.send {color: #fff;background-color: #FC5531;}}.empty-state {text-align: center;padding: 20px;color: #999;}
</style>
🛠? 補充建議
功能 | 實現方式 |
---|---|
顯示 RSSI 信號強度 | 在設備項中顯示?{{ device.RSSI }} dBm |
自動刷新設備列表 | 使用定時器每隔幾秒重新掃描 |
防止重復點擊連接 | 添加?connectingDeviceId ?狀態控制 |
發送自定義數據包 | 使用?buildBluetoothPacket() ?構造特定格式數據 |
📦 最終效果預覽

📌 總結
? 本教程實現了從藍牙權限申請 → 設備掃描 → 連接設備 → 獲取服務 → 特征值讀寫 → 數據發送的一整套流程。
🎯 適用于智能門鎖、手環、打印機、IoT 等需要藍牙通信的場景。
💡 如果你需要對接具體藍牙協議(如 BLE 服務 UUID、數據格式),歡迎繼續提問,我可以幫你定制!