Add Skoda Enyaq (#1030)

This commit is contained in:
andig 2021-05-16 21:03:14 +02:00 • committed by GitHub
parent 3bb4990312
commit 05c4453501
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
12 changed files with 512 additions and 41 deletions

View file

@ -258,7 +258,8 @@ Available vehicle remote interface implementations are:
- `renault`: Renault (all ZE models: Zoe, Twingo Electric, Master, Kangoo)
- `porsche`: Porsche (Taycan)
- `seat`: Seat (Cupra, Mii)
- `skoda`: Skoda (Citygo, Enyaq)
- `skoda`: Skoda (Citygo)
- `enyaq`: Skoda (Enyaq)
- `vw`: Volkswagen (eGolf, eUp)
- `id`: Volkswagen (ID.3, ID.4)
- `volvo`: Volvo

View file

@ -43,7 +43,7 @@ func NewAudiFromConfig(other map[string]interface{}) (api.Vehicle, error) {
}
log := util.NewLogger("audi")
identity := vw.NewIdentity(log, "77869e21-e30a-4a92-b016-48ab7d3db1d8")
identity := vw.NewIdentity(log)
query := url.Values(map[string][]string{
"response_type": {"id_token token"},
@ -54,7 +54,7 @@ func NewAudiFromConfig(other map[string]interface{}) (api.Vehicle, error) {
"ui_locales": {"de-DE"},
})
err := identity.Login(query, cc.User, cc.Password)
err := identity.LoginVAG("77869e21-e30a-4a92-b016-48ab7d3db1d8", query, cc.User, cc.Password)
if err != nil {
return v, fmt.Errorf("login failed: %w", err)
}

94
internal/vehicle/enyaq.go Normal file
View file

@ -0,0 +1,94 @@
package vehicle
import (
"fmt"
"net/url"
"strings"
"time"
"github.com/andig/evcc/api"
"github.com/andig/evcc/internal/vehicle/skoda"
"github.com/andig/evcc/internal/vehicle/vw"
"github.com/andig/evcc/util"
)
// https://github.com/lendy007/skodaconnect
// Enyaq is an api.Vehicle implementation for Skoda Enyaq cars
type Enyaq struct {
*embed
*skoda.Provider // provides the api implementations
}
func init() {
registry.Add("enyaq", NewEnyaqFromConfig)
}
// NewEnyaqFromConfig creates a new vehicle
func NewEnyaqFromConfig(other map[string]interface{}) (api.Vehicle, error) {
cc := struct {
embed `mapstructure:",squash"`
User, Password, VIN string
Cache time.Duration
}{
Cache: interval,
}
if err := util.DecodeOther(other, &cc); err != nil {
return nil, err
}
v := &Enyaq{
embed: &cc.embed,
}
var err error
log := util.NewLogger("enyaq")
if cc.VIN == "" {
identity := vw.NewIdentity(log)
// Skoda native api
query := url.Values(map[string][]string{
"response_type": {"code id_token"},
"redirect_uri": {"skodaconnect://oidc.login/"},
"client_id": {"f9a2359a-b776-46d9-bd0c-db1904343117@apps_vw-dilab_com"},
"scope": {"openid profile mbb"},
})
err = identity.LoginSkoda(query, cc.User, cc.Password)
if err != nil {
return v, fmt.Errorf("login failed: %w", err)
}
api := skoda.NewAPI(log, identity)
cc.VIN, err = findVehicle(api.Vehicles())
if err == nil {
log.DEBUG.Printf("found vehicle: %v", cc.VIN)
}
}
if err == nil {
identity := vw.NewIdentity(log)
// Skoda connect api
query := url.Values(map[string][]string{
"response_type": {"code id_token"},
"redirect_uri": {"skodaconnect://oidc.login/"},
"client_id": {"7f045eee-7003-4379-9968-9355ed2adb06@apps_vw-dilab_com"},
"scope": {"openid profile phone address cars email birthdate badge dealers driversLicense mbb"},
})
err := identity.LoginSkoda(query, cc.User, cc.Password)
if err != nil {
return v, fmt.Errorf("login failed: %w", err)
}
api := skoda.NewAPI(log, identity)
v.Provider = skoda.NewProvider(api, strings.ToUpper(cc.VIN), cc.Cache)
}
return v, err
}

View file

@ -43,7 +43,7 @@ func NewIDFromConfig(other map[string]interface{}) (api.Vehicle, error) {
}
log := util.NewLogger("id")
identity := vw.NewIdentity(log, "")
identity := vw.NewIdentity(log)
query := url.Values(map[string][]string{
"response_type": {"code id_token token"},
@ -52,7 +52,7 @@ func NewIDFromConfig(other map[string]interface{}) (api.Vehicle, error) {
"scope": {"openid profile badge cars dealers vin"},
})
err := identity.Login(query, cc.User, cc.Password)
err := identity.LoginID(query, cc.User, cc.Password)
if err != nil {
return v, fmt.Errorf("login failed: %w", err)
}

View file

@ -43,7 +43,7 @@ func NewSeatFromConfig(other map[string]interface{}) (api.Vehicle, error) {
}
log := util.NewLogger("seat")
identity := vw.NewIdentity(log, "9dcc70f0-8e79-423a-a3fa-4065d99088b4")
identity := vw.NewIdentity(log)
query := url.Values(map[string][]string{
"response_type": {"code id_token"},
@ -52,7 +52,7 @@ func NewSeatFromConfig(other map[string]interface{}) (api.Vehicle, error) {
"scope": {"openid profile mbb cars birthdate nickname address phone"},
})
err := identity.Login(query, cc.User, cc.Password)
err := identity.LoginVAG("9dcc70f0-8e79-423a-a3fa-4065d99088b4", query, cc.User, cc.Password)
if err != nil {
return v, fmt.Errorf("login failed: %w", err)
}

View file

@ -43,7 +43,7 @@ func NewSkodaFromConfig(other map[string]interface{}) (api.Vehicle, error) {
}
log := util.NewLogger("skoda")
identity := vw.NewIdentity(log, "28cd30c6-dee7-4529-a0e6-b1e07ff90b79")
identity := vw.NewIdentity(log)
query := url.Values(map[string][]string{
"response_type": {"code id_token"},
@ -52,7 +52,7 @@ func NewSkodaFromConfig(other map[string]interface{}) (api.Vehicle, error) {
"scope": {"openid profile phone address cars email birthdate badge dealers driversLicense mbb"},
})
err := identity.Login(query, cc.User, cc.Password)
err := identity.LoginVAG("28cd30c6-dee7-4529-a0e6-b1e07ff90b79", query, cc.User, cc.Password)
if err != nil {
return v, fmt.Errorf("login failed: %w", err)
}

View file

@ -0,0 +1,166 @@
package skoda
import (
"fmt"
"net/http"
"github.com/andig/evcc/util"
"github.com/andig/evcc/util/request"
"golang.org/x/oauth2"
)
const BaseURI = "https://api.connect.skoda-auto.cz/api"
// API is the Skoda api client
type API struct {
*request.Helper
}
// NewAPI creates a new api client
func NewAPI(log *util.Logger, identity oauth2.TokenSource) *API {
v := &API{
Helper: request.NewHelper(log),
}
v.Client.Transport = &oauth2.Transport{
Source: identity,
Base: v.Client.Transport,
}
return v
}
func (v *API) getJSON(uri string, res interface{}) error {
req, err := request.New(http.MethodGet, uri, nil, request.AcceptJSON)
if err == nil {
err = v.DoJSON(req, &res)
}
return err
}
// Vehicle is the /v2/garage/vehicles api
type Vehicle struct {
ID, VIN string
LastUpdatedAt string
Specification struct {
Title, Brand, Model string
Battery struct {
CapacityInKWh int
}
}
// Connectivities
// Capabilities
}
// Vehicles implements the /vehicles response
func (v *API) Vehicles() ([]string, error) {
var res []Vehicle
uri := fmt.Sprintf("%s/v2/garage/vehicles", BaseURI)
err := v.getJSON(uri, &res)
var vehicles []string
if err == nil {
for _, v := range res {
vehicles = append(vehicles, v.VIN)
}
}
return vehicles, err
}
// ChargerResponse is the /v1/charging/<vin>/status api
type ChargerResponse struct {
Plug struct {
ConnectionState string // Connected
LockState string // Unlocked
}
Charging struct {
State string // Error
RemainingToCompleteInSeconds int64
ChargingPowerInWatts float64
ChargingRateInKilometersPerHour float64
ChargingType string // Invalid
ChargeMode string // MANUAL
}
Battery struct {
CruisingRangeElectricInMeters int64
StateOfChargeInPercent int
}
}
// charging/settings
// {
// "autoUnlockPlugWhenCharged": "Permanent",
// "maxChargeCurrentAc": "Maximum",
// "targetStateOfChargeInPercent": 100
// }
// Charger implements the /v1/charging/<vin>/status response
func (v *API) Charger(vin string) (ChargerResponse, error) {
var res ChargerResponse
uri := fmt.Sprintf("%s/v1/charging/%s/status", BaseURI, vin)
err := v.getJSON(uri, &res)
return res, err
}
// ClimaterResponse is the /bs/climatisation/v1/%s/%s/vehicles/%s/climater api
// type ClimaterResponse struct {
// }
// // Climater implements the /climater response
// func (v *API) Climater(vin string) (ClimaterResponse, error) {
// var res ClimaterResponse
// uri := fmt.Sprintf("%s/bs/climatisation/v1/%s/%s/vehicles/%s/climater", BaseURI, v.brand, v.country, vin)
// err := v.getJSON(uri, &res)
// return res, err
// }
// const (
// ActionCharge = "batterycharge"
// ActionChargeStart = "start"
// ActionChargeStop = "stop"
// )
// type actionDefinition struct {
// contentType string
// appendix string
// }
// var actionDefinitions = map[string]actionDefinition{
// ActionCharge: {
// "application/vnd.vwg.mbb.ChargerAction_v1_0_0+xml",
// "charger/actions",
// },
// }
// // Action implements vehicle actions
// func (v *API) Action(vin, action, value string) error {
// def := actionDefinitions[action]
// uri := fmt.Sprintf("%s/bs/%s/v1/%s/%s/vehicles/%s/%s", BaseURI, action, v.brand, v.country, vin, def.appendix)
// body := "<?xml version=\"1.0\" encoding=\"UTF-8\" ?><action><type>" + value + "</type></action>"
// req, err := request.New(http.MethodPost, uri, strings.NewReader(body), map[string]string{
// "Content-type": def.contentType,
// })
// if err == nil {
// var resp *http.Response
// if resp, err = v.Do(req); err == nil {
// resp.Body.Close()
// }
// }
// return err
// }
// // Any implements any api response
// func (v *API) Any(base, vin string) (interface{}, error) {
// var res interface{}
// uri := fmt.Sprintf("%s/"+strings.TrimLeft(base, "/"), BaseURI, v.brand, v.country, vin)
// err := v.getJSON(uri, &res)
// return res, err
// }

View file

@ -0,0 +1,129 @@
package skoda
import (
"time"
"github.com/andig/evcc/api"
"github.com/andig/evcc/provider"
)
// Provider implements the evcc vehicle api
type Provider struct {
chargerG func() (interface{}, error)
// climateG func() (interface{}, error)
// action func(action, value string) error
}
// NewProvider provides the evcc vehicle api provider
func NewProvider(api *API, vin string, cache time.Duration) *Provider {
impl := &Provider{
chargerG: provider.NewCached(func() (interface{}, error) {
return api.Charger(vin)
}, cache).InterfaceGetter(),
// climateG: provider.NewCached(func() (interface{}, error) {
// return api.Climater(vin)
// }, cache).InterfaceGetter(),
// action: func(action, value string) error {
// return api.Action(vin, action, value)
// },
}
return impl
}
var _ api.Battery = (*Provider)(nil)
// SoC implements the api.Vehicle interface
func (v *Provider) SoC() (float64, error) {
res, err := v.chargerG()
if res, ok := res.(ChargerResponse); err == nil && ok {
return float64(res.Battery.StateOfChargeInPercent), 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.chargerG()
if res, ok := res.(ChargerResponse); err == nil && ok {
if res.Plug.ConnectionState == "Connected" {
status = api.StatusB
}
if res.Plug.ConnectionState == "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.chargerG()
if res, ok := res.(ChargerResponse); err == nil && ok {
crg := res.Charging
// estimate not available
if crg.State == "Error" || crg.ChargingType == "Invalid" {
return time.Time{}, api.ErrNotAvailable
}
remaining := time.Duration(crg.RemainingToCompleteInSeconds) * time.Second
return time.Now().Add(remaining), err
}
return time.Time{}, err
}
var _ api.VehicleRange = (*Provider)(nil)
// Range implements the api.VehicleRange interface
func (v *Provider) Range() (rng int64, err error) {
res, err := v.chargerG()
if res, ok := res.(ChargerResponse); err == nil && ok {
rng = int64(res.Battery.CruisingRangeElectricInMeters) / 1e3
}
return rng, 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.climateG()
// if res, ok := res.(ClimaterResponse); err == nil && ok {
// state := strings.ToLower(res.Climater.Status.ClimatisationStatusData.ClimatisationState.Content)
// active := state != "off" && state != "invalid" && state != "error"
// targetTemp = res.Climater.Settings.TargetTemperature.Content
// outsideTemp = res.Climater.Status.TemperatureStatusData.OutdoorTemperature.Content
// if math.IsNaN(outsideTemp) {
// outsideTemp = targetTemp // cover "invalid"
// }
// return active, outsideTemp, targetTemp, nil
// }
// return active, outsideTemp, targetTemp, err
// }
// var _ api.VehicleStartCharge = (*Provider)(nil)
// // StartCharge implements the api.VehicleStartCharge interface
// func (v *Provider) StartCharge() error {
// return v.action(ActionCharge, ActionChargeStart)
// }
// var _ api.VehicleStopCharge = (*Provider)(nil)
// // StopCharge implements the api.VehicleStopCharge interface
// func (v *Provider) StopCharge() error {
// return v.action(ActionCharge, ActionChargeStop)
// }

View file

@ -0,0 +1,42 @@
package skoda
import (
"net/http"
"net/url"
"strings"
"github.com/andig/evcc/util"
"github.com/andig/evcc/util/oauth"
"github.com/andig/evcc/util/request"
"golang.org/x/oauth2"
)
type tokenRefresher struct {
*request.Helper
}
func Refresher(log *util.Logger) oauth.TokenRefresher {
return &tokenRefresher{
Helper: request.NewHelper(log),
}
}
// RefreshToken implements oauth.TokenRefresher
func (tr *tokenRefresher) RefreshToken(token *oauth2.Token) (*oauth2.Token, error) {
uri := "https://tokenrefreshservice.apps.emea.vwapps.io/refreshTokens"
data := url.Values(map[string][]string{
"grant_type": {"refresh_token"},
"refresh_token": {token.RefreshToken},
"brand": {"skoda"},
})
req, err := request.New(http.MethodPost, uri, strings.NewReader(data.Encode()), request.URLEncoding)
var res oauth.Token
if err == nil {
err = tr.DoJSON(req, &res)
}
return (*oauth2.Token)(&res), err
}

View file

@ -43,7 +43,7 @@ func NewVWFromConfig(other map[string]interface{}) (api.Vehicle, error) {
}
log := util.NewLogger("vw")
identity := vw.NewIdentity(log, "38761134-34d0-41f3-9a73-c4be88d7d337")
identity := vw.NewIdentity(log)
query := url.Values(map[string][]string{
"response_type": {"id_token token"},
@ -52,7 +52,7 @@ func NewVWFromConfig(other map[string]interface{}) (api.Vehicle, error) {
"scope": {"openid profile mbb cars birthdate nickname address phone"},
})
err := identity.Login(query, cc.User, cc.Password)
err := identity.LoginVAG("38761134-34d0-41f3-9a73-c4be88d7d337", query, cc.User, cc.Password)
if err != nil {
return v, fmt.Errorf("login failed: %w", err)
}

View file

@ -1,13 +1,14 @@
package vw
import (
"errors"
"fmt"
"net/http"
"net/http/cookiejar"
"net/url"
"strings"
"github.com/andig/evcc/internal/vehicle/id"
"github.com/andig/evcc/internal/vehicle/skoda"
"github.com/andig/evcc/util"
"github.com/andig/evcc/util/oauth"
"github.com/andig/evcc/util/request"
@ -24,22 +25,26 @@ const (
// OauthRevokeURI is used for revoking tokens
OauthRevokeURI = "https://mbboauth-1d.prd.ece.vwg-connect.com/mbbcoauth/mobile/oauth2/v1/revoke"
// AppsURI is the login uri for ID vehicles
AppsURI = "https://login.apps.emea.vwapps.io"
// TokenServiceURI is the token service uri (used for Skoda Enyaq vehicles)
TokenServiceURI = "https://tokenrefreshservice.apps.emea.vwapps.io"
)
// Identity provides the identity.vwgroup.io login token source
type Identity struct {
log *util.Logger
*request.Helper
clientID string
oauth2.TokenSource
}
// NewIdentity creates VW identity
func NewIdentity(log *util.Logger, clientID string) *Identity {
func NewIdentity(log *util.Logger) *Identity {
v := &Identity{
log: log,
Helper: request.NewHelper(log),
clientID: clientID,
log: log,
Helper: request.NewHelper(log),
}
jar, _ := cookiejar.New(&cookiejar.Options{
@ -59,20 +64,15 @@ func NewIdentity(log *util.Logger, clientID string) *Identity {
}
// Login performs the identity.vwgroup.io login
func (v *Identity) Login(query url.Values, user, password string) error {
func (v *Identity) login(uri, user, password string) (url.Values, error) {
var vars FormVars
var req *http.Request
// add nonce and state
query.Set("nonce", RandomString(43))
query.Set("state", RandomString(43))
uri := "https://identity.vwgroup.io/oidc/v1/authorize?" + query.Encode()
// ID - get login url
if v.clientID == "" {
uri = "https://login.apps.emea.vwapps.io/authorize?nonce=NZ2Q3T6jak0E5pDh&redirect_uri=weconnect://authenticated"
query := url.Values{
"nonce": []string{RandomString(43)},
"state": []string{RandomString(43)},
}
uri += "&" + query.Encode()
// GET identity.vwgroup.io/signin-service/v1/signin/b7a5bb47-f875-47cf-ab83-2ba3bf6bb738@apps_vw-dilab_com?relayState=15404cb51c8b4cc5efeee1d2c2a73e5b41562faa
resp, err := v.Get(uri)
@ -120,38 +120,76 @@ func (v *Identity) Login(query url.Values, user, password string) error {
var location *url.URL
if err == nil {
loc := strings.ReplaceAll(resp.Header.Get("Location"), "#", "?") // convert to parseable url
location, err = url.Parse(loc)
if err == nil && location.Query().Get("id_token") == "" {
err = errors.New("missing id token")
if location, err = url.Parse(loc); err == nil {
return location.Query(), nil
}
}
// VW or Audi
if err == nil && v.clientID != "" {
return nil, err
}
// LoginVAG performs VAG login and finally exchanges id token for access and refresh tokens
func (v *Identity) LoginVAG(clientID string, query url.Values, user, password string) error {
uri := fmt.Sprintf("%s/oidc/v1/authorize?%s", IdentityURI, query.Encode())
q, err := v.login(uri, user, password)
if err == nil {
data := url.Values(map[string][]string{
"grant_type": {"id_token"},
"scope": {"sc2:fal"},
"token": {location.Query().Get("id_token")},
"token": {q.Get("id_token")},
})
var req *http.Request
req, err = request.New(http.MethodPost, OauthTokenURI, strings.NewReader(data.Encode()), map[string]string{
"Content-Type": "application/x-www-form-urlencoded",
"X-Client-Id": v.clientID,
"X-Client-Id": clientID,
})
if err == nil {
var token oauth.Token
if err = v.DoJSON(req, &token); err == nil {
v.TokenSource = oauth.RefreshTokenSource((*oauth2.Token)(&token), refresher(v.log, v.clientID))
v.TokenSource = oauth.RefreshTokenSource((*oauth2.Token)(&token), Refresher(v.log, clientID))
}
}
}
// ID
if err == nil && v.clientID == "" {
q := location.Query()
return err
}
// LoginSkoda performs Skoda login and finally exchanges code and id token for access and refresh tokens
func (v *Identity) LoginSkoda(query url.Values, user, password string) error {
uri := fmt.Sprintf("%s/oidc/v1/authorize?%s", IdentityURI, query.Encode())
q, err := v.login(uri, user, password)
if err == nil {
data := url.Values(map[string][]string{
"auth_code": {q.Get("code")},
"id_token": {q.Get("id_token")},
"brand": {"skoda"},
})
var req *http.Request
uri = fmt.Sprintf("%s/exchangeAuthCode", TokenServiceURI)
req, err = request.New(http.MethodPost, uri, strings.NewReader(data.Encode()), request.URLEncoding)
if err == nil {
var token oauth.Token
if err = v.DoJSON(req, &token); err == nil {
v.TokenSource = oauth.RefreshTokenSource((*oauth2.Token)(&token), skoda.Refresher(v.log))
}
}
}
return err
}
// LoginID performs ID login and finally exchanges state and id token for access and refresh tokens
func (v *Identity) LoginID(query url.Values, user, password string) error {
uri := fmt.Sprintf("%s/authorize?%s", AppsURI, query.Encode())
q, err := v.login(uri, user, password)
if err == nil {
data := map[string]string{
"state": q.Get("state"),
"id_token": q.Get("id_token"),
@ -161,7 +199,8 @@ func (v *Identity) Login(query url.Values, user, password string) error {
"authorizationCode": q.Get("code"),
}
uri := "https://login.apps.emea.vwapps.io/login/v1"
var req *http.Request
uri = fmt.Sprintf("%s/login/v1", AppsURI)
req, err = request.New(http.MethodPost, uri, request.MarshalJSON(data), request.JSONEncoding)
if err == nil {

View file

@ -16,7 +16,7 @@ type tokenRefresher struct {
clientID string
}
func refresher(log *util.Logger, clientID string) oauth.TokenRefresher {
func Refresher(log *util.Logger, clientID string) oauth.TokenRefresher {
return &tokenRefresher{
Helper: request.NewHelper(log),
clientID: clientID,