Skip to main content

Analytics screen integration (web + Flutter)

This page is for the frontend engineers building the Analytics screens. It covers the mobile design's Step 5 screens 39–41, the device selector sheet (40) and the Energy Rates sheet (39f).

It explains what to send for each screen state, how to map every field of the reply onto the design, and which edge cases the backend already handles for you.

:::warning Same gaps as the rest of the gateway userId is an unverified claim and there is no TLS at the dev tier. See Known gaps. Analytics adds nothing new here, but it does expose a user's production history to anyone who knows their userId. :::

The model in one paragraph​

Each Analytics screen state — a period tab, a date and a device selection — is one get_analytics request on the same WebSocket connection the rest of the app uses. The reply carries everything that state draws: the summary tiles, the Production / Consumption cards, the chart (with per-bar revenue), the partial-data banner, the money estimate and, on the Total tab, Operation Statistics.

There is no push and no subscription. Re-request when the user changes something, or on a timer while the Day view of today is on screen.

The backend does the aggregation, the local-day arithmetic, the plant totals and the money maths. The app formats and draws.

1. Building the request​

{
"type": "get_analytics",
"requestId": "a-17",
"userId": "<signed-in user id>",
"plantId": "<selectedPlantId>",
"timezone": "Asia/Karachi",
"period": "day",
"date": "2025-08-12",
"deviceKey": null,
"view": "inverter",
"rates": { "currency": "PKR", "buy": 65.0, "export": 40.0 }
}
UI stateSend
Plant opened from the tab bar (default)plantId = selectedPlantId, deviceKey omitted or null, view omitted
Day tabperiod: "day", date: "YYYY-MM-DD" (the pager's day; today by default)
Month tabperiod: "month", month: "YYYY-MM"
Year tabperiod: "year", year: "YYYY" (a number is accepted too, but send the string)
Custom tab (calendar)period: "custom", from / to as "YYYY-MM-DD", both inclusive
Selector → an inverter (40, 41)deviceKey = <that inverter's deviceKey from get_devices>
Selector → a battery (40)deviceKey = <deviceKey of the battery's parent inverter>, view: "battery"
Selector → Entire Plantdrop deviceKey (and view)
Historical Data screen (one inverter), Month / Year / Total tabsplantId omitted, deviceKey = <the inverter's deviceKey>, period: "month" / "year" / "total" — see below

Rules to respect:

  • timezone is always the user's saved IANA zone name, for example "Asia/Karachi". Never send a UTC offset such as "+05:00": it is refused with invalid_timezone.
  • Dates are the user's local calendar dates in that zone. Build them from the zone, not from the phone's clock zone if the two differ.
  • plantId or deviceKey is required. plantId: "all" is refused. The Analytics scope never writes the global selectedPlantId; the device selector is a local filter, as the design's state contract says.
  • Device-only scope. Omitting plantId and sending a deviceKey reads that one inverter, for any device the user owns, including one that has no plant. It is what the per-inverter Historical Data screen's Month, Year and Total tabs use. A device the user does not own (or a made-up logger id) is device_not_found. Its scope.plantId is "", and it never records the plant's timezone.
  • period: "total" takes no date field. It returns one bar per calendar year (series.grain: "year", date: "YYYY"), from the first year with stored energy to the current year, which includes today. A year with no data in between is a bar of nulls. Last year's bar can still change during the first few days of January, as the last days of December are finalised, just as the Year view's December does. History starts when the device's energy was first rolled up (late September 2026 at the earliest, or up to 4 months earlier where an operator ran the backfill), not at the inverter's installation.
  • Historical Data filter mapping. The six Month / Year / Total checkboxes map to generated (Production), gridExport (Grid Feed-in), consumed (Consumption), gridImport (Electricity Purchasing), batteryCharge (Charging Capacity) and batteryDischarge (Discharging Capacity). Every reply carries all six, so the checkboxes filter client-side; disable a checkbox whose capabilities flag is false.
  • Meters are not supported. Hide the "Meters" group in the selector sheet. Batteries need their parentDeviceId (from cse-http-be's device record) to find the inverter's loggerId.
  • rates come from the plant record in cse-http-be:
    • buy comes from electricityRate.amountPerKwh.
    • export comes from the export rate, once cse-http-be stores one. Send null until then.
    • Send null for a rate the user has not set.
    • Omit rates entirely only if you never want the Financial Summary.
  • period must not start in the future. The current month or year is clipped to today automatically. A custom to may not be after today, and the range may not be longer than 5 years; disable those dates in the calendar.

2. Mapping the reply onto the screens​

Energy Summary card (39, 39c, 41)​

TileFieldNotes
GENERATEDsummary.generatedKwh
CONSUMEDsummary.consumedKwh
GRID IMPORTsummary.gridImportKwh
GRID EXPORTsummary.gridExportKwhIf capabilities.gridExport is false, show BATTERY CHARGED (summary.batteryChargeKwh) in this slot instead — screen 39d
"1 unit = 1 kWh"static
"Peak solar 11.06 kW" (Day)summary.peakPvW ÷ 1000Time of the peak is summary.peakPvAt (UTC); null when the peak is 0 W
"Best day 44.6 kWh" (Month) / best month (Year)summary.best.generatedKwh, summary.best.datedate is YYYY-MM-DD for a best day, YYYY-MM for a best month
Header "12 Aug", "Aug 2025", "12 Aug · partial"period.from/period.to, plus completeness.partial

The pager subtitle "1–12 Aug so far" is period.from..period.to while period.isCurrent is true.

Chart (39, 39c, 41)​

The shape depends on series.grain.

"15m" — a Day, or a custom range of a single day. The chart is a power curve and series.unit is "W".

  • series.points[] has one entry per 15-minute slot that has data, with t as the slot's UTC start. Plot it at t converted to period.timezone, on a 00–24 axis for that local date.
  • Each point carries pv (Solar chip), load (Load), batteryCharge and batteryDischarge (Battery), gridImport (Import) and gridExport (Export).
  • Draw Import solid and Export dashed. They are always separate, non-negative series; never merge them into one signed Grid line.
  • A missing slot is a gap (device offline). Do not interpolate across a long gap, and do not draw it as zero.
  • A series whose capability is false is null in every point. Hide its chip.

"day" — a Month, or a custom range of up to 92 days. The chart is bars and series.unit is "kWh".

  • There is one point per local date in the period, date = YYYY-MM-DD, including days with no data (all fields null). Draw those as an empty slot, not a zero bar.
  • The same chips pick generated, consumed, gridImport, gridExport, batteryCharge and batteryDischarge.

"month" — a Year, or a custom range longer than 92 days. The shape is the same as "day", but date is YYYY-MM.

The caption "Daily generation, 1–12 Aug" comes from the grain and the period.

Production and Consumption cards​

summary.production (To Load · To Battery · To Grid) and summary.consumption (From Solar · From Battery · From Grid), for every period in the inverter view:

Card rowField
Production · To Loadsummary.production.toLoadKwh
Production · To Batterysummary.production.toBatteryKwh
Production · To Gridsummary.production.toGridKwh
Consumption · From Solarsummary.consumption.fromSolarKwh
Consumption · From Batterysummary.consumption.fromBatteryKwh
Consumption · From Gridsummary.consumption.fromGridKwh
  • The three rows add up to the card's headline exactly (to 0.01 kWh) when every part is non-null: To Battery / To Grid and From Battery / From Grid are measured, and To Load / From Solar are the remainder (they absorb conversion losses, so To Load and From Solar can differ). Shares computed from them total 100 %.
  • A null row is "not measurable" (an IP20 has no battery power, so only To Load / From Solar are known, as measured — the rows then don't add up), or "this period includes a day with energy stored before the breakdown existed". Show "—", never 0. A null headline (generatedKwh / consumedKwh) always comes with null rows.
  • On a mixed plant, coverage["production.toBatteryKwh"] etc. says a row covers only some inverters; the rows then don't add up either.

Revenue bars​

Each "day", "month" and "year" point carries revenue: that bar's money estimate, priced like financial (self-used × buy + export × export rate). Draw it on the PKR axis for the Estimated Revenue option. It is null wherever financial is (rates omitted or both rates null, device scope, battery view) and on a bar with no energy — draw no bar.

Operation Statistics (Total tab)​

lifetime, present for period: "total" in the inverter view:

RowFieldNotes
Running Dayslifetime.runningDaysCounted from lifetime.since (the first stored sample), today included; 0 before any data
Total Productionlifetime.generatedKwhThe same stored history as the Total summary.generatedKwh; 0 when there is none
Total Grid Feed-inlifetime.gridExportKwhSame as summary.gridExportKwh; 0 when there is none
Profit Estimatelifetime.financial.totalPlant scope with rates only
CO₂ Reductionlifetime.co2AvoidedKggeneratedKwh × co2KgPerKwh; the factor is set on the server and echoed
Equivalent trees plantedlifetime.treesEquivalent⌊co2AvoidedKg ÷ co2KgPerTree⌋

Every lifetime number is a number, never null: no data is 0. Only since can be null (nothing stored yet), and financial is null when no rates were sent.

Where data starts​

dataStartsAt is the earliest stored sample. When the period starts before it, notices has {"code": "NO_DATA_BEFORE", "from": ...}: grey the bars before that date out as "no data stored", not as zero production. A period that ends before it (or any period, when nothing is stored yet) has unavailable: [{"block": "all", "reason": "NO_DATA"}] and completeness.partial: false — show "No data for this period", not the "Data May Be Incomplete" banner.

A Day inside the last 4 months with no 15-minute readings has unavailable: [{"block": "series", "reason": "NO_READINGS"}]: show the day's totals with "No detailed data for this day" in place of the chart.

last7Days is no longer sent.

Partial data (39b)​

completeness.partial === true shows the "Data May Be Incomplete" banner.

  • Banner text: name the inverter(s) in completeness.missing[]. Match deviceKey to the device list for the name. Use lastSampleAt (UTC, show in the plant zone) for "stopped reporting at 11:42 AM". It is null for a device that has never reported.
  • "2 of 3 reporting" is devicesReporting of devicesExpected. Both count inverters.
  • "12 Aug · partial", the "Values exclude …" note and the Financial Summary's "Partial period" label all come from the same partial flag.
  • Meaning of "reporting": while period.isCurrent, an inverter is reporting if it was seen in the last 15 minutes. For a finished period, it is reporting if it recorded anything in that period.
  • What the totals contain: they include everything each inverter recorded. An inverter that stopped at 11:42 contributes its energy up to 11:42. When it comes back, the energy it made while offline is added to the day it reconnects.

Coverage (mixed plants)​

coverage appears only when a plant mixes inverter models and some cannot report a metric. For example, {"gridExportKwh": {"devices": 1, "of": 2}} means the export figure is the sum of one inverter out of two.

Show a small "1 of 2 inverters" qualifier next to that tile. When coverage is absent, every figure covers every reporting inverter.

Financial Summary (39, 39b, 39c, 39d, 39e)​

financial is null in device scope and in the battery view (screen 41 has no money block), and when you did not send rates.

DesignField
PKR 3,031 "Total Benefit"financial.total
Electricity Savingsfinancial.savings (= selfUsedKwh × buy)
Export Creditfinancial.exportCredit (= gridExportKwh × export)
"Buy 65 · Export 40 PKR/unit"the rates you sent (not echoed back, apart from currency)
"Savings cover the 39.0 kWh of solar used on site; export credit covers the 12.4 kWh sent to the grid."financial.selfUsedKwh, summary.gridExportKwh
"Estimated" / "Partial period" / "Rates needed" labelcompleteness.partial, or a null figure because its rate is missing
  • A missing rate never produces PKR 0. If savings is null because buy was null, show "Set electricity rate ›". If exportCredit is null because export was null, show "Set export rate ›" (39e). Draw nothing for a null figure.
  • Export not reported (capabilities.gridExport === false, 39d): exportCredit is null for that reason, not because a rate is missing. Hide the export row and the export rate instead of showing "Set export rate", and show "Solar used on site" (financial.selfUsedKwh).
  • total is the sum of the non-null parts. If both are null, it is null and the headline is replaced by the call to action.
  • Energy Rates sheet (39f): save the rates to cse-http-be (the plant owns them), then resend the current get_analytics with the new rates. The backend stores no rate.

Battery view​

Send view: "battery" with the parent inverter's deviceKey.

  • Summary: only batteryChargeKwh and batteryDischargeKwh are set.
  • Series: batteryCharge and batteryDischarge (W), plus soc (%) in 15-minute points. Everything else is null.
  • Absent blocks: there is no financial, production, consumption or lifetime.
  • No battery data: if capabilities.battery is false, the inverter reports no battery data. Hide that battery in the selector rather than opening an empty screen.

3. Nulls, zeros and capabilities​

This is the one rule that matters most:

ValueMeaningRender
a number, including 0measuredthe number (a real 0.0 kWh is valid)
null, capability truesupported, but no data for this slot/day/perioda gap or "—"
null, capability falsethis inverter model cannot report ithide the tile, chip or row

capabilities flags:

  • generation, load, gridImport, gridExport and battery gate tiles and chips.
  • batteryPower and gridPower gate the power chart's Battery, Import and Export series.
  • batterySoc gates the battery view's SOC line.

Current models:

ModelSupportedNot supported
Aotai Hybrideverything—
IP20 2–12 kWenergy tiles, in whole kWh (the inverter's counters have 1 kWh resolution, so small daily flows show as 0 or 1)batteryPower (the Battery power series stays empty until its sign is verified on hardware)
IP20 3K6/5K (since 2026-11-23)generation, load, gridImport (energy drawn from the mains), in 0.01 kWh steps. batteryPower, battery and batterySoc: battery power is the BMS's V × I, so the Battery series and battery charge/discharge energy (integrated from it) appear only while a BMS reportsgridExport (the protocol has no export reading). Since 2026-11-24 gridPower is supported, but the Import series is an estimate (load in Line mode + the mains share of charging), because the protocol has no grid power reading; see the protocol page

4. Freshness, retention, errors​

  • Refreshing today. Stored telemetry is every 5 minutes. While the Day view of today is visible, re-request about every 5 minutes. Other periods only change after midnight. dataAsOf is the newest reading included.
  • Yesterday settles early the next morning. Past days are finalised at 00:30 local and re-checked at +6 h and +24 h, so yesterday's figure can still rise slightly then if an inverter was catching up.
  • Day views older than 4 months return totals but no chart. unavailable contains {"block": "series", "reason": "PERIOD_OUTSIDE_RETENTION"}. Show the summary with a "Detailed chart not available for this date" note.
  • One request in flight per connection. Replies carry your requestId. When the user taps quickly through periods, keep only the latest requestId and ignore older replies. A request sent while another is running on the same connection gets code: "busy" straight away. When the whole gateway is saturated, a request waits (up to its 5 s budget) for a slot before answering busy.
  • Debounce pager taps (about 250 ms) and send only the settled state. Resend on busy after the in-flight reply arrives.
  • Errors arrive as ok: false with a code:
codeApp action
invalid_request, invalid_period, invalid_timezone, invalid_ratesA client bug (or, for invalid_request "more than 50 inverters", a data problem): log it and show a generic error. These never fix themselves on retry. A frame with a wrongly typed field still gets this reply, with your requestId.
device_not_in_plantThe device list is stale (device moved or deleted): refresh get_devices, fall back to Entire Plant.
device_not_foundDevice-only scope: the device is not this user's (or no longer exists). Refresh get_devices and leave the screen.
busyRetry once the in-flight reply is in, or after about 1 s.
timeout, unavailable, internalShow "Couldn't load analytics — Retry", with exponential backoff; never an infinite loop.
  • userId must be the user's UUID (the cse-http-be user id); anything else is invalid_request.
  • A plant with no inverters returns ok: true with completeness.devicesExpected: 0 and every figure null. Show the design's "No Plant Selected" / add-device empty state (36).

5. Types​

TypeScript​

type Kwh = number | null;
type Watts = number | null;

interface AnalyticsRequest {
type: "get_analytics";
requestId?: string;
userId: string;
plantId?: string; // omit for the device-only scope
timezone: string; // IANA, e.g. "Asia/Karachi"
period: "day" | "month" | "year" | "total" | "custom";
date?: string; month?: string; year?: string; from?: string; to?: string;
deviceKey?: string | null;
view?: "inverter" | "battery";
rates?: { currency?: string; buy: number | null; export: number | null } | null;
}

interface PowerPoint { t: string; pv: Watts; load: Watts; batteryCharge: Watts;
batteryDischarge: Watts; gridImport: Watts; gridExport: Watts; soc: number | null; }
interface EnergyPoint { date: string; generated: Kwh; consumed: Kwh; gridImport: Kwh;
gridExport: Kwh; batteryCharge: Kwh; batteryDischarge: Kwh; revenue: number | null; }

interface AnalyticsReply {
type: "analytics"; ok: boolean; requestId?: string; code?: string; error?: string;
scope?: { plantId: string; deviceKey: string | null; view: "inverter" | "battery" };
period?: { kind: string; from: string; to: string; timezone: string;
grain: "15m" | "day" | "month" | "year"; isCurrent: boolean; complete: boolean };
capabilities?: { generation: boolean; load: boolean; gridImport: boolean; gridExport: boolean;
battery: boolean; batteryPower: boolean; gridPower: boolean; batterySoc: boolean };
coverage?: Record<string, { devices: number; of: number }>;
summary?: { generatedKwh: Kwh; consumedKwh: Kwh; gridImportKwh: Kwh; gridExportKwh: Kwh;
batteryChargeKwh: Kwh; batteryDischargeKwh: Kwh; selfUsedKwh: Kwh;
peakPvW: Watts; peakPvAt: string | null;
best: { date: string; generatedKwh: number } | null;
production?: { toLoadKwh: Kwh; toBatteryKwh: Kwh; toGridKwh: Kwh };
consumption?: { fromSolarKwh: Kwh; fromBatteryKwh: Kwh; fromGridKwh: Kwh } };
series?: { grain: "15m"; unit: "W"; points: PowerPoint[] }
| { grain: "day" | "month" | "year"; unit: "kWh"; points: EnergyPoint[] };
lifetime?: { since: string | null; runningDays: number; generatedKwh: number;
gridExportKwh: number; co2KgPerKwh: number; co2AvoidedKg: number;
co2KgPerTree: number; treesEquivalent: number;
financial: { currency?: string; selfUsedKwh: Kwh; savings: number | null;
exportCredit: number | null; total: number | null } | null };
completeness?: { partial: boolean; devicesExpected: number; devicesReporting: number;
missing: { deviceKey: string; lastSampleAt: string | null }[] };
financial?: { currency?: string; selfUsedKwh: Kwh; savings: number | null;
exportCredit: number | null; total: number | null } | null;
dataAsOf?: string | null;
dataStartsAt?: string | null;
unavailable?: { block: string; reason: string }[];
notices?: { code: string; from?: string }[];
}

Sending it and keeping only the latest reply (web)​

let latest = 0;
function requestAnalytics(ws: WebSocket, req: Omit<AnalyticsRequest, "type" | "requestId">) {
const requestId = `a-${++latest}`;
ws.send(JSON.stringify({ type: "get_analytics", requestId, ...req }));
return requestId;
}

ws.addEventListener("message", (ev) => {
const msg = JSON.parse(ev.data);
if (msg.type !== "analytics") return;
if (msg.requestId !== `a-${latest}`) return; // a stale reply for an older tap
if (!msg.ok) return showAnalyticsError(msg.code, msg.error);
render(msg as AnalyticsReply);
});

Flutter (Dart)​

class AnalyticsClient {
AnalyticsClient(this._send);
final void Function(Map<String, dynamic>) _send; // your shared connection's send
int _seq = 0;
String? _latest;

void request({
required String userId, required String plantId, required String timezone,
required String period, String? date, String? month, String? year,
String? from, String? to, String? deviceKey, String view = 'inverter',
double? buyRate, double? exportRate, String currency = 'PKR',
}) {
_latest = 'a-${++_seq}';
_send({
'type': 'get_analytics', 'requestId': _latest,
'userId': userId, 'plantId': plantId, 'timezone': timezone,
'period': period,
if (date != null) 'date': date, if (month != null) 'month': month,
if (year != null) 'year': year, if (from != null) 'from': from, if (to != null) 'to': to,
if (deviceKey != null) 'deviceKey': deviceKey, 'view': view,
'rates': {'currency': currency, 'buy': buyRate, 'export': exportRate},
});
}

/// Returns the reply if it is the latest one, else null (drop it).
Map<String, dynamic>? accept(Map<String, dynamic> msg) =>
msg['type'] == 'analytics' && msg['requestId'] == _latest ? msg : null;
}

// num? → double?, keeping null distinct from 0.
double? kwh(dynamic v) => v == null ? null : (v as num).toDouble();

Format times with the plant zone, not the device's. package:timezone (tz.TZDateTime.from(DateTime.parse(t), tz.getLocation(timezone))) does this in Flutter; Intl.DateTimeFormat(..., { timeZone }) does it on the web.

6. Test checklist​

Walk through each design state against the dev gateway:

#StateHow to get itExpect
139 Day, whole plantdefaulttiles, power curve, Production/Consumption cards, Financial
239b partialpower one inverter's logger off for more than 15 minutesbanner, "N of M reporting", "partial" labels
339c MonthMonth tabdaily bars up to today, Best day, per-bar revenue with rates
439d no exportan inverter model without export (or a mocked gridExport: false)Battery Charged tile, no Export chip, no export credit
539e rates not setsend buy: null, export: null"Set … rate" rows, no PKR figure
639f rates savedsave in the sheet, then re-requestnew figures
740/41 one inverterpick an inverterdevice totals, no Financial Summary
8battery viewpick a batterycharge/discharge + SOC only
9YearYear tabmonthly bars Jan→current month, Best month
10Custom 1 day / 30 days / 6 monthscalendar15m curve / daily bars / monthly bars
11Old day (> 4 months)pager backsummary, "chart not available"
12Fast tappingtap the pager quicklyonly the latest reply renders; no busy shown to the user
13Bad inputsoffset timezone, future dateinvalid_timezone, invalid_period handled
14Timezonea user whose zone differs from the phone'sdays cut at the saved zone's midnight
15Total, Operation StatisticsTotal tablifetime running days, total production from the inverter counter, CO₂, trees
16Before data startsthe month containing the first stored day / a month before itnotices NO_DATA_BEFORE greys out the early bars / NO_DATA, no banner
17Day without readingsa day with totals but no 15-minute dataNO_READINGS, totals shown, no chart