Device Data Statistics

Last Updated on : 2025-11-27 09:35:59download

Overview

This service provides APIs for retrieving device data statistics at four different time granularities, which can be used for business displays such as device data visualization in charts and device data analytics.

  • Energy consumption charts: Show device energy consumption, temperature, humidity, and more.
  • Trend analytics: Analyze data change trends.
  • Usage statistics: Track device usage duration and frequency.
  • Data comparison: Compare data across different time periods.

To utilize the statistics capabilities, you must first submit a ticket to subscribe to the product data statistics service.

Usage

  1. Add the following dependency to the Podfile:

    source 'https://github.com/tuya/tuya-pod-specs.git'
    platform :ios, '11.0'
    
    target 'Your_Project_Name' do
        # Build and get ThingSmartCryption from the Tuya Developer Platform (https://platform.tuya.com).
        # After the official edition  is purchased, rebuild the SDK on the Tuya Developer Platform and integrate it into your project.
        # The dot slash (./) notation represents that the files that are obtained after ios_core_sdk.tar.gz is extracted are put at a sibling directory as podfile.
        # To use another directory, change the path to your desired directory.
        pod 'ThingSmartCryption', :path =>'./'
        pod 'ThingSmartHomeKit'
        // Extension API
        pod 'ThingSmartBusinessApiExtensionKit'
    end
    
  2. In the root directory of your project, run pod update.

Core advantages

  • Four time granularities: Offer 15-minute, hourly, daily, and monthly intervals to meet various chart requirements.
  • Flexible statistical types: Support 7 statistical types, including sum, maximum, minimum, and average values.
  • Intelligent data imputation: Automatically fill missing data points to ensure chart continuity.
  • Out-of-the-box: Minimalist design, ready to use without initialization.

Overview

Data statistics across four time granularities

Time granularity Typical use case Data points
15 minutes Real-time monitoring, detailed analytics 96 points/day
Hourly Intra-day trends, hourly comparison 24 points/day
Daily Weekly/Monthly reports Custom range
Monthly Annual reports, long-term trends Custom range

Seven statistical types (StatType enum)

Statistical type Enum value Description Scenario
SUM sum Summation Total energy consumption, usage statistics
MAX max Maximum value Peak analytics, maximum temperature
MIN min Minimum value Valley analytics, minimum temperature
AVG avg Average value Average power, average temperature
MINUX minux Differential value Increment calculation
COUNT count Count Switch cycles, trigger events
RECENT recent Most recent value Real-time status (hourly only)

API description

Get statistics at 15-minute intervals

Feature description

Get device data statistics at 15-minute intervals within a single day, suitable for real-time monitoring charts and detailed data analytics.

Data characteristics

  • 96 data points per day (24 hours × 4)
  • Time format: YYYYMMDDhhmm. For example, 202411130000 and 202411130015.
  • Ideal for: Line charts and bar charts.
/**
 Get 15-minute DP statistics for device

 @param devId Device ID
 @param dpId Data point ID
 @param date Date time, format: 20210601
 @param correction Data correction mode: 0=fill with 0 for missing data, 1=use previous time point data for missing data, 2=fill with # for missing data
 @param type Statistical type, e.g., sum, max, min (lowercase letters)
 @param keepScalaPoint Whether to keep decimal places according to DP point scaling factor, e.g., if scaled by 1000, choosing true will keep 3 decimal places
 @param success Success callback
 @param failure Failure callback
 */
+ (void)get15minDpStatisticWithDevId:(NSString *)devId
                                dpId:(NSString *)dpId
                                date:(NSString *)date
                          correction:(NSUInteger)correction
                                type:(NSString *)type
                      keepScalaPoint:(BOOL)keepScalaPoint
                             success:(void(^)(NSDictionary *retData))success
                             failure:(void(^)(NSError *error))failure;

Parameter description

Parameter Type Required Default value Description
devId String Yes - The device ID obtained from the device object.
dpId String Yes - The ID of the specified data point.
date String Yes - The query date in a format like 20241113.
type String No sum The statistical type. It is recommended to use StatType enum.
correction NSUInteger No 0
  • 0: Fill with 0.
  • 1: Fill with previous value. 
  • 2: Fill with #.
keepScalaPoint Boolean No false Specifies whether to retain decimal points.
success successBlock - - The success callback.
failure failureBlock - - The failure callback.

Example

Scenario: Draw a line chart of today’s electricity consumption at a 15-minute interval.

// Get today's date
let formatter = DateFormatter()
formatter.dateFormat = "yyyyMMdd"
let today = formatter.string(from: Date())

// Call the 15-minute statistics interface
ThingSmartBusinessRequest.get15minDpStatistic(
    withDevId: deviceId,
    dpId: "101",  // Assume 101 is the power consumption DP
    date: today,
    correction: 0,  // Fill with 0 when no data is available
    type: "sum",
    keepScalaPoint: true,  // Retain decimal places
    success: { retData in
        // Parse data points
        guard let result = retData?["result"] as? [String: String] else { return }
        // Draw a chart
        self.drawLineChart(with: result)
    },
    failure: { error in
        print("Loading failed:  \(error?.localizedDescription ?? "")")
    }
)

Example of returned data

{
  "result": {
    "202411130000": "12.34",
    "202411130015": "11.89",
    "202411130030": "13.45",
    "202411130045": "12.01",
    "202411130100": "14.23",
    "202411130115": "13.67",
    ...
    "202411132345": "10.12"
  },
  "t": 1699862400000,
  "success": true,
  "status": "ok"
}

Data description

  • A total of 96 time points (15 minutes × 96 = 24 hours)
  • Key: Timestamp (YYYYMMDDhhmm)
  • Value: Statistical value (string format)

Get hourly statistics

Feature description

Get device data statistics aggregated by hour within a single day. This is the most commonly used chart data interface.

Data characteristics

  • 24 data points per day.
  • Time format: YYYYMMDDhh. For example, 2024111300 and 2024111301.
  • Ideal for: Intraday trend charts and bar comparison charts.
/**
 Get hourly DP statistics for device

 @param devId Device ID
 @param dpId Data point ID
 @param date Date time, format: 20210601
 @param correction Data correction mode: 0=fill with 0 for missing data, 1=use previous time point data for missing data, 2=fill with # for missing data
 @param type Statistical type, e.g., sum, max, min (lowercase letters)
 @param keepScalaPoint Whether to keep decimal places according to DP point scaling factor, e.g., if scaled by 1000, choosing true will keep 3 decimal places
 @param success Success callback
 @param failure Failure callback
 */
+ (void)getHourDpStatisticWithDevId:(NSString *)devId
                               dpId:(NSString *)dpId
                               date:(NSString *)date
                         correction:(NSUInteger)correction
                               type:(NSString *)type
                     keepScalaPoint:(BOOL)keepScalaPoint
                            success:(void(^)(NSDictionary *retData))success
                            failure:(void(^)(NSError *error))failure;

Parameter description

Parameter Type Required Default value Description
devId String Yes - The device ID obtained from the device object.
dpId String Yes - The ID of the specified data point.
date String Yes - The query date in a format like 20241113.
type String No sum The statistical type. It is recommended to use StatType enum.
correction NSUInteger No 0
  • 0: Fill with 0.
  • 1: Fill with previous value. 
  • 2: Fill with #.
keepScalaPoint Boolean No false Specifies whether to retain decimal points.
success successBlock - - The success callback.
failure failureBlock - - The failure callback.

Example

Scenario: Draw today’s 24-hour temperature curve.

// Call the hourly statistics interface
ThingSmartBusinessRequest.getHourDpStatistic(
    withDevId: deviceId,
    dpId: "102",
    date: "20241113",
    correction: 1, // Fill the gap with the previous value
    type: "avg",  // Use the average temperature
    keepScalaPoint: true,
    success: { retData in
        // Analyze and plot the temperature curve
        guard let result = retData?["result"] as? [String: String] else { return }
        self.drawTemperatureChart(with: result)
    },
    failure: { error in
        print("Loading failed: \(error?.localizedDescription ?? "")")
    }
)

Example of returned data

{
  "result": {
    "2024111300": "22.5",
    "2024111301": "22.3",
    "2024111302": "22.1",
    ...
    "2024111323": "21.8"
  },
  "t": 1699862400000,
  "success": true,
  "status": "ok"
}

Get daily statistics

Feature description

Get device data statistics aggregated by day within a specified date range, suitable for weekly and monthly reports.

Data characteristics

  • Supports querying across any number of days.
  • Time format: YYYYMMDD. For example, 20241101 and 20241102.
  • Ideal for: Weekly trend charts and monthly comparison charts.
/**
 Get daily DP statistics for device

 @param devId Device ID
 @param dpId Data point ID
 @param startDay Start date, format: 20210601
 @param endDay End date, format: 20210605
 @param correction Data correction mode: 0=fill with 0 for missing data, 1=use previous time point data for missing data, 2=fill with # for missing data
 @param type Statistical type, e.g., sum, max, min (lowercase letters)
 @param keepScalaPoint Whether to keep decimal places according to DP point scaling factor, e.g., if scaled by 1000, choosing true will keep 3 decimal places
 @param success Success callback
 @param failure Failure callback
 */
+ (void)getDayDpStatisticWithDevId:(NSString *)devId
                              dpId:(NSString *)dpId
                          startDay:(NSString *)startDay
                            endDay:(NSString *)endDay
                        correction:(NSUInteger)correction
                              type:(NSString *)type
                    keepScalaPoint:(BOOL)keepScalaPoint
                           success:(void(^)(NSDictionary *retData))success
                           failure:(void(^)(NSError *error))failure;

Parameter description

Parameter Type Required Default value Description
devId String Yes - The device ID obtained from the device object.
dpId String Yes - The ID of the specified data point.
startDay String Yes - The start date, in the format YYYYMMDD.
endDay String Yes - The end date, in the format YYYYMMDD.
type String No sum The statistical type. It is recommended to use StatType enum.
correction NSUInteger No 0
  • 0: Fill with 0.
  • 1: Fill with previous value. 
  • 2: Fill with #.
keepScalaPoint Boolean No false Specifies whether to retain decimal points.
success successBlock - - The success callback.
failure failureBlock - - The failure callback.

Example

Scenario: Draw a bar chart of this week’s 7-day electricity consumption.

// Calculate the date range
let formatter = DateFormatter()
formatter.dateFormat = "yyyyMMdd"

let today = Date()
let endDay = formatter.string(from: today)

let weekAgo = today.addingTimeInterval(-6 * 24 * 60 * 60)
let startDay = formatter.string(from: weekAgo)

// Call the daily statistics interface
ThingSmartBusinessRequest.getDayDpStatistic(
    withDevId: deviceId,
    dpId: "101",
    startDay: startDay,  // 7 days ago
    endDay: endDay,  // Today
    correction: 0,
    type: "sum",
    keepScalaPoint: true,
    success: { retData in
        // Parse weekly data
        guard let resultDict = retData?["result"] as? [String: Any],
              let result = resultDict["result"] as? [String: String] else { return }
        self.drawWeeklyBarChart(with: result)
    },
    failure: { error in
        print("Failed to load weekly data:  \(error?.localizedDescription ?? "")")
    }
)

Example of returned data

{
  "result": {
    "result": {
      "20241107": "45.67",
      "20241108": "52.34",
      "20241109": "48.90",
      "20241110": "51.23",
      "20241111": "49.56",
      "20241112": "53.78",
      "20241113": "47.89"
    },
    "min": "20241113"
  },
  "t": 1699862400000,
  "success": true,
  "status": "ok"
}

Get monthly statistics

Feature description

Get device data statistics aggregated by month within a specified month range, suitable for annual reports and long-term trend analytics.

Data characteristics

  • Supports querying across any month range.
  • Time format: YYYYMM. For example, 202401 and 202402.
  • Ideal for: Annual trend charts and monthly comparison charts.
/**
 Get monthly DP statistics for device

 @param devId Device ID
 @param dpId Data point ID
 @param startMonth Start month, format: 202105
 @param endMonth End month, format: 202107
 @param correction Data correction mode: 0=fill with 0 for missing data, 1=use previous time point data for missing data, 2=fill with # for missing data
 @param type Statistical type, e.g., sum, max, min (lowercase letters)
 @param keepScalaPoint Whether to keep decimal places according to DP point scaling factor, e.g., if scaled by 1000, choosing true will keep 3 decimal places
 @param success Success callback
 @param failure Failure callback
 */
+ (void)getMonthDpStatisticWithDevId:(NSString *)devId
                                dpId:(NSString *)dpId
                          startMonth:(NSString *)startMonth
                            endMonth:(NSString *)endMonth
                          correction:(NSUInteger)correction
                                type:(NSString *)type
                      keepScalaPoint:(BOOL)keepScalaPoint
                             success:(void(^)(NSDictionary *retData))success
                             failure:(void(^)(NSError *error))failure;

Parameter description

Parameter Type Required Default value Description
devId String Yes - The device ID obtained from the device object.
dpId String Yes - The ID of the specified data point.
startMonth String Yes - The start month, in the format YYYYMM.
endMonth String Yes - The end month, in the format YYYYMM.
type String No sum The statistical type. It is recommended to use StatType enum.
correction NSUInteger No 0
  • 0: Fill with 0.
  • 1: Fill with previous value. 
  • 2: Fill with #.
keepScalaPoint Boolean No false Specifies whether to retain decimal points.
success successBlock - - The success callback.
failure failureBlock - - The failure callback.

Example

Scenario: Draw a comparison chart of this year’s 12-month electricity consumption.

// Get the current year
let calendar = Calendar.current
let currentYear = calendar.component(.year, from: Date())

let startMonth = String(format: "%d01", currentYear)
let endMonth = String(format: "%d12", currentYear)

// Call the monthly statistics interface
ThingSmartBusinessRequest.getMonthDpStatistic(
    withDevId: deviceId,
    dpId: "101",
    startMonth: startMonth,
    endMonth: endMonth,
    correction: 0,
    type: "sum",
    keepScalaPoint: true,
    success: { retData in
        // Parse annual data
        guard let resultDict = retData?["result"] as? [String: Any],
              let result = resultDict["result"] as? [String: String] else { return }
        self.drawYearlyChart(with: result)
    },
    failure: { error in
        print("Failed to load annual data: \(error?.localizedDescription ?? "")")
    }
)

Example of returned data

{
  "result": {
    "result": {
      "202401": "1234.56",
      "202402": "1156.78",
      "202403": "1289.90",
      "202404": "1345.67",
      "202405": "1298.45",
      "202406": "1423.89",
      "202407": "1567.23",
      "202408": "1489.01",
      "202409": "1376.54",
      "202410": "1298.76",
      "202411": "1234.00",
      "202412": "0"
    },
    "min": "202412"
  },
  "t": 1699862400000,
  "success": true,
  "status": "ok"
}