Improve optimizer integration (#23047)
Some checks failed
Some checks failed
This commit is contained in:
parent
0617c128f0
commit
e4d6cd589e
11 changed files with 421 additions and 229 deletions
|
|
@ -89,15 +89,18 @@ export default defineComponent({
|
|||
chartData(): ChartData {
|
||||
const datasets: any[] = [];
|
||||
|
||||
// 1. Solar Forecast (first, with increased tension)
|
||||
datasets.push(...this.getSolarDatasets());
|
||||
// 1. Grid power data (import/export)
|
||||
datasets.push(...this.getGridPowerDatasets());
|
||||
|
||||
// 2. Battery power data
|
||||
datasets.push(...this.getBatteryPowerDatasets());
|
||||
// 2. Solar Forecast
|
||||
datasets.push(...this.getSolarDatasets());
|
||||
|
||||
// 3. Household Demand (power)
|
||||
datasets.push(...this.getHouseholdDatasets());
|
||||
|
||||
// 4. Battery power data
|
||||
datasets.push(...this.getBatteryPowerDatasets());
|
||||
|
||||
return {
|
||||
labels: this.timeLabels,
|
||||
datasets: datasets,
|
||||
|
|
@ -133,6 +136,16 @@ export default defineComponent({
|
|||
label: (context) => {
|
||||
const label = context.dataset.label || "";
|
||||
const value = context.parsed.y;
|
||||
// Special handling for Grid Power
|
||||
if (label === "Grid Power") {
|
||||
if (value > 0) {
|
||||
return `Grid Import: ${this.formatValue(Math.abs(value))} kW`;
|
||||
} else if (value < 0) {
|
||||
return `Grid Export: ${this.formatValue(Math.abs(value))} kW`;
|
||||
} else {
|
||||
return `Grid: 0 kW`;
|
||||
}
|
||||
}
|
||||
// Power axis (kW)
|
||||
return `${label}: ${this.formatValue(value)} kW`;
|
||||
},
|
||||
|
|
@ -159,23 +172,11 @@ export default defineComponent({
|
|||
display: true,
|
||||
text: "Power (kW)",
|
||||
},
|
||||
stacked: true,
|
||||
stacked: false,
|
||||
grid: {
|
||||
drawOnChartArea: true,
|
||||
color: (context: any) => {
|
||||
// Make zero axis black to highlight
|
||||
if (context.tick?.value === 0) {
|
||||
return "#000000";
|
||||
}
|
||||
return colors.border || "#e0e0e0";
|
||||
},
|
||||
lineWidth: (context: any) => {
|
||||
// Make zero axis slightly thicker
|
||||
if (context.tick?.value === 0) {
|
||||
return 2;
|
||||
}
|
||||
return 1;
|
||||
},
|
||||
color: colors.border || "",
|
||||
lineWidth: 1,
|
||||
},
|
||||
// Keep scales purely based on values, no fixed boundaries
|
||||
},
|
||||
|
|
@ -207,7 +208,7 @@ export default defineComponent({
|
|||
borderColor: colors.self,
|
||||
backgroundColor: colors.self,
|
||||
fill: false,
|
||||
tension: 0.25,
|
||||
tension: 0.2,
|
||||
borderJoinStyle: "round",
|
||||
borderCapStyle: "round",
|
||||
pointRadius: 0,
|
||||
|
|
@ -215,6 +216,7 @@ export default defineComponent({
|
|||
borderWidth: 3,
|
||||
yAxisID: "y",
|
||||
type: "line" as const,
|
||||
stack: false,
|
||||
},
|
||||
];
|
||||
},
|
||||
|
|
@ -253,7 +255,6 @@ export default defineComponent({
|
|||
return datasets;
|
||||
},
|
||||
getHouseholdDatasets() {
|
||||
// Household Demand (as power, not energy like in SocChart)
|
||||
const householdPower = this.evopt.req.time_series.gt.map(this.convertWToKW);
|
||||
|
||||
// Use the next color in the palette after all battery colors
|
||||
|
|
@ -262,7 +263,7 @@ export default defineComponent({
|
|||
|
||||
return [
|
||||
{
|
||||
label: "Household Demand",
|
||||
label: "Household",
|
||||
data: householdPower,
|
||||
backgroundColor: householdColor,
|
||||
borderWidth: 0,
|
||||
|
|
@ -273,6 +274,41 @@ export default defineComponent({
|
|||
];
|
||||
},
|
||||
|
||||
getGridPowerDatasets() {
|
||||
const datasets: any[] = [];
|
||||
|
||||
// Get grid import and export data
|
||||
const gridImport = this.evopt.res.grid_import || [];
|
||||
const gridExport = this.evopt.res.grid_export || [];
|
||||
|
||||
// Combine grid import and export into a single line
|
||||
// Grid import is positive, grid export is negative (one is always zero)
|
||||
const gridPower = gridImport.map((importValue, index) => {
|
||||
const exportValue = gridExport[index] || 0;
|
||||
const importKW = this.convertWToKW(importValue);
|
||||
const exportKW = this.convertWToKW(exportValue);
|
||||
// Return import as positive, export as negative
|
||||
return importKW > 0 ? importKW : -exportKW;
|
||||
});
|
||||
|
||||
datasets.push({
|
||||
label: "Grid Power",
|
||||
data: gridPower,
|
||||
borderColor: "#666666", // Dark gray
|
||||
backgroundColor: "#666666", // Dark gray
|
||||
fill: false,
|
||||
tension: 0.2,
|
||||
borderWidth: 2, // Same thickness as price chart lines
|
||||
pointRadius: 0,
|
||||
pointHoverRadius: 6,
|
||||
yAxisID: "y",
|
||||
type: "line" as const,
|
||||
stack: false,
|
||||
});
|
||||
|
||||
return datasets;
|
||||
},
|
||||
|
||||
convertWToKW: (watts: number): number => {
|
||||
return watts / 1000;
|
||||
},
|
||||
|
|
|
|||
69
assets/js/components/Optimize/CopyButton.vue
Normal file
69
assets/js/components/Optimize/CopyButton.vue
Normal file
|
|
@ -0,0 +1,69 @@
|
|||
<template>
|
||||
<button
|
||||
class="btn btn-link position-absolute text-primary rounded"
|
||||
:style="buttonStyle"
|
||||
:title="copied ? 'Copied!' : 'Copy to clipboard'"
|
||||
@click="handleCopy"
|
||||
>
|
||||
<shopicon-regular-checkmark v-if="copied"></shopicon-regular-checkmark>
|
||||
<shopicon-regular-copy v-else></shopicon-regular-copy>
|
||||
</button>
|
||||
</template>
|
||||
|
||||
<script lang="ts">
|
||||
import { defineComponent } from "vue";
|
||||
import "@h2d2/shopicons/es/regular/copy";
|
||||
import "@h2d2/shopicons/es/regular/checkmark";
|
||||
|
||||
export default defineComponent({
|
||||
name: "CopyButton",
|
||||
props: {
|
||||
content: {
|
||||
type: String,
|
||||
required: true,
|
||||
},
|
||||
top: {
|
||||
type: String,
|
||||
default: "1px",
|
||||
},
|
||||
right: {
|
||||
type: String,
|
||||
default: "1px",
|
||||
},
|
||||
padding: {
|
||||
type: String,
|
||||
default: "10px",
|
||||
},
|
||||
},
|
||||
data() {
|
||||
return {
|
||||
copied: false,
|
||||
};
|
||||
},
|
||||
computed: {
|
||||
buttonStyle() {
|
||||
return {
|
||||
top: this.top,
|
||||
right: this.right,
|
||||
padding: this.padding,
|
||||
backgroundColor: "var(--evcc-box)",
|
||||
};
|
||||
},
|
||||
},
|
||||
methods: {
|
||||
handleCopy() {
|
||||
navigator.clipboard
|
||||
.writeText(this.content)
|
||||
.then(() => {
|
||||
this.copied = true;
|
||||
setTimeout(() => {
|
||||
this.copied = false;
|
||||
}, 2000); // Reset after 2 seconds
|
||||
})
|
||||
.catch((err) => {
|
||||
console.error("Failed to copy to clipboard:", err);
|
||||
});
|
||||
},
|
||||
},
|
||||
});
|
||||
</script>
|
||||
|
|
@ -135,22 +135,9 @@ export default defineComponent({
|
|||
},
|
||||
grid: {
|
||||
drawOnChartArea: true,
|
||||
color: (context: any) => {
|
||||
// Make zero axis black to highlight
|
||||
if (context.tick?.value === 0) {
|
||||
return "#000000";
|
||||
}
|
||||
return colors.border || "#e0e0e0";
|
||||
},
|
||||
lineWidth: (context: any) => {
|
||||
// Make zero axis slightly thicker
|
||||
if (context.tick?.value === 0) {
|
||||
return 2;
|
||||
}
|
||||
return 1;
|
||||
},
|
||||
color: colors.border || "",
|
||||
lineWidth: 1,
|
||||
},
|
||||
// Remove fixed minimum to allow negative values
|
||||
},
|
||||
},
|
||||
};
|
||||
|
|
|
|||
|
|
@ -30,31 +30,6 @@
|
|||
{{ formatPower(value) }}
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td class="fw-medium text-nowrap text-start">
|
||||
{{ gridFeedinPriceLabel }}
|
||||
</td>
|
||||
<td
|
||||
v-for="(value, index) in evopt.req.time_series.p_E"
|
||||
:key="index"
|
||||
:class="['text-end', { 'text-muted': value === 0 }]"
|
||||
>
|
||||
{{ fmtPricePerKWh(value * 1000, currency, false, false) }}
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td class="fw-medium text-nowrap text-start">
|
||||
{{ gridImportPriceLabel }}
|
||||
</td>
|
||||
<td
|
||||
v-for="(value, index) in evopt.req.time_series.p_N"
|
||||
:key="index"
|
||||
:class="['text-end', { 'text-muted': value === 0 }]"
|
||||
>
|
||||
{{ fmtPricePerKWh(value * 1000, currency, false, false) }}
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td class="fw-medium text-nowrap text-start">Household Demand (kW)</td>
|
||||
<td
|
||||
|
|
@ -75,6 +50,30 @@
|
|||
{{ formatDuration(value) }}
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td class="fw-medium text-nowrap text-start">
|
||||
{{ gridImportPriceLabel }}
|
||||
</td>
|
||||
<td
|
||||
v-for="(value, index) in evopt.req.time_series.p_N"
|
||||
:key="index"
|
||||
:class="['text-end', { 'text-muted': value === 0 }]"
|
||||
>
|
||||
{{ fmtPricePerKWh(value * 1000, currency, false, false) }}
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td class="fw-medium text-nowrap text-start">
|
||||
{{ gridFeedinPriceLabel }}
|
||||
</td>
|
||||
<td
|
||||
v-for="(value, index) in evopt.req.time_series.p_E"
|
||||
:key="index"
|
||||
:class="['text-end', { 'text-muted': value === 0 }]"
|
||||
>
|
||||
{{ fmtPricePerKWh(value * 1000, currency, false, false) }}
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<!-- Response Data -->
|
||||
<tr class="table-secondary">
|
||||
|
|
@ -125,7 +124,7 @@
|
|||
class="battery-indicator me-2"
|
||||
:style="{ backgroundColor: batteryColors[batteryIndex] }"
|
||||
></span>
|
||||
{{ getBatteryTitle(batteryIndex) }} Response
|
||||
{{ getBatteryTitle(batteryIndex) }}
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
|
|
|
|||
56
assets/js/components/Optimize/compactJson.ts
Normal file
56
assets/js/components/Optimize/compactJson.ts
Normal file
|
|
@ -0,0 +1,56 @@
|
|||
/**
|
||||
* Custom JSON formatter that keeps arrays of primitive values on a single line
|
||||
*/
|
||||
export function formatCompactJson(obj: any, indent: number = 2): string {
|
||||
const spaces = " ".repeat(indent);
|
||||
|
||||
function stringify(value: any, depth: number): string {
|
||||
const currentIndent = spaces.repeat(depth);
|
||||
const nextIndent = spaces.repeat(depth + 1);
|
||||
|
||||
if (value === null) return "null";
|
||||
if (value === undefined) return "undefined";
|
||||
|
||||
// Handle primitive types
|
||||
if (typeof value !== "object") {
|
||||
return JSON.stringify(value);
|
||||
}
|
||||
|
||||
// Handle arrays
|
||||
if (Array.isArray(value)) {
|
||||
// Check if all elements are primitives (numbers, strings, booleans, null)
|
||||
const allPrimitive = value.every(
|
||||
(item) => item === null || item === undefined || typeof item !== "object"
|
||||
);
|
||||
|
||||
if (allPrimitive && value.length > 0) {
|
||||
// Format primitive array on single line
|
||||
const items = value.map((item) => JSON.stringify(item)).join(", ");
|
||||
return `[${items}]`;
|
||||
} else if (value.length === 0) {
|
||||
return "[]";
|
||||
} else {
|
||||
// Format complex array with indentation
|
||||
const items = value.map((item) => `${nextIndent}${stringify(item, depth + 1)}`).join(",\n");
|
||||
return `[\n${items}\n${currentIndent}]`;
|
||||
}
|
||||
}
|
||||
|
||||
// Handle objects
|
||||
const entries = Object.entries(value);
|
||||
if (entries.length === 0) {
|
||||
return "{}";
|
||||
}
|
||||
|
||||
const items = entries
|
||||
.map(([key, val]) => {
|
||||
const formattedValue = stringify(val, depth + 1);
|
||||
return `${nextIndent}${JSON.stringify(key)}: ${formattedValue}`;
|
||||
})
|
||||
.join(",\n");
|
||||
|
||||
return `{\n${items}\n${currentIndent}}`;
|
||||
}
|
||||
|
||||
return stringify(obj, 0);
|
||||
}
|
||||
|
|
@ -343,6 +343,7 @@ export type ValueOf<T> = T[keyof T];
|
|||
export interface EvOpt {
|
||||
req: OptimizationInput;
|
||||
res: OptimizationResult;
|
||||
curl: string;
|
||||
details: OptimizationDetails;
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
<template>
|
||||
<div class="container px-4 safe-area-inset">
|
||||
<TopHeader title="Optimize" />
|
||||
<TopHeader title="Optimize Debug" />
|
||||
<div class="alert alert-light mb-5">
|
||||
This page is for development purposes only. Gives insights into the upcoming
|
||||
optimization algorithm.
|
||||
|
|
@ -81,19 +81,44 @@
|
|||
:dimmed-battery-colors="dimmedBatteryColors"
|
||||
/>
|
||||
|
||||
<details class="mb-4">
|
||||
<summary class="btn btn-link text-decoration-none p-0 mb-3">
|
||||
<h3 class="fw-normal text-muted text-decoration-underline">
|
||||
Show Raw Data
|
||||
</h3>
|
||||
</summary>
|
||||
<div>
|
||||
<p>Request:</p>
|
||||
<pre>{{ JSON.stringify(evopt.req, null, 2) }}</pre>
|
||||
<p>Response:</p>
|
||||
<pre>{{ JSON.stringify(evopt.res, null, 2) }}</pre>
|
||||
<h3 class="fw-normal mb-4">Raw Data</h3>
|
||||
|
||||
<div class="mb-4">
|
||||
<p class="mb-2">Curl Command:</p>
|
||||
<div class="position-relative">
|
||||
<div
|
||||
class="p-3 rounded border overflow-auto"
|
||||
style="background-color: var(--evcc-box)"
|
||||
>
|
||||
<code class="text-nowrap d-block">{{ evopt.curl }}</code>
|
||||
</div>
|
||||
<CopyButton :content="evopt.curl" />
|
||||
</div>
|
||||
</details>
|
||||
</div>
|
||||
|
||||
<div class="mb-4">
|
||||
<p class="mb-2">Request:</p>
|
||||
<div class="position-relative">
|
||||
<pre
|
||||
class="p-3 rounded border overflow-auto"
|
||||
style="background-color: var(--evcc-box)"
|
||||
>{{ formattedRequest }}</pre
|
||||
>
|
||||
<CopyButton :content="formattedRequest" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="mb-4">
|
||||
<p class="mb-2">Response:</p>
|
||||
<div class="position-relative">
|
||||
<pre
|
||||
class="p-3 rounded border overflow-auto"
|
||||
style="background-color: var(--evcc-box)"
|
||||
>{{ formattedResponse }}</pre
|
||||
>
|
||||
<CopyButton :content="formattedResponse" />
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
<div v-else>
|
||||
|
|
@ -112,6 +137,8 @@ import SocChart from "../components/Optimize/SocChart.vue";
|
|||
import ChargeChart from "../components/Optimize/ChargeChart.vue";
|
||||
import PriceChart from "../components/Optimize/PriceChart.vue";
|
||||
import TimeSeriesDataTable from "../components/Optimize/TimeSeriesDataTable.vue";
|
||||
import CopyButton from "../components/Optimize/CopyButton.vue";
|
||||
import { formatCompactJson } from "../components/Optimize/compactJson";
|
||||
import store from "../store";
|
||||
import formatter from "../mixins/formatter";
|
||||
import colors from "../colors";
|
||||
|
|
@ -126,10 +153,11 @@ export default defineComponent({
|
|||
ChargeChart,
|
||||
PriceChart,
|
||||
TimeSeriesDataTable,
|
||||
CopyButton,
|
||||
},
|
||||
mixins: [formatter],
|
||||
head() {
|
||||
return { title: this.$t("energy.title") };
|
||||
return { title: "Optimize Debug" };
|
||||
},
|
||||
computed: {
|
||||
evopt() {
|
||||
|
|
@ -162,6 +190,12 @@ export default defineComponent({
|
|||
dimmedBatteryColors() {
|
||||
return this.batteryColors.map((color) => this.dimColorBy25Percent(color));
|
||||
},
|
||||
formattedRequest() {
|
||||
return this.evopt?.req ? formatCompactJson(this.evopt.req) : "";
|
||||
},
|
||||
formattedResponse() {
|
||||
return this.evopt?.res ? formatCompactJson(this.evopt.res) : "";
|
||||
},
|
||||
},
|
||||
methods: {
|
||||
dimColorBy25Percent(color: string): string {
|
||||
|
|
|
|||
|
|
@ -17,12 +17,12 @@ import (
|
|||
"github.com/evcc-io/evcc/util/sponsor"
|
||||
"github.com/jinzhu/now"
|
||||
"github.com/samber/lo"
|
||||
"moul.io/http2curl"
|
||||
)
|
||||
|
||||
var (
|
||||
eta = float32(0.9) // efficiency of the battery charging/discharging
|
||||
batteryPower = float32(6000) // power of the battery in W
|
||||
pa = float32(0.3 / 1e3) // Value per Wh at end of time horizon
|
||||
eta = float32(0.9) // efficiency of the battery charging/discharging
|
||||
batteryPower = float32(6000) // power of the battery in W
|
||||
|
||||
updated time.Time
|
||||
)
|
||||
|
|
@ -48,9 +48,25 @@ type responseDetails struct {
|
|||
}
|
||||
|
||||
func (site *Site) optimizerUpdateAsync(battery []measurement) {
|
||||
if err := site.optimizerUpdate(battery); err != nil {
|
||||
site.log.ERROR.Println("optimizer:", err)
|
||||
if time.Since(updated) < 5*time.Minute {
|
||||
return
|
||||
}
|
||||
|
||||
var err error
|
||||
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
err = fmt.Errorf("panic %v", r)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
site.log.ERROR.Println("optimizer:", err)
|
||||
}
|
||||
}()
|
||||
|
||||
err = site.optimizerUpdate(battery)
|
||||
|
||||
updated = time.Now()
|
||||
}
|
||||
|
||||
func (site *Site) optimizerUpdate(battery []measurement) error {
|
||||
|
|
@ -59,14 +75,6 @@ func (site *Site) optimizerUpdate(battery []measurement) error {
|
|||
return nil
|
||||
}
|
||||
|
||||
if time.Since(updated) < time.Minute {
|
||||
return nil
|
||||
}
|
||||
|
||||
defer func() {
|
||||
updated = time.Now()
|
||||
}()
|
||||
|
||||
solarTariff := site.GetTariff(api.TariffUsageSolar)
|
||||
solarRates, err := solarTariff.Rates()
|
||||
if err != nil {
|
||||
|
|
@ -100,6 +108,9 @@ func (site *Site) optimizerUpdate(battery []measurement) error {
|
|||
}
|
||||
|
||||
req := evopt.OptimizationInput{
|
||||
Strategy: &evopt.OptimizerStrategy{
|
||||
ChargingStrategy: lo.ToPtr(evopt.ChargeBeforeExport),
|
||||
},
|
||||
EtaC: &eta,
|
||||
EtaD: &eta,
|
||||
TimeSeries: evopt.TimeSeries{
|
||||
|
|
@ -111,6 +122,9 @@ func (site *Site) optimizerUpdate(battery []measurement) error {
|
|||
},
|
||||
}
|
||||
|
||||
// end of horizon Wh value
|
||||
pa := lo.Min(req.TimeSeries.PN)
|
||||
|
||||
details := responseDetails{
|
||||
Timestamps: asTimestamps(dt),
|
||||
}
|
||||
|
|
@ -202,12 +216,12 @@ func (site *Site) optimizerUpdate(battery []measurement) error {
|
|||
return err
|
||||
}
|
||||
|
||||
var curl *http2curl.CurlCommand
|
||||
resp, err := apiClient.PostOptimizeChargeScheduleWithResponse(context.TODO(), req, func(_ context.Context, req *http.Request) error {
|
||||
if sponsor.IsAuthorized() {
|
||||
req.Header.Set("Authorization", "Bearer "+sponsor.Token)
|
||||
}
|
||||
// command, _ := http2curl.GetCurlCommand(req)
|
||||
// log.TRACE.Println("\n" + command.String())
|
||||
curl, _ = http2curl.GetCurlCommand(req)
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
|
|
@ -229,16 +243,19 @@ func (site *Site) optimizerUpdate(battery []measurement) error {
|
|||
site.publish("evopt", struct {
|
||||
Req evopt.OptimizationInput `json:"req"`
|
||||
Res evopt.OptimizationResult `json:"res"`
|
||||
Curl string `json:"curl"`
|
||||
Details responseDetails `json:"details"`
|
||||
}{
|
||||
Req: req,
|
||||
Res: *resp.JSON200,
|
||||
Curl: curl.String(),
|
||||
Details: details,
|
||||
})
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// loadpointProfile returns the loadpoint's charging profile in Wh
|
||||
// TODO consider charging efficiency
|
||||
func loadpointProfile(lp loadpoint.API, firstSlotDuration time.Duration, minLen int) []float64 {
|
||||
mode := lp.GetMode()
|
||||
|
|
@ -275,86 +292,75 @@ func loadpointProfile(lp loadpoint.API, firstSlotDuration time.Duration, minLen
|
|||
return res
|
||||
}
|
||||
|
||||
// homeProfile returns the home base load in Wh
|
||||
func (site *Site) homeProfile(minLen int) []float64 {
|
||||
now := time.Now().Truncate(time.Hour)
|
||||
|
||||
profile, err := metrics.Profile(now.AddDate(0, 0, -30))
|
||||
// kWh over last 30 days
|
||||
profile, err := metrics.Profile(now.BeginningOfDay().AddDate(0, 0, -30))
|
||||
if err != nil {
|
||||
site.log.ERROR.Printf("household metrics profile: %v", err)
|
||||
site.log.WARN.Println("optimizer:", err)
|
||||
return lo.RepeatBy(minLen, func(_ int) float64 {
|
||||
return 0
|
||||
})
|
||||
}
|
||||
|
||||
res := slotsToHours(now, profile)
|
||||
for len(res) < minLen {
|
||||
res = append(res, profile[:]...)
|
||||
// max 4 days
|
||||
hours := make([]float64, 0, minLen+1)
|
||||
|
||||
combined := combineSlots(profile[:])
|
||||
for len(hours) <= minLen+24 { // allow for prorating first day
|
||||
hours = append(hours, combined...)
|
||||
}
|
||||
|
||||
res := prorateFirstHour(time.Now(), hours)
|
||||
if len(res) < minLen {
|
||||
panic("minimum home profile length failed")
|
||||
}
|
||||
if len(res) > minLen {
|
||||
res = res[:minLen]
|
||||
}
|
||||
|
||||
return res
|
||||
// convert to Wh
|
||||
return lo.Map(res, func(v float64, i int) float64 {
|
||||
return v * 1e3
|
||||
})
|
||||
}
|
||||
|
||||
// slotsToHours converts a daily consumption profile consisting of 96 15min slots
|
||||
// to an hourly profile by totaling the values per hour and returning the first minLen values.
|
||||
// the first value is fractional part of the the current hour, prorated.
|
||||
func slotsToHours(now time.Time, profile *[96]float64) []float64 {
|
||||
// combineSlots combines 15-minute slots into hourly values
|
||||
func combineSlots(profile []float64) []float64 {
|
||||
if profile == nil {
|
||||
return []float64{}
|
||||
}
|
||||
|
||||
// Calculate current 15-minute slot within the day (0-95)
|
||||
currentMinute := now.Hour()*60 + now.Minute()
|
||||
currentSlot := currentMinute / 15
|
||||
result := make([]float64, 0, 24)
|
||||
|
||||
// Calculate remaining minutes in current hour for prorating
|
||||
minutesIntoHour := now.Minute()
|
||||
remainingMinutesInHour := 60 - minutesIntoHour
|
||||
|
||||
var result []float64
|
||||
|
||||
// Handle the partial current hour first
|
||||
if remainingMinutesInHour > 0 && currentSlot < 96 {
|
||||
var partialHourValue float64
|
||||
slotsInCurrentHour := remainingMinutesInHour / 15
|
||||
if remainingMinutesInHour%15 != 0 {
|
||||
slotsInCurrentHour++
|
||||
// Process complete hours starting from the start slot
|
||||
for hour := range 24 {
|
||||
var sum float64
|
||||
for i := range 4 {
|
||||
sum += profile[4*hour+i]
|
||||
}
|
||||
|
||||
// Sum the remaining slots in the current hour
|
||||
for i := 0; i < slotsInCurrentHour && currentSlot+i < 96; i++ {
|
||||
if currentSlot+i >= 0 {
|
||||
partialHourValue += profile[currentSlot+i]
|
||||
}
|
||||
}
|
||||
|
||||
// Prorate based on the fraction of the hour remaining
|
||||
fractionOfHour := float64(remainingMinutesInHour) / 60.0
|
||||
partialHourValue *= fractionOfHour
|
||||
|
||||
result = append(result, float64(partialHourValue))
|
||||
}
|
||||
|
||||
// Process complete hours starting from the next hour
|
||||
nextHourSlot := (currentSlot/4 + 1) * 4
|
||||
|
||||
// Don't wrap around at end of day - only process remaining hours
|
||||
for hourSlot := nextHourSlot; len(result) < 24 && hourSlot < 96; hourSlot += 4 {
|
||||
var hourValue float64
|
||||
|
||||
// Sum 4 slots (4 × 15min = 60min = 1 hour)
|
||||
for i := 0; i < 4 && hourSlot+i < 96; i++ {
|
||||
hourValue += profile[hourSlot+i]
|
||||
}
|
||||
|
||||
result = append(result, float64(hourValue))
|
||||
result = append(result, sum)
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
// prorateFirstHour strips away any slots before "now" and prorates the first remaining hour
|
||||
// based on remaining time in current hour. The profile contains hourly slots (0-23) that repeat for multiple days.
|
||||
func prorateFirstHour(now time.Time, profile []float64) []float64 {
|
||||
// Take only slots from current hour onwards
|
||||
res := profile[now.Hour():]
|
||||
|
||||
// Prorate the first hour based on remaining time in current hour
|
||||
if minutesIntoHour := now.Minute(); minutesIntoHour > 0 {
|
||||
fractionOfHour := float64(60-minutesIntoHour) / 60.0
|
||||
res[0] *= fractionOfHour
|
||||
}
|
||||
|
||||
return res
|
||||
}
|
||||
|
||||
func ratesToEnergy(rr api.Rates, firstSlot time.Duration) (api.Rates, error) {
|
||||
res := make(api.Rates, 0, len(rr))
|
||||
|
||||
|
|
|
|||
|
|
@ -95,111 +95,112 @@ func TestUpdateHouseholdProfile(t *testing.T) {
|
|||
}
|
||||
}
|
||||
|
||||
func TestSlotsToHours(t *testing.T) {
|
||||
// Create a test profile with known values
|
||||
// Slots 0-3: hour 0 (00:00-01:00), values 1,2,3,4 -> sum = 10
|
||||
// Slots 4-7: hour 1 (01:00-02:00), values 5,6,7,8 -> sum = 26
|
||||
// etc.
|
||||
var profile [96]float64
|
||||
func TestCombineSlots(t *testing.T) {
|
||||
// Create test profile with known values
|
||||
// Slots 0-3: hour 0, values 1,2,3,4 -> sum = 10
|
||||
// Slots 4-7: hour 1, values 5,6,7,8 -> sum = 26
|
||||
// Slots 8-11: hour 2, values 9,10,11,12 -> sum = 42
|
||||
profile := make([]float64, 96)
|
||||
for i := range 96 {
|
||||
profile[i] = float64(i + 1)
|
||||
}
|
||||
|
||||
t.Run("standard profile", func(t *testing.T) {
|
||||
result := combineSlots(profile)
|
||||
require.Equal(t, 24, len(result), "should return 24 hours")
|
||||
require.InDelta(t, 10, result[0], 0.01, "hour 0: slots 0-3 (1+2+3+4)")
|
||||
require.InDelta(t, 26, result[1], 0.01, "hour 1: slots 4-7 (5+6+7+8)")
|
||||
require.InDelta(t, 42, result[2], 0.01, "hour 2: slots 8-11 (9+10+11+12)")
|
||||
require.InDelta(t, 378, result[23], 0.01, "hour 23: slots 92-95 (93+94+95+96)")
|
||||
})
|
||||
|
||||
t.Run("nil profile", func(t *testing.T) {
|
||||
result := combineSlots(nil)
|
||||
require.Empty(t, result)
|
||||
})
|
||||
}
|
||||
|
||||
func TestProrateFirstHour(t *testing.T) {
|
||||
// Create test hourly profile with known values
|
||||
// Hour 0: 10, Hour 1: 20, Hour 2: 30, etc.
|
||||
profile := make([]float64, 24)
|
||||
for i := range 24 {
|
||||
profile[i] = float64((i + 1) * 10)
|
||||
}
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
now time.Time
|
||||
expected []float32
|
||||
name string
|
||||
now time.Time
|
||||
expectedFirstHour float64
|
||||
expectedLength int
|
||||
expectedSecond float64
|
||||
}{
|
||||
{
|
||||
name: "start of hour",
|
||||
now: time.Date(2024, 1, 1, 0, 0, 0, 0, time.UTC), // 00:00
|
||||
expected: []float32{
|
||||
10, // hour 0: slots 0-3 (1+2+3+4)
|
||||
26, // hour 1: slots 4-7 (5+6+7+8)
|
||||
42, // hour 2: slots 8-11 (9+10+11+12)
|
||||
},
|
||||
name: "start of hour 0 - no proration",
|
||||
now: time.Date(2024, 1, 1, 0, 0, 0, 0, time.UTC),
|
||||
expectedFirstHour: 10.0, // full hour: no proration applied
|
||||
expectedLength: 24, // all 24 hours remain
|
||||
expectedSecond: 20.0, // hour 1 value
|
||||
},
|
||||
{
|
||||
name: "middle of hour",
|
||||
now: time.Date(2024, 1, 1, 0, 30, 0, 0, time.UTC), // 00:30
|
||||
expected: []float32{
|
||||
3.5, // remaining 30min of hour 0: slots 2-3 (3+4) * 0.5 = 7 * 0.5 = 3.5
|
||||
26, // hour 1: slots 4-7 (5+6+7+8)
|
||||
42, // hour 2: slots 8-11 (9+10+11+12)
|
||||
},
|
||||
name: "30 minutes into hour 0",
|
||||
now: time.Date(2024, 1, 1, 0, 30, 0, 0, time.UTC),
|
||||
expectedFirstHour: 5.0, // 30min remaining: 10 * 0.5 = 5
|
||||
expectedLength: 24, // all 24 hours remain
|
||||
expectedSecond: 20.0, // hour 1 value unchanged
|
||||
},
|
||||
{
|
||||
name: "quarter past hour",
|
||||
now: time.Date(2024, 1, 1, 0, 15, 0, 0, time.UTC), // 00:15
|
||||
expected: []float32{
|
||||
6.75, // remaining 45min of hour 0: slots 1-3 (2+3+4) * 0.75 = 9 * 0.75 = 6.75
|
||||
26, // hour 1: slots 4-7 (5+6+7+8)
|
||||
42, // hour 2: slots 8-11 (9+10+11+12)
|
||||
},
|
||||
name: "start of hour 2 - no proration",
|
||||
now: time.Date(2024, 1, 1, 2, 0, 0, 0, time.UTC),
|
||||
expectedFirstHour: 30.0, // hour 2 value: 30
|
||||
expectedLength: 22, // hours 2-23 remain (22 hours)
|
||||
expectedSecond: 40.0, // hour 3 value
|
||||
},
|
||||
{
|
||||
name: "middle of slot early",
|
||||
now: time.Date(2024, 1, 1, 0, 10, 0, 0, time.UTC), // 00:10 (middle of slot 0)
|
||||
expected: []float32{
|
||||
8.33, // remaining 50min of hour 0: slots 0-3 (1+2+3+4) * (50/60) = 10 * 0.833 = 8.33
|
||||
26, // hour 1: slots 4-7 (5+6+7+8)
|
||||
42, // hour 2: slots 8-11 (9+10+11+12)
|
||||
},
|
||||
name: "15 minutes into hour 2",
|
||||
now: time.Date(2024, 1, 1, 2, 15, 0, 0, time.UTC),
|
||||
expectedFirstHour: 22.5, // 45min remaining: 30 * 0.75 = 22.5
|
||||
expectedLength: 22, // hours 2-23 remain (22 hours)
|
||||
expectedSecond: 40.0, // hour 3 value unchanged
|
||||
},
|
||||
{
|
||||
name: "middle of slot late",
|
||||
now: time.Date(2024, 1, 1, 0, 50, 0, 0, time.UTC), // 00:50 (middle of slot 3)
|
||||
expected: []float32{
|
||||
0.67, // remaining 10min of hour 0: slot 3 (4) * (10/60) = 4 * 0.167 = 0.67
|
||||
26, // hour 1: slots 4-7 (5+6+7+8)
|
||||
42, // hour 2: slots 8-11 (9+10+11+12)
|
||||
},
|
||||
name: "45 minutes into hour 5",
|
||||
now: time.Date(2024, 1, 1, 5, 45, 0, 0, time.UTC),
|
||||
expectedFirstHour: 15.0, // 15min remaining: 60 * 0.25 = 15.0
|
||||
expectedLength: 19, // hours 5-23 remain (19 hours)
|
||||
expectedSecond: 70.0, // hour 6 value unchanged
|
||||
},
|
||||
{
|
||||
name: "10 minutes into hour 10",
|
||||
now: time.Date(2024, 1, 1, 10, 10, 0, 0, time.UTC),
|
||||
expectedFirstHour: 91.67, // 50min remaining: 110 * (50/60) = 91.67
|
||||
expectedLength: 14, // hours 10-23 remain (14 hours)
|
||||
expectedSecond: 120.0, // hour 11 value unchanged
|
||||
},
|
||||
{
|
||||
name: "near end of day - hour 23",
|
||||
now: time.Date(2024, 1, 1, 23, 30, 0, 0, time.UTC),
|
||||
expectedFirstHour: 120.0, // 30min remaining: 240 * 0.5 = 120
|
||||
expectedLength: 1, // only hour 23 remains
|
||||
expectedSecond: 0.0, // no second hour
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
result := slotsToHours(tt.now, &profile)
|
||||
require.GreaterOrEqual(t, len(result), len(tt.expected), "insufficient result length")
|
||||
|
||||
for i, expected := range tt.expected {
|
||||
require.InDelta(t, expected, result[i], 0.01, "mismatch at index %d", i)
|
||||
result := prorateFirstHour(tt.now, profile)
|
||||
require.Equal(t, tt.expectedLength, len(result), "length mismatch")
|
||||
if len(result) > 0 {
|
||||
require.InDelta(t, tt.expectedFirstHour, result[0], 0.01, "first hour value mismatch")
|
||||
// Verify second hour is unchanged (if exists)
|
||||
if len(result) > 1 {
|
||||
require.Equal(t, tt.expectedSecond, result[1], "second hour should be unchanged")
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestSlotsToHoursEdgeCases(t *testing.T) {
|
||||
var profile [96]float64
|
||||
for i := range 96 {
|
||||
profile[i] = float64(i + 1)
|
||||
}
|
||||
|
||||
t.Run("nil profile", func(t *testing.T) {
|
||||
result := slotsToHours(time.Now(), nil)
|
||||
require.Empty(t, result)
|
||||
})
|
||||
|
||||
t.Run("end of day", func(t *testing.T) {
|
||||
now := time.Date(2024, 1, 1, 23, 45, 0, 0, time.UTC) // 23:45
|
||||
result := slotsToHours(now, &profile)
|
||||
|
||||
// Should only return the remaining 15min of the current hour
|
||||
expected := []float32{24} // slot 95 (value 96) * 0.25 (15min/60min)
|
||||
require.Equal(t, len(expected), len(result))
|
||||
require.InDelta(t, expected[0], result[0], 0.01)
|
||||
})
|
||||
|
||||
t.Run("exact hour boundary", func(t *testing.T) {
|
||||
now := time.Date(2024, 1, 1, 1, 0, 0, 0, time.UTC) // 01:00
|
||||
result := slotsToHours(now, &profile)
|
||||
|
||||
// Should start from hour 1 (slots 4-7)
|
||||
require.GreaterOrEqual(t, len(result), 1)
|
||||
require.InDelta(t, float32(26), result[0], 0.01) // 5+6+7+8 = 26
|
||||
})
|
||||
}
|
||||
|
||||
func TestLoadpointProfile(t *testing.T) {
|
||||
ctrl := gomock.NewController(t)
|
||||
|
||||
|
|
|
|||
3
go.mod
3
go.mod
|
|
@ -9,7 +9,7 @@ require (
|
|||
github.com/Masterminds/sprig/v3 v3.3.0
|
||||
github.com/PuerkitoBio/goquery v1.10.3
|
||||
github.com/WulfgarW/sensonet v0.0.4
|
||||
github.com/andig/evopt v0.0.0-20250806061439-fc50d99582e9
|
||||
github.com/andig/evopt v0.0.0-20250820184747-c28617953a3c
|
||||
github.com/andig/go-powerwall v0.2.1-0.20230808194509-dd70cdb6e140
|
||||
github.com/andig/gosunspec v0.0.0-20240918203654-860ce51d602b
|
||||
github.com/andig/mbserver v0.0.0-20230310211055-1d29cbb5820e
|
||||
|
|
@ -114,6 +114,7 @@ require (
|
|||
google.golang.org/grpc v1.74.2
|
||||
google.golang.org/protobuf v1.36.6
|
||||
gorm.io/gorm v1.30.1
|
||||
moul.io/http2curl v1.0.0
|
||||
)
|
||||
|
||||
require (
|
||||
|
|
|
|||
6
go.sum
6
go.sum
|
|
@ -33,8 +33,8 @@ github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751/go.mod h1:LOuy
|
|||
github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0=
|
||||
github.com/alecthomas/units v0.0.0-20190717042225-c3de453c63f4/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0=
|
||||
github.com/alecthomas/units v0.0.0-20190924025748-f65c72e2690d/go.mod h1:rBZYJk541a8SKzHPHnH3zbiI+7dagKZ0cgpgrD7Fyho=
|
||||
github.com/andig/evopt v0.0.0-20250806061439-fc50d99582e9 h1:tWGkO2RipG162BGfxuLj3TbxA2BiI/oHH7ftQGUJ/VI=
|
||||
github.com/andig/evopt v0.0.0-20250806061439-fc50d99582e9/go.mod h1:TE4sjD3Fxu4Jn49ecE6H6EdHliJA5KnkRfY6WGdHBu0=
|
||||
github.com/andig/evopt v0.0.0-20250820184747-c28617953a3c h1:tEJUsri5R7OP/Zs9P1eh1uASs6oStsZJIrKFF3bofV0=
|
||||
github.com/andig/evopt v0.0.0-20250820184747-c28617953a3c/go.mod h1:TE4sjD3Fxu4Jn49ecE6H6EdHliJA5KnkRfY6WGdHBu0=
|
||||
github.com/andig/go-powerwall v0.2.1-0.20230808194509-dd70cdb6e140 h1:C93T8vg7CN4Q4BBDbBMOvBoTYBA+CaBEvlY2SZF8aa0=
|
||||
github.com/andig/go-powerwall v0.2.1-0.20230808194509-dd70cdb6e140/go.mod h1:Xk09mD+7RTCuuHMX5RxlqgEUeh9oZdIX0rL0qiY6l/4=
|
||||
github.com/andig/gosunspec v0.0.0-20240918203654-860ce51d602b h1:81UMfM949I7StrRay7YDUZazY8M1u/JHkzwcFEjiilQ=
|
||||
|
|
@ -1077,6 +1077,8 @@ modernc.org/strutil v1.2.1 h1:UneZBkQA+DX2Rp35KcM69cSsNES9ly8mQWD71HKlOA0=
|
|||
modernc.org/strutil v1.2.1/go.mod h1:EHkiggD70koQxjVdSBM3JKM7k6L0FbGE5eymy9i3B9A=
|
||||
modernc.org/token v1.1.0 h1:Xl7Ap9dKaEs5kLoOQeQmPWevfnk/DM5qcLcYlA8ys6Y=
|
||||
modernc.org/token v1.1.0/go.mod h1:UGzOrNV1mAFSEB63lOFHIpNRUVMvYTc6yu1SMY/XTDM=
|
||||
moul.io/http2curl v1.0.0 h1:6XwpyZOYsgZJrU8exnG87ncVkU1FVCcTRpwzOkTDUi8=
|
||||
moul.io/http2curl v1.0.0/go.mod h1:f6cULg+e4Md/oW1cYmwW4IWQOVl2lGbmCNGOHvzX2kE=
|
||||
pgregory.net/rapid v1.1.0 h1:CMa0sjHSru3puNx+J0MIAuiiEV4N0qj8/cMWGBBCsjw=
|
||||
pgregory.net/rapid v1.1.0/go.mod h1:PY5XlDGj0+V1FCq0o192FdRhpKHGTRIWBgqjDBTrq04=
|
||||
sigs.k8s.io/yaml v1.1.0/go.mod h1:UJmg0vDUVViEyp3mgSv9WPwZCDxu4rQW1olrI1uml+o=
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue