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

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

Overview of tuya ble sdk

Framework

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

  • 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

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

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

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

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

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

The following picture illustrates the broadcast packet format of BLE.

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

Length: 0x0C or 0x14 Type: 0x16 Data: 0x01, 0xA2, type (0-pid,1-product_key)PID, or product_key (in 8 or 16 byte)

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

Length: 0x19 Type: 0xff Date: COMPANY ID:0x07D0 FLAG: 0x00 Protocol version: 0x03 Encryption method: 0x00 Communication capacity: 0x0000 Reserved field: 0x00

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

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.

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

TUYA_BLE_LOG

Function name

TUYA_BLE_LOG

Prototype

void TUYA_BLE_LOG(const char *format,…)

Description

Formatted output.

Parameters

format[in]: format controller. …[in]: variable parameters.

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_data[in]: the data pointer to be printed. len[in]: data length.

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_ad_data[in]: new broadcast data. ad_len[in]: data length.

Responses

TUYA_BLE_SUCCESS: success. Others: failure.

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_sr_data[in]: new scan response data. sr_len[in]: data length.

Responses

TUYA_BLE_SUCCESS: success. Others: failure.

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

TUYA_BLE_SUCCESS: success. Others: failure.

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_data[in]: the data pointer to send. len[in]: the data length, less than 20 bytes.

Responses

TUYA_BLE_SUCCESS: success. Others: failure.

Notice

It must be done in the notification method.

tuya_ble_timer_create

Function name

tuya_ble_timer_create

Prototype

tuya_ble_status_t tuya_ble_timer_create(void** p_timer_id,uint32_t timeout_value_ms, tuya_ble_timer_mode mode,tuya_ble_timer_handler_t timeout_handler)

Description

create a timer.

Parameters

p_timer_id[out]: the timer pointer. timeout_value_ms[in]: the timing, unit: ms. mode[in]: - TUYA_BLE_TIMER_SINGLE_SHOT: one-time mode. - TUYA_BLE_TIMER_REPEATED: recurring mode. - timeout_handler [in]: the timer callback.

Responses

TUYA_BLE_SUCCESS: success. Others: failure.

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

TUYA_BLE_SUCCESS: success. TUYA_BLE_ERR_INVALID_PARAM: invalid parameters. Others: failure.

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

TUYA_BLE_SUCCESS: success. TUYA_BLE_ERR_INVALID_PARAM: invalid parameters. Others: failure.

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

timer_id [in]: the timer ID. timeout_value_ms[in]: the timing, unit: ms.

Responses

TUYA_BLE_SUCCESS: success. TUYA_BLE_ERR_INVALID_PARAM: invalid parameters. Others: failure.

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

TUYA_BLE_SUCCESS: success. TUYA_BLE_ERR_INVALID_PARAM: invalid parameters. Others: failure.

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

TUYA_BLE_SUCCESS: success. Others: failure.

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

TUYA_BLE_SUCCESS: success. Others: failure.

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

TUYA_BLE_SUCCESS: success. Others: failure.

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_buf [out]: the array of random digit pointer. len[in]: the byte number of the random value.

Responses

TUYA_BLE_SUCCESS: success. Others: failure.

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

timestamp [out]: the timestamp. timezone [out]: the time zone, data type: signed integer, the value must be 100 times of the real time.

Responses

TUYA_BLE_SUCCESS: success. Others: failure.

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

timestamp [in]: Unix timestamp. timezone [in]: the time zone, data type: signed integer, the value must be 100 times of the real time.

Responses

TUYA_BLE_SUCCESS: success. Others: failure.

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

TUYA_BLE_SUCCESS: success. Others: failure.

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

addr[in]: the initial address of NV space to be erased. size[in]: the space length to be erased, unit: byte.

Responses

TUYA_BLE_SUCCESS: success. Others: failure.

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

addr[in]: the initial address of NV space to write data. p_data[in]: the initial address of NV space to write data. size[in]: the data size, unit: byte.

Responses

TUYA_BLE_SUCCESS: success. Others: failure.

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

addr[in]: the initial address of NV space to read data. p_data[out]: the initial address of NV space to write data. size[in]: the data size, unit: byte.

Responses

TUYA_BLE_SUCCESS: success. Others: failure.

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

addr[in]: the initial address of NV space to erase data. size[in]: the data size, unit: byte. p_context[in]: user custom data. callback[in]: returns the API results.

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

addr[in]: the initial address of NV space to write data. p_src[in]: the address to write date. size[in]: the data size, unit: byte. p_context[in]: user custom data. callback[in]: returns the API results.

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

addr[in]: the initial address of NV space to read data. p_dest[out]: the address to read data. size[in]: the data size, unit: byte. p_context[in]: user custom data. callback[in]: returns the API results.

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

TUYA_BLE_SUCCESS: success. Others: failure.

Notice

Under the following circumstances, there is no need to implement the tuya_ble_common_uart_init interface: - The functions of test and production authorization are not used. - The SDK's production testing authorization function are used, and the Application has initialized the UART before initializing the SDK.

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_data[in]: the data pointer to send. len[in]: the data size.

Responses

TUYA_BLE_SUCCESS: success. Others: failure.

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

pp_handle [out]: passes back a handle by which the created task can be referenced. p_name[in]: A descriptive name for the task. p_routine [in]: pointer to task routine function that must be implemented to never return. p_param[in]: pointer parameter passed to the task routine function. stack_size[in]: the size of the task stack that is specified as the number of bytes. priority[in]: the priority at which the task should run. Higher priority task has higher priority value.

Responses

True: task was created successfully and added to task ready list. False: task was failed to create.

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

True: task was deleted successfully False: task was failed to delete.

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

True: task was suspend successfully. False: task was failed to suspend.

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

True: task was resumed successfully. False: task was failed to resume.

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

pp_handle [out]: passes back a handle by which the message queue can be referenced. msg_num [in]: the maximum number of items that the queue can contain. msg_size [in]: the number of bytes each item in the queue will require.

Responses

True: message queue was created successfully. False: message queue was failed to create.

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

True: message queue was deleted successfully. False: message queue was failed to delete.

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

pp_handle [in]: the handle to the message queue being peeked. p_msg_num[out]: passes back the number of items residing on the message queue.

Responses

True: message queue was peeked successfully. False: message queue was failed to peek.

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

pp_handle [in]: the handle to the message queue on which the item is to be sent. p_msg[in]: pointer to the item that is to be sent on the queue. wait_ms[in]: the maximum amount of time in milliseconds that the task should block waiting for the item to sent on the queue. - 0: no blocking and return immediately. - 0xFFFFFFFF: blocks infinitely until the item received. - others: the timeout value in milliseconds.

Responses

True: message item was sent successfully. False: message item was failed to send.

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

pp_handle [in]: the handle to the message queue from which the item is to be received. p_msg[out]: pointer to the buffer into which the received item will be copied. wait_ms[in]: the maximum amount of time in milliseconds that the task should block waiting for the item to received on the queue. - 0: no blocking and return immediately. - 0xFFFFFFFF: blocks infinitely until the item received. - others: the timeout value in milliseconds.

Responses

True: message item was received successfully. False: message item was failed to receive.

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

If the TUYA_BLE_SELF_BUILT_TASK is undefined, Application should provide the task to sdk to process the event. The sdk will use this port to send event to the task of provided by Application.

Parameters

evt [in]: the message data point to be send. wait_ms[in]: the maximum amount of time in milliseconds that the task should block waiting for the item to sent on the queue.

  • 0: no blocking and return immediately.

  • 0xFFFFFFFF: blocks infinitely until the item received.

  • others: the timeout value in milliseconds.

Responses

True: message item was sent successfully. False: message item was failed to send.

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

key [in]: keys to encrypt the plaintext In_put[in]: specified plaintext to be encrypted. in_put_len[in]: byte length of the data to be encrypted, must be multiples of 16. Out_put[out]: output buffer to store encrypted data.

Responses

True: successful. False: fail.

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

key [in]: keys to decrypt the plaintext In_put[in]: specified encrypted data to be decypted in_put_len[in]: byte length of the data to be decrypted, must be multiples of 16. Out_put[out]: output buffer to store decrypted data.

Responses

True: successful. False: fail.

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_toutput)

Description

128 bit AES CBC encryption on specified plaintext and keys.

Parameters

key [in]: keys to encrypt the plaintext. iv[in]: initialization vector (IV) for CBC mode. In_put[in]: specified plain text to be encrypted. in_put_len[in]: byte length of the data to be encrypted, must be multiples of 16. Out_put[out]: output buffer to store encrypted data.

Responses

True: successful. False: fail.

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

key [in]: keys to decrypt the plaintext. Iv[in]: initialization vector (IV) for CBC mode In_put[in]: specified encrypted data to be decrypted. in_put_len[in]: byte length of the data to be decrypted, must be multiples of 16. Out_put[out]: output buffer to store decrypted data.

Responses

True: successful. False: fail.

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

In_put[in]: specified plain text to be encrypted. in_put_len[in]: byte length of the data to be encrypted. Out_put[out]: output buffer to store md5 result data,output data lenghth is always 16.

Responses

True: successful. False: fail.

tuya_ble_hmac_sha1_crypt

Function name

tuya_ble_hmac_sha1_crypt

Prototype

bool tuya_ble_hmac_sha1_crypt(constuint8_t *key, uint32_t key_len, const uint8_t *input, uint32_t input_len,uint8_t *output)

Description

Calculates the full generic HMAC on the input buffer with the provided key.

Parameters

key [in]: The HMAC secret key. key_len[in]: The length of the HMAC secret key in bytes. In_put[in]: specified plain text to be encrypted. in_put_len[in]: byte length of the data to be encrypted. Out_put[out]: output buffer to store the result data.

Responses

True: successful. False: fail.

Notice

Not used currently, no need to implement.

tuya_ble_hmac_sha256_crypt

Function name

tuya_ble_hmac_sha1_crypt

Prototype

bool tuya_ble_hmac_sha256_crypt(const uint8_t *key, uint32_t key_len, const uint8_t *input, uint32_t input_len, uint8_t *output)

Description

Calculates the full generic HMAC on the input buffer with the provided key.

Parameters

key [in]: The HMAC secret key. key_len[in]: The length of the HMAC secret key in Bytes. In_put[in]: specified plain text to be encrypted. in_put_len[in]: byte length of the data to be encrypted. out_put[out]: output buffer to store the result data.

Responses

True: successful. False: fail.

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

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

Custom configuration file. This file overwrites the default settings in the tuya_ble_config.h file. Your Application must create a configuration file with a new name, and assign the file name to the CUSTOMIZED_TUYA_BLE_CONFIG_FILE, for example, CUSTOMIZED_TUYA_BLE_CONFIG_FILE = <custom_tuya_ble_config.h>.

CUSTOMIZED_TUYA_BLE_APP_PRODUCT_TEST_HEADER_FILE

Macro

CUSTOMIZED_TUYA_BLE_APP_PRODUCT_TEST_HEADER_FILE

Dependency

None.

Description

The tuya ble sdk provides basic test and production authorization services. 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 CUSTOMIZED_TUYA_BLE_APP_PRODUCT_TEST_HEADER_FILE.

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

If the chip architecture is based on OS, such as FreeRTOS, set #define TUYA_BLE_USE_OS 1, otherwise, set #define TUYA_BLE_USE_OS 0.

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

#define TUYA_BLE_USE_OS 1 #define TUYA_BLE_SELF_BUILT_TASK 1

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

#define TUYA_BLE_USE_OS 1 #define TUYA_BLE_SELF_BUILT_TASK 1

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

The communication of devices. Possible setting: TUYA_BLE_DEVICE_COMMUNICATION_ABILITY_BLE : whether use BLE or not. TUYA_BLE_DEVICE_COMMUNICATION_ABILITY_REGISTER_FROM_BLE : whether register devices via ble or not. TUYA_BLE_DEVICE_COMMUNICATION_ABILITY_MESH : whether use Mesh or not. TUYA_BLE_DEVICE_COMMUNICATION_ABILITY_WIFI_24G : whether support 2.4G Wi-Fi or not. TUYA_BLE_DEVICE_COMMUNICATION_ABILITY_WIFI_5G : whether support 5G Wi-Fi or not. TUYA_BLE_DEVICE_COMMUNICATION_ABILITY_ZIGBEE : whether support Zigbee or not. TUYA_BLE_DEVICE_COMMUNICATION_ABILITY_NB : whether support NB-IoT or not.

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

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: #define TUYA_BLE_WIFI_DEVICE_REGISTER_MODE 1 If no: #define TUYA_BLE_WIFI_DEVICE_REGISTER_MODE 0

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

The communication encryption method of devices. Possible setting: TUYA_BLE_SECURE_CONNECTION_WITH_AUTH_KEY : encrypt with auth_key. TUYA_BLE_SECURE_CONNECTION_WITH_ECC : encrypt with ECDH. TUYA_BLE_SECURE_CONNECTION_WTIH_PASSTHROUGH : no encrypt. For example: #define TUYA_BLE_DEVICE_AUTH_SELF_MANAGEMENT TUYA_BLE_SECURE_CONNECTION_WITH_AUTH_KEY

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

Determines whether the device needs to restart after updating the MAC address to take effect or not. If yes: #define TUYA_BLE_DEVICE_MAC_UPDATE_RESET 1 If no: #define TUYA_BLE_DEVICE_MAC_UPDATE_RESET 0

TUYA_BLE_USE_PLATFORM_MEMORY_HEAP

Macro

TUYA_BLE_USE_PLATFORM_MEMORY_HEAP

Dependency

None.

Description

Whether tuya ble sdk uses its own memory heap. If yes: #define TUYA_BLE_USE_PLATFORM_MEMORY_HEAP 0 If no: #define TUYA_BLE_USE_PLATFORM_MEMORY_HEAP 1

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

The size of the GATT send queue used by tuya ble sdk. Default value: 20. #define TUYA_BLE_GATT_SEND_DATA_QUEUE_SIZE 20

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

The size of GATT MTU: #define TUYA_BLE_DATA_MTU_MAX 20

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

Determines whether to enable log of tuya ble sdk or not. If yes: #define TUYA_BLE_LOG_ENABLE 1 If no: #define TUYA_BLE_LOG_ENABLE 0

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

Determines whether to enable the multi-color display for logs of SDK or not. If yes: #define TUYA_BLE_LOG_COLORS_ENABLE 1 If no: #define TUYA_BLE_LOG_COLORS_ENABLE 0

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

Defines the display level of the log of tuya ble sdk, which is divided into the following levels: #defineTUYA_BLE_LOG_LEVEL_ERROR 1U #defineTUYA_BLE_LOG_LEVEL_WARNING 2U #defineTUYA_BLE_LOG_LEVEL_INFO 3U #defineTUYA_BLE_LOG_LEVEL_DEBUG 4U If only error information needs to be printed, set as: #define TUYA_BLE_LOG_LEVEL TUYA_BLE_LOG_LEVEL_ERROR

TUYA_APP_LOG_ENABLE

Macro

TUYA_APP_LOG_ENABLE

Dependency

None.

Description

Whether to enable Application log. If yes: #define TUYA_APP_LOG_ENABLE 1 If no: #define TUYA_APP_LOG_ENABLE 0

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

Determines whether to enable the multi-color display for logs of Application or not. If yes: #define TUYA_APP_LOG_COLORS_ENABLE 1 If no: #define TUYA_APP_LOG_COLORS_ENABLE 0

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

