ホームページ  >  記事  >  WeChat アプレット  >  WeChat アプレットは Bluetooth リンク用のコードを実装します

WeChat アプレットは Bluetooth リンク用のコードを実装します

小云云
小云云オリジナル
2018-05-18 15:14:226267ブラウズ

この記事は主に WeChat アプレットの Bluetooth リンクに関する情報を紹介します。この記事を通じて Bluetooth アプレットの開発方法を習得できることを願っています。それが必要な友人に役立つことを願っています。みんな。

WeChat アプレット Bluetooth リンク

WeChat アプレット Bluetooth 接続 2.0 説明:

1. このバージョンは、ANDROID および IOS システムでの Bluetooth 接続のさまざまな方法を区別します。

2. より多くの状況で互換性のあるリンクは次のとおりです:

(1) デバイスの Bluetooth がオンになっていない場合、Bluetooth がオンになると接続が自動的に開始されます。
(2) Bluetooth の初期化に失敗した後、3000ms ごとに Bluetooth アダプターを自動的に再初期化します。
(3) Android 側で Bluetooth アダプターを開く際の Bluetooth アダプターのスキャンが失敗し、3000ms ごとに自動的に再起動されます。
(4) IOS側は接続されているBluetoothデバイスを空として取得し、3000msごとに自動で再取得します。
(5) Android Bluetooth接続開始後にスキャンが中断される 接続に失敗した場合は、再度スキャンしてください。
(6) IOS側はデバイスへの接続を開始した後、接続されたデバイスの取得を停止し、接続に失敗した場合は自動的に取得を再開します。
(7) 接続に成功したら、システムの Bluetooth をオフにして、Bluetooth アダプターをリセットします。
(8) 接続が成功したら、システムの Bluetooth をオフにし、再度 Bluetooth をオンにして、自動的に接続を再開します。
(9) 接続に成功したら、対象のBluetoothデバイスの電源を切り、自動的にスキャン(取得)を再開します。
(10) 接続が成功したら、アプレットを最小化し (接続は中断されません)、アプレットを開くと、接続されたことが表示されます。
(11) 接続成功後、アプレットプロセスを強制終了し、接続を閉じ、自動的にスキャン(取得)を再開します。

3.思い出したら更新します。

4. フローチャート、もし時間があれば、明日か明後日か...

私の接続は App.js で行われます。

App.js の onLaunch トリガーは、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 は、接続したい Bluetooth デバイスの serviceId を記述するだけです。
2.characterId_write は、データを書き込むために接続することがわかっている Bluetooth デバイスの特性値です。
3.characterId_read は、データを読み取るために接続することがわかっている Bluetooth デバイスの特性値です。
(上記の 3 つは比較用であり、実際の操作は取得した sericeid とcharacterid に基づいています)。
4. ConnectedDevice は、接続されたデバイス情報オブジェクトです。

初期化が完了したら、接続 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
    })
   }
  });
 }

注: この段落にはコメントがあるため、これ以上は説明しません。比較的単純です。

Bluetooth アダプターの状態を正常に初期化した後、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);
   }
  })
 }

説明: このメソッドは、現在の Bluetooth ステータスを取得するために使用されます。

Bluetooth が利用可能であることが検出されると、judegIfDiscovering メソッドが呼び出されます。

judegIfDiscovering code:

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. アプレットの getSystemInfo を通じて isAndroidPlatform を取得し、Android デバイスか IOS デバイスかを判断します。

Android デバイスの場合は、startBluetoothDevicesDiscovery() を呼び出してスキャンを開始します。IOS デバイスの場合は、getConnectedBluetoothDevices() を呼び出して、ペアリングされた Bluetooth デバイスの取得を開始します。

startBluetoothDevices検出コード:

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. Android デバイスのみで近くの Bluetooth デバイスのスキャンを有効にします。

2. 成功したコールバックで、新しい Bluetooth デバイスを検出するために 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. 検出された Bluetooth デバイスは、ここで 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 に基づいて低電力 Bluetooth 接続を作成します。接続が成功した場合は、後続の読み取りおよび書き込み操作を続行します。
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;
   }
  });
 }

注: Bluetooth ペアリングされた Bluetooth デバイスの取得が失敗した場合、または取得されたリストが空調用の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: '请开蓝牙',
       icon: 'loading',
       duration: 2000
      })
     } else {
      if (!that.connectedDevice['state']) {
       that.getConnectedBluetoothDevices();
      }
     }
    },
    fail: function (err) {
     console.log(err);
    }
   })
  }, 5000);
 }

説明:

1. メソッドが正常に呼び出された後に返されるデバイスは、システムによってペアリングされている複数の Bluetooth デバイスを含む配列です。
2. デバイスリストを取得したら、loopConnect()メソッドを呼び出してBluetoothデバイスの再帰呼び出しを開始します。

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

説明: 接続を作成するメソッドが失敗すると、looConnect は配列の最初の値を削除し、その中のすべてのデバイスが接続されるまでメソッドの呼び出しを続けます。

ほとんど見逃していました: app.js の onShow で init() メソッドを呼び出します。

特別な指示:

1. 現在のバージョンでは、Android と IOS での Bluetooth 接続には異なる方法が推奨されています。 Android デバイスは、アプレットの Bluetooth 接続を直接使用して、システム ペアリングをキャンセルします。 IOS デバイスは、システムをペアリングしてミニ プログラムを開いた後、数秒以内に正常に接続できます。

2. このバージョンの接続はまだ改善の必要があります。接続は自動的に終了せず、成功するまで無限にスキャンと再接続を行います。

3. リンク成功後の操作は、データの書き込みと通知のオンを同時に行う必要がある場合、最初に書き込みを行ってから通知をオンにすることをお勧めします。 (理由は不明です。そうでない場合は 10008 エラーが発生します)。

関連する推奨事項:

WeChat アプレットが Bluetooth を実装する方法の例の共有

Linux へのドライバーのインストールと、Blueman を使用した Bluetooth ヘッドセットの接続に関する詳細な紹介 (画像とテキスト)

WeChat アプレット--ブルートゥース

以上がWeChat アプレットは Bluetooth リンク用のコードを実装しますの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。