WeChat applet uses Bluetooth communication protocol to connect hardware summary (initialize Bluetooth, search for devices, display devices)


Recently, we have launched a small program project, which is exclusive to the whole country. It mainly detects some basic vital signs of the human body, such as the detection of electrocardiogram, heart rate, blood oxygen saturation, blood sugar, uric acid, etc., because the product is independently developed by us, and the hardware is also made by ourselves, so the software is also developed by our entire R&D team.

The current detection board only supports 蓝牙协议data transmission, and the small program and the detection board need to send and receive instructions to realize various functions. Strike while the iron is hot. Today I will sort out how we use the small program to connect to Bluetooth.

Initialize the bluetooth module

In the applet, if you want to use the Bluetooth capability, you must first call to wx.openBluetoothAdapterinitialize the Bluetooth adapter module, and the effective period is from calling wx.openBluetoothAdapterto calling wx.closeBluetoothAdapteror applet destruction.

WeChat open document: Only when the Bluetooth adapter module of the applet is in effect, the developer can normally call the Bluetooth-related applet API and receive the event callback related to the Bluetooth module (binding monitoring is not subject to this limitation).

The Bluetooth support of the applet is as follows: 经典蓝牙: iOS is temporarily unavailable due to system restrictions, and Android is currently under planning. 蓝牙低功耗 (BLE):: 主机模式Basic library 1.1.0 (WeChat client iOS 6.5.6, Android 6.5.7) started to support. 从机模式: Basic library 2.10.3 started to support. 蓝牙信标 (Beacon): Basic library 1.2.0 started to support.

The general process of Bluetooth connection

1. Initialize the Bluetooth device

First, let's call the method of initializing the Bluetooth module wx.openBluetoothAdapter. When the mobile phone fails to turn on Bluetooth or the Bluetooth authorization of the applet is rejected, a failure callback will be triggered. In order to enhance the user's good experience, we can give it an effective reminder. code show as below:

wx.openBluetoothAdapter({success: function (res) {console.log("初始化蓝牙成功")//查找蓝牙设备findBlue();},fail: function (res) {wx.showModal({content: '请开启手机蓝牙!',showCancel: false,success (res) {}})}}) 

Note : Other bluetooth related APImust wx.openBluetoothAdapterbe used after calling. Otherwise, APIan error **(errCode=10000)** will be returned.

2. Search for Bluetooth devices

After we successfully initialize the Bluetooth module, we can search for Bluetooth devices in the next step. We need to call this method to wx.startBluetoothDevicesDiscoverystart searching for nearby Bluetooth devices. This operation consumes system resources. After searching for the desired device, we need to call it in time to stop the search wx.stopBluetoothDevicesDiscovery. The relevant code is as follows:

const findBlue = model => {wx.startBluetoothDevicesDiscovery({services:	["xxxxxxxx", "0000FFB0-xxxxxx"],interval: 0,success: function (res) {ConnectedDeviceRelated.isSearchBluetooth_detectionBoard = trueif (model != 'repeat' && e != 'notSearch') {wx.showToast({title: '正在搜索中...',icon: 'none',duration: 1500})}//解决iOS第一次进入检测页面卡死的问题setTimeout(function (params) {getBluetoothDevices()},500)},fail:function (res) {console.log('搜索蓝牙设备错误',res)if (res.errMsg == 'startBluetoothDevicesDiscovery:fail:location permission is denied') {wx.showModal({title: '警告',content: '微信的位置权限被拒绝,请到设置中手动开启授权!',showCancel: false,success(res) {}})}}})} 

Among them is the servicesmain service list of Bluetooth devices to be searched UUID, and some Bluetooth devices will broadcast their own main serviceservices UUID. If this parameter is set, only the bluetooth devices whose broadcast packets have the main service corresponding to UUID will be searched, and other bluetooth devices that do not need to be processed can be filtered out by this parameter. What is written in my sample code is XXXthat you can come according to your actual situation.

Note that the Bluetooth function needs to use the positioning permission, 安卓微信 6.0and the above version, without the positioning permission or the positioning switch is not turned on, the device search cannot be performed. In this case, 安卓微信 8.0.16before the interface call is successful but the device cannot be scanned; 8.0.16and above versions, an error will be returned. After returning an error, it is recommended to prompt the user to enable the location permission.

The code is the following paragraph, which has already been put on it:

fail:function (res) {console.log('搜索蓝牙设备错误',res)if (res.errMsg == 'startBluetoothDevicesDiscovery:fail:location permission is denied') {wx.showModal({title: '警告',content: '微信的位置权限被拒绝,请到设置中手动开启授权!',showCancel: false,success(res) {}})}} 

3. Get the searched Bluetooth devices

In the previous method, we searched for nearby Bluetooth devices, so what should we do after we find them? We will get it out for use in business scenarios. Obtain all searched Bluetooth devices when the Bluetooth module is in effect, including devices that have been connected to the device. After obtaining the device you specified, save the device id of the Bluetooth device separately, which will be used in subsequent operations. code show as below:

 //获取蓝牙设备信息const getBluetoothDevices = () => {wx.getBluetoothDevices({success: function (res) {if (res.devices.length > 0) {for (var i = 0; i < res.devices.length; i++) {if (res.devices[i].localName == ConnectedDeviceRelated.inputValue) {console.log('看一下获取到的指定设备', res.devices[i])ConnectedDeviceRelated.deviceId = res.devices[i].deviceIdapp.globalData.deviceId = res.devices[i].deviceIdapp.globalData.bluetooth = res.devices[i].localNamecreateBLEConnection()break;}if (res.devices.length - 1 == i) {findBlue('repeat')}}} else {findBlue('repeat')}},fail: function () {console.log("搜索蓝牙设备失败")}})} 

The following figure is the device printing information we obtained:

at last

For students who have never been exposed to network security, we have prepared a detailed learning and growth roadmap for you. It can be said that it is the most scientific and systematic learning route, and it is no problem for everyone to follow this general direction.

At the same time, there are supporting videos for each section corresponding to the growth route:

Of course, in addition to supporting videos, various documents, books, materials & tools have been sorted out for you, and they have been classified into categories for you.

Due to the limited space, only part of the information is displayed. Friends in need can [click the card below] to get it for free:

Guess you like

Origin blog.csdn.net/Android062005/article/details/129195588