# Statistics

> This interface depends on cloud capabilities and requires authorization configuration in the [Mini Program Developer Platform](https://iot.tuya.com/miniapp/)`Development Settings`-`Cloud Capabilities`. **<font color="red">📢Note: To use statistical capabilities, you need to submit a work order to enable product data statistics. Please [submit a quick work order](https://service.console.tuya.com/8/3/list?source=support_center) before use.</font>**

<Image src="/images/api/cloud/cloud_support.en.jpg" style={{width: 400}} />

## Interface Capabilities

For smart metering capabilities, we provide the following interface capabilities, which developers can directly call using the API to complete related business development.

**Note that the following APIs require the use of `@ray-js/ray^1.2.12`.**

| Interface Name         | Description                                                                                       |
| ---------------------- | ------------------------------------------------------------------------------------------------- |
| getStatisticsConfig    | Get the configuration information for statistical data                                            |
| getStatisticsRang15min | Get the statistics data for the device in the specified period with a time interval of 15 minutes |
| exportStatistics15min  | Export the statistics data for the device for a specified date with a time interval of 15 minutes |
| getStatisticsRangHour  | Get the statistics data for the device in the specified period with a time interval of 1 hour     |
| exportStatisticsHour   | Export the statistics data for the device in the specified period with a time interval of 1 hour  |
| getStatisticsRangDay   | Get the statistics data for the device in the specified period with a time interval of 1 day      |
| exportStatisticsDay    | Export the statistics data for the device in the specified period with a time interval of 1 day   |
| getStatisticsRangMonth | Get the statistics data for the device in the specified period with a time interval of 1 month    |
| exportStatisticsMonth  | Export the statistics data for the device for the past month                                      |
| resetStatistics        | Reset the statistics data for the device                                                          |

## Chart Component

### Installation

```bash
npm install @ray-js/stat-charts
```

### Component Props

| Name             | Type                                               | Required | Default                                                                                | Description                                                                                                                                               |
| ---------------- | -------------------------------------------------- | -------- | -------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- |
| style            | React.CSSProperties                                | No       |                                                                                        | The style of the chart container                                                                                                                          |
| devIdList        | `string[]`                                         | Yes      |                                                                                        | List of device IDs (not yet supported for multiple devices)                                                                                               |
| dpList           | `Dp[]`                                             | Yes      |                                                                                        | List of dp (data point) functions, representing the data dimensions for the chart. Format: `{ name: string, id: number }`                                 |
| range            | string                                             | Yes      |                                                                                        | Data range, representing a data point for the specified time unit, e.g., 15min, 1hour, 1day, 1month                                                       |
| type             | string                                             | No       | sum                                                                                    | Statistical type. See [Statistics Type Reference](#statistics-type-reference). e.g., avg, max, min, sum, count                                                                 |
| unit             | string                                             | Yes      |                                                                                        | Data unit, e.g., ℃, %, m                                                                                                                                  |
| startDate        | string                                             | Yes      |                                                                                        | Data start time, format: YYYYMMDD, e.g., 202305 20230522                                                                                                  |
| endDate          | string                                             | Optional | ''                                                                                     | Data end time, required for data ranges of 1day and 1month, format: YYYYMMDD                                                                              |
| renderTitle      | `({ data }) => React.ReactNode`                    | No       | ''                                                                                     | Customize the chart title                                                                                                                                 |
| renderFooter     | `({ data }) => React.ReactNode`                    | No       | ''                                                                                     | Customize the chart footer                                                                                                                                |
| theme            | string                                             | No       | light                                                                                  | Theme used for the chart, 'light' / 'dark'                                                                                                                |
| dataZoom         | number                                             | No       | 0                                                                                      | Display data zoom on the data axis, percentage value between `1~100` or `-100~-1`. Default is left, negative numbers represent the right side of the data |
| chartType        | string                                             | No       | line                                                                                   | Chart type, `line` / `bar` / `line-area`                                                                                                                  |
| width            | number                                             | No       | 654                                                                                    | Chart width in rpx                                                                                                                                        |
| height           | number                                             | No       | 422                                                                                    | Chart height in rpx                                                                                                                                       |
| placeholder      | `{ loading: string; error: string; none: string }` | No       | `{ loading: 'Loading...', error: 'Failed To Load', none: 'No data for this period…' }` | Placeholder text displayed in the center of the chart, based on the placeholderIcon state                                                                 |
| placeholderIcon  | string                                             | No       | loading                                                                                | Placeholder icon displayed when there is no data, can be 'loading', 'error', or 'none'                                                                    |
| placeholderYAxis | number                                             | No       | 10                                                                                     | Maximum value on the Y-axis when there is no data, 0 means the Y-axis is not displayed                                                                    |
| placeholderXAxis | `string[]`                                         | N        | `['6:00', '12:00', '18:00']`                                                           | X-axis labels when there is no data, if set to an empty array `[]`, the X-axis will not be displayed.                                                     |
| debug            | boolean                                            | N        | false                                                                                  | Whether to enable debugging mode? Enabling it will generate random data. Please do not use it in production mode.                                         |

#### Display yearly temperature statistics

```jsx
import StatCharts from '@ray-js/stat-charts';

<StatCharts
  devIdList={['vdevo168473759041567']} // Device ID
  dpList={[{ id: 27, name: 'Temperature' }]} // Data point ID and name
  unit="℃" // Data unit
  range="1month" // Data range, one point per month
  type="avg" // Statistical type, average value for the month
  startDate="202301" // Start date of data (January)
  endDate="202312" // End date of data (December)
  count={25} // Data to be displayed in the subtitle
  chartType={'line'} // Line chart
/>;
```

#### Calculate device energy consumption data

```jsx
<StatCharts
  devIdList={['vdevo168473759041567']}
  dpList={[
    { id: 27, name: 'Thermostat' },
    { id: 28, name: 'Ambient Light' },
  ]}
  unit="kwH" // Data unit in kilowatt hours
  range="15min" // Data range, one point every 15 minutes
  startDate="20230522" // Start date for data statistics (current day)
  dataZoom={-30} // Display data zoom on the right side of the data by default
  chartType="bar" // Bar chart
/>
```

<Image width={375} src="/images/panel/stat-charts.jpg"/>

## Explanation of the "type" Parameter in Statistical Interfaces for Chart-related Requirements

### Statistics Type Reference

> The time interval below is currently written as `1 hour`, but it can be replaced with `1 day` or `1 month`, which are supported.

#### sum

Sum the data reported within `1 hour` to get the **total** for that period. Use for cumulative values (e.g., energy consumption, water usage).

#### minux

Take the **maximum** value of data reported within `1 hour`, subtract the **maximum** of data reported in the **previous hour**, to get the **delta/usage** for this period. Use for meter/counter-style period usage (e.g., electricity or water usage per period).

- Tip: If there is no data for the `previous hour`, subtract the maximum reported data before that to obtain the data used for `this hour`.
- Tip: This type should have been named "minus," but due to a spelling mistake made initially (three years ago), it has been consistently used as `minux`.

#### avg

Sum the data reported within `1 hour`, then divide by the **number of reports** to get the **average** for that hour. Use for metrics where you need the average level (e.g., temperature, humidity).

#### min

The minimum value of data reported within `1 hour`. Use for lowest temperature, lowest power, valley power, etc.

#### max

The maximum value of data reported within `1 hour`. Use for peak temperature, peak power, peak load, etc.

#### count

The number of data reports within `1 hour`. Use for switch count, report frequency, event count, etc.

#### recent

The data point closest to the **hour boundary**. This type only supports hourly statistics, not daily or monthly. Use for charts that need one sample per hour aligned to the hour (e.g., line chart with one point per hour).

### Statistical Interval

#### Statistical by Hour

Simply put, it is to statistically analyze the data reported within `1 hour` based on the `statistical type` and then aggregate it into one point.

#### Statistical by Day

Simply put, it is to statistically analyze the data reported within `1 day` based on the `statistical type` and then aggregate it into one point.

#### Statistical by Month

Simply put, it is to statistically analyze the data reported within the month based on the `statistical type` and then aggregate it into one point.