Defines the display level of the log of tuya ble sdk, which is divided into the following levels: #defineTUYA_APP_LOG_LEVEL_ERROR 1U #defineTUYA_APP_LOG_LEVEL_WARNING 2U #defineTUYA_APP_LOG_LEVEL_INFO 3U #defineTUYA_APP_LOG_LEVEL_DEBUG 4U If only error information needs to be printed, set as: #define TUYA_APP_LOG_LEVEL TUYA_APP_LOG_LEVEL_ERROR

TUYA_BLE_ADVANCED_ENCRYPTION_DEVICE

Macro

TUYA_BLE_ADVANCED_ENCRYPTION_DEVICE

Dependency

None.

Description

Determines whether to use advanced encryption method. If yes: #define TUYA_BLE_ADVANCED_ENCRYPTION_DEVICE 1 If no: #define TUYA_BLE_ADVANCED_ENCRYPTION_DEVICE 0

Notice

It is not supported currently.

TUYA_NV_ERASE_MIN_SIZE

Macro

TUYA_NV_ERASE_MIN_SIZE

Dependency

None.

Description

The minimum erasure unit of NV space allocated to tuya ble sdk, for example: #define TUYA_NV_ERASE_MIN_SIZE 4096

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

The maximum write granularity in the NV space. For example, #define TUYA_NV_WRITE_GRAN 4 allows 4 bytes if you write to NV.

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

The initial NV space address allocated to tuya ble sdk. For example: #define TUYA_NV_START_ADDR 0x1000.

TUYA_NV_AREA_SIZE

Macro

TUYA_NV_AREA_SIZE

Dependency

None.

Description

The NV space size allocated to tuya ble sdk. For example, #define TUYA_NV_AREA_SIZE (4*TUYA_NV_ERASE_MIN_SIZE) . The value must be an integer multiple of TUYA_NV_ERASE_MIN_SIZE.

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

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

This function must be called from within the main loop. It will execute all events scheduled since the last time it was called.

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_data[in]: point to the data to be sent. len[in]: the length of the data to be sent, cannot exceed TUYA_BLE_DATA_MTU_MAX.

Responses

TUYA_BLE_SUCCESS: send successfully. TUYA_BLE_ERR_INTERNAL: failed.

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

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. If you do not use the production testing authorization function module provided by tuya ble sdk, you do not need to call this function.

Parameters

p_data[in]: point to the data to be sent. len[in]: length of data to be sent.

Responses

TUYA_BLE_SUCCESS: sent successfully. Other: failed to send.

Notice

This function internally calls malloc to apply for memory. If the Application configuration uses the malloc interface provided by the platform, confirm whether the platform malloc supports interrupt calls. If it does not support, it must not be called in UART interrupt tuya_ble_common_uart_receive_data().

tuya_ble_common_uart_send_full_instruction_received

Function name

tuya_ble_common_uart_send_full_instruction_received

Prototype

tuya_ble_status_t. tuya_ble_common_uart_send_full_instruction_received (uint8_t *p_data,uint16_t len)

Description

Sends the Tuya production testing protocol command (including the cmd/data/checksum) that are received and resolved by the UART to tuya ble sdk. If your Application does not use the protocol parsing function tuya_ble_common_uart_receive_data() provided by tuya ble sdk but uses a custom UART parsing function to parse the production testing protocol data, you need to call this function to send the parsed completed production testing instruction to tuya ble sdk.

Parameters

p_data[in]: Point to the complete command data to be sent. len[in]: Command data length to be sent.

Responses

TUYA_BLE_SUCCESS: Sent successfully. TUYA_BLE_ERR_INVALID_PARAM: parameter error. TUYA_BLE_ERR_NO_MEM: Failed to apply for memory. TUYA_BLE_ERR_BUSY: BLE SDK busy.

Notice

This function internally calls the malloc interface. If the Application is configured to use the chip platform-provided malloc interface, make sure that platform malloc supports interrupt calls. If it does not, you must not call tuya_ble_common_uart_send_full_instruction_received() in the UART interrupt.

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

tuya_ble_status_t tuya_ble_device_update_product_id. (tuya_ble_product_id_type_t type, uint8_t len, uint8_t* p_buf)

Description

Updates product id function.

Parameters

type [in]: id type. len[in]: id length. p_buf[in]: id data.

Responses

TUYA_BLE_SUCCESS: Sent successfully. TUYA_BLE_ERR_INVALID_PARAM: parameter error. TUYA_BLE_ERR_INTERNAL: internal error.

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

len[in]: length. p_buf[in]: loginkey.

Responses

TUYA_BLE_SUCCESS: Sent successfully. TUYA_BLE_ERR_INVALID_PARAM: parameter error. TUYA_BLE_ERR_INTERNAL: internal error.

Notice

This API is mainly used in Wi-Fi/BLE dual-protocol devices. Send network configuration information to Wi-Fi through BLE. The device registers the device with the cloud through Wi-Fi and calls. the login key after successful registration This function is sent to tuya ble sdk, but also needs to update the binding status.

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

TUYA_BLE_SUCCESS: Sent successfully. TUYA_BLE_ERR_INVALID_PARAM: parameter error. TUYA_BLE_ERR_INTERNAL: internal error.

Notice

This API is mainly used in Wi-Fi/BLE dual-protocol devices. (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. It also requires updating login key).

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

mcu_firmware_version [in]: MCU Firmware version number,For example, 0x010101 indicates v1.1.1. mcu_hardware_version [in]: MCU hardware version number (PCBA version number).

Responses

TUYA_BLE_SUCCESS: Sent successfully. Other: failed.

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

TUYA_BLE_SUCCESS: Sent successfully. TUYA_BLE_ERR_INVALID_PARAM: parameter error.

Notice

Initialization function, the Application must call this function to initialize the SDK, otherwise the SDK will not work. The initialization function may also be tuya_ble_sdk_init_async().

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, itsdevice_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

param_data [in]: Initialize parameter. callback[in]: Callback, This callback will be executed automatically after the initialization is completed.

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_data [in]: dp point data. len[in]: Data length,Cannot exceed TUYA_BLE_REPORT_MAX_DP_DATA_LEN.

Responses

TUYA_BLE_SUCCESS: Sent successfully. TUYA_BLE_ERR_INVALID_PARAM: parameter invalid. TUYA_BLE_ERR_INVALID_STATE: The current status does not support sending, such as Bluetooth disconnection. TUYA_BLE_ERR_NO_MEM: Memory Application failed. TUYA_BLE_ERR_INVALID_LENGTH: Data length error . TUYA_BLE_ERR_NO_EVENT: Other errors.

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

timestamp[in]: 4 byte Unix timestamp. p_data [in] :dp data. len[in]: The data length cannot exceed TUYA_BLE_REPORT_MAX_DP_DATA_LEN.

Responses

TUYA_BLE_SUCCESS: Sent successfully. TUYA_BLE_ERR_INVALID_PARAM: parameter error. TUYA_BLE_ERR_INVALID_STATE: The current status does not support sending, such as Bluetooth disconnection; TUYA_BLE_ERR_NO_MEM: Memory Application failed. TUYA_BLE_ERR_INVALID_LENGTH: Data length error. TUYA_BLE_ERR_NO_EVENT: Other errors.

Notice

The Application code reports dp point data to the App with time stamp by calling this function. Generally, data that is cached offline needs to be reported with time stamp.

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

time_string[in]: 13 byte ms level string format time. p_data [in]: dp point data. Len[in]: Data length, the maximum cannot exceed TUYA_BLE_REPORT_MAX_DP_DATA_LEN.

Responses

