Skip to content

Conversation

@ross-w
Copy link
Contributor

@ross-w ross-w commented Oct 4, 2025

Very excited to see #21162 merged!

This updates Amber to normalise to SlotDuration rather than 1-hour slots. A reminder that Amber can return 5-minute or 30-minute prices (usually 5-minute for the short term and 30-minute for longer, but some accounts will be 30-minute for all due to their smart meter being too old)

I considered not doing any normalising (since the wrapper will do this) but we still need the hack to override the current slot with the current price in order to maintain charging session accuracy (please let me know if there's a better way to do this as I could then remove most of this code)

Copy link
Contributor

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey there - I've reviewed your changes - here's some feedback:

  • Consider sorting the intervals slice by start time before computing minTime to ensure correct slot range and ordering.
  • You might want to skip generating slots with no overlap (totalDuration == 0 and no currentPrice) to avoid populating rates with meaningless zero‐value entries.
  • The nested logic for computing slot values could be broken out into a helper function for clarity and easier unit testing.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- Consider sorting the intervals slice by start time before computing minTime to ensure correct slot range and ordering.
- You might want to skip generating slots with no overlap (totalDuration == 0 and no currentPrice) to avoid populating rates with meaningless zero‐value entries.
- The nested logic for computing slot values could be broken out into a helper function for clarity and easier unit testing.

## Individual Comments

### Comment 1
<location> `tariff/amber.go:147` </location>
<code_context>
+			var currentPrice *float64
+
+			// Find all intervals that overlap with this 15-minute slot
+			for _, interval := range intervals {
+				if interval.end.After(slotStart) && interval.start.Before(slotEnd) {
+					// Calculate overlap duration
</code_context>

<issue_to_address>
**issue (complexity):** Consider sharding intervals into 15-minute buckets in a single pass to avoid nested loops and simplify slot processing.

You can avoid the O(slots × intervals) nested loops by “sharding” each interval into its 15 min buckets in one pass. That way you only iterate slots that actually have data, simplify your logic, and keep exact behavior:

```go
const Slot = 15 * time.Minute

// 1) build a map of per-slot accumulators
type bucket struct {
  totalSecs   float64
  weightedSum float64
  current     *float64
}
buckets := make(map[time.Time]*bucket)

for _, iv := range intervals {
  // truncate start to slot boundary
  slot := iv.start.Truncate(Slot)
  end := iv.end

  for slot.Before(end) {
    next := slot.Add(Slot)
    // compute overlap [max(slot, iv.start), min(next, iv.end))
    s := slot
    if iv.start.After(slot) {
      s = iv.start
    }
    e := next
    if iv.end.Before(next) {
      e = iv.end
    }
    secs := e.Sub(s).Seconds()

    b, ok := buckets[slot]
    if !ok {
      b = &bucket{}
      buckets[slot] = b
    }

    if iv.isCurrent {
      // override any forecast for this slot
      b.current = &iv.value
    } else {
      b.weightedSum += iv.value * secs
      b.totalSecs += secs
    }

    slot = next
  }
}

// 2) convert buckets into sorted api.Rates
var data api.Rates
for start, b := range buckets {
  var v float64
  if b.current != nil {
    v = *b.current
  } else if b.totalSecs > 0 {
    v = b.weightedSum / b.totalSecs
  }
  data = append(data, api.Rate{Start: start, End: start.Add(Slot), Value: v})
}
// sort by Start if needed, then mergeRates(...)
```

This preserves current‐interval overrides and weighted averaging, but only iterates each interval’s slots once—no full scan over all slots for every interval.
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

@ross-w
Copy link
Contributor Author

ross-w commented Oct 4, 2025

@sourcery-ai guide

@sourcery-ai
Copy link
Contributor

sourcery-ai bot commented Oct 4, 2025

Reviewer's Guide

The PR refactors rate normalization from fixed 1-hour buckets to flexible SlotDuration shards by replacing the legacy hourly aggregation with a generic bucket sharding approach in a new buildSlotRates helper.

Class diagram for Amber rate normalization refactor

classDiagram
    class Amber {
        +run(done chan error)
        +buildSlotRates(intervals)
        data: api.Rates
        channel: string
    }
    class bucket {
        totalSecs: float64
        weightedSum: float64
        current: *float64
    }
    Amber --> bucket : uses for slot aggregation
    class api.Rate {
        Start: time.Time
        End: time.Time
        Value: float64
    }
    class api.Rates {
        <<slice of Rate>>
    }
    Amber --> "api.Rates" : produces
    Amber --> "api.Rate" : produces
    bucket --> "api.Rate" : produces
Loading

Flow diagram for slot-based rate normalization

flowchart TD
    A["Amber intervals (5-min/30-min)"] --> B["Sort intervals by start time"]
    B --> C["Shard intervals into SlotDuration buckets"]
    C --> D["Aggregate weighted average per slot"]
    D --> E["Override slot with current interval if present"]
    E --> F["Produce sorted api.Rates for each slot"]
Loading

File-Level Changes

Change Details Files
Removed legacy hourly grouping in favor of collecting raw intervals
  • Deleted hourlyData map and associated weighted average aggregation
  • Built an intervals slice capturing start, end, value, and current-indicator
  • Sorted intervals by start time before processing
tariff/amber.go
Introduced buildSlotRates to shard intervals into SlotDuration buckets
  • Added bucket struct to accumulate weighted sums, durations, and current overrides
  • Looped through each interval per slot to compute overlap and update buckets
  • Computed final slot values (override or weighted average), skipped empty slots, and sorted results
tariff/amber.go
Updated run method to invoke buildSlotRates and handle empty intervals
  • Added early path for zero intervals calling mergeRates and closing done
  • Replaced direct mergeRates with buildSlotRates output followed by mergeRates
  • Removed in-loop close and mergeRates logic tied to hourly buckets
tariff/amber.go

Possibly linked issues

  • #AmberElectricBillingChange: PR updates Amber's tariff calculation to use SlotDuration for 5-minute intervals, resolving evcc's outdated pricing.
  • #GH-Issue-Amber-Slots: The PR updates Amber integration to normalize tariff data to SlotDuration (e.g., 15-minute) instead of 1-hour slots, resolving the graph display issue caused by half-hour forecasts.

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@ross-w
Copy link
Contributor Author

ross-w commented Oct 4, 2025

@sourcery-ai review

Copy link
Contributor

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey there - I've reviewed your changes and they look great!

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location> `tariff/amber.go:151` </location>
<code_context>
+	}
+}
+
+// buildSlotRates converts Amber intervals into 15-minute slots using bucket sharding
+// to avoid O(slots × intervals) complexity and only create slots with actual data
+func (t *Amber) buildSlotRates(intervals []struct {
</code_context>

<issue_to_address>
**issue (complexity):** Consider refactoring buildSlotRates to use a flat slice of slot overlaps, sort, and then group in a single pass for clarity and linear workflow.

You can simplify buildSlotRates by collecting all per-slot overlaps into a flat slice, sorting it, then doing a single pass to group by slot. This removes the map lookup noise and separates concerns into three clear steps: expand, sort, reduce.

Example:

```go
func (t *Amber) buildSlotRates(intervals []interval) api.Rates {
    type entry struct {
        slot      time.Time
        secs      float64
        weighted  float64
        isCurrent bool
        value     float64
    }

    // 1) Expand each interval into slot‐sized entries
    var entries []entry
    for _, iv := range intervals {
        for slot := iv.start.Truncate(SlotDuration); slot.Before(iv.end); slot = slot.Add(SlotDuration) {
            next := slot.Add(SlotDuration)
            start := maxTime(slot, iv.start)
            end   := minTime(next, iv.end)
            secs  := end.Sub(start).Seconds()

            entries = append(entries, entry{
                slot:      slot,
                secs:      secs,
                weighted:  iv.value * secs,
                isCurrent: iv.isCurrent,
                value:     iv.value,
            })
        }
    }

    if len(entries) == 0 {
        return nil
    }

    // 2) Sort by slot
    slices.SortFunc(entries, func(a, b entry) int {
        return a.slot.Compare(b.slot)
    })

    // 3) Single pass: group by slot, pick current or compute weighted avg
    var rates api.Rates
    for i := 0; i < len(entries); {
        slot := entries[i].slot
        var (
            totalSecs float64
            totalW    float64
            curVal    *float64
            j         = i
        )
        for ; j < len(entries) && entries[j].slot.Equal(slot); j++ {
            e := entries[j]
            if e.isCurrent {
                v := e.value
                curVal = &v
            } else {
                totalSecs += e.secs
                totalW    += e.weighted
            }
        }

        val := totalW / totalSecs
        if curVal != nil {
            val = *curVal
        }
        rates = append(rates, api.Rate{
            Start: slot,
            End:   slot.Add(SlotDuration),
            Value: val,
        })

        i = j
    }

    return rates
}

// helpers
func minTime(a, b time.Time) time.Time {
    if a.Before(b) { return a }
    return b
}
func maxTime(a, b time.Time) time.Time {
    if a.After(b) { return a }
    return b
}
```

— This drops the map, makes the workflow linear (expand→sort→reduce) and keeps the exact same slot-level logic.
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

@andig
Copy link
Member

andig commented Oct 4, 2025

I'm not sure what this PR really does- switching to 30m slots would have been sufficient. If you think it's good I can merge anyway.

@andig andig added the tariffs Specific tariff support label Oct 4, 2025
@andig andig changed the title fix: normalise to SlotDuration rather than 1-hour slots Amber: use 30min slots Oct 4, 2025
@ross-w
Copy link
Contributor Author

ross-w commented Oct 4, 2025

Hi @andig sorry if it’s not clear!

It will work without merging, but because the existing code will normalise to 1-hour slots, then the wrapper normalises that into 15-minute slots, it means the 5-minute resolution from the Amber API becomes less accurate than it would be if it was directly supplied with the 15-minute slots in the first place

Let me know if I need to do anything to make to more obvious!

@andig andig changed the title Amber: use 30min slots Amber: use 15min slots Oct 4, 2025
@andig andig merged commit 96b82fe into evcc-io:master Oct 4, 2025
7 checks passed
@ross-w ross-w deleted the rw-update-normalisation branch October 4, 2025 07:52
mfuchs1984 pushed a commit to mfuchs1984/evcc that referenced this pull request Oct 12, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

tariffs Specific tariff support

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants