Add Octopus Energy Italy tariff (#31505)
This commit is contained in:
parent
8a771d5fb3
commit
de976b7aa2
13 changed files with 360 additions and 67 deletions
99
tariff/octopuskraken/graphql/api.go
Normal file
99
tariff/octopuskraken/graphql/api.go
Normal file
|
|
@ -0,0 +1,99 @@
|
|||
package graphql
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/evcc-io/evcc/util"
|
||||
"github.com/evcc-io/evcc/util/request"
|
||||
"github.com/evcc-io/evcc/util/transport"
|
||||
"github.com/hasura/go-graphql-client"
|
||||
"golang.org/x/oauth2"
|
||||
)
|
||||
|
||||
// BaseURI is Octopus Energy Germany's Kraken API root.
|
||||
// The implementation in this file follows the published example at https://octopusenergy.de/blog/wohnen/dynamisch-sparen-per-api
|
||||
const BaseURI = "https://api.oeg-kraken.energy/v1/graphql/"
|
||||
|
||||
// ItBaseURI is Octopus Energy Italy's Kraken API root, the same platform under its own domain.
|
||||
const ItBaseURI = "https://api.oeit-kraken.energy/v1/graphql/"
|
||||
|
||||
// Client provides an interface for communicating with an Octopus Energy Kraken platform instance.
|
||||
type Client struct {
|
||||
log *util.Logger
|
||||
*graphql.Client
|
||||
accountNumber string
|
||||
}
|
||||
|
||||
// NewClient returns a new, authenticated instance for the given Kraken instance
|
||||
// (other regional Octopus companies run the same platform under their own baseURI).
|
||||
func NewClient(log *util.Logger, baseURI, email, password, accountNumber string) (*Client, error) {
|
||||
ts := oauth2.ReuseTokenSource(nil, &tokenSource{
|
||||
log: log,
|
||||
baseURI: baseURI,
|
||||
email: email,
|
||||
password: password,
|
||||
})
|
||||
|
||||
cli := request.NewClient(log)
|
||||
cli.Transport = &transport.Decorator{
|
||||
Decorator: func(req *http.Request) error {
|
||||
token, err := ts.Token()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// Kraken API requires Authorization header without "Bearer" prefix
|
||||
req.Header.Set("Authorization", token.AccessToken)
|
||||
return nil
|
||||
},
|
||||
Base: cli.Transport,
|
||||
}
|
||||
|
||||
gq := &Client{
|
||||
log: log,
|
||||
accountNumber: accountNumber,
|
||||
Client: graphql.NewClient(baseURI, cli),
|
||||
}
|
||||
|
||||
return gq, nil
|
||||
}
|
||||
|
||||
// ActiveAgreement queries the Kraken API and returns the active electricity supply agreement.
|
||||
func (c *Client) ActiveAgreement() (Agreement, error) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), time.Second*10)
|
||||
defer cancel()
|
||||
|
||||
var q getAgreements
|
||||
if err := c.Client.Query(ctx, &q, map[string]any{
|
||||
"accountNumber": c.accountNumber,
|
||||
}); err != nil {
|
||||
return Agreement{}, err
|
||||
}
|
||||
|
||||
if len(q.Account.Properties) == 0 {
|
||||
return Agreement{}, errors.New("no properties found")
|
||||
}
|
||||
|
||||
agr, err := findActiveAgreement(&q)
|
||||
if err != nil {
|
||||
return Agreement{}, err
|
||||
}
|
||||
|
||||
return *agr, nil
|
||||
}
|
||||
|
||||
// findActiveAgreement returns the first agreement marked IsActive across all properties.
|
||||
func findActiveAgreement(q *getAgreements) (*Agreement, error) {
|
||||
for _, property := range q.Account.Properties {
|
||||
for _, malo := range property.ElectricityMalos {
|
||||
for _, agr := range malo.Agreements {
|
||||
if agr.IsActive {
|
||||
return &agr, nil
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil, errors.New("no active agreement found")
|
||||
}
|
||||
71
tariff/octopuskraken/graphql/tokensource.go
Normal file
71
tariff/octopuskraken/graphql/tokensource.go
Normal file
|
|
@ -0,0 +1,71 @@
|
|||
package graphql
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/evcc-io/evcc/util"
|
||||
"github.com/evcc-io/evcc/util/request"
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
"github.com/hasura/go-graphql-client"
|
||||
"golang.org/x/oauth2"
|
||||
)
|
||||
|
||||
// ErrAuthFailed indicates the Kraken API rejected the supplied credentials.
|
||||
// Callers should treat this as permanent and stop retrying to avoid account lockouts.
|
||||
var ErrAuthFailed = errors.New("authentication failed")
|
||||
|
||||
type tokenSource struct {
|
||||
log *util.Logger
|
||||
baseURI string
|
||||
email, password string
|
||||
}
|
||||
|
||||
var _ oauth2.TokenSource = (*tokenSource)(nil)
|
||||
|
||||
// RefreshToken implements oauth.TokenRefresher to obtain a new JWT token.
|
||||
// It parses the JWT to extract the actual expiry time from the token claims.
|
||||
func (ts *tokenSource) Token() (*oauth2.Token, error) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), time.Second*10)
|
||||
defer cancel()
|
||||
|
||||
// Create a temporary client without authentication for the token request
|
||||
cli := request.NewClient(ts.log)
|
||||
tempClient := graphql.NewClient(ts.baseURI, cli)
|
||||
|
||||
var q krakenTokenAuthentication
|
||||
if err := tempClient.Mutate(ctx, &q, map[string]any{
|
||||
"email": ts.email,
|
||||
"password": ts.password,
|
||||
}); err != nil {
|
||||
// Any GraphQL error response from obtainKrakenToken is an application-level
|
||||
// rejection (bad credentials, account locked, etc.) — repeating the request
|
||||
// will not change the outcome and continued retries can lock the account.
|
||||
// Network/transport failures don't surface as graphql.Errors and stay
|
||||
// transient via the wrapped path below.
|
||||
if _, ok := errors.AsType[graphql.Errors](err); ok {
|
||||
return nil, fmt.Errorf("%w: %v", ErrAuthFailed, err)
|
||||
}
|
||||
return nil, fmt.Errorf("authentication failed: %w", err)
|
||||
}
|
||||
|
||||
// Parse JWT to extract expiry time using RegisteredClaims
|
||||
// We use ParseUnverified since we don't have the signing key and trust the token from the API
|
||||
var claims jwt.RegisteredClaims
|
||||
if _, _, err := jwt.NewParser(jwt.WithoutClaimsValidation()).ParseUnverified(q.ObtainKrakenToken.Token, &claims); err != nil {
|
||||
return nil, fmt.Errorf("failed to parse JWT: %w", err)
|
||||
}
|
||||
|
||||
// Extract expiry from JWT claims
|
||||
expiry := time.Now().Add(time.Hour)
|
||||
if claims.ExpiresAt != nil {
|
||||
expiry = claims.ExpiresAt.Time
|
||||
}
|
||||
|
||||
return &oauth2.Token{
|
||||
AccessToken: q.ObtainKrakenToken.Token,
|
||||
Expiry: expiry,
|
||||
}, nil
|
||||
}
|
||||
97
tariff/octopuskraken/graphql/types.go
Normal file
97
tariff/octopuskraken/graphql/types.go
Normal file
|
|
@ -0,0 +1,97 @@
|
|||
package graphql
|
||||
|
||||
import "time"
|
||||
|
||||
// krakenTokenAuthentication is a representation of a GraphQL query for obtaining a Kraken API token.
|
||||
type krakenTokenAuthentication struct {
|
||||
ObtainKrakenToken struct {
|
||||
Token string
|
||||
} `graphql:"obtainKrakenToken(input: {email: $email, password: $password})"`
|
||||
}
|
||||
|
||||
// Agreement represents a single electricity supply agreement.
|
||||
// The unitRateForecast field is only populated for dynamic tariffs.
|
||||
// The unitRateInformation field covers all tariff types (Simple, TimeOfUse).
|
||||
type Agreement struct {
|
||||
IsActive bool
|
||||
ValidFrom time.Time
|
||||
ValidTo time.Time
|
||||
UnitRateInformation AgreementUnitRateInformation
|
||||
UnitRateForecast []UnitRateForecast
|
||||
Product product
|
||||
}
|
||||
|
||||
type getAgreements struct {
|
||||
Account struct {
|
||||
Properties []struct {
|
||||
ElectricityMalos []struct {
|
||||
Agreements []Agreement
|
||||
}
|
||||
}
|
||||
} `graphql:"account(accountNumber: $accountNumber)"`
|
||||
}
|
||||
|
||||
type product struct {
|
||||
Code string
|
||||
IsTimeOfUse bool
|
||||
Term int
|
||||
}
|
||||
|
||||
// AgreementUnitRateInformation is the current rate information for an agreement.
|
||||
// It supports both SimpleProductUnitRateInformation (fixed rate) and
|
||||
// TimeOfUseProductUnitRateInformation (time-slot based rates with activation rules).
|
||||
type AgreementUnitRateInformation struct {
|
||||
SimpleProductUnitRateInformation SimpleProductUnitRateInformation `graphql:"... on SimpleProductUnitRateInformation"`
|
||||
TimeOfUseProductUnitRateInformation TouAgreementUnitRateInformation `graphql:"... on TimeOfUseProductUnitRateInformation"`
|
||||
}
|
||||
|
||||
// SimpleProductUnitRateInformation holds a single fixed rate.
|
||||
type SimpleProductUnitRateInformation struct {
|
||||
LatestGrossUnitRateCentsPerKwh string
|
||||
NetUnitRateCentsPerKwh string
|
||||
}
|
||||
|
||||
// TouAgreementUnitRateInformation holds multiple time-slot rates with their activation rules.
|
||||
type TouAgreementUnitRateInformation struct {
|
||||
Rates []TouRate
|
||||
}
|
||||
|
||||
// TouRate is a rate with time-slot activation rules (used in non-dynamic ToU agreements).
|
||||
type TouRate struct {
|
||||
NetUnitRateCentsPerKwh string `graphql:"netUnitRateCentsPerKwh"`
|
||||
LatestGrossUnitRateCentsPerKwh string `graphql:"latestGrossUnitRateCentsPerKwh"`
|
||||
TimeslotName string
|
||||
TimeslotActivationRules []TimeslotActivationRule
|
||||
}
|
||||
|
||||
// TimeslotActivationRule defines the time window during which a rate slot is active.
|
||||
type TimeslotActivationRule struct {
|
||||
ActiveFromTime string
|
||||
ActiveToTime string
|
||||
}
|
||||
|
||||
// UnitRateForecast holds a single forecast entry with its validity window.
|
||||
type UnitRateForecast struct {
|
||||
ValidFrom time.Time
|
||||
ValidTo time.Time
|
||||
UnitRateInformation ForecastUnitRateInformation
|
||||
}
|
||||
|
||||
// ForecastUnitRateInformation is the rate information embedded in forecast entries.
|
||||
// Dynamic tariffs use TimeOfUseProductUnitRateInformation; simple forecasts use
|
||||
// SimpleProductUnitRateInformation.
|
||||
type ForecastUnitRateInformation struct {
|
||||
SimpleProductUnitRateInformation SimpleProductUnitRateInformation `graphql:"... on SimpleProductUnitRateInformation"`
|
||||
TimeOfUseProductUnitRateInformation TimeOfUseProductUnitRateInformation `graphql:"... on TimeOfUseProductUnitRateInformation"`
|
||||
}
|
||||
|
||||
// TimeOfUseProductUnitRateInformation holds a list of per-slot rates for dynamic/ToU forecasts.
|
||||
type TimeOfUseProductUnitRateInformation struct {
|
||||
Rates []Rate
|
||||
}
|
||||
|
||||
// Rate holds the net and gross unit rate strings for a single dynamic forecast slot.
|
||||
type Rate struct {
|
||||
NetUnitRateCentsPerKwh string `graphql:"netUnitRateCentsPerKwh"`
|
||||
LatestGrossUnitRateCentsPerKwh string `graphql:"latestGrossUnitRateCentsPerKwh"`
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue