微信小程序之藍(lán)牙鏈接的示例分析

這篇文章將為大家詳細(xì)講解有關(guān)微信小程序之藍(lán)牙鏈接的示例分析,小編覺(jué)得挺實(shí)用的,因此分享給大家做個(gè)參考,希望大家閱讀完這篇文章后可以有所收獲。

成都創(chuàng)新互聯(lián)堅(jiān)持“要么做到,要么別承諾”的工作理念,服務(wù)領(lǐng)域包括:網(wǎng)站設(shè)計(jì)、成都網(wǎng)站設(shè)計(jì)、企業(yè)官網(wǎng)、英文網(wǎng)站、手機(jī)端網(wǎng)站、網(wǎng)站推廣等服務(wù),滿足客戶于互聯(lián)網(wǎng)時(shí)代的城關(guān)網(wǎng)站設(shè)計(jì)、移動(dòng)媒體設(shè)計(jì)的需求,幫助企業(yè)找到有效的互聯(lián)網(wǎng)解決方案。努力成為您成熟可靠的網(wǎng)絡(luò)建設(shè)合作伙伴!

微信小程序之藍(lán)牙的鏈接

微信小程序藍(lán)牙連接2.0說(shuō)明:

1、本版本區(qū)分了ANDROID和IOS系統(tǒng)下藍(lán)牙連接的不同方式。

2、兼容了更多情況下的鏈接包括:

(1)未開(kāi)啟設(shè)備藍(lán)牙,當(dāng)監(jiān)聽(tīng)到開(kāi)啟了藍(lán)牙后自動(dòng)開(kāi)始連接。
(2)初始化藍(lán)牙失敗后每3000ms自動(dòng)重新初始化藍(lán)牙適配器。
(3)安卓端開(kāi)啟藍(lán)牙適配器掃描失敗,每3000ms自動(dòng)重新開(kāi)啟。
(4)IOS端獲取已連接藍(lán)牙設(shè)備為空,每3000ms自動(dòng)重新獲取。
(5)安卓端藍(lán)牙開(kāi)始鏈接后中斷掃描,連接失敗了,重新開(kāi)始掃描。
(6)IOS端開(kāi)始連接設(shè)備后,停止獲取已連接設(shè)備,連接失敗自動(dòng)重新開(kāi)啟獲取。
(7)連接成功后,關(guān)閉系統(tǒng)藍(lán)牙,藍(lán)牙適配器重置。
(8)連接成功后,關(guān)閉系統(tǒng)藍(lán)牙,再次打開(kāi)藍(lán)牙,自動(dòng)重新開(kāi)始連接。
(9)連接成功后,關(guān)閉目標(biāo)藍(lán)牙設(shè)備,自動(dòng)重新開(kāi)始掃描(獲取)。
(10)連接成功后,最小化小程序(連接未中斷),打開(kāi)小程序顯示已連接。
(11)連接成功后,殺掉小程序進(jìn)程,連接關(guān)閉,自動(dòng)重新開(kāi)始掃描(獲?。?/p>

3、想起來(lái)了再來(lái)更新....。

4、流程圖,明天或后天或...誰(shuí)有空幫我畫(huà)一下也行。

我的連接是在App.js中做的。

在App.js中的onLaunch觸發(fā)是調(diào)用 init()方法。

init代碼:

init: function (n) {
  this.list = [];
  this.serviceId = "6E400001-B5A3-F393-E0A9-E50E24DCCA9E";
  this.serviceId_2 = "00001803-0000-1000-8000-00805F9B34FB";
  this.serviceId_3 = "00001814-0000-1000-8000-00805F9B34FB";
  this.serviceId_4 = "00001802-0000-1000-8000-00805F9B34FB";
  this.serviceId_5 = "00001804-0000-1000-8000-00805F9B34FB";
  this.serviceId_6 = "00001535-1212-EFDE-1523-785FEABCD123";
  this.characterId_write = "6E400042-B5A3-F393-E0A9-E50E24DCCA9E";
  this.characterId_read = "6E400012-B5A3-F393-E0A9-E50E24DCCA9E";
  this.connectDeviceIndex = 0;
  this.isGettingConnected = false;
  this.isDiscovering = false;
  this.isConnecting = false;
  this.connectedDevice = {};
  console.log('init state', this.connectedDevice.state);
  if (!this.connectedDevice.state || n == 200) {
   this.connectedDevice.state = false;
   this.connectedDevice.deviceId = '';
   this.adapterHasInit = false
  }
  this.startConnect();
 }

說(shuō)明:

1、 serviceId_2~6 是我已知的想要連接的藍(lán)牙設(shè)備的serviceId可以只寫(xiě)一個(gè)。
2、characterId_write 是我已知的想要連接的藍(lán)牙設(shè)備寫(xiě)入數(shù)據(jù)的特征值。
3、characterId_read是我已知的想要連接的藍(lán)牙設(shè)備讀取數(shù)據(jù)的特征值。
(以上3個(gè)都是為了做比對(duì),真實(shí)的操作按照獲取到的sericeid, characterid為準(zhǔn))。
4、connectedDevice 是已連接了的設(shè)備信息對(duì)象。

init完成后開(kāi)始調(diào)用連接 startConnect();

startConnect代碼:

startConnect: function () {
  var that = this;
  if (that.connectedDevice.state) return;
  that.connectedDevice.deviceId = "";
  that.connectedDevice.state = false;
  // 如果適配器已經(jīng)初始化不在調(diào)用初始化(重復(fù)初始化會(huì)報(bào)錯(cuò))
  if (this.adapterHasInit == undefined || this.adapterHasInit) return;
  wx.showLoading({
   title: '初始化藍(lán)牙',
   duration: 2000
  });
  // 開(kāi)啟藍(lán)牙適配器狀態(tài)監(jiān)聽(tīng)
  this.listenAdapterStateChange();
  // 初始化藍(lán)牙適配器狀態(tài)(必須步驟,否則無(wú)法進(jìn)行后續(xù)的任何操作)
  wx.openBluetoothAdapter({
   success: function (res) {
    console.log("初始化藍(lán)牙適配器成功");
    that.getBluetoothAdapterState();
    that.adapterHasInit = true;
   },
   fail: function (err) {
    console.log(err);
    wx.showLoading({
     title: '請(qǐng)開(kāi)藍(lán)牙',
     icon: 'loading',
     duration: 2000
    })
   }
  });
 }

說(shuō)明:這段有注釋,就不多說(shuō)了,比較簡(jiǎn)單。

在初始化藍(lán)牙適配器狀態(tài)成功后調(diào)用getBluetoothAdapterState()方法。

getBluetoothAdapterState代碼:

getBluetoothAdapterState: function () {
  var that = this;
  wx.getBluetoothAdapterState({
   success: function (res) {
    console.log(res);
    var available = res.available;
    that.isDiscovering = res.discovering;
    if (!available) {
     wx.showLoading({
      title: '請(qǐng)開(kāi)藍(lán)牙',
      icon: 'loading',
      duration: 2000
     })
    } else {
     if (!that.connectedDevice['state']) {
      that.judegIfDiscovering(res.discovering);
     }
    }
   },
   fail: function (err) {
    console.log(err);
   }
  })
 }

說(shuō)明:此方法是用來(lái)獲取當(dāng)前藍(lán)牙狀態(tài)。

當(dāng)檢測(cè)到藍(lán)牙可用時(shí)調(diào)用judegIfDiscovering方法。

judegIfDiscovering代碼

judegIfDiscovering: function (discovering) {
  var that = this;
  if (this.isConnectinng) return;
  wx.getConnectedBluetoothDevices({
   services: [that.serviceId],
   success: function (res) {
    console.log("獲取處于連接狀態(tài)的設(shè)備", res);
    var devices = res['devices'];
    if (devices[0]) {
     if (that.isAndroidPlatform) {
      wx.showToast({
       title: '藍(lán)牙連接成功',
       icon: 'success',
       duration: 2000
      });
     } else {
      that.getConnectedBluetoothDevices(256);
     }
    } else {
     if (discovering) {
      wx.showLoading({
       title: '藍(lán)牙搜索中'
      })
     } else {
      if (that.isAndroidPlatform) {
       that.startBluetoothDevicesDiscovery();
      } else {
       that.getConnectedBluetoothDevices(267);
      }
     }
    }
   },
   fail: function (err) {
    console.log('getConnectedBluetoothDevices err 264', err);
    if (that.isAndroidPlatform) {
     that.startBluetoothDevicesDiscovery();
    } else {
     that.getConnectedBluetoothDevices(277);
    }
   }
  });
 }

說(shuō)明:

1、此方法是用來(lái)判斷是否正在掃描。

2、isAndroidPlatform 是通過(guò)小程序的getSystemInfo獲取到的判斷是安卓設(shè)備還是IOS設(shè)備。

如果是安卓設(shè)備調(diào)用startBluetoothDevicesDiscovery()開(kāi)啟掃描,如果是IOS設(shè)備調(diào)用getConnectedBluetoothDevices() 開(kāi)啟獲取已配對(duì)的藍(lán)牙設(shè)備。

startBluetoothDevicesDiscovery代碼:

startBluetoothDevicesDiscovery: function () {
  var that = this;
  if (!this.isAndroidPlatform) return;
  if (!this.connectedDevice['state']) {
   wx.getBluetoothAdapterState({
    success: function (res) {
     console.log(res);
     var available = res.available;
     that.isDiscovering = res.discovering;
     if (!available) {
      wx.showLoading({
       title: '請(qǐng)開(kāi)藍(lán)牙',
       icon: 'loading',
       duration: 2000
      })
     } else {
      if (res.discovering) {
       wx.showLoading({
        title: '藍(lán)牙搜索中'
       })
      } else {
       wx.startBluetoothDevicesDiscovery({
        services: [],
        allowDuplicatesKey: true,
        success: function (res) {
         that.onBluetoothDeviceFound();
         wx.showLoading({
          title: '藍(lán)牙搜索中'
         })
        },
        fail: function (err) {
         if (err.isDiscovering) {
          wx.showLoading({
           title: '藍(lán)牙搜索中'
          })
         } else {
          that.startDiscoveryTimer = setTimeout(function () {
           if (!that.connectedDevice.state) {
            that.startBluetoothDevicesDiscovery();
           }
          }, 5000)
         }
        }
       });
      }
     }
    },
    fail: function (err) {
     console.log(err);
    }
   })
  }

說(shuō)明:

1、僅在安卓端設(shè)備上開(kāi)啟掃描附近藍(lán)牙設(shè)備。

2、在開(kāi)啟成功的回調(diào)中開(kāi)啟發(fā)現(xiàn)新藍(lán)牙設(shè)備的事件監(jiān)聽(tīng)onBluetoothDeviceFound()。

onBluetoothDeviceFound代碼:

[mw_shl_code=javascript,true]onBluetoothDeviceFound: function () {
  var that = this;
  wx.onBluetoothDeviceFound(function (res) {
   console.log('new device list has founded');
   if (res.devices[0]) {
    var name = res.devices[0]['name'];
    if (name.indexOf('FeiZhi') != -1) {
     var deviceId = res.devices[0]['deviceId'];
     console.log(deviceId);
     that.deviceId = deviceId;
     if (!that.isConnecting) {
      that.startConnectDevices();
     }
    }
   }
  })
 }

說(shuō)明:

1、此處對(duì)已發(fā)現(xiàn)的藍(lán)牙設(shè)備根據(jù)name屬性進(jìn)行了過(guò)濾。

2、當(dāng)篩選出含有需要連接的設(shè)備的name屬性的設(shè)備是獲取到deviceId,開(kāi)始連接調(diào)用startConnectDevices()方法。

startConnectDevices代碼:

startConnectDevices: function (ltype, array) {
  var that = this;
  clearTimeout(this.getConnectedTimer);
  clearTimeout(this.startDiscoveryTimer);
  this.getConnectedTimer = null;
  this.startDiscoveryTimer = null;
  this.isConnectinng = true;
  wx.showLoading({
   title: '正在連接'
  });
  that.stopBluetoothDevicesDiscovery();
  wx.createBLEConnection({
   deviceId: that.deviceId,
   success: function (res) {
    console.log('連接成功', res);
    wx.showLoading({
     title: '正在連接'
    });
    that.connectedDevice.state = true;
    that.connectedDevice.deviceId = that.deviceId;
    if (res.errCode == 0) {
     setTimeout(function () {
      that.getService(that.deviceId);
     }, 5000)
    }
    wx.onBLEConnectionStateChange(function (res) {
     console.log('連接變化', res);
     that.connectedDevice.state = res.connected;
     that.connectedDevice.deviceId = res.deviceId;
     if (!res.connected) {
      that.init('200');
     }
    });
   },
   fail: function (err) {
    console.log('連接失?。?#39;, err);
    wx.hideLoading();
    if (ltype == 'loop') {
     array = array.splice(0, 1);
     console.log(array);
     that.loopConnect(array);
    } else {
     if (that.isAndroidPlatform) {
      that.startBluetoothDevicesDiscovery();
     } else {
      that.getConnectedBluetoothDevices(488);
     }
    }
   },
   complete: function () {
    that.isConnectinng = false;
   }
  });
 }

說(shuō)明:

1、開(kāi)啟連接后終止掃描(獲取已配對(duì))方法。
2、根據(jù)deviceId創(chuàng)建低功耗藍(lán)牙連接。如果連接成功,就繼續(xù)做后續(xù)讀寫(xiě)操作。
3、如果連接失敗根據(jù)設(shè)備系統(tǒng)分別調(diào)用startBluetoothDevicesDiscovery() 或 getConnectedBluetoothDevices();

getConnectedBluetoothDevices代碼:

getConnectedBluetoothDevices: function (n) {
  var that = this;
  that.isGettingConnected = true;
  wx.showLoading({
   title: '藍(lán)牙搜索中'
  });
  wx.getConnectedBluetoothDevices({
   services: [that.serviceId],
   success: function (res) {
    console.log("獲取處于連接狀態(tài)的設(shè)備", res);
    var devices = res['devices'],
     flag = false,
     index = 0,
     conDevList = [];
    devices.forEach(function (value, index, array) {
     if (value['name'].indexOf('FeiZhi') != -1) {
      // 如果存在包含F(xiàn)eiZhi字段的設(shè)備
      flag = true;
      index += 1;
      conDevList.push(value['deviceId']);
      that.deviceId = value['deviceId'];
     }
    });
    if (flag) {
     that.connectDeviceIndex = 0;
     that.loopConnect(conDevList);
    } else {
     that.failToGetConnected();
    }
   },
   fail: function (err) {
    that.failToGetConnected();
   },
   complete: function () {
    that.isGettingConnected = false;
   }
  });
 }

說(shuō)明:如果獲取藍(lán)牙已配對(duì)的藍(lán)牙設(shè)備失敗了,或獲取到的列表為空調(diào)用failToGetConnected();

failToGetConnected代碼:

failToGetConnected: function () {
  var that = this;
  if (!that.getConnectedTimer) {
   clearTimeout(that.getConnectedTimer);
   that.getConnectedTimer = null;
  }
  that.getConnectedTimer = setTimeout(function () {
   wx.getBluetoothAdapterState({
    success: function (res) {
     console.log(res);
     var available = res.available;
     if (!available) {
      wx.showLoading({
       title: '請(qǐng)開(kāi)藍(lán)牙',
       icon: 'loading',
       duration: 2000
      })
     } else {
      if (!that.connectedDevice['state']) {
       that.getConnectedBluetoothDevices();
      }
     }
    },
    fail: function (err) {
     console.log(err);
    }
   })
  }, 5000);
 }

說(shuō)明:

1、該方法調(diào)用成功后返回的devices是一個(gè)數(shù)組包含多個(gè)已經(jīng)系統(tǒng)配對(duì)的藍(lán)牙設(shè)備。
2、如果devices列表獲取到調(diào)用loopConnect()方法開(kāi)始遞歸調(diào)用連接藍(lán)牙設(shè)備。

loopConnect代碼:

loopConnect: function (array) {
  var that = this;
  var listLen = array.length;
  if (array[0]) {
   that.deviceId = array[0];
   if (!that.isConnecting) {
    that.startConnectDevices('loop', array);
   }
  } else {
   console.log('已配對(duì)的設(shè)備小程序藍(lán)牙連接失敗');
   if (!that.isAndroidPlatform) {
    that.getConnectedBluetoothDevices(431);
   }
  }
 }

說(shuō)明:looConnect在創(chuàng)建連接的方法連接失敗后會(huì)操作刪除數(shù)組的第一個(gè)值,然后繼續(xù)調(diào)用該方法,直到其中所有的設(shè)備都連接過(guò)。

差點(diǎn)漏了:在app.js的onShow里調(diào)用init()方法。

特別說(shuō)明:

1、安卓和IOS的藍(lán)牙連接在當(dāng)前版本中推薦采用不同方式。安卓設(shè)備直接使用小程序的藍(lán)牙連接,取消系統(tǒng)配對(duì)。IOS設(shè)備先系統(tǒng)配對(duì)在打開(kāi)小程序可以時(shí)效秒連接成功。

2、此版本的連接仍然有待完善,連接不會(huì)自動(dòng)終止(需要的可以自己加),會(huì)無(wú)限掃描重連,直到成功。

3、鏈接成功后的操作如果寫(xiě)入數(shù)據(jù)和開(kāi)啟notify需要同時(shí)進(jìn)行,建議先寫(xiě)入,后開(kāi)啟notify。(原因未知,否則必然出現(xiàn)10008錯(cuò)誤)。

關(guān)于“微信小程序之藍(lán)牙鏈接的示例分析”這篇文章就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,使各位可以學(xué)到更多知識(shí),如果覺(jué)得文章不錯(cuò),請(qǐng)把它分享出去讓更多的人看到。

網(wǎng)站標(biāo)題:微信小程序之藍(lán)牙鏈接的示例分析
網(wǎng)站URL:http://bm7419.com/article24/iihgce.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供小程序開(kāi)發(fā)、微信小程序、網(wǎng)站內(nèi)鏈、電子商務(wù)、響應(yīng)式網(wǎng)站品牌網(wǎng)站建設(shè)

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)

微信小程序開(kāi)發(fā)