支付寶小程序(ble 適配android和ios) 入門一

直接把藍牙相關工具封裝js文件,然後通過page頁面調用即可


//page功能實現頁面

import { scan } from '../../util/bles';
import { openDoor } from '../../util/bles';
const app = getApp();

Page({
  // 調試log輸出
  data: {
    text: '',
    arr:[]
  },
onLoad() {
  app.getUserInfo().then(
    user => this.setData({
    user,
    }),
  );
},

scanBle () { 
    const that = this; 
    // let  mAdvertisData = 'asfasfasgdgwerjertjwpejwioejrioweg';
    // that.setData({ 
    //         text: mAdvertisData.substring(0 , 2) + mAdvertisData.charAt(2),
    //       })
          


    my.offBluetoothDeviceFound();
    my.onBluetoothDeviceFound({
      success: (resFound) => {
        my.getBluetoothDevices({
          success: (resFouned) => {
            that.setData({
              arr: resFouned.devices,
            });
          },
        });
      },
    });   
    scan(function(e){
      that.setData({ 
            text:e,
        })
    });
}, 

onClickItem (e) {
    const that = this; 
    openDoor(e,function(result){
        that.setData({ 
            text:result,
        })
    })
}, 

});

封裝的ble功能js文件(因爲涉及保密項目比如門禁,保險櫃等,有些數據都是隨便寫的,改成自己的就行了)

let timeoutID;
let log = '';
let mDeviceID = "E6:3B:97:21:14:42:12:54";//  android
let uuid_service = "0000fdasde6-0000-1000-8000-0080asd5f9b34fb";
let uuid_descriptorId = "0000asd2902-0000-1000-8000-0080a5f9b34fb"; // 只有android 會用到
let uuid_characteristicId = "0000fade8-0000-1000-8000-00805f9b3412r12fb";
let uuid_char_write = "0000fdeasdfa7-0000-1000-8000-00805f9b34fasdfasdb";
// let mAdvertisData = "888832454e4asdfa344asdfa44575766";
let mAdvertisData = "8888325939514aasdfa955446945";
let data_openDoor = "fe0fas1186501010asdf002016fb1";
let data_openDoor2 = "b9asdfasc1b4c7e1csfaaasdfa7af41d672188f02";

export function scan(callback){
    callback.call(this,'搜索中...');
    my.getSystemInfo({
            success: (resSystem) => {                       
                let os = resSystem.platform;
                if(os == 'Android'){
             
                }else{
                    uuid_service = "FDE6";
                    uuid_characteristicId = "FDE8";
                    uuid_char_write = "FDE7";
                    mDeviceID = "ABEB31F5-5B05-4346-98E8-401FE0asdaffasd62A1F7";//  ios
                }          
            },
        })  
    my.openBluetoothAdapter({ 
        success: function (resOpen) { // 搜索到藍牙回調
              // 開始掃描
              my.stopBluetoothDevicesDiscovery();
              my.startBluetoothDevicesDiscovery({
                services:[uuid_service],

              });

              setTimeout(function(){
                   my.stopBluetoothDevicesDiscovery();
                      callback.call(this,'搜索完成');
                },3000)

          }, 
      fail:function(resOpen){ // 請打開藍牙
         callback.call(this,'請打開藍牙');
      }
    }) 
}

