Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How does WeChat Mini Programs use Bluetooth links

2025-02-22 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)05/31 Report--

This article mainly introduces the relevant knowledge of "how WeChat Mini Programs uses Bluetooth links". The editor shows you the operation process through an actual case, and the operation method is simple, fast and practical. I hope this article "how WeChat Mini Programs uses Bluetooth links" can help you solve the problem.

The link of WeChat Mini Programs's Bluetooth

WeChat Mini Programs Bluetooth connection 2.0description:

1. This version distinguishes the different ways of connecting Bluetooth in ANDROID and IOS systems.

2. links that are compatible in more cases include:

(1) Bluetooth is not enabled, and automatically starts to connect when it is monitored that Bluetooth is turned on.

(2) after the failure to initialize Bluetooth, each 3000ms automatically reinitializes the Bluetooth adapter.

(3) failed to turn on Bluetooth adapter scanning on Android, and automatically restart each 3000ms.

(4) the acquisition of the connected Bluetooth device on the IOS side is empty, and it is automatically re-acquired per 3000ms.

(5) after the Android Bluetooth starts the link, the scan is interrupted, the connection fails, and the scan starts again.

(6) after the IOS starts to connect the device, it stops obtaining the connected device, and automatically restarts the acquisition when the connection fails.

(7) after the connection is successful, turn off the Bluetooth of the system and reset the Bluetooth adapter.

(8) after the connection is successful, turn off the Bluetooth of the system, turn on the 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 Mini Program (the connection is uninterrupted) and open Mini Program to show that it is connected.

(11) after the connection is successful, kill the Mini Program process, close the connection, and automatically restart scanning (acquisition).

3. Update it when you remember it.

4. Flow chart, tomorrow or the day after tomorrow or. Anyone who is free can draw it for me.

My connection is made in App.js.

The onLaunch trigger in App.js is a call to 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 can write only one.

2. CharacterId_write is the eigenvalue of the data written by the Bluetooth device I want to connect to.

3. CharacterId_read is the eigenvalue of data read by the Bluetooth device I know I want to connect to.

(the above three are all for comparison. The actual operation is based on the obtained sericeid and characterid.)

4. ConnectedDevice is a connected device information object.

Call connection startConnect () after the init is completed

StartConnect Code:

