首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

微信小程序藍牙BLE開發完整實戰指南

     編輯:Java 相關知識

微信小程序基礎庫 1.1.0+ 引入藍牙 API,iOS 6.5.6+ 支持,Android 需較新版本。本文系統梳理 18 個藍牙接口,分為搜索、連接、通信三大類,並提供完整的搜索設備、連接獲取數據、發送指令的實戰代碼。

一、API 分類速查

類別核心接口
搜索類openBluetoothAdapter、startBluetoothDevicesDiscovery、getBluetoothDevices、onBluetoothDeviceFound
連接類createBLEConnection、closeBLEConnection、getBLEDeviceServices、getBLEDeviceCharacteristics、onBLEConnectionStateChanged
通信類writeBLECharacteristicValue、readBLECharacteristicValue、notifyBLECharacteristicValueChanged、onBLECharacteristicValueChange

二、搜索藍牙設備頁面(index.wxml/js)

// index.js
Page({
  data: { logs: [], list: [] },
  onLoad() {
    const that = this;
    wx.openBluetoothAdapter({
      success(res) {
        console.log('適配器初始化成功', res);
        wx.startBluetoothDevicesDiscovery({
          services: [],
          success() { console.log('開始搜索設備'); }
        });
        wx.getBluetoothDevices({
          success(res) {
            that.setData({ list: res.devices });
          }
        });
      }
    });
  },
  bindViewTap(e) {
    const { title, name } = e.currentTarget.dataset;
    wx.redirectTo({ url: `../conn/conn?deviceId=${title}&name=${name}` });
  }
});

三、連接設備並通信頁面(conn.wxml/js)

// conn.js 核心邏輯
Page({
  data: {
    deviceId: '', name: '', serviceId: '',
    cd20: '', cd01: '', cd02: '', cd03: '', cd04: '',
    characteristics20: null, characteristics01: null, /* ... */,
    result: ''
  },
  onLoad(opt) {
    const that = this;
    that.setData({ deviceId: opt.deviceId, name: opt.name });

    // 監聽連接狀態變化
    wx.onBLEConnectionStateChanged(res => {
      console.log(`設備 ${res.deviceId} 狀態變化: ${res.connected}`);
    });

    // 1. 建立連接
    wx.createBLEConnection({
      deviceId: that.data.deviceId,
      success() {
        // 2. 獲取服務列表
        wx.getBLEDeviceServices({
          deviceId: that.data.deviceId,
          success(res) {
            that.setData({ services: res.services });
            const targetService = res.services[1]; // 假設第二個服務為目標
            that.setData({ serviceId: targetService.uuid });

            // 3. 延遲獲取特徵值(等待服務就緒)
            setTimeout(() => {
              wx.getBLEDeviceCharacteristics({
                deviceId: that.data.deviceId,
                serviceId: that.data.serviceId,
                success(res) {
                  res.characteristics.forEach(c => {
                    if (c.uuid.includes('cd20')) that.setData({ cd20: c.uuid, characteristics20: c });
                    if (c.uuid.includes('cd01')) that.setData({ cd01: c.uuid, characteristics01: c });
                    if (c.uuid.includes('cd02')) that.setData({ cd02: c.uuid, characteristics02: c });
                    if (c.uuid.includes('cd03')) that.setData({ cd03: c.uuid, characteristics03: c });
                    if (c.uuid.includes('cd04')) that.setData({ cd04: c.uuid, characteristics04: c });
                  });

                  // 4. 監聽數據變化
                  wx.onBLECharacteristicValueChange(ch => {
                    const hex = that.buf2hex(ch.value);
                    if (ch.characteristicId.includes('cd01') || ch.characteristicId.includes('cd04')) {
                      console.log('收到數據:', hex);
                      if (ch.characteristicId.includes('cd04')) that.setData({ result: hex });
                    }
                  });

                  // 5. 啟用 notify
                  ['cd01','cd02','cd03','cd04'].forEach(uuidKey => {
                    wx.notifyBLECharacteristicValueChanged({
                      deviceId: that.data.deviceId,
                      serviceId: that.data.serviceId,
                      characteristicId: that.data[uuidKey],
                      state: true
                    });
                  });
                }
              });
            }, 1500);
          }
        });
      }
    });
  },

  // 發送校驗指令
  bindViewTap() {
    const that = this;
    const hex = 'AA5504B10000B5';
    const typedArray = new Uint8Array(hex.match(/[\da-f]{2}/gi).map(h => parseInt(h, 16)));
    wx.writeBLECharacteristicValue({
      deviceId: that.data.deviceId,
      serviceId: that.data.serviceId,
      characteristicId: that.data.cd20,
      value: typedArray.buffer,
      success() { console.log('指令發送成功'); }
    });
  },

  // ArrayBuffer 轉 Hex 字符串
  buf2hex(buffer) {
    return Array.from(new Uint8Array(buffer))
      .map(x => ('00' + x.toString(16)).slice(-2))
      .join('');
  }
});

四、運行效果展示

設備列表與連接界面

發送指令並接收返回數據

五、關鍵注意事項

  1. UUID 大小寫:微信返回的 UUID 可能為大寫,匹配時建議統一轉大寫/小寫
  2. ArrayBuffer 處理:發送需構造 Uint8Array,接收需轉 Hex 字符串便於業務解析
  3. 異步串行:連接→獲取服務→獲取特徵→啟用 notify 必須嚴格串行,建議用 Promise 或 async/await 管理
  4. Android 兼容:部分機型需開啟 GPS 定位權限才能掃描藍牙
  5. 基礎庫版本:開發工具詳情面板查看基礎庫版本,確保 ≥ 1.1.0

本示例涵蓋了微信小程序 BLE 開發的核心流程,可作為物聯網設備接入的參考模板。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved