Sweeper SDK Development

Last Updated on : 2023-10-11 03:13:01download

Applicability

  • Devices run Linux or Android.
  • Devices support the TCP/IP stack.

Terms

Term Description
Pairing Pairing enables a device to connect to the cloud, hence allowing the device, mobile app, and cloud to communicate with each other.
PID A product ID (PID), uniquely identifying a product, is associated with all the data points defined for a product. IPC devices built on the same product share the same PID.
UUID A universally unique identifier (UUID) is a unique number generated by various algorithms to identify hardware or software.
AuthKey AuthKey is used to authorize devices registered on the Tuya IoT Development Platform to access cloud services.
P2P ID P2P ID stands for point-to-point ID. For SDK v3.0.0 and later, the P2P ID is automatically assigned by the cloud without manual assignment.
Token When users scan the QR code to pair a device, the cloud server generates a token. This token is an identification code that remains valid for 10 minutes.
DP A data point (DP) represents a feature defined for a product. The DP serves the communication between a device and the cloud.
OTA updates OTA stands for over-the-air and refers to any type of wireless transmission. It is most commonly used to describe the wireless delivery of new software, firmware, or other data to IoT devices.

Feature description

The sweeper SDK includes APIs that enable communication between Linux-based Wi-Fi devices, Tuya-based mobile apps, and the cloud. Its features include:

  • Uplink and downlink messaging: command sending and status and map data reporting with Tuya-defined protocol.
  • Data filter: data check, rule-based data reporting, and reporting frequency setting.
  • Standard services: device pairing, firmware update, local schedule, and LAN control.
  • Data security: protection for your data in transit.

Get started

Follow these steps to try the Tuya sweeper SDK.

  1. Get the Tuya sweeper SDK.
  2. Get the Tuya sweeper demo.
  3. Download and install the Smart Life app from app stores.
  4. Adapt the code in a Linux environment.
  5. Run the demo and try features with the Smart Life app.

Get the SDK

Contact the project manager for the SDK’s GitHub link.

Run the demo

  1. Download the demo from GitHub.

  2. Unzip the SDK.

    Copy the SDK folder that includes include and lib folders to the ubuntu_demo/sdk folder.

    Copy the demo_resource in the demo folder to the ubuntu_demo/components/demo_tuya_ipc/resource folder.

    Build the code

    ./build.sh ubuntu_sweeper
    

    The output is placed in cmake-build/out/demo_ipc.

  3. Open the Smart Life app and tap the + icon in the top right corner to add a device.

  4. Tap Small Home Appliances > Robot Vacuum (IPC).

  5. Select QR Code in the top right corner of the screen, select Confirm the indicator is blinking, and tap Next.

  6. Select Wi-Fi network and enter the password.

    Make sure to use the 2.4 GHz Wi-Fi network to connect to devices.

  7. Create and scan the QR code.

    Take a screenshot of the QR code, and scan the QR code with a QR code reader.

  8. Extract the token from the obtained data.

    Data obtained: {"p":"test","s":"test","t":"AYYBJt2OGvY2w1"}

    The value after t is the token that is valid for 10 minutes. After the token expired, you need to repeat the process and get a new token.

  9. Run the executable in the build directory.

    # Enter the following command.
    #./cmake-build/out/demo_ipc -m 2 -r "." -t "TOKEN"
    #Note: -m is used to select a pairing mode, with three valid values from 0 to 2. 0: Wi-Fi Easy Connect (EZ mode). 1: access point (AP) mode. 2: debugging mode. -r is the map file path. Here, the single dot (.) represents the current directory. Token is obtained from QR code scanning.
    
  10. When the executable is running, select I Heard a Prompt on the mobile app. Note that there will be no audible prompt from the actual device.

  11. Wait for the process to be completed.

Tap the added device to get it online. If the device is offline, check if you run the executable with the correct parameter values.

The following table lists the command to simulate a robot vacuum. You can run it to test different features.

Command Description
p2p_map Simulate the robot vacuum

When the virtual robot vacuum operates, you can run the following commands.

#p2p_map
please input support file type
#63
please input sleep time
#20
please input file pathname(Input the file path in the sequence shown above (map.bin cleanPath.bin, navPath.bin))
#./components/demo_tuya_ipc/resource/ipc_sweeper_robot/map.bin1
#./components/demo_tuya_ipc/resource/ipc_sweeper_robot/cleanPath.bin1
#./components/demo_tuya_ipc/resource/ipc_sweeper_robot/navPath.bin1

Description of the supported file types and the sleep time.

Supported file types:
map.bin: full map transfer
cleanPath.bin: cleaning route transfer
navPath.bin: navigation route transfer
map.bin.stream: full map streaming
cleanPath.bin.stream: cleaning route streaming
navPath.bin.stream: navigation route streaming
// Input an integer value, with bits 1 to 6 to indicate support for the above six file types. For example, bit 1 for map.bin and bit 6 for navPath.bin.stream. 0 = Supported. 1 = Not supported.
// If all file types are supported, the integer in binary is 11 1111 (63). If only map.bin is supported, the integer in binary is 00 0001 (1), and so on.


The sleep time represents the streaming interval. This parameter is invalid when only ordinary transfer is used.

After running the above commands, the map should appear on the Smart Life app. If it does not, verify that you have set the correct directory for the map file.

This is how the demo works. You can build applications on top of the demo as instructed in the following sections.

Set the parameter values

  • In the demo_src/user_main.c file, change the save path of DB files, OTA files, and local recording files.

    The DB file contains the device pairing information. It must be saved in the non-volatile memory.

    Make sure to check whether or not there is a slash (/) at the end of the path to save the DB file and local media file.

    #define IPC_APP_STORAGE_PATH "/tmp/"
    #define IPC_APP_UPGRADE_FILE "/tmp/upgrade.file"
    #define IPC_APP_SD_BASE_PATH "/tmp/"
    
  • Consult your product manager if you are unsure about setting the PID, UUID, and AuthKey.

      #CHAR_T s_ipc_pid[64]="tuya_pid";			//pid
      #CHAR_T s_ipc_uuid[64]="tuya_uuid";			//uuid
      #CHAR_T s_ipc_authkey[64]="tuya_authkey";	//authkey
      # Replace the PID, UUID, and AuthKey with your own values and write them to the flash memory.
    
  • Change the macro of the firmware version number.

    The version number must be set in the format xx.xx.xx, no more than 20 characters.

    #define IPC_APP_VERSION "1.2.3"
    

The basic parameter setting is completed. Next, you can proceed with developing pairing modes.

Device pairing

The SDK provides a complete set of functions for implementing device pairing. This section describes the pairing processes and the purpose of each function. You can follow the instructions to implement the required features.

Wi-Fi EZ mode

Development process

  • Find the parameter mode in the main function. Select WIFI_INIT_AUTO mode and set the token as NULL.

    CHAR_T token[30] = {0};  // A token is an identification code generated by the cloud when users scan the QR code to pair a device. It is valid for 10 minutes.
    WIFI_INIT_MODE_E mode = WIFI_INIT_AUTO; // Specify a pairing mode.
    
  • TUYA_IPC_SDK_START passes in the configured pairing mode to initiate pairing. You can call this function when you want to put the device into pairing mode.

    TUYA_IPC_SDK_START(mode,token);
    
  • Process of Wi-Fi EZ pairing:

    // Scan all the channels and transmit the captured data to the struct AP_IF_S**ap.
    OPERATE_RET tuya_adapter_wifi_assign_ap_scan(IN CONST CHAR_T *ssid,OUT AP_IF_S **ap)
    // Start the thread func_Sniffer.
    // The setsockopt function sets the network interface.
    // The recvfrom function receives the captured packet collected in promiscuous mode.
    // Skip the radiotap header to get the actual 802.11 frame. Invoke s_pSnifferCall to send the frame to the SDK.
    // Turn off the sniffer after the SSID, UUID, and token are received.
    // Connect to the router to create a P2P connection over MQTT.
    
  • The interfaces below need to be implemented by you. For the reference implementation, see the demo.

    // The interface to get the Wi-Fi mode, defaulting to sniffer mode.
    OPERATE_RET tuya_adapter_wifi_get_work_mode(OUT WF_WK_MD_E *mode)
    // Scan all the channels and transmit the captured data to the struct AP_IF_S**ap.
    OPERATE_RET tuya_adapter_wifi_assign_ap_scan(IN CONST CHAR_T *ssid,OUT AP_IF_S **ap)
    // Set the Wi-Fi mode. When the SDK determines that the input packet data is correct, it sets the Wi-Fi as station mode.
    OPERATE_RET tuya_adapter_wifi_set_work_mode(IN CONST WF_WK_MD_E mode)
    // Register the sniffer callback.
    int tuya_adapter_wifi_sniffer_set(const bool en, const SNIFFER_CALLBACK cb)
    // Perform network connection according to the parsed data.
    OPERATE_RET tuya_adapter_wifi_station_connect(IN CONST CHAR_T *ssid,IN CONST CHAR_T *passwd)
    // Notify the SDK of the obtained IP address on a successful pairing. This is a frequently called interface.
    OPERATE_RET tuya_adapter_wifi_station_get_status(OUT WF_STATION_STAT_E *stat)
    
  • Pass in the received packet for Wi-Fi signal strength display.

    OPERATE_RET tuya_adapter_wifi_station_get_conn_ap_rssi(OUT SCHAR_T *rssi)
    

    If you want to change the interface, consult technical support before any modification is made to avoid any unknown errors.

Direct connection (QR code scanning)

  • Make sure you have downloaded the direct connection supported IPC SDK, and the UUID has been tagged in the Tuya’s system.
  • Make sure the device has been connected to the internet when the SDK runs.
  • Call TUYA_IPC_SDK_START to initialize the SDK. Set WIFI_INIT_MODE_E as WIFI_INIT_NULL and token as NULL.
  • Tap the scan icon in the top right corner of the mobile app to scan the QR code for device activation.
  • Devices with tagged UUIDs can receive a short URL from the cloud. You can use an open source library to convert this short URL into a QR code.

If you want to change the interface, consult technical support before any modification is made to avoid any unknown errors.

DP services

Device DPs

Tuya provides a network application protocol over MQTT. MQTT is a lightweight publish/subscribe messaging protocol that is ideal for connecting IoT devices with a small code footprint and minimal network bandwidth.

The sweeper SDK has an MQTT implementation. Each product feature is represented by a DP, which supports six data types: value, Boolean, enum, string, fault, and raw.

Before implementing the DP service, you need to create a product and define DPs on the Tuya IoT Development Platform.

Feature

  1. A product can have up to 35 DPs defined. You can use the raw data type to implement complex features. There are three categories of DP data types.
  2. Object type: includes Boolean, value, string, and enum.
  3. Bitmap: The SDK filters out duplicate data in consecutive reporting requests.
  4. Raw: The SDK does not filter the consecutively-reported data. Set the data reporting frequency to a minimum of one second.

API description

The function prototype for sending object-type DP data.

/**
 * @brief dev_report_dp_json_async 
 * @desc report dp info a-synced.
 *
 * @param[in] dev_id: if sub-device, then devid = sub-device_id
 *                if gateway/soc/mcu, then devid = NULL
 * @param[in] dp_data: dp array header
 * @param[in] cnt: dp array count
 *
 * @return OPRT_OK: success  Other: fail
 */
OPERATE_RET dev_report_dp_json_async(IN CONST CHAR_T *dev_id,IN CONST TY_OBJ_DP_S *dp_data,IN CONST UINT_T cnt);

The function prototype for sending raw DP data.

/**
 * @brief dev_report_dp_raw_sync_extend 
 * @desc report dp raw info synced.
 *
 * @param[in] dev_id: if sub-device, then devid = sub-device_id
 *                if gateway/soc/mcu, then devid = NULL
 * @param[in] dpid: raw dp id
 * @param[in] data: raw data
 * @param[in] len: len of raw data
 * @param[in] timeout: function blocks until timeout seconds
 *
 * @return OPRT_OK: success  Other: fail
 */
 dev_report_dp_raw_sync(dev_id, dpid, data, len, timeout)

Robot vacuum services

The robot vacuum can transfer files, such as maps and routes, in three different modes: streaming, P2P, and OSS.

  • Streaming: file transfer over MQTT, with low data footprint and bandwidth. Streaming applies to inertial navigation robot vacuums.
  • P2P: file transfer over P2P, such as real-time maps, navigation routes, and cleaning routes.
  • OSS: uses third-party OSS services to store maps, with high overhead due to the consumption of server resources. OSS is primarily used for multimap cases.

Streaming mode

Small chunks of data are incrementally transmitted over MQTT to the cloud and delivered to the mobile app. Notifications are sent to indicate the start and end of transmission. Quality of Service (QoS) 1 (at least once) ensures reliable message delivery.

API description

tuya_iot_media_data_report is used for synchronous data reporting.

/***********************************************************
* Function: tuya_iot_media_data_report
* Input: dt_body->media data
        timeout->need report time
* Output: none
* Return: OPERATE_RET
***********************************************************/
OPERATE_RET tuya_iot_media_data_report(IN CONST FLOW_BODY_ST *dt_body,IN CONST UINT_T timeout);

Reference code

OPERATE_RET op_ret;
    unsigned char data_buf[] = {"iot.tuya.com"}; // example
    FLOW_BODY_ST*flow_data=(FLOW_BODY_ST*)malloc(sizeof(FLOW_BODY_ST)+sizeof(data_buf));
    if(flow_data == NULL){
        PR_ERR("malloc flow_data");
        return OPRT_MALLOC_FAILED;
    }
    memset(flow_data, 0, sizeof(FLOW_BODY_ST)+sizeof(data_buf));

    flow_data->id = map_id;
    flow_data->posix = uni_time_get_posix();
    flow_data->step = TS_TRANSFER;
    flow_data->offset = 0;
    flow_data->len = sizeof(data_buf);
    memcpy((unsigned char *)flow_data->data, data_buf, flow_data->len);
    op_ret = tuya_iot_media_data_report(flow_data, 5);
    if (op_ret != OPRT_OK){
        PR_ERR("tuya_iot_media_data_report->TS_TRANSFER is error %d\n", op_ret);
    }
    free(flow_data);
    return op_ret;

tuya_iot_media_data_report_v2

/***********************************************************
* Function: tuya_iot_media_data_report_v2
* Input: dt_body->media data
        timeout->need report time
* Output: none
* Return: OPERATE_RET
***********************************************************/
OPERATE_RET tuya_iot_media_data_report_v2(IN CONST FLOW_BODY_V2_ST *dt_body,IN CONST UINT_T timeout);

P2P mode

P2P mode supports three actions on files.

  • Query the map.
  • Download the map.
  • Cancel map download.

P2P mode supports three types of map files.

  • Full map
  • Navigation route
  • Cleaning route

Two transfer modes are available for the three file types.

  • File transfer
  • Streaming transfer

File transfer: A session is created solely for file transfer. Once the transfer is finished, the sender notifies the receiver with a message signaling its completion.

Streaming transfer: A session is created solely for streaming transfer and will remain open until the download is canceled. The other party will receive a notification before the session is terminated.

P2P mode supports six types of maps.

  • map.bin: full map transfer

  • cleanPath.bin: cleaning route transfer

  • navPath.bin: navigation route transfer

  • map.bin.stream: full map streaming

  • cleanPath.bin.stream: cleaning route streaming

  • navPath.bin.stream: navigation route streaming

If the mobile app requests a full map transfer, name the file to be downloaded as map.bin. For full map streaming requests, name the file map.bin.stream. The rule also applies to the cleaning route and navigation route.

Query the map

Sweeper SDK Development

Download the map

Sweeper SDK Development

Cancel map download

Sweeper SDK Development

API description

SWEEPER_ALBUM_FILE_TYPE_E struct
The struct lists the supported map types.

  • map.bin: full map transfer

  • cleanPath.bin: cleaning route transfer

  • navPath.bin: navigation route transfer

  • map.bin.stream: full map streaming

  • cleanPath.bin.stream: cleaning route streaming

  • navPath.bin.stream: navigation route streaming

typedef enum {
    SWEEPER_ALBUM_FILE_TYPE_MIN = 0,
    SWEEPER_ALBUM_FILE_MAP = SWEEPER_ALBUM_FILE_TYPE_MIN,//map file
    SWEEPER_ALBUM_FILE_CLEAN_PATH = 1,
    SWEEPER_ALBUM_FILE_NAVPATH = 2,
    SWEEPER_ALBUM_FILE_TYPE_MAX = SWEEPER_ALBUM_FILE_NAVPATH,

    SWEEPER_ALBUM_STREAM_TYPE_MIN = 3,
    SWEEPER_ALBUM_STREAM_MAP = SWEEPER_ALBUM_STREAM_TYPE_MIN, // map stream , devcie should send map file to app continue
    SWEEPER_ALBUM_STREAM_CLEAN_PATH = 4,
    SWEEPER_ALBUM_STREAM_NAVPATH = 5,
    SWEEPER_ALBUM_STREAM_TYPE_MAX = SWEEPER_ALBUM_STREAM_NAVPATH,

    SWEEPER_ALBUM_FILE_ALL_TYPE_MAX = SWEEPER_ALBUM_STREAM_TYPE_MAX, // a maximum value of 5
    SWEEPER_ALBUM_FILE_ALL_TYPE_COUNT, // 6
} SWEEPER_ALBUM_FILE_TYPE_E;

tuya_ipc_sweeper_convert_file_info

/**
 * \fn tuya_ipc_sweeper_convert_file_info
 * \brief transfer file info into buff pointered by pIndexFile by tuya SDK
 * \param[in] fileArray: arr[0] means SWEEPER_ALBUM_FILE_TYPE_MIN, refer to SWEEPER_ALBUM_FILE_TYPE_E
 * \param[inout] pIndexFileInfo: file infomation
 * \param[inout] fileInfoLen: file infomation len
 * \return ret
 */
INT_T tuya_ipc_sweeper_convert_file_info(IN INT_T* fileArray, OUT VOID** pIndexFileInfo, OUT INT_T* fileInfoLen);

This interface converts the supported map types into a fixed format. P2P-enabled robot vacuums can support six map types.

If your product supports all the map types, set the first parameter as shown below.

int g_file_arr[SWEEPER_ALBUM_FILE_ALL_TYPE_COUNT] = { 1, 1, 1, 1, 1, 1 };
tuya_ipc_sweeper_convert_file_info(g_file_arr, &(pSrcType->pIndexFile), &(pSrcType->fileLen));

If your product only supports full map transfer and full map streaming, set the first parameter as shown below.

int g_file_arr[SWEEPER_ALBUM_FILE_ALL_TYPE_COUNT] = { 1, 0, 0, 1, 0, 0 };
tuya_ipc_sweeper_convert_file_info(g_file_arr, &(pSrcType->pIndexFile), &(pSrcType->fileLen));

Implement the interface according to your needs, ensuring that you return the result in the required format.

tuya_ipc_sweeper_parse_file_info

/**
 * \fn tuya_ipc_sweeper_parse_file_info
 * \brief parse download file info into file Array
 * \param[in] srcfileInfo: download info
 * \param[inout] fileArray: array of file infomation
 * \param[in] arrSize: array size 
 * \return ret
 */
INT_T tuya_ipc_sweeper_parse_file_info(IN C2C_CMD_IO_CTRL_ALBUM_DOWNLOAD_START* srcfileInfo, INOUT INT_T* fileArray, IN INT_T arrSize);

This interface is used to parse the type of map file requested by the mobile app. The return value is an array that indicates which map type is to be downloaded.

  • map.bin: full map transfer

  • cleanPath.bin: cleaning route transfer

  • navPath.bin: navigation route transfer

  • map.bin.stream: full map streaming

  • cleanPath.bin.stream: cleaning route streaming

  • navPath.bin.stream: navigation route streaming

The array is sorted in the order shown above, where 1 indicates download and 0 indicates not download. This interface is optional. You can parse the type of map file in your own way.

tuya_ipc_sweeper_send_data_with_buff

/**
 * \fn simple_album_send_data_with_buff
 * \brief send file to app by p2p
 * \param[in] client: handle
 * \param[in] type: file type, refer SWEEPER_ALBUM_FILE_TYPE_E
 * \param[in] fileLen: file len
 * \param[in] fileBuff: file buff
 * \return ret
 */
INT_T tuya_ipc_sweeper_send_data_with_buff(IN INT_T client, SWEEPER_ALBUM_FILE_TYPE_E type , IN INT_T fileLen, IN CHAR_T* fileBuff);

This interface sends the map data to the mobile app via the P2P channel.

The first parameter is the P2P channel struct, which can be obtained from the callback when downloading the map.

The second parameter is the map type. For more information, see the enum of SWEEPER_ALBUM_FILE_TYPE_E.

The third parameter is the length of the map data.

The fourth parameter is the map data.

For ordinary map transfer, call tuya_ipc_sweeper_send_finish_2_app when the transfer is completed. This operation is unnecessary for map streaming because the stream will continue until the user ends it.

tuya_ipc_sweeper_send_finish_2_app

/**
 * \fn simple_album_send_finish_2_app
 * \brief tell app sending is finished
 * \param[in] client: session client
 * \return ret
 */
INT_T tuya_ipc_sweeper_send_finish_2_app(IN INT_T client);

This interface notifies the mobile app of file transfer completion, with the same parameters as tuya_ipc_sweeper_send_data_with_buff.

Map event callback

The following four events need to be implemented to send and receive data via P2P.

  • Query the map.

  • Start downloading the map.

  • Stop downloading the map.

  • Delete the map.

typedef enum
{
  ……
    TRANS_ALBUM_QUERY = 203,  			  // Query the map.
    TRANS_ALBUM_DOWNLOAD_START = 204,  	// Start downloading the map.
    TRANS_ALBUM_DOWNLOAD_CANCEL = 205,  	// Stop downloading the map.
    TRANS_ALBUM_DELETE = 206,  			  // Delete the map.
}TRANSFER_EVENT_E;

OSS mode

This mode is used for laser navigation robot vacuums to report large volumes of full map data.

Cloud storage

Sweeper SDK Development

tuya_iot_map_record_upload_buffer

/***********************************************************
*  Function: tuya_iot_map_record_upload_buffer
*  Desc:  sweeper function. upload record map info
*  Input: map_id
*  Input: buffer
*  Input: len
*  Input: cloud_file_name
*  Input: extend
*  Return: OPERATE_RET
***********************************************************/
#define tuya_iot_map_record_upload_buffer(map_id,buffer,len,cloud_file_name,extend)\
    upload_map_custom_buffer(map_id,buffer,len,cloud_file_name,0,FALSE,extend,TRUE)

OPERATE_RET upload_map_custom_buffer(IN CONST INT_T map_id, IN CONST BYTE_T *buf,IN CONST UINT_T len, \
                                     IN CONST CHAR_T *cloud_file_name, \
                                     IN CONST INT_T map_type, IN CONST BOOL_T send_mqtt, \
                                     IN CONST CHAR_T *extend_msg, IN CONST BOOL_T http_update);

This interface is used to upload the cleaning history to the OSS server.

Multimap

Multimap management

Sweeper SDK Development

