首頁  >  文章  >  微信小程式  >  微信小程式實現藍牙連結的程式碼

微信小程式實現藍牙連結的程式碼

小云云
小云云原創
2018-05-18 15:14:226268瀏覽

本文主要和大家介紹微信小程式之藍牙的連結的相關資料,希望透過本文大家能夠掌握小程式藍牙的開發方法,需要的朋友可以參考下,希望能幫助到大家。

微信小程式之藍牙的連結

微信小程式藍牙連接2.0說明:

1、本版本區分了ANDROID和IOS系統下藍牙連線的不同方式。

2、相容了更多情況下的連結包括:

(1)未開啟裝置藍牙,當監聽到開啟了藍牙後自動開始連線。
(2)初始化藍牙失敗後每3000ms自動重新初始化藍牙適配器。
(3)安卓端開啟藍牙適配器掃描失敗,每3000ms自動重新開啟。
(4)IOS端取得已連線藍牙裝置為空,每3000ms自動重新取得。
(5)安卓端藍牙開始連結後中斷掃描,連線失敗了,重新開始掃描。
(6)IOS端開始連接設備後,停止取得已連接設備,連線失敗會自動重新開啟取得。
(7)連線成功後,關閉系統藍牙,藍牙轉接器重設。
(8)連線成功後,關閉系統藍牙,再次開啟藍牙,自動重新開始連線。
(9)連線成功後,關閉目標藍牙設備,自動重新開始掃描(取得)。
(10)連線成功後,最小化小程式(連線未中斷),開啟小程式顯示已連線。
(11)連線成功後,殺掉小程式進程,連線關閉,自動重新開始掃描(取得)。

3、想起來了再來更新....。

4、流程圖,明天或後天或...誰有空幫我畫一下也行。

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

在App.js中的onLaunch觸發是呼叫 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();
 }

說明:

1、serviceId_2~6 是我已知的想要連線的藍牙裝置的serviceId可以只寫一個。
2、characterId_write 是我已知的想要連接的藍牙裝置寫入資料的特徵值。
3、characterId_read是我已知的想要連接的藍牙裝置讀取資料的特徵值。
(以上3個都是為了做比對,真實的操作依照取得到的sericeid, characterid為準)。
4、connectedDevice 是連接了的裝置資訊物件。

init完成後開始呼叫連線startConnect();

startConnect程式碼:

startConnect: function () {
  var that = this;
  if (that.connectedDevice.state) return;
  that.connectedDevice.deviceId = "";
  that.connectedDevice.state = false;
  // 如果适配器已经初始化不在调用初始化(重复初始化会报错)
  if (this.adapterHasInit == undefined || this.adapterHasInit) return;
  wx.showLoading({
   title: '初始化蓝牙',
   duration: 2000
  });
  // 开启蓝牙适配器状态监听
  this.listenAdapterStateChange();
  // 初始化蓝牙适配器状态(必须步骤,否则无法进行后续的任何操作)
  wx.openBluetoothAdapter({
   success: function (res) {
    console.log("初始化蓝牙适配器成功");
    that.getBluetoothAdapterState();
    that.adapterHasInit = true;
   },
   fail: function (err) {
    console.log(err);
    wx.showLoading({
     title: '请开蓝牙',
     icon: 'loading',
     duration: 2000
    })
   }
  });
 }

說明:這段有註釋,就不多說了,比較簡單。

在初始化藍牙適配器狀態成功後呼叫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: '请开蓝牙',
      icon: 'loading',
      duration: 2000
     })
    } else {
     if (!that.connectedDevice['state']) {
      that.judegIfDiscovering(res.discovering);
     }
    }
   },
   fail: function (err) {
    console.log(err);
   }
  })
 }

#說明:此方法是用來取得目前藍牙狀態。

當偵測到藍牙可用時呼叫judegIfDiscovering方法。

judegIfDiscovering程式碼

judegIfDiscovering: function (discovering) {
  var that = this;
  if (this.isConnectinng) return;
  wx.getConnectedBluetoothDevices({
   services: [that.serviceId],
   success: function (res) {
    console.log("获取处于连接状态的设备", res);
    var devices = res['devices'];
    if (devices[0]) {
     if (that.isAndroidPlatform) {
      wx.showToast({
       title: '蓝牙连接成功',
       icon: 'success',
       duration: 2000
      });
     } else {
      that.getConnectedBluetoothDevices(256);
     }
    } else {
     if (discovering) {
      wx.showLoading({
       title: '蓝牙搜索中'
      })
     } 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);
    }
   }
  });
 }

#說明:

1、此方法是用來判斷是否正在掃描。

