Development 1.0 flowchart of small program Bluetooth connection

General process:
* 1. Turn on Bluetooth adaptation
* 2. Obtain the status of the Bluetooth adapter and determine whether the device’s Bluetooth is available.
* 3. When it is judged that the Bluetooth adapter is available, turn on scanning for Bluetooth devices and turn on to obtain connected Bluetooth devices
* 4. If the scanning for Bluetooth devices fails to scan for 5 seconds, then automatically turn on scanning again
* 5. Turn on scanning for Bluetooth After the device is successful, turn on and monitor the scanned device
* 6. If the new device that has been scanned contains a device with the FeiZhi name (required for personal products), then start to connect to the device
* 7. Turn on and get connected Bluetooth devices to turn on After the device is successfully obtained, it is judged that the obtained device name contains the FeiZhi (personal product required) string, and the device starts to connect to the device.
* 8. Start to obtain the connected Bluetooth device. It is not successful to obtain the connected Bluetooth device after 5 seconds. Reopen acquisition.
* 9. When starting to connect to a device, stop scanning for devices and stop looping to obtain connected devices.
* 10. After the connection is successful, stop scanning for devices and stop looping to obtain connected devices

share picture

hint

1, call to open the connection in the onLaunch() method of app.js this.startConnect(); A prompt box will pop up to turn on the adaptation. If it fails, it will prompt that the device’s Bluetooth is unavailable. At the same time, turn on the Bluetooth adapter status monitoring.

 

startConnect: function () {

var that = this;

wx.showLoading({

title: ‘开启蓝牙适配’

});

wx.openBluetoothAdapter({

success: function (res) {

console.log(“初始化蓝牙适配器”);

console.log(res);

that.getBluetoothAdapterState();

},

fail: function (err ) {

console.log(err);

wx.showToast({

title: ‘蓝牙初始化失败’,

icon: ‘success ‘,

duration: 2000

})

setTimeout(function () {

wx.hideToast()

}, 2000)

}

});

wx.onBluetoothAdapterStateChange(function (res) {

var available = res.available;
< br> if (available) {

that.getBluetoothAdapterState();

}

})

}
2、初始化蓝牙适配器成功, Call this.getBluetoothAdapterState() to get the status of the native Bluetooth adapter and determine whether it is available. If available is false, it is because the user has not turned on the system Bluetooth. At the same time, it is judged that the program has not started searching for Bluetooth devices, call this.startBluetoothDevicesDiscovery(); to start scanning for nearby Bluetooth devices, and at the same time call this.getConnectedBluetoothDevices() to start obtaining the paired Bluetooth devices of this machine.

getBluetoothAdapterState: function () {

var that = this;

wx.getBluetoothAdapterState({

success: function (res) {

var available = res.available,

discovering = res.discovering;

if (!available) {

wx.showToast({
< br> title: ‘设备无法开启蓝牙连接’,

icon: ‘success’,

duration: 2000

})

setTimeout(function () {

wx.hideToast()

}, 2000)

} else {

if (!discovering) {

that.startBluetoothDevicesDiscovery();

that.getConnectedBluetoothDevices();

}

}

}

})

}
3. Start searching for Bluetooth devices startBluetoothDevicesDiscovery(), prompting Bluetooth search.

startBluetoothDevicesDiscovery: function () {

var that = this;

wx.showLoading({

title: ‘蓝牙搜索’

});

wx.startBluetoothDevicesDiscovery({

services: [],

allowDuplicatesKey: false,

success: function (res) {

if (!res.isDiscovering) {

that.getBluetoothAdapterState();

} else {

that.onBluetoothDeviceFound();

}

},

fail: function (err) {

console.log(err);

}
< br> });

}
4、获取已配对的蓝牙设备。 This method specifically indicates that the parameter services (Array) is required, but in the official examples and various cheating demos, I have never seen anyone fill it out, but this method cannot get any paired devices without filling in this attribute. If you want to call this method, you need to connect to a specific device and know the serviceId of a main service of the device. If you don’t know, you can manually connect to the device you want to connect to, then get the service list, and record at least one value of the attribute primary as true.

getConnectedBluetoothDevices: function () {

var that = this;

wx.getConnectedBluetoothDevices({

services: [that.serviceId],< br>
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’];

return;

}

});

if (flag) {

this.connectDeviceIndex = 0;

that.loopConnect(conDevList);

} else {< br>
if (!this.getConnectedTimer) {

that.getConnectedTimer = setTimeout(function () {

that.getConnectedBluetoothDevices();

}, 5000 );

}

}

},

fail: function (err) {

if (!this.getC onnectedTimer) {

that.getConnectedTimer = setTimeout(function () {

that.getConnectedBluetoothDevices();

}, 5000);

}< br>
}

});

}
5、开启蓝牙搜索功能失败,则回到第2步重新检查蓝牙是适配器是否可用,开启蓝牙搜索After the function is successful, turn on the event monitoring of nearby Bluetooth devices found. this.onBluetoothDeviceFound()

onBluetoothDeviceFound: function () {

var that = this;

console.log(‘onBluetoothDeviceFound’);

wx.onBluetoothDeviceFound(function (res) {

console.log(‘new device list has founded’)

console.log(res);

if (res. devices[0]) {

var name = res.devices[0][‘name’];

if (name != ”) {

if ( name.indexOf(‘FeiZhi’) != -1) {

var deviceId = res.devices[0][‘deviceId’];

that.deviceId = deviceId;

console.log(that.deviceId);

that.startConnectDevices();

}

}

}

})

}
此方法可自定义过滤一些无效的蓝牙设备比如name为空的,个人产品开发中需要过滤devices name 不含有FeiZhi字符串的设备。

6. In step 5, if you find a device you want to pair with, get the deviceId of the device, and then start pairing the device this.startConnectDevices().

startConnectDevices: function (ltype, array) {

var that = this;

clearTimeout(that.getConnectedTimer);

that.getConnectedTimer = null;

clearTimeout(that.discoveryDevicesTimer);

that.stopBluetoothDevicesDiscovery();

this.isConnectting = true;

wx.createBLEConnection({

deviceId: that.deviceId,

success: function (res) {

if (res.errCode == 0) {

setTimeout(function () {

that.getService(that.deviceId);

}, 5000)

}

},

fail : function (err) {

console.log(‘连接失败:’, err);

if (ltype == ‘loop’) {

that.connectDeviceIndex += 1;

that.loopConnect(array);

} else {

that.startBluetoothDevicesDiscovery();

that.getConnectedBluetoothDevices();

}

},

complete: function () {

console.log(‘complete connect devices’);

this.isConnectting = false;

}

});

}

开启连接后为了避免出现冲突,一旦开启连接则终止扫描附近蓝牙设备,终止读取本机已配对设备。

#####7、连接成功后根据deiviceId获取设备的所有服务。 this.getService(deviceId);

getService: function (deviceId) {

var that = this;

// 监听蓝牙连接

wx. onBLEConnectionStateChange(function (res) {

console.log(res);

});

// 获取蓝牙设备service值

wx. getBLEDeviceServices({

deviceId: deviceId,

success: function (res) {

that.getCharacter(deviceId, res.services);

}

})

}
8、读取服务的特征值。

getCharacter: function (deviceId, services) {

var that = this;

services.forEach(function (value, index, array) {
< br> if (value == that.serviceId) {

that.serviceId = array[index];

}

});

wx .getBLEDeviceCharacteristics({

deviceId: deviceId,

serviceId: that.serviceId,

success: function (res) {

that.writeBLECharacteristicValue(deviceId , that.serviceId, that.characterId_write);

that.openNotifyService(deviceId, that.serviceId, that.characterId_read);

},

fail: function (err ) {

console.log(err);

},

complete: function () {

console.log(‘complete’);

}

})

}
9、如果扫描到的设备中没有想要连接的设备,可以尝试使用系统蓝牙手动配对,然后再In the applet, call getConnectedBluetoothDevices() to obtain the paired Bluetooth devices of this machine, and then filter the devices (may obtain multiple paired Bluetooth devices). Put the acquired deviceId of the Bluetooth device into an array and call the custom method this.loopConnect(); Idea: Get the deviceId of the paired Bluetooth device through recursive calls, and connect if it is obtained. DevicesId[x] is empty. All the paired devices obtained when calling getConnectedBluetoothDevices() failed to connect. Turn on to reacquire paired Bluetooth devices, and turn on scanning for nearby Bluetooth devices.

loopConnect: function (devicesId) {

var that = this;

var listLen = devicesId.length;

if (devicesId[this. connectDeviceIndex]) {

this.deviceId = devicesId[this.connectDeviceIndex];

this.startConnectDevices(‘loop’, devicesId);

} else {

console.log(‘已配对的设备小程序蓝牙连接失败’);

that.startBluetoothDevicesDiscovery();

that.getConnectedBluetoothDevices();

}

}
10、**startConnectDevices(‘loop’, array)方法,是当获取已配对蓝牙设备进行连接时这样调用。 The processing logic has been posted above, which means that after the connection fails, a global variable is accumulated in the fail method, and then the loopConnect(array) method is called back.

**11. Manual connection. The method described above is for direct and automatic connection. If automatic connection is not required, you can use the method getBluetoothDevices() to get a list of scanned Bluetooth devices , You can make a page to display the device name, click on the device to start the connection.

Note:

1. that.serviceId is set during initialization. Since the serviceId and various characteristic values ​​of the main service that need to be connected to the device are known, this can be done Do. If unknowable, you can do a scanning method to check the purpose of the characteristic value yourself.

2. The writeBLECharacteristicValue and openNotifyService operations after a successful connection need to be paid attention to. If both operations are enabled at the same time, you must first call wirte and then enable notify (the reason is unknown, personal experience).

3. After someone reminds you, you can also improve it. OnBlueToothAdapterStateChange()** can monitor the status of the Bluetooth adapter to determine that the user has turned on the device Bluetooth during or after the connection. If it is judged that the Bluetooth is turned off Prompt, please turn it on. If the monitor is turned on, go back to step 1.

Leave a Comment

Your email address will not be published.