Home >WeChat Applet >Mini Program Development >WeChat Mini Program Bluetooth Link Example Tutorial
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 what I know I want to connect to You can write only one serviceId for the Bluetooth device.
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 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 }) } }); }Description: This There are comments in the paragraph, so I won’t go into details, it’s relatively simple. 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.
judegIfDiscoveringCode:
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:
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 nearby scanning only on Android devices Bluetooth device. 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:
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:
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() 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; } }); }Description: If the acquisition of Bluetooth paired Bluetooth devices fails, or the obtained list is empty, use 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); }Instructions:
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); } } }
说明:looConnect在创建连接的方法连接失败后会操作删除数组的第一个值,然后继续调用该方法,直到其中所有的设备都连接过。
差点漏了:在app.js的onShow里调用init()方法。
特别说明:
1、安卓和IOS的蓝牙连接在当前版本中推荐采用不同方式。安卓设备直接使用小程序的蓝牙连接,取消系统配对。IOS设备先系统配对在打开小程序可以时效秒连接成功。
2、此版本的连接仍然有待完善,连接不会自动终止(需要的可以自己加),会无限扫描重连,直到成功。
3、链接成功后的操作如果写入数据和开启notify需要同时进行,建议先写入,后开启notify。(原因未知,否则必然出现10008错误)。
相关推荐:
The above is the detailed content of WeChat Mini Program Bluetooth Link Example Tutorial. For more information, please follow other related articles on the PHP Chinese website!