Real-time EV charging and battery monitoring with streaming SQL means connector availability, session health, site demand headroom, smart charging setpoints, short-horizon demand forecasts, and battery state of health are all maintained as materialized views that update with every OCPP status notification, meter value, tariff signal, and battery management system reading. This guide builds the operational layer of a charging network on RisingWave, a PostgreSQL-compatible streaming database, from fleet monitoring through smart charging control, demand forecasting, and battery health.
Why Charging Networks Need Streaming SQL
Drivers expect a charger to work when they arrive. A faulted connector undetected for 30 minutes means abandonment, one-star reviews, and lost revenue, and a soft fault, a station that reports Charging while delivering nothing, is worse because it is invisible to status polling. Static charging schedules and timer-based controls cannot keep a site inside its contracted demand limit when ten vehicles arrive at once, cannot shift load toward cheap intervals, and cannot answer a utility curtailment signal. Highway corridor demand is bursty, near zero for two hours and then ten 150 kW sessions at once. Battery packs degrade for months before state of health crosses the 80 percent replacement threshold, and a nightly recalculation leaves a day-long blind spot.
Every one of these is a current-state view, a windowed aggregate, or a join across streams. RisingWave maintains them incrementally, so only the affected connector, session, site, or vehicle row changes on each event, and serves them over the PostgreSQL protocol to the network operations center dashboard or through Kafka sinks to the charge point management system (CPMS) for setpoint execution. RisingWave is open source under Apache 2.0, written in Rust, and checkpoints state to S3.
Sources: OCPP Messages, Site Demand, Tariffs, Grid Signals, and Battery Telemetry
The CPMS forwards OCPP StatusNotification, MeterValues, and transaction messages to Kafka. The building energy management system publishes site demand. Tariff and utility demand response signals arrive on their own topics. Vehicles that report battery management system data through the charger publish battery telemetry.
CREATE SOURCE ocpp_status_notifications (
charge_point_id VARCHAR,
connector_id INTEGER,
site_id VARCHAR,
network_region VARCHAR,
status VARCHAR, -- Available, Preparing, Charging, SuspendedEV, SuspendedEVSE, Finishing, Reserved, Unavailable, Faulted
error_code VARCHAR, -- NoError, ConnectorLockFailure, EVCommunicationError, GroundFailure, HighTemperature, InternalError
vendor_error_code VARCHAR,
event_ts TIMESTAMPTZ
) WITH (connector = 'kafka', topic = 'ocpp.status.notifications', properties.bootstrap.server = 'kafka:9092', scan.startup.mode = 'latest')
FORMAT PLAIN ENCODE JSON;
CREATE SOURCE ocpp_meter_values (
charge_point_id VARCHAR,
connector_id INTEGER,
site_id VARCHAR,
transaction_id VARCHAR,
connector_type VARCHAR, -- 'CCS', 'CHAdeMO', 'Type2'
rated_power_kw DOUBLE PRECISION,
energy_kwh DOUBLE PRECISION, -- cumulative since session start
power_kw DOUBLE PRECISION,
voltage_v DOUBLE PRECISION,
current_a DOUBLE PRECISION,
soc_pct DOUBLE PRECISION,
sampled_ts TIMESTAMPTZ
) WITH (connector = 'kafka', topic = 'ocpp.meter.values', properties.bootstrap.server = 'kafka:9092', scan.startup.mode = 'latest')
FORMAT PLAIN ENCODE JSON;
CREATE SOURCE ocpp_transactions (
transaction_id VARCHAR,
charge_point_id VARCHAR,
connector_id INTEGER,
site_id VARCHAR,
connector_type VARCHAR,
id_tag VARCHAR,
start_ts TIMESTAMPTZ,
stop_ts TIMESTAMPTZ,
start_kwh DOUBLE PRECISION,
stop_kwh DOUBLE PRECISION,
stop_reason VARCHAR -- Local, Remote, EVDisconnected, HardReset, PowerLoss
) WITH (connector = 'kafka', topic = 'ocpp.transactions', properties.bootstrap.server = 'kafka:9092', scan.startup.mode = 'latest')
FORMAT PLAIN ENCODE JSON;
CREATE SOURCE site_demand (
site_id VARCHAR,
demand_limit_kw DOUBLE PRECISION, -- contracted cap
current_demand_kw DOUBLE PRECISION, -- building plus EV load
ev_load_kw DOUBLE PRECISION,
measured_ts TIMESTAMPTZ
) WITH (connector = 'kafka', topic = 'bems.site.demand', properties.bootstrap.server = 'kafka:9092', scan.startup.mode = 'latest')
FORMAT PLAIN ENCODE JSON;
CREATE SOURCE electricity_prices (
tariff_id VARCHAR,
site_id VARCHAR,
price_usd_kwh DOUBLE PRECISION,
price_tier VARCHAR, -- 'OFF_PEAK', 'MID_PEAK', 'ON_PEAK', 'CRITICAL_PEAK'
grid_load_pct DOUBLE PRECISION,
valid_from TIMESTAMPTZ,
valid_to TIMESTAMPTZ
) WITH (connector = 'kafka', topic = 'tariff.price.signals', properties.bootstrap.server = 'kafka:9092', scan.startup.mode = 'latest')
FORMAT PLAIN ENCODE JSON;
CREATE SOURCE dr_signals (
dr_event_id VARCHAR,
site_id VARCHAR,
curtailment_pct DOUBLE PRECISION,
baseline_kw DOUBLE PRECISION,
event_start_ts TIMESTAMPTZ,
event_end_ts TIMESTAMPTZ,
signal_ts TIMESTAMPTZ
) WITH (connector = 'kafka', topic = 'utility.dr.signals', properties.bootstrap.server = 'kafka:9092', scan.startup.mode = 'latest')
FORMAT PLAIN ENCODE JSON;
CREATE SOURCE battery_telemetry (
vehicle_id VARCHAR,
session_id VARCHAR,
station_id VARCHAR,
connector_type VARCHAR,
voltage_v DOUBLE PRECISION,
current_a DOUBLE PRECISION,
soc_percent INT,
soh_percent DOUBLE PRECISION, -- reported by the BMS
temperature_c DOUBLE PRECISION,
energy_kwh DOUBLE PRECISION,
charge_power_kw DOUBLE PRECISION,
event_ts TIMESTAMPTZ
) WITH (connector = 'kafka', topic = 'ev.battery.telemetry', properties.bootstrap.server = 'kafka:9092', scan.startup.mode = 'latest')
FORMAT PLAIN ENCODE JSON;
CREATE TABLE vehicle_baselines (
vehicle_id VARCHAR PRIMARY KEY, manufacturer VARCHAR, model_year INT, rated_capacity_kwh DOUBLE PRECISION
);
Station Monitoring: Connector State, Availability, Sessions, and Faults
The current status of every connector is a DISTINCT ON over status notifications. Regional availability in five-minute windows is the network operations center headline. Active session energy and completed session summaries give the throughput picture, and two alert views catch hard faults and soft faults.
CREATE MATERIALIZED VIEW connector_current_status AS
SELECT DISTINCT ON (charge_point_id, connector_id)
charge_point_id, connector_id, site_id, network_region, status, error_code, vendor_error_code, event_ts AS last_status_ts
FROM ocpp_status_notifications
ORDER BY charge_point_id, connector_id, event_ts DESC;
CREATE MATERIALIZED VIEW network_availability AS
SELECT network_region,
COUNT(*) AS total_connectors,
COUNT(*) FILTER (WHERE status = 'Available') AS available_count,
COUNT(*) FILTER (WHERE status = 'Charging') AS charging_count,
COUNT(*) FILTER (WHERE status = 'Faulted') AS faulted_count,
COUNT(*) FILTER (WHERE status = 'Unavailable') AS unavailable_count,
ROUND(100.0 * COUNT(*) FILTER (WHERE status IN ('Available', 'Charging', 'Finishing', 'Preparing')) / NULLIF(COUNT(*), 0), 2) AS availability_pct
FROM connector_current_status
GROUP BY network_region;
CREATE MATERIALIZED VIEW active_session_metrics AS
SELECT DISTINCT ON (transaction_id)
transaction_id, charge_point_id, connector_id, site_id, connector_type, rated_power_kw, energy_kwh, power_kw, soc_pct, sampled_ts
FROM ocpp_meter_values
WHERE transaction_id IS NOT NULL
ORDER BY transaction_id, sampled_ts DESC;
CREATE MATERIALIZED VIEW session_summary AS
SELECT transaction_id, charge_point_id, connector_id, site_id, connector_type, id_tag, start_ts, stop_ts,
EXTRACT(EPOCH FROM (stop_ts - start_ts)) / 60.0 AS duration_min,
stop_kwh - start_kwh AS energy_delivered_kwh,
stop_reason
FROM ocpp_transactions
WHERE stop_ts IS NOT NULL;
CREATE MATERIALIZED VIEW fault_alerts AS
SELECT charge_point_id, connector_id, site_id, network_region, error_code, vendor_error_code, last_status_ts, 'CONNECTOR_FAULT' AS alert_type
FROM connector_current_status
WHERE status = 'Faulted';
CREATE MATERIALIZED VIEW low_power_session_alerts AS
SELECT m.transaction_id, m.charge_point_id, m.connector_id, m.power_kw, m.energy_kwh, m.sampled_ts, 'LOW_POWER_DELIVERY' AS alert_type
FROM active_session_metrics m
JOIN connector_current_status cs ON m.charge_point_id = cs.charge_point_id AND m.connector_id = cs.connector_id
WHERE cs.status = 'Charging' AND m.power_kw < 1.0 AND m.sampled_ts > NOW() - INTERVAL '5 MINUTES';
Grouping fault_alerts by station model and firmware version, from a CDC asset table, turns individual faults into a fault rate trend that prioritizes maintenance. stop_reason in session_summary is diagnostic too: a rising share of PowerLoss or HardReset at one site points at the site rather than the vehicles.
Smart Charging: Headroom, Tariffs, Curtailment, and Setpoints
Smart charging turns the monitoring views into control. Each site has a contracted demand limit; the headroom available to EV load is the limit minus current building demand. The current tariff tier and any active utility curtailment event scale that headroom down. Dividing the result across active sessions, bounded below by a minimum guaranteed rate and above by the connector's rating, gives a per-session setpoint the CPMS applies through OCPP.
CREATE MATERIALIZED VIEW site_ev_headroom AS
SELECT DISTINCT ON (site_id)
site_id, demand_limit_kw, current_demand_kw, ev_load_kw,
GREATEST(0, demand_limit_kw - current_demand_kw) AS available_headroom_kw, measured_ts
FROM site_demand
ORDER BY site_id, measured_ts DESC;
CREATE MATERIALIZED VIEW active_dr_events AS
SELECT DISTINCT ON (site_id) dr_event_id, site_id, curtailment_pct, baseline_kw, event_start_ts, event_end_ts
FROM dr_signals
WHERE NOW() BETWEEN event_start_ts AND event_end_ts
ORDER BY site_id, signal_ts DESC;
CREATE MATERIALIZED VIEW current_price_tier AS
SELECT DISTINCT ON (site_id) site_id, tariff_id, price_usd_kwh, price_tier, grid_load_pct, valid_to
FROM electricity_prices
WHERE NOW() BETWEEN valid_from AND valid_to
ORDER BY site_id, valid_from DESC;
CREATE MATERIALIZED VIEW active_sessions_per_site AS
SELECT site_id, COUNT(*) AS active_sessions
FROM active_session_metrics
WHERE sampled_ts > NOW() - INTERVAL '5 MINUTES'
GROUP BY site_id;
CREATE MATERIALIZED VIEW session_setpoints AS
SELECT a.transaction_id, a.charge_point_id, a.connector_id, a.site_id, a.rated_power_kw, a.power_kw AS current_power_kw, a.soc_pct,
COALESCE(pt.price_tier, 'OFF_PEAK') AS price_tier, COALESCE(dr.curtailment_pct, 0) AS curtailment_pct,
LEAST(a.rated_power_kw,
GREATEST(3.0, -- minimum guaranteed rate
h.available_headroom_kw / NULLIF(cnt.active_sessions, 0)
* (1.0 - COALESCE(dr.curtailment_pct, 0) / 100.0)
* CASE COALESCE(pt.price_tier, 'OFF_PEAK')
WHEN 'CRITICAL_PEAK' THEN 0.2
WHEN 'ON_PEAK' THEN 0.5
WHEN 'MID_PEAK' THEN 0.8
ELSE 1.0 END)) AS setpoint_kw
FROM active_session_metrics a
JOIN site_ev_headroom h ON a.site_id = h.site_id
JOIN active_sessions_per_site cnt ON a.site_id = cnt.site_id
LEFT JOIN active_dr_events dr ON a.site_id = dr.site_id
LEFT JOIN current_price_tier pt ON a.site_id = pt.site_id
WHERE a.sampled_ts > NOW() - INTERVAL '5 MINUTES';
CREATE MATERIALIZED VIEW setpoint_deviation_alerts AS
SELECT transaction_id, charge_point_id, connector_id, site_id, current_power_kw, setpoint_kw,
ABS(current_power_kw - setpoint_kw) AS deviation_kw, price_tier, 'SETPOINT_DEVIATION' AS alert_type
FROM session_setpoints
WHERE ABS(current_power_kw - setpoint_kw) > 2.0;
CREATE MATERIALIZED VIEW site_overdemand_alerts AS
SELECT site_id, demand_limit_kw, current_demand_kw, available_headroom_kw, measured_ts, 'SITE_OVER_DEMAND' AS alert_type
FROM site_ev_headroom
WHERE current_demand_kw > demand_limit_kw;
Equal sharing is the simplest fairness rule. Priority sessions, vehicles with low state of charge, or departure-time-aware allocation are changes to the GREATEST/LEAST expression or a join to a reservation table, not a new control system. A session that keeps drawing more than its setpoint after two minutes is either a charger ignoring the OCPP command or a firmware fault, and setpoint_deviation_alerts is where it shows.
Demand Forecasting Inputs: Rolling Load, Throughput, and Surges
Forecasting splits into an operational horizon (the next 15 to 60 minutes: how many connectors, whether to activate demand response, whether vehicle-to-grid discharge should start) and a planning horizon (weeks: whether a cluster is saturating). Streaming SQL serves the operational horizon directly, by maintaining the aggregated, context-joined inputs a forecasting service or rule engine reads.
CREATE MATERIALIZED VIEW station_demand_15m AS
SELECT site_id, window_start, window_end,
COUNT(DISTINCT transaction_id) AS active_sessions,
SUM(power_kw) AS total_power_kw,
AVG(power_kw) AS avg_power_kw,
MAX(power_kw) AS peak_power_kw,
COUNT(DISTINCT transaction_id) FILTER (WHERE connector_type = 'CCS') AS ccs_sessions,
COUNT(DISTINCT transaction_id) FILTER (WHERE connector_type = 'CHAdeMO') AS chademo_sessions
FROM HOP(ocpp_meter_values, sampled_ts, INTERVAL '1 MINUTE', INTERVAL '15 MINUTES')
GROUP BY site_id, window_start, window_end;
CREATE MATERIALIZED VIEW station_throughput_1h AS
SELECT site_id, connector_type, window_start, window_end,
COUNT(*) AS sessions_completed,
AVG(energy_delivered_kwh) AS avg_energy_kwh,
AVG(duration_min) AS avg_duration_min,
PERCENTILE_CONT(0.95) WITHIN GROUP (ORDER BY energy_delivered_kwh) AS p95_energy_kwh
FROM TUMBLE(session_summary, stop_ts, INTERVAL '1 HOUR')
GROUP BY site_id, connector_type, window_start, window_end;
CREATE MATERIALIZED VIEW demand_with_grid_context AS
SELECT d.site_id, d.window_start, d.window_end, d.active_sessions, d.total_power_kw, d.avg_power_kw,
pt.price_usd_kwh, pt.grid_load_pct,
CASE WHEN d.total_power_kw > 500 AND pt.grid_load_pct > 80 THEN 'HIGH'
WHEN d.total_power_kw > 250 OR pt.grid_load_pct > 60 THEN 'MEDIUM'
ELSE 'LOW' END AS demand_pressure
FROM station_demand_15m d
LEFT JOIN current_price_tier pt ON d.site_id = pt.site_id;
CREATE MATERIALIZED VIEW demand_surge_alerts AS
SELECT d.site_id, d.window_start, d.window_end, d.total_power_kw AS current_power_kw, b.baseline_power_kw,
ROUND((d.total_power_kw / NULLIF(b.baseline_power_kw, 0))::NUMERIC, 2) AS surge_ratio, d.demand_pressure
FROM demand_with_grid_context d
JOIN (
SELECT site_id, AVG(total_power_kw) AS baseline_power_kw
FROM station_demand_15m
WHERE window_end > NOW() - INTERVAL '2 HOURS'
GROUP BY site_id
) b ON d.site_id = b.site_id
WHERE d.window_end > NOW() - INTERVAL '2 MINUTES'
AND d.total_power_kw > b.baseline_power_kw * 2.0;
A surge at a corridor site with demand_pressure = 'HIGH' is the trigger to request curtailment headroom from the utility or begin vehicle-to-grid discharge before the site limit binds. Hourly throughput by connector type, accumulated into the lake, is the planning-horizon dataset for deciding where the next charger goes.
Battery State of Health: Trends, Capacity Fade, and Thermal Stress
Battery state of health is usable capacity over rated capacity, and packs degrade through charge cycles, temperature extremes, and high C-rate sessions for months before crossing 80 percent. Processing each battery management system reading as it arrives gives fleet operators a rolling SoH trend per vehicle, an estimate of capacity lost, and an alert the moment a session runs hot.
CREATE MATERIALIZED VIEW vehicle_soh_trend AS
SELECT vehicle_id, window_start, window_end,
AVG(soh_percent) AS avg_soh_pct,
MIN(soh_percent) AS min_soh_pct,
MAX(temperature_c) AS max_temp_c,
AVG(charge_power_kw) AS avg_charge_power_kw,
COUNT(DISTINCT session_id) AS charge_sessions,
SUM(energy_kwh) AS total_energy_kwh
FROM HOP(battery_telemetry, event_ts, INTERVAL '1 HOUR', INTERVAL '24 HOURS')
GROUP BY vehicle_id, window_start, window_end;
CREATE MATERIALIZED VIEW capacity_fade AS
SELECT t.vehicle_id, b.manufacturer, b.model_year, b.rated_capacity_kwh,
MAX(t.soh_percent) AS latest_soh_pct,
b.rated_capacity_kwh * MAX(t.soh_percent) / 100.0 AS estimated_usable_kwh,
b.rated_capacity_kwh * (1 - MAX(t.soh_percent) / 100.0) AS capacity_loss_kwh,
MAX(t.event_ts) AS last_updated
FROM battery_telemetry t
JOIN vehicle_baselines b ON t.vehicle_id = b.vehicle_id
WHERE t.event_ts > NOW() - INTERVAL '7 DAYS'
GROUP BY t.vehicle_id, b.manufacturer, b.model_year, b.rated_capacity_kwh;
CREATE MATERIALIZED VIEW thermal_stress_sessions AS
SELECT vehicle_id, session_id, connector_type, window_start, window_end,
AVG(temperature_c) AS avg_temp_c, MAX(temperature_c) AS peak_temp_c, AVG(charge_power_kw) AS avg_power_kw
FROM TUMBLE(battery_telemetry, event_ts, INTERVAL '10 MINUTES')
WHERE temperature_c > 40.0
GROUP BY vehicle_id, session_id, connector_type, window_start, window_end;
CREATE MATERIALIZED VIEW soh_alerts AS
SELECT vehicle_id, manufacturer, model_year, latest_soh_pct, rated_capacity_kwh, estimated_usable_kwh, capacity_loss_kwh, last_updated,
CASE WHEN latest_soh_pct < 70 THEN 'CRITICAL' ELSE 'WARNING' END AS alert_level
FROM capacity_fade
WHERE latest_soh_pct < 80;
CREATE MATERIALIZED VIEW thermal_alerts AS
SELECT vehicle_id, session_id, connector_type, peak_temp_c, avg_power_kw, window_end AS detected_at, 'THERMAL_STRESS' AS alert_type
FROM thermal_stress_sessions
WHERE peak_temp_c > 45.0;
Grouping capacity_fade by manufacturer and model year gives a fleet-level degradation curve by vehicle type, which is what a fleet buyer uses for replacement planning and warranty claims. A charger whose sessions repeatedly appear in thermal_alerts across different vehicles is a charger problem, and the join to connector_current_status by station confirms it.
Routing Setpoints and Alerts
Setpoints go to the CPMS over Kafka for OCPP execution. Alerts go to the network operations center and mobile notification systems; battery alerts go to the fleet management system; demand signals go to the forecasting service.
CREATE SINK setpoint_command_sink AS
SELECT transaction_id, charge_point_id, connector_id, setpoint_kw, price_tier, NOW() AS command_ts
FROM session_setpoints
WITH (connector = 'kafka', topic = 'ocpp.setpoint.commands', properties.bootstrap.server = 'kafka:9092')
FORMAT UPSERT ENCODE JSON;
CREATE SINK charging_alert_sink AS
SELECT charge_point_id, connector_id, site_id, error_code AS detail, last_status_ts AS ts, alert_type FROM fault_alerts
UNION ALL
SELECT charge_point_id, connector_id, NULL, power_kw::VARCHAR, sampled_ts, alert_type FROM low_power_session_alerts
UNION ALL
SELECT charge_point_id, connector_id, site_id, deviation_kw::VARCHAR, NOW(), alert_type FROM setpoint_deviation_alerts
UNION ALL
SELECT NULL, NULL, site_id, current_demand_kw::VARCHAR, measured_ts, alert_type FROM site_overdemand_alerts
WITH (connector = 'kafka', topic = 'charging.network.alerts', properties.bootstrap.server = 'kafka:9092')
FORMAT PLAIN ENCODE JSON;
CREATE SINK demand_forecast_signals FROM demand_with_grid_context
WITH (connector = 'kafka', topic = 'forecasting.demand.signals', properties.bootstrap.server = 'kafka:9092')
FORMAT PLAIN ENCODE JSON;
CREATE SINK battery_alert_sink AS
SELECT vehicle_id, alert_level AS severity, 'SOH' AS alert_type, latest_soh_pct AS value, last_updated AS ts FROM soh_alerts
UNION ALL
SELECT vehicle_id, 'WARNING', alert_type, peak_temp_c, detected_at FROM thermal_alerts
WITH (connector = 'kafka', topic = 'alerts.battery', properties.bootstrap.server = 'kafka:9092')
FORMAT PLAIN ENCODE JSON;
The network operations center dashboard queries network_availability, connector_current_status, and site_ev_headroom directly over PostgreSQL.
Polling and Schedules vs Streaming SQL for Charging Networks
| Concern | Polling and static schedules | Streaming SQL (RisingWave) |
|---|---|---|
| Faulted connector | Found on the next poll or by a driver | Current status view, alert on the status event |
| Soft fault | Invisible | Charging status joined to near-zero power |
| Site demand limit | Timer-based or manual | Headroom per measurement, setpoints per session |
| Tariff and curtailment response | Manual | Tier and event joined into the setpoint |
| Demand surge | Noticed when the site limit binds | Fifteen-minute rolling load against a two-hour baseline |
| Battery health | Nightly batch, 12 to 24 hour blind spot | Rolling SoH, capacity fade, thermal stress per reading |
| New control rule | Rules engine change | Edit one SQL expression |
Frequently Asked Questions
How quickly do setpoints need to reach the charger?
Site demand charges are typically assessed on 15-minute intervals, so a setpoint loop of a few seconds from meter value to OCPP SetChargingProfile is ample. RisingWave recomputes session_setpoints on each meter value or demand reading; the CPMS applies the command.
How do I prioritize some vehicles over others?
Join a reservation or fleet priority table into session_setpoints and give priority sessions a larger share or a higher minimum rate. Departure-time-aware allocation uses the same pattern with a required-energy-by-time column.
Does the demand response baseline need to exclude prior events?
For utility settlement, usually yes. Compute the site baseline from site_demand with a NOT EXISTS against past dr_signals, which mirrors the method in the energy and utilities guide.
Can state of health be estimated when the battery management system does not report it?
Yes, approximately. Energy delivered between two known state-of-charge readings in a session, divided by the state-of-charge delta, estimates usable capacity, and that over rated capacity is an SoH estimate. Express it as a view over battery_telemetry using the first and last readings per session.
How are OCPP messages from different protocol versions handled? Normalize at the CPMS or a thin adapter before Kafka so the sources carry one schema. OCPP 1.6 and 2.0.1 differ in message shape but not in the status, meter value, and transaction semantics the views depend on.
