Home  >  Article  >  WeChat Applet  >  WeChat applet implements code for Bluetooth link

WeChat applet implements code for Bluetooth link

小云云
小云云Original
2018-05-18 15:14:226268browse

This article mainly introduces to you the relevant information about the Bluetooth link of the WeChat applet. I hope that through this article you can master the development method of the Bluetooth applet. Friends who need it can refer to it. I hope it can help everyone.

WeChat Mini Program Bluetooth Link

WeChat Mini Program Bluetooth Connection 2.0 Description:

1. This version distinguishes between ANDROID and Different ways of Bluetooth connection under IOS system.

2. Links compatible with more situations include:

(1) The device Bluetooth is not turned on, and the connection will automatically start when Bluetooth is turned on.
(2) Automatically reinitialize the Bluetooth adapter every 3000ms after failing to initialize Bluetooth.
(3) Scanning the Bluetooth adapter on the Android side failed and will automatically restart every 3000ms.
(4) The IOS side obtains the connected Bluetooth device as empty, and automatically reacquires every 3000ms.
(5) The Android Bluetooth connection interrupts scanning after starting the connection. If the connection fails, start scanning again.
(6) After the IOS side starts to connect to the device, it will stop acquiring the connected device. If the connection fails, it will automatically restart the acquisition.
(7) After the connection is successful, turn off the system Bluetooth and reset the Bluetooth adapter.
(8) After the connection is successful, turn off the system Bluetooth, turn on Bluetooth again, and automatically restart the connection.
(9) After the connection is successful, turn off the target Bluetooth device and automatically restart scanning (acquisition).
(10) After the connection is successful, minimize the applet (the connection is not interrupted), open the applet and it will show that it is connected.
(11) After the connection is successful, kill the applet process, close the connection, and automatically restart scanning (acquisition).

3. I will update when I remember it....

4. Flowchart, whoever has time can help me draw it tomorrow or the day after tomorrow or...

My connection is made in App.js.

The onLaunch trigger in App.js is to call the init() method.

Init code:

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();
 }

Description:

1. serviceId_2~6 is the serviceId of the Bluetooth device I know I want to connect to. I can only write one.
2. characterId_write is the characteristic value of the Bluetooth device I know I want to connect to write data to.
3. characterId_read is the characteristic value of the Bluetooth device I know I want to connect to read data.
(The above three are for comparison, the actual operation is based on the obtained sericeid and characterid).
4. connectedDevice is the connected device information object.

After the init is completed, start calling the connection startConnect();

startConnect code:

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
    })
   }
  });
 }

Note: There are comments in this paragraph, so I won’t say more. ,easier.

Call the getBluetoothAdapterState() method after successfully initializing the Bluetooth adapter state.

getBluetoothAdapterState Code:

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);
   }
  })
 }

Description: This method is used to obtain the current Bluetooth status.

The judegIfDiscovering method is called when it is detected that Bluetooth is available.

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);
    }
   }
  });
 }

Description:

1. This method is used to determine whether scanning is in progress.

2. isAndroidPlatform is obtained through getSystemInfo of the applet to determine whether it is an Android device or an IOS device.

If it is an Android device, call startBluetoothDevicesDiscovery() to start scanning. If it is an IOS device, call getConnectedBluetoothDevices() to start obtaining paired Bluetooth devices.

startBluetoothDevicesDiscovery Code:

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);
    }
   })
  }

Instructions:

1. Enable scanning for nearby Bluetooth devices only on Android devices.

2. In the successful callback, enable event monitoring onBluetoothDeviceFound() for discovering new Bluetooth devices.

onBluetoothDeviceFound Code:

[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();
     }
    }
   }
  })
 }

Description:

1. Here, the discovered Bluetooth devices are filtered based on the name attribute.

2. When the device containing the name attribute of the device that needs to be connected is filtered out and the deviceId is obtained, the startConnectDevices() method is called to start the connection.

startConnectDevices Code:

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;
   }
  });
 }

Description:

1. Terminate scanning (get paired) method after opening the connection.
2. Create a low-power Bluetooth connection based on deviceId. If the connection is successful, continue with subsequent read and write operations.
3. If the connection fails, call startBluetoothDevicesDiscovery() or getConnectedBluetoothDevices() respectively according to the device system;

getConnectedBluetoothDevices code:

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;
   }
  });
 }

Instructions: If the Bluetooth is paired The Bluetooth device failed, or the list obtained is empty. Call failToGetConnected();

failToGetConnected Code:

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);
 }

Description:

1. The devices returned after the method is successfully called is an array containing multiple Bluetooth devices that have been paired by the system.
2. If the devices list is obtained, call the loopConnect() method to start recursively calling the Bluetooth device.

loopConnect code:

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);
   }
  }
 }

Description: looConnect will delete the first value of the array after the method of creating the connection fails, and then continue to call the method until All devices are connected.

Almost missed it: call the init() method in onShow of app.js.

Special Note:

1. Different methods are recommended for Bluetooth connection on Android and IOS in the current version. The Android device directly uses the Bluetooth connection of the applet to cancel system pairing. IOS devices can be successfully connected within seconds after system pairing and opening the mini program.

2. The connection of this version still needs to be improved. The connection will not be automatically terminated (you can add it yourself if needed), and it will scan and reconnect infinitely until it succeeds.

3. Operation after the link is successful. If writing data and turning on notify need to be done at the same time, it is recommended to write first and then turn on notify. (The reason is unknown, otherwise a 10008 error will occur).

Related recommendations:

Example sharing of how WeChat applet implements Bluetooth

Linux installs the driver and uses Blueman to connect to Bluetooth Detailed introduction of headphones (pictures and text)

WeChat applet--Ble Bluetooth

The above is the detailed content of WeChat applet implements code for Bluetooth link. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn