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.
- Wire protocol reference:
get_analyticsin the WebSocket guide. - Why it works this way: Analytics design.
- Whole-plant (combined) data for parallel inverters, including the
scopefield and thePARALLEL_SET_COMBINEDnotice: Parallel inverters: mobile app changes. - Connecting, reconnecting and the general message shape: WebSocket integration.
:::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 state | Send |
|---|---|
| Plant opened from the tab bar (default) | plantId = selectedPlantId, deviceKey omitted or null, view omitted |
| Day tab | period: "day", date: "YYYY-MM-DD" (the pager's day; today by default) |
| Month tab | period: "month", month: "YYYY-MM" |
| Year tab | period: "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 Plant | drop deviceKey (and view) |
| Historical Data screen (one inverter), Month / Year / Total tabs | plantId omitted, deviceKey = <the inverter's deviceKey>, period: "month" / "year" / "total" — see below |
Rules to respect:
timezoneis always the user's saved IANA zone name, for example"Asia/Karachi". Never send a UTC offset such as"+05:00": it is refused withinvalid_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.
plantIdordeviceKeyis required.plantId: "all"is refused. The Analytics scope never writes the globalselectedPlantId; the device selector is a local filter, as the design's state contract says.- Device-only scope. Omitting
plantIdand sending adeviceKeyreads 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) isdevice_not_found. Itsscope.plantIdis"", 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 ofnulls. 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) andbatteryDischarge(Discharging Capacity). Every reply carries all six, so the checkboxes filter client-side; disable a checkbox whosecapabilitiesflag isfalse. - 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'sloggerId. ratescome from the plant record in cse-http-be:buycomes fromelectricityRate.amountPerKwh.exportcomes from the export rate, once cse-http-be stores one. Sendnulluntil then.- Send
nullfor a rate the user has not set. - Omit
ratesentirely only if you never want the Financial Summary.
periodmust not start in the future. The current month or year is clipped to today automatically. A customtomay 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)
| Tile | Field | Notes |
|---|---|---|
| GENERATED | summary.generatedKwh | |
| CONSUMED | summary.consumedKwh | |
| GRID IMPORT | summary.gridImportKwh | |
| GRID EXPORT | summary.gridExportKwh | If 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 ÷ 1000 | Time 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.date | date 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, withtas the slot's UTC start. Plot it attconverted toperiod.timezone, on a 00–24 axis for that local date.- Each point carries
pv(Solar chip),load(Load),batteryChargeandbatteryDischarge(Battery),gridImport(Import) andgridExport(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
falseisnullin 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 fieldsnull). Draw those as an empty slot, not a zero bar. - The same chips pick
generated,consumed,gridImport,gridExport,batteryChargeandbatteryDischarge.
"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 row | Field |
|---|---|
| Production · To Load | summary.production.toLoadKwh |
| Production · To Battery | summary.production.toBatteryKwh |
| Production · To Grid | summary.production.toGridKwh |
| Consumption · From Solar | summary.consumption.fromSolarKwh |
| Consumption · From Battery | summary.consumption.fromBatteryKwh |
| Consumption · From Grid | summary.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
nullrow 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. Anullheadline (generatedKwh/consumedKwh) always comes withnullrows. - 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:
| Row | Field | Notes |
|---|---|---|
| Running Days | lifetime.runningDays | Counted from lifetime.since (the first stored sample), today included; 0 before any data |
| Total Production | lifetime.generatedKwh | The same stored history as the Total summary.generatedKwh; 0 when there is none |
| Total Grid Feed-in | lifetime.gridExportKwh | Same as summary.gridExportKwh; 0 when there is none |
| Profit Estimate | lifetime.financial.total | Plant scope with rates only |
| CO₂ Reduction | lifetime.co2AvoidedKg | generatedKwh × co2KgPerKwh; the factor is set on the server and echoed |
| Equivalent trees planted | lifetime.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[]. MatchdeviceKeyto the device list for the name. UselastSampleAt(UTC, show in the plant zone) for "stopped reporting at 11:42 AM". It isnullfor a device that has never reported. - "2 of 3 reporting" is
devicesReportingofdevicesExpected. Both count inverters. - "12 Aug · partial", the "Values exclude …" note and the Financial
Summary's "Partial period" label all come from the same
partialflag. - 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.
| Design | Field |
|---|---|
| PKR 3,031 "Total Benefit" | financial.total |
| Electricity Savings | financial.savings (= selfUsedKwh × buy) |
| Export Credit | financial.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" label | completeness.partial, or a null figure because its rate is missing |
- A missing rate never produces PKR 0. If
savingsisnullbecausebuywasnull, show "Set electricity rate ›". IfexportCreditisnullbecauseexportwasnull, show "Set export rate ›" (39e). Draw nothing for anullfigure. - Export not reported (
capabilities.gridExport === false, 39d):exportCreditisnullfor 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). totalis the sum of the non-null parts. If both arenull, it isnulland 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_analyticswith the newrates. The backend stores no rate.
Battery view
Send view: "battery" with the parent inverter's deviceKey.
- Summary: only
batteryChargeKwhandbatteryDischargeKwhare set. - Series:
batteryChargeandbatteryDischarge(W), plussoc(%) in 15-minute points. Everything else isnull. - Absent blocks: there is no
financial,production,consumptionorlifetime. - No battery data: if
capabilities.batteryisfalse, 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:
| Value | Meaning | Render |
|---|---|---|
a number, including 0 | measured | the number (a real 0.0 kWh is valid) |
null, capability true | supported, but no data for this slot/day/period | a gap or "—" |
null, capability false | this inverter model cannot report it | hide the tile, chip or row |
capabilities flags:
generation,load,gridImport,gridExportandbatterygate tiles and chips.batteryPowerandgridPowergate the power chart's Battery, Import and Export series.batterySocgates the battery view's SOC line.
Current models:
| Model | Supported | Not supported |
|---|---|---|
| Aotai Hybrid | everything | — |
| IP20 2–12 kW | energy 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 reports | gridExport (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.
dataAsOfis 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.
unavailablecontains{"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 latestrequestIdand ignore older replies. A request sent while another is running on the same connection getscode: "busy"straight away. When the whole gateway is saturated, a request waits (up to its 5 s budget) for a slot before answeringbusy. - Debounce pager taps (about 250 ms) and send only the settled state.
Resend on
busyafter the in-flight reply arrives. - Errors arrive as
ok: falsewith acode:
code | App action |
|---|---|
invalid_request, invalid_period, invalid_timezone, invalid_rates | A 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_plant | The device list is stale (device moved or deleted): refresh get_devices, fall back to Entire Plant. |
device_not_found | Device-only scope: the device is not this user's (or no longer exists). Refresh get_devices and leave the screen. |
busy | Retry once the in-flight reply is in, or after about 1 s. |
timeout, unavailable, internal | Show "Couldn't load analytics — Retry", with exponential backoff; never an infinite loop. |
userIdmust be the user's UUID (the cse-http-be user id); anything else isinvalid_request.- A plant with no inverters returns
ok: truewithcompleteness.devicesExpected: 0and every figurenull. 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:
| # | State | How to get it | Expect |
|---|---|---|---|
| 1 | 39 Day, whole plant | default | tiles, power curve, Production/Consumption cards, Financial |
| 2 | 39b partial | power one inverter's logger off for more than 15 minutes | banner, "N of M reporting", "partial" labels |
| 3 | 39c Month | Month tab | daily bars up to today, Best day, per-bar revenue with rates |
| 4 | 39d no export | an inverter model without export (or a mocked gridExport: false) | Battery Charged tile, no Export chip, no export credit |
| 5 | 39e rates not set | send buy: null, export: null | "Set … rate" rows, no PKR figure |
| 6 | 39f rates saved | save in the sheet, then re-request | new figures |
| 7 | 40/41 one inverter | pick an inverter | device totals, no Financial Summary |
| 8 | battery view | pick a battery | charge/discharge + SOC only |
| 9 | Year | Year tab | monthly bars Jan→current month, Best month |
| 10 | Custom 1 day / 30 days / 6 months | calendar | 15m curve / daily bars / monthly bars |
| 11 | Old day (> 4 months) | pager back | summary, "chart not available" |
| 12 | Fast tapping | tap the pager quickly | only the latest reply renders; no busy shown to the user |
| 13 | Bad inputs | offset timezone, future date | invalid_timezone, invalid_period handled |
| 14 | Timezone | a user whose zone differs from the phone's | days cut at the saved zone's midnight |
| 15 | Total, Operation Statistics | Total tab | lifetime running days, total production from the inverter counter, CO₂, trees |
| 16 | Before data starts | the month containing the first stored day / a month before it | notices NO_DATA_BEFORE greys out the early bars / NO_DATA, no banner |
| 17 | Day without readings | a day with totals but no 15-minute data | NO_READINGS, totals shown, no chart |