tuya_iot_map_upload_files

    /***********************************************************
    *  Function: tuya_iot_map_upload_file
    *  Desc:  sweeper function. upload cleaner map info
    *  Input: bitmap_file
    *  Input: datamap_file
    *  Input: descript
    *  Output: cloud_map_id
    *  Return: OPERATE_RET
    ***********************************************************/
    OPERATE_RET tuya_iot_map_upload_files(IN CONST CHAR_T *bitmap_file, 
                                          IN CONST CHAR_T *datamap_file, 
                                          IN CONST CHAR_T *descript, 
                                          OUT CONST UINT_T *map_id);

Function: Upload maps

Parameter description

Parameter name Description
bitmap_file Upload the map file used for display on the mobile app. The file name must not exceed 16 bytes.
datamap_file Upload the map file for relocation. The format is user-defined, but the file name must not exceed 16 bytes.
descript The description information. Refer to the format in the mm_bin_mapid_nowtime.txt file.
map_id The returned map ID after the data is reported.

Return value

Return value Description
OPRT_OK Operation succeeded.
Error code The error code on a failed operation.

tuya_iot_map_update_files

    OPERATE_RET tuya_iot_map_update_files(IN CONST UINT_T map_id, 
                                          IN CONST CHAR_T *bitmap_file, 
                                          IN CONST CHAR_T *data_map_file);

Function: Update the map data by map ID

Parameter

Parameter name Description
map_id cloud_map_id
bitmap_file Update the full map file used for display on the mobile app.
datamap_file Update the full map file for relocation.

Return value

Return value Description
OPRT_OK Operation succeeded.
Error code The error code on a failed operation.

tuya_iot_map_delete

OPERATE_RET tuya_iot_map_delete(IN CONST UINT_T map_id);

Function: Delete map files from cloud

Parameter

Parameter name Description
map_id The map ID assigned by the cloud server.

Return value

Return value Description
OPRT_OK Operation succeeded.
Error code The error code on a failed operation.

tuya_iot_get_map_files

PERATE_RET tuya_iot_get_map_files(IN CONST UINT_T map_id, IN CONST CHAR_T *map_path)

Function: Download the map file by map ID and store it in the specified directory.

Parameter

Parameter name Description
map_id The map ID.
map_path The path where the downloaded map file resides.

Return value

Return value Description
OPRT_OK Operation succeeded.
Error code The error code on a failed operation.

OTA update

This section describes how to implement the OTA update, a popular method to update the firmware. When the SDK detects firmware updates, it will notify the device of OTA updates through a callback.

Business logic

The OTA firmware update process involves three components: the mobile app, device, and cloud.

  • Mobile app: prompts the user with a firmware update notification and displays the update progress.
  • Cloud: stores the firmware update, updates the progress, and pushes the update notification.
  • Device: receives and installs the firmware update.

Firmware package configuration

  • After a gateway or sub-device is paired, you can get its virtual ID from the mobile app to add it to the firmware update allowlist.

  • Build the firmware package, with a version number higher than the currently installed one.

  • Log in to the Tuya IoT Development Platform. Find the target product and upload the firmware package.

  • Choose SDK firmware as the firmware type to update the Wi-Fi module.

  • Choose MCU firmware as the firmware type to update the MCU on the Wi-Fi device.

Update methods

Tuya provides four methods to initiate a firmware update on the user side.

  • Update notification: When users open the app panel, they receive a firmware update notification. They can then choose whether to install the update.
  • Automatic update (silent update): The device automatically checks for updates once after a restart and installs them if available. During the update installation, users will see a progress bar in the app panel and cannot operate the device.
  • Forced update: When users open the app panel, they receive a firmware update notification. They have no option but to update the firmware.
  • Check for updates: Users will not receive a firmware update notification, but need to open the app panel of a device and check for updates manually.

Development processes

  • The OTA callback IPC_APP_Upgrade_Inform_cb() passes in the update download URL and the size of the update file.

  • To release memory, call tuya_ipc_ss_set_write_mode() to disable local recording. And then, call tuya_ipc_ss_uninit() and tuya_ipc_tranfser_close(). The uninit and close functions are used for deinitialization of the local storage and P2P feature to release memory as much as possible.

    Release memory before tuya_ipc_upgrade_sdk is called.

    VOID IPC_APP_Upgrade_Inform_cb(IN CONST FW_UG_S *fw)
    {
      PR_DEBUG("Rev Upgrade Info");
      PR_DEBUG("fw->fw_url:%s", fw->fw_url);
      PR_DEBUG("fw->sw_ver:%s", fw->sw_ver);
      PR_DEBUG("fw->file_size:%u", fw->file_size);
    
      FILE *p_upgrade_fd = fopen(s_mgr_info.upgrade_file_path, "w+b");
      // optimize the memory resources
      tuya_ipc_upgrade_sdk(fw, __IPC_APP_get_file_data_cb, __IPC_APP_upgrade_notify_cb, p_upgrade_fd);
    }
    

    The first callback __IPC_APP_get_file_data_cb in tuya_ipc_upgrade_sdk is used to get the sharding data. This function has input and output parameters. The input parameters can be used for your purpose. After you get the output parameters, you need to return whether the data has been written. Return 0 on successful writing.

    The second callback __IPC_APP_upgrade_notify_cb is used to display the update progress.

  • Replace the old firmware with the new one in __IPC_APP_upgrade_notify_cb. For more information about the reference implementation, see tuya_ipc_sdk_upgrade_demo.c.

    After the firmware is downloaded, you need to implement firmware replacement and restart the device in the specified function.

    Before replacement, back up the DB file. After replacement, compare the MD5 hash of the DB file before and after replacement. If the MD5 hash is identical, restart the device. Otherwise, replace the current DB file with the backup DB file and restart the device.

  VOID __IPC_APP_upgrade_notify_cb(IN CONST FW_UG_S *fw, IN CONST INT_T download_result, IN PVOID_T pri_data)
  • If the OTA update fails, add the restart operation in __IPC_APP_upgrade_notify_cb.

    Deinitialization is not reversible. If the OTA update fails, the device must be restarted.

Custom OTA update progress

  • The device downloads the updates through a URL and calls tuya_ipc_upgrade_progress_report to report download progress.

    The progress value reported is recommended to be less than 99%.

    /*
    \fn OPERATE_RET tuya_ipc_upgrade_progress_report
    \brief  Sends the update progress to the cloud and the mobile app.
    \param[in] percent: the update progress in percentage, with valid values from 0 to 100.
    \return SUCCESS – OPERATE_RET , FAIL – COMM ERROR
    */
    OPERATE_RET tuya_ipc_upgrade_progress_report(IN UINT_T percent);
    
  • When the firmware is updated, the progress displayed on the app will pause at 98%. At this time, the firmware has been downloaded, and the app is waiting for the device to be restarted and send the new firmware version number. After receiving the new version number, the app will display a successful update.

  • Generally, the app waits one minute for the device to replace the firmware and report the new version number. If the waiting time of your device exceeds one minute, you can contact the project manager to configure the PID in the backend.

Remove and reset devices

This section describes how to remove devices from the app and reset devices by button press.

Remove devices

  • When users tap Remove Device on the mobile app, the SDK will clear the pairing information in the DB file and execute the callback IPC_APP_Reset_System_CB to restart the device.

    In this function, you need to implement device restart and DP file reset. Do not delete the DB file.

    VOID IPC_APP_Reset_System_CB(GW_RESET_TYPE_E type)
    {
      printf("reset ipc success. please restart the ipc %d\n", type);
      IPC_APP_Notify_LED_Sound_Status_CB(IPC_RESET_SUCCESS);
      //TODO
      /* Developers need to restart IPC operations */
    }
    

Reset devices

  • When the device detects that the reset button is pressed, three DB files tuya_user.db_bak, tuya_user.db, and tuya_enckey.db will be deleted.
  • The DP data files are reset, and the device is restarted.