Home WeChat Applet Mini Program Development Bluetooth link in WeChat applet

Bluetooth link in WeChat applet

Jun 22, 2018 pm 04:33 PM
Applets WeChat applet Bluetooth

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

WeChat applet Bluetooth link of the program

WeChat applet Bluetooth connection 2.0 description:

1. This version distinguishes different ways of Bluetooth connection under ANDROID and IOS systems.

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

Description:

1, serviceId_2~6 are the ones I know You can write only one serviceId for the Bluetooth device to be connected.
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 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
    })
   }
  });
 }
Copy after login

Note: There are comments in this section, so I won’t go into details, it’s relatively simple.

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);
   }
  })
 }
Copy after login

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

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

judegIfDiscoveringCode

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);
    }
   }
  });
 }
Copy after login

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 acquiring 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);
    }
   })
  }
Copy after login

Instructions:

1. Only on Android devices Turn on scanning for nearby Bluetooth 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();
     }
    }
   }
  })
 }
Copy after login

Description:

1. Here is 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;
   }
  });
 }
Copy after login

Instructions:

1. After opening the connection Terminate scan (get paired) method.
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() 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;
   }
  });
 }
Copy after login

Note: If the acquisition of Bluetooth paired Bluetooth devices fails, or the obtained list is empty, use 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);
 }
Copy after login

Description:

1. The devices returned after the method is successfully called is an array containing multiple Bluetooth devices that have been paired with 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);
   }
  }
 }
Copy after login

Note: looConnect will delete the first value of the array after the connection method of creating a connection fails, and then continue to call this method until all devices in it have been 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 in 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 will scan and reconnect infinitely until successful.

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).

The above is the entire content of this article. I hope it will be helpful to everyone's study. For more related content, please pay attention to the PHP Chinese website!

Related recommendations:

Simple example of shopping cart in WeChat mini program

How to implement Meituan menu in WeChat mini program

About the steps for login authentication of WeChat applet

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

Statement of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Solve the problem of playing headphones and speakers at the same time in win11 Solve the problem of playing headphones and speakers at the same time in win11 Jan 06, 2024 am 08:50 AM

Generally speaking, we only need to use one of the headphones or speakers at the same time. However, some friends have reported that in the win11 system, they encountered the problem of headphones and speakers sounding at the same time. In fact, we can turn it off in the realtek panel and it will be fine. , let’s take a look below. What should I do if my headphones and speakers sound together in win11? 1. First find and open the "Control Panel" on the desktop. 2. Enter the control panel, find and open "Hardware and Sound" 3. Then find the "Realtek High Definition" with a speaker icon. Audio Manager" 4. Select "Speakers" and click "Rear Panel" to enter the speaker settings. 5. After opening, we can see the device type. If you want to turn off the headphones, uncheck "Headphones".

How to turn on Bluetooth in vivo phone How to turn on Bluetooth in vivo phone Mar 23, 2024 pm 04:26 PM

1. Swipe up at the bottom of the screen to bring up the control center, as shown below. Click the Bluetooth switch to turn on Bluetooth. 2. We can connect to other paired Bluetooth devices or click [Search Bluetooth Device] to connect to a new Bluetooth device. Remember to turn on [Detectability] when you want other friends to search for your phone and connect to Bluetooth. Switch. Method 2. 1. Enter the mobile phone desktop, find and open settings. 2. Pull down the [Settings] directory to find [More Settings] and click to enter. 3. Click to open [Bluetooth] and turn on the Bluetooth switch to turn on Bluetooth.

Xianyu WeChat mini program officially launched Xianyu WeChat mini program officially launched Feb 10, 2024 pm 10:39 PM

Xianyu's official WeChat mini program has quietly been launched. In the mini program, you can post private messages to communicate with buyers/sellers, view personal information and orders, search for items, etc. If you are curious about what the Xianyu WeChat mini program is called, take a look now. What is the name of the Xianyu WeChat applet? Answer: Xianyu, idle transactions, second-hand sales, valuations and recycling. 1. In the mini program, you can post idle messages, communicate with buyers/sellers via private messages, view personal information and orders, search for specified items, etc.; 2. On the mini program page, there are homepage, nearby, post idle, messages, and mine. 5 functions; 3. If you want to use it, you must activate WeChat payment before you can purchase it;

There is no Bluetooth module in win11 system device manager There is no Bluetooth module in win11 system device manager Mar 02, 2024 am 08:01 AM

