Home WeChat Applet Mini Program Development WeChat Mini Program--Ble Bluetooth

WeChat Mini Program--Ble Bluetooth

May 10, 2018 pm 03:13 PM
WeChat applet Bluetooth

This article mainly introduces the implementation method of WeChat applet-Ble Bluetooth. The source code download is attached to the article, which has good reference value. Let’s take a look with the editor below

It’s been a while. There are no articles written about mini programs. On March 28, WeChat’s API received another new update. The long-awaited Bluetooth API update. Just started masturbating.

Source code address

1. Brief description

The Bluetooth adapter interface is supported starting from version 1.1.0 of the basic library.

The iOS WeChat client starts to support version 6.5.6, the Android client does not support it yet

Bluetooth has added a total of 18 api interfaces.

2.Api classification

Search class

Connection class

Communication class

3 .API specific usage

For details, please see the official website:

https://mp.weixin.qq.com/debug/wxadoc/dev/api/bluetooth.html#wxgetconnectedbluethoothdevicesobject

4. Case implementation

#4.1 Search for Bluetooth devices

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

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

/**

 * 搜索设备界面

 */

Page({

 data: {

 logs: [],

 list:[],

 },

 onLoad: function () {

 console.log('onLoad')

var that = this;

// const SDKVersion = wx.getSystemInfoSync().SDKVersion || '1.0.0'

// const [MAJOR, MINOR, PATCH] = SDKVersion.split('.').map(Number)

// console.log(SDKVersion);

// console.log(MAJOR);

// console.log(MINOR);

// console.log(PATCH);

 

// const canIUse = apiName => {

// if (apiName === 'showModal.cancel') {

//  return MAJOR >= 1 && MINOR >= 1

// }

// return true

// }

 

// wx.showModal({

// success: function(res) {

//  if (canIUse('showModal.cancel')) {

//  console.log(res.cancel)

//  }

// }

// })

  //获取适配器

  wx.openBluetoothAdapter({

  success: function(res){

  // success

  console.log("-----success----------");

   console.log(res);

   //开始搜索

  wx.startBluetoothDevicesDiscovery({

 services: [],

 success: function(res){

 // success

  console.log("-----startBluetoothDevicesDiscovery--success----------");

  console.log(res);

 },

 fail: function(res) {

 // fail

  console.log(res);

 },

 complete: function(res) {

 // complete

  console.log(res);

 }

})

 

  },

  fail: function(res) {

   console.log("-----fail----------");

  // fail

   console.log(res);

  },

  complete: function(res) {

  // complete

   console.log("-----complete----------");

   console.log(res);

  }

 })

 

  wx.getBluetoothDevices({

  success: function(res){

   // success

   //{devices: Array[11], errMsg: "getBluetoothDevices:ok"}

   console.log("getBluetoothDevices");

   console.log(res);

   that.setData({

   list:res.devices

   });

   console.log(that.data.list);

  },

  fail: function(res) {

   // fail

  },

  complete: function(res) {

   // complete

  }

  })

 

 },

 onShow:function(){

 

 },

 //点击事件处理

 bindViewTap: function(e) {

  console.log(e.currentTarget.dataset.title);

  console.log(e.currentTarget.dataset.name);

  console.log(e.currentTarget.dataset.advertisData);

 

 var title = e.currentTarget.dataset.title;

 var name = e.currentTarget.dataset.name;

  wx.redirectTo({

  url: '../conn/conn?deviceId='+title+'&name='+name,

  success: function(res){

   // success

  },

  fail: function(res) {

   // fail

  },

  complete: function(res) {

   // complete

  }

  })

 },

})

Copy after login

4.2 Connect to obtain data

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

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

150

151

152

153

154

155

156

157

158

159

160

161

162

163

164

165

166

167

168

169

170

171

172

173

174

175

176

177

178

179

180

181

182

183

184

185

186

187

188

189

190

191

192

193

194

195

196

197

198

199

200

201

202

203

204

205

206

207

208

209

210

211

212

213

214

215

216

217

218

219

220

221

222

223

224

225

226

227

228

229

230

231

232

233

234

235

236

237

238

239

240

241

242

243

244

245

246

/**

 * 连接设备。获取数据

 */

