Bluetooth Pairing

Last Updated on : 2024-09-18 03:30:50download

After the robot vacuum receives the pairing information (that is, the SSID and password of the router’s wireless network) from the mobile phone over Bluetooth, it performs the pairing process until the pairing is finished.

TuyaOS SDK comes with the implementation of the business logic of the pairing process. It defines a set of TuyaOS Kernel Layer (TKL) that shields differences in hardware and system. The underlying hardware is controlled by the TKL interfaces that need to be implemented by you. This topic guides you through developing the TKL interfaces.

Procedure

TuyaOS SDKMobile AppRouterCloudInitialize the deviceand send Bluetoothadvertising packetsDiscover Bluetooth advertisingpackets and discover thedeviceConnect to the deviceSend a device query commandto get device informationSend a pairing commandSend a Bluetooth pairingcommandGet the SSID andpasswordConnect to the router's Wi-FiConnect to the cloud and get activatedTuyaOS SDKMobile AppRouterCloud
  1. Initialize the TuyaOS SDK and send Bluetooth advertising packets.
  2. The mobile app proactively connects to unpaired devices.
  3. The mobile app gets the device information.
  4. The mobile app sends a pairing command. If an unpaired device does not respond within 30 seconds, it will be removed as an illegal device, causing Bluetooth disconnection.
  5. The mobile app sends a Bluetooth pairing command. From this command, the device gets the router’s Wi-Fi SSID, password, and token information.
  6. The device connects to the router through SSID and password.
  7. With the token, the device connects to the cloud and gets activated. The entire pairing process is completed.

As can be seen from the above procedure, Bluetooth pairing is very simple and almost the same as access point (AP) pairing, except that the router’s Wi-Fi SSID, password, and token are obtained over the Bluetooth channel.

Development guide

Prerequisites

  • You have a Tuya-enabled app, router, and device ready.
  • The device has enabled Bluetooth LE advertising mode.

How to use

  • tkl_ble_stack_init

    OPERATE_RET tkl_ble_stack_init(UCHAR_T role);
    

    During TuyaOS SDK initialization, you can call this API to initialize the Bluetooth stack. If you do not need such initialization, you should make an empty implementation for this interface.

  • tkl_ble_gap_callback_register

    OPERATE_RET tkl_ble_gap_callback_register(CONST TKL_BLE_GAP_EVT_FUNC_CB gap_evt);
    

    Register Bluetooth Low Energy (LE) Generic Access Profile (GAP) event callbacks. The application should save the pointer to the gap_evt function to the global variable. When the application receives Bluetooth LE GAP data, it passes the data to the TuyaOS SDK for processing through the function pointer.

    During Bluetooth pairing, take care of the TKL_BLE_GAP_EVT_CONNECT event. When the application detects that the mobile phone establishes a Bluetooth connection with the robot vacuum, it passes the GAP data to the TuyaOS SDK through the function pointer.

  • tkl_ble_gatt_callback_register

    OPERATE_RET tkl_ble_gatt_callback_register(CONST TKL_BLE_GATT_EVT_FUNC_CB gatt_evt);
    

    Register Bluetooth LE Generic Attribute Profile (GATT) event callbacks. The application should save the pointer to the gatt_evt function to the global variable. When the application receives Bluetooth LE GATT data, it passes the data to the TuyaOS SDK for processing through the function pointer.

    During Bluetooth pairing, take care of the TKL_BLE_GATT_EVT_WRITE_REQ event. When the application receives a Write Request with the Service UUID 0xFD50, it passes the GATT data to the TuyaOS SDK through the function pointer.

  • tkl_ble_gatts_service_add

    OPERATE_RET tkl_ble_gatts_service_add(TKL_BLE_GATTS_PARAMS_T *p_service);
    

    Bluetooth LE GATT adds services and assigns handle values for three services (WRITE, NOTIFY, and READ). The values can be those returned by the Bluetooth platform, or fixed values specified by you at the adaptation layer. The handle values of the services here must be consistent with the handle values when data is transmitted to TuyaOS SDK. For example, the response to the TKL_BLE_GATT_EVT_WRITE_REQ data.

  • tkl_ble_gap_adv_rsp_data_set

    OPERATE_RET tkl_ble_gap_addr_set(TKL_BLE_GAP_ADDR_T CONST *p_peer_addr);
    

    TuyaOS SDK sets advertising and scan response. The application should cache the advertising and scan response data in this interface. Advertising data is used to broadcast information. Scan response data is sent upon the reception of scanning requests.

  • tkl_ble_gap_adv_start

    OPERATE_RET tkl_ble_gap_adv_start(TKL_BLE_GAP_ADV_PARAMS_T CONST *p_adv_params);
    

    TuyaOS SDK notifies the application of turning on Bluetooth LE advertising. The application should be able to turn on advertising in this interface accordingly, with the advertising and scan response data set by tkl_ble_gap_adv_rsp_data_set.

  • tkl_ble_gap_adv_stop

    OPERATE_RET tkl_ble_gap_adv_stop(VOID);
    

    TuyaOS SDK notifies the application of turning off Bluetooth LE advertising. The application should be able to turn off advertising accordingly.

  • tkl_ble_gatts_value_notify

    OPERATE_RET tkl_ble_gatts_value_notify(USHORT_T conn_handle, USHORT_T char_handle, UCHAR_T *p_data, USHORT_T length);
    

    TuyaOS SDK calls this interface to send Bluetooth LE GATT data to the mobile phone. The application should send GATT data to the mobile phone over Bluetooth.

  • tkl_ble_gattc_exchange_mtu_request

    OPERATE_RET tkl_ble_gattc_exchange_mtu_request(USHORT_T conn_handle, USHORT_T client_rx_mtu);
    

    MTU is the value negotiated between the device and the mobile app. To set an MTU value in the device, you need to implement the tkl_ble_gattc_exchange_mtu_request interface and report the MTU in the device to the TuyaOS SDK. If the tkl_ble_gattc_exchange_mtu_request interface is not implemented, the MTU defaults to 23.

    The above interfaces must be implemented for Bluetooth pairing. For more information about how to implement other TKL interfaces in Bluetooth pairing, see Port TuyaOS to Linux Platforms.