export function openDoor(e, callback){
    callback.call(this , '準備校驗');
    mDeviceID = e.target.dataset.value.deviceId;
        mAdvertisData = e.target.dataset.value.advertisData;
        if (mAdvertisData == "888832454e434444575766"|| mAdvertisData == "888832454E434444575766"){     
            data_openDoor = "fe01186501010002016fb1";
            data_openDoor2 = "b9c1b4c7e1c7af41d672188f02";
        }else if(mAdvertisData == "8888325939514955446945" ){
            data_openDoor = "fe01186501010002494059";
            data_openDoor2 = "341a593cdafb0b04cb35fcea6a";
        }

   
    mAdvertisData = e.target.dataset.value.advertisData;

  let time = 0;

   // 支付寶下一個版本優化
    // my.disconnectBLEDevice({
    //     deviceId:mDeviceID,
    //     success: (resState) => {
    //     callback.call(this,'校驗中'+ JSON.stringify(e));
    //     },
    //     fail:()=>{
    //         callback.call(this,'校驗失敗,藍牙可能累了,請斷開藍牙休息一下!');
    //     }
    // });

  my.stopBluetoothDevicesDiscovery();// 連接之前最好停止掃描
  my.offBLEConnectionStateChanged();
  my.onBLEConnectionStateChanged({
    success: (resState) => {
      callback.call(this,'校驗中.');
      if (resState.connected){
                my.getBLEDeviceServices({
                    deviceId: mDeviceID,
                    success: (resServices) => {  // 獲取服務成功       
                            callback.call(this,'開門中'); 
                            my.getBLEDeviceCharacteristics({
                              deviceId: mDeviceID,
                              serviceId: uuid_service,
                              success: (resChar) => { // 獲取特徵值成功
                                       callback.call(this,'開門中.');          
                                       my.notifyBLECharacteristicValueChange({// 第二步:設置接受到char通知
                                        deviceId: mDeviceID,
                                        serviceId: uuid_service,
                                        characteristicId: uuid_characteristicId,
                                        descriptorId: uuid_descriptorId,
                                        success: (resValue) => { // 通知成功
                                              callback.call(this,'開門中..'); 
                                              my.onBLECharacteristicValueChange({//第三步:設置接受char數據監聽
                                                  success: (resChange) => {
                                                    clearTimeout(timeoutID);
                                                      my.offBLECharacteristicValueChange();// 移除低功耗藍牙設備的特徵值變化事件的監聽。
                                                      my.offBLEConnectionStateChanged();// 移除低功耗藍牙連接的錯誤事件的監聽。
                                                      my.disconnectBLEDevice({
                                                        deviceId: mDeviceID, // 藍牙設備id
                                                        success: (resDisConnect) => { // 斷開設備成功
                                                            callback.call(this,'開門成功');
                                                        },
                                                        fail: (resDisConnect) => { // 斷開設備失敗
                                                            callback.call(this,'開門成功..'); 
                                                            my.closeBluetoothAdapter({
                                                                success: (res) => {
                                                                    callback.call(this,'開門成功...'); 
                                                                    },
                                                                fail:(res) => {
                                                                    callback.call(this,'開門成功....'); 
                                                                    },
                                                         });
                                                        }
                                                      });
                                                      time=10;
                                                    callback.call(this,'開門成功!');  
                                                  }
                                              });

                                              
                                              my.writeBLECharacteristicValue({// 第四步通信1
                                                deviceId: mDeviceID,
                                                serviceId: uuid_service,
                                                characteristicId: uuid_char_write,
                                                value: data_openDoor,
                                                    success: (resWrite) => { // 寫入成功
                                                    callback.call(this,'開門中...');  
                                                        setTimeout(function(){ // 第二包數據,爲了適配部分手機延時50ms
                                                          my.writeBLECharacteristicValue({// 第四步通信1
                                                            deviceId: mDeviceID,
                                                            serviceId: uuid_service,
                                                            characteristicId: uuid_char_write,
                                                            value: data_openDoor2,
                                                                success: (resWrite) => {  // 寫入成功                         
                                                                },
                                                                fail:(resWrite) => {// 寫入失敗1
                                                                    time=10;
                                                                },
                                                          }); 
                                                            },50)
                                                    },
                                              }); 
                                      },
                                      fail:(resValue) => {// 通知失敗
                                        callback.call(this,'開門中..');
                                      },
                                  });


                                    
                              },
                              fail:(resChar) => {// 獲取特徵值失敗
                                 callback.call(this,'開門中..');
                              },
                            });
                                                 
                    },
                    fail:(resServices) => {// 獲取服務失敗
                        callback.call(this,'開門中');  
                    },
                });
           }else{// 連接中斷1
                callback.call(this,'校驗中..');  
              if(time++<2){ // ios手機可能會出現連接後馬上斷開,嘗試重連三次
                  my.connectBLEDevice({ //第一步:連接ble,
                      deviceId: mDeviceID
                  }) 
              }else{
             callback.call(this,'校驗中...'); 
              }
          }
    },
    fail: function (resState) { // 連接中斷2
        callback.call(this,'校驗中....'); 
        if(time++<2){ // ios手機可能會出現連接後馬上斷開,嘗試重連三次
            my.connectBLEDevice({ // 第一步:連接ble,
                deviceId: mDeviceID
            }) 
        } else {
            callback.call(this,'校驗中.....');
        }
      }
  });

  // 第一步:連接ble,
  my.connectBLEDevice({ 
      deviceId: mDeviceID,
  }) 
    
 timeoutID = setTimeout(function(){
        my.offBLECharacteristicValueChange();// 移除低功耗藍牙設備的特徵值變化事件的監聽。
        my.offBLEConnectionStateChanged();// 移除低功耗藍牙連接的錯誤事件的監聽。
        my.disconnectBLEDevice({
        deviceId: mDeviceID, // 藍牙設備id
        success: (resDisConnect) => {
             clearTimeout(timeoutID);
            // that.setData({ 
            //     text: "連接超時" ,
            // })
        },
        fail: (resDisConnect) => {
             clearTimeout(timeoutID);
            // that.setData({ 
            //     text: "連接超時.." ,
            // })
        }
        });
    },5000)//開門時間限定5s
}




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章