All Products
Search
Document Center

Bluetooth API list

Last Updated: Feb 19, 2021
Note:
  • Bluetooth APIs are supported in mPaaS 1.60.0 and later versions.
  • Currently, debugging on developer tools is not supported. You need to use a physical device to properly call the Bluetooth API of Mini Program.

my.openBluetoothAdapter

This interface is used to initialize the Bluetooth module in the mini program, with the effective period beginning when my.openBluetoothAdapter is called and ending when my.closeBluetoothAdapter is called or the mini program is destroyed. During the effective period of the Bluetooth adapter module, developers can call the following APIs, and receive the on event callback related to the Bluetooth module.

Input parameters

Parameter Type Required Description
autoClose Boolean No Indicates whether to automatically disconnect Bluetooth when you leave the current page. The default value is true. Note, only Android is supported.
success Function No The callback function that indicates a successful call.
fail Function No The callback function that indicates a failed call.
complete Function No The callback function that indicates the call is completed (this will be executed regardless of whether the call succeeds or fails).

Return value on success

Parameter Type Description
isSupportBLE Boolean Indicates whether BLE is supported.

Error codes

Error Description Solution
12 Bluetooth is not turned on. Try again to turn on Bluetooth.
13 The connection to the system service is temporarily lost. Try again to reconnect.
14 The client does not have the permission to use Bluetooth. Authorize app to use Bluetooth.
15 Unknown error -

Code sample

 
  1. <!-- .axml-->
  2. <view class="page">
  3. <view class="page-description">Bluetooth API</view>
  4. <view class="page-section">
  5. <view class="page-section-title">Bluetooth state</view>
  6. <view class="page-section-demo">
  7. <button type="primary" onTap="openBluetoothAdapter">Initialize Bluetooth</button>
  8. <button type="primary" onTap="closeBluetoothAdapter">Close Bluetooth</button>
  9. <button type="primary" onTap="getBluetoothAdapterState">Obtain Bluetooth state</button>
  10. </view>
  11. <view class="page-section-title">Scan the Bluetooth device</view>
  12. <view class="page-section-demo">
  13. <button type="primary" onTap="startBluetoothDevicesDiscovery">Start searching</button>
  14. <button type="primary" onTap="getBluetoothDevices">All devices found</button>
  15. <button type="primary" onTap="getConnectedBluetoothDevices">All connected devices/button>
  16. <button type="primary" onTap="stopBluetoothDevicesDiscovery">Stop searching</button>
  17. </view>
  18. <view class="page-section-title">Connect the device</view>
  19. <view class="page-section-demo">
  20. <input class="input" onInput="bindKeyInput" type="{{text}}" placeholder=" Input the ID of the device to be connected"></input>
  21. <button type="primary" onTap="connectBLEDevice">Connect the device</button>
  22. <button type="primary" onTap="getBLEDeviceServices"> Obtain device services </button>
  23. <button type="primary" onTap="getBLEDeviceCharacteristics"> Obtain read and write characteristics </button>
  24. <button type="primary" onTap="disconnectBLEDevice"> Disconnect the device </button>
  25. </view>
  26. <view class="page-section-title">Read and write data</view>
  27. <view class="page-section-demo">
  28. <button type="primary" onTap="notifyBLECharacteristicValueChange">Listen to the characteristic data change</button>
  29. <button type="primary" onTap="readBLECharacteristicValue">Read data</button>
  30. <button type="primary" onTap="writeBLECharacteristicValue">Write data</button>
  31. <button type="primary" onTap="offBLECharacteristicValueChange">Cancel listening to characteristic value</button>
  32. </view>
  33. <view class="page-section-title">Other events</view>
  34. <view class="page-section-demo">
  35. <button type="primary" onTap="bluetoothAdapterStateChange">Bluetooth status change</button>
  36. <button type="primary" onTap="offBluetoothAdapterStateChange">Cancel listening to Bluetooth status</button>
  37. <button type="primary" onTap="BLEConnectionStateChanged">Bluetooth connection status changes</button>
  38. <button type="primary" onTap="offBLEConnectionStateChanged">Cancel listening to Bluetooth connection status</button>
  39. </view>
  40. </view>
  41. </view>
 
  1. // .js
  2. Page({
  3. data: {
  4. devid: '0D9C82AD-1CC0-414D-9526-119E08D28124',
  5. serid: 'FEE7',
  6. notifyId: '36F6',
  7. writeId: '36F5',
  8. charid: '',
  9. alldev: [{ deviceId: '' }],
  10. },
  11. //Obtain the Bluetooth state
  12. openBluetoothAdapter() {
  13. my.openBluetoothAdapter({
  14. success: res => {
  15. if (!res.isSupportBLE) {
  16. my.alert({ content: 'Sorry, your mobile Bluetooth is unavailable temporarily' });
  17. return;
  18. }
  19. my.alert({ content: 'Initialization succeeded!' });
  20. },
  21. fail: error => {
  22. my.alert({ content: JSON.stringify(error) });
  23. },
  24. });
  25. },
  26. closeBluetoothAdapter() {
  27. my.closeBluetoothAdapter({
  28. success: () => {
  29. my.alert({ content: 'Bluetooth closed!' });
  30. },
  31. fail: error => {
  32. my.alert({ content: JSON.stringify(error) });
  33. },
  34. });
  35. },
  36. getBluetoothAdapterState() {
  37. my.getBluetoothAdapterState({
  38. success: res => {
  39. if (!res.available) {
  40. my.alert({ content: 'Sorry, your mobile Bluetooth is unavailable temporarily' });
  41. return;
  42. }
  43. my.alert({ content: JSON.stringify(res) });
  44. },
  45. fail: error => {
  46. my.alert({ content: JSON.stringify(error) });
  47. },
  48. });
  49. },
  50. //Scan the Bluetooth device
  51. startBluetoothDevicesDiscovery() {
  52. my.startBluetoothDevicesDiscovery({
  53. allowDuplicatesKey: false,
  54. success: () => {
  55. my.onBluetoothDeviceFound({
  56. success: res => {
  57. // my.alert({content:'Listen to new device '+JSON.stringify(res)});
  58. var deviceArray = res.devices;
  59. for (var i = deviceArray.length - 1; i >= 0; i--) {
  60. var deviceObj = deviceArray[i];
  61. //Match the target device by device name or broadcast data, and then record the device ID for later use
  62. if (deviceObj.name == this.data.name) {
  63. my.alert({ content: 'Target device is found' });
  64. my.offBluetoothDeviceFound();
  65. this.setData({
  66. deviceId: deviceObj.deviceId,
  67. });
  68. break;
  69. }
  70. }
  71. },
  72. fail: error => {
  73. my.alert({ content: 'Failed to listen to new device' + JSON.stringify(error) });
  74. },
  75. });
  76. },
  77. fail: error => {
  78. my.alert({ content: 'Failed to start scanning' + JSON.stringify(error) });
  79. },
  80. });
  81. },
  82. //Stop scanning
  83. stopBluetoothDevicesDiscovery() {
  84. my.stopBluetoothDevicesDiscovery({
  85. success: res => {
  86. my.offBluetoothDeviceFound();
  87. my.alert({ content: 'Succeeded!' });
  88. },
  89. fail: error => {
  90. my.alert({ content: JSON.stringify(error) });
  91. },
  92. });
  93. },
  94. //Obtain the connected device
  95. getConnectedBluetoothDevices() {
  96. my.getConnectedBluetoothDevices({
  97. success: res => {
  98. if (res.devices.length === 0) {
  99. my.alert({ content: 'No connected devices!' });
  100. return;
  101. }
  102. my.alert({ content: JSON.stringify(res) });
  103. devid = res.devices[0].deviceId;
  104. },
  105. fail: error => {
  106. my.alert({ content: JSON.stringify(error) });
  107. },
  108. });
  109. },
  110. //Obtain all devices found
  111. getBluetoothDevices() {
  112. my.getBluetoothDevices({
  113. success: res => {
  114. my.alert({ content: JSON.stringify(res) });
  115. },
  116. fail: error => {
  117. my.alert({ content: JSON.stringify(error) });
  118. },
  119. });
  120. },
  121. bindKeyInput(e) {
  122. this.setData({
  123. devid: e.detail.value,
  124. });
  125. },
  126. //Connect the device
  127. connectBLEDevice() {
  128. my.connectBLEDevice({
  129. deviceId: this.data.devid,
  130. success: res => {
  131. my.alert({ content: 'Connected successfully' });
  132. },
  133. fail: error => {
  134. my.alert({ content: JSON.stringify(error) });
  135. },
  136. });
  137. },
  138. //Disconnect
  139. disconnectBLEDevice() {
  140. my.disconnectBLEDevice({
  141. deviceId: this.data.devid,
  142. success: () => {
  143. my.alert({ content: Disconnected successfully!' });
  144. },
  145. fail: error => {
  146. my.alert({ content: JSON.stringify(error) });
  147. },
  148. });
  149. },
  150. //Obtain the services of the connected devices. The services can only be obtained when the devices are connected.
  151. getBLEDeviceServices() {
  152. my.getConnectedBluetoothDevices({
  153. success: res => {
  154. if (res.devices.length === 0) {
  155. my.alert({ content: 'No connected devices' });
  156. return;
  157. }
  158. my.getBLEDeviceServices({
  159. deviceId: this.data.devid,
  160. success: res => {
  161. my.alert({ content: JSON.stringify(res) });
  162. this.setData({
  163. serid: res.services[0].serviceId,
  164. });
  165. },
  166. fail: error => {
  167. my.alert({ content: JSON.stringify(error) });
  168. },
  169. });
  170. },
  171. });
  172. },
  173. //Obtain the charid of the connected devices. The charid can only be obtained when the devices are connected. The read and write characteristics are respectively screened out.
  174. getBLEDeviceCharacteristics() {
  175. my.getConnectedBluetoothDevices({
  176. success: res => {
  177. if (res.devices.length === 0) {
  178. my.alert({ content: 'No connected devices' });
  179. return;
  180. }
  181. this.setData({
  182. devid: res.devices[0].deviceId,
  183. });
  184. my.getBLEDeviceCharacteristics({
  185. deviceId: this.data.devid,
  186. serviceId: this.data.serid,
  187. success: res => {
  188. my.alert({ content: JSON.stringify(res) });
  189. //See the related document for more information about the attributes of the characteristics. Match the read/write characteristics by attribute and record the value for later use.
  190. this.setData({
  191. charid: res.characteristics[0].characteristicId,
  192. });
  193. },
  194. fail: error => {
  195. my.alert({ content: JSON.stringify(error) });
  196. },
  197. });
  198. },
  199. });
  200. },
  201. //Read and write data
  202. readBLECharacteristicValue() {
  203. my.getConnectedBluetoothDevices({
  204. success: res => {
  205. if (res.devices.length === 0) {
  206. my.alert({ content: 'No connected devices' });
  207. return;
  208. }
  209. this.setData({
  210. devid: res.devices[0].deviceId,
  211. });
  212. my.readBLECharacteristicValue({
  213. deviceId: this.data.devid,
  214. serviceId: this.data.serid,
  215. characteristicId: this.data.notifyId,
  216. //1. Android read and write services
  217. // serviceId:'0000180d-0000-1000-8000-00805f9b34fb',
  218. // characteristicId:'00002a38-0000-1000-8000-00805f9b34fb',
  219. success: res => {
  220. my.alert({ content: JSON.stringify(res) });
  221. },
  222. fail: error => {
  223. my.alert({ content: 'Failed to read and write' + JSON.stringify(error) });
  224. },
  225. });
  226. },
  227. });
  228. },
  229. writeBLECharacteristicValue() {
  230. my.getConnectedBluetoothDevices({
  231. success: res => {
  232. if (res.devices.length === 0) {
  233. my.alert({ content: 'No connected devices' });
  234. return;
  235. }
  236. this.setData({
  237. devid: res.devices[0].deviceId,
  238. });
  239. my.writeBLECharacteristicValue({
  240. deviceId: this.data.devid,
  241. serviceId: this.data.serid,
  242. characteristicId: this.data.charid,
  243. //Android write service
  244. //serviceId:'0000180d-0000-1000-8000-00805f9b34fb',
  245. //characteristicId:'00002a39-0000-1000-8000-00805f9b34fb',
  246. value: 'ABCD',
  247. success: res => {
  248. my.alert({ content: 'Data written successfully!' });
  249. },
  250. fail: error => {
  251. my.alert({ content: JSON.stringify(error) });
  252. },
  253. });
  254. },
  255. });
  256. },
  257. notifyBLECharacteristicValueChange() {
  258. my.getConnectedBluetoothDevices({
  259. success: res => {
  260. if (res.devices.length === 0) {
  261. my.alert({ content: 'No connected devices' });
  262. return;
  263. }
  264. this.setData({
  265. devid: res.devices[0].deviceId,
  266. });
  267. my.notifyBLECharacteristicValueChange({
  268. state: true,
  269. deviceId: this.data.devid,
  270. serviceId: this.data.serid,
  271. characteristicId: this.data.notifyId,
  272. success: () => {
  273. //Listen to characteristic change events
  274. my.onBLECharacteristicValueChange({
  275. success: res => {
  276. // my.alert({content: 'Characteristic change:'+JSON.stringify(res)});
  277. my.alert({ content: 'Obtain the response data = ' + res.value });
  278. },
  279. });
  280. my.alert({ content: 'Listened successfully' });
  281. },
  282. fail: error => {
  283. my.alert({ content: 'Failed to listen' + JSON.stringify(error) });
  284. },
  285. });
  286. },
  287. });
  288. },
  289. offBLECharacteristicValueChange() {
  290. my.offBLECharacteristicValueChange();
  291. },
  292. //Other events
  293. bluetoothAdapterStateChange() {
  294. my.onBluetoothAdapterStateChange(this.getBind('onBluetoothAdapterStateChange'));
  295. },
  296. onBluetoothAdapterStateChange() {
  297. if (res.error) {
  298. my.alert({ content: JSON.stringify(error) });
  299. } else {
  300. my.alert({ content: 'Bluetooth status change: ' + JSON.stringify(res) });
  301. }
  302. },
  303. offBluetoothAdapterStateChange() {
  304. my.offBluetoothAdapterStateChange(this.getBind('onBluetoothAdapterStateChange'));
  305. },
  306. getBind(name) {
  307. if (!this[`bind${name}`]) {
  308. this[`bind${name}`] = this[name].bind(this);
  309. }
  310. return this[`bind${name}`];
  311. },
  312. BLEConnectionStateChanged() {
  313. my.onBLEConnectionStateChanged(this.getBind('onBLEConnectionStateChanged'));
  314. },
  315. onBLEConnectionStateChanged(res) {
  316. if (res.error) {
  317. my.alert({ content: JSON.stringify(error) });
  318. } else {
  319. my.alert({ content: 'Connection status change: ' + JSON.stringify(res) });
  320. }
  321. },
  322. offBLEConnectionStateChanged() {
  323. my.offBLEConnectionStateChanged(this.getBind('onBLEConnectionStateChanged'));
  324. },
  325. onUnload() {
  326. this.offBLEConnectionStateChanged();
  327. this.offBLECharacteristicValueChange();
  328. this.offBluetoothAdapterStateChange();
  329. this.closeBluetoothAdapter();
  330. },
  331. });

Instructions

  • If you call other APIs in the Bluetooth module before calling the API my.openBluetoothAdapter, an error will be returned:

    • Error Code: 10000
    • Error description: The Bluetooth adapter is not initialized.
    • Solution: Call the API my.openBluetoothAdapter.
  • When users do not switch on the Bluetooth or the Bluetooth function is not supported on the user’s mobile phone, an error is returned after my.openBluetoothAdapter is called. For more information about error codes, see the Bluetooth API error codes. After the Bluetooth module is initialized, you can use the API my.onBluetoothAdapterStateChange to monitor changes of the Bluetooth status.

my.closeBluetoothAdapter

This interface is used to close the Bluetooth module in the mini program.

Input parameters

Parameter Type Required Description
success Function No The callback function that indicates a successful call.
fail Function No The callback function that indicates a failed call.
complete Function No The callback function that indicates the call is completed (this will be executed regardless of whether the call succeeds or fails).

Code sample

 
  1. my.closeBluetoothAdapter({
  2. success: (res) => {
  3. },
  4. fail:(res) => {
  5. },
  6. complete: (res)=>{
  7. }
  8. });

Instructions

  • Calling this method will disconnect all established Bluetooth connections and release system resources.
  • We recommend that you call this API in pair with my.openBluetoothAdapter when ending the Bluetooth process of the Mini Program.
  • Calling my.closeBluetoothAdapter to free resources is an asynchronous operation. We do not recommend that you use my.closeBluetoothAdapter and my.openBluetoothAdapter to handle exception, because it is equivalent to turning Bluetooth off, and then turning on and reinitializing it. The whole process is inefficient and prone to thread synchronization problems.

my.getBluetoothAdapterState

Obtains the status of the Bluetooth module in the mini program.

Input parameters

Parameter Type Required Description
success Function No The callback function that indicates a successful call.
fail Function No The callback function that indicates a failed call.
complete Function No The callback function that indicates the call is completed (this will be executed regardless of whether the call succeeds or fails).

Return value on success

Parameter Type Description
discovering Boolean Indicates whether the device is searching for matching devices.
available Boolean Indicates whether the Bluetooth module is available (BLE is supported and Bluetooth is on).

Code sample

 
  1. my.getBluetoothAdapterState({
  2. success: (res) => {
  3. console.log(res)
  4. },
  5. fail:(res) => {
  6. },
  7. complete: (res)=>{
  8. }
  9. });

my.startBluetoothDevicesDiscovery

You can call this interface to start searching for nearby Bluetooth devices. The search results are returned in the my.onBluetoothDeviceFound event.

Input parameters

Parameter Type Required Description
services Array No The UUID list of the Bluetooth device’s master service.
allowDuplicatesKey Boolean No Whether to report the same device repeatedly. If yes, the onBluetoothDeviceFound method will report the same device multiple times, but the RSSI value may be different.
interval Integer No Specifies the interval for reporting devices. Default value is 0, that is, when a new device is found, it is reported immediately. Otherwise, it is reported according to the specified interval.
success Function No The callback function that indicates a successful call.
fail Function No The callback function that indicates a failed call.
complete Function No The callback function that indicates the call is completed (this will be executed regardless of whether the call succeeds or fails).

Code sample

 
  1. my.startBluetoothDevicesDiscovery({
  2. services: ['fff0'],
  3. success: (res) => {
  4. console.log(res)
  5. },
  6. fail:(res) => {
  7. },
  8. complete: (res)=>{
  9. }
  10. });

Instructions

  • This operation consumes more system resources. Please call the stop method to stop the search after any device is discovered and connected.

my.stopBluetoothDevicesDiscovery

You can call this interface to stop searching for nearby Bluetooth devices.

Input parameters

Parameter Type Required Description
success Function No The callback function that indicates a successful call.
fail Function No The callback function that indicates a failed call.
complete Function No The callback function that indicates the call is completed (this will be executed regardless of whether the call succeeds or fails).

Code sample

 
  1. my.stopBluetoothDevicesDiscovery({
  2. success: (res) => {
  3. console.log(res)
  4. },
  5. fail:(res) => {
  6. },
  7. complete: (res)=>{
  8. }
  9. });

my.getBluetoothDevices

You can call this interface to obtain all discovered Bluetooth devices, including the Bluetooth device that is already connected.

Input parameters

Parameter Type Required Description
success Function No The callback function that indicates a successful call.
fail Function No The callback function that indicates a failed call.
complete Function No The callback function that indicates the call is completed (this will be executed regardless of whether the call succeeds or fails).

Return value on success

Parameter Type Description
devices Array List of discovered devices

device objects

Name Type Description
name String The name of the Bluetooth device. Some devices may not have a name.
deviceName (compatible with earlier versions) String The value is consistent with that of name.
localName String Name of the advertising device.
deviceId String Device ID
RSSI Number The signal strength of the device.
advertisData Hex String The advertising content of the device.
manufacturerData Hex String The manufacturer data of the device.

Code sample

 
  1. my.getBluetoothDevices({
  2. success: (res) => {
  3. console.log(res)
  4. },
  5. fail:(res) => {
  6. },
  7. complete: (res)=>{
  8. }
  9. });

Instructions

  • The simulator may not be able to obtain advertisData and RSSI. Please use a physical device for debugging.
  • For Integrated Development Environment (IDE) and Android devices, the device ID is the MAC address of the device; for iOS device, the device ID is the UUID of the device. Therefore, the device ID cannot be hard coded, and needs to be processed based on the specific platform. iOS can dynamically match the deviceId according to the device properties (such as localName, advertisData, manufacturerData).

my.getConnectedBluetoothDevices

You can call this interface to obtain information of the connected devices.

Input parameters

Parameter Type Required Description
deviceId String No The ID of the Bluetooth device.
success Function No The callback function that indicates a successful call.
fail Function No The callback function that indicates a failed call.
complete Function No The callback function that indicates the call is completed (this will be executed regardless of whether the call succeeds or fails).

Code sample

 
  1. my.getConnectedBluetoothDevices({
  2. success: (res) => {
  3. console.log(res)
  4. },
  5. fail:(res) => {
  6. },
  7. complete: (res)=>{
  8. }
  9. });

Instructions

  • If you have searched for a Bluetooth device in the mini program before, you can directly pass in the deviceId obtained by the previous search to connect to the device.
  • If the specified bluetooth device is connected, you’ll be returned with a success response if the connection is repeated.

my.connectBLEDevice

You can call this interface to connect to the Bluetooth Low Energy (BLE) device.

Input parameters

Parameter Type Required Description
deviceId String Yes The ID of the Bluetooth device.
success Function No The callback function that indicates a successful call.
fail Function No The callback function that indicates a failed call.
complete Function No The callback function that indicates the call is completed (this will be executed regardless of whether the call succeeds or fails).

Code sample

 
  1. my.connectBLEDevice({
  2. // The device ID here needs to be obtained in the getBluetoothDevices or onBluetoothDeviceFound APIs above
  3. deviceId: deviceId,
  4. success: (res) => {
  5. console.log(res)
  6. },
  7. fail:(res) => {
  8. },
  9. complete: (res)=>{
  10. }
  11. });

Instructions

  • If you have searched for a Bluetooth device in the mini program before, you can directly pass in the deviceId obtained by the previous search to connect to the device.
  • If the specified Bluetooth device is connected, you’ll be returned with a success response if the connection is repeated.
  • The interface is supported by iOS as well as Android 5.0 and later versions.

my.disconnectBLEDevice

You can call this interface to disconnect from the BLE device.

Input parameters

Parameter Type Required Description
deviceId String Yes The ID of the Bluetooth device.
success Function No The callback function that indicates a successful call.
fail Function No The callback function that indicates a failed call.
complete Function No The callback function that indicates the call is completed (this will be executed regardless of whether the call succeeds or fails).

Code sample

 
  1. my.disconnectBLEDevice({
  2. deviceId: deviceId,
  3. success: (res) => {
  4. console.log(res)
  5. },
  6. fail:(res) => {
  7. },
  8. complete: (res)=>{
  9. }
  10. });

Instructions

  • The Bluetooth device may be disconnected at any time. We recommend that you listen to the my.onBLEConnectionStateChanged callback, and reconnect as needed when the Bluetooth device is disconnected.
  • If the API for data read/write operation is called for unconnected devices or disconnected devices, 10006 error is returned. See the Bluetooth API error codes for details. It is recommended to perform the reconnection operation.
  • The interface is supported by iOS as well as Android 5.0 and later versions.

my.writeBLECharacteristicValue

You can call this interface to write data into the characteristic value of the BLE device.

Input parameters

Parameter Type Required Description
deviceId String Yes The ID of the Bluetooth device. For more information, see the device objects.
serviceId String Yes The UUID of the service to which the Bluetooth characteristic corresponds.
characteristicId String Yes The UUID of the Bluetooth characteristic.
value Hex String Yes The value corresponding to the Bluetooth characteristic. It is a hexadecimal string limited to 20 bytes.
success Function No The callback function that indicates a successful call.
fail Function No The callback function that indicates a failed call.
complete Function No The callback function that indicates the call is completed (this will be executed regardless of whether the call succeeds or fails).

Code sample

 
  1. my.writeBLECharacteristicValue({
  2. deviceId: deviceId,
  3. serviceId: serviceId,
  4. characteristicId: characteristicId,
  5. value: 'fffe',
  6. success: (res) => {
  7. console.log(res)
  8. },
  9. fail:(res) => {
  10. },
  11. complete: (res)=>{
  12. }
  13. });

Instructions

  • The characteristic of the device must support “write”, otherwise the interface cannot be successfully called. Please see the properties of the characteristic for details.
  • The binary data written needs to be hex encoded.
  • The interface is supported by iOS as well as Android 5.0 and later versions.

my.readBLECharacteristicValue

You can call this interface to read data from the characteristic value of the BLE device. Then, the data is returned in the my.onBLECharacteristicValueChange() event.

Input parameters

Parameter Type Required Description
deviceId String Yes The ID of the Bluetooth device. For more information, see the device objects.
serviceId String Yes The UUID of the service to which the Bluetooth characteristic corresponds.
characteristicId String Yes The UUID of the Bluetooth characteristic.
success Function No The callback function that indicates a successful call.
fail Function No The callback function that indicates a failed call.
complete Function No The callback function that indicates the call is completed (this will be executed regardless of whether the call succeeds or fails).

Return value on success

Parameter Type Description
characteristic Object The information of the device characteristic.

characteristic objects

The characteristic information of the Bluetooth device.

Name Type Description
characteristicId String The UUID of the Bluetooth device characteristic.
serviceId String The UUID of the service corresponding to the Bluetooth device characteristic.
value Hex String The value of the Bluetooth device characteristic.

Code sample

 
  1. my.readBLECharacteristicValue({
  2. deviceId: deviceId,
  3. serviceId: serviceId,
  4. characteristicId: characteristicId,
  5. success: (res) => {
  6. console.log(res)
  7. },
  8. fail:(res) => {
  9. },
  10. complete: (res)=>{
  11. }
  12. });

Instructions

  • The characteristic of the device must support “read”, otherwise the interface cannot be successfully called. Please see the properties of the characteristic for details.
  • Multiple parallel reading and writing calls might cause failures.
  • If the reading times out, the error code is 10015. However, my.onBLECharacteristicValueChange interface might return data later. Please process the error with reference to Bluetooth API error codes.
  • The interface is supported by iOS as well as Android 5.0 and later versions.

my.notifyBLECharacteristicValueChange

You can call this interface to enable the “notify” feature for the characteristic value change of the BLE device.

Input parameters

Parameter Type Required Description
deviceId String Yes The ID of the Bluetooth device. For more information, see the device objects.
serviceId String Yes The UUID of the service to which the Bluetooth characteristic corresponds.
characteristicId String Yes The UUID of the Bluetooth characteristic.
descriptorId String No The UUID of the descriptor for the notify (This is only used by Android, and is not required. The default value is 00002902-0000-10008000-00805f9b34fb)
state Boolean No Whether to enable notify or indicate.
success Function No The callback function that indicates a successful call.
fail Function No The callback function that indicates a failed call.
complete Function No The callback function that indicates the call is completed (this will be executed regardless of whether the call succeeds or fails).

Code sample

 
  1. my.notifyBLECharacteristicValueChange({
  2. deviceId: deviceId,
  3. serviceId: serviceId,
  4. characteristicId: characteristicId,
  5. success: (res) => {
  6. console.log(res)
  7. },
  8. fail:(res) => {
  9. },
  10. complete: (res)=>{
  11. }
  12. });

Instructions

  • The characteristic of the device must support “notify/indicate”, otherwise the interface cannot be successfully called.
  • The “notify” feature must be enabled to listen to the characteristicValueChange event of the device.
  • After the subscription operation is successful, the device needs to actively update the characteristic value to trigger my.onBLECharacteristicValueChange.
  • The subscription operation is more efficient. So, it is recommended to use the subscription method instead of the read method.

my.getBLEDeviceServices

You can call this interface to obtain all the Bluetooth devices that are discovered, including the connected devices.

Input parameters

Parameter Type Required Description
deviceId String Yes The ID of the Bluetooth device. For more information, see the device objects.
success Function No The callback function that indicates a successful call.
fail Function No The callback function that indicates a failed call.
complete Function No The callback function that indicates the call is completed (this will be executed regardless of whether the call succeeds or fails).

Return value on success

Parameter Type Description
services Array List of discovered device services

service objects

The service information of the Bluetooth device.

Name Type Description
serviceId String The UUID of the Bluetooth device service.
isPrimary Boolean Indicates whether the service is the primary service.
true: primary service
false: not primary service

Code sample

 
  1. // Obtain the services of the connected devices. The services can only be obtained when the devices are connected.
  2. getBLEDeviceServices() {
  3. my.getConnectedBluetoothDevices({
  4. success: res => {
  5. if (res.devices.length === 0) {
  6. my.alert({ content: 'No connected devices' });
  7. return;
  8. }
  9. my.getBLEDeviceServices({
  10. deviceId: this.data.devid,
  11. success: res => {
  12. my.alert({ content: JSON.stringify(res) });
  13. this.setData({
  14. serid: res.services[0].serviceId,
  15. });
  16. },
  17. fail: error => {
  18. my.alert({ content: JSON.stringify(error) });
  19. },
  20. });
  21. },
  22. });
  23. },

Example of return value

 
  1. {
  2. "services": [{
  3. "isPrimary": true,
  4. "serviceId": "00001800-0000-1000-8000-00805f9b34fb"
  5. }, {
  6. "isPrimary": true,
  7. "serviceId": "00001801-0000-1000-8000-00805f9b34fb"
  8. }, {
  9. "isPrimary": true,
  10. "serviceId": "d0611e78-bbb4-4591-a5f8-487910ae4366"
  11. }, {
  12. "isPrimary": true,
  13. "serviceId": "9fa480e0-4967-4542-9390-d343dc5d04ae"
  14. }]
  15. }

Instructions

  • After the connection is established, you should execute my.getBLEDeviceServices and my.getBLEDeviceCharacteristics first, and then perform data interaction with the Bluetooth device.
  • The interface is supported by iOS as well as Android 5.0 and later versions.

my.getBLEDeviceCharacteristics

You can call this interface to obtain all characteristics of the Bluetooth device.

Input parameters

Parameter Type Required Description
deviceId String Yes The ID of the Bluetooth device. For more information, see the device objects.
serviceId String Yes The UUID of the service to which the Bluetooth characteristic corresponds.
success Function No The callback function that indicates a successful call.
fail Function No The callback function that indicates a failed call.
complete Function No The callback function that indicates the call is completed (this will be executed regardless of whether the call succeeds or fails).

Return value on success

Name Type Description
characteristics Array The list of device characteristics.

characteristic objects

The characteristic information of the Bluetooth device.

Name Type Description
characteristicId String The UUID of the Bluetooth device characteristic.
serviceId String The UUID of the service corresponding to the Bluetooth device characteristic.
value Hex String The hexadecimal value corresponding to the Bluetooth device characteristic.
properties Object The type of operation supported by the characteristic.

properties objects

Name Type Description
read Boolean Indicates whether the characteristic supports read operations.
write Boolean Indicates whether the characteristic supports write operations.
notify Boolean Indicates whether the characteristic supports notify operations.
indicate Boolean Indicates whether the characteristic supports indicate operations.

Code sample

 
  1. my.getBLEDeviceCharacteristics({
  2. deviceId: deviceId,
  3. serviceId: serviceId,
  4. success: (res) => {
  5. console.log(res)
  6. },
  7. fail:(res) => {
  8. },
  9. complete: (res)=>{
  10. }
  11. });

Instructions

  • After the connection is established, you should execute my.getBLEDeviceServices and my.getBLEDeviceCharacteristics first, and then perform data interaction with the Bluetooth device.
  • The interface is supported by iOS as well as Android 5.0 and later versions.

my.onBluetoothDeviceFound(callback)

This callback is triggered when a new Bluetooth device is found.

Input parameters

Parameter Type Required Description
callback Function Yes The callback that is triggered when the specified event occurs.

Return values of callback

Parameter Type Description
devices Array The list of newly found devices.

device objects

Name Type Description
name String The name of the Bluetooth device. Some devices may not have a name.
deviceName (compatible with earlier versions) String The value is consistent with that of name.
localName String The name of the advertising device.
deviceId String The ID of the device.
RSSI Number The signal strength of the device.
advertisData Hex String The advertising content of the device.

Code sample

 
  1. Page({
  2. onLoad() {
  3. this.callback = this.callback.bind(this);
  4. my.onBluetoothDeviceFound(this.callback);
  5. },
  6. onUnload() {
  7. my.offBluetoothDeviceFound(this.callback);
  8. },
  9. callback(res) {
  10. console.log(res);
  11. },
  12. })

Instructions

  • The simulator may not be able to obtain advertisData and RSSI. Please use a physical device for debugging.
  • For Integrated Development Environment (IDE) and Android devices, the device ID is the MAC address of the device; for iOS device, the device ID is the UUID of the device. Therefore, the device ID cannot be hard coded, and needs to be processed based on the specific platform. iOS can dynamically match the deviceId according to the device properties (such as localName, advertisData, manufacturerData).
  • If a Bluetooth device is included in the my.onBluetoothDeviceFound callback, the device is added to the array obtained by my.getBluetoothDevices.

my.offBluetoothDeviceFound

You can call this interface to remove the listener for new Bluetooth device discovery events.

Code sample

 
  1. my.offBluetoothDeviceFound();

Whether to pass callback value or not

  • If the callback value is not passed, the callbacks of all events will be removed. The sample code is as follows:
       
    1. my.offBluetoothDeviceFoun();
  • If the callback value is passed, only the corresponding callback is removed. The sample code is as follows:
       
    1. my.offBluetoothDeviceFoun(this.callback);

Instructions

  • It is recommended that you call the off method to close existing event listening before you call the on method to listen events to prevent the situation where multiple event listening causes multiple callbacks of an event.

my.onBLECharacteristicValueChange(callback)

You can call this interface to listen to characteristic value change events of BLE device.

Input parameters

Parameter Type Required Description
callback Function Yes The callback function that is triggered when a specified event occurs.

Return values of callback

Parameter Type Description
deviceId String The ID of the Bluetooth device. For more information, see the device objects.
connected Boolean The current state of the connection.

Code sample

 
  1. Page({
  2. onLoad() {
  3. this.callback = this.callback.bind(this);
  4. my.onBLECharacteristicValueChange(this.callback);
  5. },
  6. onUnload() {
  7. my.offBLECharacteristicValueChange(this.callback);
  8. },
  9. callback(res) {
  10. console.log(res);
  11. },
  12. })

Instructions

  • It is recommended that you call the off method to close existing event listening before you call the on method to listen events to prevent the situation where multiple event listening causes multiple callbacks of an event.

my.offBLECharacteristicValueChange

You can call this interface to stop listening to the characteristic value change events of BLE device.

Input parameters

Parameter Type Description
deviceId String The ID of the Bluetooth device. For more information, see the device objects.
serviceId String The UUID of the service to which the Bluetooth characteristic corresponds.
characteristicId String The UUID of the Bluetooth characteristic.
value Hex String The latest hexadecimal value of the characteristic.

Whether to pass callback value or not

  • If the callback value is not passed, the callbacks of all events will be removed. The sample code is as follows:
       
    1. my.offBLECharacteristicValueChange();
  • If the callback value is passed, only the corresponding callback is removed. The sample code is as follows:
       
    1. my.offBLECharacteristicValueChange();

Code sample

 
  1. Page({
  2. onLoad() {
  3. this.callback = this.callback.bind(this);
  4. my.onBLECharacteristicValueChange(this.callback);
  5. },
  6. onUnload() {
  7. my.offBLECharacteristicValueChange(this.callback);
  8. },
  9. callback(res) {
  10. console.log(res);
  11. },
  12. })

my.onBLEConnectionStateChanged(callback)

You can call this interface to listen to the BLE connection error events, such as device lost and device disconnected.

Input parameters

Parameter Type Required Description
callback Function Yes The callback function that is triggered when a specified event occurs.

Return values of callback

Parameter Type Description
deviceId String The ID of the Bluetooth device. For more information, see the device objects.
connected Boolean The current state of the connection.

Code sample

 
  1. /* .acss */
  2. .help-info {
  3. padding:10px;
  4. color:#000000;
  5. }
  6. .help-title {
  7. padding:10px;
  8. color:#FC0D1B;
  9. }
 
  1. // .json
  2. {
  3. "defaultTitle": "Bluetooth"
  4. }
 
  1. <!-- .axml-->
  2. <view class="page">
  3. <view class="page-description">Bluetooth API</view>
  4. <view class="page-section">
  5. <view class="page-section-title">Bluetooth state</view>
  6. <view class="page-section-demo">
  7. <button type="primary" onTap="openBluetoothAdapter">Initialize Bluetooth</button>
  8. <button type="primary" onTap="closeBluetoothAdapter">Close Bluetooth</button>
  9. <button type="primary" onTap="getBluetoothAdapterState">Obtain Bluetooth state</button>
  10. </view>
  11. <view class="page-section-title">Scan the Bluetooth device</view>
  12. <view class="page-section-demo">
  13. <button type="primary" onTap="startBluetoothDevicesDiscovery">Start searching</button>
  14. <button type="primary" onTap="getBluetoothDevices">All devices found</button>
  15. <button type="primary" onTap="getConnectedBluetoothDevices">All connected devicese/button>
  16. <button type="primary" onTap="stopBluetoothDevicesDiscovery">Stop searching</button>
  17. </view>
  18. <view class="page-section-title">Connect the device</view>
  19. <view class="page-section-demo">
  20. <input class="input" onInput="bindKeyInput" type="{{text}}" placeholder=" Input the ID of the device to be connected "></input>
  21. <button type="primary" onTap="connectBLEDevice">Connect the device</button>
  22. <button type="primary" onTap="getBLEDeviceServices">Obtain device services</button>
  23. <button type="primary" onTap="getBLEDeviceCharacteristics">Obtain read and write characteristics</button>
  24. <button type="primary" onTap="disconnectBLEDevice"> Disconnect the device </button>
  25. </view>
  26. <view class="page-section-title">Read and write data</view>
  27. <view class="page-section-demo">
  28. <button type="primary" onTap="notifyBLECharacteristicValueChange">Listen to the characteristic data change</button>
  29. <button type="primary" onTap="readBLECharacteristicValue">Read data</button>
  30. <button type="primary" onTap="writeBLECharacteristicValue">Write data</button>
  31. <button type="primary" onTap="offBLECharacteristicValueChange">Cancel listening to characteristic value</button>
  32. </view>
  33. <view class="page-section-title">Other events</view>
  34. <view class="page-section-demo">
  35. <button type="primary" onTap="bluetoothAdapterStateChange">Bluetooth status change</button>
  36. <button type="primary" onTap="offBluetoothAdapterStateChange">Cancel listening to Bluetooth status</button>
  37. <button type="primary" onTap="BLEConnectionStateChanged">Bluetooth connection status changes</button>
  38. <button type="primary" onTap="offBLEConnectionStateChanged">Cancel listening to Bluetooth connection status</button>
  39. </view>
  40. </view>
  41. </view>
 
  1. // .js
  2. Page({
  3. data: {
  4. devid: '0D9C82AD-1CC0-414D-9526-119E08D28124',
  5. serid: 'FEE7',
  6. notifyId: '36F6',
  7. writeId: '36F5',
  8. charid: '',
  9. alldev: [{ deviceId: '' }],
  10. },
  11. //Obtain the Bluetooth state
  12. openBluetoothAdapter() {
  13. my.openBluetoothAdapter({
  14. success: res => {
  15. if (!res.isSupportBLE) {
  16. my.alert({ content: 'Sorry, your mobile Bluetooth is unavailable temporarily' });
  17. return;
  18. }
  19. my.alert({ content: 'Initialization succeeded!' });
  20. },
  21. fail: error => {
  22. my.alert({ content: JSON.stringify(error) });
  23. },
  24. });
  25. },
  26. closeBluetoothAdapter() {
  27. my.closeBluetoothAdapter({
  28. success: () => {
  29. my.alert({ content: 'Bluetooth closed!' });
  30. },
  31. fail: error => {
  32. my.alert({ content: JSON.stringify(error) });
  33. },
  34. });
  35. },
  36. getBluetoothAdapterState() {
  37. my.getBluetoothAdapterState({
  38. success: res => {
  39. if (!res.available) {
  40. my.alert({ content: 'Sorry, your mobile Bluetooth is unavailable temporarily' });
  41. return;
  42. }
  43. my.alert({ content: JSON.stringify(res) });
  44. },
  45. fail: error => {
  46. my.alert({ content: JSON.stringify(error) });
  47. },
  48. });
  49. },
  50. //Scan the Bluetooth device
  51. startBluetoothDevicesDiscovery() {
  52. my.startBluetoothDevicesDiscovery({
  53. allowDuplicatesKey: false,
  54. success: () => {
  55. my.onBluetoothDeviceFound({
  56. success: res => {
  57. // my.alert({content:'Listen to new device'+JSON.stringify(res)});
  58. var deviceArray = res.devices;
  59. for (var i = deviceArray.length - 1; i >= 0; i--) {
  60. var deviceObj = deviceArray[i];
  61. //Match the target device by device name or broadcast data, and then record the device ID for later use
  62. if (deviceObj.name == this.data.name) {
  63. my.alert({ content: 'Target device is found' });
  64. my.offBluetoothDeviceFound();
  65. this.setData({
  66. deviceId: deviceObj.deviceId,
  67. });
  68. break;
  69. }
  70. }
  71. },
  72. fail: error => {
  73. my.alert({ content: 'Failed to listen to new device' + JSON.stringify(error) });
  74. },
  75. });
  76. },
  77. fail: error => {
  78. my.alert({ content: 'Failed to start scanning' + JSON.stringify(error) });
  79. },
  80. });
  81. },
  82. //Stop scanning
  83. stopBluetoothDevicesDiscovery() {
  84. my.stopBluetoothDevicesDiscovery({
  85. success: res => {
  86. my.offBluetoothDeviceFound();
  87. my.alert({ content: 'Succeeded!' });
  88. },
  89. fail: error => {
  90. my.alert({ content: JSON.stringify(error) });
  91. },
  92. });
  93. },
  94. //Obtain the connected device
  95. getConnectedBluetoothDevices() {
  96. my.getConnectedBluetoothDevices({
  97. success: res => {
  98. if (res.devices.length === 0) {
  99. my.alert({ content: 'No connected devices!' });
  100. return;
  101. }
  102. my.alert({ content: JSON.stringify(res) });
  103. devid = res.devices[0].deviceId;
  104. },
  105. fail: error => {
  106. my.alert({ content: JSON.stringify(error) });
  107. },
  108. });
  109. },
  110. //Obtain all devices found
  111. getBluetoothDevices() {
  112. my.getBluetoothDevices({
  113. success: res => {
  114. my.alert({ content: JSON.stringify(res) });
  115. },
  116. fail: error => {
  117. my.alert({ content: JSON.stringify(error) });
  118. },
  119. });
  120. },
  121. bindKeyInput(e) {
  122. this.setData({
  123. devid: e.detail.value,
  124. });
  125. },
  126. //Connect the device
  127. connectBLEDevice() {
  128. my.connectBLEDevice({
  129. deviceId: this.data.devid,
  130. success: res => {
  131. my.alert({ content: 'Connected successfully' });
  132. },
  133. fail: error => {
  134. my.alert({ content: JSON.stringify(error) });
  135. },
  136. });
  137. },
  138. //Disconnect
  139. disconnectBLEDevice() {
  140. my.disconnectBLEDevice({
  141. deviceId: this.data.devid,
  142. success: () => {
  143. my.alert({ content: Disconnected successfully!' });
  144. },
  145. fail: error => {
  146. my.alert({ content: JSON.stringify(error) });
  147. },
  148. });
  149. },
  150. //Obtain the services of the connected devices. The services can only be obtained when the devices are connected.
  151. getBLEDeviceServices() {
  152. my.getConnectedBluetoothDevices({
  153. success: res => {
  154. if (res.devices.length === 0) {
  155. my.alert({ content: 'No connected devices' });
  156. return;
  157. }
  158. my.getBLEDeviceServices({
  159. deviceId: this.data.devid,
  160. success: res => {
  161. my.alert({ content: JSON.stringify(res) });
  162. this.setData({
  163. serid: res.services[0].serviceId,
  164. });
  165. },
  166. fail: error => {
  167. my.alert({ content: JSON.stringify(error) });
  168. },
  169. });
  170. },
  171. });
  172. },
  173. //Obtain the charid of the connected devices. The charid can only be obtained when the devices are connected. The read and write characteristics are respectively screened out.
  174. getBLEDeviceCharacteristics() {
  175. my.getConnectedBluetoothDevices({
  176. success: res => {
  177. if (res.devices.length === 0) {
  178. my.alert({ content: 'No connected devices' });
  179. return;
  180. }
  181. this.setData({
  182. devid: res.devices[0].deviceId,
  183. });
  184. my.getBLEDeviceCharacteristics({
  185. deviceId: this.data.devid,
  186. serviceId: this.data.serid,
  187. success: res => {
  188. my.alert({ content: JSON.stringify(res) });
  189. //See the related document for more information about the attributes of the characteristics. Match the read/write characteristics by attribute and record the value for later use.
  190. this.setData({
  191. charid: res.characteristics[0].characteristicId,
  192. });
  193. },
  194. fail: error => {
  195. my.alert({ content: JSON.stringify(error) });
  196. },
  197. });
  198. },
  199. });
  200. },
  201. //Read and write data
  202. readBLECharacteristicValue() {
  203. my.getConnectedBluetoothDevices({
  204. success: res => {
  205. if (res.devices.length === 0) {
  206. my.alert({ content: 'No connected devices' });
  207. return;
  208. }
  209. this.setData({
  210. devid: res.devices[0].deviceId,
  211. });
  212. my.readBLECharacteristicValue({
  213. deviceId: this.data.devid,
  214. serviceId: this.data.serid,
  215. characteristicId: this.data.notifyId,
  216. //1. Android read and write services
  217. // serviceId:'0000180d-0000-1000-8000-00805f9b34fb',
  218. // characteristicId:'00002a38-0000-1000-8000-00805f9b34fb',
  219. success: res => {
  220. my.alert({ content: JSON.stringify(res) });
  221. },
  222. fail: error => {
  223. my.alert({ content: 'Failed to read and write' + JSON.stringify(error) });
  224. },
  225. });
  226. },
  227. });
  228. },
  229. writeBLECharacteristicValue() {
  230. my.getConnectedBluetoothDevices({
  231. success: res => {
  232. if (res.devices.length === 0) {
  233. my.alert({ content: 'No connected devices' });
  234. return;
  235. }
  236. this.setData({
  237. devid: res.devices[0].deviceId,
  238. });
  239. my.writeBLECharacteristicValue({
  240. deviceId: this.data.devid,
  241. serviceId: this.data.serid,
  242. characteristicId: this.data.charid,
  243. //Android write service
  244. //serviceId:'0000180d-0000-1000-8000-00805f9b34fb',
  245. //characteristicId:'00002a39-0000-1000-8000-00805f9b34fb',
  246. value: 'ABCD',
  247. success: res => {
  248. my.alert({ content: 'Data written successfully!' });
  249. },
  250. fail: error => {
  251. my.alert({ content: JSON.stringify(error) });
  252. },
  253. });
  254. },
  255. });
  256. },
  257. notifyBLECharacteristicValueChange() {
  258. my.getConnectedBluetoothDevices({
  259. success: res => {
  260. if (res.devices.length === 0) {
  261. my.alert({ content: 'No connected devices' });
  262. return;
  263. }
  264. this.setData({
  265. devid: res.devices[0].deviceId,
  266. });
  267. my.notifyBLECharacteristicValueChange({
  268. state: true,
  269. deviceId: this.data.devid,
  270. serviceId: this.data.serid,
  271. characteristicId: this.data.notifyId,
  272. success: () => {
  273. //Listen to characteristic change events
  274. my.onBLECharacteristicValueChange({
  275. success: res => {
  276. // my.alert({content: 'Characteristic change:'+JSON.stringify(res)});
  277. my.alert({ content: 'Obtain the response data = ' + res.value });
  278. },
  279. });
  280. my.alert({ content: 'Listened successfully' });
  281. },
  282. fail: error => {
  283. my.alert({ content: 'Failed to listen' + JSON.stringify(error) });
  284. },
  285. });
  286. },
  287. });
  288. },
  289. offBLECharacteristicValueChange() {
  290. my.offBLECharacteristicValueChange();
  291. },
  292. //Other events
  293. bluetoothAdapterStateChange() {
  294. my.onBluetoothAdapterStateChange(this.getBind('onBluetoothAdapterStateChange'));
  295. },
  296. onBluetoothAdapterStateChange() {
  297. if (res.error) {
  298. my.alert({ content: JSON.stringify(error) });
  299. } else {
  300. my.alert({ content: 'Bluetooth status change: ' + JSON.stringify(res) });
  301. }
  302. },
  303. offBluetoothAdapterStateChange() {
  304. my.offBluetoothAdapterStateChange(this.getBind('onBluetoothAdapterStateChange'));
  305. },
  306. getBind(name) {
  307. if (!this[`bind${name}`]) {
  308. this[`bind${name}`] = this[name].bind(this);
  309. }
  310. return this[`bind${name}`];
  311. },
  312. BLEConnectionStateChanged() {
  313. my.onBLEConnectionStateChanged(this.getBind('onBLEConnectionStateChanged'));
  314. },
  315. onBLEConnectionStateChanged(res) {
  316. if (res.error) {
  317. my.alert({ content: JSON.stringify(error) });
  318. } else {
  319. my.alert({ content: 'Connection status change: ' + JSON.stringify(res) });
  320. }
  321. },
  322. offBLEConnectionStateChanged() {
  323. my.offBLEConnectionStateChanged(this.getBind('onBLEConnectionStateChanged'));
  324. },
  325. onUnload() {
  326. this.offBLEConnectionStateChanged();
  327. this.offBLECharacteristicValueChange();
  328. this.offBluetoothAdapterStateChange();
  329. this.closeBluetoothAdapter();
  330. },
  331. });

Instructions

  • It is recommended that you call the off method to close existing event listening before you call the on method to listen events to prevent the situation where multiple event listening causes multiple callbacks of an event.

my.offBLEConnectionStateChanged

You can call this interface to stop listening to the connection status change events of the BLE device.

Code sample

 
  1. my.offBLEConnectionStateChanged();

Whether to pass callback value or not

  • If the callback value is not passed, the callbacks of all events will be removed. The sample code is as follows:
       
    1. my.offBLEConnectionStateChanged();
  • If the callback value is passed, only the corresponding callback is removed. The sample code is as follows:

       
    1. my.offBLEConnectionStateChanged(this.callback);

    Instructions

  • It is recommended that you call the off method to close existing event listening before you call the on method to listen events to prevent the situation where multiple event listening causes multiple callbacks of an event.

my.onBluetoothAdapterStateChange(callback)

You can call this interface to listen to the native Bluetooth status change events.

Input parameters

Parameter Type Required Description
callback Function Yes The callback function that is triggered when a specified event occurs.

Return values of callback

Parameter Type Description
available Boolean Indicates whether the Bluetooth module is available.
discovering Boolean Indicates whether the Bluetooth module is in the searching state.

Code sample

 
  1. /* .acss */
  2. .help-info {
  3. padding:10px;
  4. color:#000000;
  5. }
  6. .help-title {
  7. padding:10px;
  8. color:#FC0D1B;
  9. }
 
  1. // .json
  2. {
  3. "defaultTitle": "Bluetooth"
  4. }
 
  1. <!-- .axml-->
  2. <view class="page">
  3. <view class="page-description">Bluetooth API</view>
  4. <view class="page-section">
  5. <view class="page-section-title">Bluetooth state</view>
  6. <view class="page-section-demo">
  7. <button type="primary" onTap="openBluetoothAdapter">Initialize Bluetooth</button>
  8. <button type="primary" onTap="closeBluetoothAdapter">Close Bluetooth</button>
  9. <button type="primary" onTap="getBluetoothAdapterState">Obtain Bluetooth state</button>
  10. </view>
  11. <view class="page-section-title">Scan the Bluetooth device</view>
  12. <view class="page-section-demo">
  13. <button type="primary" onTap="startBluetoothDevicesDiscovery">Start searching</button>
  14. <button type="primary" onTap="getBluetoothDevices">All devices found</button>
  15. <button type="primary" onTap="getConnectedBluetoothDevices">All connected devices/button>
  16. <button type="primary" onTap="stopBluetoothDevicesDiscovery">Stop searching</button>
  17. </view>
  18. <view class="page-section-title">Connect the device</view>
  19. <view class="page-section-demo">
  20. <input class="input" onInput="bindKeyInput" type="{{text}}" placeholder=" Input the ID of the device to be connected "></input>
  21. <button type="primary" onTap="connectBLEDevice">Connect the device</button>
  22. <button type="primary" onTap="getBLEDeviceServices">Obtain device services</button>
  23. <button type="primary" onTap="getBLEDeviceCharacteristics">Obtain read and write characteristics</button>
  24. <button type="primary" onTap="disconnectBLEDevice">Disconnect the device</button>
  25. </view>
  26. <view class="page-section-title">Read and write data</view>
  27. <view class="page-section-demo">
  28. <button type="primary" onTap="notifyBLECharacteristicValueChange">Listen to the characteristic data change</button>
  29. <button type="primary" onTap="readBLECharacteristicValue">Read data</button>
  30. <button type="primary" onTap="writeBLECharacteristicValue">Write data</button>
  31. <button type="primary" onTap="offBLECharacteristicValueChange">Cancel listening to characteristic value</button>
  32. </view>
  33. <view class="page-section-title">Other events</view>
  34. <view class="page-section-demo">
  35. <button type="primary" onTap="bluetoothAdapterStateChange">Bluetooth status change</button>
  36. <button type="primary" onTap="offBluetoothAdapterStateChange">Cancel listening to Bluetooth status</button>
  37. <button type="primary" onTap="BLEConnectionStateChanged">Bluetooth connection status changes</button>
  38. <button type="primary" onTap="offBLEConnectionStateChanged">Cancel listening to Bluetooth connection status</button>
  39. </view>
  40. </view>
  41. </view>
 
  1. // .js
  2. Page({
  3. data: {
  4. devid: '0D9C82AD-1CC0-414D-9526-119E08D28124',
  5. serid: 'FEE7',
  6. notifyId: '36F6',
  7. writeId: '36F5',
  8. charid: '',
  9. alldev: [{ deviceId: '' }],
  10. },
  11. //Obtain the Bluetooth state
  12. openBluetoothAdapter() {
  13. my.openBluetoothAdapter({
  14. success: res => {
  15. if (!res.isSupportBLE) {
  16. my.alert({ content: 'Sorry, your mobile Bluetooth is unavailable temporarily' });
  17. return;
  18. }
  19. my.alert({ content: 'Initialization succeeded!' });
  20. },
  21. fail: error => {
  22. my.alert({ content: JSON.stringify(error) });
  23. },
  24. });
  25. },
  26. closeBluetoothAdapter() {
  27. my.closeBluetoothAdapter({
  28. success: () => {
  29. my.alert({ content: 'Bluetooth closed!' });
  30. },
  31. fail: error => {
  32. my.alert({ content: JSON.stringify(error) });
  33. },
  34. });
  35. },
  36. getBluetoothAdapterState() {
  37. my.getBluetoothAdapterState({
  38. success: res => {
  39. if (!res.available) {
  40. my.alert({ content: 'Sorry, your mobile Bluetooth is unavailable temporarily' });
  41. return;
  42. }
  43. my.alert({ content: JSON.stringify(res) });
  44. },
  45. fail: error => {
  46. my.alert({ content: JSON.stringify(error) });
  47. },
  48. });
  49. },
  50. //Scan the Bluetooth device
  51. startBluetoothDevicesDiscovery() {
  52. my.startBluetoothDevicesDiscovery({
  53. allowDuplicatesKey: false,
  54. success: () => {
  55. my.onBluetoothDeviceFound({
  56. success: res => {
  57. // my.alert({content:'Listen to new device'+JSON.stringify(res)});
  58. var deviceArray = res.devices;
  59. for (var i = deviceArray.length - 1; i >= 0; i--) {
  60. var deviceObj = deviceArray[i];
  61. //Match the target device by device name or broadcast data, and then record the device ID for later use
  62. if (deviceObj.name == this.data.name) {
  63. my.alert({ content: 'Target device is found' });
  64. my.offBluetoothDeviceFound();
  65. this.setData({
  66. deviceId: deviceObj.deviceId,
  67. });
  68. break;
  69. }
  70. }
  71. },
  72. fail: error => {
  73. my.alert({ content: 'Failed to listen to new device' + JSON.stringify(error) });
  74. },
  75. });
  76. },
  77. fail: error => {
  78. my.alert({ content: 'Failed to start scanning' + JSON.stringify(error) });
  79. },
  80. });
  81. },
  82. //Stop scanning
  83. stopBluetoothDevicesDiscovery() {
  84. my.stopBluetoothDevicesDiscovery({
  85. success: res => {
  86. my.offBluetoothDeviceFound();
  87. my.alert({ content: 'Succeeded!' });
  88. },
  89. fail: error => {
  90. my.alert({ content: JSON.stringify(error) });
  91. },
  92. });
  93. },
  94. //Obtain the connected device
  95. getConnectedBluetoothDevices() {
  96. my.getConnectedBluetoothDevices({
  97. success: res => {
  98. if (res.devices.length === 0) {
  99. my.alert({ content: 'No connected devices!' });
  100. return;
  101. }
  102. my.alert({ content: JSON.stringify(res) });
  103. devid = res.devices[0].deviceId;
  104. },
  105. fail: error => {
  106. my.alert({ content: JSON.stringify(error) });
  107. },
  108. });
  109. },
  110. //Obtain all devices found
  111. getBluetoothDevices() {
  112. my.getBluetoothDevices({
  113. success: res => {
  114. my.alert({ content: JSON.stringify(res) });
  115. },
  116. fail: error => {
  117. my.alert({ content: JSON.stringify(error) });
  118. },
  119. });
  120. },
  121. bindKeyInput(e) {
  122. this.setData({
  123. devid: e.detail.value,
  124. });
  125. },
  126. //Connect the device
  127. connectBLEDevice() {
  128. my.connectBLEDevice({
  129. deviceId: this.data.devid,
  130. success: res => {
  131. my.alert({ content: 'Connected successfully' });
  132. },
  133. fail: error => {
  134. my.alert({ content: JSON.stringify(error) });
  135. },
  136. });
  137. },
  138. //Disconnect
  139. disconnectBLEDevice() {
  140. my.disconnectBLEDevice({
  141. deviceId: this.data.devid,
  142. success: () => {
  143. my.alert({ content: Disconnected successfully!' });
  144. },
  145. fail: error => {
  146. my.alert({ content: JSON.stringify(error) });
  147. },
  148. });
  149. },
  150. //Obtain the services of the connected devices. The services can only be obtained when the devices are connected.
  151. getBLEDeviceServices() {
  152. my.getConnectedBluetoothDevices({
  153. success: res => {
  154. if (res.devices.length === 0) {
  155. my.alert({ content: 'No connected devices' });
  156. return;
  157. }
  158. my.getBLEDeviceServices({
  159. deviceId: this.data.devid,
  160. success: res => {
  161. my.alert({ content: JSON.stringify(res) });
  162. this.setData({
  163. serid: res.services[0].serviceId,
  164. });
  165. },
  166. fail: error => {
  167. my.alert({ content: JSON.stringify(error) });
  168. },
  169. });
  170. },
  171. });
  172. },
  173. //Obtain the charid of the connected devices. The charid can only be obtained when the devices are connected. The read and write characteristics are respectively screened out.
  174. getBLEDeviceCharacteristics() {
  175. my.getConnectedBluetoothDevices({
  176. success: res => {
  177. if (res.devices.length === 0) {
  178. my.alert({ content: 'No connected devices' });
  179. return;
  180. }
  181. this.setData({
  182. devid: res.devices[0].deviceId,
  183. });
  184. my.getBLEDeviceCharacteristics({
  185. deviceId: this.data.devid,
  186. serviceId: this.data.serid,
  187. success: res => {
  188. my.alert({ content: JSON.stringify(res) });
  189. //See the related document for more information about the attributes of the characteristics. Match the read/write characteristics by attribute and record the value for later use.
  190. this.setData({
  191. charid: res.characteristics[0].characteristicId,
  192. });
  193. },
  194. fail: error => {
  195. my.alert({ content: JSON.stringify(error) });
  196. },
  197. });
  198. },
  199. });
  200. },
  201. //Read and write data
  202. readBLECharacteristicValue() {
  203. my.getConnectedBluetoothDevices({
  204. success: res => {
  205. if (res.devices.length === 0) {
  206. my.alert({ content: 'No connected devices' });
  207. return;
  208. }
  209. this.setData({
  210. devid: res.devices[0].deviceId,
  211. });
  212. my.readBLECharacteristicValue({
  213. deviceId: this.data.devid,
  214. serviceId: this.data.serid,
  215. characteristicId: this.data.notifyId,
  216. //1. Android read and write services
  217. // serviceId:'0000180d-0000-1000-8000-00805f9b34fb',
  218. // characteristicId:'00002a38-0000-1000-8000-00805f9b34fb',
  219. success: res => {
  220. my.alert({ content: JSON.stringify(res) });
  221. },
  222. fail: error => {
  223. my.alert({ content: 'Failed to read and write' + JSON.stringify(error) });
  224. },
  225. });
  226. },
  227. });
  228. },
  229. writeBLECharacteristicValue() {
  230. my.getConnectedBluetoothDevices({
  231. success: res => {
  232. if (res.devices.length === 0) {
  233. my.alert({ content: 'No connected devices' });
  234. return;
  235. }
  236. this.setData({
  237. devid: res.devices[0].deviceId,
  238. });
  239. my.writeBLECharacteristicValue({
  240. deviceId: this.data.devid,
  241. serviceId: this.data.serid,
  242. characteristicId: this.data.charid,
  243. //Android write service
  244. //serviceId:'0000180d-0000-1000-8000-00805f9b34fb',
  245. //characteristicId:'00002a39-0000-1000-8000-00805f9b34fb',
  246. value: 'ABCD',
  247. success: res => {
  248. my.alert({ content: 'Data written successfully!' });
  249. },
  250. fail: error => {
  251. my.alert({ content: JSON.stringify(error) });
  252. },
  253. });
  254. },
  255. });
  256. },
  257. notifyBLECharacteristicValueChange() {
  258. my.getConnectedBluetoothDevices({
  259. success: res => {
  260. if (res.devices.length === 0) {
  261. my.alert({ content: 'No connected devices' });
  262. return;
  263. }
  264. this.setData({
  265. devid: res.devices[0].deviceId,
  266. });
  267. my.notifyBLECharacteristicValueChange({
  268. state: true,
  269. deviceId: this.data.devid,
  270. serviceId: this.data.serid,
  271. characteristicId: this.data.notifyId,
  272. success: () => {
  273. //Listen to characteristic change events
  274. my.onBLECharacteristicValueChange({
  275. success: res => {
  276. // my.alert({content: 'Characteristic change:'+JSON.stringify(res)});
  277. my.alert({ content: 'Obtain the response data = ' + res.value });
  278. },
  279. });
  280. my.alert({ content: 'Listened successfully' });
  281. },
  282. fail: error => {
  283. my.alert({ content: 'Failed to listen' + JSON.stringify(error) });
  284. },
  285. });
  286. },
  287. });
  288. },
  289. offBLECharacteristicValueChange() {
  290. my.offBLECharacteristicValueChange();
  291. },
  292. //Other events
  293. bluetoothAdapterStateChange() {
  294. my.onBluetoothAdapterStateChange(this.getBind('onBluetoothAdapterStateChange'));
  295. },
  296. onBluetoothAdapterStateChange() {
  297. if (res.error) {
  298. my.alert({ content: JSON.stringify(error) });
  299. } else {
  300. my.alert({ content: 'Bluetooth status change: ' + JSON.stringify(res) });
  301. }
  302. },
  303. offBluetoothAdapterStateChange() {
  304. my.offBluetoothAdapterStateChange(this.getBind('onBluetoothAdapterStateChange'));
  305. },
  306. getBind(name) {
  307. if (!this[`bind${name}`]) {
  308. this[`bind${name}`] = this[name].bind(this);
  309. }
  310. return this[`bind${name}`];
  311. },
  312. BLEConnectionStateChanged() {
  313. my.onBLEConnectionStateChanged(this.getBind('onBLEConnectionStateChanged'));
  314. },
  315. onBLEConnectionStateChanged(res) {
  316. if (res.error) {
  317. my.alert({ content: JSON.stringify(error) });
  318. } else {
  319. my.alert({ content: 'Connection status change: ' + JSON.stringify(res) });
  320. }
  321. },
  322. offBLEConnectionStateChanged() {
  323. my.offBLEConnectionStateChanged(this.getBind('onBLEConnectionStateChanged'));
  324. },
  325. onUnload() {
  326. this.offBLEConnectionStateChanged();
  327. this.offBLECharacteristicValueChange();
  328. this.offBluetoothAdapterStateChange();
  329. this.closeBluetoothAdapter();
  330. },
  331. });

my.offBluetoothAdapterStateChange

You can call this interface to stop listening to the native Bluetooth status change events.

Code sample

 
  1. my.offBluetoothAdapterStateChange();

Whether to pass callback value or not

  • If the callback value is not passed, the callbacks of all events will be removed. The sample code is as follows:

       
    1. my.offBluetoothAdapterStateChange();
  • If the callback value is passed, only the corresponding callback is removed. The sample code is as follows:

       
    1. my.offBluetoothAdapterStateChange(this.callback);

Instructions

  • It is recommended that you call the off method to close existing event listening before you call the on method to listen events to prevent the situation where multiple event listening causes multiple callbacks of an event.