Data format

The following figure shows the data format of Bluetooth broadcast and scan response.

Bluetooth Pairing

Service and characteristic are defined as follows:

Service UUID: 0xFD50.

Characteristic                           UUID                           Description
WRITE_UUID           “00000001-0000-1001-8001-00805f9b07d0”   // Tuya Bluetooth LE Write Characteristic UUID

NOTIFY_UUID          “00000002-0000-1001-8001-00805f9b07d0”   // Tuya Bluetooth LE Notify Characteristic UUID

READ_UUID            “00000003-0000-1001-8001-00805f9b07d0”   // Tuya Bluetooth LE Read Characteristic UUID

Device development

  • Turn on Bluetooth services

    /**
    * @brief Set enable switch for Bluetooth service
    *
    * @param[in] switch: enable switch: TRUE-open, FALSE-close
    *
    * @note This API is used for setting enable switch for Bluetooth service, it should be called before SDK initialization.
    *
    * @return VOID
    */
    VOID_T tuya_ble_set_serv_switch(BOOL_T swith);
    
  • Sample code

    /**
    * @brief The entry point to system startup.
    * @param  [int] mode
    * @param  [char *] token
    * @return [*]
    */
    OPERATE_RET ty_sys_start(WIFI_INIT_MODE_E connect_mode, CHAR_T *p_token)
    {
        OPERATE_RET ret = OPRT_OK;
        PR_DEBUG("sys start ");
        ret = ty_iot_sdk_init(connect_mode, p_token);    //Initialize the SDK.
    if(OPRT_OK != ret){         PR_ERR("tuya iot sdk init failed\n");
            return ret;
        }
        #if defined(TY_BT_MOD) && TY_BT_MOD == 1 //When the capability is turned on, it must be called after the SDK is initialized.
            tuya_ble_set_serv_switch(true); //Bluetooth capability switch.
        #endif
        ret = ty_robot_media_sdk_init(); //Initialize the media SDK.
    if(OPRT_OK != ret){         PR_ERR("ty robot media sdk init failed\n");
            return ret;
        }
        /***You can complete the business interfaces that need to be initialized here***/
        /***You can complete the business interfaces that need to be initialized here***/
        return ret;
    }
    

Things to note

  • The Bluetooth advertising length of TuyaOS SDK is the standard 31 bytes, but the advertising length of certain platforms only supports 28 bytes, resulting in the advertising data not being sent. As a result, the Bluetooth device manufacturer is required to modify the advertising length to 31 bytes.

  • After Bluetooth initialization is successful, the real callback event of the underlying protocol stack of the Bluetooth platform needs to be sent to TuyaOS SDK. Then, TuyaOS SDK can call tkl_ble_gap_adv_rsp_data_set to initiate an advertising update.

  • In order to join the GATT service, the UUID of 0x2902 needs to be added to the Client Characteristic Configuration descriptor. If not added, the NOTIFY service will not work.

    Bluetooth Pairing
  • When the tkl_ble_gatts_service_add interface is registered, the Bluetooth platform assigns the handle values of three services (WRITE, NOTIFY, and READ). The values can be those returned by the Bluetooth platform, or fixed values specified by you at the adaptation layer.

    The registered handle values must be consistent with the handle values actually transmitted to TuyaOS SDK. For example, the response to the TKL_BLE_GATT_EVT_WRITE_REQ data requires transmitting the handle values to TuyaOS SDK. Otherwise, TuyaOS SDK cannot receive Bluetooth data.

  • The following example is that the registered handle value is inconsistent with the one reported to the TuyaOS SDK. Thus, the device fails to respond to the 0x01 command sent by the mobile app, resulting in an unsuccessful pairing after a Bluetooth connection. After a 30s timeout, the device’s Bluetooth connection is considered illegal by the mobile app and is removed.

    Bluetooth Pairing
  • Refer to the ble_test folder in the laser robot vacuum demo to verify the integrity of the TKL interface. It is recommended to use an Android phone to verify it first.

  • Do not block TKL APIs. It is recommended to process time-consuming tasks asynchronously.

  • Bluetooth pairing uses the proprietary Tuya-specific service and data. The SDK parses and packages all the data, so you can directly pass the raw data to the SDK.

  • Currently, some Android phone systems have Bluetooth compatibility issues, which might cause Bluetooth pairing failure. To solve this issue, you can change the MTU value of the Bluetooth underlying layer to 247. For example, in BlueZ, you can change the BT_ATT_MAX_LE_MTU macro value.