There is no Bluetooth module in the device manager of win11 system. When using Windows 11 system, sometimes you will encounter the situation that there is no bluetooth module in the device manager. This may bring inconvenience to our daily use, because Bluetooth technology has become very common in modern society, and we often need to use it to connect wireless devices. If you can't find the Bluetooth module in the device manager, don't worry, here are some possible solutions for you: 1. Check the hardware connection: First, make sure you actually have a Bluetooth module on your computer or laptop. Some devices may not have built-in Bluetooth functionality, in which case you need to purchase an external Bluetooth adapter to connect. 2. Update the driver: Sometimes the reason why there is no Bluetooth module in the device manager is because of the driver.

How to solve the problem of Harry Potter curse swap not using Bluetooth How to solve the problem of Harry Potter curse swap not using Bluetooth Mar 21, 2024 pm 04:30 PM

Harry Potter: Magic Awakening has recently added a spell exchange function, which requires players to use Bluetooth or WiFi to exchange spells. Some players find that they cannot use Bluetooth exchange, so how can they use Bluetooth to exchange spells? ? Next, the editor will bring you a solution to the problem that Harry Potter spells cannot be exchanged using Bluetooth. I hope it can help you. Solution to Harry Potter Spell Exchange Not Using Bluetooth 1. First, players need to find the Spell Exchange in the library, and then they can use Bluetooth or WiFi to exchange. 2. Click Use Bluetooth, and it prompts that you need to download a new installation package, but it has been downloaded before, and some players become confused. 3. In fact, players can download the new installation package by going to the store. For ios, they can go to the Apple store to update. For Android, they can download it.

Does Bluetooth 5.3 require mobile phone support? For details please see Does Bluetooth 5.3 require mobile phone support? For details please see Jan 14, 2024 pm 04:57 PM

When we buy a mobile phone, we will see that there is a Bluetooth support option in the mobile phone parameters. Sometimes we will encounter a situation where the purchased Bluetooth headset does not match the mobile phone. So does Bluetooth 5.3 need to be supported by the mobile phone? In fact, it is not necessary. Does Bluetooth 5.3 require mobile phone support? Answer: Bluetooth 5.3 requires mobile phone support. However, any mobile phone that supports Bluetooth can be used. 1. Bluetooth is backward compatible, but using the corresponding version requires mobile phone support. 2. For example, if we buy a wireless Bluetooth headset using Bluetooth 5.3. 3. Then, if our mobile phone only supports Bluetooth 5.0, then Bluetooth 5.0 is used when connecting. 4. Therefore, we can still use this mobile phone to connect headphones to listen to music, but the speed is not as good as Bluetooth.

Samsung brings Bluetooth Auracast audio functionality to multiple Galaxy phones and tablets Samsung brings Bluetooth Auracast audio functionality to multiple Galaxy phones and tablets Feb 21, 2024 pm 01:50 PM

According to news on February 21, Samsung announced today that it will bring Bluetooth Auracast audio broadcasting function to the Galaxy S23 series, ZFold5, ZFlip5 mobile phones, and Galaxy Tab S9 series tablets that have been upgraded to OneUI6.1 and above. Starting last year, Samsung has successively added support for the Bluetooth Auracast audio broadcast function on Galaxy Buds 2 Pro headsets and Samsung smart TVs. Galaxy S24 series mobile phones running OneUI6.1 have also added support. For Samsung devices that are eligible to be upgraded to OneUI6.1, you can open "Settings" > "Bluetooth" > "Three-dot menu" > "Use Auracast to broadcast sound."

Solution to the problem of Bluetooth being unable to connect in Win11 system Solution to the problem of Bluetooth being unable to connect in Win11 system Jan 29, 2024 pm 02:36 PM

What should I do if Bluetooth cannot be used in Win11 system? With the launch of Win11 system, many users can’t wait to upgrade their computers. However, some users encountered a common problem after upgrading: Bluetooth not working. This is a frustrating issue for those who rely on Bluetooth devices. Fortunately, there are some simple solutions that can help you solve this problem. First, you can try restarting your computer. Sometimes, simply restarting your system can solve some problems, including Bluetooth not working. After restarting, check if Bluetooth is working properly. If restarting does not resolve the issue, then you can try updating the Bluetooth driver. Sometimes, old or corrupt drivers can cause

See all articles