StartConnect: function () {var that = this; if (that.connectedDevice.state) return; that.connectedDevice.deviceId = ""; that.connectedDevice.state = false; / / if the adapter is no longer initialized (repeated initialization will cause an error) if (this.adapterHasInit = = undefined | | this.adapterHasInit) return; wx.showLoading ({title: 'initialize Bluetooth', duration: 2000}) / / enable Bluetooth adapter status monitoring this.listenAdapterStateChange (); / / initialize Bluetooth adapter status (step is required, otherwise no subsequent operation can be performed) wx.openBluetoothAdapter ({success: function (res) {console.log ("initialize Bluetooth adapter successfully"); that.getBluetoothAdapterState (); that.adapterHasInit = true;}, fail: function (err) {console.log (err) Wx.showLoading ({title: 'please turn on Bluetooth', icon: 'loading', duration: 2000})});}

Explanation: if there are notes in this paragraph, I won't say much about it. It's relatively simple.

The getBluetoothAdapterState () method is called after the Bluetooth adapter state is initialized successfully.

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: 'please turn on Bluetooth', 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.

Call the judegIfDiscovering method when Bluetooth is detected to be available.

JudegIfDiscovering Code:

JudegIfDiscovering: function (discovering) {var that = this; if (this.isConnectinng) return; wx.getConnectedBluetoothDevices ({services: [that.serviceId], success: function (res) {console.log ("get connected device", res); var devices = res ['devices'] If (devices [0]) {if (that.isAndroidPlatform) {wx.showToast ({title: 'Bluetooth connection succeeded', icon: 'success', duration: 2000});} else {that.getConnectedBluetoothDevices }} else {if (discovering) {wx.showLoading ({title: 'Bluetooth searching'})} else {if (that.isAndroidPlatform) {that.startBluetoothDevicesDiscovery ();} else {that.getConnectedBluetoothDevices (267);}, fail: function (err) {console.log ('getConnectedBluetoothDevices err 264searching, err) If (that.isAndroidPlatform) {that.startBluetoothDevicesDiscovery ();} else {that.getConnectedBluetoothDevices (277);}});}

Description:

1. This method is used to determine whether it is being scanned.

2. Whether the isAndroidPlatform is an Android device or an IOS device is determined by Mini Program's getSystemInfo.

If it is an Android device calling startBluetoothDevicesDiscovery () to start scanning, if it is an IOS device calling getConnectedBluetoothDevices () to turn on getting the paired Bluetooth device.

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: 'please turn on Bluetooth', icon: 'loading', duration: 2000})} else {if (res.discovering) {wx.showLoading ({title:' Bluetooth searching'})} else {wx.startBluetoothDevicesDiscovery ({services: [], allowDuplicatesKey: true Success: function (res) {that.onBluetoothDeviceFound () Wx.showLoading ({title: 'searching with Bluetooth'})} Fail: function (err) {if (err.isDiscovering) {wx.showLoading ({title: 'searching with Bluetooth'})} else {that.startDiscoveryTimer = setTimeout (function () {if (! that.connectedDevice.state) {that.startBluetoothDevicesDiscovery () }, 5000)});}}, fail: function (err) {console.log (err);}})}

Description:

1. Turn on the scanning nearby Bluetooth device only on the Android device.

2. Enable event listener onBluetoothDeviceFound () for discovering new Bluetooth devices in the callback that is enabled successfully.

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 according to the name attribute.

2. When the device that contains the name attribute of the device to be connected is obtained to the deviceId, 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: 'connecting'}); that.stopBluetoothDevicesDiscovery (); wx.createBLEConnection ({deviceId: that.deviceId, success: function (res) {console.log ('connected successfully', res) Wx.showLoading ({title: 'connecting'}); 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 ('connection change', res); that.connectedDevice.state = res.connected That.connectedDevice.deviceId = res.deviceId; if (! res.connected) {that.init ('200');}}, fail: function (err) {console.log (' connection failure:', 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. The method of terminating scanning (obtaining paired data) after opening the connection.

2. Create a low-power Bluetooth connection according to deviceId. If the connection is successful, continue to do 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: 'Bluetooth searching'}); wx.getConnectedBluetoothDevices ({services: [that.serviceId], success: function (res) {console.log ("get connected device", res); var devices = res ['devices'], flag = false, index = 0, conDevList = [] Devices.forEach (function (value, index, array) {if (value ['name'] .indexOf (' FeiZhi')! =-1) {/ / if there is a device containing the FeiZhi field 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;}});}

Description: if you fail to get a Bluetooth paired Bluetooth device, or get a list of air conditioning 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: 'please turn on Bluetooth', icon: 'loading', duration: 2000})} else {if (! that.connectedDevice [' state']) {that.getConnectedBluetoothDevices ();}}, fail: function (err) {console.log (err);}}), 5000);}

Description:

1. The devices returned after a successful call to this method is an array containing multiple Bluetooth devices that have been paired by the system.

2. If the devices list is obtained, the loopConnect () method is called to start the recursive call to connect 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 (' paired device Mini Program Bluetooth connection failed'); if (! that.isAndroidPlatform) {that.getConnectedBluetoothDevices;}

Description: looConnect will delete the first value of the array after the connection failure of the method to create the connection, and then continue to call the method until all the devices in it are connected.

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

Special note:

1. Bluetooth connections for Android and IOS are recommended in different ways in the current version. Android devices use Mini Program's Bluetooth connection directly, unpairing the system. The IOS device can be successfully connected in a second after opening Mini Program.

2. This version of the connection still needs to be improved. The connection will not be terminated automatically (you can add what you need). It will scan indefinitely and reconnect until it is successful.

3. If you need to write data and enable notify at the same time after a successful link, it is recommended to write first and then enable notify. The reason is unknown, otherwise a 10008 error is bound to occur.

This is the end of the introduction to "how WeChat Mini Programs uses Bluetooth links". Thank you for reading. If you want to know more about the industry, you can follow the industry information channel. The editor will update different knowledge points for you every day.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report