# TUYA BLE SDK User Guide

The tuya ble sdk encapsulates the communication protocol with Tuya Smart mobile App and implements event scheduling abilities. The device using tuya ble sdk does not need to care about the specific communication protocol implementation details. It can be interconnected with Tuya Smart App by calling the API and callback provided by the tuya ble sdk.

This topic gives details of the components, porting instruction, SDK configuration, API description, and usage of tuya ble sdk.

### Project address <a href="#title-0-project-20address" id="title-0-project-20address"></a>

<https://github.com/TuyaInc/tuya_ble_sdk.git>

### Overview of tuya ble sdk <a href="#title-1-overview-20of-20tuya-20ble-20sdk" id="title-1-overview-20of-20tuya-20ble-20sdk"></a>

#### Framework <a href="#title-2-framework" id="title-2-framework"></a>

The following figure shows the Application framework based on tuya ble sdk:

![TUYA BLE SDK User Guide](https://airtake-public-data.oss-cn-hangzhou.aliyuncs.com/goat/20200310/4de0b2ed979d4b5593ee00f2793ca99b.png)

* **platform**: the chip platform. The chip and protocol stack are maintained by the chip company.
* **Port**: the abstract interfaces needed by the tuya ble sdk. You must implement them according to the chip-specific platform.
* **tuya ble sdk**: encapsulates the communication protocol of Tuya BLE and provides the service interface to develop Tuya BLE devices.
* **Application**: your application, built by using tuya ble sdk.
* **Tuya sdk API**: implements BLE related management, communication, and so forth. The calls of API are based on asynchronous messages, and the result of API will be notified to the Application of device by message or call back.
* **sdk config**: by setting the macro in the configuration file, you can configure tuya ble sdk to different modes, for example, the general network configuration mode applicable to multi-protocol devices, Bluetooth singlepoint devices mode, ECDH key based encryption method, whether to use OS, and so forth.
* **Main process function**: the engine of tuya ble sdk, to which the Application will call all the time. If the platform architecture has an OS, The tuya ble sdk will automatically create a task to run the main process based on the OS related interface provided by the port layer. If the platform does not have an OS, the device Application needs to be called circularly.
* **Message or Call back**: SDK sends the data of status, data, and others to device Application through call back function registered by device Application or messages.

#### OS compatibility <a href="#title-3-os-20compatibility" id="title-3-os-20compatibility"></a>

The tuya ble sdk can run on OS based chip platform besides Linux. If an OS is used, the API requests are based on asynchronous messages. When tuya ble sdk is initialized, the SDK automatically creates a task based on '`tuya_ble_config.h` file to process the message events of the SDK, and creates a message queue to receive the responses of the Application API. The results of the API are notified to the Application of the device in the form of message, so your Application needs to create a message queue and call `tuya_ble_callback_queue_register()` after calling `tuya_ble_sdk_init()` or `tuya_ble_sdk_init_async()` to register the message queue to the SDK.

In the chip platform that has an OS, you can also configure the tuya ble sdk to process messages using the task provided by Application instead of tasks within the tuya ble sdk. By doing so, the Application must implement the outbound message interface at the port layer.

#### Event queue <a href="#title-4-event-20queue" id="title-4-event-20queue"></a>

The earlier event takes precedence to leave (FIFO). Event queue caches the messages sent by the Application and platform layer, the event can be API calls, data response from BLE devices, and so forth. The main process function module circularly queries the message queue and takes it out for processing.

#### Directories <a href="#title-5-directories" id="title-5-directories"></a>

| **Directory**               | **Description**                                                                                                                         |
| --------------------------- | --------------------------------------------------------------------------------------------------------------------------------------- |
| app                         | Stores Applications that managed by the tuya ble sdk, such as Tuya test and production module, general connection modules and so forth. |
| doc                         | Help file.                                                                                                                              |
| extern\_components          | External components, for example, the extension for security-specific algorithm.                                                        |
| port                        | The abstract interfaces which must be implemented by Applications.                                                                      |
| sdk                         | The core code of the tuya ble sdk.                                                                                                      |
| tuya\_ble\_config.h         | The configuration file for tuya ble sdk. However, your Application needs to create another configuration files on demand.               |
| tuya\_ble\_sdk\_version.h   | The version file.                                                                                                                       |
| README.md                   | A brief introduction of the tuya ble sdk.                                                                                               |
| tuya\_ble\_sdk\_version.txt | Explains what are updated for each version in Chinese.                                                                                  |
| CHANGELOG.md                | Explains what are updated for each version in English.                                                                                  |

### The concepts of tuya ble service <a href="#title-6-the-20concepts-20of-20tuya-20ble-20service" id="title-6-the-20concepts-20of-20tuya-20ble-20service"></a>

The tuya ble sdk does not provide the interfaces for initializing service. Your Application needs to implement the service characteristics defined in the following table before you initializing the SDK. Other than the services required by the tuya ble sdk, you can also define other services if needed. The initial format of broadcast data must be implemented according to the following table, otherwise the tuya ble sdk cannot work.

| **Service UUID** | **Characteristic UUID** | **Properties**                | **Security Permissions** |
| ---------------- | ----------------------- | ----------------------------- | ------------------------ |
| 1910             | 2b10                    | Notify                        | None.                    |
|                  | 2b11                    | Write,write without response. | None.                    |

#### The MTU <a href="#title-7-the-20mtu" id="title-7-the-20mtu"></a>

For a better compatibility, the ATT MTU used by tuya ble sdk is 23, and the GATT MTU (ATT DATA MAX) is 20.

#### Broadcast data format <a href="#title-8-broadcast-20data-20format" id="title-8-broadcast-20data-20format"></a>

The following picture illustrates the broadcast packet format of BLE.

![TUYA BLE SDK User Guide](https://images.tuyacn.com/fe-static/docs/img/a48b425f-19e7-40c1-986e-11f082416b49.png)

The following table describes what are contained in the broadcast packet.

| Broadcast data segment                       | Type | Description                                                                                                                      |
| -------------------------------------------- | ---- | -------------------------------------------------------------------------------------------------------------------------------- |
| Physical connection identifier of BLE device | 0x01 | Length: 0x02;Type: 0X01; Data: 0x16                                                                                              |
| Service UUID                                 | 0x02 | Length: 0x03; Type: 0x02; Data: 0xA201                                                                                           |
| Service Data                                 | 0x16 | <p>Length: 0x0C or 0x14<br>Type: 0x16<br>Data: 0x01, 0xA2, type (0-pid,1-product\_key)PID, or product\_key (in 8 or 16 byte)</p> |

Example of 8 byte PID: `02 01 05 03 02 01 A2 0C 16 01 A2 00 00 00 00 00 00 00 00 00`

The following table describes what are contained in the scan response data.

| Response data segment               | Type | Description                                                                                                                                                                               |
| ----------------------------------- | ---- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Complete Local Name                 | 0x09 | Length: 0x03; Type: 0x09; Date: 0x54 or 0x59                                                                                                                                              |
| Custom data defined by manufacturer | 0xff | <p>Length: 0x19<br>Type: 0xff<br>Date: COMPANY ID:0x07D0<br>FLAG: 0x00<br>Protocol version: 0x03<br>Encryption method: 0x00<br>Communication capacity: 0x0000<br>Reserved field: 0x00</p> |
|                                     |      | ID field: 6 or 16 bytes                                                                                                                                                                   |

Example of an unassociated devices: `03 09 54 59 19 FF D0 07 00 0300 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00`

### How to port and configure tuya ble sdk <a href="#title-9-how-20to-20port-20and-20configure-20tuya-20ble-20sdk" id="title-9-how-20to-20port-20and-20configure-20tuya-20ble-20sdk"></a>

As the following picture shows, the interfaces defined in the file `tuya_ble_port.h` and `tuya_ble_port_peripheral.h` must be ported and implemented according to the chip-specific platform. Note that if the platform used in the Application does not have an OS, the OS related interfaces do not need to be implemented. The `tuya_ble_port.c` and `tuya_ble_port_peripheral.c` are the weak implementation of the interfaces defined for the `tuya_ble_port.h` and `tuya_ble_port_peripheral.h`.

![TUYA BLE SDK User Guide](https://airtake-public-data-1254153901.cos.ap-shanghai.myqcloud.com/goat/20200606/feac2f6cf3c847a7a0b12077b435fac3.png)

You cannot implement platform-specific interfaces in the preceding `.c` files, please create a new one, for example `tuya_ble_port_nrf52832.c`. If the file name contains the keyword `tuya`, it is the platform implementation file that Tuya Smart has adapted and transplanted, you can refer to it if needed.

#### Reference of porting APIs <a href="#title-10-reference-20of-20porting-20apis" id="title-10-reference-20of-20porting-20apis"></a>

**TUYA\_BLE\_LOG**

| **Function name** | TUYA\_BLE\_LOG                                                         |
| ----------------- | ---------------------------------------------------------------------- |
| **Prototype**     | void TUYA\_BLE\_LOG(const char \*format,…)                             |
| **Description**   | Formatted output.                                                      |
| **Parameters**    | <p>format\[in]: format controller.<br>…\[in]: variable parameters.</p> |
| **Responses**     | TUYA\_BLE\_ERR\_INVALID\_PARAM: invalid parameters                     |

**TUYA\_BLE\_HEXDUMP**

| **Function name** | TUYA\_BLE\_HEXDUMP                                                             |
| ----------------- | ------------------------------------------------------------------------------ |
| **Prototype**     | void TUYA\_BLE\_HEXDUMP(uint8\_t \*p\_data , uint16\_t len)                    |
| **Description**   | Print in hex values.                                                           |
| **Parameters**    | <p>p\_data\[in]: the data pointer to be printed.<br>len\[in]: data length.</p> |
| **Responses**     | TUYA\_BLE\_ERR\_INVALID\_PARAM: invalid parameters                             |

**tuya\_ble\_gap\_advertising\_adv\_data\_update**

| **Function name** | tuya\_ble\_gap\_advertising\_adv\_data\_update                                                                       |
| ----------------- | -------------------------------------------------------------------------------------------------------------------- |
| **Prototype**     | tuya\_ble\_status\_t tuya\_ble\_gap\_advertising\_adv\_data\_update(uint8\_t const \* p\_ad\_data, uint8\_t ad\_len) |
| **Description**   | Updates the BLE broadcast packets.                                                                                   |
| **Parameters**    | <p>p\_ad\_data\[in]: new broadcast data.<br>ad\_len\[in]: data length.</p>                                           |
| **Responses**     | <p>TUYA\_BLE\_SUCCESS: success.<br>Others: failure.</p>                                                              |

**tuya\_ble\_gap\_advertising\_scan\_rsp\_data\_update**

| **Function name** | tuya\_ble\_gap\_advertising\_scan\_rsp\_data\_update                                                                      |
| ----------------- | ------------------------------------------------------------------------------------------------------------------------- |
| **Prototype**     | tuya\_ble\_status\_t tuya\_ble\_gap\_advertising\_scan\_rsp\_data\_update(uint8\_t const \*p\_sr\_data, uint8\_t sr\_len) |
| **Description**   | Updates the scan response data.                                                                                           |
| **Parameters**    | <p>p\_sr\_data\[in]: new scan response data.<br>sr\_len\[in]: data length.</p>                                            |
| **Responses**     | <p>TUYA\_BLE\_SUCCESS: success.<br>Others: failure.</p>                                                                   |

**tuya\_ble\_gap\_disconnect**

| **Function name** | tuya\_ble\_gap\_disconnect                              |
| ----------------- | ------------------------------------------------------- |
| **Prototype**     | tuya\_ble\_status\_t tuya\_ble\_gap\_disconnect(void)   |
| **Description**   | Break the BLE connection.                               |
| **Parameters**    | None.                                                   |
| **Responses**     | <p>TUYA\_BLE\_SUCCESS: success.<br>Others: failure.</p> |

**tuya\_ble\_gatt\_send\_data**

| **Function name** | tuya\_ble\_gatt\_send\_data                                                                      |
| ----------------- | ------------------------------------------------------------------------------------------------ |
| **Prototype**     | tuya\_ble\_status\_t tuya\_ble\_gatt\_send\_data(const uint8\_t \*p\_data,uint16\_t len)         |
| **Description**   | Sends data via BLE GATT.                                                                         |
| **Parameters**    | <p>p\_data\[in]: the data pointer to send.<br>len\[in]: the data length, less than 20 bytes.</p> |
| **Responses**     | <p>TUYA\_BLE\_SUCCESS: success.<br>Others: failure.</p>                                          |
| **Notice**        | It must be done in the notification method.                                                      |

**tuya\_ble\_timer\_create**

| **Function name** | tuya\_ble\_timer\_create                                                                                                                                                                                                                                            |
| ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Prototype**     | <p>tuya\_ble\_status\_t tuya\_ble\_timer\_create(void\*\* p\_timer\_id,uint32\_t timeout\_value\_ms,<br>tuya\_ble\_timer\_mode mode,tuya\_ble\_timer\_handler\_t timeout\_handler)</p>                                                                              |
| **Description**   | create a timer.                                                                                                                                                                                                                                                     |
| **Parameters**    | <p>p\_timer\_id\[out]: the timer pointer.<br>timeout\_value\_ms\[in]: the timing, unit: ms.<br>mode\[in]:<br>- TUYA\_BLE\_TIMER\_SINGLE\_SHOT: one-time mode.<br>- TUYA\_BLE\_TIMER\_REPEATED: recurring mode.<br>- timeout\_handler \[in]: the timer callback.</p> |
| **Responses**     | <p>TUYA\_BLE\_SUCCESS: success.<br>Others: failure.</p>                                                                                                                                                                                                             |

**tuya\_ble\_timer\_delete**

| **Function name** | tuya\_ble\_timer\_delete                                                                                       |
| ----------------- | -------------------------------------------------------------------------------------------------------------- |
| **Prototype**     | tuya\_ble\_status\_t tuya\_ble\_timer\_delete(void\* timer\_id)                                                |
| **Description**   | Deletes a timer.                                                                                               |
| **Parameters**    | timer\_id \[in]: the timer ID.                                                                                 |
| **Responses**     | <p>TUYA\_BLE\_SUCCESS: success.<br>TUYA\_BLE\_ERR\_INVALID\_PARAM: invalid parameters.<br>Others: failure.</p> |

**tuya\_ble\_timer\_start**

| **Function name** | tuya\_ble\_timer\_start                                                                                        |
| ----------------- | -------------------------------------------------------------------------------------------------------------- |
| **Prototype**     | tuya\_ble\_status\_t tuya\_ble\_timer\_start(void\* timer\_id)                                                 |
| **Description**   | Starts a timer.                                                                                                |
| **Parameters**    | timer\_id \[in]: the timer ID.                                                                                 |
| **Responses**     | <p>TUYA\_BLE\_SUCCESS: success.<br>TUYA\_BLE\_ERR\_INVALID\_PARAM: invalid parameters.<br>Others: failure.</p> |
| **Notice**        | If a timer has been started, a `tuya_ble_timer_start` request will start the timer again.                      |

**tuya\_ble\_timer\_restart**

| **Function name** | tuya\_ble\_timer\_restart                                                                                          |
| ----------------- | ------------------------------------------------------------------------------------------------------------------ |
| **Prototype**     | tuya\_ble\_status\_t tuya\_ble\_timer\_restart(void\* timer\_id,uint32\_t timeout\_value\_ms)                      |
| **Description**   | Restarts a timer with a new time.                                                                                  |
| **Parameters**    | <p>timer\_id \[in]: the timer ID.<br>timeout\_value\_ms\[in]: the timing, unit: ms.</p>                            |
| **Responses**     | <p>TUYA\_BLE\_SUCCESS: success.<br><br>TUYA\_BLE\_ERR\_INVALID\_PARAM: invalid parameters.<br>Others: failure.</p> |

**tuya\_ble\_timer\_stop**

| **Function name** | tuya\_ble\_timer\_stop                                                                                             |
| ----------------- | ------------------------------------------------------------------------------------------------------------------ |
| **Prototype**     | tuya\_ble\_status\_t tuya\_ble\_timer\_stop(void\* timer\_id)                                                      |
| **Description**   | Stops a timer.                                                                                                     |
| **Parameters**    | timer\_id \[in]: the timer ID.                                                                                     |
| **Responses**     | <p>TUYA\_BLE\_SUCCESS: success.<br><br>TUYA\_BLE\_ERR\_INVALID\_PARAM: invalid parameters.<br>Others: failure.</p> |

**tuya\_ble\_device\_delay\_ms**

| **Function name** | tuya\_ble\_device\_delay\_ms                                                                                                                             |
| ----------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Prototype**     | void tuya\_ble\_device\_delay\_ms(uint32\_t ms)                                                                                                          |
| **Description**   | Delays an activity at the millisecond level.                                                                                                             |
| **Parameters**    | ms \[in]: the delay time, unit: ms.                                                                                                                      |
| **Responses**     | None.                                                                                                                                                    |
| **Notice**        | If the platform has an OS, it must be non-blocking delay. This method only applies to specific cases, for example, SDK initialization or device restart. |

**tuya\_ble\_device\_delay\_us**

| **Function name** | tuya\_ble\_device\_delay\_us                                                                                                                             |
| ----------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Prototype**     | void tuya\_ble\_device\_delay\_us(uint32\_t us)                                                                                                          |
| **Description**   | Delays an activity at the microsecond level.                                                                                                             |
| **Parameters**    | us \[in]: the delay time, unit: us.                                                                                                                      |
| **Responses**     | None.                                                                                                                                                    |
| **Notice**        | If the platform has an OS, it must be non-blocking delay. This method only applies to specific cases, for example, SDK initialization or device restart. |

**tuya\_ble\_device\_reset**

| **Function name** | tuya\_ble\_device\_reset                                |
| ----------------- | ------------------------------------------------------- |
| **Prototype**     | tuya\_ble\_status\_t tuya\_ble\_device\_reset(void)     |
| **Description**   | Restarts devices.                                       |
| **Parameters**    | None.                                                   |
| **Responses**     | <p>TUYA\_BLE\_SUCCESS: success.<br>Others: failure.</p> |

**tuya\_ble\_gap\_addr\_get**

| **Function name** | tuya\_ble\_gap\_addr\_get                                                          |
| ----------------- | ---------------------------------------------------------------------------------- |
| **Prototype**     | tuya\_ble\_status\_t tuya\_ble\_gap\_addr\_get(tuya\_ble\_gap\_addr\_t \*p\_addr); |
| **Description**   | Obtains the MAC address of devices.                                                |
| **Parameters**    | p\_addr \[out]: the MAC address pointer.                                           |
| **Responses**     | <p>TUYA\_BLE\_SUCCESS: success.<br>Others: failure.</p>                            |

The following sample illustrates how to use the `tuya_ble_gap_addr_get` method.

```
typedef enum

{

TUYA_BLE_ADDRESS_TYPE_PUBLIC, // The public address

TUYA_BLE_ADDRESS_TYPE_RANDOM, // The random address

} tuya_ble_addr_type_t;

typedef struct

{

tuya_ble_addr_type_t addr_type;

uint8_t addr[6];

}tuya_ble_gap_addr_t;
```

**tuya\_ble\_gap\_addr\_set**

| **Function name** | tuya\_ble\_gap\_addr\_set                                                          |
| ----------------- | ---------------------------------------------------------------------------------- |
| **Prototype**     | tuya\_ble\_status\_t tuya\_ble\_gap\_addr\_set(tuya\_ble\_gap\_addr\_t \*p\_addr); |
| **Description**   | Updates the MAC address of the device.                                             |
| **Parameters**    | p\_addr \[in]: the MAC address pointer.                                            |
| **Responses**     | <p>TUYA\_BLE\_SUCCESS: success.<br>Others: failure.</p>                            |

**tuya\_ble\_device\_enter\_critical**

| **Function name** | tuya\_ble\_device\_enter\_critical           |
| ----------------- | -------------------------------------------- |
| **Prototype**     | voidtuya\_ble\_device\_enter\_critical(void) |
| **Description**   | Enters the critical zone.                    |
| **Parameters**    | None.                                        |
| **Responses**     | None.                                        |

**tuya\_ble\_device\_exit\_critical**

| **Function name** | tuya\_ble\_device\_exit\_critical            |
| ----------------- | -------------------------------------------- |
| **Prototype**     | void tuya\_ble\_device\_exit\_critical(void) |
| **Description**   | Quits the critial zone.                      |
| **Parameters**    | None.                                        |
| **Responses**     | None.                                        |

**tuya\_ble\_rand\_generator**

| **Function name** | tuya\_ble\_rand\_generator                                                                                 |
| ----------------- | ---------------------------------------------------------------------------------------------------------- |
| **Prototype**     | tuya\_ble\_status\_t tuya\_ble\_rand\_generator(uint8\_t\* p\_buf, uint8\_t len)                           |
| **Description**   | Generates a random digit.                                                                                  |
| **Parameters**    | <p>p\_buf \[out]: the array of random digit pointer.<br>len\[in]: the byte number of the random value.</p> |
| **Responses**     | <p>TUYA\_BLE\_SUCCESS: success.<br>Others: failure.</p>                                                    |

**tuya\_ble\_rtc\_get\_timestamp**

| **Function name** | tuya\_ble\_rtc\_get\_timestamp                                                                                                                                          |
| ----------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Prototype**     | tuya\_ble\_status\_t tuya\_ble\_rtc\_get\_timestamp(uint32\_t \*timestamp,int32\_t \*timezone);                                                                         |
| **Description**   | Obtains the Unix timestamp.                                                                                                                                             |
| **Parameters**    | <p>timestamp \[out]: the timestamp.<br>timezone \[out]: the time zone, data type: signed integer, the value must be 100 times of the real time.</p>                     |
| **Responses**     | <p>TUYA\_BLE\_SUCCESS: success.<br>Others: failure.</p>                                                                                                                 |
| **Notice**        | The data comes from the RTC (real-time clock) maintained by the Application itself. If the Application does not have an RTC, it is not necessary to use this interface. |

**tuya\_ble\_rtc\_set\_timestamp**

| **Function name** | tuya\_ble\_rtc\_set\_timestamp                                                                                                                                  |
| ----------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Prototype**     | tuya\_ble\_status\_t tuya\_ble\_rtc\_set\_timestamp(uint32\_t timestamp,int32\_t timezone)                                                                      |
| **Description**   | Updates the Unix timestamp.                                                                                                                                     |
| **Parameters**    | <p>timestamp \[in]: Unix timestamp.<br>timezone \[in]: the time zone, data type: signed integer, the value must be 100 times of the real time.</p>              |
| **Responses**     | <p>TUYA\_BLE\_SUCCESS: success.<br>Others: failure.</p>                                                                                                         |
| **Notice**        | The tuya ble sdk uses this API to update the RTC clock for the Application. If the Application does not have an RTC, it is not necessary to use this interface. |

**tuya\_ble\_nv\_init**

| **Function name** | tuya\_ble\_nv\_init                                                                                                                                                                       |
| ----------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Prototype**     | tuya\_ble\_status\_t tuya\_ble\_nv\_init(void)                                                                                                                                            |
| **Description**   | Initializes the NV.                                                                                                                                                                       |
| **Parameters**    | None.                                                                                                                                                                                     |
| **Responses**     | <p>TUYA\_BLE\_SUCCESS: success.<br><br>Others: failure.</p>                                                                                                                               |
| **Notice**        | It is used together with the NV space address that is defined in the configuration file. The tuya ble sdk calls NV related functions to store and manage authorization and other details. |

**tuya\_ble\_nv\_erase**

| **Function name** | tuya\_ble\_nv\_erase                                                                                                                                                                      |
| ----------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Prototype**     | tuya\_ble\_status\_t tuya\_ble\_nv\_erase(uint32\_t addr,uint32\_t size)                                                                                                                  |
| **Description**   | Erases the NV.                                                                                                                                                                            |
| **Parameters**    | <p>addr\[in]: the initial address of NV space to be erased.<br>size\[in]: the space length to be erased, unit: byte.</p>                                                                  |
| **Responses**     | <p>TUYA\_BLE\_SUCCESS: success.<br>Others: failure.</p>                                                                                                                                   |
| **Notice**        | It is used together with the NV space address that is defined in the configuration file. The tuya ble sdk calls NV related functions to store and manage authorization and other details. |

**tuya\_ble\_nv\_write**

| **Function name** | tuya\_ble\_nv\_write                                                                                                                                                                      |
| ----------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Prototype**     | tuya\_ble\_status\_t tuya\_ble\_nv\_write(uint32\_t addr,const uint8\_t \* p\_data, uint32\_t size)                                                                                       |
| **Description**   | Writes data to NV.                                                                                                                                                                        |
| **Parameters**    | <p>addr\[in]: the initial address of NV space to write data.<br>p\_data\[in]: the initial address of NV space to write data.<br>size\[in]: the data size, unit: byte.</p>                 |
| **Responses**     | <p>TUYA\_BLE\_SUCCESS: success.<br>Others: failure.</p>                                                                                                                                   |
| **Notice**        | It is used together with the NV space address that is defined in the configuration file. The tuya ble sdk calls NV related functions to store and manage authorization and other details. |

**tuya\_ble\_nv\_read**

| **Function name** | tuya\_ble\_nv\_read                                                                                                                                                                       |
| ----------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Prototype**     | tuya\_ble\_status\_t tuya\_ble\_nv\_read(uint32\_t addr,uint8\_t \* p\_data, uint32\_t size)                                                                                              |
| **Description**   | Reads data from NV.                                                                                                                                                                       |
| **Parameters**    | <p>addr\[in]: the initial address of NV space to read data.<br>p\_data\[out]: the initial address of NV space to write data.<br>size\[in]: the data size, unit: byte.</p>                 |
| **Responses**     | <p>TUYA\_BLE\_SUCCESS: success.<br>Others: failure.</p>                                                                                                                                   |
| **Notice**        | It is used together with the NV space address that is defined in the configuration file. The tuya ble sdk calls NV related functions to store and manage authorization and other details. |

**tuya\_ble\_nv\_erase\_async**

| **Function name** | tuya\_ble\_nv\_erase\_async                                                                                                                                                                                                                               |
| ----------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Prototype**     | void tuya\_ble\_nv\_erase\_async(uint32\_t addr,uint32\_t size,void \*p\_context,tuya\_ble\_nv\_async\_callback\_t callback)                                                                                                                              |
| **Description**   | Erases data from NV asynchronously.                                                                                                                                                                                                                       |
| **Parameters**    | <p>addr\[in]: the initial address of NV space to erase data.<br>size\[in]: the data size, unit: byte.<br>p\_context\[in]: user custom data.<br>callback\[in]: returns the API results.</p>                                                                |
| **Responses**     | None.                                                                                                                                                                                                                                                     |
| **Notice**        | It is used together with the NV space address that is defined in the configuration file. The tuya ble sdk calls NV related functions to store and manage authorization and other details. The interface is used in the asynchronous flash based platform. |

**tuya\_ble\_nv\_write\_async**

| **Function name** | tuya\_ble\_nv\_write\_async                                                                                                                                                                                                                               |
| ----------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Prototype**     | void tuya\_ble\_nv\_write\_async(uint32\_t addr,const uint8\_t \* p\_src, uint32\_t size,void \*p\_context,tuya\_ble\_nv\_async\_callback\_t callback)                                                                                                    |
| **Description**   | Writes data to NV asynchronously.                                                                                                                                                                                                                         |
| **Parameters**    | <p>addr\[in]: the initial address of NV space to write data.<br>p\_src\[in]: the address to write date.<br>size\[in]: the data size, unit: byte.<br>p\_context\[in]: user custom data.<br>callback\[in]: returns the API results.</p>                     |
| **Responses**     | None.                                                                                                                                                                                                                                                     |
| **Notice**        | It is used together with the NV space address that is defined in the configuration file. The tuya ble sdk calls NV related functions to store and manage authorization and other details. The interface is used in the asynchronous flash based platform. |

**tuya\_ble\_nv\_read\_async**

| **Function name** | tuya\_ble\_nv\_read\_async                                                                                                                                                                                                                                |
| ----------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Prototype**     | void tuya\_ble\_nv\_read\_async(uint32\_t addr, uint8\_t \* p\_dest, uint32\_t size,void \*p\_context,tuya\_ble\_nv\_async\_callback\_t callback)                                                                                                         |
| **Description**   | Reads data from NV asynchronously.                                                                                                                                                                                                                        |
| **Parameters**    | <p>addr\[in]: the initial address of NV space to read data.<br>p\_dest\[out]: the address to read data.<br>size\[in]: the data size, unit: byte.<br>p\_context\[in]: user custom data.<br>callback\[in]: returns the API results.</p>                     |
| **Responses**     | None.                                                                                                                                                                                                                                                     |
| **Notice**        | It is used together with the NV space address that is defined in the configuration file. The tuya ble sdk calls NV related functions to store and manage authorization and other details. The interface is used in the asynchronous flash based platform. |

**tuya\_ble\_common\_uart\_init**

| **Function name** | tuya\_ble\_common\_uart\_init                                                                                                                                                                                                                                                                                                                        |
| ----------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Prototype**     | tuya\_ble\_status\_t tuya\_ble\_common\_uart\_init(void)                                                                                                                                                                                                                                                                                             |
| **Description**   | Initializes the UART.                                                                                                                                                                                                                                                                                                                                |
| **Parameters**    | None.                                                                                                                                                                                                                                                                                                                                                |
| **Responses**     | <p>TUYA\_BLE\_SUCCESS: success.<br>Others: failure.</p>                                                                                                                                                                                                                                                                                              |
| **Notice**        | <p>Under the following circumstances, there is no need to implement the <code>tuya\_ble\_common\_uart\_init</code> interface:<br>- The functions of test and production authorization are not used.<br>- The SDK's production testing authorization function are used, and the Application has initialized the UART before initializing the SDK.</p> |

**tuya\_ble\_common\_uart\_send\_data**

| **Function name** | tuya\_ble\_common\_uart\_send\_data                                                                                                               |
| ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Prototype**     | tuya\_ble\_status\_t tuya\_ble\_common\_uart\_send\_data(const uint8\_t \*p\_data,uint16\_t len)                                                  |
| **Description**   | Sends data via UART.                                                                                                                              |
| **Parameters**    | <p>p\_data\[in]: the data pointer to send.<br>len\[in]: the data size.</p>                                                                        |
| **Responses**     | <p>TUYA\_BLE\_SUCCESS: success.<br>Others: failure.</p>                                                                                           |
| **Notice**        | If the functions of test and production authorization are not used, there is no need to implement the `tuya_ble_common_uart_send_data` interface. |

**tuya\_ble\_os\_task\_create**

| **Function name** | tuya\_ble\_os\_task\_create                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   |
| ----------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Prototype**     | bool tuya\_ble\_os\_task\_create(void \*\*pp\_handle, const char \*p\_name, void(\*p\_routine)(void \*),void \*p\_param, uint16\_t stack\_size, uint16\_t priority)                                                                                                                                                                                                                                                                                                                                                           |
| **Description**   | Creates tasks.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                |
| **Parameters**    | <p>pp\_handle \[out]: passes back a handle by which the created task can be referenced.<br>p\_name\[in]: A descriptive name for the task.<br>p\_routine \[in]: pointer to task routine function that must be implemented to never return.<br>p\_param\[in]: pointer parameter passed to the task routine function.<br>stack\_size\[in]: the size of the task stack that is specified as the number of bytes.<br>priority\[in]: the priority at which the task should run. Higher priority task has higher priority value.</p> |
| **Responses**     | <p>True: task was created successfully and added to task ready list.<br>False: task was failed to create.</p>                                                                                                                                                                                                                                                                                                                                                                                                                 |
| **Notice**        | This interface is required only in the platform that has an OS.                                                                                                                                                                                                                                                                                                                                                                                                                                                               |

**tuya\_ble\_os\_task\_delete**

| **Function name** | tuya\_ble\_os\_task\_delete                                                                                               |
| ----------------- | ------------------------------------------------------------------------------------------------------------------------- |
| **Prototype**     | bool tuya\_ble\_os\_task\_delete(void \*p\_handle)                                                                        |
| **Description**   | Removes a task from RTOS's task management. The task being deleted will be removed from RUNNING, READY, or WAITING state. |
| **Parameters**    | pp\_handle \[in]: the handle of the task to be deleted.                                                                   |
| **Responses**     | <p>True: task was deleted successfully<br>False: task was failed to delete.</p>                                           |
| **Notice**        | This interface is required only in the platform that has an OS.                                                           |

**tuya\_ble\_os\_task\_suspend**

| **Function name** | tuya\_ble\_os\_task\_suspend                                                                                   |
| ----------------- | -------------------------------------------------------------------------------------------------------------- |
| **Prototype**     | bool tuya\_ble\_os\_task\_suspend(void \*p\_handle)                                                            |
| **Description**   | Suspends the task. The suspended task will not be scheduled and never get any microcontroller processing time. |
| **Parameters**    | pp\_handle \[in]: the handle of the task to be suspend.                                                        |
| **Responses**     | <p>True: task was suspend successfully.<br>False: task was failed to suspend.</p>                              |
| **Notice**        | This interface is required only in the platform that has an OS.                                                |

**tuya\_ble\_os\_task\_resume**

| **Function name** | tuya\_ble\_os\_task\_resume                                                      |
| ----------------- | -------------------------------------------------------------------------------- |
| **Prototype**     | bool tuya\_ble\_os\_task\_resume(void \*p\_handle)                               |
| **Description**   | Resumes the suspended task.                                                      |
| **Parameters**    | pp\_handle \[in]: the handle of the task to be resumed.                          |
| **Responses**     | <p>True: task was resumed successfully.<br>False: task was failed to resume.</p> |
| **Notice**        | This interface is required only in the platform that has an OS.                  |

**tuya\_ble\_os\_msg\_queue\_create**

| **Function name** | tuya\_ble\_os\_msg\_queue\_create                                                                                                                                                                                                                    |
| ----------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Prototype**     | bool tuya\_ble\_os\_msg\_queue\_create(void \*\*pp\_handle, uint32\_t msg\_num, uint32\_tmsg\_size)                                                                                                                                                  |
| **Description**   | Creates a message queue instance. This allocates the storage required by the new queue and passes back a handle for the queue.                                                                                                                       |
| **Parameters**    | <p>pp\_handle \[out]: passes back a handle by which the message queue can be referenced.<br>msg\_num \[in]: the maximum number of items that the queue can contain.<br>msg\_size \[in]: the number of bytes each item in the queue will require.</p> |
| **Responses**     | <p>True: message queue was created successfully.<br>False: message queue was failed to create.</p>                                                                                                                                                   |
| **Notice**        | This interface is required only in the platform that has an OS.                                                                                                                                                                                      |

**tuya\_ble\_os\_msg\_queue\_delete**

| **Function name** | tuya\_ble\_os\_msg\_queue\_delete                                                                                              |
| ----------------- | ------------------------------------------------------------------------------------------------------------------------------ |
| **Prototype**     | bool tuya\_ble\_os\_msg\_queue\_delete(void \*p\_handle)                                                                       |
| **Description**   | Creates a message queue instance. This allocates the storage required by the new queue and passes back a handle for the queue. |
| **Parameters**    | pp\_handle \[in]: the handle to the message queue being deleted.                                                               |
| **Responses**     | <p>True: message queue was deleted successfully.<br>False: message queue was failed to delete.</p>                             |
| **Notice**        | This interface is required only in the platform that has an OS.                                                                |

**tuya\_ble\_os\_msg\_queue\_peek**

| **Function name** | tuya\_ble\_os\_msg\_queue\_peek                                                                                                                             |
| ----------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Prototype**     | bool tuya\_ble\_os\_msg\_queue\_peek(void \*p\_handle, uint32\_t \*p\_msg\_num)                                                                             |
| **Description**   | Peeks the number of items sent and resided on the message queue.                                                                                            |
| **Parameters**    | <p>pp\_handle \[in]: the handle to the message queue being peeked.<br>p\_msg\_num\[out]: passes back the number of items residing on the message queue.</p> |
| **Responses**     | <p>True: message queue was peeked successfully.<br>False: message queue was failed to peek.</p>                                                             |
| **Notice**        | This interface is required only in the platform that has an OS.                                                                                             |

**tuya\_ble\_os\_msg\_queue\_send**

| **Function name** | tuya\_ble\_os\_msg\_queue\_send                                                                                                                                                                                                                                                                                                                                                                                                                           |
| ----------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Prototype**     | bool tuya\_ble\_os\_msg\_queue\_send(void \*p\_handle, void \*p\_msg, uint32\_t wait\_ms)                                                                                                                                                                                                                                                                                                                                                                 |
| **Description**   | Sends an item to the back of the specified message queue.                                                                                                                                                                                                                                                                                                                                                                                                 |
| **Parameters**    | <p>pp\_handle \[in]: the handle to the message queue on which the item is to be sent.<br>p\_msg\[in]: pointer to the item that is to be sent on the queue.<br>wait\_ms\[in]: the maximum amount of time in milliseconds that the task should block waiting for the item to sent on the queue.<br>- 0: no blocking and return immediately.<br>- 0xFFFFFFFF: blocks infinitely until the item received.<br>- others: the timeout value in milliseconds.</p> |
| **Responses**     | <p>True: message item was sent successfully.<br>False: message item was failed to send.</p>                                                                                                                                                                                                                                                                                                                                                               |
| **Notice**        | This interface is required only in the platform that has an OS.                                                                                                                                                                                                                                                                                                                                                                                           |

**tuya\_ble\_os\_msg\_queue\_recv**

| **Function name** | tuya\_ble\_os\_msg\_queue\_recv                                                                                                                                                                                                                                                                                                                                                                                                                                                    |
| ----------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Prototype**     | bool tuya\_ble\_os\_msg\_queue\_recv(void \*p\_handle, void \*p\_msg, uint32\_t wait\_ms)                                                                                                                                                                                                                                                                                                                                                                                          |
| **Description**   | Receives an item from the specified message queue.                                                                                                                                                                                                                                                                                                                                                                                                                                 |
| **Parameters**    | <p>pp\_handle \[in]: the handle to the message queue from which the item is to be received.<br>p\_msg\[out]: pointer to the buffer into which the received item will be copied.<br>wait\_ms\[in]: the maximum amount of time in milliseconds that the task should block waiting for the item to received on the queue.<br>- 0: no blocking and return immediately.<br>- 0xFFFFFFFF: blocks infinitely until the item received.<br>- others: the timeout value in milliseconds.</p> |
| **Responses**     | <p>True: message item was received successfully.<br>False: message item was failed to receive.</p>                                                                                                                                                                                                                                                                                                                                                                                 |
| **Notice**        | This interface is required only in the platform that has an OS.                                                                                                                                                                                                                                                                                                                                                                                                                    |

**tuya\_ble\_event\_queue\_send\_port**

| **Function name** | tuya\_ble\_event\_queue\_send\_port                                                                                                                                                                                                                                                                                                                               |
| ----------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Prototype**     | bool tuya\_ble\_event\_queue\_send\_port(tuya\_ble\_evt\_param\_t \*evt, uint32\_t wait\_ms)                                                                                                                                                                                                                                                                      |
| **Description**   | <p>If the TUYA\_BLE\_SELF\_BUILT\_TASK is undefined, Application should provide the task to sdk to process the event.<br>The sdk will use this port to send event to the task of provided by Application.</p>                                                                                                                                                     |
| **Parameters**    | <p>evt \[in]: the message data point to be send.<br>wait\_ms\[in]: the maximum amount of time in milliseconds that the task should block waiting for the item to sent on the queue.</p><ul><li>0: no blocking and return immediately.</li><li>0xFFFFFFFF: blocks infinitely until the item received.</li><li>others: the timeout value in milliseconds.</li></ul> |
| **Responses**     | <p>True: message item was sent successfully.<br>False: message item was failed to send.</p>                                                                                                                                                                                                                                                                       |
| **Notice**        | This interface is required only in the platform that has an OS.                                                                                                                                                                                                                                                                                                   |

**tuya\_ble\_aes128\_ecb\_encrypt**

| **Function name** | tuya\_ble\_aes128\_ecb\_encrypt                                                                                                                                                                                                                         |
| ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Prototype**     | bool tuya\_ble\_aes128\_ecb\_encrypt(uint8\_t \*key,uint8\_t \*input,uint16\_tinput\_len,uint8\_t \*output)                                                                                                                                             |
| **Description**   | 128 bit AES ECB encryption on specified plaintext and keys.                                                                                                                                                                                             |
| **Parameters**    | <p>key \[in]: keys to encrypt the plaintext<br>In\_put\[in]: specified plaintext to be encrypted.<br>in\_put\_len\[in]: byte length of the data to be encrypted, must be multiples of 16.<br>Out\_put\[out]: output buffer to store encrypted data.</p> |
| **Responses**     | <p>True: successful.<br>False: fail.</p>                                                                                                                                                                                                                |

**tuya\_ble\_aes128\_ecb\_decrypt**

| **Function name** | tuya\_ble\_aes128\_ecb\_decrypt                                                                                                                                                                                                                            |
| ----------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Prototype**     | bool tuya\_ble\_aes128\_ecb\_decrypt(uint8\_t \*key,uint8\_t \*input,uint16\_tinput\_len,uint8\_t \*output)                                                                                                                                                |
| **Description**   | 128 bit AES ECB decryption on specified encrypted data and keys                                                                                                                                                                                            |
| **Parameters**    | <p>key \[in]: keys to decrypt the plaintext<br>In\_put\[in]: specified encrypted data to be decypted<br>in\_put\_len\[in]: byte length of the data to be decrypted, must be multiples of 16.<br>Out\_put\[out]: output buffer to store decrypted data.</p> |
| **Responses**     | <p>True: successful.<br>False: fail.</p>                                                                                                                                                                                                                   |

**tuya\_ble\_aes128\_cbc\_encrypt**

| **Function name** | tuya\_ble\_aes128\_cbc\_encrypt                                                                                                                                                                                                                                                                                |
| ----------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Prototype**     | bool tuya\_ble\_aes128\_cbc\_encrypt(uint8\_t \*key,uint8\_t \*iv,uint8\_t *input,uint16\_t input\_len,uint8\_t*output)                                                                                                                                                                                        |
| **Description**   | 128 bit AES CBC encryption on specified plaintext and keys.                                                                                                                                                                                                                                                    |
| **Parameters**    | <p>key \[in]: keys to encrypt the plaintext.<br>iv\[in]: initialization vector (IV) for CBC mode.<br>In\_put\[in]: specified plain text to be encrypted.<br>in\_put\_len\[in]: byte length of the data to be encrypted, must be multiples of 16.<br>Out\_put\[out]: output buffer to store encrypted data.</p> |
| **Responses**     | <p>True: successful.<br>False: fail.</p>                                                                                                                                                                                                                                                                       |

**tuya\_ble\_aes128\_cbc\_decrypt**

| **Function name** | tuya\_ble\_aes128\_cbc\_decrypt                                                                                                                                                                                                                                                                                   |
| ----------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Prototype**     | bool tuya\_ble\_aes128\_cbc\_decrypt(uint8\_t\*key,uint8\_t \*iv,uint8\_t \*input,uint16\_t input\_len,uint8\_t \*output)                                                                                                                                                                                         |
| **Description**   | 128 bit AES CBC decryption on specified plaintext and keys.                                                                                                                                                                                                                                                       |
| **Parameters**    | <p>key \[in]: keys to decrypt the plaintext.<br>Iv\[in]: initialization vector (IV) for CBC mode<br>In\_put\[in]: specified encrypted data to be decrypted.<br>in\_put\_len\[in]: byte length of the data to be decrypted, must be multiples of 16.<br>Out\_put\[out]: output buffer to store decrypted data.</p> |
| **Responses**     | <p>True: successful.<br>False: fail.</p>                                                                                                                                                                                                                                                                          |

**tuya\_ble\_md5\_crypt**

| **Function name** | tuya\_ble\_md5\_crypt                                                                                                                                                                                                 |
| ----------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Prototype**     | booltuya\_ble\_md5\_crypt(uint8\_t \*input,uint16\_t input\_len,uint8\_t \*output)                                                                                                                                    |
| **Description**   | MD5 checksum.                                                                                                                                                                                                         |
| **Parameters**    | <p>In\_put\[in]: specified plain text to be encrypted.<br>in\_put\_len\[in]: byte length of the data to be encrypted.<br>Out\_put\[out]: output buffer to store md5 result data,output data lenghth is always 16.</p> |
| **Responses**     | <p>True: successful.<br>False: fail.</p>                                                                                                                                                                              |

**tuya\_ble\_hmac\_sha1\_crypt**

| **Function name** | tuya\_ble\_hmac\_sha1\_crypt                                                                                                                                                                                                                                                          |
| ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Prototype**     | <p>bool tuya\_ble\_hmac\_sha1\_crypt(constuint8\_t \*key, uint32\_t key\_len,<br>const uint8\_t \*input, uint32\_t input\_len,uint8\_t \*output)</p>                                                                                                                                  |
| **Description**   | Calculates the full generic HMAC on the input buffer with the provided key.                                                                                                                                                                                                           |
| **Parameters**    | <p>key \[in]: The HMAC secret key.<br>key\_len\[in]: The length of the HMAC secret key in bytes.<br>In\_put\[in]: specified plain text to be encrypted.<br>in\_put\_len\[in]: byte length of the data to be encrypted.<br>Out\_put\[out]: output buffer to store the result data.</p> |
| **Responses**     | <p>True: successful.<br>False: fail.</p>                                                                                                                                                                                                                                              |
| **Notice**        | Not used currently, no need to implement.                                                                                                                                                                                                                                             |

**tuya\_ble\_hmac\_sha256\_crypt**

| **Function name** | tuya\_ble\_hmac\_sha1\_crypt                                                                                                                                                                                                                                                          |
| ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Prototype**     | <p>bool tuya\_ble\_hmac\_sha256\_crypt(const uint8\_t \*key, uint32\_t key\_len,<br>const uint8\_t \*input, uint32\_t input\_len, uint8\_t \*output)</p>                                                                                                                              |
| **Description**   | Calculates the full generic HMAC on the input buffer with the provided key.                                                                                                                                                                                                           |
| **Parameters**    | <p>key \[in]: The HMAC secret key.<br>key\_len\[in]: The length of the HMAC secret key in Bytes.<br>In\_put\[in]: specified plain text to be encrypted.<br>in\_put\_len\[in]: byte length of the data to be encrypted.<br>out\_put\[out]: output buffer to store the result data.</p> |
| **Responses**     | <p>True: successful.<br>False: fail.</p>                                                                                                                                                                                                                                              |
| **Notice**        | Not used currently, no need to implement.                                                                                                                                                                                                                                             |

**tuya\_ble\_port\_malloc**

| **Function name** | tuya\_ble\_port\_malloc                                                                           |
| ----------------- | ------------------------------------------------------------------------------------------------- |
| **Prototype**     | void \*tuya\_ble\_port\_malloc( uint32\_t size )                                                  |
| **Description**   | Allocate a memory block with required size.                                                       |
| **Parameters**    | Size\[in]: Required memory size.                                                                  |
| **Responses**     | The address of the allocated memory block. If the address is NULL, the memory allocation failed.  |
| **Notice**        | You need to implement this interface only when `TUYA_BLE_USE_PLATFORM_MEMORY_HEAP` is set to `1`. |

**tuya\_ble\_port\_free**

| **Function name** | tuya\_ble\_port\_free                                                                             |
| ----------------- | ------------------------------------------------------------------------------------------------- |
| **Prototype**     | void tuya\_ble\_port\_free(void \*pv )                                                            |
| **Description**   | Frees a memory block that had been allocated.                                                     |
| **Parameters**    | pv\[in]: The address of memory block being freed.                                                 |
| **Responses**     | None.                                                                                             |
| **Notice**        | You need to implement this interface only when `TUYA_BLE_USE_PLATFORM_MEMORY_HEAP` is set to `1`. |

#### Reference of configuration APIs <a href="#title-11-reference-20of-20configuration-20apis" id="title-11-reference-20of-20configuration-20apis"></a>

The items in the `tuya_ble_config.h` file are used to configure the tuya ble sdk for different use cases, for example, network configuration for multi-protocol devices, whether running an OS on the platform or not, device communication, whether self-manage the authorization, and so forth.

**CUSTOMIZED\_TUYA\_BLE\_CONFIG\_FILE**

| **Macro**       | CUSTOMIZED\_TUYA\_BLE\_CONFIG\_FILE                                                                                                                                                                                                                                                                                                                                                  |
| --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| **Dependency**  | None.                                                                                                                                                                                                                                                                                                                                                                                |
| **Description** | <p>Custom configuration file.<br>This file overwrites the default settings in the <code>tuya\_ble\_config.h</code> file.<br>Your Application must create a configuration file with a new name, and assign the file name to the <code>CUSTOMIZED\_TUYA\_BLE\_CONFIG\_FILE</code>, for example, <code>CUSTOMIZED\_TUYA\_BLE\_CONFIG\_FILE = \<custom\_tuya\_ble\_config.h></code>.</p> |

**CUSTOMIZED\_TUYA\_BLE\_APP\_PRODUCT\_TEST\_HEADER\_FILE**

| **Macro**       | CUSTOMIZED\_TUYA\_BLE\_APP\_PRODUCT\_TEST\_HEADER\_FILE                                                                                                                                                                                                                                                                                      |
| --------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Dependency**  | None.                                                                                                                                                                                                                                                                                                                                        |
| **Description** | <p>The tuya ble sdk provides basic test and production authorization services.<br>If the Tuya testing protocol is used in your Application to perform many customized test activities, your must create a file to achieve that, and assign the header file name to <code>CUSTOMIZED\_TUYA\_BLE\_APP\_PRODUCT\_TEST\_HEADER\_FILE</code>.</p> |
| **Notice**      | It must be completed in the custom configuration file.                                                                                                                                                                                                                                                                                       |

**CUSTOMIZED\_TUYA\_BLE\_APP\_UART\_COMMON\_HEADER\_FILE**

| **Macro**       | CUSTOMIZED\_TUYA\_BLE\_APP\_UART\_COMMON\_HEADER\_FILE                    |
| --------------- | ------------------------------------------------------------------------- |
| **Dependency**  | None.                                                                     |
| **Description** | At present, it only applies to the general module protocol of Tuya Smart. |
| **Notice**      | It must be completed in the custom configuration file.                    |

**TUYA\_BLE\_USE\_OS**

| **Macro**       | TUYA\_BLE\_USE\_OS                                                                                                                                                               |
| --------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Dependency**  | None.                                                                                                                                                                            |
| **Description** | <p>If the chip architecture is based on OS, such as FreeRTOS, set<br><code>#define TUYA\_BLE\_USE\_OS 1</code>, otherwise, set<br><code>#define TUYA\_BLE\_USE\_OS 0</code>.</p> |

**TUYA\_BLE\_SELF\_BUILT\_TASK**

| **Macro**       | TUYA\_BLE\_SELF\_BUILT\_TASK                                                                                                                                                                                |
| --------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Dependency**  | `#define TUYA_BLE_USE_OS 1`                                                                                                                                                                                 |
| **Description** | For the OS architecture platform, if you use self-built tasks in the tuya ble sdk to handle messages, please set `#define TUYA_BLE_SELF_BUILT_TASK 1`, otherwise, set `#define TUYA_BLE_SELF_BUILT_TASK 0`. |

**TUYA\_BLE\_TASK\_PRIORITY**

| **Macro**       | TUYA\_BLE\_TASK\_PRIORITY                                                                               |
| --------------- | ------------------------------------------------------------------------------------------------------- |
| **Dependency**  | <p><code>#define TUYA\_BLE\_USE\_OS 1</code><br><code>#define TUYA\_BLE\_SELF\_BUILT\_TASK 1</code></p> |
| **Description** | The priority of a task initiated by tuya ble sdk. For example, `#define TUYA_BLE_TASK_PRIORITY 1`.      |
| **Notice**      | The priority value needs to be defined according to the OS used by the chip platform.                   |

**TUYA\_BLE\_TASK\_STACK\_SIZE**

| **Macro**       | TUYA\_BLE\_TASK\_STACK\_SIZE                                                                                |
| --------------- | ----------------------------------------------------------------------------------------------------------- |
| **Dependency**  | <p><code>#define TUYA\_BLE\_USE\_OS 1</code><br><code>#define TUYA\_BLE\_SELF\_BUILT\_TASK 1</code></p>     |
| **Description** | The stack size of a task initiated by tuya ble sdk. For example, `#define TUYA_BLE_TASK_STACK_SIZE 256*10`. |

**TUYA\_BLE\_DEVICE\_COMMUNICATION\_ABILITY**

| **Macro**       | TUYA\_BLE\_DEVICE\_COMMUNICATION\_ABILITY                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    |
| --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| **Dependency**  | None.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        |
| **Description** | <p>The communication of devices. Possible setting:<br><code>TUYA\_BLE\_DEVICE\_COMMUNICATION\_ABILITY\_BLE</code><br>: whether use BLE or not.<br><code>TUYA\_BLE\_DEVICE\_COMMUNICATION\_ABILITY\_REGISTER\_FROM\_BLE</code><br>: whether register devices via ble or not.<br><code>TUYA\_BLE\_DEVICE\_COMMUNICATION\_ABILITY\_MESH</code><br>: whether use Mesh or not.<br><code>TUYA\_BLE\_DEVICE\_COMMUNICATION\_ABILITY\_WIFI\_24G</code><br>: whether support 2.4G Wi-Fi or not.<br><code>TUYA\_BLE\_DEVICE\_COMMUNICATION\_ABILITY\_WIFI\_5G</code><br>: whether support 5G Wi-Fi or not.<br><code>TUYA\_BLE\_DEVICE\_COMMUNICATION\_ABILITY\_ZIGBEE</code><br>: whether support Zigbee or not.<br><code>TUYA\_BLE\_DEVICE\_COMMUNICATION\_ABILITY\_NB</code><br>: whether support NB-IoT or not.</p> |

**TUYA\_BLE\_DEVICE\_SHARED**

| **Macro**       | TUYA\_BLE\_DEVICE\_SHARED                                                                        |
| --------------- | ------------------------------------------------------------------------------------------------ |
| **Dependency**  | None.                                                                                            |
| **Description** | Determines whether a device is shared.                                                           |
| **Notice**      | If you do not understand what are shared devices, please set `#define TUYA_BLE_DEVICE_SHARED 0`. |

**TUYA\_BLE\_DEVICE\_UNBIND\_MODE**

| **Macro**       | TUYA\_BLE\_DEVICE\_UNBIND\_MODE                                                                       |
| --------------- | ----------------------------------------------------------------------------------------------------- |
| **Dependency**  | None.                                                                                                 |
| **Description** | Determines whether the shared devices need to perform the unbind operation.                           |
| **Notice**      | If you do not understand what are shared devices, please set `#define TUYA_BLE_DEVICE_UNBIND_MODE 1`. |

**TUYA\_BLE\_WIFI\_DEVICE\_REGISTER\_MODE**

| **Macro**       | TUYA\_BLE\_WIFI\_DEVICE\_REGISTER\_MODE                                                                                                                                                                                                                                                           |
| --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Dependency**  | The devices must support Wi-Fi connection.                                                                                                                                                                                                                                                        |
| **Description** | <p>Determines whether to send command to query the network configuration state or not when use BLE to configure network for Wi-Fi devices. If yes:<br><code>#define TUYA\_BLE\_WIFI\_DEVICE\_REGISTER\_MODE 1</code><br>If no: <code>#define TUYA\_BLE\_WIFI\_DEVICE\_REGISTER\_MODE 0</code></p> |
| **Notice**      | Currently not supported.                                                                                                                                                                                                                                                                          |

**TUYA\_BLE\_DEVICE\_AUTH\_SELF\_MANAGEMENT**

| **Macro**       | TUYA\_BLE\_DEVICE\_AUTH\_SELF\_MANAGEMENT                                                                                                                                                              |
| --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| **Dependency**  | None.                                                                                                                                                                                                  |
| **Description** | If you use self-built tasks in the tuya ble sdk to manage authorization, please set `#define TUYA_BLE_DEVICE_AUTH_SELF_MANAGEMENT 1`, otherwise, set `#define TUYA_BLE_DEVICE_AUTH_SELF_MANAGEMENT 0`. |
| **Notice**      | For BLE devices without Wi-Fi capability, this value is recommended to be defined as 1.                                                                                                                |

**TUYA\_BLE\_SECURE\_CONNECTION\_TYPE**

| **Macro**       | TUYA\_BLE\_SECURE\_CONNECTION\_TYPE                                                                                                                                                                                                                                                                                                                                                                                                                                                   |
| --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Dependency**  | None.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 |
| **Description** | <p>The communication encryption method of devices. Possible setting:<br><code>TUYA\_BLE\_SECURE\_CONNECTION\_WITH\_AUTH\_KEY</code><br>: encrypt with <code>auth\_key</code>.<br><code>TUYA\_BLE\_SECURE\_CONNECTION\_WITH\_ECC</code><br>: encrypt with ECDH.<br><code>TUYA\_BLE\_SECURE\_CONNECTION\_WTIH\_PASSTHROUGH</code><br>: no encrypt.<br>For example:<br><code>#define TUYA\_BLE\_DEVICE\_AUTH\_SELF\_MANAGEMENT TUYA\_BLE\_SECURE\_CONNECTION\_WITH\_AUTH\_KEY</code></p> |
| **Notice**      | Currently, only `TUYA_BLE_SECURE_CONNECTION_WITH_AUTH_KEY` is supported.                                                                                                                                                                                                                                                                                                                                                                                                              |

**TUYA\_BLE\_DEVICE\_MAC\_UPDATE**

| **Macro**       | TUYA\_BLE\_DEVICE\_MAC\_UPDATE                                                                                    |
| --------------- | ----------------------------------------------------------------------------------------------------------------- |
| **Dependency**  | None.                                                                                                             |
| **Description** | Determines whether to use the MAC address in the Tuya authorization information as the device MAC address or not. |

**TUYA\_BLE\_DEVICE\_MAC\_UPDATE\_RESET**

| **Macro**       | TUYA\_BLE\_DEVICE\_MAC\_UPDATE\_RESET                                                                                                                                                                                                                      |
| --------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Dependency**  | `#define TUYA_BLE_DEVICE_MAC_UPDATE 1`                                                                                                                                                                                                                     |
| **Description** | <p>Determines whether the device needs to restart after updating the MAC address to take effect or not. If yes:<br><code>#define TUYA\_BLE\_DEVICE\_MAC\_UPDATE\_RESET 1</code><br>If no: <code>#define TUYA\_BLE\_DEVICE\_MAC\_UPDATE\_RESET 0</code></p> |

**TUYA\_BLE\_USE\_PLATFORM\_MEMORY\_HEAP**

| **Macro**       | TUYA\_BLE\_USE\_PLATFORM\_MEMORY\_HEAP                                                                                                                                                                 |
| --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| **Dependency**  | None.                                                                                                                                                                                                  |
| **Description** | <p>Whether tuya ble sdk uses its own memory heap. If yes:<br><code>#define TUYA\_BLE\_USE\_PLATFORM\_MEMORY\_HEAP 0</code><br>If no: <code>#define TUYA\_BLE\_USE\_PLATFORM\_MEMORY\_HEAP 1</code></p> |
| **Notice**      | If it is defined as `1`, your Application must port and implement memory management ability in the porting layer for tuya ble sdk.                                                                     |

**TUYA\_BLE\_GATT\_SEND\_DATA\_QUEUE\_SIZE**

| **Macro**       | TUYA\_BLE\_GATT\_SEND\_DATA\_QUEUE\_SIZE                                                                                                            |
| --------------- | --------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Dependency**  | None.                                                                                                                                               |
| **Description** | <p>The size of the GATT send queue used by tuya ble sdk. Default value: 20.<br><code>#define TUYA\_BLE\_GATT\_SEND\_DATA\_QUEUE\_SIZE 20</code></p> |
| **Notice**      | If you do not know much about the macro, it is recommended to keep it at 20.                                                                        |

**TUYA\_BLE\_DATA\_MTU\_MAX**

| **Macro**       | TUYA\_BLE\_DATA\_MTU\_MAX                                                                   |
| --------------- | ------------------------------------------------------------------------------------------- |
| **Dependency**  | None.                                                                                       |
| **Description** | <p>The size of GATT MTU:<br><code>#define TUYA\_BLE\_DATA\_MTU\_MAX 20</code></p>           |
| **Notice**      | Currently, only 20 bytes GATT MTU are supported, which will be expanded and upgraded later. |

**TUYA\_BLE\_LOG\_ENABLE**

| **Macro**       | TUYA\_BLE\_LOG\_ENABLE                                                                                                                                                           |
| --------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Dependency**  | None.                                                                                                                                                                            |
| **Description** | <p>Determines whether to enable log of tuya ble sdk or not.<br>If yes: <code>#define TUYA\_BLE\_LOG\_ENABLE 1</code><br>If no: <code>#define TUYA\_BLE\_LOG\_ENABLE 0</code></p> |
| **Notice**      | Enabling the internal log consumes the code space. It is recommended to turn on it for the debug version and turn off for the release version.                                   |

**TUYA\_BLE\_LOG\_COLORS\_ENABLE**

| **Macro**       | TUYA\_BLE\_LOG\_COLORS\_ENABLE                                                                                                                                                                                       |
| --------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Dependency**  | `#define TUYA_BLE_LOG_ENABLE 1`                                                                                                                                                                                      |
| **Description** | <p>Determines whether to enable the multi-color display for logs of SDK or not.<br>If yes: <code>#define TUYA\_BLE\_LOG\_COLORS\_ENABLE 1</code><br>If no: <code>#define TUYA\_BLE\_LOG\_COLORS\_ENABLE 0</code></p> |
| **Notice**      | Some tools do not support it, for example, RTT of J-link.                                                                                                                                                            |

**TUYA\_BLE\_LOG\_LEVEL**

| **Macro**       | TUYA\_BLE\_LOG\_LEVEL                                                                                                                                                                                                                                                                                                                                                                                                                                                   |
| --------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Dependency**  | `#define TUYA_BLE_LOG_ENABLE 1`                                                                                                                                                                                                                                                                                                                                                                                                                                         |
| **Description** | <p>Defines the display level of the log of tuya ble sdk, which is divided into the following levels:<br><code>#defineTUYA\_BLE\_LOG\_LEVEL\_ERROR 1U</code><br><code>#defineTUYA\_BLE\_LOG\_LEVEL\_WARNING 2U</code><br><code>#defineTUYA\_BLE\_LOG\_LEVEL\_INFO 3U</code><br><code>#defineTUYA\_BLE\_LOG\_LEVEL\_DEBUG 4U</code><br>If only error information needs to be printed, set as: <code>#define TUYA\_BLE\_LOG\_LEVEL TUYA\_BLE\_LOG\_LEVEL\_ERROR</code></p> |

**TUYA\_APP\_LOG\_ENABLE**

| **Macro**       | TUYA\_APP\_LOG\_ENABLE                                                                                                                                     |
| --------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Dependency**  | None.                                                                                                                                                      |
| **Description** | <p>Whether to enable Application log.<br>If yes: <code>#define TUYA\_APP\_LOG\_ENABLE 1</code><br>If no: <code>#define TUYA\_APP\_LOG\_ENABLE 0</code></p> |
| **Notice**      | Enabling the internal log consumes the code space. It is recommended to turn on it for the debug version and turn off for the release version.             |

**TUYA\_APP\_LOG\_COLORS\_ENABLE**

| **Macro**       | TUYA\_APP\_LOG\_COLORS\_ENABLE                                                                                                                                                                                               |
| --------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Dependency**  | `#define TUYA_APP_LOG_ENABLE 1`                                                                                                                                                                                              |
| **Description** | <p>Determines whether to enable the multi-color display for logs of Application or not.<br>If yes: <code>#define TUYA\_APP\_LOG\_COLORS\_ENABLE 1</code><br>If no: <code>#define TUYA\_APP\_LOG\_COLORS\_ENABLE 0</code></p> |
| **Notice**      | Some tools do not support it, for example, RTT of J-Link.                                                                                                                                                                    |

**TUYA\_APP\_LOG\_LEVEL**

| **Macro**       | TUYA\_APP\_LOG\_LEVEL                                                                                                                                                                                                                                                                                                                                                                                                                                                      |
| --------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Dependency**  | `#define TUYA_APP_LOG_ENABLE 1`                                                                                                                                                                                                                                                                                                                                                                                                                                            |
| **Description** | <p>Defines the display level of the log of tuya ble sdk, which is divided into the following levels:<br><code>#defineTUYA\_APP\_LOG\_LEVEL\_ERROR 1U</code><br><code>#defineTUYA\_APP\_LOG\_LEVEL\_WARNING 2U</code><br><code>#defineTUYA\_APP\_LOG\_LEVEL\_INFO 3U</code><br><code>#defineTUYA\_APP\_LOG\_LEVEL\_DEBUG 4U</code><br>If only error information needs to be printed, set as:<br><code>#define TUYA\_APP\_LOG\_LEVEL TUYA\_APP\_LOG\_LEVEL\_ERROR</code></p> |

**TUYA\_BLE\_ADVANCED\_ENCRYPTION\_DEVICE**

| **Macro**       | TUYA\_BLE\_ADVANCED\_ENCRYPTION\_DEVICE                                                                                                                                                                         |
| --------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Dependency**  | None.                                                                                                                                                                                                           |
| **Description** | <p>Determines whether to use advanced encryption method.<br>If yes: <code>#define TUYA\_BLE\_ADVANCED\_ENCRYPTION\_DEVICE 1</code><br>If no: <code>#define TUYA\_BLE\_ADVANCED\_ENCRYPTION\_DEVICE 0</code></p> |
| **Notice**      | It is not supported currently.                                                                                                                                                                                  |

**TUYA\_NV\_ERASE\_MIN\_SIZE**

| **Macro**       | TUYA\_NV\_ERASE\_MIN\_SIZE                                                                                                                  |
| --------------- | ------------------------------------------------------------------------------------------------------------------------------------------- |
| **Dependency**  | None.                                                                                                                                       |
| **Description** | <p>The minimum erasure unit of NV space allocated to tuya ble sdk, for example:<br><code>#define TUYA\_NV\_ERASE\_MIN\_SIZE 4096</code></p> |
| **Notice**      | It must be defined according to the implementation of NV interface in the port layer.                                                       |

**TUYA\_NV\_WRITE\_GRAN**

| **Macro**       | TUYA\_NV\_WRITE\_GRAN                                                                                                                                    |
| --------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Dependency**  | None.                                                                                                                                                    |
| **Description** | <p>The maximum write granularity in the NV space. For example,<br><code>#define TUYA\_NV\_WRITE\_GRAN 4</code><br>allows 4 bytes if you write to NV.</p> |
| **Notice**      | It must be defined according to the implementation of NV interface in the port layer.                                                                    |

**TUYA\_NV\_START\_ADDR**

| **Macro**       | TUYA\_NV\_START\_ADDR                                                                                                             |
| --------------- | --------------------------------------------------------------------------------------------------------------------------------- |
| **Dependency**  | None.                                                                                                                             |
| **Description** | <p>The initial NV space address allocated to tuya ble sdk. For example:<br><code>#define TUYA\_NV\_START\_ADDR 0x1000</code>.</p> |

**TUYA\_NV\_AREA\_SIZE**

| **Macro**       | TUYA\_NV\_AREA\_SIZE                                                                                                                                                                                                              |
| --------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Dependency**  | None.                                                                                                                                                                                                                             |
| **Description** | <p>The NV space size allocated to tuya ble sdk. For example, <code>#define TUYA\_NV\_AREA\_SIZE (4\*TUYA\_NV\_ERASE\_MIN\_SIZE)</code><br>. The value must be an integer multiple of <code>TUYA\_NV\_ERASE\_MIN\_SIZE</code>.</p> |

**TUYA\_BLE\_APP\_VERSION\_STRING**

| **Macro**       | TUYA\_BLE\_APP\_VERSION\_STRING                                                                  |
| --------------- | ------------------------------------------------------------------------------------------------ |
| **Dependency**  | None.                                                                                            |
| **Description** | The Application version number string, for example, `#define TUYA_BLE_APP_VERSION_STRING "1.0"`. |
| **Notice**      | Currently, only two digit version numbers are supported.                                         |

**TUYA\_BLE\_APP\_BUILD\_FIRMNAME\_STRING**

| **Macro**       | TUYA\_BLE\_APP\_BUILD\_FIRMNAME\_STRING                                                                               |
| --------------- | --------------------------------------------------------------------------------------------------------------------- |
| **Dependency**  | None.                                                                                                                 |
| **Description** | The Application firmware name, for example, `#define TUYA_BLE_APP_BUILD_FIRMNAME_STRING "tuya_ble_sdk_app_demo_xxx"`. |
| **Notice**      | It is only required when you use the Tuya production testing license agreement.                                       |

### API reference <a href="#title-12-api-20reference" id="title-12-api-20reference"></a>

The tuya ble sdk provides packaged API for Application to achieve BLE related management, communication, and so forth. The APIs are defined in the `tuya_ble_api.c` and `tuya_ble_api.h` files, you can read the source code to understand how the APIs are implemented. The following tables describes the details of each API.

**tuya\_ble\_main\_tasks\_exec**

| **Function name** | tuya\_ble\_main\_tasks\_exec                                                                                                               |
| ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------ |
| **Prototype**     | void tuya\_ble\_main\_tasks\_exec(void)                                                                                                    |
| **Description**   | The tuya ble sdk event main scheduler when using the non-OS architecture chip platform. The Application can call it only in the main loop. |
| **Parameters**    | None.                                                                                                                                      |
| **Responses**     | None.                                                                                                                                      |
| **Notice**        | <p>This function must be called from within the main loop.<br>It will execute all events scheduled since the last time it was called.</p>  |

> Example: the calling location under nrf52832 platform is as follows:

```
/**@brief Function for handling the idle state (main loop).
 *
 * @details If there is no pending log operation, then sleep until next the next event occurs.
 */
static void idle_state_handle(void)
{
    tuya_ble_main_tasks_exec();

    if (NRF_LOG_PROCESS() == false)
    {
        nrf_pwr_mgmt_run();
    }

}
```

**tuya\_ble\_gatt\_receive\_data**

| **Function name** | tuya\_ble\_gatt\_receive\_data                                                                                                                           |
| ----------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Prototype**     | tuya\_ble\_status\_t tuya\_ble\_gatt\_receive\_data(uint8\_t\*p\_data,uint16\_t len);                                                                    |
| **Description**   | By calling this function, the GATT data received by Bluetooth is sent to tuya ble sdk.                                                                   |
| **Parameters**    | <p>p\_data\[in]: point to the data to be sent.<br>len\[in]: the length of the data to be sent, cannot exceed <code>TUYA\_BLE\_DATA\_MTU\_MAX</code>.</p> |
| **Responses**     | <p>TUYA\_BLE\_SUCCESS: send successfully.<br>TUYA\_BLE\_ERR\_INTERNAL: failed.</p>                                                                       |
| **Notice**        | This function must be called from where the BLE data is received.                                                                                        |

> Example (nrf52832 example demo):

```
/**@brief Function for handling the data from the Nordic UART Service.
 *
 * @details This function will process the data received from the Nordic UART BLE Service and send
 *          it to the UART module.
 *
 * @param[in] p_evt       Nordic UART Service event.
 */
/**@snippet [Handling the data received over BLE] */
static void nus_commdata_handler(ble_nus_evt_t * p_evt)
{

    if (p_evt->type == BLE_NUS_EVT_RX_DATA)
    {
        tuya_ble_gatt_receive_data((uint8_t*)(p_evt->params.rx_data.p_data),p_evt->params.rx_data.length);
        TUYA_BLE_HEXDUMP("nus_commdata_handler :",20,(uint8_t*)(p_evt->params.rx_data.p_data),p_evt->params.rx_data.length);
    }

}
```

**tuya\_ble\_common\_uart\_receive\_data**

| **Function name** | tuya\_ble\_common\_uart\_receive\_data                                                                                                                                                                                                                                                                                                               |
| ----------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Prototype**     | tuya\_ble\_status\_t tuya\_ble\_common\_uart\_receive\_data (uint8\_t \*p\_data,uint16\_t len)                                                                                                                                                                                                                                                       |
| **Description**   | <p>If an Application uses the production testing authorization module provided by tuya ble sdk, you need to send UART data to tuya ble sdk by calling this function.<br>If you do not use the production testing authorization function module provided by tuya ble sdk, you do not need to call this function.</p>                                  |
| **Parameters**    | <p>p\_data\[in]: point to the data to be sent.<br>len\[in]: length of data to be sent.</p>                                                                                                                                                                                                                                                           |
| **Responses**     | <p>TUYA\_BLE\_SUCCESS: sent successfully.<br>Other: failed to send.</p>                                                                                                                                                                                                                                                                              |
| **Notice**        | <p>This function internally calls malloc to apply for memory.<br>If the Application configuration uses the malloc interface provided by the platform,<br>confirm whether the platform malloc supports interrupt calls.<br>If it does not support, it must not be called in UART interrupt <code>tuya\_ble\_common\_uart\_receive\_data()</code>.</p> |

**tuya\_ble\_common\_uart\_send\_full\_instruction\_received**

| **Function name** | tuya\_ble\_common\_uart\_send\_full\_instruction\_received                                                                                                                                                                                                                                                                                                                                                                                                                                                                     |
| ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| **Prototype**     | <p>tuya\_ble\_status\_t.<br>tuya\_ble\_common\_uart\_send\_full\_instruction\_received (uint8\_t \*p\_data,uint16\_t len)</p>                                                                                                                                                                                                                                                                                                                                                                                                  |
| **Description**   | <p>Sends the Tuya production testing protocol command (including the <code>cmd/data/checksum</code>) that are received and resolved by the UART to tuya ble sdk.<br>If your Application does not use the protocol parsing function<br><code>tuya\_ble\_common\_uart\_receive\_data()</code> provided by tuya ble sdk but uses a custom UART parsing function to<br>parse the production testing protocol data, you need to call this function to send the parsed completed production testing instruction to tuya ble sdk.</p> |
| **Parameters**    | <p>p\_data\[in]: Point to the complete command data to be sent.<br>len\[in]: Command data length to be sent.</p>                                                                                                                                                                                                                                                                                                                                                                                                               |
| **Responses**     | <p>TUYA\_BLE\_SUCCESS: Sent successfully.<br>TUYA\_BLE\_ERR\_INVALID\_PARAM: parameter error.<br>TUYA\_BLE\_ERR\_NO\_MEM: Failed to apply for memory.<br>TUYA\_BLE\_ERR\_BUSY: BLE SDK busy.</p>                                                                                                                                                                                                                                                                                                                               |
| **Notice**        | <p>This function internally calls the malloc interface. If the Application is configured to use the chip platform-provided malloc interface,<br>make sure that platform malloc supports interrupt calls.<br>If it does not, you must not call <code>tuya\_ble\_common\_uart\_send\_full\_instruction\_received()</code> in the UART interrupt.</p>                                                                                                                                                                             |

> Explanation:

* The tuya ble sdk integrates the production testing authorization function module. The production testing authorization module communicates through the UART and PC production testing authorization tools. UART communication has a complete set of command formats. For details, refer to the Bluetooth General Production Test Authorization Agreement.
* The tuya ble sdk includes the UART communication instruction parsing function. The Application only needs to call the `tuya_ble_common_uart_receive_data()` function where UART data is received. The Application can also parse out the complete UART communication instruction, and then call `tuya_ble_common_uart_send_full_instruction_received()` function to send a complete command to tuya ble sdk.

**tuya\_ble\_device\_update\_product\_id**

| **Function name** | tuya\_ble\_device\_update\_product\_id                                                                                                                      |
| ----------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Prototype**     | <p>tuya\_ble\_status\_t tuya\_ble\_device\_update\_product\_id.<br>(tuya\_ble\_product\_id\_type\_t type, uint8\_t len, uint8\_t\* p\_buf)</p>              |
| **Description**   | Updates product id function.                                                                                                                                |
| **Parameters**    | <p>type \[in]: id type.<br>len\[in]: id length.<br>p\_buf\[in]: id data.</p>                                                                                |
| **Responses**     | <p>TUYA\_BLE\_SUCCESS: Sent successfully.<br>TUYA\_BLE\_ERR\_INVALID\_PARAM: parameter error.<br>TUYA\_BLE\_ERR\_INTERNAL: internal error.</p>              |
| **Notice**        | In the SoC development scheme based on tuya ble sdk, it is generally not necessary to call this function, because the product ID generally does not change. |

**tuya\_ble\_device\_update\_login\_key**

| **Function name** | tuya\_ble\_device\_update\_login\_key                                                                                                                                                                                                                                                                                                         |
| ----------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Prototype**     | tuya\_ble\_status\_t tuya\_ble\_device\_update\_login\_key(uint8\_t\* p\_buf, uint8\_t len)                                                                                                                                                                                                                                                   |
| **Description**   | Updates login key function.                                                                                                                                                                                                                                                                                                                   |
| **Parameters**    | <p>len\[in]: length.<br>p\_buf\[in]: loginkey.</p>                                                                                                                                                                                                                                                                                            |
| **Responses**     | <p>TUYA\_BLE\_SUCCESS: Sent successfully.<br>TUYA\_BLE\_ERR\_INVALID\_PARAM: parameter error.<br>TUYA\_BLE\_ERR\_INTERNAL: internal error.</p>                                                                                                                                                                                                |
| **Notice**        | <p>This API is mainly used in Wi-Fi/BLE dual-protocol devices.<br>Send network configuration information to Wi-Fi through BLE. The device registers the device with the cloud through Wi-Fi and calls.<br>the login key after successful registration This function is sent to tuya ble sdk, but also needs to update the binding status.</p> |

**tuya\_ble\_device\_update\_bound\_state**

| **Function name** | tuya\_ble\_device\_update\_bound\_state                                                                                                                                                                                                                         |
| ----------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Prototype**     | tuya\_ble\_status\_t tuya\_ble\_device\_update\_bound\_state(uint8\_t state)                                                                                                                                                                                    |
| **Description**   | Updates registration binding status.                                                                                                                                                                                                                            |
| **Parameters**    | state\[in]: 1-The device is registered for binding，0-The device is not registered for binding.                                                                                                                                                                  |
| **Responses**     | <p>TUYA\_BLE\_SUCCESS: Sent successfully.<br>TUYA\_BLE\_ERR\_INVALID\_PARAM: parameter error.<br>TUYA\_BLE\_ERR\_INTERNAL: internal error.</p>                                                                                                                  |
| **Notice**        | <p>This API is mainly used in Wi-Fi/BLE dual-protocol devices.<br>(After the device registers and binds successfully through the Wi-Fi link, this function is called to update the binding status to tuya ble sdk.<br>It also requires updating login key).</p> |

**tuya\_ble\_device\_update\_mcu\_version**

| **Function name** | tuya\_ble\_device\_update\_mcu\_version                                                                                                                                                      |
| ----------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Prototype**     | tuya\_ble\_status\_t tuya\_ble\_device\_update\_mcu\_version(uint32\_t mcu\_firmware\_version, uint32\_t mcu\_hardware\_version)                                                             |
| **Description**   | Updates external mcu version number.                                                                                                                                                         |
| **Parameters**    | <p>mcu\_firmware\_version \[in]: MCU Firmware version number，For example, 0x010101 indicates v1.1.1.<br>mcu\_hardware\_version \[in]: MCU hardware version number (PCBA version number).</p> |
| **Responses**     | <p>TUYA\_BLE\_SUCCESS: Sent successfully.<br>Other: failed.</p>                                                                                                                              |
| **Notice**        | The API is mainly used to develop BLE module, SoC development program does not need to use.                                                                                                  |

**tuya\_ble\_sdk\_init**

| **Function name** | tuya\_ble\_sdk\_init                                                                                                                                                                                                   |
| ----------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Prototype**     | tuya\_ble\_status\_t tuya\_ble\_sdk\_init(tuya\_ble\_device\_param\_t \* param\_data)                                                                                                                                  |
| **Description**   | The tuya ble sdk initialization function.                                                                                                                                                                              |
| **Parameters**    | param\_data \[in]: Initialize parameter.                                                                                                                                                                               |
| **Responses**     | <p>TUYA\_BLE\_SUCCESS: Sent successfully.<br>TUYA\_BLE\_ERR\_INVALID\_PARAM: parameter error.</p>                                                                                                                      |
| **Notice**        | <p>Initialization function, the Application must call this function to initialize the SDK, otherwise the SDK will not work.<br>The initialization function may also be <code>tuya\_ble\_sdk\_init\_async()</code>.</p> |

> Parameter explanation:

The structure of `tuya_ble_device_param_t` is as follows:

```
typedef struct{
    uint8_t device_id_len;   //if ==20,Compressed into 16
	uint8_t device_id[DEVICE_ID_LEN_MAX];
    tuya_ble_product_id_type_t p_type;
    uint8_t product_id_len;
	uint8_t product_id[TUYA_BLE_PRODUCT_ID_MAX_LEN];
    uint8_t device_vid[DEVICE_VIRTUAL_ID_LEN];
	uint8_t auth_key[AUTH_KEY_LEN];
	uint8_t login_key[LOGIN_KEY_LEN];
    uint8_t bound_flag;
    uint32_t firmware_version; //0x00010102: v1.1.2
    uint32_t hardware_version;
    uint8_t reserve_1;
    uint8_t reserve_2;
}tuya_ble_device_param_t;
```

The following items describe the variables in the preceding snippet.

* `device_id` and `auth_key`: the `device_uuid` and the `auth_key` are unique identifier pairs assigned to the BLE devices by the Tuya IoT platform. They are required when you perform the production testing authorization via Tuya testing tool. After a BLE device is authorized by production testing, the tuya ble sdk takes control of and manages them automatically. Therefore, you can set the `device_uuid` ad the `auth_key` to `0` when the tuya ble sdk is initialized. If they are not `0`, the tuya ble sdk uses the pre-defined `device_id` and `auth_key`. For a Wi-Fi/BLE dual-mode device, its`device_id` and `auth_key` are managed by the Wi-Fi layer, therefore, the actual `device_id` and `auth_key` are needed when the tuya ble sdk is initialized.
* `product_id`: pid for short. It is automatically generated when a new product is created on the IoT platform. In your Application, the PID needs to be saved in the form of a constant. It is required when initializing the tuya ble sdk.
* `device_vid`: the virtual ID of a BLE device, which is generated by Tuya IoT platform after the binding of the notice volume. It can be used to find the data record of the cloud to the BLE device when the BLE device is added or removed. For BLE devices that need the authorization information of the tuya ble sdk management, the value is `0`. For Wi-Fi/BLE dual mode devices, or BLE devices of which the authorization is managed by your Application, the actual `device_vid` is needed.
* `login_key` and `bound_flag`: if the authorization of BLE devices are managed by the tuya ble sdk, set the values to `0`. For Wi-Fi/BLE dual mode devices, or BLE devices of which the authorization is managed by your Application, the actual values are needed.
* `firmware_version` and `hardware_version`: indicates the firmware version number and the hardware (PCBA) version number of BLE devices. They are required when initializing the tuya ble sdk. Currently, BLE devices only support two digit version numbers, for example 0x0100 represents v1.0.

The following snippet is the initialization example of tuya ble sdk for nrf52832 platform.

```
static const char auth_key_test[] = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
static const char device_id_test[] = "yyyyyyyyyyyyyyyy";

#define APP_PRODUCT_ID  "vvvvvvvv"

void tuya_ble_app_init(void)
{
	tuya_ble_device_param_t device_param = {0};
    device_param.device_id_len = 16;
    memcpy(device_param.auth_key,(void *)auth_key_test,AUTH_KEY_LEN);
    memcpy(device_param.device_id,(void *)device_id_test,DEVICE_ID_LEN);
    device_param.p_type = TUYA_BLE_PRODUCT_ID_TYPE_PID;
    device_param.product_id_len = 8;
    memcpy(device_param.product_id,APP_PRODUCT_ID,8);
    device_param.firmware_version = TY_APP_VER_NUM;
    device_param.hardware_version = TY_HARD_VER_NUM;

    tuya_ble_sdk_init(&device_param);
    tuya_ble_callback_queue_register(tuya_cb_handler);

    tuya_ota_init();
}

/*nrf52832 example*/
int main(void)
{
    bool erase_bonds;

    // Initialize.
    uart_init();
    app_log_init();
    timers_init();
    buttons_leds_init(&erase_bonds);
    power_management_init();
    ble_stack_init();
    gap_params_init();
    gatt_init();
    services_init();
    advertising_init();
    conn_params_init();
    tuya_ble_app_init();
    advertising_start();

    NRF_LOG_INFO("App version: %s\r\n",TY_APP_VER_STR);

    // Enter main loop.
    for (;;)
    {
        idle_state_handle();
    }
}
```

**tuya\_ble\_sdk\_init\_async**

| **Function name** | tuya\_ble\_sdk\_init\_async                                                                                                                                     |
| ----------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Prototype**     | void tuya\_ble\_sdk\_init\_async(tuya\_ble\_device\_param\_t \* param\_data,tuya\_ble\_nv\_async\_callback\_t callback)                                         |
| **Description**   | The tuya ble sdk initialization function, mainly used in tuya ble sdk of asynchronous flash operation architecture.                                             |
| **Parameters**    | <p>param\_data \[in]: Initialize parameter.<br>callback\[in]: Callback， This callback will be executed automatically after the initialization is completed.</p> |
| **Responses**     | None.                                                                                                                                                           |
| **Notice**        | The tuya ble sdk Asynchronous initialization function, the Application must call this function to initialize the SDK, otherwise the SDK will not work.          |

> Example of tuya ble sdk asynchronous initialization:

```
static const char auth_key_test[] = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
static const char device_id_test[] = "yyyyyyyyyyyyyyyy";

#define APP_PRODUCT_ID  "vvvvvvvv"

static void tuya_ble_sdk_init_async_completed(void *p_param,tuya_ble_status_t result)
{
    if(result==TUYA_BLE_SUCCESS)
    {
        tuya_ble_callback_queue_register(tuya_cb_handler);

        tuya_ota_init();

        TUYA_APP_LOG_INFO("tuya sdk init succeed.");
        TUYA_APP_LOG_INFO("App version: "TY_APP_VER_STR);
        TUYA_APP_LOG_DEBUG("current free heap size = %d",xTuyaPortGetFreeHeapSize());
        //tuya_ble_device_factory_reset();
    }
    else
    {
        TUYA_APP_LOG_INFO("tuya sdk init failed.");
    }
}

void tuya_ble_app_init(void)
{
    tuya_ble_nv_init_custom();
    memset(&device_param,0,sizeof(tuya_ble_device_param_t));
    device_param.device_id_len = 16;
    memcpy(device_param.auth_key,(void *)auth_key_test,AUTH_KEY_LEN);
    memcpy(device_param.device_id,(void *)device_id_test,DEVICE_ID_LEN);

    device_param.p_type = TUYA_BLE_PRODUCT_ID_TYPE_PID;
    device_param.product_id_len = 8;
    memcpy(device_param.product_id,APP_PRODUCT_ID,8);
    device_param.firmware_version = TY_APP_VER_NUM;
    device_param.hardware_version = TY_HARD_VER_NUM;

    tuya_ble_sdk_init_async(&device_param,tuya_ble_sdk_init_async_completed);


}

/*nrf52832 example*/
int main(void)
{
    bool erase_bonds;

    // Initialize.
    uart_init();
    app_log_init();
    timers_init();
    buttons_leds_init(&erase_bonds);
    power_management_init();
    ble_stack_init();
    gap_params_init();
    gatt_init();
    services_init();
    advertising_init();
    conn_params_init();
    tuya_ble_app_init();
    advertising_start();

    NRF_LOG_INFO("App version: %s\r\n",TY_APP_VER_STR);

    // Enter main loop.
    for (;;)
    {
        idle_state_handle();
    }
}
```

**tuya\_ble\_dp\_data\_report**

| **Function name** | tuya\_ble\_dp\_data\_report                                                                                                                                                                                                                                                                                                                                                     |
| ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Prototype**     | tuya\_ble\_status\_t tuya\_ble\_dp\_data\_report(uint8\_t \*p\_data,uint32\_t len)                                                                                                                                                                                                                                                                                              |
| **Description**   | Reports dp point data to APP.                                                                                                                                                                                                                                                                                                                                                   |
| **Parameters**    | <p>p\_data \[in]: dp point data.<br>len\[in]: Data length，Cannot exceed <code>TUYA\_BLE\_REPORT\_MAX\_DP\_DATA\_LEN</code>.</p>                                                                                                                                                                                                                                                 |
| **Responses**     | <p>TUYA\_BLE\_SUCCESS: Sent successfully.<br>TUYA\_BLE\_ERR\_INVALID\_PARAM: parameter invalid.<br>TUYA\_BLE\_ERR\_INVALID\_STATE: The current status does not support sending, such as Bluetooth disconnection.<br>TUYA\_BLE\_ERR\_NO\_MEM: Memory Application failed.<br>TUYA\_BLE\_ERR\_INVALID\_LENGTH: Data length error .<br>TUYA\_BLE\_ERR\_NO\_EVENT: Other errors.</p> |
| **Notice**        | Application reports DP data to mobile App by calling this function.                                                                                                                                                                                                                                                                                                             |

> parameter description:

* Tuya IoT platform manages data in the form of dp points. The data generated by any device needs to be abstracted in the form of dp points. A complete dp point data consists of four parts (refer to the relevant introduction on the IoT platform for details):

  Dp\_id: 1 byte, dp\_id serial number registered in the development platform.

  Dp\_type: 1 byte, dp point type.

\#define DT\_RAW 0 //raw type

\#define DT\_BOOL 1 //Boolean type

\#define DT\_VALUE 2 //Value type

\#define DT\_STRING 3 //String type

\#define DT\_ENUM 4 //Enumeration type

\#define DT\_BITMAP 5 // Bitmap type

Dp\_len: Bluetooth currently supports only one byte, that is, the longest data of a single dp point is 255 bytes.

Dp\_data: Data, dp\_len bytes.

* The dp point reporting function, the data pointed to by parameter p\_data must be assembled and reported in the form of a table:

| Dp point 1 data | \~       |         |          |    | Dp point n data |          |         |          |
| --------------- | -------- | ------- | -------- | -- | --------------- | -------- | ------- | -------- |
| 1               | 2        | 3       | 4\~      | \~ | n               | n+1      | n+2     | n+3\~    |
| Dp\_id          | Dp\_type | Dp\_len | Dp\_data | \~ | Dp\_id          | Dp\_type | Dp\_len | Dp\_data |

* When calling this function, the maximum length of parameter len is `TUYA_BLE_REPORT_MAX_DP_DATA_LEN` (currently 255+3).

**tuya\_ble\_dp\_data\_with\_time\_report**

| **Function name** | tuya\_ble\_dp\_data\_with\_time\_report                                                                                                                                                                                                                                                                                                                                      |
| ----------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Prototype**     | tuya\_ble\_status\_t tuya\_ble\_dp\_data\_with\_time\_report(uint32\_t timestamp,uint8\_t \*p\_data,uint32\_t len)                                                                                                                                                                                                                                                           |
| **Description**   | Reports dp point data with time stamp.                                                                                                                                                                                                                                                                                                                                       |
| **Parameters**    | <p>timestamp\[in]: 4 byte Unix timestamp.<br>p\_data \[in] :dp data.<br>len\[in]: The data length cannot exceed <code>TUYA\_BLE\_REPORT\_MAX\_DP\_DATA\_LEN</code>.</p>                                                                                                                                                                                                      |
| **Responses**     | <p>TUYA\_BLE\_SUCCESS: Sent successfully.<br>TUYA\_BLE\_ERR\_INVALID\_PARAM: parameter error.<br>TUYA\_BLE\_ERR\_INVALID\_STATE: The current status does not support sending, such as Bluetooth disconnection;<br>TUYA\_BLE\_ERR\_NO\_MEM: Memory Application failed.<br>TUYA\_BLE\_ERR\_INVALID\_LENGTH: Data length error.<br>TUYA\_BLE\_ERR\_NO\_EVENT: Other errors.</p> |
| **Notice**        | <p>The Application code reports dp point data to the App with time stamp by calling this function.<br>Generally, data that is cached offline needs to be reported with time stamp.</p>                                                                                                                                                                                       |

**tuya\_ble\_dp\_data\_with\_time\_ms\_string\_report**

| **Function name** | tuya\_ble\_dp\_data\_with\_time\_ms\_string\_report                                                                                                                                                                                                                                                                                                                          |
| ----------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Prototype**     | tuya\_ble\_status\_t tuya\_ble\_dp\_data\_with\_time\_ms\_string\_report(uint8\_t \*time\_string,uint8\_t \*p\_data,uint32\_t len)                                                                                                                                                                                                                                           |
| **Description**   | Reports dp point data with string format time.                                                                                                                                                                                                                                                                                                                               |
| **Parameters**    | <p>time\_string\[in]: 13 byte ms level string format time.<br>p\_data \[in]: dp point data.<br>Len\[in]: Data length, the maximum cannot exceed <code>TUYA\_BLE\_REPORT\_MAX\_DP\_DATA\_LEN</code>.</p>                                                                                                                                                                      |
| **Responses**     | <p>TUYA\_BLE\_SUCCESS: Sent successfully.<br>TUYA\_BLE\_ERR\_INVALID\_PARAM: parameter error.<br>TUYA\_BLE\_ERR\_INVALID\_STATE: The current status does not support sending, such as Bluetooth disconnection.<br>TUYA\_BLE\_ERR\_NO\_MEM: Memory Application failed.<br>TUYA\_BLE\_ERR\_INVALID\_LENGTH: Data length error.<br>TUYA\_BLE\_ERR\_NO\_EVENT: Other errors.</p> |
| **Notice**        | <p>The Application code reports dp point data to the App with string format time by calling this function.<br>generally offline data only needs to be reported with time.<br>13 byte ms level time string, such as "0000000123456" ", less than 13 bytes before the supplementary character 0.</p>                                                                           |

**tuya\_ble\_dp\_data\_with\_flag\_report**

| **Function name** | tuya\_ble\_dp\_data\_with\_flag\_report                                                                                                                                                                                                                                                                                                                                      |
| ----------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Prototype**     | tuya\_ble\_status\_t tuya\_ble\_dp\_data\_with\_flag\_report(uint16\_t sn,tuya\_ble\_report\_mode\_t mode,uint8\_t \*p\_data,uint32\_t len)                                                                                                                                                                                                                                  |
| **Description**   | Reports dp point data with flag.                                                                                                                                                                                                                                                                                                                                             |
| **Parameters**    | <p>sn\[in]: Application defined serial number.<br>mode\[in]: Reporting mode.<br>p\_data \[in]: dp point data.<br>len\[in]: dp point data length, the maximum cannot exceed <code>TUYA\_BLE\_REPORT\_MAX\_DP\_DATA\_LEN</code>.</p>                                                                                                                                           |
| **Responses**     | <p>TUYA\_BLE\_SUCCESS: Sent successfully.<br>TUYA\_BLE\_ERR\_INVALID\_PARAM: parameter error.<br>TUYA\_BLE\_ERR\_INVALID\_STATE: The current status does not support sending, such as Bluetooth disconnection;<br>TUYA\_BLE\_ERR\_NO\_MEM: Memory Application failed.<br>TUYA\_BLE\_ERR\_INVALID\_LENGTH: Data length error.<br>TUYA\_BLE\_ERR\_NO\_EVENT: Other errors.</p> |
| **Notice**        | Application calls this function to report the marked DP point data to the App.                                                                                                                                                                                                                                                                                               |

> parameter description:
>
> mode:
>
> `REPORT_FOR_CLOUD_PANEL`: report to the panel and the cloud at the same time.
>
> `REPORT_FOR_CLOUD`: only report to the cloud.
>
> `REPORT_FOR_PANEL`: only report to the panel.
>
> `REPORT_FOR_NONE`: neither reported to the panel nor to the cloud.

**tuya\_ble\_dp\_data\_with\_flag\_and\_time\_report**

| **Function name** | tuya\_ble\_dp\_data\_with\_flag\_and\_time\_report                                                                                                                                                                                                                                                                                                                           |
| ----------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Prototype**     | <p>tuya\_ble\_status\_t tuya\_ble\_dp\_data\_with\_flag\_and\_time\_report<br>(uint16\_t sn,tuya\_ble\_report\_mode\_t mode,uint32\_t timestamp,uint8\_t \*p\_data,uint32\_t len)</p>                                                                                                                                                                                        |
| **Description**   | Reports dp point data with time stamp.                                                                                                                                                                                                                                                                                                                                       |
| **Parameters**    | <p>sn\[in]: Application defined serial number.<br>mode\[in]: reporting mode.<br>timestamp\[in]: 4 byte Unix timestamp.<br>p\_data \[in]: dp data.<br>len\[in]: dp point data length, the maximum cannot exceed <code>TUYA\_BLE\_REPORT\_MAX\_DP\_DATA\_LEN</code>.</p>                                                                                                       |
| **Responses**     | <p>TUYA\_BLE\_SUCCESS: Sent successfully.<br>TUYA\_BLE\_ERR\_INVALID\_PARAM: parameter error.<br>TUYA\_BLE\_ERR\_INVALID\_STATE: The current status does not support sending, such as Bluetooth disconnection.<br>TUYA\_BLE\_ERR\_NO\_MEM: Memory Application failed.<br>TUYA\_BLE\_ERR\_INVALID\_LENGTH: Data length error.<br>TUYA\_BLE\_ERR\_NO\_EVENT: Other errors.</p> |
| **Notice**        | <p>The Application code reports dp point data to the App with timestamp by calling this function.<br>Generally, data that is cached offline needs to be reported with a time stamp.</p>                                                                                                                                                                                      |

**tuya\_ble\_dp\_data\_with\_flag\_and\_time\_ms\_string\_report**

| **Function name** | tuya\_ble\_dp\_data\_with\_flag\_and\_time\_ms\_string\_report                                                                                                                                                                                                                                                                                                               |
| ----------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Prototype**     | <p>tuya\_ble\_status\_t tuya\_ble\_dp\_data\_with\_flag\_and\_time\_ms\_string\_report<br>(uint16\_t sn,tuya\_ble\_report\_mode\_t mode,uint8\_t \*time\_string,uint8\_t \*p\_data,uint32\_t len)</p>                                                                                                                                                                        |
| **Description**   | Reports dp point data with string formatted time with flag.                                                                                                                                                                                                                                                                                                                  |
| **Parameters**    | <p>sn\[in]: Application defined serial number.<br>mode\[in]: reporting mode.<br>time\_string\[in]: 13-byte ms-level string format time;<br>p\_data \[in]: dp point data.<br>Len\[in]: data length, the maximum cannot exceed <code>TUYA\_BLE\_REPORT\_MAX\_DP\_DATA\_LEN</code>.</p>                                                                                         |
| **Responses**     | <p>TUYA\_BLE\_SUCCESS: Sent successfully.<br>TUYA\_BLE\_ERR\_INVALID\_PARAM: parameter error.<br>TUYA\_BLE\_ERR\_INVALID\_STATE: The current status does not support sending, such as Bluetooth disconnection.<br>TUYA\_BLE\_ERR\_NO\_MEM: Memory Application failed.<br>TUYA\_BLE\_ERR\_INVALID\_LENGTH: Data length error.<br>TUYA\_BLE\_ERR\_NO\_EVENT: Other errors.</p> |
| **Notice**        | <p>The Application code reports dp point data to the App with string format time by calling this function.<br>generally offline data only needs to be reported with time.<br>13 byte ms level time string, such as "0000000123456" ", less than 13 bytes before the supplementary character 0.</p>                                                                           |

**tuya\_ble\_connected\_handler**

| **Function name** | tuya\_ble\_connected\_handler                                                                                                                                                                                       |
| ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Prototype**     | void tuya\_ble\_connected\_handler(void)                                                                                                                                                                            |
| **Description**   | Bluetooth connection callback function.                                                                                                                                                                             |
| **Parameters**    | None.                                                                                                                                                                                                               |
| **Responses**     | None.                                                                                                                                                                                                               |
| **Notice**        | <p>The Application code needs to call this function at the Bluetooth connection callback of the chip platform SDK.<br>tuya ble sdk is based on this function to manage the internal Bluetooth connection state.</p> |

**tuya\_ble\_disconnected\_handler**

| **Function name** | tuya\_ble\_disconnected\_handler                                                                                                                                                                                                           |
| ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| **Prototype**     | void tuya\_ble\_disconnected\_handler(void)                                                                                                                                                                                                |
| **Description**   | Bluetooth disconnection callback function.                                                                                                                                                                                                 |
| **Parameters**    | None.                                                                                                                                                                                                                                      |
| **Responses**     | None.                                                                                                                                                                                                                                      |
| **Notice**        | <p>The Application code needs to call this function at the Bluetooth disconnection callback of the chip platform SDK.<br>The tuya ble sdk manages the internal Bluetooth connection state according to the execution of this function.</p> |

> Example of calling tuya\_ble\_connected\_handler and tuya\_ble\_disconnected\_handler on nrf52832 platform:

```
/**@brief Function for handling BLE events.
 *
 * @param[in]   p_ble_evt   Bluetooth stack event.
 * @param[in]   p_context   Unused.
 */
static void ble_evt_handler(ble_evt_t const * p_ble_evt, void * p_context)
{
    uint32_t err_code;

    switch (p_ble_evt->header.evt_id)
    {
    case BLE_GAP_EVT_CONNECTED:

        NRF_LOG_INFO("Connected");

        tuya_ble_connected_handler();

        err_code = bsp_indication_set(BSP_INDICATE_CONNECTED);
        APP_ERROR_CHECK(err_code);
        m_conn_handle = p_ble_evt->evt.gap_evt.conn_handle;
        err_code = nrf_ble_qwr_conn_handle_assign(&m_qwr, m_conn_handle);
        APP_ERROR_CHECK(err_code);

        break;

    case BLE_GAP_EVT_DISCONNECTED:

        NRF_LOG_INFO("Disconnected");

        tuya_ble_disconnected_handler();

        tuya_ota_init_disconnect();
        // LED indication will be changed when advertising starts.
        m_conn_handle = BLE_CONN_HANDLE_INVALID;
        break;

    case BLE_GAP_EVT_PHY_UPDATE_REQUEST:
    {
        NRF_LOG_DEBUG("PHY update request.");
        ble_gap_phys_t const phys =
        {
            .rx_phys = BLE_GAP_PHY_AUTO,
            .tx_phys = BLE_GAP_PHY_AUTO,
        };
        err_code = sd_ble_gap_phy_update(p_ble_evt->evt.gap_evt.conn_handle, &phys);
        APP_ERROR_CHECK(err_code);
    }
    break;

    case BLE_GAP_EVT_SEC_PARAMS_REQUEST:
        // Pairing not supported
        err_code = sd_ble_gap_sec_params_reply(m_conn_handle, BLE_GAP_SEC_STATUS_PAIRING_NOT_SUPP, NULL, NULL);
        APP_ERROR_CHECK(err_code);
        break;

    case BLE_GATTS_EVT_SYS_ATTR_MISSING:
        // No system attributes have been stored.
        err_code = sd_ble_gatts_sys_attr_set(m_conn_handle, NULL, 0, 0);
        APP_ERROR_CHECK(err_code);
        break;

    case BLE_GATTC_EVT_TIMEOUT:
        // Disconnect on GATT Client timeout event.
        err_code = sd_ble_gap_disconnect(p_ble_evt->evt.gattc_evt.conn_handle,
                                         BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
        APP_ERROR_CHECK(err_code);
        break;

    case BLE_GATTS_EVT_TIMEOUT:
        // Disconnect on GATT Server timeout event.
        err_code = sd_ble_gap_disconnect(p_ble_evt->evt.gatts_evt.conn_handle,
                                         BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
        APP_ERROR_CHECK(err_code);
        break;

    default:
        // No implementation needed.
        break;
    }
}
```

**tuya\_ble\_adv\_data\_connecting\_request\_set**

| **Function name** | tuya\_ble\_adv\_data\_connecting\_request\_set                                                                                                                                                                                                     |
| ----------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Prototype**     | tuya\_ble\_status\_t tuya\_ble\_adv\_data\_connecting\_request\_set(uint8\_t on\_off)                                                                                                                                                              |
| **Description**   | Triggers broadcast packet change request connection flag.                                                                                                                                                                                          |
| **Parameters**    | on\_off\[in]: 0 - Clear flag，1 - set flag.                                                                                                                                                                                                         |
| **Responses**     | <p>TUYA\_BLE\_SUCCESS: success.<br>TUYA\_BLE\_ERR\_INVALID\_STATE: The current state is not supported, for example, it is currently connected.<br>TUYA\_BLE\_ERR\_INVALID\_PARAM: parameter error.<br>TUYA\_BLE\_ERR\_NO\_EVENT: Other errors.</p> |

**tuya\_ble\_data\_passthrough**

| **Function name** | tuya\_ble\_data\_passthrough                                                                                                                                                                                                                                      |
| ----------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Prototype**     | tuya\_ble\_status\_t tuya\_ble\_data\_passthrough(uint8\_t \*p\_data,uint32\_t len)                                                                                                                                                                               |
| **Description**   | Passes through the custom data of the Application.                                                                                                                                                                                                                |
| **Parameters**    | <p>p\_data \[in]: data pointer that needs to be transparently transmitted.<br>len\[in]: data length, the maximum cannot exceed <code>TUYA\_BLE\_TRANSMISSION\_MAX\_DATA\_LEN</code>.</p>                                                                          |
| **Responses**     | <p>TUYA\_BLE\_SUCCESS: Sent successfully.<br>TUYA\_BLE\_ERR\_INVALID\_STATE: The current status does not support sending, such as Bluetooth disconnection.<br>TUYA\_BLE\_ERR\_INVALID\_LENGTH: Data length error.<br>TUYA\_BLE\_ERR\_NO\_EVENT: Other errors.</p> |
| **Notice**        | <p>Application transparently transmits data to App by calling this function.<br>The transparently transmitted data format is negotiated by the device Application and the mobile App, and tuya ble sdk does not parse it.</p>                                     |

**tuya\_ble\_production\_test\_asynchronous\_response**

| **Function name** | tuya\_ble\_production\_test\_asynchronous\_response                                                                                                                                                                                                                                                                                                                                                                              |
| ----------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Prototype**     | <p>tuya\_ble\_status\_t tuya\_ble\_production\_test\_asynchronous\_response<br>(uint8\_t channel,uint8\_t \*p\_data,uint32\_t len)</p>                                                                                                                                                                                                                                                                                           |
| **Description**   | Asynchronously respond to the production testing command.                                                                                                                                                                                                                                                                                                                                                                        |
| **Parameters**    | <p>Channel\[in]: Transmission channel，0-uart;1-ble.<br>p\_data \[in]: complete command data that needs to be responded to.<br>len\[in]: Data length.</p>                                                                                                                                                                                                                                                                         |
| **Responses**     | <p>TUYA\_BLE\_SUCCESS: Sent successfully.<br>TUYA\_BLE\_ERR\_INVALID\_STATE: The current status does not support sending, such as Bluetooth disconnection.<br>TUYA\_BLE\_ERR\_INVALID\_LENGTH: Data length error.<br>TUYA\_BLE\_ERR\_NO\_MEM: Failed to apply for memory.<br>TUYA\_BLE\_ERR\_NO\_EVENT: Other errors.</p>                                                                                                        |
| **Notice**        | <p>When performing production testing (production testing authorization is through UART, the whole machine test passes BLE)<br>Some test items can not immediately respond to the results of the upper computer production testing tool,<br>or some test items need to be processed by the Application. At this time, you need to call this function to send the test results to the upper computer production testing tool.</p> |

**tuya\_ble\_net\_config\_response**

| **Function name** | tuya\_ble\_net\_config\_response                                                                                                                                                                           |
| ----------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Prototype**     | tuya\_ble\_status\_t tuya\_ble\_net\_config\_response(int16\_t result\_code)                                                                                                                               |
| **Description**   | Responds the Wi-Fi network configuration request.                                                                                                                                                          |
| **Parameters**    | Result\_code\[in]: status code.                                                                                                                                                                            |
| **Responses**     | <p>TUYA\_BLE\_SUCCESS: Sent successfully.<br>TUYA\_BLE\_ERR\_INVALID\_STATE: The current status does not support sending, such as Bluetooth disconnection.<br>TUYA\_BLE\_ERR\_NO\_EVENT: Other errors.</p> |
| **Notice**        | Suitable for Wi-Fi / BLE combo devices.                                                                                                                                                                    |

**tuya\_ble\_ubound\_response**

| **Function name** | tuya\_ble\_ubound\_response                                                                                                                                                                            |
| ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| **Prototype**     | tuya\_ble\_status\_t tuya\_ble\_ubound\_response(uint8\_t result\_code)                                                                                                                                |
| **Description**   | Responds to the removal requests of multi-protocol combo device.                                                                                                                                       |
| **Parameters**    | Result\_code\[in]: status code, 0 - success，1 - fail.                                                                                                                                                  |
| **Responses**     | <p>TUYA\_BLE\_SUCCESS: Sent successfully.<br>TUYA\_BLE\_ERR\_INVALID\_STATE: The current status does not support sending, such as Bluetooth disconnection.TUYA\_BLE\_ERR\_NO\_EVENT: Other errors.</p> |
| **Notice**        | Suitable for Wi-Fi / BLE combo devices.                                                                                                                                                                |

**tuya\_ble\_anomaly\_ubound\_response**

| **Function name** | tuya\_ble\_anomaly\_ubound\_response                                                                                                                                                                       |
| ----------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Prototype**     | tuya\_ble\_status\_t tuya\_ble\_anomaly\_ubound\_response (uint8\_t result\_code)                                                                                                                          |
| **Description**   | Responds to the abnormal removal requests of multi-protocol combo device.                                                                                                                                  |
| **Parameters**    | Result\_code\[in]: status code，0 - success，1 - fail.                                                                                                                                                       |
| **Responses**     | <p>TUYA\_BLE\_SUCCESS: Sent successfully.<br>TUYA\_BLE\_ERR\_INVALID\_STATE: The current status does not support sending, such as Bluetooth disconnection.<br>TUYA\_BLE\_ERR\_NO\_EVENT: Other errors.</p> |
| **Notice**        | Suitable for Wi-Fi / BLE combo devices.                                                                                                                                                                    |

**tuya\_ble\_device\_reset\_response**

| **Function name** | tuya\_ble\_device\_reset\_response                                                                                                                                                                     |
| ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| **Prototype**     | tuya\_ble\_status\_t tuya\_ble\_device\_reset\_response (uint8\_t result\_code)                                                                                                                        |
| **Description**   | Responds to the reset requests of multi-protocol combo device.                                                                                                                                         |
| **Parameters**    | Result\_code\[in]: status code，0 - success，1 - fail.                                                                                                                                                   |
| **Responses**     | <p>TUYA\_BLE\_SUCCESS: Sent successfully.<br>TUYA\_BLE\_ERR\_INVALID\_STATE: The current status does not support sending, such as Bluetooth disconnection.TUYA\_BLE\_ERR\_NO\_EVENT: Other errors.</p> |
| **Notice**        | Suitable for Wi-Fi / BLE combo devices.                                                                                                                                                                |

**tuya\_ble\_connect\_status\_get**

| **Function name** | tuya\_ble\_connect\_status\_get                                              |
| ----------------- | ---------------------------------------------------------------------------- |
| **Prototype**     | tuya\_ble\_connect\_status\_t tuya\_ble\_connect\_status\_get(void)          |
| **Description**   | Gets current BLE connection status                                           |
| **Parameters**    | None.                                                                        |
| **Responses**     | `tuya_ble_connect_status_t`. See the following response example for details. |

> Responses description:
>
> ```
> typedef enum{
>     UNBONDING_UNCONN = 0,
>     UNBONDING_CONN,
>     BONDING_UNCONN,
>     BONDING_CONN,
>     BONDING_UNAUTH_CONN,
>     UNBONDING_UNAUTH_CONN,
>     UNKNOW_STATUS
> }tuya_ble_connect_status_t;
> ```

**tuya\_ble\_device\_factory\_reset**

| **Function name** | tuya\_ble\_device\_factory\_reset                                                                                                                                                                                             |
| ----------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Prototype**     | tuya\_ble\_status\_t tuya\_ble\_device\_factory\_reset(void)                                                                                                                                                                  |
| **Description**   | Resets BLE devices.                                                                                                                                                                                                           |
| **Parameters**    | None.                                                                                                                                                                                                                         |
| **Responses**     | <p>TUYA\_BLE\_SUCCESS: Sent successfully.<br>TUYA\_BLE\_ERR\_INTERNAL: Other errors.</p>                                                                                                                                      |
| **Notice**        | For devices that define an external key reset function, the Application needs to call this function to notify tuya ble sdk to reset related information after the key triggers a reset, such as clearing binding information. |

**tuya\_ble\_time\_req**

| **Function name** | tuya\_ble\_time\_req                                                                                                                                                                                                                                                                                                                                                                |
| ----------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Prototype**     | tuya\_ble\_status\_t tuya\_ble\_time\_req(uint8\_t time\_type)                                                                                                                                                                                                                                                                                                                      |
| **Description**   | Requests cloud time.                                                                                                                                                                                                                                                                                                                                                                |
| **Parameters**    | <p>time\_type\[in]:<br>0 - Request time in 13-byte ms-level string format.<br>1 - Find the year, month, day, hour, minute, second, week format time.</p>                                                                                                                                                                                                                            |
| **Responses**     | <p>TUYA\_BLE\_SUCCESS: Sent successfully.<br>TUYA\_BLE\_ERR\_INVALID\_PARAM: parameter error.<br>TUYA\_BLE\_ERR\_INTERNAL: Other errors.</p>                                                                                                                                                                                                                                        |
| **Notice**        | <p>13 byte string time format: "0000000123456" means 123456 ms timestamp.<br>normal time format: 0x13,0x04,0x1C,0x0C,0x17,0x19,0x02 means:<br>April 28, 2019 :23:25 Tuesday.<br>tuya ble sdk will send the corresponding instruction to the App after receiving the request,<br>sdk will send a message to the device Application after receiving the time returned by the App.</p> |

**tuya\_ble\_ota\_response**

| **Function name** | tuya\_ble\_ota\_response                                                                                                                                                                                                                             |
| ----------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Prototype**     | tuya\_ble\_status\_t tuya\_ble\_ota\_response(tuya\_ble\_ota\_response\_t \*p\_data)                                                                                                                                                                 |
| **Description**   | OTA response command.                                                                                                                                                                                                                                |
| **Parameters**    | p\_data\[in]: OTA response data.                                                                                                                                                                                                                     |
| **Responses**     | <p>TUYA\_BLE\_SUCCESS: Sent successfully.<br>TUYA\_BLE\_ERR\_INVALID\_STATE: State error.<br>TUYA\_BLE\_ERR\_INVALID\_LENGTH: Data length error.<br>TUYA\_BLE\_ERR\_NO\_MEM: Memory Application fail.<br>TUYA\_BLE\_ERR\_INTERNAL: Other errors.</p> |
| **Notice**        | See the OTA introduction chapter for the specific format.                                                                                                                                                                                            |

**tuya\_ble\_custom\_event\_send**

| **Function name** | tuya\_ble\_custom\_event\_send                                                                                       |
| ----------------- | -------------------------------------------------------------------------------------------------------------------- |
| **Prototype**     | uint8\_t tuya\_ble\_custom\_event\_send(tuya\_ble\_custom\_evt\_t evt)                                               |
| **Description**   | Sends Application custom message and callback to tuya ble sdk.                                                       |
| **Parameters**    | evt\[in]: Custom event.                                                                                              |
| **Responses**     | <p>0: Sent successfully.<br>1: fail.</p>                                                                             |
| **Notice**        | <p>typedef struct{<br>void \*data;<br>void (*custom\_event\_handler)(void*data);<br>} tuya\_ble\_custom\_evt\_t;</p> |

> Description: This function is mainly used when the Application wants to use the internal message scheduler of tuya ble sdk to process the Application's message events. `tuya_ble_custom_event_send` Application examples:

```
#define APP_CUSTOM_EVENT_1  1
#define APP_CUSTOM_EVENT_2  2
#define APP_CUSTOM_EVENT_3  3
#define APP_CUSTOM_EVENT_4  4
#define APP_CUSTOM_EVENT_5  5

typedef struct {
    uint8_t data[50];
} custom_data_type_t;

void custom_data_process(int32_t evt_id,void *data)
{
    custom_data_type_t *event_1_data;
    TUYA_BLE_LOG_DEBUG("custom event id = %d",evt_id);
    switch (evt_id)
    {
        case APP_CUSTOM_EVENT_1:
            event_1_data = (custom_data_type_t *)data;
            TUYA_BLE_LOG_HEXDUMP_DEBUG("received APP_CUSTOM_EVENT_1 data:",event_1_data->data,50);
            break;
        case APP_CUSTOM_EVENT_2:
            break;
        case APP_CUSTOM_EVENT_3:
            break;
        case APP_CUSTOM_EVENT_4:
            break;
        case APP_CUSTOM_EVENT_5:
            break;
        default:
            break;

    }
}

custom_data_type_t custom_data;

void custom_evt_1_send_test(uint8_t data)
{
    tuya_ble_custom_evt_t event;

    for(uint8_t i=0; i<50; i++)
    {
        custom_data.data[i] = data;
    }
    event.evt_id = APP_CUSTOM_EVENT_1;
    event.custom_event_handler = (void *)custom_data_process;
    event.data = &custom_data;
    tuya_ble_custom_event_send(event);
}
```

**tuya\_ble\_callback\_queue\_register**

| **Function name** | tuya\_ble\_callback\_queue\_register                                                                                                                                                                                                                     |
| ----------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Prototype**     | <p>prototype 1: tuya\_ble\_status\_t tuya\_ble\_callback\_queue\_register(void \*cb\_queue).<br>prototype 2: tuya\_ble\_status\_t tuya\_ble\_callback\_queue\_register(tuya\_ble\_callback\_t cb).</p>                                                   |
| **Description**   | <p>To register the message queue for receiving tuya ble sdk messages under the OS platform architecture, use prototype 1.<br>To register callback function for receiving tuya ble sdk messages under OS-less platform architecture, use prototype 2.</p> |
| **Parameters**    | <p>cb\_queue \[in]: message queue.<br>cb\[in]: callback Function address.</p>                                                                                                                                                                            |
| **Responses**     | <p>TUYA\_BLE\_ERR\_RESOURCES: Register fail.<br>TUYA\_BLE\_SUCCESS: Register success.</p>                                                                                                                                                                |

> Application examples for OS platform:

```
void *tuya_custom_queue_handle;

os_msg_queue_create(&tuya_custom_queue_handle, MAX_NUMBER_OF_TUYA_CUSTOM_MESSAGE, sizeof(tuya_ble_cb_evt_param_t));

tuya_ble_callback_queue_register(tuya_custom_queue_handle);
```

> Application example without OS platform:

```
void tuya_cb_handler(tuya_ble_cb_evt_param_t* event).

tuya_ble_callback_queue_register(tuya_cb_handler);
```

**tuya\_ble\_event\_response**

| **Function name** | tuya\_ble\_event\_response                                                                                                                                                     |
| ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| **Prototype**     | tuya\_ble\_status\_t tuya\_ble\_event\_response(tuya\_ble\_cb\_evt\_param\_t \*param)                                                                                          |
| **Description**   | Responds to tuya ble sdk messages under the OS platform architecture.                                                                                                          |
| **Parameters**    | param \[in]: message pointer.                                                                                                                                                  |
| **Responses**     | <p>TUYA\_BLE\_SUCCESS: success.<br>other: fail.</p>                                                                                                                            |
| **Notice**        | <p>Under the OS platform architecture, after the Application code processes the message sent by tuya ble sdk，<br>Must call this function to give feedback to tuya ble sdk.</p> |

> Application examples:

```
 /*Application task to process ble sdk messages*/
void app_custom_task(void *p_param)
{
    tuya_ble_cb_evt_param_t event;

    while (true)
    {
        if (os_msg_recv(tuya_custom_queue_handle, &event, 0xFFFFFFFF) == true)
        {
            switch (event.evt)
            {
            case TUYA_BLE_CB_EVT_CONNECTE_STATUS:
                break;
            case TUYA_BLE_CB_EVT_DP_WRITE:
                break;
            case TUYA_BLE_CB_EVT_DP_DATA_REPORT_RESPONSE:
                break;
            case TUYA_BLE_CB_EVT_DP_DATA_WTTH_TIME_REPORT_RESPONSE:
                break;
            case TUYA_BLE_CB_EVT_UNBOUND:
                break;
            case TUYA_BLE_CB_EVT_ANOMALY_UNBOUND:
                break;
            case TUYA_BLE_CB_EVT_DEVICE_RESET:
                break;
            case TUYA_BLE_CB_EVT_DP_QUERY:
                break;
            case TUYA_BLE_CB_EVT_OTA_DATA:
                break;
            case TUYA_BLE_CB_EVT_NETWORK_INFO:
                break;
            case TUYA_BLE_CB_EVT_WIFI_SSID:
                break;
            case TUYA_BLE_CB_EVT_TIME_STAMP:
                break;
            case TUYA_BLE_CB_EVT_TIME_NORMAL:
                break;
            case TUYA_BLE_CB_EVT_DATA_PASSTHROUGH:
                break;
            default:
                break;
            }

            tuya_ble_event_response(&event);
        }
    }

}
```

**tuya\_ble\_scheduler\_queue\_size\_get**

| **Function name** | tuya\_ble\_scheduler\_queue\_size\_get                                            |
| ----------------- | --------------------------------------------------------------------------------- |
| **Prototype**     | uint16\_t tuya\_ble\_scheduler\_queue\_size\_get(void)                            |
| **Description**   | Gets the total size of tuya ble sdk scheduler queue in platforms that have no OS. |
| **Parameters**    | None.                                                                             |
| **Responses**     | Total size of the scheduler queue.                                                |

**tuya\_ble\_scheduler\_queue\_space\_get**

| **Function name** | tuya\_ble\_scheduler\_queue\_space\_get                                            |
| ----------------- | ---------------------------------------------------------------------------------- |
| **Prototype**     | uint16\_t tuya\_ble\_scheduler\_queue\_space\_get(void)                            |
| **Description**   | Gets the idle number of tuya ble sdk scheduler queue in platforms that have no OS. |
| **Parameters**    | None.                                                                              |
| **Responses**     | Scheduler queue idle.                                                              |

**tuya\_ble\_scheduler\_queue\_events\_get**

| **Function name** | tuya\_ble\_scheduler\_queue\_events\_get                                                                |
| ----------------- | ------------------------------------------------------------------------------------------------------- |
| **Prototype**     | uint16\_t tuya\_ble\_scheduler\_queue\_events\_get(void)                                                |
| **Description**   | Gets the number of unprocessed events in the tuya ble sdk scheduler queue in platforms that have no OS. |
| **Parameters**    | None.                                                                                                   |
| **Responses**     | The number of unprocessed events in the scheduler queue.                                                |

### The callback event of tuya ble sdk <a href="#title-13-the-20callback-20event-20of-20tuya-20ble-20sdk" id="title-13-the-20callback-20event-20of-20tuya-20ble-20sdk"></a>

The tuya ble sdk sends message of status, data, and other information to Application through message (for OS architecture platform) or callback function registered by Application (for non-OS architecture platform). According to the previous section, the example of `tuya_ble_event_response` describes how the Application in the OS architecture platform handle the messages sent by tuya ble sdk. The chip platform without an OS can use the similar code to process messages, however it is not necessary to call the `tuya_ble_event_response()` to respond to tuya ble sdk after the messages is handled by the callback function. As the following snippet shows an example for callback registration in the platform without an OS.

```
    /*Call back function for processing ble sdk messages*/
	static void tuya_cb_handler(tuya_ble_cb_evt_param_t* event)
	{
            switch (event->evt)
            {
            case TUYA_BLE_CB_EVT_CONNECTE_STATUS:
                break;
            case TUYA_BLE_CB_EVT_DP_WRITE:
                break;
            case TUYA_BLE_CB_EVT_DP_DATA_REPORT_RESPONSE:
                break;
            case TUYA_BLE_CB_EVT_DP_DATA_WTTH_TIME_REPORT_RESPONSE:
                break;
            case TUYA_BLE_CB_EVT_UNBOUND:
                break;
            case TUYA_BLE_CB_EVT_ANOMALY_UNBOUND:
                break;
            case TUYA_BLE_CB_EVT_DEVICE_RESET:
                break;
            case TUYA_BLE_CB_EVT_DP_QUERY:
                break;
            case TUYA_BLE_CB_EVT_OTA_DATA:
                break;
            case TUYA_BLE_CB_EVT_NETWORK_INFO:
                break;
            case TUYA_BLE_CB_EVT_WIFI_SSID:
                break;
            case TUYA_BLE_CB_EVT_TIME_STAMP:
                break;
            case TUYA_BLE_CB_EVT_TIME_NORMAL:
                break;
            case TUYA_BLE_CB_EVT_DATA_PASSTHROUGH:
                break;
            default:
                break;
            }

    }

    void tuya_ble_app_init(void)
	{
		device_param.device_id_len = 16;
		memcpy(device_param.auth_key,(void *)auth_key_test,AUTH_KEY_LEN);
		memcpy(device_param.device_id,(void *)device_id_test,DEVICE_ID_LEN);
		device_param.p_type = TUYA_BLE_PRODUCT_ID_TYPE_PID;
		device_param.product_id_len = 8;
		memcpy(device_param.product_id,APP_PRODUCT_ID,8);
		device_param.firmware_version = TY_APP_VER_NUM;
		device_param.hardware_version = TY_HARD_VER_NUM;

		tuya_ble_sdk_init(&device_param);
		tuya_ble_callback_queue_register(tuya_cb_handler);

		tuya_ota_init();
	}
```

**TUYA\_BLE\_CB\_EVT\_CONNECTE\_STATUS**

| **Event**       | TUYA\_BLE\_CB\_EVT\_CONNECTE\_STATUS                                                     |
| --------------- | ---------------------------------------------------------------------------------------- |
| **Description** | Every time the state changes, tuya ble sdk will send the event to the device Application |

> Corresponding data structure:
>
> ```
> typedef enum{
>     UNBONDING_UNCONN = 0,
>     UNBONDING_CONN,
>     BONDING_UNCONN,
>     BONDING_CONN,
>     BONDING_UNAUTH_CONN,
>     UNBONDING_UNAUTH_CONN,
>     UNKNOW_STATUS
> }tuya_ble_connect_status_t;
> ```

**TUYA\_BLE\_CB\_EVT\_DP\_WRITE**

| **Event**       | TUYA\_BLE\_CB\_EVT\_DP\_WRITE                               |
| --------------- | ----------------------------------------------------------- |
| **Description** | The tuya ble sdk received dp point data sent by mobile App. |
| **Notice**      | See format `tuya_ble_dp_data_report` API introduction.      |

> Corresponding data structure:
>
> ```
> /*
>  * dp data  buffer:  (Dp_id,Dp_type,Dp_len,Dp_data),(Dp_id,Dp_type,Dp_len,Dp_data),....
>  * */
> typedef struct{
> 	uint8_t *p_data;
> 	uint16_t data_len;
> }tuya_ble_dp_write_data_t;
> ```

**TUYA\_BLE\_CB\_EVT\_DP\_QUERY**

| **Event**       | TUYA\_BLE\_CB\_EVT\_DP\_QUERY                                                                                                                                                                                                                 |
| --------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Description** | The dp point to be checked, which is sent from the mobile App.                                                                                                                                                                                |
| **Notice**      | data\_len=0 means to query all dp points, otherwise each byte pointed to by p\_data represents a dp point to be queried, for example, data\_len=3, p\_data{0x01,0x02,0x03}, means to query dp\_id=1, dp\_id=2 , dp\_id=3 data of 3 dp points. |

> Corresponding data structure:
>
> ```
> /*
>  * query dp point data,if data_len is 0,means query all dp point data,otherwise query the dp point in p_data buffer.
>  * */
> typedef struct{
> 	uint8_t *p_data;
> 	uint16_t data_len;
> }tuya_ble_dp_query_data_t;
> ```

**TUYA\_BLE\_CB\_EVT\_OTA\_DATA**

| **Event**       | TUYA\_BLE\_CB\_EVT\_OTA\_DATA                              |
| --------------- | ---------------------------------------------------------- |
| **Description** | tuya ble sdk received the OTA data sent by the mobile App. |
| **Notice**      | See the OTA section for details.                           |

> Corresponding data structure:
>
> ```
> typedef struct{
> 	tuya_ble_ota_data_type_t type;
> 	uint16_t data_len;
> 	uint8_t *p_data;
> }tuya_ble_ota_data_t;
> ```

**TUYA\_BLE\_CB\_EVT\_NETWORK\_INFO**

| **Event**       | TUYA\_BLE\_CB\_EVT\_NETWORK\_INFO                                                                                                                                                      |
| --------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Description** | <p>The tuya ble sdk received Wi-Fi distribution information sent by the mobile app, for example:<br><code>{"wifi\_ssid":"tuya","password":"12345678","token":"xxxxxxxxxx".}</code></p> |
| **Notice**      | Only applicable to Wi-Fi / BLE dual protocol combo devices.                                                                                                                            |

> Corresponding data structure:
>
> ```
> /*
>  * network data,unformatted json data,for example " {"wifi_ssid":"tuya","password":"12345678","token":"xxxxxxxxxx"} "
>  * */
> typedef struct{
> 	uint16_t data_len;//include '\0'
> 	uint8_t *p_data;
> }tuya_ble_network_data_t;
> ```

**TUYA\_BLE\_CB\_EVT\_WIFI\_SSID**

| **Event**       | TUYA\_BLE\_CB\_EVT\_WIFI\_SSID                                                                                                                                                                               |
| --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| **Description** | <p>tuya ble sdk received Wi-Fi distribution information sent by the mobile app, for example:<br>"{"wifi\_ssid":"tuya","password":"12345678"}".</p>                                                           |
| **Notice**      | Only applicable to Wi-Fi / BLE dual protocol combo devices，Compared with `TUYA_BLE_CB_EVT_NETWORK_INFO`, it lacks the token field, and is mainly used for Wi-Fi SSID update of the network-equipped devices. |

> Corresponding data structure:
>
> ```
> /*
>  * wifi ssid data,unformatted json data,for example " {"wifi_ssid":"tuya","password":"12345678"} "
>  * */
> typedef struct{
> 	uint16_t data_len;//include '\0'
> 	uint8_t *p_data;
> }tuya_ble_wifi_ssid_data_t;
> ```

**TUYA\_BLE\_CB\_EVT\_TIME\_STAMP**

| **Event**       | TUYA\_BLE\_CB\_EVT\_TIME\_STAMP                                                                                                                                                       |
| --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Description** | The tuya ble sdk received the timestamp in the format of a string sent by the mobile phone app, for example, `0000000123456` means 123456ms, Unix timestamp at the millisecond level. |
| **Notice**      | time\_zone The time zone is 100 times the actual time zone, for example, -8 zone is -800.                                                                                             |

> Corresponding data structure:
>
> ```
> /*
>  * Unix timestamp
>  * */
> typedef struct{
> 	uint8_t timestamp_string[14];
> 	int16_t  time_zone;   //actual time zone Multiply by 100.
> }tuya_ble_timestamp_data_t;
> ```

**TUYA\_BLE\_CB\_EVT\_TIME\_NORMAL**

| **Event**       | TUYA\_BLE\_CB\_EVT\_TIME\_NORMAL                                                                                                                                                                                                                          |
| --------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Description** | <p>tuya ble sdk received the time in the conventional format sent by the mobile app, for example:<br>UTC +8, Tuesday, April 28, 2019 12:23:25.<br>corresponding data: 0x13, 0x04, 0x1C, 0x0C, 0x17, 0x19, 0x02 (week), 0x0320 (time zone time\_zone).</p> |

> Corresponding data structure:
>
> ```
> /*
>  * normal time formatted
>  * */
> typedef struct{
> 	uint16_t nYear;
>     uint8_t nMonth;
>     uint8_t nDay;
>     uint8_t nHour;
>     uint8_t nMin;
>     uint8_t nSec;
>     uint8_t DayIndex; /* 0 = Sunday */
> 	int16_t time_zone;   //actual time zone Multiply by 100.
> }tuya_ble_time_noraml_data_t;
> ```

**TUYA\_BLE\_CB\_EVT\_DATA\_PASSTHROUGH**

| **Event**       | TUYA\_BLE\_CB\_EVT\_DATA\_PASSTHROUGH                                                                                                                   |
| --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Description** | The tuya ble sdk received the transparent transmission data sent by the mobile app.                                                                     |
| **Notice**      | The tuya ble sdk does not parse transparently transmitted data, and the data format is negotiated and defined by the device Application and mobile App. |

> Corresponding data structure:
>
> ```
> typedef struct{
> 	uint16_t data_len;
> 	uint8_t *p_data;
> }tuya_ble_passthrough_data_t;
> ```

**TUYA\_BLE\_CB\_EVT\_DP\_DATA\_REPORT\_RESPONSE**

| **Event**       | TUYA\_BLE\_CB\_EVT\_DP\_DATA\_REPORT\_RESPONSE                                                                                                                                                                                                                                                                                                         |
| --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| **Description** | After the Device Application calls the `tuya_ble_dp_data_report()` function to send dp point data, if you need to confirm whether it is sent successfully, you need to wait for the Event. status=0 means success, and other failures. If the Device Application waits for the sending result, you need to add a timeout mechanism. Unlimited waiting. |

> Corresponding data structure:
>
> ```
> typedef struct{
> 	uint8_t status;
> }tuya_ble_dp_data_report_response_t;
> ```

**TUYA\_BLE\_CB\_EVT\_DP\_DATA\_WTTH\_TIME\_REPORT\_RESPONSE**

| **Event**       | TUYA\_BLE\_CB\_EVT\_DP\_DATA\_WTTH\_TIME\_REPORT\_RESPONSE                                                                                                                                                                                                                                                                                                                                                                            |
| --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Description** | Device Application calls `tuya_ble_dp_data_with_time_report()` and `tuya_ble_dp_data_with_time_ms_string_report()` function after sending the time-stamped dp point data, if you need to confirm whether it is sent successfully, you need to wait for the Event, status=0 means success, other failure, device Application You must add a timeout mechanism for waiting for the results to be sent, and you can't wait indefinitely. |

> Corresponding data structure:
>
> ```
> typedef struct{
> 	uint8_t status;
> }tuya_ble_dp_data_with_time_report_response_t;
> ```

**TUYA\_BLE\_CB\_EVT\_DP\_DATA\_WITH\_FLAG\_REPORT\_RESPONSE**

| **Event**       | TUYA\_BLE\_CB\_EVT\_DP\_DATA\_WITH\_FLAG\_REPORT\_RESPONSE                                                                                                                                                                                                                                                                                                                                                      |
| --------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Description** | <p>After the Application calls the <code>tuya\_ble\_dp\_data\_with\_flag\_report()</code> function to send dp point data, if you need to confirm whether it is sent successfully, wait for the Event.<br>The <code>sn</code> and the <code>mode</code> are the serial number and mode of dp point data sent by the Application.<br><code>status=0</code> indicates success, other values indicate failures.</p> |
| **Notice**      | Device Application can determine which response point of dp point data is sent according to the serial number.                                                                                                                                                                                                                                                                                                  |

> Corresponding data structure:
>
> ```
> typedef struct{
>     uint16_t sn;
>     tuya_ble_report_mode_t mode;
> 	uint8_t status;
> }tuya_ble_dp_data_with_flag_report_response_t;
> ```

**TUYA\_BLE\_CB\_EVT\_DP\_DATA\_WITH\_FLAG\_AND\_TIME\_REPORT\_RESPONSE**

| **Event**       | TUYA\_BLE\_CB\_EVT\_DP\_DATA\_WITH\_FLAG\_AND\_TIME\_REPORT\_RESPONSE                                                                                                                                                                                                                                                                                                                                                                                                               |
| --------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Description** | <p>Device Application calls <code>tuya\_ble\_dp\_data\_with\_flag\_and\_time\_report()</code> and <code>tuya\_ble\_dp\_data\_with\_flag\_and\_time\_ms\_string\_report()</code> function after sending dp point data with flag and timestamp, if you need to confirm whether Sent successfully, you need to wait for this Event;<br>sn and mode are device Application Sending dp point data is the incoming serial number and mode;<br>status=0 means success, other failures.</p> |
| **Notice**      | Device Application can determine which response point of dp point data is sent according to the serial number.                                                                                                                                                                                                                                                                                                                                                                      |

> Corresponding data structure:
>
> ```
> typedef struct{
>     uint16_t sn;
>     tuya_ble_report_mode_t mode;
> 	uint8_t status;
> }tuya_ble_dp_data_with_flag_and_time_report_response_t;
> ```

**TUYA\_BLE\_CB\_EVT\_UNBOUND**

| **Event**       | TUYA\_BLE\_CB\_EVT\_UNBOUND                                                                                                                                           |
| --------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Description** | Receiving the Event means that the mobile phone App sends an instruction to learn the binding. The data field is a reserved field and is not used for the time being. |

> Corresponding data structure:
>
> ```
> typedef struct{
> 	uint8_t data;
> }tuya_ble_unbound_data_t;
> ```

**TUYA\_BLE\_CB\_EVT\_ANOMALY\_UNBOUND**

| **Event**       | TUYA\_BLE\_CB\_EVT\_ANOMALY\_UNBOUND                                                                                                                                      |
| --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Description** | Receiving the Event indicates that the mobile App sent an abnormal unbinding instruction, in which the data field is a reserved field and is not used for the time being. |

> Corresponding data structure:
>
> ```
> typedef struct{
> 	uint8_t data;
> }tuya_ble_anomaly_unbound_data_t;
> ```

**TUYA\_BLE\_CB\_EVT\_DEVICE\_RESET**

| **Event**       | TUYA\_BLE\_CB\_EVT\_DEVICE\_RESET                                                                                                                        |
| --------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Description** | Receiving the Event indicates that the mobile App has sent a reset command, where the data field is a reserved field and is not used for the time being. |
| **Notice**      | After the device Application receives the reset event, it needs to perform some operations defined by the reset function.                                |

> Corresponding data structure:
>
> ```
> typedef struct{
> 	uint8_t data;
> }tuya_ble_device_reset_data_t;
> ```

**TUYA\_BLE\_CB\_EVT\_UPDATE\_LOGIN\_KEY\_VID**

| **Event**       | TUYA\_BLE\_CB\_EVT\_UPDATE\_LOGIN\_KEY\_VID                                                                                  |
| --------------- | ---------------------------------------------------------------------------------------------------------------------------- |
| **Description** | After the Notification book is bound to success, the mobile App will send the login key and device virtual ID to the device. |
| **Notice**      | The BLE device does not need to process this information.                                                                    |

> Corresponding data structure:
>
> ```
> typedef struct{
>     uint8_t login_key_len;
>     uint8_t vid_len;
> 	uint8_t login_key[LOGIN_KEY_LEN];
> 	uint8_t vid[DEVICE_VIRTUAL_ID_LEN];
> }tuya_ble_login_key_vid_data_t;
> ```

### Example of SDK port in nrf52832 <a href="#title-14-example-20of-20sdk-20port-20in-20nrf52832" id="title-14-example-20of-20sdk-20port-20in-20nrf52832"></a>

This section takes nrf52832 as an example to describe the porting steps for the OS-free architecture platforms. You can contact your account manager in Tuya for the detailed procedure of nrf52832 and the demo of other platforms.

1. Download the original SDK of nrf52832 chip, for example, nRF5\_SDK\_15.2.0\_9412b96, and prepare a nrf52832 development board.
2. Unzip the SDK to a custom directory, as shown in the following picture.

   ![TUYA BLE SDK User Guide](https://airtake-public-data-1254153901.cos.ap-shanghai.myqcloud.com/goat/20200606/c93fc48db4224b6c81eccbe4ad7911b9.png)
3. Open the **examples** > **ble\_peripheral** directories. In this directory, you can see tutorials of ble peripheral.

   ![TUYA BLE SDK User Guide](https://airtake-public-data-1254153901.cos.ap-shanghai.myqcloud.com/goat/20200606/f65a85a15a8843ddb53e62f01c2ca6cc.png)
4. Create a project with `ble_app_uart` as the template, and copy the `ble_app_uart` folder and rename it (for example, `tuya_ble_standard_nordic`).

   ![TUYA BLE SDK User Guide](https://airtake-public-data-1254153901.cos.ap-shanghai.myqcloud.com/goat/20200606/79263a3d6b9944b9bf5e4ea05efc2602.png)
5. Enter the **PCA10040** > **S123** directories, open the project and compile it. You must confirm that it can be compiled and run correctly on the development board.
6. Create a file with the `ble_nus.c` in the **nRF\_BLE\_Services** directory as the template and `tuya_ble_service.c` as the name, modify your code to cater for the `tuya ble service`, modify the code in the `main.c` file and broadcast the changes according the broadcasting content specified in the previous introduction.
7. Compile and download to your development board and run, use Bluetooth scanning tool in your mobile phone (for example, LightBlue for iOS) to scan devices. Make sure that your scanning result meet the requirement of broadcasting and service.
8. Download the tuya ble sdk to the directory of a new project, add the source files to the project and compile for once.

   ![TUYA BLE SDK User Guide](https://airtake-public-data-1254153901.cos.ap-shanghai.myqcloud.com/goat/20200606/82905df0e29c47e1bb0702b81d5244f3.png)
9. Your project must have the same directories as the following pictures. Note that select correct library files.

   ![TUYA BLE SDK User Guide](https://airtake-public-data-1254153901.cos.ap-shanghai.myqcloud.com/goat/20200606/dbca373f8cdd4b528fa6b7cc0d5b9343.png)
10. Create a `custom_tuya_ble_config.h` file, and save to the directories of your project, for example, `tuya_ble_app`.

    You must configure the items in the `custom_tuya_ble_config.h` according to your actual demand and environment. The tuya ble sdk provides references for some chip platforms. The reference configuration files are stored in each platform directory under the `port` directory in the `tuya ble sdk` folder.
11. Assign the name of `custom_tuya_ble_config.h` to the `CUSTOMIZED_TUYA_BLE_CONFIG_FILE` file, and add to the macro of your project.

    ![TUYA BLE SDK User Guide](https://airtake-public-data-1254153901.cos.ap-shanghai.myqcloud.com/goat/20200606/86e7c620288845919d79a4d8bdb6df5e.png)
12. Create port files, and the name can be `tuya_ble_port_nrf52832.h` and `tuya_ble_port_nrf52832.c`, or replace the `nrf52832` with other platforms.

    In the port file, implement the interfaces listed in the `tuya_ble_port.h` file according to your configurations. Not all of the listed interfaces need to be implemented, for example, this porting tutorial does not involve OS, therefore, the OS-specific APIs are not needed. This tutorial is configured to use the internal memory management module of tuya ble sdk, therefore the memory allocation and release APIs are not needed. Under the port file of the tuya ble sdk, every platform is provided with porting reference file with the platform as the file name.
13. After the port file is completed, define the port file in the `custom_tuya_ble_config.h`.

    ![TUYA BLE SDK User Guide](https://airtake-public-data-1254153901.cos.ap-shanghai.myqcloud.com/goat/20200606/2498f621b07144b2a90cc81794a6352e.png)
14. Compile. If the compiling fails, examine your code first.
15. In this tutorial, a specific file is created to handle the initialization of the tuya ble sdk, call back function registration, and callback message handling. As the following picture shows.

    ![TUYA BLE SDK User Guide](https://airtake-public-data-1254153901.cos.ap-shanghai.myqcloud.com/goat/20200606/d7e93f1ccd2142b681e7e16ef7aafb5e.png)
16. Register the product in the Tuya IoT console and copy the product ID to your project code. The macro name `APP_PRODUCT_ID`, `APP_BUILD_FIRMNAME`, `TY_APP_VER_NUM`, `TY_APP_VER_STR`, `TY_HARD_VER_NUM`, and `TY_HARD_VER_STR` cannot be changed. Replace the `xxxxxxxx` as the product ID. If you use the test and production tooling authorization, contact your Tuya account manager to create a project for you, and replace the `tuya_ble_sdk_app_demo_nrf52832` as the project name.

    ![TUYA BLE SDK User Guide](https://airtake-public-data-1254153901.cos.ap-shanghai.myqcloud.com/goat/20200606/0ddbfd9f0e6d4d3b86bb3401182fec32.png)
17. Call the `tuya_ble_app_init()`, `tuya_ble_main_tasks_exec()`, `tuya_ble_gatt_receive_data()`, `tuya_ble_common_uart_receive_data()`, `tuya_ble_disconnected_handler()`, and `tuya_ble_connected_handler()` respectively in your code, as the following picture shows.

    ![TUYA BLE SDK User Guide](https://airtake-public-data-1254153901.cos.ap-shanghai.myqcloud.com/goat/20200606/60e2680231f7463d90e01a7804e3a770.png)
18. During the development and debug stage, contact your Tuya account manager to obtain the `auth_key_test` and `device_id_test`.
19. Compile your code, download the code to the development board, download Tuya Smart App, and scan to add devices.

### OTA protocol <a href="#title-15-ota-20protocol" id="title-15-ota-20protocol"></a>

The firmware upgrade and the chip platform architecture are related, therefore the tuya ble sdk only provides a firmware upgrade interface, and your Application only needs to be implemented according to the OTA protocol described below through the OTA communication interface provided by tuya ble sdk.

The Application receives OTA data through the registered callback function (if the chip platform does not have OS) or registered queue (if the chip platform has an OS), the EVENT ID is `TUYA_BLE_CB_EVT_OTA_DATA`.

For the data format, see the upgrade protocol section. And the OTA response data is sent through the `tuya_ble_ota_response(tuya_ble_ota_response_t *p_data)` function.

#### OTA upgrade process <a href="#title-16-ota-20upgrade-20process" id="title-16-ota-20upgrade-20process"></a>

The following picture illustrates the process of OTA upgrade.

![TUYA BLE SDK User Guide](https://airtake-public-data-1254153901.cos.ap-shanghai.myqcloud.com/goat/20200615/1a6743e468604464958021844cc8462e.png)

#### OTA upgrade protocol <a href="#title-17-ota-20upgrade-20protocol" id="title-17-ota-20upgrade-20protocol"></a>

**OTA data types**

```
typedef enum 

{

​ TUYA_BLE_OTA_REQ, // OTA Upgrade request command

​ TUYA_BLE_OTA_FILE_INFO, // OTA Upgrade file information command

​ TUYA_BLE_OTA_FILE_OFFSET_REQ, // OTA Upgrade file offset command

​ TUYA_BLE_OTA_DATA, // OTA Upgrade data command

​ TUYA_BLE_OTA_END, // End of OTA upgrade command

​ TUYA_BLE_OTA_UNKONWN,

}tuya_ble_ota_data_type_t;

typedef struct{

​ tuya_ble_ota_data_type_t type; 

​ uint16_t data_len;

​ uint8_t *p_data;

}tuya_ble_ota_data_t; //The mobile app sends the data struct corresponding to the OTA upgrade EVENT (TUYA_BLE_CB_EVT_OTA_DATA)..

typedef struct{

​ tuya_ble_ota_data_type_t type; 

​ uint16_t data_len;

​ uint8_t *p_data;

}tuya_ble_ota_response_t;  //Data struct corresponding to OTA response data sending function tuya_ble_ota_response(tuya_ble_ota_response_t *p_data)
```

**OTA upgrade request (TUYA\_BLE\_OTA\_REQ)**

**From App to BLE devices**

|         | data\_len=1 |
| ------- | ----------- |
| Length: | 1 byte      |
| Data:   | fixed 0     |

**From BLE devices to App**

|         | data\_len=9 |              |        |         |                        |
| ------- | ----------- | ------------ | ------ | ------- | ---------------------- |
| Length: | 1 byte      | 1 byte       | 1 byte | 4 byte  | 2 byte                 |
| Data:   | Flag        | OTA\_Version | 0      | Version | Maximum packet length. |

* `Flag`: 0x00 indicates upgrade confirmation, 0x01 indicates upgrade denial.
* `OTA_Version`: OTA Protocol version, for example 0x03 indicates the protocol version of 3.X.
* `Version`: the current firmware version number in the big-endian format. For example, `0x00 01 00 02` indicates the version number is V1.0.2.
* `Maximum packet length`: the maximum length of a single packet allowed by the device, unit: byte. The current version cannot exceed 512 bytes.

**OTA upgrade file information (TUYA\_BLE\_OTA\_FILE\_INFO)**

**From App to BLE devices**

|         | data\_len=37 |            |              |          |             |        |
| ------- | ------------ | ---------- | ------------ | -------- | ----------- | ------ |
| Length: | 1 byte       | 8 byte     | 4 byte       | 16 byte  | 4 byte      | 4 byte |
| Data:   | 0            | product id | file version | file MD5 | file length | CRC32  |

* `product id`: the PID.
* `file version`: for example, `0x00010002` indicates the version is V1.0.2.

**From BLE devices to App**

|         | data\_len=26 |        |                   |                  |                                     |
| ------- | ------------ | ------ | ----------------- | ---------------- | ----------------------------------- |
| Length: | 1 byte       | 1 byte | 4 byte            | 4 byte           | 16 byte                             |
| Data:   | 0            | STATE  | Saved data length | Saved data CRC32 | saved data MD5 (Not used currently) |

* `STATE`:

  `0x00`: upgrade success

  `0x01`: PID different

  `0x02`: the file version is lower than or equal to the current version

  `0x03`: file size is out of range.
* `Other`: a reserved field.
* `File information has been saved`: to support the resuming of the breakpoint, the file information that are stored in the device will be returned. After receiving the infomration, the App first calculates the CRC32 of the corresponding length of the new file according to the length of the stored file returned by the device, and then compares it with the CRC32 returned by the device. If the both are consistent, then in the following file start transmission request, the start transmission offset is changed to the length value. Otherwise, the file start transmission offset is changed to `0`, indicating that the transmission starts from the beginning.

**OTA upgrade file offset (TUYA\_BLE\_OTA\_FILE\_OFFSET\_REQ)**

**From App to BLE devices**

|         | data\_len=5 |        |
| ------- | ----------- | ------ |
| Length: | 1 byte      | 4 byte |
| Data:   | 0           | Offset |

`offset`: upgrade file offset.

**From BLE devices to App**

|         | data\_len=5 |        |
| ------- | ----------- | ------ |
| Length: | 1 byte      | 4 byte |
| Data:   | 0           | Offset |

`offset`: the starting file offset required by the device. The offset address of the actual file transfer should be based on the device requirements, and the address required by the device will be less or equal to the offset given by the App.

**OTA Upgrade data (TUYA\_BLE\_OTA\_DATA)**

**From App to BLE devices**

|         | data\_len=7+n |                |                               |                            |                      |
| ------- | ------------- | -------------- | ----------------------------- | -------------------------- | -------------------- |
| Length: | 1 byte        | 2 byte         | 2 byte                        | 2 byte                     | n byte               |
| Data:   | 0             | Package number | Current package data length n | Current package data CRC16 | Current package data |

The packet number starts from `0`, and the high byte is at the beginning of the packet.

**From BLE devices to App**

|         | data\_len=2 |        |
| ------- | ----------- | ------ |
| Length: | 1 byte      | 1 byte |
| Data:   | 0           | STATE  |

`STATE`:

* `0x00`: success
* `0x01`: the package number is abnormal
* `0x02`: the length is inconsistent
* `0x03`: CRC check fails
* `0x04`: others

**OTA upgrade is over (TUYA\_BLE\_OTA\_END)**

**From App to BLE devices**

|         | data\_len=1 |
| ------- | ----------- |
| Length: | 1 byte      |
| Data:   | 0           |

**From BLE devices to App**

|         | data\_len=2 |        |
| ------- | ----------- | ------ |
| Length: | 1 byte      | 1 byte |
| Data:   | 0           | STATE  |

`STATE`:

* `0x00`: success
* `0x01`: the total data length is wrong
* `0x02`: the total CRC of data check fails
* `0x03`: others

  If you need to restart after verifying the success of the ble device OTA file, you can call the API `tuya_ble_ota_response(tuya_ble_ota_response_t *p_data)` to respond to the App result at least no delay and restart after 2 seconds.

#### OTA upgrade APIs <a href="#title-18-ota-20upgrade-20apis" id="title-18-ota-20upgrade-20apis"></a>

The Application receives OTA data through the registered callback function (without RTOS environment) or registered queue (in the RTOS environment), the EVENT ID is `TUYA_BLE_CB_EVT_OTA_DATA`. And the OTA response data is sent through `tuya_ble_ota_response(tuya_ble_ota_response_t *p_data)` function.

As the following picture shows, the Application calls the custom OTA processing function.

![TUYA BLE SDK User Guide](https://airtake-public-data-1254153901.cos.ap-shanghai.myqcloud.com/goat/20200318/a128f0deee0746709a593f66b47cce18.png)

An example of OTA processing function:

```
void tuya_ota_proc(uint16_t cmd,uint8_t*recv_data,uint32_t recv_len)
{
TUYA_BLE_LOG_DEBUG("ota cmd: 0x%04x , recv_len: %d",cmd,recv_len);
switch(cmd)
{
case TUYA_BLE_OTA_REQ:
tuya_ota_start_req(recv_data,recv_len);
break;
case TUYA_BLE_OTA_FILE_INFO:
tuya_ota_file_info_req(recv_data,recv_len);
break;
case TUYA_BLE_OTA_FILE_OFFSET_REQ:
tuya_ota_offset_req(recv_data,recv_len);
break;
case TUYA_BLE_OTA_DATA:
tuya_ota_data_req(recv_data,recv_len);
break;
case TUYA_BLE_OTA_END:
tuya_ota_end_req(recv_data,recv_len);
break;
default:
break;
}

}
```

### Reference of production testing APIs <a href="#title-19-reference-20of-20production-20testing-20apis" id="title-19-reference-20of-20production-20testing-20apis"></a>

Before BLE devices are connected to Tuya IoT development platform, they must be burned with license information (one set of licenses for one device), which is usually burned in factory production. You can also use Tuya production testing tools to burn license and test. Alternatively, you can purchase licenses in batches, and use custom protocol and interface to manage them.

If you use custom protocol, you must set the `auth_key` and `device_id` when you initialize the tuya ble sdk. As the following sample shows.

```
tuya_ble_device_param_t device_param ;

void tuya_ble_app_init(void)
{
memset(&device_param,0,sizeof(tuya_ble_device_param_t));
device_param.device_id_len = 16;
memcpy(device_param.auth_key,(void *)auth_key_test,AUTH_KEY_LEN);
memcpy(device_param.device_id,(void *)device_id_test,DEVICE_ID_LEN);
device_param.p_type = TUYA_BLE_PRODUCT_ID_TYPE_PID;
device_param.product_id_len = 8;
memcpy(device_param.product_id,APP_PRODUCT_ID,8);
device_param.firmware_version = TY_APP_VER_NUM;
device_param.hardware_version = TY_HARD_VER_NUM;

tuya_ble_sdk_init(&device_param);
tuya_ble_callback_queue_register(tuya_cb_handler);

tuya_ota_init();

TUYA_APP_LOG_INFO("app version: "TY_APP_VER_STR);
}

```

If you use the authorization tool of Tuya production testing to burn the license and you use the tuya ble sdk to manage authorization, then the `auth_key` and `device_id` are not needed when you initialize the tuya ble sdk. As the following sample shows.

```
tuya_ble_device_param_t device_param ;

void tuya_ble_app_init(void)
{
memset(&device_param,0,sizeof(tuya_ble_device_param_t));
device_param.device_id_len = 0;
device_param.p_type = TUYA_BLE_PRODUCT_ID_TYPE_PID;
device_param.product_id_len = 8;
memcpy(device_param.product_id,APP_PRODUCT_ID,8);
device_param.firmware_version = TY_APP_VER_NUM;
device_param.hardware_version = TY_HARD_VER_NUM;

tuya_ble_sdk_init(&device_param);
tuya_ble_callback_queue_register(tuya_cb_handler);

tuya_ota_init();

TUYA_APP_LOG_INFO("app version: "TY_APP_VER_STR);
}
```

If you use the authorization tool of Tuya production testing to burn the license, make sure that the `TUYA_BLE_DEVICE_AUTH_SELF_MANAGEMENT` is enabled by setting `#define TUYA_BLE_DEVICE_AUTH_SELF_MANAGEMENT 1`.

The production testing consists of the general authorization testing and the general device testing, and the general machine testing is subordinate to the general authorization testing. The general authorization testing includes authorization burning, GPIO testing and RSSI testing. The general device testing provides additional testing for tailored products, you can see the Bluetooth General Authorization Protocol of Production Testing or Bluetooth General Device Testing Protocol of Production Testing for more information.

The tuya ble sdk has achieved the protocol of general authorization testing, however, testing such as RSSI testing, GPIO testing and additional testing for tailored products provided by general device testing must be implemented according to the product configuration. The source file `tuya_ble_app_production_test.c` in the tuya ble sdk has prepared APIs for the preceding testings, and they are defined in the form of `__TUYA_BLE_WEAK` weak implement. Your Application can redefine those APIs in other source files, for example, creating a `custom_app_product_test.c` file, and referring to it in your custom configuration file. As the following pictures show.

![TUYA BLE SDK User Guide](https://airtake-public-data-1254153901.cos.ap-shanghai.myqcloud.com/goat/20200606/3adadee1378d45529b58be0a19c8c18d.png)

![TUYA BLE SDK User Guide](https://airtake-public-data-1254153901.cos.ap-shanghai.myqcloud.com/goat/20200606/62bb68050a38429b8f7e040bacca9c3a.png)

![](https://2999784448-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-MBlD-pGvqUEQDs9SdgH%2F-MC2SU0GJi78x02f5wEr%2F-MC2UX3CcShIbvpbEybs%2Fimage.png?alt=media\&token=a68cd049-ee1e-4569-8d6f-e00748c96acf)