Page({

 data: {

  motto: 'Hello World',

  userInfo: {},

  deviceId: '',

  name: '',

  serviceId: '',

  services: [],

  cd20: '',

  cd01: '',

  cd02: '',

  cd03: '',

  cd04: '',

  characteristics20: null,

  characteristics01: null,

  characteristics02: null,

  characteristics03: null,

  characteristics04: null,

  result,

 

 },

 onLoad: function (opt) {

  var that = this;

  console.log("onLoad");

  console.log('deviceId=' + opt.deviceId);

  console.log('name=' + opt.name);

  that.setData({ deviceId: opt.deviceId });

  /**

   * 监听设备的连接状态

   */

  wx.onBLEConnectionStateChanged(function (res) {

   console.log(`device ${res.deviceId} state has changed, connected: ${res.connected}`)

  })

  /**

   * 连接设备

   */

  wx.createBLEConnection({

   deviceId: that.data.deviceId,

   success: function (res) {

    // success

    console.log(res);

    /**

     * 连接成功,后开始获取设备的服务列表

     */

    wx.getBLEDeviceServices({

     // 这里的 deviceId 需要在上面的 getBluetoothDevices中获取

     deviceId: that.data.deviceId,

     success: function (res) {

      console.log('device services:', res.services)

      that.setData({ services: res.services });

      console.log('device services:', that.data.services[1].uuid);

      that.setData({ serviceId: that.data.services[1].uuid });

      console.log('--------------------------------------');

      console.log('device设备的id:', that.data.deviceId);

      console.log('device设备的服务id:', that.data.serviceId);

      /**

       * 延迟3秒,根据服务获取特征

       */

      setTimeout(function () {

       wx.getBLEDeviceCharacteristics({

        // 这里的 deviceId 需要在上面的 getBluetoothDevices

        deviceId: that.data.deviceId,

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

        serviceId: that.data.serviceId,

        success: function (res) {

         console.log('000000000000' + that.data.serviceId);

         console.log('device getBLEDeviceCharacteristics:', res.characteristics)

         for (var i = 0; i < 5; i++) {

          if (res.characteristics[i].uuid.indexOf("cd20") != -1) {

           that.setData({

            cd20: res.characteristics[i].uuid,

            characteristics20: res.characteristics[i]

           });

          }

          if (res.characteristics[i].uuid.indexOf("cd01") != -1) {

           that.setData({

            cd01: res.characteristics[i].uuid,

            characteristics01: res.characteristics[i]

           });

          }

          if (res.characteristics[i].uuid.indexOf("cd02") != -1) {

           that.setData({

            cd02: res.characteristics[i].uuid,

            characteristics02: res.characteristics[i]

           });

          } if (res.characteristics[i].uuid.indexOf("cd03") != -1) {

           that.setData({

            cd03: res.characteristics[i].uuid,

            characteristics03: res.characteristics[i]

           });

          }

          if (res.characteristics[i].uuid.indexOf("cd04") != -1) {

           that.setData({

            cd04: res.characteristics[i].uuid,

            characteristics04: res.characteristics[i]

           });

          }

         }

         console.log(&#39;cd01= &#39; + that.data.cd01 + &#39;cd02= &#39; + that.data.cd02 + &#39;cd03= &#39; + that.data.cd03 + &#39;cd04= &#39; + that.data.cd04 + &#39;cd20= &#39; + that.data.cd20);

         /**

          * 回调获取 设备发过来的数据

          */

         wx.onBLECharacteristicValueChange(function (characteristic) {

          console.log(&#39;characteristic value comed:&#39;, characteristic.value)

          //{value: ArrayBuffer, deviceId: "D8:00:D2:4F:24:17", serviceId: "ba11f08c-5f14-0b0d-1080-007cbe238851-0x600000460240", characteristicId: "0000cd04-0000-1000-8000-00805f9b34fb-0x60800069fb80"}

          /**

           * 监听cd04cd04中的结果

           */

          if (characteristic.characteristicId.indexOf("cd01") != -1) {

           const result = characteristic.value;

           const hex = that.buf2hex(result);

           console.log(hex);

          }

          if (characteristic.characteristicId.indexOf("cd04") != -1) {

           const result = characteristic.value;

           const hex = that.buf2hex(result);

           console.log(hex);

           that.setData({ result: hex });

          }

 

         })

         /**

          * 顺序开发设备特征notifiy

          */

         wx.notifyBLECharacteristicValueChanged({

          deviceId: that.data.deviceId,

          serviceId: that.data.serviceId,

          characteristicId: that.data.cd01,

          state: true,

          success: function (res) {

           // success

           console.log(&#39;notifyBLECharacteristicValueChanged success&#39;, res);

          },

          fail: function (res) {

           // fail

          },

          complete: function (res) {

           // complete

          }

         })

         wx.notifyBLECharacteristicValueChanged({

          deviceId: that.data.deviceId,

          serviceId: that.data.serviceId,

          characteristicId: that.data.cd02,

          state: true,

          success: function (res) {

           // success

           console.log(&#39;notifyBLECharacteristicValueChanged success&#39;, res);

          },

          fail: function (res) {

           // fail

          },

          complete: function (res) {

           // complete

          }

         })

         wx.notifyBLECharacteristicValueChanged({

          deviceId: that.data.deviceId,

          serviceId: that.data.serviceId,

          characteristicId: that.data.cd03,

          state: true,

          success: function (res) {

           // success

           console.log(&#39;notifyBLECharacteristicValueChanged success&#39;, res);

          },

          fail: function (res) {

           // fail

          },

          complete: function (res) {

           // complete

          }

         })

 

         wx.notifyBLECharacteristicValueChanged({

          // 启用 notify 功能

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

          deviceId: that.data.deviceId,

          serviceId: that.data.serviceId,

          characteristicId: that.data.cd04,

          state: true,

          success: function (res) {

           console.log(&#39;notifyBLECharacteristicValueChanged success&#39;, res)

          }

         })

 

        }, fail: function (res) {

         console.log(res);

        }

       })

      }

       , 1500);

     }

    })

   },

   fail: function (res) {

    // fail

   },

   complete: function (res) {

    // complete

   }

  })

 },

 

 /**

  * 发送 数据到设备中

  */

 bindViewTap: function () {

  var that = this;

  var hex = &#39;AA5504B10000B5&#39;

  var typedArray = new Uint8Array(hex.match(/[\da-f]{2}/gi).map(function (h) {

   return parseInt(h, 16)

  }))

  console.log(typedArray)

  console.log([0xAA, 0x55, 0x04, 0xB1, 0x00, 0x00, 0xB5])

  var buffer1 = typedArray.buffer

  console.log(buffer1)

  wx.writeBLECharacteristicValue({

   deviceId: that.data.deviceId,

   serviceId: that.data.serviceId,

   characteristicId: that.data.cd20,

   value: buffer1,

   success: function (res) {

    // success

    console.log("success 指令发送成功");

    console.log(res);

   },

   fail: function (res) {

    // fail

    console.log(res);

   },

   complete: function (res) {

    // complete

   }

  })

 

 },

 /**

  * ArrayBuffer 转换为 Hex

  */

 buf2hex: function (buffer) { // buffer is an ArrayBuffer

  return Array.prototype.map.call(new Uint8Array(buffer), x => (&#39;00&#39; + x.toString(16)).slice(-2)).join(&#39;&#39;);

 }

})

Copy after login


5. Effect display

WeChat Mini Program--Ble Bluetooth

Send verification instructions. Get results

WeChat Mini Program--Ble Bluetooth

The above is the detailed content of WeChat Mini Program--Ble Bluetooth. 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."

How to Pair a Logitech Keyboard [USB Receiver, Bluetooth, iPad] How to Pair a Logitech Keyboard [USB Receiver, Bluetooth, iPad] Nov 18, 2023 pm 11:27 PM

Before you can use your new wireless keyboard with your PC, you need to pair it, and in this guide, we'll show you how to pair your Logitech keyboard properly. The process is very simple and only takes a few clicks, so join us and we'll show you how to do it on your PC. How do I put a Logitech keyboard into pairing mode? How do we test, review and score? Over the past 6 months, we have been working hard to establish a new review system for how we produce content. Using this, we subsequently redid much of the article to provide practical, hands-on expertise on the guides we produced. For more details, you can read about how we test, review, and rate on Windows Report. Open the keyboard. If the LED does not flash

See all articles