WeChat applet implements code for Bluetooth link
This article mainly introduces to you the relevant information about the Bluetooth link of the WeChat applet. I hope that through this article you can master the development method of the Bluetooth applet. Friends who need it can refer to it. I hope it can help everyone.
WeChat Mini Program Bluetooth Link
WeChat Mini Program Bluetooth Connection 2.0 Description:
1. This version distinguishes between ANDROID and Different ways of Bluetooth connection under IOS system.
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(); }
Description:
1. serviceId_2~6 is the serviceId of the Bluetooth device I know I want to connect to. I can only write one.
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 the 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 }) } }); }
Note: There are comments in this paragraph, so I won’t say more. ,easier.
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); } }) }
Description: This method is used to obtain the current Bluetooth status.
The judegIfDiscovering method is called when it is detected that Bluetooth is available.
judegIfDiscovering Code:
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); } } }); }
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 obtaining 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); } }) }
Instructions:
1. Enable scanning for nearby Bluetooth devices only on Android 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(); } } } }) }
Description:
1. Here, 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; } }); }
Description:
1. Terminate scanning (get paired) method after opening the connection.
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() respectively 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; } }); }
Instructions: If the Bluetooth is paired The Bluetooth device failed, or the list obtained is empty. Call 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); }
Description:
1. The devices returned after the method is successfully called is an array containing multiple Bluetooth devices that have been paired by 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); } } }
Description: looConnect will delete the first value of the array after the method of creating the connection fails, and then continue to call the method until All devices are 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 within 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 it will scan and reconnect infinitely until it succeeds.
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).
Related recommendations:
Example sharing of how WeChat applet implements Bluetooth
The above is the detailed content of WeChat applet implements code for Bluetooth link. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Magnet link is a link method for downloading resources, which is more convenient and efficient than traditional download methods. Magnet links allow you to download resources in a peer-to-peer manner without relying on an intermediary server. This article will introduce how to use magnet links and what to pay attention to. 1. What is a magnet link? A magnet link is a download method based on the P2P (Peer-to-Peer) protocol. Through magnet links, users can directly connect to the publisher of the resource to complete resource sharing and downloading. Compared with traditional downloading methods, magnetic

Recently, many users have been asking the editor, how to download links starting with 115://? If you want to download links starting with 115://, you need to use the 115 browser. After you download the 115 browser, let's take a look at the download tutorial compiled by the editor below. Introduction to how to download links starting with 115:// 1. Log in to 115.com, download and install the 115 browser. 2. Enter: chrome://extensions/ in the 115 browser address bar, enter the extension center, search for Tampermonkey, and install the corresponding plug-in. 3. Enter in the address bar of 115 browser: Grease Monkey Script: https://greasyfork.org/en/

Some users encountered errors when installing the device, prompting error code 28. In fact, this is mainly due to the driver. We only need to solve the problem of win7 driver code 28. Let’s take a look at what should be done. Do it. What to do with win7 driver code 28: First, we need to click on the start menu in the lower left corner of the screen. Then, find and click the "Control Panel" option in the pop-up menu. This option is usually located at or near the bottom of the menu. After clicking, the system will automatically open the control panel interface. In the control panel, we can perform various system settings and management operations. This is the first step in the nostalgia cleaning level, I hope it helps. Then we need to proceed and enter the system and

As part of the WeChat ecosystem, WeChat video accounts have gradually become an important promotion tool for content creators and merchants. Getting links to video accounts on this platform is crucial for sharing and disseminating content. The following will introduce in detail how to obtain the WeChat video account link and how to add product links to the video account to improve the dissemination effect of the content. 1. How to get the WeChat video account link? After posting a video on your WeChat video account, the system will automatically create a video link. Authors can copy the link after publishing to facilitate sharing and dissemination. After logging in to your WeChat video account, you can browse the homepage of your video account. On the home page, each video is accompanied by a corresponding link so you can copy or share it directly. 3. Search video account: Enter the video account name in the WeChat search box

What to do with blue screen code 0x0000001? The blue screen error is a warning mechanism when there is a problem with the computer system or hardware. Code 0x0000001 usually indicates a hardware or driver failure. When users suddenly encounter a blue screen error while using their computer, they may feel panicked and at a loss. Fortunately, most blue screen errors can be troubleshooted and dealt with with a few simple steps. This article will introduce readers to some methods to solve the blue screen error code 0x0000001. First, when encountering a blue screen error, we can try to restart

With the popularity of short video platforms, more and more creators are beginning to use video accounts to create and promote content. Video accounts can not only showcase personal talents, but also realize commercial monetization through product links. However, to add a link to a video account, certain conditions must be met. 1. What are the requirements for a video link? Video account authentication is a prerequisite for adding links to your video account. Currently, major short video platforms such as Douyin and Kuaishou provide certification services, which mainly include two types: personal certification and institutional certification. Personal certification requires the submission of real identity information, while institutional certification requires the provision of certification materials from relevant companies or organizations. After completing the authentication, users can add links to their video accounts to enhance the credibility and authority of their accounts. One of the video link

The win10 system is a very excellent high-intelligence system. Its powerful intelligence can bring the best user experience to users. Under normal circumstances, users’ win10 system computers will not have any problems! However, it is inevitable that various faults will occur in excellent computers. Recently, friends have been reporting that their win10 systems have encountered frequent blue screens! Today, the editor will bring you solutions to different codes that cause frequent blue screens in Windows 10 computers. Let’s take a look. Solutions to frequent computer blue screens with different codes each time: causes of various fault codes and solution suggestions 1. Cause of 0×000000116 fault: It should be that the graphics card driver is incompatible. Solution: It is recommended to replace the original manufacturer's driver. 2,

If you need to program any device remotely, this article will help you. We will share the top GE universal remote codes for programming any device. What is a GE remote control? GEUniversalRemote is a remote control that can be used to control multiple devices such as smart TVs, LG, Vizio, Sony, Blu-ray, DVD, DVR, Roku, AppleTV, streaming media players and more. GEUniversal remote controls come in various models with different features and functions. GEUniversalRemote can control up to four devices. Top Universal Remote Codes to Program on Any Device GE remotes come with a set of codes that allow them to work with different devices. you may
