Add Seat Cupra (#2997)

This commit is contained in:
andig 2022-03-25 18:24:35 +01:00 • committed by GitHub
parent 58d4dd5cf8
commit 4a921e3825
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
9 changed files with 416 additions and 3 deletions

View file

@ -0,0 +1,19 @@
template: cupra
products:
- brand: Seat
description:
generic: My Cupra
- brand: Seat
description:
generic: Cupra Born
params:
- preset: vehiclebase
- preset: vehicleidentify
- name: capacity
default: 10
- preset: vehiclecloud
render: |
type: cupra
{{include "vehicle-base" .}}
{{include "vehicle-identify" .}}
{{include "vehicle-cloud" .}}

View file

@ -0,0 +1,30 @@
product:
brand: Seat
description: My Cupra
render:
- default: |
type: template
template: cupra
title: # Wird in der Benutzeroberfläche angezeigt # Optional
user: # Benutzername um auf das Gerät zuzugreifen
password: # Passwort des Benutzerkontos
vin: W... # Erforderlich, wenn mehrere Fahrzeuge des Herstellers vorhanden sind # Optional
capacity: 10 # Akku-Kapazität in kWh # Optional
cloud: # Anstatt auf die Online API des Fahrzeugherstellers von der lokalen Installation zuzugreifen,... # Optional
advanced: |
type: template
template: cupra
title: # Wird in der Benutzeroberfläche angezeigt # Optional
user: # Benutzername um auf das Gerät zuzugreifen
password: # Passwort des Benutzerkontos
vin: W... # Erforderlich, wenn mehrere Fahrzeuge des Herstellers vorhanden sind # Optional
capacity: 10 # Akku-Kapazität in kWh # Optional
phases: 3 # Die maximale Anzahl der Phasen welche genutzt werden können # Optional
mode: # Möglich sind Off, Now, MinPV und PV, oder leer wenn keiner definiert werden soll # Optional
minSoC: 25 # Lade sofort mit maximaler Geschwindigkeit bis zu dem angegeben Ladestand, wenn der Lademodus nicht auf 'Aus' steht # Optional
targetSoC: 80 # Bis zu welchem Ladestand (SoC) soll das Fahrzeug geladen werden # Optional
minCurrent: 6 # Definiert die minimale Stromstärke pro angeschlossener Phase mit welcher das Fahrzeug geladen werden soll # Optional
maxCurrent: 16 # Definiert die maximale Stromstärke pro angeschlossener Phase mit welcher das Fahrzeug geladen werden soll # Optional
identifiers: # Kann meist erst später eingetragen werden, siehe: https://docs.evcc.io/docs/guides/vehicles/#erkennung-des-fahrzeugs-an-der-wallbox # Optional
cloud: # Anstatt auf die Online API des Fahrzeugherstellers von der lokalen Installation zuzugreifen,... # Optional

View file

@ -0,0 +1,30 @@
product:
brand: Seat
description: Cupra Born
render:
- default: |
type: template
template: cupra
title: # Wird in der Benutzeroberfläche angezeigt # Optional
user: # Benutzername um auf das Gerät zuzugreifen
password: # Passwort des Benutzerkontos
vin: W... # Erforderlich, wenn mehrere Fahrzeuge des Herstellers vorhanden sind # Optional
capacity: 10 # Akku-Kapazität in kWh # Optional
cloud: # Anstatt auf die Online API des Fahrzeugherstellers von der lokalen Installation zuzugreifen,... # Optional
advanced: |
type: template
template: cupra
title: # Wird in der Benutzeroberfläche angezeigt # Optional
user: # Benutzername um auf das Gerät zuzugreifen
password: # Passwort des Benutzerkontos
vin: W... # Erforderlich, wenn mehrere Fahrzeuge des Herstellers vorhanden sind # Optional
capacity: 10 # Akku-Kapazität in kWh # Optional
phases: 3 # Die maximale Anzahl der Phasen welche genutzt werden können # Optional
mode: # Möglich sind Off, Now, MinPV und PV, oder leer wenn keiner definiert werden soll # Optional
minSoC: 25 # Lade sofort mit maximaler Geschwindigkeit bis zu dem angegeben Ladestand, wenn der Lademodus nicht auf 'Aus' steht # Optional
targetSoC: 80 # Bis zu welchem Ladestand (SoC) soll das Fahrzeug geladen werden # Optional
minCurrent: 6 # Definiert die minimale Stromstärke pro angeschlossener Phase mit welcher das Fahrzeug geladen werden soll # Optional
maxCurrent: 16 # Definiert die maximale Stromstärke pro angeschlossener Phase mit welcher das Fahrzeug geladen werden soll # Optional
identifiers: # Kann meist erst später eingetragen werden, siehe: https://docs.evcc.io/docs/guides/vehicles/#erkennung-des-fahrzeugs-an-der-wallbox # Optional
cloud: # Anstatt auf die Online API des Fahrzeugherstellers von der lokalen Installation zuzugreifen,... # Optional

72
vehicle/cupra/api.go Normal file
View file

@ -0,0 +1,72 @@
package cupra
import (
"fmt"
"net/http"
"github.com/evcc-io/evcc/util"
"github.com/evcc-io/evcc/util/request"
"golang.org/x/oauth2"
)
const (
// BaseURL is the API base url
BaseURL = "https://ola.prod.code.seat.cloud.vwgroup.com"
ActionCharge = "charging"
ActionChargeStart = "start"
ActionChargeStop = "stop"
)
// API is an api.Vehicle implementation for Seat Cupra cars
type API struct {
*request.Helper
}
// NewAPI creates a new vehicle
func NewAPI(log *util.Logger, ts oauth2.TokenSource) *API {
v := &API{
Helper: request.NewHelper(log),
}
v.Client.Transport = &oauth2.Transport{
Source: ts,
Base: v.Client.Transport,
}
return v
}
// Vehicles implements the /vehicles response
func (v *API) Vehicles(userID string) (res []string, err error) {
var vehicles struct {
Vehicles []Vehicle
}
uri := fmt.Sprintf("%s/v1/users/%s/garage/vehicles", BaseURL, userID)
err = v.GetJSON(uri, &vehicles)
for _, v := range vehicles.Vehicles {
res = append(res, v.VIN)
}
return res, err
}
// Status implements the /status response
func (v *API) Status(userID, vin string) (Status, error) {
var res Status
uri := fmt.Sprintf("%s/v2/users/%s/vehicles/%s/mycar", BaseURL, userID, vin)
err := v.GetJSON(uri, &res)
return res, err
}
// Action implements the /requests response
func (v *API) Action(vin, action, cmd string) error {
uri := fmt.Sprintf("%s/vehicles/%s/%s/requests/%s", BaseURL, vin, action, cmd)
req, err := request.New(http.MethodPost, uri, nil, request.JSONEncoding)
if err == nil {
_, err = v.DoBody(req)
}
return err
}

13
vehicle/cupra/params.go Normal file
View file

@ -0,0 +1,13 @@
package cupra
import "net/url"
// TODO check AuthParam usage (currently using seat)
// Authorization parameters
var AuthParams = url.Values{
"response_type": {"code id_token"},
"client_id": {"3c756d46-f1ba-4d78-9f9a-cff0d5292d51@apps_vw-dilab_com"},
"redirect_uri": {"cupra://oauth-callback"},
"scope": {"openid profile mbb"}, // cars birthdate nickname address phone
}

117
vehicle/cupra/provider.go Normal file
View file

@ -0,0 +1,117 @@
package cupra
import (
"strings"
"time"
"github.com/evcc-io/evcc/api"
"github.com/evcc-io/evcc/provider"
)
// Provider is an api.Vehicle implementation for Seat Cupra cars
type Provider struct {
statusG func() (interface{}, error)
action func(string, string) error
}
// NewProvider creates a new vehicle
func NewProvider(api *API, userID, vin string, cache time.Duration) *Provider {
impl := &Provider{
statusG: provider.NewCached(func() (interface{}, error) {
return api.Status(userID, vin)
}, cache).InterfaceGetter(),
action: func(action, cmd string) error {
return api.Action(vin, action, cmd)
},
}
return impl
}
var _ api.Battery = (*Provider)(nil)
// SoC implements the api.Vehicle interface
func (v *Provider) SoC() (float64, error) {
res, err := v.statusG()
if res, ok := res.(Status); err == nil && ok {
return float64(res.Engines.Primary.Level), nil
}
return 0, err
}
var _ api.ChargeState = (*Provider)(nil)
// Status implements the api.ChargeState interface
func (v *Provider) Status() (api.ChargeStatus, error) {
status := api.StatusA // disconnected
res, err := v.statusG()
if res, ok := res.(Status); err == nil && ok {
switch strings.ToLower(res.Services.Charging.Status) {
case "connected":
status = api.StatusB
case "charging":
status = api.StatusC
}
}
return status, err
}
var _ api.VehicleFinishTimer = (*Provider)(nil)
// FinishTime implements the api.VehicleFinishTimer interface
func (v *Provider) FinishTime() (time.Time, error) {
res, err := v.statusG()
if res, ok := res.(Status); err == nil && ok {
rsc := res.Services.Charging
if !rsc.Active {
return time.Time{}, api.ErrNotAvailable
}
rt := rsc.RemainingTime
if rsc.TargetPct > 0 && rsc.TargetPct < 100 {
rt = rt * 100 / int64(rsc.TargetPct)
}
return time.Now().Add(time.Duration(rt) * time.Minute), err
}
return time.Time{}, err
}
var _ api.VehicleRange = (*Provider)(nil)
// Range implements the api.VehicleRange interface
func (v *Provider) Range() (int64, error) {
res, err := v.statusG()
if res, ok := res.(Status); err == nil && ok {
return int64(res.Engines.Primary.Range.Value), nil
}
return 0, err
}
var _ api.VehicleClimater = (*Provider)(nil)
// Climater implements the api.VehicleClimater interface
func (v *Provider) Climater() (active bool, outsideTemp float64, targetTemp float64, err error) {
res, err := v.statusG()
if res, ok := res.(Status); err == nil && ok {
return res.Services.Climatisation.Active, 21, 21, nil
}
return active, 21, 21, err
}
var _ api.VehicleChargeController = (*Provider)(nil)
// StartCharge implements the api.VehicleChargeController interface
func (v *Provider) StartCharge() error {
return v.action(ActionCharge, ActionChargeStart)
}
// StopCharge implements the api.VehicleChargeController interface
func (v *Provider) StopCharge() error {
return v.action(ActionCharge, ActionChargeStop)
}

40
vehicle/cupra/types.go Normal file
View file

@ -0,0 +1,40 @@
package cupra
type Vehicle struct {
VIN string
EnrollmentStatus string
UserRole string
VehicleNickname string
}
type Engine struct {
Type string
FuelType string
Range struct {
Value float64
Unit string
}
Level float64
}
type Status struct {
Engines struct {
Primary, Secondary Engine
}
Services struct {
Charging struct {
Status string
TargetPct int
ChargeMode string
Active bool
RemainingTime int64
ProgressBarPct float64
}
Climatisation struct {
Status string
Active bool
RemainingTime int64
ProgressBarPct float64
}
}
}

75
vehicle/seat-cupra.go Normal file
View file

@ -0,0 +1,75 @@
package vehicle
import (
"time"
"github.com/evcc-io/evcc/api"
"github.com/evcc-io/evcc/util"
"github.com/evcc-io/evcc/util/request"
"github.com/evcc-io/evcc/vehicle/cupra"
"github.com/evcc-io/evcc/vehicle/seat"
"github.com/evcc-io/evcc/vehicle/vag/tokenrefreshservice"
"github.com/evcc-io/evcc/vehicle/vag/vwidentity"
)
// Cupra is an api.Vehicle implementation for Seat Cupra cars
type Cupra struct {
*embed
*cupra.Provider // provides the api implementations
}
func init() {
registry.Add("cupra", NewCupraFromConfig)
}
// NewCupraFromConfig creates a new vehicle
func NewCupraFromConfig(other map[string]interface{}) (api.Vehicle, error) {
cc := struct {
embed `mapstructure:",squash"`
User, Password, VIN string
Cache time.Duration
Timeout time.Duration
}{
Cache: interval,
Timeout: request.Timeout,
}
if err := util.DecodeOther(other, &cc); err != nil {
return nil, err
}
v := &Cupra{
embed: &cc.embed,
}
log := util.NewLogger("cupra").Redact(cc.User, cc.Password, cc.VIN)
// get initial VW identity id_token
q, err := vwidentity.Login(log, seat.AuthParams, cc.User, cc.Password)
if err != nil {
return nil, err
}
trs := tokenrefreshservice.New(log, seat.TRSParams)
token, err := trs.Exchange(q)
if err != nil {
return nil, err
}
ui, err := vwidentity.UserInfo(log, token)
if err != nil {
return nil, err
}
api := cupra.NewAPI(log, trs.TokenSource(token))
cc.VIN, err = ensureVehicle(cc.VIN, func() ([]string, error) {
return api.Vehicles(ui.Subject)
})
if err == nil {
v.Provider = cupra.NewProvider(api, ui.Subject, cc.VIN, cc.Cache)
}
return v, err
}

View file

@ -8,6 +8,7 @@ import (
"net/url"
"strings"
"github.com/coreos/go-oidc"
"github.com/evcc-io/evcc/util"
"github.com/evcc-io/evcc/util/request"
"github.com/evcc-io/evcc/util/urlvalues"
@ -18,10 +19,12 @@ import (
)
const (
BaseURL = "https://identity.vwgroup.io"
WellKnown = BaseURL + "/.well-known/openid-configuration"
BaseURL = "https://identity.vwgroup.io"
WellKnown = "https://identity.vwgroup.io/.well-known/openid-configuration"
UserInfoURL = "https://identity-userinfo.vwgroup.io/oidc/userinfo"
)
// TODO use OIDC provider instead
var Endpoint = &oauth2.Endpoint{
AuthURL: BaseURL + "/oidc/v1/authorize",
TokenURL: BaseURL + "/oidc/v1/token",
@ -31,7 +34,6 @@ var Endpoint = &oauth2.Endpoint{
func Login(log *util.Logger, q url.Values, user, password string) (url.Values, error) {
return LoginWithAuthURL(log, Endpoint.AuthURL, q, user, password)
}
func LoginWithAuthURL(log *util.Logger, uri string, q url.Values, user, password string) (url.Values, error) {
var verify func(url.Values)
@ -56,6 +58,21 @@ func LoginWithAuthURL(log *util.Logger, uri string, q url.Values, user, password
return q, nil
}
// UserInfo returns the OIDS user information
func UserInfo(log *util.Logger, token *vag.Token) (oidc.UserInfo, error) {
var ui oidc.UserInfo
req, err := request.New(http.MethodGet, UserInfoURL, nil, map[string]string{
"Authorization": "Bearer " + token.AccessToken,
"Accept": "application/json",
})
if err == nil {
err = request.NewHelper(log).DoJSON(req, &ui)
}
return ui, err
}
type Service struct {
*request.Helper
}