API

Last Updated on : 2024-11-20 08:51:40download

Tuya Bluetooth SDK includes APIs for managing Bluetooth communication to help you develop applications for smart devices communicating over Bluetooth. tuya_ble_api.c and tuya_ble_api.h includes the API functions, which can be used directly without modification.

tuya_ble_main_tasks_exec

Function tuya_ble_main_tasks_exec
Function prototype void tuya_ble_main_tasks_exec(void);
Description If your chip does not run a real-time operating system (RTOS), this function is used as the task scheduler of Tuya Bluetooth SDK and must be called in the main loop.
Parameters None
Return value None
Note This function must be called in the main loop. It executes all the scheduled events since the last call.

For example, the invoke location for the 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 tuya_ble_gatt_receive_data
Function prototype tuya_ble_status_t tuya_ble_gatt_receive_data(uint8_t*p_data,uint16_t len);
Description Call this function to send the data received from the GATT client to Tuya Bluetooth SDK.
Parameters p_data[in]: the pointer to data to be sent.
len[in]: the length of data to be sent, no more than TUYA_BLE_DATA_MTU_MAX.
Return value TUYA_BLE_SUCCESS: succeeded.
TUYA_BLE_ERR_INTERNAL: failed.
Note This API is used to send the data from the Bluetooth communication infrastructure to Tuya Bluetooth SDK. It must be called in Tuya’s callback of write characteristic (UUID: 00000001-0000-1001-8001-00805F9B07D0).

The following sample code is based on the nRF52832 platform.

/**@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);  // Send to the SDK.
		TUYA_BLE_HEXDUMP("nus_commdata_handler :",20,(uint8_t*)(p_evt->params.rx_data.p_data),p_evt->params.rx_data.length);  // Print the received data.
	}

}

tuya_ble_sdk_init

Function tuya_ble_sdk_init
Function prototype tuya_ble_status_t tuya_ble_sdk_init(tuya_ble_device_param_t * param_data);
Description Initialize Tuya Bluetooth SDK.
Parameters param_data [in]: the initialization parameter.
Return value TUYA_BLE_SUCCESS: succeeded.
TUYA_BLE_ERR_INVALID_PARAM: invalid parameter.
Note The application must call this function to initialize Tuya Bluetooth SDK. Otherwise, the SDK cannot run.

Parameters

tuya_ble_device_param_t struct is as follows.

typedef struct {
uint8_t use_ext_license_key;   /**< If you use the license stored by the SDK, set this parameter to 0. Otherwise, set it to 1. */
  uint8_t device_id_len;      /**<if 20,Compressed into 16.*/
  uint8_t device_id[DEVICE_ID_LEN_MAX];
uint8_t auth_key[AUTH_KEY_LEN];
tuya_ble_gap_addr_t mac_addr;
  uint8_t mac_addr_string[MAC_STRING_LEN];
  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 adv_local_name_len;
  uint8_t adv_local_name[TUYA_BLE_ADV_LOCAL_NAME_MAX_LEN]; /**< Onlysupported when TUYA_BLE_PROTOCOL_VERSION_HIGN >= 4. */
uint32_t firmware_version;               /**< 0x00010102 :v1.1.2 */
  uint32_t hardware_version;
  uint8_t device_vid[DEVICE_VIRTUAL_ID_LEN];  
  uint8_t login_key[LOGIN_KEY_LEN];
  uint8_t beacon_key[BEACON_KEY_LEN];  
  uint8_t bound_flag;
 
  uint8_t reserve_1;
  uint8_t reserve_2;
} tuya_ble_device_param_t;

Member variables

Variable Description
use_ext_license_key Specify whether to use the license information passed in by the application, including the device id, auth key, and mac address. TUYA_BLE_DEVICE_AUTH_SELF_MANAGEMENT is defined as 1.
  • If use_ext_license_key is 1, Tuya Bluetooth SDK uses the information passed in, namely device id, auth key, and mac address. Note that these parameters must be passed in. Otherwise, the device pairing with Tuya’s app will fail. The credentials for device activation obtained from other channels are also managed by the SDK.
  • If use_ext_license_key is 0, Tuya Bluetooth SDK will use the license obtained from the production test tool for device activation. Passing in the license is not needed. Assign 0 to device_id_len.
If TUYA_BLE_DEVICE_AUTH_SELF_MANAGEMENT is defined as 0, the application manages the license and activation information independently without SDK involvement. This way, this information must be passed in when the SDK is initialized. You must assign 1 to use_ext_license_key.
device_id, auth_key, mac_addr, and mac_addr_string The unique license assigned to each device by the Tuya Developer Platform. It is written to the chip with a production test tool. After a Bluetooth device is authorized with a license, Tuya Bluetooth SDK will manage the license, device id, and auth key.
product id The product ID (PID) that is automatically assigned to each product created on the Tuya Developer Platform. The PID is fixed, which is saved as a constant and passed in when Tuya Bluetooth SDK is initialized.
p_type The type of PID. TUYA_BLE_PRODUCT_ID_TYPE_PID is supported currently.
adv_local_name adv_local_name and adv_local_name_len are the variables of the custom name for Bluetooth advertising. If adv_local_name_len is 0, the name of Bluetooth advertising defaults to TY. When the application initializes the Bluetooth generic access profile (GAP), the specified name must be the one passed to theadv_local_name and up to five characters are allowed.
firmware_version and hardware_version The firmware and PCBA hardware version number. Both are four bytes. For example, 0x00010102 indicates v1.1.2 and 0x0101 indicates v1.1.
device_vid The virtual device ID that is assigned to each registered and bound device by the Tuya Developer Platform. It is used to query the history of device binding activity. For the Bluetooth device, assign 0 to this variable. For Wi-Fi and Bluetooth combo devices, you must specify this variable.
login key For the Bluetooth device, assign 0 to the beacon key and bound flag. For Wi-Fi and Bluetooth combo devices, you must specify this variable.

The following sample code takes nRF52832 platform as an example to show Tuya Bluetooth SDK initialization.

static const char auth_key_test[] = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
static const char device_id_test[] = "yyyyyyyyyyyyyyyy";
static const char mac_test[]  = "112233445566"; //The actual MAC address is 11:22:33:44:55:66
static const char device_local_name[] = "SDK20";  // Maximum 5 characters
#define APP_PRODUCT_ID "vvvvvvvv"
#define TY_APP_VER_NUM    0x0101
#define TY_APP_VER_STR   "1.1"
#define TY_HARD_VER_NUM   0x0100
#define TY_HARD_VER_STR   "1.0"
void tuya_ble_app_init(void)
{
tuya_ble_device_param_t device_param = {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;
device_param.adv_local_name_len = strlen(device_local_name);
  
memcpy(device_param.adv_local_name,device_local_name,device_param.adv_local_name
_len);
device_param.use_ext_license_key = 1; // If you use the license stored by the SDK, set this parameter to 0. Otherwise, set it to 1.
    
  if(device_param.use_ext_license_key==1)
 {
    device_param.device_id_len = 16;
    memcpy(device_param.auth_key,(void *)auth_key_test,32);
    memcpy(device_param.device_id,(void *)device_id_test,16);
    memcpy(device_param.mac_addr_string,mac_test,12);
    device_param.mac_addr.addr_type = TUYA_BLE_ADDRESS_TYPE_RANDOM;
 }
  tuya_ble_sdk_init(&device_param);
  tuya_ble_callback_queue_register(tuya_cb_handler);
  tuya_ota_init();
}
/*nRF52832 sample*/
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();
 
 
  // Enter main loop.
  for (;;)
 {
    idle_state_handle();
 }
}

tuya_ble_common_uart_receive_data

Function tuya_ble_common_uart_receive_data
Function prototype tuya_ble_status_t tuya_ble_common_uart_receive_data (uint8_t *p_data,uint16_t len);
Description Call this function to send data that the UART interface receives to Tuya Bluetooth SDK. The UART interface is used to communicate with a host.
If you do not implement the feature of test and authorization provided by the SDK, this function is not necessary.
Parameters p_data[in]: the pointer to data to be sent.
len[in]: the length of data to be sent.
Return value TUYA_BLE_SUCCESS: succeeded.
All other values: failed.
Note This function can call malloc to allocate a memory block. If you use the malloc interface provided by your chip platform, confirm whether the interrupt call is supported. If not supported, do not call tuya_ble_common_uart_receive_data() in the UART interrupt.

tuya_ble_common_uart_send_full_instruction_received

Function tuya_ble_common_uart_send_full_instruction_received
Function prototype tuya_ble_status_t
tuya_ble_common_uart_send_full_instruction_received (uint8_t *p_data,uint16_t len);
Description Call this function to send the parsed full instruction to Tuya Bluetooth SDK including commands, data, and checksum. If you use your custom UART function instead of tuya_ble_common_uart_receive_data() to parse the instruction received from the UART interface, you must call this function to send the parsed full instruction to Tuya Bluetooth SDK.
Parameters p_data[in]: the pointer to the full instruction to be sent.
len[in]: the length of data to be sent.
Return value TUYA_BLE_SUCCESS: succeeded.
TUYA_BLE_ERR_INVALID_PARAM: invalid parameter.
TUYA_BLE_ERR_NO_MEM: failed to request memory allocation.
TUYA_BLE_ERR_BUSY: SDK is busy.
Note This function can call malloc to allocate a memory block. If you use the malloc interface provided by your chip platform, confirm whether the interrupt call is supported. If not supported, do not call tuya_ble_common_uart_send_full_instruction_received() in the UART interrupt.
  • Tuya Bluetooth SDK integrates with the test and authorization feature. The SDK implemented on the Bluetooth module can communicate with the test tool installed on the host computer through the serial port.
  • You can use the tuya_ble_common_uart_receive_data() provided by Tuya Bluetooth SDK or your custom UART function to parse the instruction received from the UART interface, and then call tuya_ble_common_uart_send_full_instruction_received() function to send the parsed full instruction to Tuya Bluetooth SDK.

