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. The initialization is 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 miniapp Bluetooth APIs and receive on event callbacks related to the Bluetooth module.
Input parameters
Name | Type | Required | Description |
autoClose | Boolean | No | Specifies whether to automatically disconnect Bluetooth when leaving the current page. If not specified, the default value is true. Important This feature is only supported on Android. |
success | Function | No | The callback function for a successful call. |
fail | Function | No | The callback function for a failed call. |
complete | Function | No | The callback function executed at the end of the call, regardless of whether the call is successful or fails. |
Success return value
Name | Type | Description |
isSupportBLE | Boolean | Indicates whether Bluetooth Low Energy (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 the user's Bluetooth is turned off or their phone does not support Bluetooth, calling
my.openBluetoothAdapterreturns an error. For more information about the error codes, see the Bluetooth API Error Code Table. At this point, the miniapp's Bluetooth module is already initialized, and you can usemy.onBluetoothAdapterStateChangeto listen for changes in the phone's Bluetooth state.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 | The callback function for a successful call. |
fail | Function | No | The callback function for a failed call. |
complete | Function | No | The callback function executed at the end of the call, regardless of whether the call is successful or fails. |
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: Releasing resources by calling
my.closeBluetoothAdapteris an asynchronous operation. Do not usemy.closeBluetoothAdapterandmy.openBluetoothAdapterin an exception handling flow. This is equivalent to closing and then reopening to re-initialize, which is inefficient and can cause thread synchronization issues.
my.getBluetoothAdapterState
Retrieves the state of the local Bluetooth module.
Input parameters
Name | Type | Required | Description |
success | Function | No | The callback function for a successful call. |
fail | Function | No | The callback function for a failed call. |
complete | Function | No | The callback function executed at the end of the call, regardless of whether the call is successful or fails. |
Success return value
Name | Type | Description |
discovering | Boolean | Is a device search in progress? |
available | Boolean | Indicates whether the Bluetooth module is available. The device must support BLE and have Bluetooth enabled. |
Code example
my.getBluetoothAdapterState({
success: (res) => {
console.log(res)
},
fail:(res) => {
},
complete: (res)=>{
}
});my.startBluetoothDevicesDiscovery
Starts searching for nearby Bluetooth peripheral devices. The search 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 | Specifies whether to report the same device multiple times. If set to true, the |
interval | Integer | No | The interval for reporting devices. The default value is 0, which means a new device is reported immediately after it is found. Otherwise, devices are reported at the specified interval. |
success | Function | No | The callback function for a successful call. |
fail | Function | No | The callback function for a failed call. |
complete | Function | No | The callback function executed at the end of the call, regardless of whether the call is successful or fails. |
Code example
my.startBluetoothDevicesDiscovery({
services: ['fff0'],
success: (res) => {
console.log(res)
},
fail:(res) => {
},
complete: (res)=>{
}
});Bugs and tips
Tip: This operation consumes significant system resources. Call the
stopmethod to stop the search after you find and connect to a device.
my.stopBluetoothDevicesDiscovery
Stops searching for nearby Bluetooth peripheral devices.
Input parameters
Name | Type | Required | Description |
success | Function | No | The callback function for a successful call. |
fail | Function | No | The callback function for a failed call. |
complete | Function | No | The callback function executed at the end of the call, regardless of whether the call is successful or fails. |
Code example
my.stopBluetoothDevicesDiscovery({
success: (res) => {
console.log(res)
},
fail:(res) => {
},
complete: (res)=>{
}
});my.getBluetoothDevices
Retrieves all discovered Bluetooth devices, including those already connected to the local device.
Input parameters
Name | Type | Required | Description |
success | Function | No | The callback function for a successful call. |
fail | Function | No | The callback function for a failed call. |
complete | Function | No | The callback function executed at the end of the call, regardless of whether the call is successful or fails. |
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: The
deviceIdobtained from developer tools and Android is the device's MAC address. On iOS, it is the device's UUID. Therefore, do not hard-code thedeviceId. You must handle it differently for each platform. On iOS, you can dynamically match the device based on its properties, such aslocalName,advertisData, ormanufacturerData.
my.getConnectedBluetoothDevices
Retrieves all connected devices.
Input parameters
Name | Type | Required | Description |
deviceId | String | No | The Bluetooth device ID. |
success | Function | No | The callback function for a successful call. |
fail | Function | No | The callback function for a failed call. |
complete | Function | No | The callback function executed at the end of the call, regardless of whether the call is successful or fails. |
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 | The callback function for a successful call. |
fail | Function | No | The callback function for a failed call. |
complete | Function | No | The callback function executed at the end of the call, regardless of whether the call is successful or fails. |
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 | The callback function for a successful call. |
fail | Function | No | The callback function for a failed call. |
complete | Function | No | The callback function executed at the end of the call, regardless of whether the call is successful or fails. |
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: If you call a data read/write API for an unconnected or disconnected device, error 10006 is returned. For more information, see the Bluetooth API Error Code Table. We recommend that you reconnect.
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 value for the characteristic, as a hex string. The value is limited to 20 bytes. |
success | Function | No | The callback function for a successful call. |
fail | Function | No | The callback function for a failed call. |
complete | Function | No | The callback function executed at the end of the call, regardless of whether the call is successful or fails. |
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. After the call, the 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 | The callback function for a successful call. |
fail | Function | No | The callback function for a failed call. |
complete | Function | No | The callback function executed at the end of the call, regardless of whether the call is successful or fails. |
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 operation times out with error code 10015, the
my.onBLECharacteristicValueChangeinterface may still return data later, which you must handle accordingly. For more information about error codes and solutions, see the 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 | Specifies whether to enable notify or indicate. |
success | Function | No | The callback function for a successful call. |
fail | Function | No | The callback function for a failed call. |
complete | Function | No | The callback function executed at the end of the call, regardless of whether the call is successful or fails. |
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 reading. We recommend that you use subscriptions instead of the read method.
my.getBLEDeviceServices
You can retrieve all discovered Bluetooth devices, including those that are already connected to the local device.
Input parameters
Name | Type | Required | Description |
deviceId | String | Yes | The Bluetooth device ID. See the |
success | Function | No | The callback function for a successful call. |
fail | Function | No | The callback function for a failed call. |
complete | Function | No | The callback function executed at the end of the call, regardless of whether the call is successful or fails. |
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
You can retrieve all characteristics of the Bluetooth 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 | The callback function for a successful call. |
fail | Function | No | The callback function for a failed call. |
complete | Function | No | The callback function executed at the end of the call, regardless of whether the call is successful or fails. |
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: The `deviceId` obtained from developer tools is the device's MAC address on Android, while on iOS, it is the device's UUID. Therefore, do not hard-code the `deviceId`. You should handle it differently for each platform. On iOS, you can dynamically match the device based on its properties, such as
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 | Indicates whether the Bluetooth module is in a searching 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();
},
});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.