Bluetooth APIs are supported in mPaaS 1.60.0 and later versions.
Currently, debugging on developer tools is not supported. You need to use a physical device to properly call the Bluetooth API of Mini Program.
my.openBluetoothAdapter
This interface is used to initialize the Bluetooth module in the mini program, with the effective period beginning when my.openBluetoothAdapter
is called and ending when my.closeBluetoothAdapter
is called or the mini program is destroyed. During the effective period of the Bluetooth adapter module, developers can call the following APIs, and receive the on
event callback related to the Bluetooth module.
Input parameters
Parameter | Type | Required | Description |
---|---|---|---|
autoClose | Boolean | No | Indicates whether to automatically disconnect Bluetooth when you leave the current page. The default value is true. Note, only Android is supported. |
success | Function | No | The callback function that indicates a successful call. |
fail | Function | No | The callback function that indicates a failed call. |
complete | Function | No | The callback function that indicates the call is completed (this will be executed regardless of whether the call succeeds or fails). |
Return value on success
Parameter | Type | Description |
---|---|---|
isSupportBLE | Boolean | Indicates whether BLE is supported. |
Error codes
Error | Description | Solution |
---|---|---|
12 | Bluetooth is not turned on. | Try again to turn on Bluetooth. |
13 | The connection to the system service is temporarily lost. | Try again to reconnect. |
14 | The client does not have the permission to use Bluetooth. | Authorize app to use Bluetooth. |
15 | Unknown error | - |
Code sample
<!-- .axml-->
<view class="page">
<view class="page-description">Bluetooth API</view>
<view class="page-section">
<view class="page-section-title">Bluetooth state</view>
<view class="page-section-demo">
<button type="primary" onTap="openBluetoothAdapter">Initialize Bluetooth</button>
<button type="primary" onTap="closeBluetoothAdapter">Close Bluetooth</button>
<button type="primary" onTap="getBluetoothAdapterState">Obtain Bluetooth state</button>
</view>
<view class="page-section-title">Scan the Bluetooth device</view>
<view class="page-section-demo">
<button type="primary" onTap="startBluetoothDevicesDiscovery">Start searching</button>
<button type="primary" onTap="getBluetoothDevices">All devices found</button>
<button type="primary" onTap="getConnectedBluetoothDevices">All connected devices/button>
<button type="primary" onTap="stopBluetoothDevicesDiscovery">Stop searching</button>
</view>
<view class="page-section-title">Connect the device</view>
<view class="page-section-demo">
<input class="input" onInput="bindKeyInput" type="{{text}}" placeholder=" Input the ID of the device to be connected"></input>
<button type="primary" onTap="connectBLEDevice">Connect the device</button>
<button type="primary" onTap="getBLEDeviceServices"> Obtain device services </button>
<button type="primary" onTap="getBLEDeviceCharacteristics"> Obtain read and write characteristics </button>
<button type="primary" onTap="disconnectBLEDevice"> Disconnect the device </button>
</view>
<view class="page-section-title">Read and write data</view>
<view class="page-section-demo">
<button type="primary" onTap="notifyBLECharacteristicValueChange">Listen to the characteristic data change</button>
<button type="primary" onTap="readBLECharacteristicValue">Read data</button>
<button type="primary" onTap="writeBLECharacteristicValue">Write data</button>
<button type="primary" onTap="offBLECharacteristicValueChange">Cancel listening to characteristic value</button>
</view>
<view class="page-section-title">Other events</view>
<view class="page-section-demo">
<button type="primary" onTap="bluetoothAdapterStateChange">Bluetooth status change</button>
<button type="primary" onTap="offBluetoothAdapterStateChange">Cancel listening to Bluetooth status</button>
<button type="primary" onTap="BLEConnectionStateChanged">Bluetooth connection status changes</button>
<button type="primary" onTap="offBLEConnectionStateChanged">Cancel listening to Bluetooth connection status</button>
</view>
</view>
</view>
// .js
Page({
data: {
devid: '0D9C82AD-1CC0-414D-9526-119E08D28124',
serid: 'FEE7',
notifyId: '36F6',
writeId: '36F5',
charid: '',
alldev: [{ deviceId: '' }],
},
//Obtain the Bluetooth state
openBluetoothAdapter() {
my.openBluetoothAdapter({
success: res => {
if (!res.isSupportBLE) {
my.alert({ content: 'Sorry, your mobile Bluetooth is unavailable temporarily' });
return;
}
my.alert({ content: 'Initialization succeeded!' });
},
fail: error => {
my.alert({ content: JSON.stringify(error) });
},
});
},
closeBluetoothAdapter() {
my.closeBluetoothAdapter({
success: () => {
my.alert({ content: 'Bluetooth closed!' });
},
fail: error => {
my.alert({ content: JSON.stringify(error) });
},
});
},
getBluetoothAdapterState() {
my.getBluetoothAdapterState({
success: res => {
if (!res.available) {
my.alert({ content: 'Sorry, your mobile Bluetooth is unavailable temporarily' });
return;
}
my.alert({ content: JSON.stringify(res) });
},
fail: error => {
my.alert({ content: JSON.stringify(error) });
},
});
},
//Scan the Bluetooth device
startBluetoothDevicesDiscovery() {
my.startBluetoothDevicesDiscovery({
allowDuplicatesKey: false,
success: () => {
my.onBluetoothDeviceFound({
success: res => {
// my.alert({content:'Listen to new device '+JSON.stringify(res)});
var deviceArray = res.devices;
for (var i = deviceArray.length - 1; i >= 0; i--) {
var deviceObj = deviceArray[i];
//Match the target device by device name or broadcast data, and then record the device ID for later use
if (deviceObj.name == this.data.name) {
my.alert({ content: 'Target device is found' });
my.offBluetoothDeviceFound();
this.setData({
deviceId: deviceObj.deviceId,
});
break;
}
}
},
fail: error => {
my.alert({ content: 'Failed to listen to new device' + JSON.stringify(error) });
},
});
},
fail: error => {
my.alert({ content: 'Failed to start scanning' + JSON.stringify(error) });
},
});
},
//Stop scanning
stopBluetoothDevicesDiscovery() {
my.stopBluetoothDevicesDiscovery({
success: res => {
my.offBluetoothDeviceFound();
my.alert({ content: 'Succeeded!' });
},
fail: error => {
my.alert({ content: JSON.stringify(error) });
},
});
},
//Obtain the connected device
getConnectedBluetoothDevices() {
my.getConnectedBluetoothDevices({
success: res => {
if (res.devices.length === 0) {
my.alert({ content: 'No connected devices!' });
return;
}
my.alert({ content: JSON.stringify(res) });
devid = res.devices[0].deviceId;
},
fail: error => {
my.alert({ content: JSON.stringify(error) });
},
});
},
//Obtain all devices found
getBluetoothDevices() {
my.getBluetoothDevices({
success: res => {
my.alert({ content: JSON.stringify(res) });
},
fail: error => {
my.alert({ content: JSON.stringify(error) });
},
});
},
bindKeyInput(e) {
this.setData({
devid: e.detail.value,
});
},
//Connect the device
connectBLEDevice() {
my.connectBLEDevice({
deviceId: this.data.devid,
success: res => {
my.alert({ content: 'Connected successfully' });
},
fail: error => {
my.alert({ content: JSON.stringify(error) });
},
});
},
//Disconnect
disconnectBLEDevice() {
my.disconnectBLEDevice({
deviceId: this.data.devid,
success: () => {
my.alert({ content: ‘Disconnected successfully!' });
},
fail: error => {
my.alert({ content: JSON.stringify(error) });
},
});
},
//Obtain the services of the connected devices. The services can only be obtained when the devices are connected.
getBLEDeviceServices() {
my.getConnectedBluetoothDevices({
success: res => {
if (res.devices.length === 0) {
my.alert({ content: 'No connected devices' });
return;
}
my.getBLEDeviceServices({
deviceId: this.data.devid,
success: res => {
my.alert({ content: JSON.stringify(res) });
this.setData({
serid: res.services[0].serviceId,
});
},
fail: error => {
my.alert({ content: JSON.stringify(error) });
},
});
},
});
},
//Obtain the charid of the connected devices. The charid can only be obtained when the devices are connected. The read and write characteristics are respectively screened out.
getBLEDeviceCharacteristics() {
my.getConnectedBluetoothDevices({
success: res => {
if (res.devices.length === 0) {
my.alert({ content: 'No connected devices' });
return;
}
this.setData({
devid: res.devices[0].deviceId,
});
my.getBLEDeviceCharacteristics({
deviceId: this.data.devid,
serviceId: this.data.serid,
success: res => {
my.alert({ content: JSON.stringify(res) });
//See the related document for more information about the attributes of the characteristics. Match the read/write characteristics by attribute and record the value for later use.
this.setData({
charid: res.characteristics[0].characteristicId,
});
},
fail: error => {
my.alert({ content: JSON.stringify(error) });
},
});
},
});
},
//Read and write data
readBLECharacteristicValue() {
my.getConnectedBluetoothDevices({
success: res => {
if (res.devices.length === 0) {
my.alert({ content: 'No connected devices' });
return;
}
this.setData({
devid: res.devices[0].deviceId,
});
my.readBLECharacteristicValue({
deviceId: this.data.devid,
serviceId: this.data.serid,
characteristicId: this.data.notifyId,
//1. Android read and write services
// serviceId:'0000180d-0000-1000-8000-00805f9b34fb',
// characteristicId:'00002a38-0000-1000-8000-00805f9b34fb',
success: res => {
my.alert({ content: JSON.stringify(res) });
},
fail: error => {
my.alert({ content: 'Failed to read and write' + JSON.stringify(error) });
},
});
},
});
},
writeBLECharacteristicValue() {
my.getConnectedBluetoothDevices({
success: res => {
if (res.devices.length === 0) {
my.alert({ content: 'No connected devices' });
return;
}
this.setData({
devid: res.devices[0].deviceId,
});
my.writeBLECharacteristicValue({
deviceId: this.data.devid,
serviceId: this.data.serid,
characteristicId: this.data.charid,
//Android write service
//serviceId:'0000180d-0000-1000-8000-00805f9b34fb',
//characteristicId:'00002a39-0000-1000-8000-00805f9b34fb',
value: 'ABCD',
success: res => {
my.alert({ content: 'Data written successfully!' });
},
fail: error => {
my.alert({ content: JSON.stringify(error) });
},
});
},
});
},
notifyBLECharacteristicValueChange() {
my.getConnectedBluetoothDevices({
success: res => {
if (res.devices.length === 0) {
my.alert({ content: 'No connected devices' });
return;
}
this.setData({
devid: res.devices[0].deviceId,
});
my.notifyBLECharacteristicValueChange({
state: true,
deviceId: this.data.devid,
serviceId: this.data.serid,
characteristicId: this.data.notifyId,
success: () => {
//Listen to characteristic change events
my.onBLECharacteristicValueChange({
success: res => {
// my.alert({content: 'Characteristic change:'+JSON.stringify(res)});
my.alert({ content: 'Obtain the response data = ' + res.value });
},
});
my.alert({ content: 'Listened successfully' });
},
fail: error => {
my.alert({ content: 'Failed to listen' + JSON.stringify(error) });
},
});
},
});
},
offBLECharacteristicValueChange() {
my.offBLECharacteristicValueChange();
},
//Other events
bluetoothAdapterStateChange() {
my.onBluetoothAdapterStateChange(this.getBind('onBluetoothAdapterStateChange'));
},
onBluetoothAdapterStateChange() {
if (res.error) {
my.alert({ content: JSON.stringify(error) });
} else {
my.alert({ content: 'Bluetooth status change: ' + JSON.stringify(res) });
}
},
offBluetoothAdapterStateChange() {
my.offBluetoothAdapterStateChange(this.getBind('onBluetoothAdapterStateChange'));
},
getBind(name) {
if (!this[`bind${name}`]) {
this[`bind${name}`] = this[name].bind(this);
}
return this[`bind${name}`];
},
BLEConnectionStateChanged() {
my.onBLEConnectionStateChanged(this.getBind('onBLEConnectionStateChanged'));
},
onBLEConnectionStateChanged(res) {
if (res.error) {
my.alert({ content: JSON.stringify(error) });
} else {
my.alert({ content: 'Connection status change: ' + JSON.stringify(res) });
}
},
offBLEConnectionStateChanged() {
my.offBLEConnectionStateChanged(this.getBind('onBLEConnectionStateChanged'));
},
onUnload() {
this.offBLEConnectionStateChanged();
this.offBLECharacteristicValueChange();
this.offBluetoothAdapterStateChange();
this.closeBluetoothAdapter();
},
});
Instructions
If you call other APIs in the Bluetooth module before calling the API
my.openBluetoothAdapter
, an error will be returned:Error Code: 10000
Error description: The Bluetooth adapter is not initialized.
Solution: Call the API
my.openBluetoothAdapter
.
When users do not switch on the Bluetooth or the Bluetooth function is not supported on the user’s mobile phone, an error is returned after
my.openBluetoothAdapter
is called. For more information about error codes, see the Bluetooth API error codes. After the Bluetooth module is initialized, you can use the APImy.onBluetoothAdapterStateChange
to monitor changes of the Bluetooth status.
my.closeBluetoothAdapter
This interface is used to close the Bluetooth module in the mini program.
Input parameters
Parameter | Type | Required | Description |
---|---|---|---|
success | Function | No | The callback function that indicates a successful call. |
fail | Function | No | The callback function that indicates a failed call. |
complete | Function | No | The callback function that indicates the call is completed (this will be executed regardless of whether the call succeeds or fails). |
Code sample
my.closeBluetoothAdapter({
success: (res) => {
},
fail:(res) => {
},
complete: (res)=>{
}
});
Instructions
Calling this method will disconnect all established Bluetooth connections and release system resources.
We recommend that you call this API in pair with
my.openBluetoothAdapter
when ending the Bluetooth process of the Mini Program.Calling
my.closeBluetoothAdapter
to free resources is an asynchronous operation. We do not recommend that you usemy.closeBluetoothAdapter
andmy.openBluetoothAdapter
to handle exception, because it is equivalent to turning Bluetooth off, and then turning on and reinitializing it. The whole process is inefficient and prone to thread synchronization problems.
my.getBluetoothAdapterState
Obtains the status of the Bluetooth module in the mini program.
Input parameters
Parameter | Type | Required | Description |
---|---|---|---|
success | Function | No | The callback function that indicates a successful call. |
fail | Function | No | The callback function that indicates a failed call. |
complete | Function | No | The callback function that indicates the call is completed (this will be executed regardless of whether the call succeeds or fails). |
Return value on success
Parameter | Type | Description |
---|---|---|
discovering | Boolean | Indicates whether the device is searching for matching devices. |
available | Boolean | Indicates whether the Bluetooth module is available (BLE is supported and Bluetooth is on). |
Code sample
my.getBluetoothAdapterState({
success: (res) => {
console.log(res)
},
fail:(res) => {
},
complete: (res)=>{
}
});
my.startBluetoothDevicesDiscovery
You can call this interface to start searching for nearby Bluetooth devices. The search results are returned in the my.onBluetoothDeviceFound
event.
Input parameters
Parameter | Type | Required | Description |
---|---|---|---|
services | Array | No | The UUID list of the Bluetooth device’s master service. |
allowDuplicatesKey | Boolean | No | Whether to report the same device repeatedly. If yes, the |
interval | Integer | No | Specifies the interval for reporting devices. Default value is 0, that is, when a new device is found, it is reported immediately. Otherwise, it is reported according to the specified interval. |
success | Function | No | The callback function that indicates a successful call. |
fail | Function | No | The callback function that indicates a failed call. |
complete | Function | No | The callback function that indicates the call is completed (this will be executed regardless of whether the call succeeds or fails). |
Code sample
my.startBluetoothDevicesDiscovery({
services: ['fff0'],
success: (res) => {
console.log(res)
},
fail:(res) => {
},
complete: (res)=>{
}
});
Instructions
This operation consumes more system resources. Please call the
stop
method to stop the search after any device is discovered and connected.
my.stopBluetoothDevicesDiscovery
You can call this interface to stop searching for nearby Bluetooth devices.
Input parameters
Parameter | Type | Required | Description |
---|---|---|---|
success | Function | No | The callback function that indicates a successful call. |
fail | Function | No | The callback function that indicates a failed call. |
complete | Function | No | The callback function that indicates the call is completed (this will be executed regardless of whether the call succeeds or fails). |
Code sample
my.stopBluetoothDevicesDiscovery({
success: (res) => {
console.log(res)
},
fail:(res) => {
},
complete: (res)=>{
}
});
my.getBluetoothDevices
You can call this interface to obtain all discovered Bluetooth devices, including the Bluetooth device that is already connected.
Input parameters
Parameter | Type | Required | Description |
---|---|---|---|
success | Function | No | The callback function that indicates a successful call. |
fail | Function | No | The callback function that indicates a failed call. |
complete | Function | No | The callback function that indicates the call is completed (this will be executed regardless of whether the call succeeds or fails). |
Return value on success
Parameter | Type | Description |
---|---|---|
devices | Array | List of discovered devices |
device objects
Name | Type | Description |
---|---|---|
name | String | The name of the Bluetooth device. Some devices may not have a name. |
deviceName (compatible with earlier versions) | String | The value is consistent with that of |
localName | String | Name of the advertising device. |
deviceId | String | Device ID |
RSSI | Number | The signal strength of the device. |
advertisData | Hex String | The advertising content of the device. |
manufacturerData | Hex String | The manufacturer data of the device. |
Code sample
my.getBluetoothDevices({
success: (res) => {
console.log(res)
},
fail:(res) => {
},
complete: (res)=>{
}
});
Instructions
The simulator may not be able to obtain advertisData and RSSI. Please use a physical device for debugging.
For Integrated Development Environment (IDE) and Android devices, the device ID is the MAC address of the device; for iOS device, the device ID is the UUID of the device. Therefore, the device ID cannot be hard coded, and needs to be processed based on the specific platform. iOS can dynamically match the deviceId according to the device properties (such as
localName
,advertisData
,manufacturerData
).
my.getConnectedBluetoothDevices
You can call this interface to obtain information of the connected devices.
Input parameters
Parameter | Type | Required | Description |
---|---|---|---|
deviceId | String | No | The ID of the Bluetooth device. |
success | Function | No | The callback function that indicates a successful call. |
fail | Function | No | The callback function that indicates a failed call. |
complete | Function | No | The callback function that indicates the call is completed (this will be executed regardless of whether the call succeeds or fails). |
Code sample
my.getConnectedBluetoothDevices({
success: (res) => {
console.log(res)
},
fail:(res) => {
},
complete: (res)=>{
}
});
Instructions
If you have searched for a Bluetooth device in the mini program before, you can directly pass in the deviceId obtained by the previous search to connect to the device.
If the specified bluetooth device is connected, you’ll be returned with a success response if the connection is repeated.
my.connectBLEDevice
You can call this interface to connect to the Bluetooth Low Energy (BLE) device.
Input parameters
Parameter | Type | Required | Description |
---|---|---|---|
deviceId | String | Yes | The ID of the Bluetooth device. |
success | Function | No | The callback function that indicates a successful call. |
fail | Function | No | The callback function that indicates a failed call. |
complete | Function | No | The callback function that indicates the call is completed (this will be executed regardless of whether the call succeeds or fails). |
Code sample
my.connectBLEDevice({
// The device ID here needs to be obtained in the getBluetoothDevices or onBluetoothDeviceFound APIs above
deviceId: deviceId,
success: (res) => {
console.log(res)
},
fail:(res) => {
},
complete: (res)=>{
}
});
Instructions
If you have searched for a Bluetooth device in the mini program before, you can directly pass in the deviceId obtained by the previous search to connect to the device.
If the specified Bluetooth device is connected, you’ll be returned with a success response if the connection is repeated.
The interface is supported by iOS as well as Android 5.0 and later versions.
my.disconnectBLEDevice
You can call this interface to disconnect from the BLE device.
Input parameters
Parameter | Type | Required | Description |
---|---|---|---|
deviceId | String | Yes | The ID of the Bluetooth device. |
success | Function | No | The callback function that indicates a successful call. |
fail | Function | No | The callback function that indicates a failed call. |
complete | Function | No | The callback function that indicates the call is completed (this will be executed regardless of whether the call succeeds or fails). |
Code sample
my.disconnectBLEDevice({
deviceId: deviceId,
success: (res) => {
console.log(res)
},
fail:(res) => {
},
complete: (res)=>{
}
});
Instructions
The Bluetooth device may be disconnected at any time. We recommend that you listen to the
my.onBLEConnectionStateChanged
callback, and reconnect as needed when the Bluetooth device is disconnected.If the API for data read/write operation is called for unconnected devices or disconnected devices, 10006 error is returned. See the Bluetooth API error codes for details. It is recommended to perform the reconnection operation.
The interface is supported by iOS as well as Android 5.0 and later versions.
my.writeBLECharacteristicValue
You can call this interface to write data into the characteristic value of the BLE device.
Input parameters
Parameter | Type | Required | Description |
---|---|---|---|
deviceId | String | Yes | The ID of the Bluetooth device. For more information, see the |
serviceId | String | Yes | The UUID of the |
characteristicId | String | Yes | The UUID of the Bluetooth characteristic. |
value | Hex String | Yes | The value corresponding to the Bluetooth characteristic. It is a hexadecimal string limited to 20 bytes. |
success | Function | No | The callback function that indicates a successful call. |
fail | Function | No | The callback function that indicates a failed call. |
complete | Function | No | The callback function that indicates the call is completed (this will be executed regardless of whether the call succeeds or fails). |
Code sample
my.writeBLECharacteristicValue({
deviceId: deviceId,
serviceId: serviceId,
characteristicId: characteristicId,
value: 'fffe',
success: (res) => {
console.log(res)
},
fail:(res) => {
},
complete: (res)=>{
}
});
Instructions
The characteristic of the device must support “write”, otherwise the interface cannot be successfully called. Please see the
properties
of the characteristic for details.The binary data written needs to be hex encoded.
The interface is supported by iOS as well as Android 5.0 and later versions.
my.readBLECharacteristicValue
You can call this interface to read data from the characteristic value of the BLE device. Then, the data is returned in the my.onBLECharacteristicValueChange()
event.
Input parameters
Parameter | Type | Required | Description |
---|---|---|---|
deviceId | String | Yes | The ID of the Bluetooth device. For more information, see the |
serviceId | String | Yes | The UUID of the |
characteristicId | String | Yes | The UUID of the Bluetooth characteristic. |
success | Function | No | The callback function that indicates a successful call. |
fail | Function | No | The callback function that indicates a failed call. |
complete | Function | No | The callback function that indicates the call is completed (this will be executed regardless of whether the call succeeds or fails). |
Return value on success
Parameter | Type | Description |
---|---|---|
characteristic | Object | The information of the device characteristic. |
characteristic objects
The characteristic information of the Bluetooth device.
Name | Type | Description |
---|---|---|
characteristicId | String | The UUID of the Bluetooth device characteristic. |
serviceId | String | The UUID of the service corresponding to the Bluetooth device characteristic. |
value | Hex String | The value of the Bluetooth device characteristic. |
Code sample
my.readBLECharacteristicValue({
deviceId: deviceId,
serviceId: serviceId,
characteristicId: characteristicId,
success: (res) => {
console.log(res)
},
fail:(res) => {
},
complete: (res)=>{
}
});
Instructions
The characteristic of the device must support “read”, otherwise the interface cannot be successfully called. Please see the
properties
of the characteristic for details.Multiple parallel reading and writing calls might cause failures.
If the reading times out, the error code is 10015. However,
my.onBLECharacteristicValueChange
interface might return data later. Please process the error with reference to Bluetooth API error codes.The interface is supported by iOS as well as Android 5.0 and later versions.
my.notifyBLECharacteristicValueChange
You can call this interface to enable the “notify” feature for the characteristic value change of the BLE device.
Input parameters
Parameter | Type | Required | Description |
---|---|---|---|
deviceId | String | Yes | The ID of the Bluetooth device. For more information, see the |
serviceId | String | Yes | The UUID of the |
characteristicId | String | Yes | The UUID of the Bluetooth characteristic. |
descriptorId | String | No | The UUID of the |
state | Boolean | No | Whether to enable |
success | Function | No | The callback function that indicates a successful call. |
fail | Function | No | The callback function that indicates a failed call. |
complete | Function | No | The callback function that indicates the call is completed (this will be executed regardless of whether the call succeeds or fails). |
Code sample
my.notifyBLECharacteristicValueChange({
deviceId: deviceId,
serviceId: serviceId,
characteristicId: characteristicId,
success: (res) => {
console.log(res)
},
fail:(res) => {
},
complete: (res)=>{
}
});
Instructions
The characteristic of the device must support “notify/indicate”, otherwise the interface cannot be successfully called.
The “notify” feature must be enabled to listen to the
characteristicValueChange
event of the device.After the subscription operation is successful, the device needs to actively update the characteristic value to trigger
my.onBLECharacteristicValueChange
.The subscription operation is more efficient. So, it is recommended to use the subscription method instead of the read method.
my.getBLEDeviceServices
You can call this interface to obtain all the Bluetooth devices that are discovered, including the connected devices.
Input parameters
Parameter | Type | Required | Description |
---|---|---|---|
deviceId | String | Yes | The ID of the Bluetooth device. For more information, see the |
success | Function | No | The callback function that indicates a successful call. |
fail | Function | No | The callback function that indicates a failed call. |
complete | Function | No | The callback function that indicates the call is completed (this will be executed regardless of whether the call succeeds or fails). |
Return value on success
Parameter | Type | Description |
---|---|---|
services | Array | List of discovered device services |
service objects
The service information of the Bluetooth device.
Name | Type | Description |
---|---|---|
serviceId | String | The UUID of the Bluetooth device service. |
isPrimary | Boolean | Indicates whether the service is the primary service. true: primary service false: not primary service |
Code sample
// Obtain the services of the connected devices. The services can only be obtained when the devices are connected.
getBLEDeviceServices() {
my.getConnectedBluetoothDevices({
success: res => {
if (res.devices.length === 0) {
my.alert({ content: 'No connected devices' });
return;
}
my.getBLEDeviceServices({
deviceId: this.data.devid,
success: res => {
my.alert({ content: JSON.stringify(res) });
this.setData({
serid: res.services[0].serviceId,
});
},
fail: error => {
my.alert({ content: JSON.stringify(error) });
},
});
},
});
},
Example of return value
{
"services": [{
"isPrimary": true,
"serviceId": "00001800-0000-1000-8000-00805f9b34fb"
}, {
"isPrimary": true,
"serviceId": "00001801-0000-1000-8000-00805f9b34fb"
}, {
"isPrimary": true,
"serviceId": "d0611e78-bbb4-4591-a5f8-487910ae4366"
}, {
"isPrimary": true,
"serviceId": "9fa480e0-4967-4542-9390-d343dc5d04ae"
}]
}
Instructions
After the connection is established, you should execute
my.getBLEDeviceServices
andmy.getBLEDeviceCharacteristics
first, and then perform data interaction with the Bluetooth device.The interface is supported by iOS as well as Android 5.0 and later versions.
my.getBLEDeviceCharacteristics
You can call this interface to obtain all characteristics of the Bluetooth device.
Input parameters
Parameter | Type | Required | Description |
---|---|---|---|
deviceId | String | Yes | The ID of the Bluetooth device. For more information, see the device objects. |
serviceId | String | Yes | The UUID of the service to which the Bluetooth characteristic corresponds. |
success | Function | No | The callback function that indicates a successful call. |
fail | Function | No | The callback function that indicates a failed call. |
complete | Function | No | The callback function that indicates the call is completed (this will be executed regardless of whether the call succeeds or fails). |
Return value on success
Name | Type | Description |
---|---|---|
characteristics | Array | The list of device characteristics. |
characteristic objects
The characteristic information of the Bluetooth device.
Name | Type | Description |
---|---|---|
characteristicId | String | The UUID of the Bluetooth device characteristic. |
serviceId | String | The UUID of the service corresponding to the Bluetooth device characteristic. |
value | Hex String | The hexadecimal value corresponding to the Bluetooth device characteristic. |
properties | Object | The type of operation supported by the characteristic. |
properties objects
Name | Type | Description |
---|---|---|
read | Boolean | Indicates whether the characteristic supports read operations. |
write | Boolean | Indicates whether the characteristic supports write operations. |
notify | Boolean | Indicates whether the characteristic supports notify operations. |
indicate | Boolean | Indicates whether the characteristic supports indicate operations. |
Code sample
my.getBLEDeviceCharacteristics({
deviceId: deviceId,
serviceId: serviceId,
success: (res) => {
console.log(res)
},
fail:(res) => {
},
complete: (res)=>{
}
});
Instructions
After the connection is established, you should execute
my.getBLEDeviceServices
andmy.getBLEDeviceCharacteristics
first, and then perform data interaction with the Bluetooth device.The interface is supported by iOS as well as Android 5.0 and later versions.
my.onBluetoothDeviceFound(callback)
This callback is triggered when a new Bluetooth device is found.
Input parameters
Parameter | Type | Required | Description |
---|---|---|---|
callback | Function | Yes | The callback that is triggered when the specified event occurs. |
Return values of callback
Parameter | Type | Description |
---|---|---|
devices | Array | The list of newly found devices. |
device objects
Name | Type | Description |
---|---|---|
name | String | The name of the Bluetooth device. Some devices may not have a name. |
deviceName (compatible with earlier versions) | String | The value is consistent with that of |
localName | String | The name of the advertising device. |
deviceId | String | The ID of the device. |
RSSI | Number | The signal strength of the device. |
advertisData | Hex String | The advertising content of the device. |
Code sample
Page({
onLoad() {
this.callback = this.callback.bind(this);
my.onBluetoothDeviceFound(this.callback);
},
onUnload() {
my.offBluetoothDeviceFound(this.callback);
},
callback(res) {
console.log(res);
},
})
Instructions
The simulator may not be able to obtain
advertisData
and RSSI. Please use a physical device for debugging.For Integrated Development Environment (IDE) and Android devices, the device ID is the MAC address of the device; for iOS device, the device ID is the UUID of the device. Therefore, the device ID cannot be hard coded, and needs to be processed based on the specific platform. iOS can dynamically match the
deviceId
according to the device properties (such aslocalName
,advertisData
,manufacturerData
).If a Bluetooth device is included in the
my.onBluetoothDeviceFound
callback, the device is added to the array obtained bymy.getBluetoothDevices
.
my.offBluetoothDeviceFound
You can call this interface to remove the listener for new Bluetooth device discovery events.
Code sample
my.offBluetoothDeviceFound();
Whether to pass callback value or not
If the callback value is not passed, the callbacks of all events will be removed. The sample code is as follows:
my.offBluetoothDeviceFound();
If the callback value is passed, only the corresponding callback is removed. The sample code is as follows:
my.offBluetoothDeviceFound(this.callback);
Instructions
It is recommended that you call the
off
method to close existing event listening before you call theon
method to listen events to prevent the situation where multiple event listening causes multiple callbacks of an event.
my.onBLECharacteristicValueChange(callback)
You can call this interface to listen to characteristic value change events of BLE device.
Input parameters
Parameter | Type | Required | Description |
---|---|---|---|
callback | Function | Yes | The callback function that is triggered when a specified event occurs. |
Return values of callback
Parameter | Type | Description |
---|---|---|
deviceId | String | The ID of the Bluetooth device. For more information, see the |
connected | Boolean | The current state of the connection. |
Code sample
Page({
onLoad() {
this.callback = this.callback.bind(this);
my.onBLECharacteristicValueChange(this.callback);
},
onUnload() {
my.offBLECharacteristicValueChange(this.callback);
},
callback(res) {
console.log(res);
},
})
Instructions
It is recommended that you call the
off
method to close existing event listening before you call theon
method to listen events to prevent the situation where multiple event listening causes multiple callbacks of an event.
my.offBLECharacteristicValueChange
You can call this interface to stop listening to the characteristic value change events of BLE device.
Input parameters
Parameter | Type | Description |
---|---|---|
deviceId | String | The ID of the Bluetooth device. For more information, see the |
serviceId | String | The UUID of the service to which the Bluetooth characteristic corresponds. |
characteristicId | String | The UUID of the Bluetooth characteristic. |
value | Hex String | The latest hexadecimal value of the characteristic. |
Whether to pass callback value or not
If the callback value is not passed, the callbacks of all events will be removed. The sample code is as follows:
my.offBLECharacteristicValueChange();
If the callback value is passed, only the corresponding callback is removed. The sample code is as follows:
my.offBLECharacteristicValueChange();
Code sample
Page({
onLoad() {
this.callback = this.callback.bind(this);
my.onBLECharacteristicValueChange(this.callback);
},
onUnload() {
my.offBLECharacteristicValueChange(this.callback);
},
callback(res) {
console.log(res);
},
})
my.onBLEConnectionStateChanged(callback)
You can call this interface to listen to the BLE connection error events, such as device lost and device disconnected.
Input parameters
Parameter | Type | Required | Description |
---|---|---|---|
callback | Function | Yes | The callback function that is triggered when a specified event occurs. |
Return values of callback
Parameter | Type | Description |
---|---|---|
deviceId | String | The ID of the Bluetooth device. For more information, see the |
connected | Boolean | The current state of the connection. |
Code sample
/* .acss */
.help-info {
padding:10px;
color:#000000;
}
.help-title {
padding:10px;
color:#FC0D1B;
}
// .json
{
"defaultTitle": "Bluetooth"
}
<!-- .axml-->
<view class="page">
<view class="page-description">Bluetooth API</view>
<view class="page-section">
<view class="page-section-title">Bluetooth state</view>
<view class="page-section-demo">
<button type="primary" onTap="openBluetoothAdapter">Initialize Bluetooth</button>
<button type="primary" onTap="closeBluetoothAdapter">Close Bluetooth</button>
<button type="primary" onTap="getBluetoothAdapterState">Obtain Bluetooth state</button>
</view>
<view class="page-section-title">Scan the Bluetooth device</view>
<view class="page-section-demo">
<button type="primary" onTap="startBluetoothDevicesDiscovery">Start searching</button>
<button type="primary" onTap="getBluetoothDevices">All devices found</button>
<button type="primary" onTap="getConnectedBluetoothDevices">All connected devicese/button>
<button type="primary" onTap="stopBluetoothDevicesDiscovery">Stop searching</button>
</view>
<view class="page-section-title">Connect the device</view>
<view class="page-section-demo">
<input class="input" onInput="bindKeyInput" type="{{text}}" placeholder=" Input the ID of the device to be connected "></input>
<button type="primary" onTap="connectBLEDevice">Connect the device</button>
<button type="primary" onTap="getBLEDeviceServices">Obtain device services</button>
<button type="primary" onTap="getBLEDeviceCharacteristics">Obtain read and write characteristics</button>
<button type="primary" onTap="disconnectBLEDevice"> Disconnect the device </button>
</view>
<view class="page-section-title">Read and write data</view>
<view class="page-section-demo">
<button type="primary" onTap="notifyBLECharacteristicValueChange">Listen to the characteristic data change</button>
<button type="primary" onTap="readBLECharacteristicValue">Read data</button>
<button type="primary" onTap="writeBLECharacteristicValue">Write data</button>
<button type="primary" onTap="offBLECharacteristicValueChange">Cancel listening to characteristic value</button>
</view>
<view class="page-section-title">Other events</view>
<view class="page-section-demo">
<button type="primary" onTap="bluetoothAdapterStateChange">Bluetooth status change</button>
<button type="primary" onTap="offBluetoothAdapterStateChange">Cancel listening to Bluetooth status</button>
<button type="primary" onTap="BLEConnectionStateChanged">Bluetooth connection status changes</button>
<button type="primary" onTap="offBLEConnectionStateChanged">Cancel listening to Bluetooth connection status</button>
</view>
</view>
</view>
// .js
Page({
data: {
devid: '0D9C82AD-1CC0-414D-9526-119E08D28124',
serid: 'FEE7',
notifyId: '36F6',
writeId: '36F5',
charid: '',
alldev: [{ deviceId: '' }],
},
//Obtain the Bluetooth state
openBluetoothAdapter() {
my.openBluetoothAdapter({
success: res => {
if (!res.isSupportBLE) {
my.alert({ content: 'Sorry, your mobile Bluetooth is unavailable temporarily' });
return;
}
my.alert({ content: 'Initialization succeeded!' });
},
fail: error => {
my.alert({ content: JSON.stringify(error) });
},
});
},
closeBluetoothAdapter() {
my.closeBluetoothAdapter({
success: () => {
my.alert({ content: 'Bluetooth closed!' });
},
fail: error => {
my.alert({ content: JSON.stringify(error) });
},
});
},
getBluetoothAdapterState() {
my.getBluetoothAdapterState({
success: res => {
if (!res.available) {
my.alert({ content: 'Sorry, your mobile Bluetooth is unavailable temporarily' });
return;
}
my.alert({ content: JSON.stringify(res) });
},
fail: error => {
my.alert({ content: JSON.stringify(error) });
},
});
},
//Scan the Bluetooth device
startBluetoothDevicesDiscovery() {
my.startBluetoothDevicesDiscovery({
allowDuplicatesKey: false,
success: () => {
my.onBluetoothDeviceFound({
success: res => {
// my.alert({content:'Listen to new device'+JSON.stringify(res)});
var deviceArray = res.devices;
for (var i = deviceArray.length - 1; i >= 0; i--) {
var deviceObj = deviceArray[i];
//Match the target device by device name or broadcast data, and then record the device ID for later use
if (deviceObj.name == this.data.name) {
my.alert({ content: 'Target device is found' });
my.offBluetoothDeviceFound();
this.setData({
deviceId: deviceObj.deviceId,
});
break;
}
}
},
fail: error => {
my.alert({ content: 'Failed to listen to new device' + JSON.stringify(error) });
},
});
},
fail: error => {
my.alert({ content: 'Failed to start scanning' + JSON.stringify(error) });
},
});
},
//Stop scanning
stopBluetoothDevicesDiscovery() {
my.stopBluetoothDevicesDiscovery({
success: res => {
my.offBluetoothDeviceFound();
my.alert({ content: 'Succeeded!' });
},
fail: error => {
my.alert({ content: JSON.stringify(error) });
},
});
},
//Obtain the connected device
getConnectedBluetoothDevices() {
my.getConnectedBluetoothDevices({
success: res => {
if (res.devices.length === 0) {
my.alert({ content: 'No connected devices!' });
return;
}
my.alert({ content: JSON.stringify(res) });
devid = res.devices[0].deviceId;
},
fail: error => {
my.alert({ content: JSON.stringify(error) });
},
});
},
//Obtain all devices found
getBluetoothDevices() {
my.getBluetoothDevices({
success: res => {
my.alert({ content: JSON.stringify(res) });
},
fail: error => {
my.alert({ content: JSON.stringify(error) });
},
});
},
bindKeyInput(e) {
this.setData({
devid: e.detail.value,
});
},
//Connect the device
connectBLEDevice() {
my.connectBLEDevice({
deviceId: this.data.devid,
success: res => {
my.alert({ content: 'Connected successfully' });
},
fail: error => {
my.alert({ content: JSON.stringify(error) });
},
});
},
//Disconnect
disconnectBLEDevice() {
my.disconnectBLEDevice({
deviceId: this.data.devid,
success: () => {
my.alert({ content: ‘Disconnected successfully!' });
},
fail: error => {
my.alert({ content: JSON.stringify(error) });
},
});
},
//Obtain the services of the connected devices. The services can only be obtained when the devices are connected.
getBLEDeviceServices() {
my.getConnectedBluetoothDevices({
success: res => {
if (res.devices.length === 0) {
my.alert({ content: 'No connected devices' });
return;
}
my.getBLEDeviceServices({
deviceId: this.data.devid,
success: res => {
my.alert({ content: JSON.stringify(res) });
this.setData({
serid: res.services[0].serviceId,
});
},
fail: error => {
my.alert({ content: JSON.stringify(error) });
},
});
},
});
},
//Obtain the charid of the connected devices. The charid can only be obtained when the devices are connected. The read and write characteristics are respectively screened out.
getBLEDeviceCharacteristics() {
my.getConnectedBluetoothDevices({
success: res => {
if (res.devices.length === 0) {
my.alert({ content: 'No connected devices' });
return;
}
this.setData({
devid: res.devices[0].deviceId,
});
my.getBLEDeviceCharacteristics({
deviceId: this.data.devid,
serviceId: this.data.serid,
success: res => {
my.alert({ content: JSON.stringify(res) });
//See the related document for more information about the attributes of the characteristics. Match the read/write characteristics by attribute and record the value for later use.
this.setData({
charid: res.characteristics[0].characteristicId,
});
},
fail: error => {
my.alert({ content: JSON.stringify(error) });
},
});
},
});
},
//Read and write data
readBLECharacteristicValue() {
my.getConnectedBluetoothDevices({
success: res => {
if (res.devices.length === 0) {
my.alert({ content: 'No connected devices' });
return;
}
this.setData({
devid: res.devices[0].deviceId,
});
my.readBLECharacteristicValue({
deviceId: this.data.devid,
serviceId: this.data.serid,
characteristicId: this.data.notifyId,
//1. Android read and write services
// serviceId:'0000180d-0000-1000-8000-00805f9b34fb',
// characteristicId:'00002a38-0000-1000-8000-00805f9b34fb',
success: res => {
my.alert({ content: JSON.stringify(res) });
},
fail: error => {
my.alert({ content: 'Failed to read and write' + JSON.stringify(error) });
},
});
},
});
},
writeBLECharacteristicValue() {
my.getConnectedBluetoothDevices({
success: res => {
if (res.devices.length === 0) {
my.alert({ content: 'No connected devices' });
return;
}
this.setData({
devid: res.devices[0].deviceId,
});
my.writeBLECharacteristicValue({
deviceId: this.data.devid,
serviceId: this.data.serid,
characteristicId: this.data.charid,
//Android write service
//serviceId:'0000180d-0000-1000-8000-00805f9b34fb',
//characteristicId:'00002a39-0000-1000-8000-00805f9b34fb',
value: 'ABCD',
success: res => {
my.alert({ content: 'Data written successfully!' });
},
fail: error => {
my.alert({ content: JSON.stringify(error) });
},
});
},
});
},
notifyBLECharacteristicValueChange() {
my.getConnectedBluetoothDevices({
success: res => {
if (res.devices.length === 0) {
my.alert({ content: 'No connected devices' });
return;
}
this.setData({
devid: res.devices[0].deviceId,
});
my.notifyBLECharacteristicValueChange({
state: true,
deviceId: this.data.devid,
serviceId: this.data.serid,
characteristicId: this.data.notifyId,
success: () => {
//Listen to characteristic change events
my.onBLECharacteristicValueChange({
success: res => {
// my.alert({content: 'Characteristic change:'+JSON.stringify(res)});
my.alert({ content: 'Obtain the response data = ' + res.value });
},
});
my.alert({ content: 'Listened successfully' });
},
fail: error => {
my.alert({ content: 'Failed to listen' + JSON.stringify(error) });
},
});
},
});
},
offBLECharacteristicValueChange() {
my.offBLECharacteristicValueChange();
},
//Other events
bluetoothAdapterStateChange() {
my.onBluetoothAdapterStateChange(this.getBind('onBluetoothAdapterStateChange'));
},
onBluetoothAdapterStateChange() {
if (res.error) {
my.alert({ content: JSON.stringify(error) });
} else {
my.alert({ content: 'Bluetooth status change: ' + JSON.stringify(res) });
}
},
offBluetoothAdapterStateChange() {
my.offBluetoothAdapterStateChange(this.getBind('onBluetoothAdapterStateChange'));
},
getBind(name) {
if (!this[`bind${name}`]) {
this[`bind${name}`] = this[name].bind(this);
}
return this[`bind${name}`];
},
BLEConnectionStateChanged() {
my.onBLEConnectionStateChanged(this.getBind('onBLEConnectionStateChanged'));
},
onBLEConnectionStateChanged(res) {
if (res.error) {
my.alert({ content: JSON.stringify(error) });
} else {
my.alert({ content: 'Connection status change: ' + JSON.stringify(res) });
}
},
offBLEConnectionStateChanged() {
my.offBLEConnectionStateChanged(this.getBind('onBLEConnectionStateChanged'));
},
onUnload() {
this.offBLEConnectionStateChanged();
this.offBLECharacteristicValueChange();
this.offBluetoothAdapterStateChange();
this.closeBluetoothAdapter();
},
});
Instructions
It is recommended that you call the
off
method to close existing event listening before you call theon
method to listen events to prevent the situation where multiple event listening causes multiple callbacks of an event.
my.offBLEConnectionStateChanged
You can call this interface to stop listening to the connection status change events of the BLE device.
Code sample
my.offBLEConnectionStateChanged();
Whether to pass callback value or not
If the callback value is not passed, the callbacks of all events will be removed. The sample code is as follows:
my.offBLEConnectionStateChanged();
If the callback value is passed, only the corresponding callback is removed. The sample code is as follows:
my.offBLEConnectionStateChanged(this.callback);
Instructions
It is recommended that you call the
off
method to close existing event listening before you call theon
method to listen events to prevent the situation where multiple event listening causes multiple callbacks of an event.
my.onBluetoothAdapterStateChange(callback)
You can call this interface to listen to the native Bluetooth status change events.
Input parameters
Parameter | Type | Required | Description |
---|---|---|---|
callback | Function | Yes | The callback function that is triggered when a specified event occurs. |
Return values of callback
Parameter | Type | Description |
---|---|---|
available | Boolean | Indicates whether the Bluetooth module is available. |
discovering | Boolean | Indicates whether the Bluetooth module is in the searching state. |
Code sample
/* .acss */
.help-info {
padding:10px;
color:#000000;
}
.help-title {
padding:10px;
color:#FC0D1B;
}
// .json
{
"defaultTitle": "Bluetooth"
}
<!-- .axml-->
<view class="page">
<view class="page-description">Bluetooth API</view>
<view class="page-section">
<view class="page-section-title">Bluetooth state</view>
<view class="page-section-demo">
<button type="primary" onTap="openBluetoothAdapter">Initialize Bluetooth</button>
<button type="primary" onTap="closeBluetoothAdapter">Close Bluetooth</button>
<button type="primary" onTap="getBluetoothAdapterState">Obtain Bluetooth state</button>
</view>
<view class="page-section-title">Scan the Bluetooth device</view>
<view class="page-section-demo">
<button type="primary" onTap="startBluetoothDevicesDiscovery">Start searching</button>
<button type="primary" onTap="getBluetoothDevices">All devices found</button>
<button type="primary" onTap="getConnectedBluetoothDevices">All connected devices/button>
<button type="primary" onTap="stopBluetoothDevicesDiscovery">Stop searching</button>
</view>
<view class="page-section-title">Connect the device</view>
<view class="page-section-demo">
<input class="input" onInput="bindKeyInput" type="{{text}}" placeholder=" Input the ID of the device to be connected "></input>
<button type="primary" onTap="connectBLEDevice">Connect the device</button>
<button type="primary" onTap="getBLEDeviceServices">Obtain device services</button>
<button type="primary" onTap="getBLEDeviceCharacteristics">Obtain read and write characteristics</button>
<button type="primary" onTap="disconnectBLEDevice">Disconnect the device</button>
</view>
<view class="page-section-title">Read and write data</view>
<view class="page-section-demo">
<button type="primary" onTap="notifyBLECharacteristicValueChange">Listen to the characteristic data change</button>
<button type="primary" onTap="readBLECharacteristicValue">Read data</button>
<button type="primary" onTap="writeBLECharacteristicValue">Write data</button>
<button type="primary" onTap="offBLECharacteristicValueChange">Cancel listening to characteristic value</button>
</view>
<view class="page-section-title">Other events</view>
<view class="page-section-demo">
<button type="primary" onTap="bluetoothAdapterStateChange">Bluetooth status change</button>
<button type="primary" onTap="offBluetoothAdapterStateChange">Cancel listening to Bluetooth status</button>
<button type="primary" onTap="BLEConnectionStateChanged">Bluetooth connection status changes</button>
<button type="primary" onTap="offBLEConnectionStateChanged">Cancel listening to Bluetooth connection status</button>
</view>
</view>
</view>
// .js
Page({
data: {
devid: '0D9C82AD-1CC0-414D-9526-119E08D28124',
serid: 'FEE7',
notifyId: '36F6',
writeId: '36F5',
charid: '',
alldev: [{ deviceId: '' }],
},
//Obtain the Bluetooth state
openBluetoothAdapter() {
my.openBluetoothAdapter({
success: res => {
if (!res.isSupportBLE) {
my.alert({ content: 'Sorry, your mobile Bluetooth is unavailable temporarily' });
return;
}
my.alert({ content: 'Initialization succeeded!' });
},
fail: error => {
my.alert({ content: JSON.stringify(error) });
},
});
},
closeBluetoothAdapter() {
my.closeBluetoothAdapter({
success: () => {
my.alert({ content: 'Bluetooth closed!' });
},
fail: error => {
my.alert({ content: JSON.stringify(error) });
},
});
},
getBluetoothAdapterState() {
my.getBluetoothAdapterState({
success: res => {
if (!res.available) {
my.alert({ content: 'Sorry, your mobile Bluetooth is unavailable temporarily' });
return;
}
my.alert({ content: JSON.stringify(res) });
},
fail: error => {
my.alert({ content: JSON.stringify(error) });
},
});
},
//Scan the Bluetooth device
startBluetoothDevicesDiscovery() {
my.startBluetoothDevicesDiscovery({
allowDuplicatesKey: false,
success: () => {
my.onBluetoothDeviceFound({
success: res => {
// my.alert({content:'Listen to new device'+JSON.stringify(res)});
var deviceArray = res.devices;
for (var i = deviceArray.length - 1; i >= 0; i--) {
var deviceObj = deviceArray[i];
//Match the target device by device name or broadcast data, and then record the device ID for later use
if (deviceObj.name == this.data.name) {
my.alert({ content: 'Target device is found' });
my.offBluetoothDeviceFound();
this.setData({
deviceId: deviceObj.deviceId,
});
break;
}
}
},
fail: error => {
my.alert({ content: 'Failed to listen to new device' + JSON.stringify(error) });
},
});
},
fail: error => {
my.alert({ content: 'Failed to start scanning' + JSON.stringify(error) });
},
});
},
//Stop scanning
stopBluetoothDevicesDiscovery() {
my.stopBluetoothDevicesDiscovery({
success: res => {
my.offBluetoothDeviceFound();
my.alert({ content: 'Succeeded!' });
},
fail: error => {
my.alert({ content: JSON.stringify(error) });
},
});
},
//Obtain the connected device
getConnectedBluetoothDevices() {
my.getConnectedBluetoothDevices({
success: res => {
if (res.devices.length === 0) {
my.alert({ content: 'No connected devices!' });
return;
}
my.alert({ content: JSON.stringify(res) });
devid = res.devices[0].deviceId;
},
fail: error => {
my.alert({ content: JSON.stringify(error) });
},
});
},
//Obtain all devices found
getBluetoothDevices() {
my.getBluetoothDevices({
success: res => {
my.alert({ content: JSON.stringify(res) });
},
fail: error => {
my.alert({ content: JSON.stringify(error) });
},
});
},
bindKeyInput(e) {
this.setData({
devid: e.detail.value,
});
},
//Connect the device
connectBLEDevice() {
my.connectBLEDevice({
deviceId: this.data.devid,
success: res => {
my.alert({ content: 'Connected successfully' });
},
fail: error => {
my.alert({ content: JSON.stringify(error) });
},
});
},
//Disconnect
disconnectBLEDevice() {
my.disconnectBLEDevice({
deviceId: this.data.devid,
success: () => {
my.alert({ content: ‘Disconnected successfully!' });
},
fail: error => {
my.alert({ content: JSON.stringify(error) });
},
});
},
//Obtain the services of the connected devices. The services can only be obtained when the devices are connected.
getBLEDeviceServices() {
my.getConnectedBluetoothDevices({
success: res => {
if (res.devices.length === 0) {
my.alert({ content: 'No connected devices' });
return;
}
my.getBLEDeviceServices({
deviceId: this.data.devid,
success: res => {
my.alert({ content: JSON.stringify(res) });
this.setData({
serid: res.services[0].serviceId,
});
},
fail: error => {
my.alert({ content: JSON.stringify(error) });
},
});
},
});
},
//Obtain the charid of the connected devices. The charid can only be obtained when the devices are connected. The read and write characteristics are respectively screened out.
getBLEDeviceCharacteristics() {
my.getConnectedBluetoothDevices({
success: res => {
if (res.devices.length === 0) {
my.alert({ content: 'No connected devices' });
return;
}
this.setData({
devid: res.devices[0].deviceId,
});
my.getBLEDeviceCharacteristics({
deviceId: this.data.devid,
serviceId: this.data.serid,
success: res => {
my.alert({ content: JSON.stringify(res) });
//See the related document for more information about the attributes of the characteristics. Match the read/write characteristics by attribute and record the value for later use.
this.setData({
charid: res.characteristics[0].characteristicId,
});
},
fail: error => {
my.alert({ content: JSON.stringify(error) });
},
});
},
});
},
//Read and write data
readBLECharacteristicValue() {
my.getConnectedBluetoothDevices({
success: res => {
if (res.devices.length === 0) {
my.alert({ content: 'No connected devices' });
return;
}
this.setData({
devid: res.devices[0].deviceId,
});
my.readBLECharacteristicValue({
deviceId: this.data.devid,
serviceId: this.data.serid,
characteristicId: this.data.notifyId,
//1. Android read and write services
// serviceId:'0000180d-0000-1000-8000-00805f9b34fb',
// characteristicId:'00002a38-0000-1000-8000-00805f9b34fb',
success: res => {
my.alert({ content: JSON.stringify(res) });
},
fail: error => {
my.alert({ content: 'Failed to read and write' + JSON.stringify(error) });
},
});
},
});
},
writeBLECharacteristicValue() {
my.getConnectedBluetoothDevices({
success: res => {
if (res.devices.length === 0) {
my.alert({ content: 'No connected devices' });
return;
}
this.setData({
devid: res.devices[0].deviceId,
});
my.writeBLECharacteristicValue({
deviceId: this.data.devid,
serviceId: this.data.serid,
characteristicId: this.data.charid,
//Android write service
//serviceId:'0000180d-0000-1000-8000-00805f9b34fb',
//characteristicId:'00002a39-0000-1000-8000-00805f9b34fb',
value: 'ABCD',
success: res => {
my.alert({ content: 'Data written successfully!' });
},
fail: error => {
my.alert({ content: JSON.stringify(error) });
},
});
},
});
},
notifyBLECharacteristicValueChange() {
my.getConnectedBluetoothDevices({
success: res => {
if (res.devices.length === 0) {
my.alert({ content: 'No connected devices' });
return;
}
this.setData({
devid: res.devices[0].deviceId,
});
my.notifyBLECharacteristicValueChange({
state: true,
deviceId: this.data.devid,
serviceId: this.data.serid,
characteristicId: this.data.notifyId,
success: () => {
//Listen to characteristic change events
my.onBLECharacteristicValueChange({
success: res => {
// my.alert({content: 'Characteristic change:'+JSON.stringify(res)});
my.alert({ content: 'Obtain the response data = ' + res.value });
},
});
my.alert({ content: 'Listened successfully' });
},
fail: error => {
my.alert({ content: 'Failed to listen' + JSON.stringify(error) });
},
});
},
});
},
offBLECharacteristicValueChange() {
my.offBLECharacteristicValueChange();
},
//Other events
bluetoothAdapterStateChange() {
my.onBluetoothAdapterStateChange(this.getBind('onBluetoothAdapterStateChange'));
},
onBluetoothAdapterStateChange() {
if (res.error) {
my.alert({ content: JSON.stringify(error) });
} else {
my.alert({ content: 'Bluetooth status change: ' + JSON.stringify(res) });
}
},
offBluetoothAdapterStateChange() {
my.offBluetoothAdapterStateChange(this.getBind('onBluetoothAdapterStateChange'));
},
getBind(name) {
if (!this[`bind${name}`]) {
this[`bind${name}`] = this[name].bind(this);
}
return this[`bind${name}`];
},
BLEConnectionStateChanged() {
my.onBLEConnectionStateChanged(this.getBind('onBLEConnectionStateChanged'));
},
onBLEConnectionStateChanged(res) {
if (res.error) {
my.alert({ content: JSON.stringify(error) });
} else {
my.alert({ content: 'Connection status change: ' + JSON.stringify(res) });
}
},
offBLEConnectionStateChanged() {
my.offBLEConnectionStateChanged(this.getBind('onBLEConnectionStateChanged'));
},
onUnload() {
this.offBLEConnectionStateChanged();
this.offBLECharacteristicValueChange();
this.offBluetoothAdapterStateChange();
this.closeBluetoothAdapter();
},
});
my.offBluetoothAdapterStateChange
You can call this interface to stop listening to the native Bluetooth status change events.
Code sample
my.offBluetoothAdapterStateChange();
Whether to pass callback value or not
If the callback value is not passed, the callbacks of all events will be removed. The sample code is as follows:
my.offBluetoothAdapterStateChange();
If the callback value is passed, only the corresponding callback is removed. The sample code is as follows:
my.offBluetoothAdapterStateChange(this.callback);
Instructions
It is recommended that you call the
off
method to close existing event listening before you call theon
method to listen events to prevent the situation where multiple event listening causes multiple callbacks of an event.