112 lines
2.2 KiB
Go
112 lines
2.2 KiB
Go
package tariff
|
|
|
|
import (
|
|
"errors"
|
|
"fmt"
|
|
"net/url"
|
|
"slices"
|
|
"strings"
|
|
"sync"
|
|
"time"
|
|
|
|
"github.com/cenkalti/backoff/v4"
|
|
"github.com/evcc-io/evcc/api"
|
|
"github.com/evcc-io/evcc/tariff/elering"
|
|
"github.com/evcc-io/evcc/util"
|
|
"github.com/evcc-io/evcc/util/request"
|
|
)
|
|
|
|
type Elering struct {
|
|
*embed
|
|
log *util.Logger
|
|
region string
|
|
data *util.Monitor[api.Rates]
|
|
}
|
|
|
|
var _ api.Tariff = (*Elering)(nil)
|
|
|
|
func init() {
|
|
registry.Add("elering", NewEleringFromConfig)
|
|
}
|
|
|
|
func NewEleringFromConfig(other map[string]any) (api.Tariff, error) {
|
|
var cc struct {
|
|
embed `mapstructure:",squash"`
|
|
Region string
|
|
}
|
|
|
|
if err := util.DecodeOther(other, &cc); err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
if cc.Region == "" {
|
|
return nil, errors.New("missing region")
|
|
}
|
|
|
|
if err := cc.init(); err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
t := &Elering{
|
|
embed: &cc.embed,
|
|
log: util.NewLogger("elering"),
|
|
region: strings.ToLower(cc.Region),
|
|
data: util.NewMonitor[api.Rates](2 * time.Hour),
|
|
}
|
|
|
|
return runOrError(t)
|
|
}
|
|
|
|
func (t *Elering) run(done chan error) {
|
|
var once sync.Once
|
|
client := request.NewHelper(t.log)
|
|
|
|
for tick := time.Tick(time.Hour); ; <-tick {
|
|
var res elering.NpsPrice
|
|
|
|
ts := time.Now().Truncate(time.Hour)
|
|
uri := fmt.Sprintf("%s/nps/price?start=%s&end=%s", elering.URI,
|
|
url.QueryEscape(ts.Format(time.RFC3339)),
|
|
url.QueryEscape(ts.Add(48*time.Hour).Format(time.RFC3339)))
|
|
|
|
if err := backoff.Retry(func() error {
|
|
return backoffPermanentError(client.GetJSON(uri, &res))
|
|
}, bo()); err != nil {
|
|
if reportError(&once, done, err) {
|
|
return
|
|
}
|
|
|
|
t.log.ERROR.Println(err)
|
|
continue
|
|
}
|
|
|
|
data := make(api.Rates, 0, len(res.Data[t.region]))
|
|
for _, r := range res.Data[t.region] {
|
|
ts := time.Unix(r.Timestamp, 0).Local()
|
|
|
|
ar := api.Rate{
|
|
Start: ts,
|
|
End: ts.Add(time.Hour),
|
|
Value: t.totalPrice(r.Price/1e3, ts),
|
|
}
|
|
data = append(data, ar)
|
|
}
|
|
|
|
mergeRates(t.data, data)
|
|
once.Do(func() { close(done) })
|
|
}
|
|
}
|
|
|
|
// Rates implements the api.Tariff interface
|
|
func (t *Elering) Rates() (api.Rates, error) {
|
|
var res api.Rates
|
|
err := t.data.GetFunc(func(val api.Rates) {
|
|
res = slices.Clone(val)
|
|
})
|
|
return res, err
|
|
}
|
|
|
|
// Type implements the api.Tariff interface
|
|
func (t *Elering) Type() api.TariffType {
|
|
return api.TariffTypePriceForecast
|
|
}
|