tuya_ble_device_update_product_id

Function tuya_ble_device_update_product_id
Function 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 Update the product ID (PID).
Parameters type [in]: the type of the ID.
len[in]: the length of the ID.
p_buf[in]: the data.
Return value TUYA_BLE_SUCCESS: succeeded.
TUYA_BLE_ERR_INVALID_PARAM: invalid parameter.
TUYA_BLE_ERR_INTERNAL: internal error.
Note If you choose the solution with an SoC as the microcontroller, this function is not necessary because the PID is a constant.

tuya_ble_device_update_login_key

Function tuya_ble_device_update_login_key
Function prototype tuya_ble_status_t tuya_ble_device_update_login_key(uint8_t* p_buf, uint8_t len);
Description Update the login_key.
Parameters len[in]: the length.
p_buf[in]: the login key.
Return value TUYA_BLE_SUCCESS: succeeded.
TUYA_BLE_ERR_INVALID_PARAM: invalid parameter.
TUYA_BLE_ERR_INTERNAL: internal error.
Note This function applies to the Wi-Fi and Bluetooth combo module. The application sends the wireless network information for pairing to the Wi-Fi module through Bluetooth. Then, a device can register with the cloud and call this function to send the updated login_key to Tuya Bluetooth SDK and update the activation status.

tuya_ble_device_update_beacon_key

Function tuya_ble_device_update_beacon_key
Function prototype tuya_ble_status_t tuya_ble_device_update_beacon_key(uint8_t* p_buf, uint8_t len);
Description Update the beacon key.
Parameters len[in]: the length.
p_buf[in]: the beacon key.
Return value TUYA_BLE_SUCCESS: succeeded.
TUYA_BLE_ERR_INVALID_PARAM: invalid parameter.
TUYA_BLE_ERR_INTERNAL: internal error.
Note This function applies to the Wi-Fi and Bluetooth combo module. The application sends the pairing information to the Wi-Fi through Bluetooth. Then, the module can register with the cloud and call this function to send the updated beacon_key to Tuya Bluetooth SDK and update the activation status.

tuya_ble_device_update_bound_state

Function tuya_ble_device_update_bound_state
Function prototype tuya_ble_status_t tuya_ble_device_update_bound_state(uint8_t state);
Description Update the binding status.
Parameters state[in]:
1: registered and bound.
0: unregistered and unbound.
Return value TUYA_BLE_SUCCESS: succeeded.
TUYA_BLE_ERR_INVALID_PARAM: invalid parameter.
TUYA_BLE_ERR_INTERNAL: internal error.
Note This function applies to the Wi-Fi and Bluetooth combo module. After a device is registered and bound through the Wi-Fi connection, the application calls this function to sync the updated login_key and binding status with Tuya Bluetooth SDK.

tuya_ble_device_update_mcu_version

Function tuya_ble_device_update_mcu_version
Function prototype tuya_ble_status_t tuya_ble_device_update_mcu_version(uint32_t mcu_firmware_version, uint32_t mcu_hardware_version);
Description Update the version number of the external MCU.
Parameters mcu_firmware_version [in]: the firmware version of the MCU. For example, 0x010101 indicates v1.1.1.
mcu_hardware_version [in]: the hardware version of the MCU, namely the PCBA version number.
Return value TUYA_BLE_SUCCESS: succeeded.
All other values: failed.
Note This function applies to developing with the Bluetooth module. If you choose the solution with an SoC as the microcontroller, this function is not necessary.

tuya_ble_dp_data_send

Function tuya_ble_dp_data_send
Function prototype tuya_ble_status_t tuya_ble_dp_data_send(
uint32_t sn,
tuya_ble_dp_data_send_type_t type,
tuya_ble_dp_data_send_mode_t mode,
tuya_ble_dp_data_send_ack_t ack,
uint8_t *p_dp_data,
uint32_t dp_data_len
) ;
Description Send data point (DP) data to the cloud.
Parameters sn[in]: the serial number.
type[in]: the type of data sending, which can be a proactive notification or a follow-up response.
mode[in]: the delivery mode.
ack[in]: whether an ACK message is required.
p_dp_data [in]: the DP data.
dp_data_len[in]: the length of data, no more than TUYA_BLE_SEND_MAX_DATA_LEN-7. TUYA_BLE_SEND_MAX_DATA_LEN is configurable.
Return value TUYA_BLE_SUCCESS: succeeded.
TUYA_BLE_ERR_INVALID_PARAM: invalid parameter.
TUYA_BLE_ERR_INVALID_STATE: failed to send data due to the current Bluetooth connection, such as Bluetooth disconnected.
TUYA_BLE_ERR_NO_MEM: failed to request memory allocation.
TUYA_BLE_ERR_INVALID_LENGTH: data length error.
TUYA_BLE_ERR_NO_EVENT: other errors.
Note The application calls this function to send DP data to the mobile app.

p_dp_data parameter description

The Tuya Developer Platform manages data through DPs. Each product feature defined on the platform is described as a DP. The DP data consists of four parts. For more information, see Custom Functions.

  • Dp_id: The 1-byte parameter indicates the ID of a DP defined on the Tuya Developer Platform.

  • Dp_type: The 1-byte parameter indicates the data type. Select the DP type based on the reported DP.

    • #define DT_RAW 0: raw type.
    • #define DT_BOOL 1: Boolean type.
    • #define DT_VALUE 2: value type. The value range is specified when a DP of value type is created on the Tuya Developer Platform.
    • #define DT_STRING 3: string type.
    • #define DT_ENUM 4: enum type.
    • #define DT_BITMAP 5: bitmap type.
  • Dp_len: The 2-byte parameter indicates the length of a DP. The maximum length of a DP is specified when you define a DP on the Tuya Developer Platform.

    • If Dp_type is 1, Dp_len must be 1.
    • If Dp_type is 2, Dp_len can be 1, 2, or 4.
    • If Dp_type is 4, Dp_len must be 1.
    • If Dp_type is 5, Dp_len can be 1, 2, and 4.
    • If Dp_type is 0 or 3, Dp_len can be customized but must not exceed the maximum length defined on the Tuya Developer Platform.
  • Dp_data: the DP data with the length of dp_len.

    The data that the parameter Dp_data points to must be packaged in the following format for reporting.

    DP 1 data DP n data
    1 2 3 to 4 5 and greater n n+1 n+2 to n+3 n+4 and greater
    Dp_id Dp_type Dp_len Dp_data Dp_id Dp_type Dp_len Dp_data

    You can send the data of multiple DPs at a time. Make sure the total length does not exceed TUYA_BLE_SEND_MAX_DATA_LEN-7. The parameter TUYA_BLE_SEND_MAX_DATA_LEN is configurable.

Other parameters

  • sn: the serial number defined by the application, typically starting with 0. sn is incremented by 1 each time data is sent. sn is used to count the data sending task and manage the response from the mobile app. When scheduled or consecutive calls are made to this function to send DP data, in the callback, the application can use sn to determine which task succeeds. sn can work with tuya_ble_dp_data_with_time_send(). tuya_ble_dp_data_with_time_send() and tuya_ble_dp_data_send() use different event IDs.

  • type: indicates the data sending is a proactive notification or a follow-up response.

    typedef enum {
      DP_SEND_TYPE_ACTIVE = 0,    // The device actively sends dp data.
      DP_SEND_TYPE_PASSIVE,      // The device passively sends DP data. For example, to answer the DP query command of the mobile app. Currently, it only applies to Wi-Fi and Bluetooth combo devices.
    } tuya_ble_dp_data_send_type_t;
    

    Whether a data sending task is DP_SEND_TYPE_ACTIVE or DP_SEND_TYPE_PASSIVE depends on the specific service. When the application responds to queries from the mobile app, DP_SEND_TYPE_PASSIVE is not necessary.

  • mode is defined as follows.

    typedef enum {
      DP_SEND_FOR_CLOUD_PANEL = 0,  // The mobile app uploads the received DP data to the cloud and also sends it to the panel for display.
      DP_SEND_FOR_CLOUD,       // The mobile app will only upload the received DP data to the cloud.
      DP_SEND_FOR_PANEL,       // The mobile app will only send the received DP data to the panel for display.
      DP_SEND_FOR_NONE,        // The DP data is neither uploaded to the cloud nor sent to the panel for display.
    } tuya_ble_dp_data_send_mode_t;
    

    The control panel on the mobile app also implements the service logic of a product. Some DP data is temporary, which is only displayed on the control panel and no sent to the cloud for storage. For example, when a user measures body weight using a smart scale, the generated dynamic data. In this situation, only DP_SEND_FOR_PANEL is required.

  • ack: specifies whether the mobile app sends an ACK message.

    typedef enum {
      DP_SEND_WITH_RESPONSE = 0,   // Need a mobile app to answer.
      DP_SEND_WITHOUT_RESPONSE,   // No need for the mobile app to answer.
    } tuya_ble_dp_data_send_ack_t;
    

    ACK message is used to notify the application that the mobile app receives DP data. Whether to enable an ACK message depends on your service logic.

tuya_ble_dp_data_with_time_send

Function tuya_ble_dp_data_with_time_send
Function prototype tuya_ble_status_t tuya_ble_dp_data_with_time_send
(uint32_t sn,
tuya_ble_dp_data_send_mode_t mode,
tuya_ble_dp_data_send_time_type_t time_type,
uint8_t *p_time_data,
uint8_t *p_dp_data,
uint32_t dp_data_len
);
Description Send DP data with timestamp to the cloud.
Parameters sn[in]: the serial number.
mode[in]: the delivery mode.
time_type[in]: the time type.
p_time_data[in]: the time data.
p_dp_data [in]: the DP data.
dp_data_len[in]: the length of data, no more than TUYA_BLE_SEND_MAX_DATA_LEN-21. TUYA_BLE_SEND_MAX_DATA_LEN is configurable.
Return value TUYA_BLE_SUCCESS: succeeded.
TUYA_BLE_ERR_INVALID_PARAM: invalid parameter.
TUYA_BLE_ERR_INVALID_STATE: failed to send data due to the current Bluetooth connection, such as Bluetooth disconnected.
TUYA_BLE_ERR_NO_MEM: failed to request memory allocation.
TUYA_BLE_ERR_INVALID_LENGTH: data length error.
TUYA_BLE_ERR_NO_EVENT: other errors.
  • sn, mode, p_dp_data, and dp_data_len: see the description of tuya_ble_dp_data_send(). dp_data_len cannot exceed TUYA_BLE_SEND_MAX_DATA_LEN-21. TUYA_BLE_SEND_MAX_DATA_LEN is configurable.

  • This function does not have the parameter ack because sending the DP data with timestamp requires a response from the mobile app.

  • time_type and p_time_data: the time type and the pointer to time data.

    typedef enum {
      DP_TIME_TYPE_MS_STRING = 0,
      DP_TIME_TYPE_UNIX_TIMESTAMP,
    } tuya_ble_dp_data_send_time_type_t;
    
    • DP_TIME_TYPE_MS_STRING: the parameter. p_time_data: the time string in milliseconds. The value must be 13 digits in milliseconds, such as 1600777955000.

    • DP_TIME_TYPE_UNIX_TIMESTAMP: the parameter. p_time_data: the 4-byte Unix timestamp in big-endian format. For example, if 1600777955 is 0x5F69EEE3, the value of p_time_data is a array of{0x5F,0x69,0xEE,0xE3}. Both the DP_TIME_TYPE_MS_STRING and DP_TIME_TYPE_UNIX_TIMESTAMP must respect the UTC time.

tuya_ble_connected_handler

Function tuya_ble_connected_handler
Function prototype void tuya_ble_connected_handler(void);
Description Bluetooth connection callback.
Parameters None
Return value None
Note The application calls this function in the Bluetooth connection callback of your chip platform SDK. Tuya Bluetooth SDK manages the internal Bluetooth connection based on this function.

tuya_ble_disconnected_handler

Function tuya_ble_disconnected_handler
Function prototype void tuya_ble_disconnected_handler(void);
Description Bluetooth disconnection callback.
Parameters None
Return value None
Note The application calls this function in the Bluetooth disconnection callback of your chip platform SDK. Tuya Bluetooth SDK manages the internal Bluetooth connection based on this function.

The nRF52832 platform calls tuya_ble_connected_handler and tuya_ble_disconnected_handler, as shown below.

/**@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_link_encrypted_handler

Function tuya_ble_link_encrypted_handler
Function prototype void tuya_ble_link_encrypted_handler(void);
Description Encryption callback in the Bluetooth link layer.
Parameters None
Return value None
Note The application calls this function in the encryption callback in the Bluetooth link layer of your chip platform SDK. Tuya Bluetooth SDK manages the internal Bluetooth connection based on this function. You can call this function to enable the encryption mechanism in the link layer.

Take the Nordic platform as an example to show the sample code.

/**@brief Function for handling Peer Manager events.
*
* @param[in] p_evt Peer Manager event.
*/
static void pm_evt_handler(pm_evt_t const * p_evt)
{
  pm_handler_on_pm_evt(p_evt);
  pm_handler_flash_clean(p_evt);
  switch (p_evt->evt_id)
 {
case PM_EVT_BONDED_PEER_CONNECTED:
     
  TUYA_APP_LOG_DEBUG("Bonded peer CONNECTED!");
      break;
case PM_EVT_CONN_SEC_SUCCEEDED:
tuya_ble_link_encrypted_handler();
  TUYA_APP_LOG_DEBUG("The link has been encrypted!");
  break;
    case PM_EVT_PEERS_DELETE_SUCCEEDED:
      //advertising_start();
  TUYA_APP_LOG_DEBUG("Erase bonds SUCCEED!");
      break;
    default:
      break;
 }
}

tuya_ble_adv_data_connecting_request_set

Function tuya_ble_adv_data_connecting_request_set
Function prototype tuya_ble_status_t tuya_ble_adv_data_connecting_request_set(uint8_t on_off);
Description Assert the connection request flag.
Parameters on_off[in]: 0 indicates de-asserting and 1 indicates asserting.
Return value None
Note This function is not available currently. To learn more, contact Technical Support.

tuya_ble_data_passthrough

Function tuya_ble_data_passthrough
Function prototype tuya_ble_status_t tuya_ble_data_passthrough(uint8_t *p_data,uint32_t len);
Description Transmit raw data.
Parameters p_data [in]: the data to be sent.
Len[in]: the length of data, no more than TUYA_BLE_SEND_MAX_DATA_LEN.
Return value TUYA_BLE_SUCCESS: succeeded.
TUYA_BLE_ERR_INVALID_STATE: failed to send data due to the current Bluetooth connection, such as Bluetooth disconnected. TUYA_BLE_ERR_INVALID_LENGTH: data length error.
TUYA_BLE_ERR_NO_EVENT: other errors.
Note The application calls this function to transmit the raw data to the mobile app. Tuya Bluetooth SDK does not parse the data.

tuya_ble_production_test_asynchronous_response

Function tuya_ble_production_test_asynchronous_response
Function prototype tuya_ble_status_t tuya_ble_production_test_asynchronous_response
(uint8_t channel,uint8_t *p_data,uint32_t len);
Description Asynchronous response to the instructions for the production test.
Parameters Channel[in]: the communication channel. 0 indicates the UART interface. 1 indicates Bluetooth.
p_data [in]: the full instruction.
len[in]: the length of data.
Return value TUYA_BLE_SUCCESS: succeeded.
TUYA_BLE_ERR_INVALID_STATE: failed to send data due to the current Bluetooth connection, such as Bluetooth disconnected.
TUYA_BLE_ERR_INVALID_LENGTH: data length error.
TUYA_BLE_ERR_NO_MEM: failed to request memory allocation.
TUYA_BLE_ERR_NO_EVENT: other errors.
Note The communication channel is UART for the authorization process and is Bluetooth for the final test. If the results of some test items are not returned to the tool on the host synchronously, or some test items are processed by the application, you can call this function to send the test result to the host.

tuya_ble_net_config_response

Function tuya_ble_net_config_response
Function prototype tuya_ble_status_t tuya_ble_net_config_response(int16_t result_code);
Description Device pairing using Wi-Fi network
Parameters Result_code[in]: the pairing result.
Return value TUYA_BLE_SUCCESS: succeeded.
TUYA_BLE_ERR_INVALID_STATE: failed to send data due to the current Bluetooth connection, such as Bluetooth disconnected.
TUYA_BLE_ERR_NO_EVENT: other errors.
Note This function applies to the Wi-Fi and Bluetooth combo module.

tuya_ble_ubound_response

Function tuya_ble_ubound_response
Function prototype tuya_ble_status_t tuya_ble_ubound_response(uint8_t result_code);
Description Respond to the request for unbinding Wi-Fi and Bluetooth combo devices.
Parameters Result_code[in]: the operation result. 0 indicates success. 1 indicates failure.
Return value TUYA_BLE_SUCCESS: succeeded.
TUYA_BLE_ERR_INVALID_STATE: failed to send data due to the current Bluetooth connection, such as Bluetooth disconnected.
TUYA_BLE_ERR_NO_EVENT: other errors.
Note This function applies to the Wi-Fi and Bluetooth combo module.

tuya_ble_anomaly_ubound_response

Function tuya_ble_anomaly_ubound_response
Function prototype tuya_ble_status_t tuya_ble_anomaly_ubound_response (uint8_t result_code);
Description Respond to the request for unbinding Wi-Fi and Bluetooth combo devices.
Parameters Result_code[in]: the operation result. 0 indicates success. 1 indicates failure.
Return value TUYA_BLE_SUCCESS: succeeded.
TUYA_BLE_ERR_INVALID_STATE: failed to send data due to the current Bluetooth connection, such as Bluetooth disconnected.
TUYA_BLE_ERR_NO_EVENT: other errors.
Note This function applies to the Wi-Fi and Bluetooth combo module.

tuya_ble_device_reset_response

Function tuya_ble_device_reset_response
Function prototype tuya_ble_status_t tuya_ble_device_reset_response (uint8_t result_code);
Description Respond to the request for resetting Wi-Fi and Bluetooth combo devices.
Parameters Result_code[in]: the operation result. 0 indicates success. 1 indicates failure.
Return value TUYA_BLE_SUCCESS: succeeded.
TUYA_BLE_ERR_INVALID_STATE: failed to send data due to the current Bluetooth connection, such as Bluetooth disconnected.
TUYA_BLE_ERR_NO_EVENT: other errors.
Note This function applies to the Wi-Fi and Bluetooth combo module.

tuya_ble_connect_status_get

Function tuya_ble_connect_status_get
Function prototype tuya_ble_connect_status_t tuya_ble_connect_status_get(void);
Description Get the Bluetooth connection status.
Parameters None
Return value The comments in the following code show the return values of tuya_ble_connect_status_t.

The possible Bluetooth connection status is as follows.

typedef enum
{
  UNBONDING_UNCONN = 0, // The device is unbound and not connected.
  UNBONDING_CONN,    // The device is unbound, connected, and authorized.
  BONDING_UNCONN,    // The device is bound and not connected.
  BONDING_CONN,     // The device is bound, connected, and authorized.
  BONDING_UNAUTH_CONN,  // The device is bound, connected, and unauthorized.
  UNBONDING_UNAUTH_CONN, // The device is unbound, connected, and unauthorized.
  UNKNOW_STATUS
}tuya_ble_connect_status_t;

The block diagram shows the connection process.

API

tuya_ble_device_unbind

Function tuya_ble_device_unbind
Function prototype tuya_ble_status_t tuya_ble_device_unbind(void);
Description Unbind a device.
Parameters None.
Return value TUYA_BLE_SUCCESS: succeeded.
TUYA_BLE_ERR_INTERNAL: other errors.
Note For devices with a physical reset button, when the button is pressed, the application should call this function to notify Tuya Bluetooth SDK to clear the associated information.
Note that the virtual device ID will not be removed.

tuya_ble_device_factory_reset

Function tuya_ble_device_factory_reset
Function prototype tuya_ble_status_t tuya_ble_device_factory_reset(void);
Description Reset the device and clear the virtual device ID.
Parameters None.
Return value TUYA_BLE_SUCCESS: succeeded.
TUYA_BLE_ERR_INTERNAL: other errors.
Note For devices with a physical reset button, when the button is pressed, the application should call this function to notify Tuya Bluetooth SDK to clear the associated information.
Note that the virtual device ID will be removed.

tuya_ble_time_req

Function tuya_ble_time_req
Function prototype tuya_ble_status_t tuya_ble_time_req(uint8_t time_type);
Description Request time information.
Parameters time_type[in]:
0: request a 13-byte time string, in milliseconds.
1: request the time on the cloud in the format of year, month, day, hour, minute, second, week.
2: request the time on the mobile phone in the format of year, month, day, hour, minute, second, week.
Return value TUYA_BLE_SUCCESS: succeeded.
TUYA_BLE_ERR_INVALID_PARAM: invalid parameter.
TUYA_BLE_ERR_INTERNAL: other errors.
Note The format of a 13-byte time string: 0000000123456 indicates the timestamp of 123456 ms.
Example: 0x13,0x04,0x1C,0x0C,0x17,0x19,0x02.
Description: 12:23:25 on April 28, 2019, Tuesday.
When Tuya Bluetooth SDK receives the request, it sends a command to the mobile app and then sends the returned time data to the application.

tuya_ble_ota_response

Function tuya_ble_ota_response
Function prototype tuya_ble_status_t tuya_ble_ota_response(tuya_ble_ota_response_t *p_data);
Description Respond to an OTA request.
Parameters p_data[in]: the response data.
Return value TUYA_BLE_SUCCESS: succeeded.
TUYA_BLE_ERR_INVALID_STATE: invalid error.
TUYA_BLE_ERR_INVALID_LENGTH: data length error.
TUYA_BLE_ERR_NO_MEM: failed to request memory allocation.
TUYA_BLE_ERR_INTERNAL: other errors.

tuya_ble_custom_event_send

Function tuya_ble_custom_event_send
Function prototype uint8_t tuya_ble_custom_event_send(tuya_ble_custom_evt_t evt);
Description Send the custom message and callback to Tuya Bluetooth SDK.
Parameters evt[in]: a custom event.
Return value 0: succeeded.
1: failed.
Data structure typedef struct{
void *data;
void (*custom_event_handler)(void*data);
} tuya_ble_custom_evt_t;

You can use this function to allow the application to use the task scheduler of Tuya Bluetooth SDK to process the event of the application.

tuya_ble_custom_event_send sample:

#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 tuya_ble_callback_queue_register
Function prototype Prototype 1: tuya_ble_status_t tuya_ble_callback_queue_register(void *cb_queue);
Prototype 2: tuya_ble_status_t tuya_ble_callback_queue_register(tuya_ble_callback_t cb);
Description With an RTOS, you can use prototype 1 to register a message queue to receive messages from Tuya Bluetooth SDK.
Without an RTOS, you can use prototype 2 to register the callback for messages from Tuya Bluetooth SDK.
Parameters cb_queue [in]: the message queue.
cb[in]: the callback address.
Return value TUYA_BLE_ERR_RESOURCES: failed.
TUYA_BLE_SUCCESS: succeeded.
  • Sample with an RTOS:

    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);
    
  • Sample without an RTOS:

    void tuya_cb_handler(tuya_ble_cb_evt_param_t* event)
    
    tuya_ble_callback_queue_register(tuya_cb_handler);
    

tuya_ble_event_response

Function tuya_ble_event_response
Function prototype tuya_ble_status_t tuya_ble_event_response(tuya_ble_cb_evt_param_t *param);
Description With an RTOS, the application calls this function to respond to events from Tuya Bluetooth SDK.
Parameters param [in]: the pointer to the message.
Return value TUYA_BLE_SUCCESS: succeeded.
Other values: failed.
Note With an RTOS, the application must call this function to return the result to the Tuya Bluetooth SDK.

Sample

/*Process an event from Tuya Bluetooth SDK*/
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 tuya_ble_scheduler_queue_size_get
Function prototype uint16_t tuya_ble_scheduler_queue_size_get(void);
Description Without an RTOS, the application gets the size of a message queue.
Parameters None
Return value The size of a message queue.

tuya_ble_scheduler_queue_space_get

Function tuya_ble_scheduler_queue_space_get
Function prototype uint16_t tuya_ble_scheduler_queue_space_get(void);
Description Without an RTOS, the application gets the free size of a message queue.
Parameters None
Return value The free size of a message queue.

tuya_ble_scheduler_queue_events_get

Function tuya_ble_scheduler_queue_events_get
Function prototype uint16_t tuya_ble_scheduler_queue_events_get(void);
Description Without an RTOS, the application call this function to get the number of unprocessed events from the scheduler of Tuya Bluetooth SDK.
Parameters None
Return value The number of unprocessed events.

tuya_ble_sleep_allowed_check

Function tuya_ble_sleep_allowed_check
Function prototype bool tuya_ble_sleep_allowed_check(void);
Description Sleep permit query to check whether sleep is allowed by the Tuya Bluetooth SDK.
Parameters None
Return value true: allowed.
false: not allowed.
Note The application must call this function to send a sleep permit query to the Tuya Bluetooth SDK before it enters sleep mode. Otherwise, an error might occur.

tuya_ble_feature_scene_request

Function tuya_ble_feature_scene_request
Function prototype tuya_ble_status_t tuya_ble_feature_scene_request(tuya_ble_request_scene_t *req_data)
Description Request scene data or scene control.
Parameters req_data[in]: request data.
Return value TUYA_BLE_SUCCESS: succeeded.
TUYA_BLE_ERR_INVALID_PARAM: invalid parameter.
TUYA_BLE_ERR_NO_MEM: failed to request memory allocation.
TUYA_BLE_ERR_NO_EVENT: other errors.

Data structure

/**@brief	Request scene cmd structure. */
typedef struct
{
	request_scene_cmd scene_cmd;					/**< request scene cmd. */

	union
	{
        request_scene_list_data_t  	scene_data;		/**< request scene list data info. */
        request_scene_control_t 	scene_control;	/**< request scene ctrl info. */
	};
} tuya_ble_request_scene_t;

/**@brief	Request scene type. */
typedef enum
{
	REQUEST_SCENE_DATA = 1,			/**< request scene list data. */
	REQUEST_SCENE_CONTROL,			/**< request scene control. */

	REQUEST_SCENE_CMD_MAX,
} request_scene_cmd;

/**@brief	Request scene list data structure. */
typedef struct
{
	uint8_t nums;					/**< request scene numbers, rang from [1-SUPPORT_REQUEST_SCENE_MAX_NUMS]. */
	uint16_t name_unicode_length;	/**< request scene name length, The encoding format is unicode, It must be a multiple of 2. */
	uint32_t check_code;			/**< scene check code, algorithm-crc32. */
} request_scene_list_data_t;

/**@brief	Request scene control structure. */
typedef struct
{
	uint8_t scene_id_length;				/**< scene id length. */
	uint8_t scene_id[SCENE_ID_MAX_LENGTH]; 	/**< scene id, Max length equal to SCENE_ID_MAX_LENGTH. */
} request_scene_control_t;

The scene request data consists of a struct that includes the request command and the specific data of this command. The request commands can be:

  • REQUEST_SCENE_DATA: requests the list of scenes.
  • REQUEST_SCENE_CONTROL: requests scene control.

Request the list of scenes

For more information about the specific data, see request_scene_list_data_t that includes the number of scenes requested, the length of the scene name (in Unicode), and the CRC-32 checksum of scene data.

  • Unicode encoding: uses 2 bytes for 1 character.

  • CRC-32 checksum: used for differential synchronization. The device sends the last received checksum each time it requests scene data. The request receiver will verify the current data of the requested scene and notify the device whether scene data sync is needed.

  • Scene data stored on the device: including scene ID, the length of scene ID, and checksum.

    Scene ID Length of scene ID Length of scene name (Unicode) Scene name (Unicode)
    xx xx xx xx
    xx xx xx xx

Request scene control

For more information about the specific data, see request_scene_control_t that includes the length of scene ID and scene ID.

Sample

/* Request the list of scenes. The number of scenes: 1. The length of scene name in Unicode: 10. The checksum of the local scene: 0. */
tuya_ble_request_scene_t req_scene_data;

req_scene_data.cmd_type = REQUEST_SCENE_DATA;
req_scene_data.scene_data.nums = 1;
req_scene_data.scene_data.name_unicode_length = 10;
req_scene_data.scene_data.check_code = 0;

tuya_ble_feature_scene_request(&req_scene_data);


/* Request scene control */
tuya_ble_request_scene_t req_scene_data;

static const char test_scene_id[] = "nRAfyPBArgTAPgUq";
req_scene_data.cmd_type = REQUEST_SCENE_CONTROL;
req_scene_data.scene_control.scene_id_length = 16;
memcpy(req_scene_data.scene_control.scene_id, test_scene_id, req_scene_data.scene_control.scene_id_length);

tuya_ble_feature_scene_request(&req_scene_data);