API Description

Last Updated on : 2022-11-24 09:20:13download

This topic describes how to use the SDK APIs for NB-IoT modules. APIs are classified based on their functionalities.

Terms

Term Description
Product ID (PID) The PID is a unique identifier that is automatically assigned to each product created on the Tuya IoT Development Platform.
Data point (DP) The DP is an abstract representation of a feature defined for a product.
International mobile equipment identity (IMEI) IMEI is a unique number used to identify NB-IoT devices.
International mobile subscriber identity (IMSI) IMSI is a number that uniquely identifies every user of a cellular network. It is usually presented as a 15-digit number (0 to 9) but can be shorter.
Integrated circuit card identifier (ICCID) ICCID is a unique number assigned to a SIM card and used to identify SIM cards internationally. ICCID is the unique identifier of an IC card, composed of 20 characters.
Schema file A JSON file that contains the DP information of a device. A device will download the schema file after it is powered on for the first time or its PID is changed.
Record type data and non-record type data Record type data helps to ensure reliable data delivery. When the NB-IoT module fails to report record type data to the cloud due to network jitter, it will cache the data and report it when the network works fine. However, if the non-record type data fails to be reported, it will be lost.
Production testing In the testing process, you flash the firmware and license to the module.
Bind Bind an NB-IoT device with the mobile app. Before the binding operation, the device must have been initialized.

Logging APIs

This section describes the APIs used to configure the logger.

Turn on or off logging

Function prototype void tuya_user_elog_switch (IN bool on)
Parameter
  • true: Turn on logging.
  • false: Turn off logging.
Feature Turn on or off logging. The change takes effect after the system restart. Turning on logging will increase power consumption.
Header file #include <tuya_user_api.h>
Return value None

Set the logging level

Function prototype void tuya_user_api_set_sdk_dbg_filter_level (unsigned char filter_level)
Parameter filter_level: The specified logging level for the SDK. For more information, see filter_level.
Feature Set the logging level to classify the entries in the SDK log file in terms of severity.
Header file #include <tuya_user_api.h>
Return value None

The macro definition for filter_level.

The following logging levels are available, from the lowest to the highest. The higher levels always include the messages from the lower levels. For example, if you select ELOG_LVL_INFO, info, warn, error, and assert messages are included.

  • ELOG_LVL_ASSERT: the value of 0. Log events at the assert level.
  • ELOG_LVL_ERROR: the value of 1. Call USER_API_LOGE to log events at the error or lower levels.
  • ELOG_LVL_WARN: the value of 2. Call USER_API_LOGW to log events at the warn or lower levels.
  • ELOG_LVL_INFO: the value of 3. Call USER_API_LOGI to log events at the info or lower levels.
  • ELOG_LVL_DEBUG: the value of 4. Call USER_API_LOGD to log events at the debug or lower levels.
  • ELOG_LVL_VERBOSE: the value of 5. Call USER_API_LOGV to log events at the verbose or lower levels.

Output logs in hex format

Function prototype #define USER_API_HEX_DUMP(name, width, buf, size) elog_hexdump(name, width, buf, size)
Parameter
  • name: The object identifier of the data to be printed, displayed on the header.
  • width: The number of hex characters in a line. For example, 16 or 32.
  • buf: The pointer to the buffer where data to be printed is stored.
  • size: The size of the data to be printed.
Feature Output logs in hex format.
Header file #include <tuya_user_api.h>
Return value None

key-value data store

Write, read or delete key-value data.

Write data

Function prototype int tuya_user_api_config_item_set(IN const char *in_key, IN const void *val, IN int len)
Parameter
  • in_key: The identifier of data to be written to the configuration.
  • val: The data to be written to the configuration.
  • len: The length of data to be written to the configuration.
Feature Write configuration data to flash.
Header file #include <tuya_user_api.h>
Return value
  • 0: Success.
  • Other values: Failure.

Read data

Function prototype int tuya_user_api_config_item_get (IN const char *in_key, OUT void *out_buffer, OUT int *out_buffer_len)
Parameter
  • in_key: The identifier of configuration data to be read.
  • val: The data buffer to be read.
  • len: The length of configuration data to be read from the buffer.
Feature Read configuration data from flash.
Header file #include <tuya_user_api.h>
Return value
  • 0: Success.
  • Other values: Failure.

Delete data

Function prototype int32_t tuya_user_api_config_item_delete (IN const char *key)
Parameter key: The identifier of configuration data to be deleted.
Feature Delete configuration data from flash.
Header file #include <tuya_user_api.h>
Return value
  • 0: Success.
  • Other values: Failure.

Write bulk data

Function prototype INT_T tuya_user_api_kv_large_set(IN CONST PCHAR_T in_key, IN CONST PVOID_T val, IN INT_T len);
Parameter
  • in_key: The identifier of data to be written.
  • val: The data to be written.
  • len: The length of data to be written.
Feature Write bulk data to flash.
Header file #include <tuya_user_api.h>
Return value
  • 0: Success.
  • -1: Insufficient space.
  • -2: Key not found.
  • -3: Other errors.
  • -4: The length of the key exceeds the limit.

Read bulk data

Function prototype INT_T tuya_user_api_kv_large_get(IN CONST PCHAR_T in_key, OUT CONST PVOID_T out_buffer, OUT PINT_T out_buffer_len);
Parameter
  • in_key: The identifier of data to be read.
  • out_buffer: The buffer for data to be read.
  • lout_buffer_len: The length of data to be read.
Feature Read bulk data from flash.
Header file #include <tuya_user_api.h>
Return value
  • 0: Success.
  • -1: Insufficient space.
  • -2: Key not found.
  • -3: Other errors.
  • -4: The length of the key exceeds the limit.

Delete bulk data

Function prototype INT_T tuya_user_api_kv_large_delete(IN CONST PCHAR_T in_key);
Parameter in_key: The identifier of data to be deleted.
Feature Delete bulk data from flash.
Header file #include <tuya_user_api.h>
Return value
  • 0: Success.
  • -1: Insufficient space.
  • -2: Key not found.
  • -3: Other errors.
  • -4: The length of the key exceeds the limit.

Process system events

The user layer gets events from the SDK.

Set the event capture callback

Function prototype system_event_cb_t tuya_user_api_event_loop_set_cb (IN system_event_cb_t cb, IN void* ctx)
Parameter
  • cb: The pointer to the event handler callbacks to be registered. For more information, see system_event_cb_t.
  • ctx: The first parameter of the event handler callback. This parameter is reserved for now and can be used as user data.
Feature Set the event capture callback
Header file #include <tuya_user_api.h>
Return value Return the pointer to the last registered main event handler callback.

For more information, see the tuya_comm.h file in the SDK.

typedef int (*system_event_cb_t)(void *ctx, system_event_t *event);

typedef enum {
    SYSTEM_EVENT_ID_CARD,               // The SIM card is detected.
    SYSTEM_EVENT_NETWORK_READY,        // The NB-IoT device is attached to the network.
    SYSTEM_EVENT_NETWORK_DISCONNECT,   // The network is disconnected.
    SYSTEM_EVENT_GOING_SLEEP,           // The NB-IoT device is going to sleep.
    SYSTEM_EVENT_GOING_REBOOT,          // The NB-IoT device is rebooting.
    EVENT_LWM2M_CONNECTED,              // The LwM2M server is connected.
    EVENT_LWM2M_READY,                  //  The LwM2M service is available.
    EVENT_LWM2M_UPDATE_SUCCESS,        // The data is reported successfully.
    EVENT_LWM2M_RESPONSE_SUCCESS,      // The command is responded successfully.
    EVENT_LWM2M_RESTART,                // The LwM2M server is reconnected.
    EVENT_DEVICE_INFO_RESET,           // The NB-IoT device information is reset.
    EVENT_DEVICE_BIND_ON,              // The NB-IoT device is bound.
    EVENT_DEVICE_UNBIND_ON,            // The NB-IoT device is not bound.
    EVENT_DEVICE_DEACTIVE,             // Device reset.
    EVENT_POWERKEY_PRESS,              // The POWER key is pressed.
    EVENT_TRIGGER_TMSRV,    // Trigger the detection that is scheduled locally.
    EVENT_COMPOSITE_ACTIVE_SUCCESS,  // A composite product with NB-IoT module activated successfully.
    EVENT_LWDP_PACKET_SEND,         // Lwdp packets are transmitted asynchronously.
    EVENT_SLEEP_TYPE,        // The type of sleep event.
    EVENT_DISCRETE_ON,       // Turn on discrete.
    EVENT_CFUN_ON,
    SYSTEM_EVENT_MAX
} system_event_id_t;

Start the event capture task

Function prototype int tuya_user_api_event_loop_start(void)
Parameter None
Feature Start the event capture task
Header file #include <tuya_user_api.h>
Return value
  • 0: Success.
  • Other values: Failure.

Get device information

Get the information about the current device.

Get the activation status

Function prototype int tuya_user_api_is_dev_actived (void)
Parameter None
Feature Get the activation status of the device. The status is identified by the device ID and the secret key.
Header file #include <tuya_user_api.h>
Return value
  • 1: The device is activated.
  • 0: The device is not activated.

Get the binding status

Function prototype int tuya_user_api_is_dev_binded (void)
Parameter None
Feature Get the binding status
Header file #include <tuya_user_api.h>
Return value
  • 0: The device is not bound.
  • 1: The device is bound.

Get the schema status

Function prototype bool tuya_user_api_schema_is_completed (void)
Parameter None
Feature Check if the schema is completed.
Header file #include <tuya_user_api.h>
Return value
  • true: The schema is competed.
  • false: The schema is not completed.

Get the signal quality

Function prototype INT_T tuya_user_api_cesq_get (extended_signal_quality_t *info)
Parameter info: The returned signal quality parameters. For more information, see the struct extended_signal_quality_t.
Feature Execute the CESQ command to get the signal quality parameters.
Header file #include <tuya_user_api.h>
Return value
  • 0: Success.
  • Other values: Failure. The return value is invalid.

The struct extended_signal_quality_t:

typedef struct {
    int32_t rxlev; // The received signal level (RxLev) is a number from 0 to 63 that corresponds to a dBm value range. 0 represents the weakest signal and 63 the strongest.
    int32_t ber;   // The bit error rate (BER) whose valid values range from 0 to 99. Typically, BER is set to 0. A larger value can cause noise.
    int32_t rscp;  // The received signal code power (RSCP).
    int32_t ecno;  // Ec/No is the ratio between the received energy from the pilot signal CPICH per chip (Ec) to the noise density (No).
    int32_t rsrq;  // The reference signal received quality (RSRQ) indicates the quality of the received signal, and its range is typically -19.5 dB (bad) to -3 dB (good).
    int32_t rsrp;  // The reference signal received power (RSRP) indicates the average power received from a single reference signal, and its range is typically around -44 dBm (good) to -140 dBm (bad).
} extended_signal_quality_t;

Get the RSSI value

Function prototype INT_T tuya_user_api_rssi_get (void)
Parameter None
Feature Get the value of the received signal strength indicator (RSSI).
Header file #include <tuya_user_api.h>
Return value The signal strength, represented by a signed integer. The higher the RSSI value, the stronger the signal. When measured in negative numbers, the number that is closer to zero usually means better signal strength.

Description

RSSI: Its range is typically 0 to -70. An RSSI value of less than -70 indicates poor signal quality.

Get the IMSI number

Function prototype CHAR_T *tuya_user_api_imsi_get (void)
Parameter None
Feature Get the international mobile subscriber identity (IMSI) of the device.
Header file #include <tuya_user_api.h>
Return value The pointer to the IMSI string.

Description

IMSI: A number that uniquely identifies every user of a cellular network. It is usually presented as a 15-digit number (0 to 9) but can be shorter.

Get the ICCID number

Function prototype CHAR_T *tuya_user_api_iccid_get (void)
Parameter None
Feature Get the integrated circuit card identifier (ICCID) of the device.
Header file #include <tuya_user_api.h>
Return value The pointer to the ICCID string.

Description

ICCID: A unique number assigned to a SIM card and used to identify SIM cards internationally. ICCID is the unique identifier of an IC card, composed of 20 characters.

Get the IMEI number

Function prototype int tuya_user_api_get_dev_imei (OUT char* device_imei)
Parameter device_imei: The pointer to the IMEI string.
Feature Get the international mobile equipment identity (IMEI) of the device.
Header file #include <tuya_user_api.h>
Return value The length of the returned IMEI, usually a 15-digit number.

Description

IMEI: A unique number used to identify NB-IoT devices. Every NB-IoT device comes with a unique IMEI, which must not be modified. If the IMEI is empty, the device cannot work as expected.

Get the device’s PID

Function prototype int tuya_user_api_get_dev_product_key (OUT char* product_key)
Parameter product_key: The pointer to the PID of the device.
Feature Get the device’s PID
Header file #include <tuya_user_api.h>
Return value The length of the returned PID.

Description

PID: A unique identifier that is automatically assigned to each product created on the Tuya IoT Development Platform. The principle of PID generation is defined by Tuya. Make sure the PID that applies to your NB-IoT devices is correct. If you have any questions, submit a service ticket.

Set the PID

Function prototype int tuya_user_api_set_product_key (IN char* product_key)
Parameter product_key: The pointer to the PID of the device.
Feature Set the PID for the device.
Header file #include <tuya_user_api.h>
Return value The length of the PID set to the device.

Description

PID: A unique identifier that is automatically assigned to each product created on the Tuya IoT Development Platform. The principle of PID generation is defined by Tuya. Make sure the PID that applies to your NB-IoT devices is correct. If you have any questions, submit a service ticket.

Set the MCU’s firmware version

Function prototype int tuya_user_api_set_soft_ver (IN char* version)
Parameter version: The firmware version of the MCU on the NB-IoT device.
Feature Set the MCU’s firmware version
Header file #include <tuya_user_api.h>
Return value The length of the string written to the version array, in bytes.

Description

The version indicates the firmware version of the MCU that communicates with the NB-IoT module via the serial port. It does not refer to the firmware version of the NB-IoT module.

Set the heartbeat interval

Function prototype void tuya_user_api_lifetime_set (IN uint32_t lifetime)
Parameter lifetime: The heartbeat interval to set, in seconds.
Feature Set the heartbeat interval
Header file #include <tuya_user_api.h>
Return value None

Description

Typically, lifetime is greater than 120 and less than or equal to 604,800, in seconds. If lifetime is set to less than 120, it will be 120 actually. If lifetime is set to 0 or greater than 604,800, it will be 604,800 actually.

This function applies to the non-record type lifetime.

Set the frequency of reporting record-type data

Function prototype void tuya_user_api_record_dp_lifetime_set (IN uint32_t lifetime)
Parameter lifetime: The heartbeat interval to set, in seconds.
Feature Set the frequency of reporting record-type data in sleep mode under an unstable network state.
Header file #include <tuya_user_api.h>
Return value None

Typically, lifetime is greater than 120 and less than or equal to 604,800, in seconds. If lifetime is set to less than 120, it will be 120 actually. If lifetime is set to 0 or greater than 604,800, it will be 604,800 actually.

This function applies to the record type lifetime.

Get the frequency of reporting record-type data

Function prototype uint32_t tuya_user_api_get_dev_record_dp_lifetime (void)
Parameter None
Feature Get the frequency of reporting record-type data
Header file #include <tuya_user_api.h>
Return value The frequency of reporting record-type data, in seconds.

Get the heartbeat interval

Function prototype uint32_t tuya_user_api_get_dev_lifetime (void)
Parameter None
Feature Get the heartbeat interval set for the device.
Header file #include <tuya_user_api.h>
Return value The heartbeat interval, in seconds.

Get the network health

Function prototype unsigned int tuya_user_api_statistic_score (void);
Parameter None
Feature Get the network health.
Header file #include <tuya_user_api.h>
Return value The network health status in terms of network attachment, registration to the cloud, and data exchange.

OTA firmware update

Set battery level query and update status callback

Function prototype void tuya_user_api_fota_notify_register (IN tuya_fota_context_t* ctx)
Parameter ctx: Information about OTA firmware update. For more information, see the struct tuya_fota_context_t.
Feature Set the battery level query and the update status callback invoked when an update is performed.
Header file #include <tuya_user_api.h>
Return value None

Description

The struct tuya_fota_context_t:

typedef struct {
    battery_state_t (*hal_battery_level_get)();
    void (*event_notify)(tuya_fota_event_id_t event_id);
} tuya_fota_context_t;

The member hal_battery_level_get is the pointer to the battery level function, which must be initialized during the system initialization process. The battery level function is implemented by you.

event_notify is the handler for OTA update event reporting.

For more information about the function definition, see the tuya_comm.h in the SDK.

Process the time data

Get Unix timestamp

Function prototype TIME_T tuya_user_api_time_get_posix_time (VOID)
Parameter None
Feature Get the system’s Unix timestamp without time zone, in seconds.
Header file #include <tuya_user_api.h>
Return value The Unix timestamp of the system, in seconds.

Description

The Unix timestamp tracks time as a running count of seconds. The count begins at the Unix epoch on January 1st, 1970 at 00:00:00, so a Unix timestamp is the total seconds between any given date and the Unix epoch.

TIME_T type indicates an unsigned integer.

Get the GMT

Function prototype OPERATE_RET tuya_user_api_get_green_time (OUT POSIX_TM_S *tm)
Parameter tm: The returned date and time. For more information, see the struct POSIX_TM_S.
Feature Get the date and time in GMT.
Header file #include <tuya_user_api.h>
Return value
  • OPRT_OK: Success.
  • Other values: Failure.

Description

The struct POSIX_TM_S:

typedef struct {
    INT_T tm_sec;   // The seconds, from 0 to 59.
    INT_T tm_min;   // The minutes, from 0 to 59.
    INT_T tm_hour;  // The hours, from 0 to 23.
    INT_T tm_mday;  // The day of the month, from 1 to 31.
    INT_T tm_mon;   // The month, from 0 to 11.
    INT_T tm_year;  // The year since 1990.
    INT_T tm_wday;  // The day of the week, from 0 to 6. 0 is for Sunday and 6 is for Saturday.
} POSIX_TM_S;

Get local time

Function prototype OPERATE_RET tuya_user_api_get_local_time (OUT POSIX_TM_S *tm)
Parameter tm: The returned date and time. For more information, see the struct POSIX_TM_S.
Feature Get local time
Header file #include <tuya_user_api.h>
Return value
  • OPRT_OK: Success.
  • Other values: Failure.

Description

The struct POSIX_TM_S:

typedef struct {
  INT_T tm_sec;   // The seconds, from 0 to 59.
  INT_T tm_min;   // The minutes, from 0 to 59.
  INT_T tm_hour;  // The hours, from 0 to 23.
  INT_T tm_mday;  // The day of the month, from 1 to 31.
  INT_T tm_mon;   // The month, from 0 to 11.
  INT_T tm_year;  // The year since 1990.
  INT_T tm_wday;  // The day of the week, from 0 to 6. 0 is for Sunday and 6 is for Saturday.
} POSIX_TM_S;

Convert local time to Unix timestamp

Function prototype OPERATE_RET tuya_user_api_local_time2posix_time (IN POSIX_TM_S *tm, OUT TIME_T *timestamp)
Parameter
  • tm: The date and time passed in. For more information, see the struct POSIX_TM_S.
  • timestamp: The returned time, in seconds.
Feature Convert the local time to Unix timestamp without time zone.
Header file #include <tuya_user_api.h>
Return value
  • OPRT_OK: Success.
  • Other values: Failure.

Description

The struct POSIX_TM_S:

typedef struct {
  INT_T tm_sec;   // The seconds, from 0 to 59.
  INT_T tm_min;   // The minutes, from 0 to 59.
  INT_T tm_hour;  // The hours, from 0 to 23.
  INT_T tm_mday;  // The day of the month, from 1 to 31.
  INT_T tm_mon;   // The month, from 0 to 11.
  INT_T tm_year;  // The year since 1990.
  INT_T tm_wday;  // The day of the week, from 0 to 6. 0 is for Sunday and 6 is for Saturday.
} POSIX_TM_S;

Check the time sync

Function prototype OPERATE_RET tuya_user_api_time_check_time_sync (void)
Parameter None
Feature Check if the local time is in sync with the server time.
Header file #include <tuya_user_api.h>
Return value
  • OPRT_OK: Normal.
  • Other values: Failure.

Get the runtime

Function prototype VOID tuya_user_api_get_system_runtime (OUT TIME_S *pSecTime,OUT TIME_MS *pMsTime);
Parameter
  • pSecTime: The returned runtime, in seconds.
  • pMsTime: The returned runtime, in milliseconds.
Feature Get the runtime from startup. Take care of the adopted unit of the runtime.
Header file #include <tuya_user_api.h>
Return value None

Restart heartbeat timer

Function prototype void tuya_user_api_heart_beat_send_timer_restart (void);
Parameter None
Feature Restart the heartbeat timer.
Header file #include <tuya_user_api.h>
Return value None

Start sleep timer

Function prototype void tuya_user_api_sleep_tmr_start(void (callback)(void data), uint32_t time_s);
Parameter
  • callback: The timer callback.
  • time_s: The specified time.
Feature Start the sleep timer.
Header file #include <tuya_user_api.h>
Return value None

Stop sleep timer

Function prototype void tuya_user_api_sleep_tmr_stop(void);
Parameter None
Feature Stop the sleep timer.
Header file #include <tuya_user_api.h>
Return value None

Process DP operations

A set of functions for processing DP operations.

Set command reception callback

Function prototype int tuya_user_api_dp_write_default_cb (IN lwdp_write_callback_t cb)
Parameter cb: The pointer to the callbacks to be set.
Feature Set the callback to invoke when commands from the cloud are received.
Header file #include <tuya_user_api.h>
Return value
  • 0: Success.
  • Other values: Failure.

Description

The function pointer lwdp_write_callback_t:

// Define your function implementation and pass in the corresponding API.
typedef uint8_t (*lwdp_write_callback_t)(lwdp_object_t* objectArrayP);

Set the non-record data reporting callback

Function prototype void tuya_user_api_dp_report_ack_register_cb (IN tuya_dp_ack_callback_t cb)
Parameter cb: The pointer to the callbacks to be set.
Feature Set the non-record data reporting callback
Header file #include <tuya_user_api.h>
Return value
  • 0: Success.
  • Other values: Failure.

Description

The function pointer tuya_dp_ack_callback_t:

// Define your function implementation and pass in the corresponding API.
typedef void (*tuya_dp_ack_callback_t)(uint16_t msgid, uint8_t result);

Get the number of non-record packets

Function prototype int tuya_user_api_not_record_packet_count(void)
Parameter None
Feature Get the number of non-record data packets.
Header file #include <tuya_user_api.h>
Return value The number of non-record data packets.

Set the record data reporting callback

Function prototype void tuya_user_api_dp_report_record_ack_register_cb (IN tuya_dp_ack_callback_t cb)
Parameter cb: The pointer to the DP reporting callback to be set.
Feature Set the record data reporting callback
Header file #include <tuya_user_api.h>
Return value None

Description

The function pointer tuya_dp_ack_callback_t:

// Define your function implementation and pass in the corresponding API.
typedef void (*tuya_dp_ack_callback_t)(uint16_t msgid, uint8_t result);

Send heartbeat packets

Function prototype void tuya_user_api_heartbeat_send (void)
Parameter None
Feature Send heartbeat packets
Header file #include <tuya_user_api.h>
Return value None

Report data to the cloud

Function prototype int tuya_user_api_dp_report (IN bool is_record_type, IN int size, IN lwdp_object_t* dataP)
Parameter
  • is_record_type: true indicates the record type data. false indicates the non-record type data.
  • size: The number of data sets.
  • dataP: The pointer to the DP data. For more information, see the struct lwdp_object_t.
Feature Report data to the cloud
Header file #include <tuya_user_api.h>
Return value
  • 0: Success
  • Other values: Failure. The return value is invalid.

Create DP objects

Function prototype lwdp_object_t* tuya_user_api_lwdp_object_new(IN int size)
Parameter size: The number of DPs created.
Feature Create DP objects
Header file #include <tuya_user_api.h>
Return value The pointer to the DP instance. For more information, see the struct lwdp_object_t.

Release DP objects

Function prototype void tuya_user_api_lwdp_object_free (IN int size, IN lwdp_object_t* dataP)
Parameter
  • size: The number of DPs released.
  • dataP: The start address of the DP data released. For more information, see the struct lwdp_object_t.
Feature Release DP objects
Header file #include <tuya_user_api.h>
Return value The pointer to the DP instance.

Get the DP packet length

Function prototype uint16_t tuya_user_api_get_lwdp_object_length (IN lwdp_object_t* dataP)
Parameter dataP: The lwdp_object_t object to be obtained. For more information, see the struct lwdp_object_t.
Feature Get the length of the current DP packet.
Header file #include <tuya_user_api.h>
Return value None

Decode Boolean DP data

Function prototype int tuya_user_api_lwdp_decode_bool (IN lwdp_object_t* dataP, OUT bool* outP)
Parameter
  • dataP: The lwdp_object_t object to be decoded. For more information, see the struct lwdp_object_t.
  • outP: The decoded Boolean data.
Feature Decode the Boolean DP data.
Header file #include <tuya_user_api.h>
Return value None

Decode integer DP data

Function prototype int tuya_user_api_lwdp_decode_int (IN lwdp_object_t* dataP, OUT int32_t* outP)
Parameter
  • dataP: The lwdp_object_t object to be decoded. For more information, see the struct lwdp_object_t.
  • outP: The decoded integer data.
Feature Decode the integer DP data.
Header file #include <tuya_user_api.h>
Return value
  • 0: Success.
  • Other values: Failure. The return value is invalid.

Decode raw DP data

Function prototype int tuya_user_api_lwdp_decode_raw (IN lwdp_object_t* dataP, OUT uint8_t* outP, OUT size_t* olen)
Parameter
  • dataP: The lwdp_object_t object to be decoded. For more information, see the struct lwdp_object_t.
  • outP: The decoded raw data.
  • olen: The length of the decoded raw data.
Feature Decode the raw DP data.
Header file #include <tuya_user_api.h>
Return value
  • 0: Success.
  • Other values: Failure. The return value is invalid.

Decode string DP data

Function prototype int tuya_user_api_lwdp_decode_string (IN lwdp_object_t* dataP, OUT char* outP, OUT size_t* olen)
Parameter
  • dataP: The lwdp_object_t object to be decoded. For more information, see the struct lwdp_object_t.
  • outP: The pointer to the decoded string.
  • olen: The length of the decoded string.
Feature Decode the string DP data.
Header file #include <tuya_user_api.h>
Return value
  • 0: Success.
  • Other values: Failure. The return value is invalid.

Decode enum DP data

Function prototype int tuya_user_api_lwdp_decode_enum (IN lwdp_object_t* dataP, OUT uint8_t* enum_idx)
Parameter
  • dataP: The lwdp_object_t object to be decoded. For more information, see the struct lwdp_object_t.
  • enum_idx: The decoded enum subscript.
Feature Decode the enum DP data.
Header file #include <tuya_user_api.h>
Return value
  • 0: Success.
  • Other values: Failure. The return value is invalid.

Encode Boolean DP data

Function prototype void tuya_user_api_lwdp_encode_bool (IN bool value, OUT lwdp_object_t* dataP)
Parameter
  • value: The Boolean data to be encoded.
  • dataP: The lwdp_object_t object to be encoded. For more information, see the struct lwdp_object_t.
Feature Encode the Boolean DP data.
Header file #include <tuya_user_api.h>
Return value None

Encode raw DP data

Function prototype void tuya_user_api_lwdp_encode_raw (IN uint8_t* buffer, IN size_t length, OUT lwdp_object_t* dataP)
Parameter
  • buffer: The pointer to the raw data to be encoded to the lwdp_object_t object.
  • length: The length of the raw data to be encoded.
  • dataP: The encapsulated object returned. For more information, see the struct lwdp_object_t.
Feature Encode raw DP data
Header file #include <tuya_user_api.h>
Return value None

Encode string DP data

Function prototype void tuya_user_api_lwdp_encode_string (IN const char* string, OUT lwdp_object_t* dataP)
Parameter
  • string: The pointer to the string data to be encapsulated to the lwdp_object_t object.
  • dataP: The encapsulated object returned. For more information, see the struct lwdp_object_t.
Feature Encode the string DP data.
Header file #include <tuya_user_api.h>
Return value None

Encode string DP data (with length)

Function prototype void tuya_user_api_lwdp_encode_nstring (IN const char* string, IN size_t length, OUT lwdp_object_t* dataP)
Parameter
  • string: The pointer to the string data to be encoded to the lwdp_object_t object.
  • length: The length of the string to be encoded.
  • dataP: The encapsulated object returned. For more information, see the struct lwdp_object_t.
Feature Encode the string DP data.
Header file #include <tuya_user_api.h>
Return value None

Encode integer DP data

Function prototype void tuya_user_api_lwdp_encode_int (IN int32_t value, OUT lwdp_object_t* dataP)
Parameter
  • value: The data to be encoded to integer data type.
  • dataP: The encoded object returned. For more information, see the struct lwdp_object_t.
Feature Encode the integer DP data.
Header file #include <tuya_user_api.h>
Return value None

Encode enum DP data

Function prototype void tuya_user_api_lwdp_encode_enum (IN uint32_t value, OUT lwdp_object_t* dataP)
Parameter
  • value: The data to be encoded to enum data type.
  • dataP: The encoded object returned. For more information, see the struct lwdp_object_t.
Feature Encode the enum DP data.
Header file #include <tuya_user_api.h>
Return value None

Encode bitmap DP data

Function prototype void tuya_user_api_lwdp_encode_map (IN uint32_t value, OUT lwdp_object_t* dataP)
Parameter
  • value: The data to be encoded to bitmap data type.
  • dataP: The encoded object returned. For more information, see the struct lwdp_object_t.
Feature Encode the bitmap DP data.
Header file #include <tuya_user_api.h>
Return value None

Get the DP ID of the RSSI

Function prototype int tuya_user_api_get_rssi_dp_digit (void)
Parameter None
Feature Get the DP ID of the RSSI.
Header file #include <tuya_user_api.h>
Return value The DP ID of the RSSI.

Get the DP ID of timestamp

Function prototype int tuya_user_api_get_timestamp_dp_digit (void)
Parameter None
Feature Get the DP ID of the timestamp.
Header file #include <tuya_user_api.h>
Return value The DP ID of the timestamp.

Get the DP ID of a request

Function prototype int tuya_user_api_get_request_dp_digit (void)
Parameter None
Feature Get the corresponding DP ID of a DP request.
Header file #include <tuya_user_api.h>
Return value The DP ID of the DP request.

Struct description

typedef struct _lwdp_object_t {
    struct _lwdp_object_* next;   // Point to the next `lwdp_object_t` node, used as a linked list.
    uint16_t       id;    // The DP ID.
    lwdp_obj_type_t    type; // Refer to the example in the SDK for value assignment.
    lwdp_obj_mode_t    mode; // Refer to the example in the SDK for value assignment.
    lwdp_obj_value_t   value;  // Refer to the example in the SDK for value assignment.
    lwdp_obj_property_t  property; // Refer to the example in the SDK for value assignment.
} lwdp_object_t;

Set the operation mode

Get and set the operation mode of the SIM card and NB-IoT devices.

Care should be taken when you set these functions.

Get the reason for system startup

Function prototype TAL_PSM_POWER_ON_RESULT_E tuya_user_api_get_powerOn_result (VOID)
Parameter None
Feature Get the reason for system startup.
Header file #include <tuya_user_api.h>
Return value The reason for system startup. For more information, see TAL_PSM_POWER_ON_RESULT_E.

For more information, see the tuya_comm.h file in the SDK.

TAL_PSM_POWER_ON_RESULT_E enum:

typedef enum {
  TAL_FIRST_BOOT_UP    = 0,   // Initial startup.
  TAL_DEEP_SLEEP     = 1,   // Startup from light sleep.
  TAL_DEEPER_SLEEP    = 2,   // Startup from deep sleep.
  TAL_SYS_RESET      = 3,   // System restart.
  TAL_WDT_HW_RESET    = 4,   // The hardware watchdog startup.
  TAL_WDT_SW_RESET    = 5,   // The software watchdog startup.
  TAL_FORCED_SHUT_DOWN  = 6,   // Force shutdown and restart.
  TAL_FORCED_RESET    = 7,   // Force restart.
  TAL_POWER_ON_RESULT_MAX
} TAL_PSM_POWER_ON_RESULT_E;

Get the trigger for wake-up

Function prototype TY_WAKEUP_SOURCE_E ty_mw_wakeup_source_get (void)
Parameter None
Feature Get the trigger for system wake-up.
Header file #include <tuya_user_api.h>
Return value The trigger for system wake-up. For more information, see TY_POWER_ON_RESULT_E.

Description

typedef enum {
  TY_WAKEUP_FROM_NONE, // Unknown trigger.
  TY_WAKEUP_FROM_POR,  // Triggered by power-on or reset.
  TY_WAKEUP_FROM_RTC, // Triggered by RTC.
  TY_WAKEUP_FROM_KEY, // Triggered by button press.
}TY_WAKEUP_SOURCE_E;

Set the operation mode

Function prototype OPERATE_RET tuya_user_api_sim_mode_set (IN char* mode)
Parameter mode: The low power mode to be set for the SIM card.
Feature Set the operation mode of the NB-IoT device, which can be PSM, DRX, or eDRX.
Header file #include <tuya_user_api.h>
Return value
  • OPRT_OK: Success.
  • Other values: Failure.

Description

The valid values of mode are psm, drx, and edrx or with all letters capitalized PSM, DRX, and EDRX. A mix of uppercase and lowercase letters such as Psm is invalid.

Set the connection mode

Function prototype bool tuya_user_api_connect_mode_set (IN char* mode)
Parameter mode: The connection mode.
Feature Set the connection mode
Header file #include <tuya_user_api.h>
Return value
  • true: Success.
  • false: Failure.

Description

The valid values of mode are tuya or TUYA and other strings. tuya or TUYA indicates the NB-IoT device is directly connected to the cloud. Other strings indicate the internet service provider (ISP) mode is adopted and the NB-IoT device is connected to the carrier’s cloud.

Get the current operation mode

Function prototype nbiot_mode_t tuya_user_api_sim_mode_get (void)
Parameter None
Feature Get the current operation mode
Header file #include <tuya_user_api.h>
Return value The current operation mode of the NB-IoT device. For more information, see the nbiot_mode_t enum.

Description

nbiot_mode_t enum:

typedef enum {
  NBIoT_MODE_PSM,      // Power saving mode.
  NBIoT_MODE_DRX,      // Discontinuous reception mode.
  NBIoT_MODE_EDRX      //  Extended discontinuous reception mode.
} nbiot_mode_t;

Prevent sleep mode

Function prototype void tuya_user_api_psm_disable (void)
Parameter None
Feature Prevent the NB-IoT device from entering sleep mode.
Header file #include <tuya_user_api.h>
Return value None

Enable sleep mode

Function prototype void tuya_user_api_psm_enable (void)
Parameter None
Feature Enable the NB-IoT device to enter sleep mode.
Header file #include <tuya_user_api.h>
Return value None

Disable the power saving lock

Function prototype void tuya_user_api_enter_psm (void)
Parameter None
Feature Disable the power saving lock to enable the NB-IoT device to enter sleep mode.
Header file #include <tuya_user_api.h>
Return value None

Set the APN

Function prototype void tuya_user_api_set_apn (char *apn, char *pdp_type)
Parameter
  • apn: The APN string.
  • pdp_type: The packet data protocol, which can be IP, IPv6, IPv4v6, or Non-IP. Typically, you can set it to IP.
Feature Set the APN for the adopted carrier.
Header file #include <tuya_user_api.h>
Return value None

Description

Setting this function is not necessary.

Force sleep mode

Function prototype void tuya_user_api_forced_sleep (void)
Parameter None
Feature Force sleep mode
Header file #include <tuya_user_api.h>
Return value None

Restart device

Function prototype void tuya_user_api_going_reboot(void);
Parameter None
Feature Restart device
Header file #include <tuya_user_api.h>
Return value None

Set the T3324 timer

Function prototype OPERATE_RET tuya_user_api_write_t3324(int64_t req_time)
Parameter req_time: The time to be written, in seconds.
Feature Set the T3324 timer
Header file #include <tuya_user_api.h>
Return value
  • OPRT_OK: Success.
  • Other values: Failure. The return value is invalid.

Set the T3412 timer

Function prototype OPERATE_RET tuya_user_api_write_t3412(int64_t req_time)
Parameter req_time: The time to be written, in seconds.
Feature Set the T3412 timer
Header file #include <tuya_user_api.h>
Return value
  • OPRT_OK: Success.
  • Other values: Failure. The return value is invalid.

Set the discrete information

Function prototype OPERATE_RET tuya_user_api_set_discrete_info(bool discrete_on, uint16_t duration, uint8_t step)
Parameter
  • discrete_on: Turn on/off discrete.
  • duration: The random seed for discrete, ranging from 120 to 1,800, in seconds.
  • step: The minimum discrete step.
    • 1: step is 60s.
    • 0: step is 30s.
Feature Set the discrete information
Header file #include <tuya_user_api.h>
Return value
  • 0: Success.
  • Other values: Failure.

Description

This API configures the discrete information the first time an NB-IoT module is started. This way, when you onboard a large number of devices at the same time, network congestion can be reduced.

Use this API with caution. Do not apply it to devices with an automatic power-off feature.

Third-party cloud connects to the user layer

Set LwM2M information

Function prototype INT_T tuya_user_api_3rd_cloud_config(TAL_NBIOT_LWM2M_REGISTER_T *lwm2m_config)
Parameter lwm2m_config: The LwM2M information about the third-party cloud.
Feature Set the LwM2M information about the third-party cloud.
Header file #include <tuya_user_api.h>
Return value
  • 0: Success.
  • Other values: Failure.

Description

typedef struct {
    TAL_NBIOT_EVENT_CB 	event_cb;                   // lwm2m event send callback
    UCHAR_T                 evt_id_ready;               // lwm2m ready event 
    UCHAR_T 		    evt_id_connected;       // lwm2m connected event 
    UCHAR_T 		    evt_id_update_success;  // lwm2m update successful event 
    UCHAR_T 		    evt_id_rsp_success;     // lwm2m response successful event 
    
    BOOL_T  		    bootstrap_en;           // boot strap enable
    TAL_NBIOT_ISP_T     isp_type;                   // connect isp type,refer to TAL_NBIOT_ISP_T
    UINT_T   		    lifetime;               // life time with the server
    UINT_T	            srv_port;               // desired port of lwm2m server
    CHAR_T *                srv_ip;                 // desired ip address of lwm2m server
    CHAR_T *		    imei;                   // imei of the client
    CHAR_T *                psk;                    // psk used for dtls
    TAL_NBIOT_OBJ_ATTRI attri;                      // object attribute;
    
    TAL_NBIOT_REV_DATA_CB data_recv_cb;             // data reveive callback
}TAL_NBIOT_LWM2M_REGISTER_T;

Things to note

Connectivity Mode Port Bootstrap state SIM card carrier Remark
China Mobile Non-DTLS 5683
  • DRX mode: Disabled
  • PSM mode: Enabled
  • China Mobile DRX only supports the APN (CMNBIOTONENET) dedicated to China Mobile.
    China Telecom DTLS 5684 Disabled China Telecom
    Directly connected DTLS 5684 Disabled China Mobile

    Usage example

    China Telecom:
    TAL_NBIOT_LWM2M_REGISTER_T params;
    params.bootstrap_en     = 0;                        // CTCC and directly connected: bs is not enabled. CMCC: in DRX mode, dedicated network is not enabled; in PSM mode, network is enabled.
    params.srv_ip           = "221.229.214.202";         // Server address, China Telecom line
    params.srv_port         = 5684;                     // Server port number, 5684 (encrypted), 5683 (not encrypted); China Mobile does not support encryption currently.
    params.isp_type         = NBIOT_ISP_OTHER;          //NBIOT_ISP_TUYA: indicates the device is directly connected to the third-party cloud. Otherwise, the device is connected to the carrier's cloud that forwards data to the destination.
    params.lifetime         = 7200;                     //LwM2M heartbeat interval, in seconds.
    params.psk              = "bFFFcDDDEB7aaBbc";       // The key for LwM2M communication, with 16 to 32 characters.
    //params.imei             = "862363050000149";        //(Optional) 15-character IMEI, which can be obtained from the underlying layer. /*endpoint_name,pskid*/
    //device attribute:
    params.attri.obj_id = 19;
    params.attri.ins_id_up = 0;
    params.attri.ins_id_down = 1;
    params.attri.res_id = 0;
    tuya_user_api_3rd_cloud_config(&params);  
    
    China Mobile DRX mode
    
    TAL_NBIOT_LWM2M_REGISTER_T params;
    params.bootstrap_en     = 0;                        // CTCC and directly connected: bs is not enabled. CMCC: in DRX mode, dedicated network is not enabled; in PSM mode, network is enabled.
    params.srv_ip           = "192.168.24.100";         // Server address, China Mobile line
    params.srv_port         = 5683;                     // Server port number, 5684 (encrypted), 5683 (not encrypted); China Mobile does not support encryption currently.
    params.isp_type         = NBIOT_ISP_OTHER;          //NBIOT_ISP_TUYA: indicates the device is directly connected to the third-party cloud. Otherwise, the device is connected to the carrier's cloud that forwards data to the destination.
    params.lifetime         = 7200;                     //LwM2M heartbeat interval, in seconds.
    //params.psk              = "bFFFcDDDEB7aaBbc";       // The key for LwM2M communication, with 16 to 32 characters.
    //params.imei             = "862363050000149";        //(Optional) 15-character IMEI, which can be obtained from the underlying layer. /*endpoint_name,pskid*/
    //device attribute:
    params.attri.obj_id = x;
    params.attri.ins_id_up = x;
    params.attri.ins_id_down = x;
    params.attri.res_id = x;
    tuya_user_api_3rd_cloud_config(&params);  
    
    China Mobile PSM mode
    
    TAL_NBIOT_LWM2M_REGISTER_T params;
    params.bootstrap_en     = 1;                        // CTCC and directly connected: bs is not enabled. CMCC: in DRX mode, dedicated network is not enabled; in PSM mode, network is enabled.
    params.srv_ip           = "183.230.40.39";         // Server address, China Mobile
    params.srv_port         = 5683;                     // Server port number, 5684 (encrypted), 5683 (not encrypted); China Mobile does not support encryption currently.
    params.isp_type         = NBIOT_ISP_OTHER;          //NBIOT_ISP_TUYA: indicates the device is directly connected to the third-party cloud. Otherwise, the device is connected to the carrier's cloud that forwards data to the destination.
    params.lifetime         = 7200;                     //LwM2M heartbeat interval, in seconds.
    //params.psk              = "bFFFcDDDEB7aaBbc";       // The key for LwM2M communication, with 16 to 32 characters.
    //params.imei             = "862363050000149";        //(Optional) 15-character IMEI, which can be obtained from the underlying layer. /*endpoint_name,pskid*/
    //device attribute:
    params.attri.obj_id = x;
    params.attri.ins_id_up = x;
    params.attri.ins_id_down = x;
    params.attri.res_id = x;
    tuya_user_api_3rd_cloud_config(&params);  
    
    Directly connected to third-party cloud
    
    TAL_NBIOT_LWM2M_REGISTER_T params;
    params.bootstrap_en     = 0;                        // CTCC and directly connected: bs is not enabled. CMCC: in DRX mode, dedicated network is not enabled; in PSM mode, network is enabled.
    params.srv_ip           = "XXX.XXX.XXX.XXX";         // Server address, third-party cloud
    params.srv_port         = 5684;                     // Server port number, 5684 (encrypted), 5683 (not encrypted); China Mobile does not support encryption currently.
    params.isp_type         = NBIOT_ISP_TUYA;          //NBIOT_ISP_TUYA: indicates the device is directly connected to the third-party cloud. Otherwise, the device is connected to the carrier's cloud that forwards data to the destination.
    params.lifetime         = 7200;                     //LwM2M heartbeat interval, in seconds.
    params.psk              = "bFFFcDDDEB7aaBbc";       // The key for LwM2M communication, with 16 to 32 characters.
    //params.imei             = "862363050000149";        //(Optional) 15-character IMEI, which can be obtained from the underlying layer. /*endpoint_name,pskid*/
    //device attribute:
    params.attri.obj_id = x;
    params.attri.ins_id_up = x;
    params.attri.ins_id_down = x;
    params.attri.res_id = x;
    tuya_user_api_3rd_cloud_config(&params);  
    

    Register raw data reception callback

    Function prototype INT_T tuya_user_api_raw_data_recv_register_cb(void (data_recv_cb_t)(const uint8_t data, uint32_t data_len))
    Parameter ata_recv_cb_t: The pointer to the reception callback.
    Feature Register raw data reception callback
    Header file #include <tuya_user_api.h>
    Return value
    • 0: Success.
    • Other values: Failure.

    Send raw data

    Function prototype INT_T tuya_user_api_raw_data_send(uint8_t* buffer, uint16_t length)
    Parameter
    • buffer: The buffer of the data to be sent.
    • length: The length of the data to be sent.
    Feature Send raw data
    Header file #include <tuya_user_api.h>
    Return value
    • 0: Success.
    • Other values: Failure.

    Reset API when data transmission fails

    Function prototype void tuya_user_api_cloud_connect_restart(void)
    Parameter None
    Feature Reset API when data transmission fails
    Header file #include <tuya_user_api.h>
    Return value None

    Restore defaults

    Reset modules

    Function prototype int32_t tuya_user_api_factory_data_reset (tuya_user_api_dev_reset_cb cb)
    Parameter cb: The event reporting callback. For more information, see tuya_user_api_dev_reset_cb.
    Feature Reset the NB-IoT module to restore factory settings.
    Header file #include <tuya_user_api.h>
    Return value
    • 0: Success.
    • Other values: Failure.

    Description

    The function pointer tuya_user_api_dev_reset_cb:

    // Implement the function. For more information, see the `tuya_user_api.h` in the SDK.
    typedef void (*tuya_user_api_dev_reset_cb)(int code);
    

    Production testing

    Implement the required functions for production tests.

    Register production test callbacks

    Function prototype void tuya_user_api_mf_test_cb_reg (int (*user_test_callback)(IN USHORT_T cmd, IN UCHAR_T *data, IN UINT_T len, OUT UCHAR_T *ret_data,OUT USHORT_T *ret_len))
    Parameter
    • user_test_callback: The callback.
    • cmd: The subcommand.
    • data: The pointer to the subcommand payload.
    • len: The length of the subcommand payload.
    • ret_data: The pointer to the return value.
    • ret_len: The length of the return value.
    Feature Register the callback for production testing.
    Header file #include <tuya_user_api.h>
    Return value
    • 0: Success.
    • Other values: Failure.

    Set the production test callback

    Function prototype void tuya_user_api_mf_test_raw_reg(mf_user_test_custom_cb user_custom_cb, mf_user_test_custom_check_cb check_cb);
    Parameter
    • tuya_user_api_dev_reset_cb and user_custom_cb: The custom callbacks for processing the test data.
    • check_cb: The custom callback for identifying the test result.
    Feature Set the production test callbacks
    Header file #include <tuya_user_api.h>
    Return value None
    Description This function is used for pin multiplexing when you test the NB-IoT module and the peripherals with one serial port.