Lists all Bluetooth APIs available in mPaaS miniapps for adapter management, device discovery, BLE connection, and characteristic read/write operations.
-
Bluetooth APIs are supported in mPaaS 10.1.60 and later.
-
Debugging in developer tools is not currently supported. You must use a physical device to call the miniapp Bluetooth APIs.
my.openBluetoothAdapter
Initializes the miniapp Bluetooth module. Effective from the time my.openBluetoothAdapter is called until my.closeBluetoothAdapter is called or the miniapp is destroyed. During this period, you can call other Bluetooth APIs and receive on event callbacks.
Input parameters
|
Name |
Type |
Required |
Description |
|
autoClose |
Boolean |
No |
Whether to auto-disconnect Bluetooth when leaving the page. Default: true. Important
This feature is only supported on Android. |
|
success |
Function |
No |
Called on success. |
|
fail |
Function |
No |
Called on failure. |
|
complete |
Function |
No |
Called when the call completes, regardless of outcome. |
Success return value
|
Name |
Type |
Description |
|
isSupportBLE |
Boolean |
Whether BLE is supported. |
Error code descriptions
|
error |
Description |
Solution |
|
12 |
Bluetooth is not enabled. |
Try enabling Bluetooth. |
|
13 |
The connection to the system service was temporarily lost. |
Try to reconnect. |
|
14 |
The client is not authorized to use Bluetooth. |
Authorize the client to use Bluetooth. |
|
15 |
Unknown error. |
- |
Code example
<!-- .axml-->
<view class="page">
<view class="page-description">Bluetooth API</view>
<view class="page-section">
<view class="page-section-title">Local Bluetooth adapter state</view>
<view class="page-section-demo">
<button type="primary" onTap="openBluetoothAdapter">Initialize Bluetooth</button>
<button type="primary" onTap="closeBluetoothAdapter">Close local Bluetooth</button>
<button type="primary" onTap="getBluetoothAdapterState">Get Bluetooth state</button>
</view>
<view class="page-section-title">Scan for Bluetooth devices</view>
<view class="page-section-demo">
<button type="primary" onTap="startBluetoothDevicesDiscovery">Start search</button>
<button type="primary" onTap="getBluetoothDevices">All discovered devices</button>
<button type="primary" onTap="getConnectedBluetoothDevices">All connected devices</button>
<button type="primary" onTap="stopBluetoothDevicesDiscovery">Stop search</button>
</view>
<view class="page-section-title">Connect to a device</view>
<view class="page-section-demo">
<input class="input" onInput="bindKeyInput" type="{{text}}" placeholder="Enter the deviceId of the device to connect to"></input>
<button type="primary" onTap="connectBLEDevice">Connect to device</button>
<button type="primary" onTap="getBLEDeviceServices">Get device services</button>
<button type="primary" onTap="getBLEDeviceCharacteristics">Get read/write characteristics</button>
<button type="primary" onTap="disconnectBLEDevice">Disconnect from device</button>
</view>
<view class="page-section-title">Read and write data</view>
<view class="page-section-demo">
<button type="primary" onTap="notifyBLECharacteristicValueChange">Listen for characteristic value changes</button>
<button type="primary" onTap="readBLECharacteristicValue">Read data</button>
<button type="primary" onTap="writeBLECharacteristicValue">Write data</button>
<button type="primary" onTap="offBLECharacteristicValueChange">Cancel characteristic value listener</button>
</view>
<view class="page-section-title">Other events</view>
<view class="page-section-demo">
<button type="primary" onTap="bluetoothAdapterStateChange">Local Bluetooth state change</button>
<button type="primary" onTap="offBluetoothAdapterStateChange">Cancel local Bluetooth state listener</button>
<button type="primary" onTap="BLEConnectionStateChanged">Bluetooth connection state change</button>
<button type="primary" onTap="offBLEConnectionStateChanged">Cancel Bluetooth connection state listener</button>
</view>
</view>
</view>// .js
Page({
data: {
devid: '0D9C82AD-1CC0-414D-9526-119E08D28124',
serid: 'FEE7',
notifyId: '36F6',
writeId: '36F5',
charid: '',
alldev: [{ deviceId: '' }],
},
// Get the local Bluetooth adapter state
openBluetoothAdapter() {
my.openBluetoothAdapter({
success: res => {
if (!res.isSupportBLE) {
my.alert({ content: 'Sorry, Bluetooth is not available on your phone.' });
return;
}
my.alert({ content: 'Initialization successful!' });
},
fail: error => {
my.alert({ content: JSON.stringify(error) });
},
});
},
closeBluetoothAdapter() {
my.closeBluetoothAdapter({
success: () => {
my.alert({ content: 'Bluetooth closed successfully!' });
},
fail: error => {
my.alert({ content: JSON.stringify(error) });
},
});
},
getBluetoothAdapterState() {
my.getBluetoothAdapterState({
success: res => {
if (!res.available) {
my.alert({ content: 'Sorry, Bluetooth is not available on your phone.' });
return;
}
my.alert({ content: JSON.stringify(res) });
},
fail: error => {
my.alert({ content: JSON.stringify(error) });
},
});
},
// Scan for Bluetooth devices
startBluetoothDevicesDiscovery() {
my.startBluetoothDevicesDiscovery({
allowDuplicatesKey: false,
success: () => {
my.onBluetoothDeviceFound({
success: res => {
// my.alert({content:'Listening for new devices'+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, then record the deviceID for later use
if (deviceObj.name == this.data.name) {
my.alert({ content: 'Target device found' });
my.offBluetoothDeviceFound();
this.setData({
deviceId: deviceObj.deviceId,
});
break;
}
}
},
fail: error => {
my.alert({ content: 'Failed to listen for new devices' + JSON.stringify(error) });
},
});
},
fail: error => {
my.alert({ content: 'Failed to start scan' + JSON.stringify(error) });
},
});
},
// Stop scanning
stopBluetoothDevicesDiscovery() {
my.stopBluetoothDevicesDiscovery({
success: res => {
my.offBluetoothDeviceFound();
my.alert({ content: 'Operation successful!' });
},
fail: error => {
my.alert({ content: JSON.stringify(error) });
},
});
},
// Get connected devices
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) });
},
});
},
// Get all discovered devices
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 to a device
connectBLEDevice() {
my.connectBLEDevice({
deviceId: this.data.devid,
success: res => {
my.alert({ content: 'Connection successful' });
},
fail: error => {
my.alert({ content: JSON.stringify(error) });
},
});
},
// Disconnect
disconnectBLEDevice() {
my.disconnectBLEDevice({
deviceId: this.data.devid,
success: () => {
my.alert({ content: 'Disconnection successful!' });
},
fail: error => {
my.alert({ content: JSON.stringify(error) });
},
});
},
// Get the services of a connected device. This must be done while 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) });
},
});
},
});
},
// Get the charid of a connected device. This must be done while connected. (This filters for read and write characteristics.)
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 document for characteristic object properties. Match and record the read/write characteristics 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 service
// 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: 'Read failed' + 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 for characteristic value changes
my.onBLECharacteristicValueChange({
success: res => {
// my.alert({content: 'Characteristic value changed: '+JSON.stringify(res)});
my.alert({ content: 'Response data received = ' + res.value });
},
});
my.alert({ content: 'Listener enabled successfully' });
},
fail: error => {
my.alert({ content: 'Failed to enable listener' + 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: 'Local Bluetooth state changed: ' + 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 state changed: ' + JSON.stringify(res) });
}
},
offBLEConnectionStateChanged() {
my.offBLEConnectionStateChanged(this.getBind('onBLEConnectionStateChanged'));
},
onUnload() {
this.offBLEConnectionStateChanged();
this.offBLECharacteristicValueChange();
this.offBluetoothAdapterStateChange();
this.closeBluetoothAdapter();
},
});
Bugs and tips
-
Bug: If Bluetooth is off or unsupported,
my.openBluetoothAdapterreturns an error (error codes: Bluetooth API Error Code Table). The Bluetooth module is still initialized, so you can usemy.onBluetoothAdapterStateChangeto listen for state changes. -
Tip: If you call other Bluetooth module APIs before calling the
my.openBluetoothAdapterAPI, an error is returned.-
Error code: 10000
-
Error description: Bluetooth adapter not initialized
-
Solution: Call
my.openBluetoothAdapter.
-
my.closeBluetoothAdapter
Shuts down the local Bluetooth module.
Input parameters
|
Name |
Type |
Required |
Description |
|
success |
Function |
No |
Called on success. |
|
fail |
Function |
No |
Called on failure. |
|
complete |
Function |
No |
Called when the call completes, regardless of outcome. |
Code example
my.closeBluetoothAdapter({
success: (res) => {
},
fail:(res) => {
},
complete: (res)=>{
}
});
Bugs and tips
-
Tip: Calling this method disconnects all established Bluetooth connections and releases system resources.
-
Tip: Call this method when the miniapp Bluetooth process ends. It should be paired with
my.openBluetoothAdapter. -
Tip:
my.closeBluetoothAdapteris asynchronous. Do not callmy.closeBluetoothAdapterfollowed bymy.openBluetoothAdapterin exception handling — this causes thread synchronization issues.
my.getBluetoothAdapterState
Retrieves the state of the local Bluetooth module.
Input parameters
|
Name |
Type |
Required |
Description |
|
success |
Function |
No |
Called on success. |
|
fail |
Function |
No |
Called on failure. |
|
complete |
Function |
No |
Called when the call completes, regardless of outcome. |
Success return value
|
Name |
Type |
Description |
|
discovering |
Boolean |
Whether a device search is in progress. |
|
available |
Boolean |
Whether the Bluetooth module is available (device supports BLE and Bluetooth is enabled). |
Code example
my.getBluetoothAdapterState({
success: (res) => {
console.log(res)
},
fail:(res) => {
},
complete: (res)=>{
}
});
my.startBluetoothDevicesDiscovery
Starts searching for nearby Bluetooth peripheral devices. Results are returned in the my.onBluetoothDeviceFound event.
Input parameters
|
Name |
Type |
Required |
Description |
|
services |
Array |
No |
A list of primary service UUIDs of the Bluetooth device. |
|
allowDuplicatesKey |
Boolean |
No |
Whether to report the same device multiple times. If true, |
|
interval |
Integer |
No |
Reporting interval. Default: 0 (report immediately). Non-zero values batch reports at the specified interval. |
|
success |
Function |
No |
Called on success. |
|
fail |
Function |
No |
Called on failure. |
|
complete |
Function |
No |
Called when the call completes, regardless of outcome. |
Code example
my.startBluetoothDevicesDiscovery({
services: ['fff0'],
success: (res) => {
console.log(res)
},
fail:(res) => {
},
complete: (res)=>{
}
});
Bugs and tips
-
Tip: Device discovery consumes significant resources. Call
stopafter finding and connecting to the target device.
my.stopBluetoothDevicesDiscovery
Stops searching for nearby Bluetooth peripheral devices.
Input parameters
|
Name |
Type |
Required |
Description |
|
success |
Function |
No |
Called on success. |
|
fail |
Function |
No |
Called on failure. |
|
complete |
Function |
No |
Called when the call completes, regardless of outcome. |
Code example
my.stopBluetoothDevicesDiscovery({
success: (res) => {
console.log(res)
},
fail:(res) => {
},
complete: (res)=>{
}
});
my.getBluetoothDevices
Retrieves all discovered Bluetooth devices, including those already connected.
Input parameters
|
Name |
Type |
Required |
Description |
|
success |
Function |
No |
Called on success. |
|
fail |
Function |
No |
Called on failure. |
|
complete |
Function |
No |
Called when the call completes, regardless of outcome. |
Success return value
|
Name |
Type |
Description |
|
devices |
Array |
A list of discovered devices. |
device object
|
Name |
Type |
Description |
|
name |
String |
The name of the Bluetooth device. Some devices may not have a name. |
|
deviceName (for backward compatibility) |
String |
The value is the same as |
|
localName |
String |
The broadcast device name. |
|
deviceId |
String |
The device ID. |
|
RSSI |
Number |
The signal strength of the device. |
|
advertisData |
Hex String |
The broadcast content of the device. |
|
manufacturerData |
Hex String |
The manufacturer data of the device. |
Code example
my.getBluetoothDevices({
success: (res) => {
console.log(res)
},
fail:(res) => {
},
complete: (res)=>{
}
});
Bugs and tips
-
Tip: The emulator may not be able to retrieve
advertisDataandRSSI. Use a physical device for debugging. -
Tip: On Android,
deviceIdis the MAC address; on iOS, it is the UUID. Do not hard-codedeviceId. On iOS, match devices dynamically bylocalName,advertisData, ormanufacturerData.
my.getConnectedBluetoothDevices
Retrieves all connected devices.
Input parameters
|
Name |
Type |
Required |
Description |
|
deviceId |
String |
No |
The Bluetooth device ID. |
|
success |
Function |
No |
Called on success. |
|
fail |
Function |
No |
Called on failure. |
|
complete |
Function |
No |
Called when the call completes, regardless of outcome. |
Code example
my.getConnectedBluetoothDevices({
success: (res) => {
console.log(res)
},
fail:(res) => {
},
complete: (res)=>{
}
});
Bugs and tips
-
Tip: If the miniapp has previously discovered a Bluetooth device, you can directly pass the
deviceIdobtained from the search to connect to the device without searching again. -
Tip: If the specified Bluetooth device is already connected, reconnecting will directly return
success.
my.connectBLEDevice
Connects to a Bluetooth Low Energy (BLE) device.
Input parameters
|
Name |
Type |
Required |
Description |
|
deviceId |
String |
Yes |
The Bluetooth device ID. |
|
success |
Function |
No |
Called on success. |
|
fail |
Function |
No |
Called on failure. |
|
complete |
Function |
No |
Called when the call completes, regardless of outcome. |
Code example
my.connectBLEDevice({
// The deviceId here needs to be obtained from the getBluetoothDevices or onBluetoothDeviceFound API.
deviceId: deviceId,
success: (res) => {
console.log(res)
},
fail:(res) => {
},
complete: (res)=>{
}
});
Bugs and tips
-
Tip: If the miniapp has previously discovered a Bluetooth device, you can directly pass the
deviceIdobtained from the search to connect to the device without searching again. -
Tip: If the specified Bluetooth device is already connected, reconnecting will directly return success.
-
Tip: This feature is supported on iOS clients and Android 5.0 or later clients.
my.disconnectBLEDevice
Disconnects from a BLE device.
Input parameters
|
Name |
Type |
Required |
Description |
|
deviceId |
String |
Yes |
The Bluetooth device ID. |
|
success |
Function |
No |
Called on success. |
|
fail |
Function |
No |
Called on failure. |
|
complete |
Function |
No |
Called when the call completes, regardless of outcome. |
Code example
my.disconnectBLEDevice({
deviceId: deviceId,
success: (res) => {
console.log(res)
},
fail:(res) => {
},
complete: (res)=>{
}
});
Bugs and tips
-
Tip: A Bluetooth connection can be lost at any time. Listen for the
my.onBLEConnectionStateChangedcallback event to reconnect as needed. -
Tip: Calling a read/write API on an unconnected device returns error 10006 (Bluetooth API Error Code Table). Reconnect before retrying.
-
Tip: This feature is supported on iOS clients and Android 5.0 or later clients.
my.writeBLECharacteristicValue
Writes data to a characteristic of a BLE device.
Input parameters
|
Name |
Type |
Required |
Description |
|
deviceId |
String |
Yes |
The Bluetooth device ID. See the |
|
serviceId |
String |
Yes |
The UUID of the |
|
characteristicId |
String |
Yes |
The UUID of the Bluetooth characteristic. |
|
value |
Hex String |
Yes |
The hex-encoded value to write. Limited to 20 bytes. |
|
success |
Function |
No |
Called on success. |
|
fail |
Function |
No |
Called on failure. |
|
complete |
Function |
No |
Called when the call completes, regardless of outcome. |
Code example
my.writeBLECharacteristicValue({
deviceId: deviceId,
serviceId: serviceId,
characteristicId: characteristicId,
value: 'fffe',
success: (res) => {
console.log(res)
},
fail:(res) => {
},
complete: (res)=>{
}
});
Bugs and tips
-
Tip: The device characteristic must support the write operation for this call to succeed. Check the
propertiesattribute of the characteristic. -
Tip: The binary data to be written must be hex-encoded.
-
Tip: This feature is supported on iOS clients and Android 5.0 or later clients.
my.readBLECharacteristicValue
Reads data from a characteristic of a BLE device. Data is returned in the my.onBLECharacteristicValueChange() event.
Input parameters
|
Name |
Type |
Required |
Description |
|
deviceId |
String |
Yes |
The Bluetooth device ID. See the |
|
serviceId |
String |
Yes |
The UUID of the |
|
characteristicId |
String |
Yes |
The UUID of the Bluetooth characteristic. |
|
success |
Function |
No |
Called on success. |
|
fail |
Function |
No |
Called on failure. |
|
complete |
Function |
No |
Called when the call completes, regardless of outcome. |
Success return value
|
Name |
Type |
Description |
|
characteristic |
Object |
The device characteristic information. |
characteristic object
Information about a Bluetooth device characteristic.
|
Name |
Type |
Description |
|
characteristicId |
String |
The UUID of the Bluetooth device characteristic. |
|
serviceId |
String |
The UUID of the service that the characteristic belongs to. |
|
value |
Hex String |
The value of the Bluetooth device characteristic. |
Code example
my.readBLECharacteristicValue({
deviceId: deviceId,
serviceId: serviceId,
characteristicId: characteristicId,
success: (res) => {
console.log(res)
},
fail:(res) => {
},
complete: (res)=>{
}
});
Bugs and tips
-
Tip: The device characteristic must support the read operation for this call to succeed. Check the
propertiesattribute of the characteristic. -
Tip: Calling read and write APIs in parallel may cause failures.
-
Tip: If a read times out (error 10015),
my.onBLECharacteristicValueChangemay still return data later — handle this case. Error codes and solutions: Bluetooth API Error Code Reference. -
Tip: This feature is supported on iOS clients and Android 5.0 or later clients.
my.notifyBLECharacteristicValueChange
Enables the notify feature for characteristic value changes on a BLE device.
Input parameters
|
Name |
Type |
Required |
Description |
|
deviceId |
String |
Yes |
The Bluetooth device ID. 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 notify or indicate. |
|
success |
Function |
No |
Called on success. |
|
fail |
Function |
No |
Called on failure. |
|
complete |
Function |
No |
Called when the call completes, regardless of outcome. |
Code example
my.notifyBLECharacteristicValueChange({
deviceId: deviceId,
serviceId: serviceId,
characteristicId: characteristicId,
success: (res) => {
console.log(res)
},
fail:(res) => {
},
complete: (res)=>{
}
});
Bugs and tips
-
Tip: The device characteristic must support notify or indicate for this call to succeed. Check the
propertiesattribute of thecharacteristic. -
Tip: You must enable notify before you can listen for the device's
characteristicValueChangeevent. -
Tip: After a successful subscription, the device must actively update the characteristic's value to trigger
my.onBLECharacteristicValueChange. -
Tip: Subscribing is more efficient than polling with read. Prefer subscriptions.
my.getBLEDeviceServices
Retrieves all services of a connected BLE device.
Input parameters
|
Name |
Type |
Required |
Description |
|
deviceId |
String |
Yes |
The Bluetooth device ID. See the |
|
success |
Function |
No |
Called on success. |
|
fail |
Function |
No |
Called on failure. |
|
complete |
Function |
No |
Called when the call completes, regardless of outcome. |
Success return value
|
Name |
Type |
Description |
|
services |
Array |
A list of discovered device services. See the following table for characteristic information. |
service object
Information about a Bluetooth device service.
|
Name |
Type |
Description |
|
serviceId |
String |
The UUID of the Bluetooth device service. |
|
isPrimary |
Boolean |
Indicates whether this is a primary service.
|
Code example
// Get the services of a connected device. This must be done while 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) });
},
});
},
});
},
Return value sample
{
"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"
}]
}
Bugs and tips
-
Tip: After you establish a connection, execute
my.getBLEDeviceServicesandmy.getBLEDeviceCharacteristicsbefore you interact with the Bluetooth device. -
Tip: This feature is supported on iOS clients and Android 5.0 or later clients.
my.getBLEDeviceCharacteristics
Retrieves all characteristics of a connected BLE device.
Input parameters
|
Name |
Type |
Required |
Description |
|
deviceId |
String |
Yes |
The Bluetooth device ID. See the |
|
serviceId |
String |
Yes |
The UUID of the |
|
success |
Function |
No |
Called on success. |
|
fail |
Function |
No |
Called on failure. |
|
complete |
Function |
No |
Called when the call completes, regardless of outcome. |
Success return value
|
Name |
Type |
Description |
|
characteristics |
Array |
A list of device characteristics. |
characteristic object
Information about a Bluetooth device characteristic.
|
Name |
Type |
Description |
|
characteristicId |
String |
The UUID of the Bluetooth device characteristic. |
|
serviceId |
String |
The UUID of the service that the characteristic belongs to. |
|
value |
Hex String |
The hex value of the Bluetooth device characteristic. |
|
properties |
Object |
The operations supported by this characteristic. |
properties object
|
Name |
Type |
Description |
|
read |
Boolean |
Indicates whether this characteristic supports the read operation. |
|
write |
Boolean |
Indicates whether this characteristic supports the write operation. |
|
notify |
Boolean |
Indicates whether this characteristic supports the notify operation. |
|
indicate |
Boolean |
Indicates whether this characteristic supports the indicate operation. |
Code example
my.getBLEDeviceCharacteristics({
deviceId: deviceId,
serviceId: serviceId,
success: (res) => {
console.log(res)
},
fail:(res) => {
},
complete: (res)=>{
}
});
Bugs and tips
-
Tip: After you establish a connection, execute
my.getBLEDeviceServicesandmy.getBLEDeviceCharacteristicsbefore you interact with the Bluetooth device. -
Tip: This feature is supported on iOS clients and Android 5.0 or later clients.
my.onBluetoothDeviceFound(callback)
This event is triggered when a new Bluetooth device is discovered.
Input parameters
|
Name |
Type |
Required |
Description |
|
callback |
Function |
Yes |
The callback function for the event. |
Callback return value
|
Name |
Type |
Description |
|
devices |
Array |
A list of newly discovered devices. |
device object
|
Name |
Type |
Description |
|
name |
String |
The name of the Bluetooth device. Some devices may not have a name. |
|
deviceName (for backward compatibility) |
String |
The value is the same as |
|
localName |
String |
The broadcast device name. |
|
deviceId |
String |
The device ID. |
|
RSSI |
Number |
The signal strength of the device. |
|
advertisData |
Hex String |
The broadcast content of the device. |
Code example
Page({
onLoad() {
this.callback = this.callback.bind(this);
my.onBluetoothDeviceFound(this.callback);
},
onUnload() {
my.offBluetoothDeviceFound(this.callback);
},
callback(res) {
console.log(res);
},
})
Bugs and tips
-
Tip: The emulator may not be able to retrieve
advertisDataandRSSI. Use a physical device for debugging. -
Tip: On Android, deviceId is the MAC address; on iOS, it is the UUID. Do not hard-code deviceId. On iOS, match devices dynamically by
localName,advertisData, ormanufacturerData. -
Tip: When the
my.onBluetoothDeviceFoundcallback finds a Bluetooth device, the device is added to the array returned by themy.getBluetoothDevicesAPI.
my.offBluetoothDeviceFound
Removes the listener for the new Bluetooth device discovery event.
Code example
my.offBluetoothDeviceFound();
Whether to pass a callback value
-
If you do not pass a callback value, all listeners for this event are removed. The following code provides an example:
my.offBluetoothDeviceFound(); -
If you pass a callback value, only the corresponding listener is removed. The following code provides an example:
my.offBluetoothDeviceFound(this.callback);
Bugs and tips
-
Tip: To prevent multiple callbacks for the same event, call the
offmethod to remove existing listeners before you call theonmethod.
my.onBLECharacteristicValueChange(callback)
Listens for characteristic value changes on a BLE device.
Input parameters
|
Name |
Type |
Required |
Description |
|
callback |
Function |
Yes |
The event callback function. |
Callback return value
|
Name |
Type |
Description |
|
deviceId |
String |
The Bluetooth device ID. See the |
|
connected |
Boolean |
The current connection state. |
Code example
Page({
onLoad() {
this.callback = this.callback.bind(this);
my.onBLECharacteristicValueChange(this.callback);
},
onUnload() {
my.offBLECharacteristicValueChange(this.callback);
},
callback(res) {
console.log(res);
},
})
Bugs and tips
-
Tip: To prevent multiple callbacks for a single event, call the
offmethod to remove existing listeners before calling theonmethod.
my.offBLECharacteristicValueChange
Removes the listener for characteristic value changes on a BLE device.
Input parameters
The type is a callback function whose input parameter is an Object with the following properties:
|
Property |
Type |
Description |
|
deviceId |
String |
The Bluetooth device ID. See the |
|
serviceId |
String |
The UUID of the |
|
characteristicId |
String |
The UUID of the Bluetooth characteristic. |
|
value |
Hex String |
The latest hex value of the characteristic. |
Passing a callback value
-
If you do not pass a callback value, all listeners for this event are removed. The following code provides an example:
my.offBLECharacteristicValueChange(); -
If you pass a callback value, only the corresponding listener is removed. The following code provides an example:
my.offBLECharacteristicValueChange(this.callback);
Code example
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)
Listens for BLE connection error events, including device loss and abnormal disconnections.
Input parameters
|
Name |
Type |
Required |
Description |
|
callback |
Function |
Yes |
The event callback function. |
Callback return value
|
Name |
Type |
Description |
|
deviceId |
String |
The Bluetooth device ID. See the |
|
connected |
Boolean |
The current connection state. |
Code example
/* .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">Local Bluetooth adapter state</view>
<view class="page-section-demo">
<button type="primary" onTap="openBluetoothAdapter">Initialize Bluetooth</button>
<button type="primary" onTap="closeBluetoothAdapter">Close local Bluetooth</button>
<button type="primary" onTap="getBluetoothAdapterState">Get Bluetooth state</button>
</view>
<view class="page-section-title">Scan for Bluetooth devices</view>
<view class="page-section-demo">
<button type="primary" onTap="startBluetoothDevicesDiscovery">Start search</button>
<button type="primary" onTap="getBluetoothDevices">All discovered devices</button>
<button type="primary" onTap="getConnectedBluetoothDevices">All connected devices</button>
<button type="primary" onTap="stopBluetoothDevicesDiscovery">Stop search</button>
</view>
<view class="page-section-title">Connect to a device</view>
<view class="page-section-demo">
<input class="input" onInput="bindKeyInput" type="{{text}}" placeholder="Enter the deviceId of the device to connect to"></input>
<button type="primary" onTap="connectBLEDevice">Connect to device</button>
<button type="primary" onTap="getBLEDeviceServices">Get device services</button>
<button type="primary" onTap="getBLEDeviceCharacteristics">Get read/write characteristics</button>
<button type="primary" onTap="disconnectBLEDevice">Disconnect from device</button>
</view>
<view class="page-section-title">Read and write data</view>
<view class="page-section-demo">
<button type="primary" onTap="notifyBLECharacteristicValueChange">Listen for characteristic value changes</button>
<button type="primary" onTap="readBLECharacteristicValue">Read data</button>
<button type="primary" onTap="writeBLECharacteristicValue">Write data</button>
<button type="primary" onTap="offBLECharacteristicValueChange">Cancel characteristic value listener</button>
</view>
<view class="page-section-title">Other events</view>
<view class="page-section-demo">
<button type="primary" onTap="bluetoothAdapterStateChange">Local Bluetooth state change</button>
<button type="primary" onTap="offBluetoothAdapterStateChange">Cancel local Bluetooth state listener</button>
<button type="primary" onTap="BLEConnectionStateChanged">Bluetooth connection state change</button>
<button type="primary" onTap="offBLEConnectionStateChanged">Cancel Bluetooth connection state listener</button>
</view>
</view>
</view>// .js
Page({
data: {
devid: '0D9C82AD-1CC0-414D-9526-119E08D28124',
serid: 'FEE7',
notifyId: '36F6',
writeId: '36F5',
charid: '',
alldev: [{ deviceId: '' }],
},
// Get the local Bluetooth adapter state
openBluetoothAdapter() {
my.openBluetoothAdapter({
success: res => {
if (!res.isSupportBLE) {
my.alert({ content: 'Sorry, Bluetooth is not available on your phone.' });
return;
}
my.alert({ content: 'Initialization successful!' });
},
fail: error => {
my.alert({ content: JSON.stringify(error) });
},
});
},
closeBluetoothAdapter() {
my.closeBluetoothAdapter({
success: () => {
my.alert({ content: 'Bluetooth closed successfully!' });
},
fail: error => {
my.alert({ content: JSON.stringify(error) });
},
});
},
getBluetoothAdapterState() {
my.getBluetoothAdapterState({
success: res => {
if (!res.available) {
my.alert({ content: 'Sorry, Bluetooth is not available on your phone.' });
return;
}
my.alert({ content: JSON.stringify(res) });
},
fail: error => {
my.alert({ content: JSON.stringify(error) });
},
});
},
// Scan for Bluetooth devices
startBluetoothDevicesDiscovery() {
my.startBluetoothDevicesDiscovery({
allowDuplicatesKey: false,
success: () => {
my.onBluetoothDeviceFound({
success: res => {
// my.alert({content:'Listening for new devices'+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, then record the deviceID for later use
if (deviceObj.name == this.data.name) {
my.alert({ content: 'Target device found' });
my.offBluetoothDeviceFound();
this.setData({
deviceId: deviceObj.deviceId,
});
break;
}
}
},
fail: error => {
my.alert({ content: 'Failed to listen for new devices' + JSON.stringify(error) });
},
});
},
fail: error => {
my.alert({ content: 'Failed to start scan' + JSON.stringify(error) });
},
});
},
// Stop scanning
stopBluetoothDevicesDiscovery() {
my.stopBluetoothDevicesDiscovery({
success: res => {
my.offBluetoothDeviceFound();
my.alert({ content: 'Operation successful!' });
},
fail: error => {
my.alert({ content: JSON.stringify(error) });
},
});
},
// Get connected devices
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) });
},
});
},
// Get all discovered devices
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 to a device
connectBLEDevice() {
my.connectBLEDevice({
deviceId: this.data.devid,
success: res => {
my.alert({ content: 'Connection successful' });
},
fail: error => {
my.alert({ content: JSON.stringify(error) });
},
});
},
// Disconnect
disconnectBLEDevice() {
my.disconnectBLEDevice({
deviceId: this.data.devid,
success: () => {
my.alert({ content: 'Disconnection successful!' });
},
fail: error => {
my.alert({ content: JSON.stringify(error) });
},
});
},
// Get the services of a connected device. This must be done while 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) });
},
});
},
});
},
// Get the charid of a connected device. This must be done while connected. (This filters for read and write characteristics.)
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 document for characteristic object properties. Match and record the read/write characteristics 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 service
// 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: 'Read failed' + 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 for characteristic value changes
my.onBLECharacteristicValueChange({
success: res => {
// my.alert({content: 'Characteristic value changed: '+JSON.stringify(res)});
my.alert({ content: 'Response data received = ' + res.value });
},
});
my.alert({ content: 'Listener enabled successfully' });
},
fail: error => {
my.alert({ content: 'Failed to enable listener' + 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: 'Local Bluetooth state changed: ' + 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 state changed: ' + JSON.stringify(res) });
}
},
offBLEConnectionStateChanged() {
my.offBLEConnectionStateChanged(this.getBind('onBLEConnectionStateChanged'));
},
onUnload() {
this.offBLEConnectionStateChanged();
this.offBLECharacteristicValueChange();
this.offBluetoothAdapterStateChange();
this.closeBluetoothAdapter();
},
});
Bugs and tips
-
Tip: To prevent multiple callbacks for a single event, call the
offmethod to remove previous listeners before calling theonmethod.
my.offBLEConnectionStateChanged
Removes the listener for BLE connection state changes.
Code example
my.offBLEConnectionStateChanged();
Is passing a callback value required?
-
If you do not pass a callback value, all listeners for this event are removed. The following code provides an example:
my.offBLEConnectionStateChanged(); -
If you pass a callback value, only the corresponding listener is removed. The following code provides an example:
my.offBLEConnectionStateChanged(this.callback);
Bugs and tips
-
Tip: To prevent multiple callbacks for a single event, call the
offmethod to remove previous listeners before calling theonmethod.
my.onBluetoothAdapterStateChange(callback)
Listens for changes in the local Bluetooth adapter state.
Input parameters
|
Name |
Type |
Required |
Description |
|
callback |
Function |
Yes |
The event callback function. |
Callback return value
|
Name |
Type |
Description |
|
available |
Boolean |
Is the Bluetooth module active? |
|
discovering |
Boolean |
Whether a device search is in progress. |
Code example
/* .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">Local Bluetooth adapter state</view>
<view class="page-section-demo">
<button type="primary" onTap="openBluetoothAdapter">Initialize Bluetooth</button>
<button type="primary" onTap="closeBluetoothAdapter">Close local Bluetooth</button>
<button type="primary" onTap="getBluetoothAdapterState">Get Bluetooth state</button>
</view>
<view class="page-section-title">Scan for Bluetooth devices</view>
<view class="page-section-demo">
<button type="primary" onTap="startBluetoothDevicesDiscovery">Start search</button>
<button type="primary" onTap="getBluetoothDevices">All discovered devices</button>
<button type="primary" onTap="getConnectedBluetoothDevices">All connected devices</button>
<button type="primary" onTap="stopBluetoothDevicesDiscovery">Stop search</button>
</view>
<view class="page-section-title">Connect to a device</view>
<view class="page-section-demo">
<input class="input" onInput="bindKeyInput" type="{{text}}" placeholder="Enter the deviceId of the device to connect to"></input>
<button type="primary" onTap="connectBLEDevice">Connect to device</button>
<button type="primary" onTap="getBLEDeviceServices">Get device services</button>
<button type="primary" onTap="getBLEDeviceCharacteristics">Get read/write characteristics</button>
<button type="primary" onTap="disconnectBLEDevice">Disconnect from device</button>
</view>
<view class="page-section-title">Read and write data</view>
<view class="page-section-demo">
<button type="primary" onTap="notifyBLECharacteristicValueChange">Listen for characteristic value changes</button>
<button type="primary" onTap="readBLECharacteristicValue">Read data</button>
<button type="primary" onTap="writeBLECharacteristicValue">Write data</button>
<button type="primary" onTap="offBLECharacteristicValueChange">Cancel characteristic value listener</button>
</view>
<view class="page-section-title">Other events</view>
<view class="page-section-demo">
<button type="primary" onTap="bluetoothAdapterStateChange">Local Bluetooth state change</button>
<button type="primary" onTap="offBluetoothAdapterStateChange">Cancel local Bluetooth state listener</button>
<button type="primary" onTap="BLEConnectionStateChanged">Bluetooth connection state change</button>
<button type="primary" onTap="offBLEConnectionStateChanged">Cancel Bluetooth connection state listener</button>
</view>
</view>
</view>// .js
Page({
data: {
devid: '0D9C82AD-1CC0-414D-9526-119E08D28124',
serid: 'FEE7',
notifyId: '36F6',
writeId: '36F5',
charid: '',
alldev: [{ deviceId: '' }],
},
// Get the local Bluetooth adapter state
openBluetoothAdapter() {
my.openBluetoothAdapter({
success: res => {
if (!res.isSupportBLE) {
my.alert({ content: 'Sorry, Bluetooth is not available on your phone.' });
return;
}
my.alert({ content: 'Initialization successful!' });
},
fail: error => {
my.alert({ content: JSON.stringify(error) });
},
});
},
closeBluetoothAdapter() {
my.closeBluetoothAdapter({
success: () => {
my.alert({ content: 'Bluetooth closed successfully!' });
},
fail: error => {
my.alert({ content: JSON.stringify(error) });
},
});
},
getBluetoothAdapterState() {
my.getBluetoothAdapterState({
success: res => {
if (!res.available) {
my.alert({ content: 'Sorry, Bluetooth is not available on your phone.' });
return;
}
my.alert({ content: JSON.stringify(res) });
},
fail: error => {
my.alert({ content: JSON.stringify(error) });
},
});
},
// Scan for Bluetooth devices
startBluetoothDevicesDiscovery() {
my.startBluetoothDevicesDiscovery({
allowDuplicatesKey: false,
success: () => {
my.onBluetoothDeviceFound({
success: res => {
// my.alert({content:'Listening for new devices'+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, then record the deviceID for later use
if (deviceObj.name == this.data.name) {
my.alert({ content: 'Target device found' });
my.offBluetoothDeviceFound();
this.setData({
deviceId: deviceObj.deviceId,
});
break;
}
}
},
fail: error => {
my.alert({ content: 'Failed to listen for new devices' + JSON.stringify(error) });
},
});
},
fail: error => {
my.alert({ content: 'Failed to start scan' + JSON.stringify(error) });
},
});
},
// Stop scanning
stopBluetoothDevicesDiscovery() {
my.stopBluetoothDevicesDiscovery({
success: res => {
my.offBluetoothDeviceFound();
my.alert({ content: 'Operation successful!' });
},
fail: error => {
my.alert({ content: JSON.stringify(error) });
},
});
},
// Get connected devices
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) });
},
});
},
// Get all discovered devices
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 to a device
connectBLEDevice() {
my.connectBLEDevice({
deviceId: this.data.devid,
success: res => {
my.alert({ content: 'Connection successful' });
},
fail: error => {
my.alert({ content: JSON.stringify(error) });
},
});
},
// Disconnect
disconnectBLEDevice() {
my.disconnectBLEDevice({
deviceId: this.data.devid,
success: () => {
my.alert({ content: 'Disconnection successful!' });
},
fail: error => {
my.alert({ content: JSON.stringify(error) });
},
});
},
// Get the services of a connected device. This must be done while 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) });
},
});
},
});
},
// Get the charid of a connected device. This must be done while connected. (This filters for read and write characteristics.)
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 document for characteristic object properties. Match and record the read/write characteristics 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 service
// 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: 'Read failed' + 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 for characteristic value changes
my.onBLECharacteristicValueChange({
success: res => {
// my.alert({content: 'Characteristic value changed: '+JSON.stringify(res)});
my.alert({ content: 'Response data received = ' + res.value });
},
});
my.alert({ content: 'Listener enabled successfully' });
},
fail: error => {
my.alert({ content: 'Failed to enable listener' + 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: 'Local Bluetooth state changed: ' + 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 state changed: ' + JSON.stringify(res) });
}
},
offBLEConnectionStateChanged() {
my.offBLEConnectionStateChanged(this.getBind('onBLEConnectionStateChanged'));
},
onUnload() {
this.offBLEConnectionStateChanged();
this.offBLECharacteristicValueChange();
this.offBluetoothAdapterStateChange();
this.closeBluetoothAdapter();
},
});
my.offBluetoothAdapterStateChange
Removes the listener for local Bluetooth state changes.
Code example
my.offBluetoothAdapterStateChange();
Whether to pass a callback value
-
If you do not pass a callback value, all listeners for this event are removed. The following code provides an example:
my.offBluetoothAdapterStateChange(); -
If you pass a callback value, only the corresponding listener is removed. The following code provides an example:
my.offBluetoothAdapterStateChange(this.callback);
Bugs and tips
-
Tip: To prevent duplicate callbacks for an event, call the
offmethod to remove any existing listeners before you call theonmethod.