TUYA_BLE_SUCCESS: Sent successfully. TUYA_BLE_ERR_INVALID_PARAM: parameter error. TUYA_BLE_ERR_INVALID_STATE: The current status does not support sending, such as Bluetooth disconnection. TUYA_BLE_ERR_NO_MEM: Memory Application failed. TUYA_BLE_ERR_INVALID_LENGTH: Data length error. TUYA_BLE_ERR_NO_EVENT: Other errors.

Notice

The Application code reports dp point data to the App with string format time by calling this function. generally offline data only needs to be reported with time. 13 byte ms level time string, such as "0000000123456" ", less than 13 bytes before the supplementary character 0.

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

sn[in]: Application defined serial number. mode[in]: Reporting mode. p_data [in]: dp point data. len[in]: dp point data length, the maximum cannot exceed TUYA_BLE_REPORT_MAX_DP_DATA_LEN.

Responses

TUYA_BLE_SUCCESS: Sent successfully. TUYA_BLE_ERR_INVALID_PARAM: parameter error. TUYA_BLE_ERR_INVALID_STATE: The current status does not support sending, such as Bluetooth disconnection; TUYA_BLE_ERR_NO_MEM: Memory Application failed. TUYA_BLE_ERR_INVALID_LENGTH: Data length error. TUYA_BLE_ERR_NO_EVENT: Other errors.

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

tuya_ble_status_t tuya_ble_dp_data_with_flag_and_time_report (uint16_t sn,tuya_ble_report_mode_t mode,uint32_t timestamp,uint8_t *p_data,uint32_t len)

Description

Reports dp point data with time stamp.

Parameters

sn[in]: Application defined serial number. mode[in]: reporting mode. timestamp[in]: 4 byte Unix timestamp. p_data [in]: dp data. len[in]: dp point data length, the maximum cannot exceed TUYA_BLE_REPORT_MAX_DP_DATA_LEN.

Responses

TUYA_BLE_SUCCESS: Sent successfully. TUYA_BLE_ERR_INVALID_PARAM: parameter error. TUYA_BLE_ERR_INVALID_STATE: The current status does not support sending, such as Bluetooth disconnection. TUYA_BLE_ERR_NO_MEM: Memory Application failed. TUYA_BLE_ERR_INVALID_LENGTH: Data length error. TUYA_BLE_ERR_NO_EVENT: Other errors.

Notice

The Application code reports dp point data to the App with timestamp by calling this function. Generally, data that is cached offline needs to be reported with a time stamp.

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

tuya_ble_status_t tuya_ble_dp_data_with_flag_and_time_ms_string_report (uint16_t sn,tuya_ble_report_mode_t mode,uint8_t *time_string,uint8_t *p_data,uint32_t len)

Description

Reports dp point data with string formatted time with flag.

Parameters

sn[in]: Application defined serial number. mode[in]: reporting mode. time_string[in]: 13-byte ms-level string format time; p_data [in]: dp point data. Len[in]: data length, the maximum cannot exceed TUYA_BLE_REPORT_MAX_DP_DATA_LEN.

Responses

TUYA_BLE_SUCCESS: Sent successfully. TUYA_BLE_ERR_INVALID_PARAM: parameter error. TUYA_BLE_ERR_INVALID_STATE: The current status does not support sending, such as Bluetooth disconnection. TUYA_BLE_ERR_NO_MEM: Memory Application failed. TUYA_BLE_ERR_INVALID_LENGTH: Data length error. TUYA_BLE_ERR_NO_EVENT: Other errors.

Notice

The Application code reports dp point data to the App with string format time by calling this function. generally offline data only needs to be reported with time. 13 byte ms level time string, such as "0000000123456" ", less than 13 bytes before the supplementary character 0.

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

The Application code needs to call this function at the Bluetooth connection callback of the chip platform SDK. tuya ble sdk is based on this function to manage the internal Bluetooth connection state.

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

The Application code needs to call this function at the Bluetooth disconnection callback of the chip platform SDK. The tuya ble sdk manages the internal Bluetooth connection state according to the execution of this function.

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;