Session cost breakdown: grid, solar, battery
Is your feature request related to a problem? Please describe. When looking at the data for a finished charging session, the cost shown is a single combined value made up of two conceptually different things: the price paid for energy imported from the grid, and the opportunity cost of self-consumed solar energy (the feed-in revenue given up by using solar power for charging instead of exporting it). Because these are blended into one number, it's not possible to see how much was actually paid to the grid versus how much solar "cost" in foregone feed-in revenue.
Describe the solution you'd like Split the session cost into two separate values:
- Imported power: the cost of grid-imported energy used for charging
- Opportunity cost of exported solar: the feed-in revenue foregone by self-consuming solar energy instead of exporting it
Show both alongside the existing total cost in the session details, so I can see the full breakdown instead of just the combined figure.
Describe alternatives you've considered
- Manually estimating the split myself using the session's solar percentage and known tariff rates, which is tedious and error-prone.
- Keeping only the combined cost value, which is simpler but hides useful information about where the cost actually comes from.
Additional context The breakdown would ideally only be shown when solar was actually used during the session (to avoid a meaningless "0.00" opportunity-cost row on setups without solar/PV). Existing/historical sessions recorded before this feature would not have the split available and would continue to show only the combined cost.
Thanks for the detailed proposal. I looked into how session cost is currently calculated and confirmed the underlying mechanics:
- The stored session cost (
core/session/session.goPrice/PricePerKWh) comes fromEnergyMetrics(core/energy_metrics.go), which accumulatescurrentPrice * addedEnergyon every loadpoint update. currentPriceis the blended effective price computed inSite.effectivePrice()(core/site_tariffs.go:86-96):effPrice := grid*(1-greenShare) + feedin*greenShare. Grid tariff and feed-in opportunity cost are combined into a single number beforeEnergyMetricsever sees them, so the split you're asking for isn't retained anywhere today.
Implementing this would require:
- Splitting
effectivePrice()into grid-cost and feed-in-opportunity-cost components (or returning both) instead of one blended value. - Adding parallel accumulators in
EnergyMetrics(and itsUpdate/Publishmethods) to track the two cost components separately, alongside the existing total. - New
Sessionfields/DB columns (e.g.PriceGrid,PriceSolar) with a migration, wired throughcore/loadpoint_session.go. - API/CSV export changes plus UI updates (
assets/js/components/Sessions/SessionDetailsModal.vueand related components) to show the breakdown, conditionally hidden when solar wasn't used, as you suggested.
This touches core pricing/accumulation logic, the session data model (with migration), and the UI — it's a legitimate but non-trivial feature request, not a small isolated fix, so I won't attempt an automated implementation here.
🤖 Generated with Claude Code
I have asked Claude Code to create an implementation of this, to show what I'm thinking - it is referenced in PR #33252
I follow the reasoning behind this. We've also gotten earlier requests "on not including the missed solar compensation" into cost calculations at all, because people see their solar energy as "free energy". Splitting this will address this.
However, another topic we have open here is how we treat home battery energy. Right now we have the baked in assumption (documented here) that home battery energy is treated like self-produced solar without losses. This was fine before we introduced grid charging and introduced the concept of charge/discharge efficiency in the optimizer (default 90%).
If we're going to restructure (db migration) how we track charging costs in sessions we should now also take battery energy cost into account. This however is a little bigger issue since we a) need to split our greenShare* values in pvShare* and batteryShare* and b) come up with a model for tracking the "energy value" (price/kWh) inside our home battery based on how it was charged (grid or pv).
Dont want to make it too complicated and I like to do it in multiple steps (split total into grid+green, split green into pv+battery). But before we do step one we need a plan for the complete the story and final picture.
I see your point - might be tricky, since it would require always keeping a tally on the value of the charged power on the home battery.
Change from 60% to 100% from grid at price X. Discharge 20% during night. Charge from 80% to 95% using solar at price Y. Discharge 10% due to it being cloudy.
Then charge the car, allowing it to use 50% from the battery - at what price? (It would have to think about at what price the discharged power was charged to, to be able to keep at running average "monetary value" of the power in the battery.
Initially I didn't think of this, since I always have charging from the house battery disabled (since it is too small to make any difference on the car anyway, and makes more sense to have it for the house for the evening/night).
I don't see an easy way to do this - so I think the best way to think of it would be to monitor if the last time it was charged, if it was from grid, grid/solar or solar, and then use the current grid price, 50/50 split between grid and solar price, and just solar price.
It won't be accurate, but at least it would give an approximation, and it would be "last time it was charged from the grid, so we calculate the price as if it was from the grid right now).
Your thoughts?
It won't be accurate, but at least it would give an approximation, and it would be "last time it was charged from the grid, so we calculate the price as if it was from the grid right now).
I think this is too simplified. We need to take dynamic grid tariffs and partial use of pv in to account for this to make sense. My thinking is more in the direction of adding the cost information to the (experimental) history feature. There we have 15min resolution of charged/discharged energy for every battery configured but no costs yet. If costs were available we could read the current charge level and the history entries backwards to calculate/estimate the monetary energy value.
But adding proper cost entries to history is a larger can of worms. So I'd say lets put this topic here in backlog first until we have a proper solution for battery cost.
I agree.
Did not know about the history experimental feature, but with that in mind, it makes perfect sense to do it like you say.
I don't know how far along that feature is in the maturing process, but I think this should be marked as depending on it (if possible)
@naltatis I noticed the merge today regarding the battery history page. If that the one you where talking about? (if so, I plan on letting Claude have a go at what it can do)
@naltatis This is what Claude has to say - it looks like it should be possible to implement cleanly:
Thanks for the detailed feedback — this is genuinely useful.
I agree with the reasoning on battery energy. The "battery = free solar" assumption in the FAQ savings calculation predates grid-charging/arbitrage and the optimizer's round-trip efficiency (eta = 0.9 in core/site_optimizer.go), so it's no longer accurate for setups using either.
To avoid getting ahead of the agreed plan again, here's the reconciled three-step picture:
- Grid vs. green split — shipped in #33252 (
Session.GridCost/SolarCost). - Green → PV vs. battery share — additive, provably safe: a
pvShare/batterySharesplit (PV serves lower power ranges first, battery fills the deficit — matches real inverter dispatch) always sums back to today's combinedgreenShare(), so existing stats (Solar %, telemetry) are unaffected. Until step 3 lands, battery-sourced energy would still be valued at the feed-in price (same as direct solar) — this step is just plumbing. - Real battery cost basis — parked in backlog as you suggested. Taking your direction seriously: rather than a live in-memory ledger, reuse what's already persisted at 15-min resolution —
Energy/ReturnEnergyper battery meter, and grid/feed-in tariff price, on the same slot timestamps, joinable with no schema change. Anchor on the battery's current usable stored energy (accounting for its ~10% reserve floor), walk backward through slots only as far as needed to explain that stored energy (self-bounding, not "keep history forever"), and apply1/etato convert accumulated per-kWh-in cost to per-kWh-out — that's the piece the current FAQ assumption misses.
I rejected my own earlier "last charge source" heuristic per your pushback — too simplistic given dynamic tariffs and partial PV use.
Open questions before I'd attempt step 3:
- Compute on-demand via backward replay (no migration) vs. denormalize a cost column into the history table (faster reads, but a migration + write cost per slot)? I'd lean on-demand.
- OK to reuse the optimizer's
eta = 0.9, or should this get its own configurable efficiency? - Aggregate site-wide battery cost basis only (matches today's
state.batteryaggregation), not per-device — agreed?
If you want, I can take your feedback and answers to those three questions, and update the draft with those changes.
- Green → PV vs. battery share
Adding these would be the first step in my perspective. I'd do the persistence change in sessions (1) only after the other two are done. This way we dont change data structure and semantics multiple times.
In the medium/long term I'd like to drop greenShare* all together since pv/battery share are more specific. But for now (bot mentioned telemtry) it's pragmatic to leave in.
- Real battery cost basis
This is the heavy lifting part. I'd also start with the suggested "on-demand" approach pulling energy and price data from our persistence. Do be in sync we should not only focus on price/cost but also build this for co2. The process is the same, grid charged battery energy should be treated with the same emissions as its source (from grid = co2 tariff, from solar = 0).
I dont have a clear picture on how this would manifest in code ("big ass sql query" vs. "go logic") but I'm interested to see. Important is that we keep the existing priority logic (who gets the solar energy / battery energy first: consumers/home, loadpoints) to align with the existing model.
Feel free do give it a try so we can discuss on a concrete basis.
Remaining questions:
- starting with a constant battery efficiency (0.9) is fine. making this ui configurable and usable in this and optimizer could be a separate step.
- cost per site-battery or per device: yes, lets start with the site-wide solution. we can always go more complex/finer if we really see benefit in it.
Okay, I have had it work on it - here is a summary:
Step 1 — Grid vs. green split
Session.GridCost/Session.SolarCost, computed inEnergyMetricsfrom the raw grid/feed-in tariff instead of the old pre-blendedeffectivePrice().- UI:
SessionDetailsModal.vueshows "Imported power" / "Direct solar" as muted sub-rows under the total cost, only when solar was actually used.
Step 2 — Split green into PV vs. battery share
- Added
Site.greenShareBySource(powerFrom, powerTo) (pvShare, batteryShare float64)next to the existinggreenShare(). PV serves the lower part of the power window first, battery discharge only fills the deficit PV can't cover (matches real inverter dispatch priority). - Provably safe:
pvShare + batterySharealways equals the existinggreenShare()result (verified algebraically and by test), so today's aggregate stats (Solar %,GreenShareLoadpoints, telemetry) are unaffected. EnergyMetricsgainedPvCost()/BatteryCost(), tracked in-memory and published as live state. Both valued at feed-in price at this stage (same as today'sSolarCost).- Decision: no
Session/DB/CSV/UI changes yet. Persistence is deferred until the full picture (steps 2+3) is settled, to avoid two separate schema migrations.
Step 3 — Real battery cost basis
- Added
Site.batteryCostBasis(): anchors on the battery's current usable stored energy (capacity * max(0, soc - reserveSoc) / 100), then walks the existing persisted battery-history and tariff data backward — FIFO, oldest stored energy considered dispatched first — until that energy is accounted for or history runs out. Applies1/etato convert the accumulated per-kWh-in cost/CO2 to a per-kWh-out value, addressing round-trip losses the "battery = free solar" FAQ assumption misses. - No schema change needed: reuses the existing (experimental) battery-history feature (
Energy/ReturnEnergy/SocTempper 15-min slot) and adds a newQueryTariffsread path against the already-persisted tariff table, joined by timestamp. EnergyMetrics.BatteryCost()now uses this real basis when available, falling back to the feed-in price (same as direct solar) otherwise. NewBatteryCo2PerKWh()alongside it.- Result cached per 15-min slot (matching the data's own granularity) rather than recomputed every update tick.
Decisions made along the way (resolving the open questions from earlier in this thread):
- Compute the cost basis on-demand via backward replay, not a denormalized column in the history table (no migration).
- Reuse the optimizer's
eta = 0.9for now; a separately configurable battery efficiency is out of scope for this pass. - Aggregate site-wide only (matches today's
state.batteryaggregation across meters), not per-device. - Price/CO2 attribution when a slot's charge source can't be determined: blend 50/50 between grid and feed-in price/CO2 — "we cannot know it, so a middle ground seems fair."
- Reserve-SoC floor: use
api.BatterySocLimiter.GetSocLimits()where the device implements it, else fall back to a hardcoded 10%. - Battery capacity unreliable (any configured battery meter missing a capacity reading, degrading
state.battery.Capacityto a meter count): returnnil BatteryCost, same graceful-degradation pattern asGridCost/SolarCosttoday. - Partial/insufficient persisted history (e.g. battery or tariff only recently configured): use whatever was accumulated so far rather than returning nothing — a best-effort answer is preferred over none.
Still open:
- Update the FAQ savings-calculation doc once this ships, since it currently documents the lossless-solar assumption this work removes.
Deliberately not yet done (all three steps): no Session struct fields, no DB migration, no CSV export changes, no API/UI surfacing. All of steps 2–3 are in-memory computation only, so the session-persistence schema only needs to change once, when it's actually exposed.
All changes are covered by unit tests (TestGreenShare, TestEnergyMetricsGreenShareSplit, TestReplayBatteryCost, TestBatteryReserveSoc, TestBatteryCapacityReliable, TestEnergyMetricsBatteryCostBasis, TestQueryTariffs) and build/vet/test clean.
This seems to be pretty clean. (I'm no expert in the Go language, but the architecture of what it says sounds reasonable).
What do you think @naltatis ?
See my comment from before.
I'd do the persistence change in sessions (1) only after the other two are done.
I wouldn't release an intermediate version where we split gird/pv and than again split to grid/pv/battery in a later iteration since we would have account for the visualization and calculation in UI. From a users perspective pvCost (when we introduce) should always mean pvCost and not an intermedia "when written with this version, pvCost might also include batteryCost".
Added Site.greenShareBySource(powerFrom, powerTo) (pvShare, batteryShare float64) next to the existing greenShare(). PV serves the lower part of the power window first, battery discharge only fills the deficit PV can't cover (matches real inverter dispatch priority).
Pasting this AI output is not helpful for making a plan together. It's too detailed for a strategic discussion. Feel free to make a PR, optimize, refine and test it and than lets discuss the actual changeset.
Added Site.greenShareBySource(powerFrom, powerTo) (pvShare, batteryShare float64) next to the existing greenShare(). PV serves the lower part of the power window first, battery discharge only fills the deficit PV can't cover (matches real inverter dispatch priority).
Pasting this AI output is not helpful for making a plan together. It's too detailed for a strategic discussion. Feel free to make a PR, optimize, refine and test it and than lets discuss the actual changeset.
I will - right now I'm just making sure I'm on the right track. 🙂
FWIW I use HA to calculate the cost of battery power based on grid/PV/SoC. so I have a sensor in HA which shows me the price / kWh in the battery. Would be great if I could use this as battery price in EVCC. Currently I use this sensor as the feedin price so it's calculated in my total charge costs.
Coming from #34734 (closed in favor of this issue). One aspect that I think the battery cost model should cover besides the cost basis:
The cost basis answers "what did the energy in the battery cost when it was stored". When battery energy goes into the car, there is a second question: "what does using it now cost me". If the battery would otherwise last until it is refilled, using it for the car only costs the feed-in I gave up. If it runs empty overnight because of that, the home imports the same energy from the grid later, so its real cost is the grid price, however it was charged.
My PR approximated this with a fixed SoC threshold, which is too static, agreed. But the optimizer already forecasts whether the battery hits its minimum before it refills (battery.forecast.lowest.limit). That could decide which value applies when battery energy is used for charging, without a new setting:
- battery forecast to hit its minimum: grid price (and grid CO2)
- otherwise: the battery's cost basis (or feed-in, as today)
Does this fit into the model you have in mind, or should it stay out of scope?
The cost basis answers "what did the energy in the battery cost when it was stored". When battery energy goes into the car, there is a second question: "what does using it now cost me".
Lets not go there. This includes prediction of the future which might e.g. be destroyed by someone deciding to cook a large meal in the meantime. Lets focus on the costs we can reliably and repeatably measure.
Thanks for working on this – the planned battery cost basis (step 3) is exactly what I need.
Two questions about my setup:
-
My home battery is charged from the grid by Home Assistant (force charge via Modbus on a FoxESS H3 Pro, based on Tibber prices and PV forecast), not by evcc's grid charging. Will step 3 detect this grid charging from the site meters and battery history anyway, or does it only consider grid charging triggered by evcc?
-
Like @marcelnam, I already calculate a blended battery price in Home Assistant (PV share + grid share at the 15-min Tibber price). Is an option planned to provide such an external battery price (e.g. via plugin/MQTT), as an alternative or override?
Setup: evcc 0.318.2 (HA app), FoxESS H3 Pro 25, 2× FoxESS ECS (~48 kWh), ~23.3 kWp PV, Tibber.