2、isAndroidPlatform 是透過小程式的getSystemInfo所取得的判斷是安卓裝置還是IOS裝置。

如果是安卓裝置呼叫startBluetoothDevicesDiscovery()開啟掃描,如果是IOS裝置呼叫getConnectedBluetoothDevices() 開啟取得已配對的藍牙裝置。

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: '请开蓝牙',
       icon: 'loading',
       duration: 2000
      })
     } else {
      if (res.discovering) {
       wx.showLoading({
        title: '蓝牙搜索中'
       })
      } else {
       wx.startBluetoothDevicesDiscovery({
        services: [],
        allowDuplicatesKey: true,
        success: function (res) {
         that.onBluetoothDeviceFound();
         wx.showLoading({
          title: '蓝牙搜索中'
         })
        },
        fail: function (err) {
         if (err.isDiscovering) {
          wx.showLoading({
           title: '蓝牙搜索中'
          })
         } else {
          that.startDiscoveryTimer = setTimeout(function () {
           if (!that.connectedDevice.state) {
            that.startBluetoothDevicesDiscovery();
           }
          }, 5000)
         }
        }
       });
      }
     }
    },
    fail: function (err) {
     console.log(err);
    }
   })
  }

說明:

1、僅在安卓端裝置上開啟掃描附近藍牙裝置。

2、在開啟成功的回呼中開啟發現新藍牙裝置的事件監聽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();
     }
    }
   }
  })
 }

#說明:

1、此處對已發現的藍牙裝置根據name屬性進行了篩選。

2、當篩選出含有需要連線的裝置的name屬性的裝置是取得到deviceId,開始連線呼叫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('连接失败:', 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;
   }
  });
 }

說明:

1、開啟連線後終止掃描(取得已配對)方法。
2、根據deviceId建立低功耗藍牙連線。如果連線成功,就繼續做後續讀寫操作。
3、如果連線失敗根據裝置系統分別呼叫startBluetoothDevicesDiscovery() 或getConnectedBluetoothDevices();

getConnectedBluetoothDevices程式碼:

getConnectedBluetoothDevices: function (n) {
  var that = this;
  that.isGettingConnected = true;
  wx.showLoading({
   title: '蓝牙搜索中'
  });
  wx.getConnectedBluetoothDevices({
   services: [that.serviceId],
   success: function (res) {
    console.log("获取处于连接状态的设备", res);
    var devices = res['devices'],
     flag = false,
     index = 0,
     conDevList = [];
    devices.forEach(function (value, index, array) {
     if (value['name'].indexOf('FeiZhi') != -1) {
      // 如果存在包含FeiZhi字段的设备
      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;
   }
  });
 }

##getConnectedBluetoothDevices程式碼:

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: '请开蓝牙',
       icon: 'loading',
       duration: 2000
      })
     } else {
      if (!that.connectedDevice['state']) {
       that.getConnectedBluetoothDevices();
      }
     }
    },
    fail: function (err) {
     console.log(err);
    }
   })
  }, 5000);
 }
說明:如果取得藍牙已配對的藍牙設備失敗了,或取得到的清單為空調用failToGetConnected();

failToGetConnected代碼:

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('已配对的设备小程序蓝牙连接失败');
   if (!that.isAndroidPlatform) {
    that.getConnectedBluetoothDevices(431);
   }
  }
 }

#說明:


#1、此方法呼叫成功後回傳的devices是一個陣列包含多個已經系統配對的藍牙裝置。

2、如果devices列表取得到呼叫loopConnect()方法開始遞歸呼叫連接藍牙裝置。

loopConnect程式碼:

###rrreee###說明:looConnect在建立連線的方法連線失敗後會操作刪除陣列的第一個值,然後繼續呼叫該方法,直到其中所有的設備都連接過。 #########差點漏了:在app.js的onShow裡呼叫init()方法。 #########特別說明:######

1、安卓和IOS的藍牙連線在目前版本中推薦採用不同方式。安卓裝置直接使用小程式的藍牙連接,取消系統配對。 IOS設備先系統配對在開啟小程式可以時效秒連線成功。

2、此版本的連線仍有待完善,連線不會自動終止(需要的可以自行加),會無限掃描重連,直到成功。

3、連結成功後的操作如果寫入資料和開啟notify需要同時進行,建議先寫入,然後再開啟notify。 (原因未知,否則必然出現10008錯誤)。

相關推薦:

微信小程式如何實作藍牙的實例分享

Linux安裝驅動程式並使用Blueman連接藍牙耳機的詳細介紹(圖文)

微信小程式--Ble藍牙

以上是微信小程式實現藍牙連結的程式碼的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn