Home WeChat Applet Mini Program Development How to implement Bluetooth connection in WeChat applet? (code example)

How to implement Bluetooth connection in WeChat applet? (code example)

Nov 13, 2018 pm 01:55 PM
WeChat applet Bluetooth connection

How does the WeChat applet implement Bluetooth connection? What this article brings to you is to introduce the method (steps) of WeChat applet to implement Bluetooth connection. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

A recent project requires the use of the Bluetooth function of the mini program to connect with hardware devices to transmit data instructions to each other. During the joint debugging process, some problems were discovered, so I thought of recording them for future reference!

1. Initialize the Bluetooth device

Generally, when using the Bluetooth function, you must want to connect to a certain Bluetooth device, so you need to know the name of the Bluetooth device. , generally you scan the QR code to connect, then when you scan the QR code of this device, you need to initialize the Bluetooth module on your phone

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

/**

* 初始化蓝牙设备

*/

  initBlue:function(){

    var that = this;

    wx.openBluetoothAdapter({//调用微信小程序api 打开蓝牙适配器接口

      success: function (res) {

        // console.log(res)

        wx.showToast({

          title: '初始化成功',

          icon: 'success',

          duration: 800

        })

        that.findBlue();//2.0

      },

      fail: function (res) {//如果手机上的蓝牙没有打开,可以提醒用户

        wx.showToast({

          title: '请开启蓝牙',

          icon: 'fails',

          duration: 1000

        })

      }

    })

  },

Copy after login

2. Search for Bluetooth devices

After the mobile phone Bluetooth is initialized successfully, it will search for surrounding Bluetooth devices

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

/**

*开始搜索蓝牙设备

*/

findBlue(){

    var that = this

    wx.startBluetoothDevicesDiscovery({

      allowDuplicatesKey: false,

      interval: 0,

      success: function (res) {

        

        wx.showLoading({

          title: '正在搜索设备',

        })

        that.getBlue()//3.0

      }

    })

  },

Copy after login

3. Obtain Bluetooth device information

After searching for Bluetooth devices, you need to obtain the searched Bluetooth device information. The WeChat applet provides two methods to obtain the searched Bluetooth device information, which are:

wx.onBluetoothDeviceFound: Listen to the event of finding a new device, which means that this method will be called once as long as a new Bluetooth device is found.

wx.getBluetoothDevices:Get all discovered Bluetooth devices during the validity period of the Bluetooth module, including devices that are already connected to the machine

Look at the two methods Introduction We know their differences, but what kind of problems will it cause if we don’t understand their differences?

The first time I used the wx.onBluetoothDeviceFound method for joint debugging, I found that everything was normal. Since there was only one device during debugging, I found that when I re-scanned the Bluetooth device for the second time, it could not be found. to this device, because for this method, this is not a new device and has been connected before; or when you make an error when transmitting data commands via Bluetooth for some reason and need to reconnect, you cannot find it when you connect again. To the current device, it’s the same reason, because the current device is not a new device for this method

So then I used the wx.getBluetoothDevices method

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

/**

  * 获取搜索到的设备信息

 */

  getBlue(){

    var that = this

    wx.getBluetoothDevices({

      success: function(res) {

        wx.hideLoading();

        for (var i = 0; i < res.devices.length; i++){

           /*that.data.inputValue:表示的是需要连接的蓝牙设备ID,简单点来说就是我想要连接这个蓝牙设备,所以我去遍历我搜索到的蓝牙设备中是否有这个ID*/

          if (res.devices[i].name == that.data.inputValue || res.devices[i].localName == that.data.inputValue){

            that.setData({

              deviceId: res.devices[i].deviceId,

              consoleLog: "设备:" + res.devices[i].deviceId,

            })

            that.connetBlue(res.devices[i].deviceId);//4.0

            return;

          }

        }

      },

      fail: function(){

        console.log("搜索蓝牙设备失败")

      }

    })

  },

Copy after login

4. Connect the Bluetooth device

After finding the Bluetooth through the previous step, make the Bluetooth connection through the id of the Bluetooth device

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

/**

  * 获取到设备之后连接蓝牙设备

 */

  connetBlue(deviceId){                   

    var that = this;

    wx.createBLEConnection({

      // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接

      deviceId: deviceId,//设备id

      success: function (res) {

        wx.showToast({

          title: &#39;连接成功&#39;,

          icon: &#39;fails&#39;,

          duration: 800

        })

        console.log("连接蓝牙成功!")

        wx.stopBluetoothDevicesDiscovery({

          success: function (res) {

            console.log(&#39;连接蓝牙成功之后关闭蓝牙搜索&#39;);

          }

        })

        that.getServiceId()//5.0

      }

    })

  },

Copy after login

5. Obtain Service uuid

After connecting to the required Bluetooth device, obtain the service uuid of this Bluetooth device

1

2

3

4

5

6

7

8

9

10

11

12

13

14

getServiceId(){

    var that = this

    wx.getBLEDeviceServices({

      // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接

      deviceId: that.data.deviceId,

      success: function (res) {

        var model = res.services[0]

        that.setData({

          services: model.uuid

        })

        that.getCharacteId()//6.0

      }

    })

  },

Copy after login

6. View the Bluetooth device by id Characteristic value

If a Bluetooth device needs to write and transmit data, it must have certain characteristic values, so the id obtained through the above steps can be used to view the current Bluetooth Characteristic value of the device

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

getCharacteId(){

    var that = this

    wx.getBLEDeviceCharacteristics({

      // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接

      deviceId: that.data.deviceId,

      // 这里的 serviceId 需要在上面的 getBLEDeviceServices 接口中获取

      serviceId: that.data.services,

      success: function (res) {

        for (var i = 0; i < res.characteristics.length; i++) {//2个值

          var model = res.characteristics[i]

          if (model.properties.notify == true) {

            that.setData({

              notifyId: model.uuid//监听的值

            })

            that.startNotice(model.uuid)//7.0

          }

          if (model.properties.write == true){

            that.setData({

              writeId: model.uuid//用来写入的值

            })

          }

        }

      }

    })

  },

Copy after login

7. Instructions obtained from the background server

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

startNotice(uuid){

    var that = this;

    wx.notifyBLECharacteristicValueChange({

      state: true, // 启用 notify 功能

      // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接

      deviceId: that.data.deviceId,

      // 这里的 serviceId 需要在上面的 getBLEDeviceServices 接口中获取

      serviceId: that.data.services,

      // 这里的 characteristicId 需要在上面的 getBLEDeviceCharacteristics 接口中获取

      characteristicId: uuid,  //第一步 开启监听 notityid  第二步发送指令 write

      success: function (res) {

       

          // 设备返回的方法

          wx.onBLECharacteristicValueChange(function (res) {

              // 此时可以拿到蓝牙设备返回来的数据是一个ArrayBuffer类型数据,所以需要通过一个方法转换成字符串

              var nonceId = that.ab2hex(res.value)

      //拿到这个值后,肯定要去后台请求服务(当前步骤根据当前需求自己书写),获取下一步操作指令写入到蓝牙设备上去

      

     wx.request({

                    method: "POST",

         

                    data: {

                      xx:nonceId

                    },

                    url: url,

                    success: (res) => {

                      //res.data.data.ciphertext:我这边服务返回来的是16进制的字符串,蓝牙设备是接收不到当前格式的数据的,需要转换成ArrayBuffer

                      that.sendMy(that.string2buffer(res.data.data.ciphertext))//8.0

                      // 服务器返回一个命令  我们要把这个命令写入蓝牙设备

                    }

                   })

  }

    })

  },

Copy after login

8. Will be served from the background The obtained instructions are written into the Bluetooth device

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

sendMy(buffer){

    var that = this

    wx.writeBLECharacteristicValue({

      // 这里的 deviceId 需要在上面的 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取

      deviceId: that.data.deviceId,

      // 这里的 serviceId 需要在上面的 getBLEDeviceServices 接口中获取

      serviceId: that.data.services,

      // 这里的 characteristicId 需要在上面的 getBLEDeviceCharacteristics 接口中获取

      characteristicId: that.data.writeId,//第二步写入的特征值

      // 这里的value是ArrayBuffer类型

      value: buffer,

      success: function (res) {

        console.log("写入成功")

      },

      fail: function () {

        console.log(&#39;写入失败&#39;)

      },

      complete:function(){

        console.log("调用结束");

      }

    })

  },

Copy after login

Note: The following is the method of converting the two formats that need to be used

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

/**

* 将字符串转换成ArrayBufer

*/

  string2buffer(str) {

    let val = ""

    if(!str) return;

    let length = str.length;

    let index = 0;

    let array = []

    while(index < length){

      array.push(str.substring(index,index+2));

      index = index + 2;

    }

    val = array.join(",");

    // 将16进制转化为ArrayBuffer

    return new Uint8Array(val.match(/[\da-f]{2}/gi).map(function (h) {

      return parseInt(h, 16)

    })).buffer

  },

  

  /**

   * 将ArrayBuffer转换成字符串

   */

  ab2hex(buffer) {

    var hexArr = Array.prototype.map.call(

      new Uint8Array(buffer),

      function (bit) {

        return (&#39;00&#39; + bit.toString(16)).slice(-2)

      }

    )

    return hexArr.join(&#39;&#39;);

  },

Copy after login

Note: The above is a Bluetooth connection The entire process, but we will definitely not be so smooth in actual use, and the devices that send commands via Bluetooth will have a feature, that is, after someone connects to the current Bluetooth device, others will not be able to search for this Bluetooth device, so you need Considering some special circumstances, the code needs to actively disconnect the Bluetooth connection and release the device for other users to use. In addition, it is easy to cause problems when writing instructions to the Bluetooth device, so a callback must be written to write multiple times. Enter, success guaranteed!

Summary: The above is the entire content of this article, I hope it will be helpful to everyone's study. .

Recommended related video tutorials:

WeChat Mini Program Development Document

WeChat Mini Program Comprehensive and In-depth Analysis Video Tutorial

WeChat applet development CMS system video tutorial

The above is the detailed content of How to implement Bluetooth connection in WeChat applet? (code example). 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)

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;

WeChat applet implements image upload function WeChat applet implements image upload function Nov 21, 2023 am 09:08 AM

WeChat applet implements picture upload function With the development of mobile Internet, WeChat applet has become an indispensable part of people's lives. WeChat mini programs not only provide a wealth of application scenarios, but also support developer-defined functions, including image upload functions. This article will introduce how to implement the image upload function in the WeChat applet and provide specific code examples. 1. Preparatory work Before starting to write code, we need to download and install the WeChat developer tools and register as a WeChat developer. At the same time, you also need to understand WeChat

How to solve the problem of unstable Bluetooth connection in win11? Analysis of the problem of unstable Bluetooth connection in win11 How to solve the problem of unstable Bluetooth connection in win11? Analysis of the problem of unstable Bluetooth connection in win11 Mar 03, 2024 pm 09:10 PM

Now more and more people like to use Bluetooth headsets, but many users are asking what to do if the Bluetooth connection in win11 is unstable? Users can directly find BluetoothSupportService to set it up. Let this site carefully introduce to users the analysis of the problem of unstable Bluetooth connection in Win11. Method 1 for analyzing the problem of unstable Bluetooth connection in win11: Restart the Bluetooth service 1. Press the shortcut key win+R to open the run dialog box, enter the services.msc command, and press Enter to enter the service interface. 3. Click Start below, enter devicemanager in the search box, and click Open on the right to open it. 5. The most

Implement the drop-down menu effect in WeChat applet Implement the drop-down menu effect in WeChat applet Nov 21, 2023 pm 03:03 PM

To implement the drop-down menu effect in WeChat Mini Programs, specific code examples are required. With the popularity of mobile Internet, WeChat Mini Programs have become an important part of Internet development, and more and more people have begun to pay attention to and use WeChat Mini Programs. The development of WeChat mini programs is simpler and faster than traditional APP development, but it also requires mastering certain development skills. In the development of WeChat mini programs, drop-down menus are a common UI component, achieving a better user experience. This article will introduce in detail how to implement the drop-down menu effect in the WeChat applet and provide practical

Implement image filter effects in WeChat mini programs Implement image filter effects in WeChat mini programs Nov 21, 2023 pm 06:22 PM

Implementing picture filter effects in WeChat mini programs With the popularity of social media applications, people are increasingly fond of applying filter effects to photos to enhance the artistic effect and attractiveness of the photos. Picture filter effects can also be implemented in WeChat mini programs, providing users with more interesting and creative photo editing functions. This article will introduce how to implement image filter effects in WeChat mini programs and provide specific code examples. First, we need to use the canvas component in the WeChat applet to load and edit images. The canvas component can be used on the page

Use WeChat applet to achieve carousel switching effect Use WeChat applet to achieve carousel switching effect Nov 21, 2023 pm 05:59 PM

Use the WeChat applet to achieve the carousel switching effect. The WeChat applet is a lightweight application that is simple and efficient to develop and use. In WeChat mini programs, it is a common requirement to achieve carousel switching effects. This article will introduce how to use the WeChat applet to achieve the carousel switching effect, and give specific code examples. First, add a carousel component to the page file of the WeChat applet. For example, you can use the &lt;swiper&gt; tag to achieve the switching effect of the carousel. In this component, you can pass b

What is the name of Xianyu WeChat applet? What is the name of Xianyu WeChat applet? Feb 27, 2024 pm 01:11 PM

The official WeChat mini program of Xianyu has been quietly launched. It provides users with a convenient platform that allows you to easily publish and trade idle items. In the mini program, you can communicate with buyers or sellers via private messages, view personal information and orders, and search for the items you want. So what exactly is Xianyu called in the WeChat mini program? This tutorial guide will introduce it to you in detail. Users who want to know, please follow this article and continue reading! 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.

Implement the sliding delete function in WeChat mini program Implement the sliding delete function in WeChat mini program Nov 21, 2023 pm 06:22 PM

Implementing the sliding delete function in WeChat mini programs requires specific code examples. With the popularity of WeChat mini programs, developers often encounter problems in implementing some common functions during the development process. Among them, the sliding delete function is a common and commonly used functional requirement. This article will introduce in detail how to implement the sliding delete function in the WeChat applet and give specific code examples. 1. Requirements analysis In the WeChat mini program, the implementation of the sliding deletion function involves the following points: List display: To display a list that can be slid and deleted, each list item needs to include

See all articles