chore: remove deprecated VW, Audi, Cupra and Seat vehicle implementations (#30549)

This commit is contained in:
andig 2026-06-21 12:05:33 +02:00 • committed by GitHub
parent a641ad68fb
commit 1421849d6b
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
35 changed files with 2 additions and 8185 deletions

View file

@ -1,218 +0,0 @@
package vw
import (
"errors"
"fmt"
"net/http"
"strings"
"github.com/evcc-io/evcc/util"
"github.com/evcc-io/evcc/util/request"
"golang.org/x/oauth2"
)
// DefaultBaseURI is the VW api base URI
const DefaultBaseURI = "https://msg.volkswagen.de/fs-car"
// RegionAPI is the VW api used for determining the home region
const RegionAPI = "https://mal-1a.prd.ece.vwg-connect.com/api"
// API is the VW api client
type API struct {
*request.Helper
brand, country string
baseURI string
statusURI string
}
// NewAPI creates a new api client
func NewAPI(log *util.Logger, ts oauth2.TokenSource, brand, country string) *API {
v := &API{
Helper: request.NewHelper(log),
brand: brand,
country: country,
baseURI: DefaultBaseURI,
}
v.Client.Transport = &oauth2.Transport{
Source: ts,
Base: v.Client.Transport,
}
return v
}
// HomeRegion updates the home region for the given vehicle
func (v *API) HomeRegion(vin string) error {
var res HomeRegion
uri := fmt.Sprintf("%s/cs/vds/v1/vehicles/%s/homeRegion", RegionAPI, vin)
err := v.GetJSON(uri, &res)
if err == nil {
if api := res.HomeRegion.BaseURI.Content; strings.HasPrefix(api, "https://mal-3a.prd.eu.dp.vwg-connect.com") {
api = "https://fal" + strings.TrimPrefix(api, "https://mal")
api = strings.TrimSuffix(api, "/api") + "/fs-car"
v.baseURI = api
}
} else if res.Error != nil {
err = res.Error.Error()
}
return err
}
// RolesRights implements the /rolesrights/operationlist response
func (v *API) RolesRights(vin string) (RolesRights, error) {
var res RolesRights
uri := fmt.Sprintf("%s/rolesrights/operationlist/v3/vehicles/%s", RegionAPI, vin)
err := v.GetJSON(uri, &res)
return res, err
}
// ServiceURI renders the service URI for the given vin and service
func (v *API) ServiceURI(vin, service string, rr RolesRights) (uri string) {
if si := rr.ServiceByID(service); si != nil {
uri = si.InvocationUrl.Content
uri = strings.ReplaceAll(uri, "{vin}", vin)
uri = strings.ReplaceAll(uri, "{brand}", v.brand)
uri = strings.ReplaceAll(uri, "{country}", v.country)
}
return uri
}
// Status implements the /status response
func (v *API) Status(vin string) (StatusResponse, error) {
var res StatusResponse
uri := fmt.Sprintf("%s/bs/vsr/v1/vehicles/%s/status", RegionAPI, vin)
if v.statusURI != "" {
uri = v.statusURI
}
headers := map[string]string{
"Accept": request.JSONContent,
"X-App-Name": "foo", // required
"X-App-Version": "foo", // required
}
req, err := request.New(http.MethodGet, uri, nil, headers)
if err == nil {
err = v.DoJSON(req, &res)
}
if _, ok := errors.AsType[*request.StatusError](err); ok {
var rr RolesRights
rr, err = v.RolesRights(vin)
if err == nil {
if uri = v.ServiceURI(vin, StatusService, rr); uri == "" {
err = fmt.Errorf("%s not found", StatusService)
}
}
if err == nil {
if strings.HasSuffix(uri, fmt.Sprintf("%s/", vin)) {
uri += "status"
}
if req, err = request.New(http.MethodGet, uri, nil, headers); err == nil {
if err = v.DoJSON(req, &res); err == nil {
v.statusURI = uri
}
}
}
}
return res, err
}
// Charger implements the /charger response
func (v *API) Charger(vin string) (ChargerResponse, error) {
var res ChargerResponse
uri := fmt.Sprintf("%s/bs/batterycharge/v1/%s/%s/vehicles/%s/charger", v.baseURI, v.brand, v.country, vin)
err := v.GetJSON(uri, &res)
if err != nil && res.Error != nil {
err = res.Error.Error()
}
return res, err
}
// 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", v.baseURI, v.brand, v.country, vin)
err := v.GetJSON(uri, &res)
if err != nil && res.Error != nil {
err = res.Error.Error()
}
return res, err
}
// Position implements the /position response
func (v *API) Position(vin string) (PositionResponse, error) {
var res PositionResponse
uri := fmt.Sprintf("%s/bs/cf/v1/%s/%s/vehicles/%s/position", v.baseURI, v.brand, v.country, vin)
req, err := request.New(http.MethodGet, uri, nil, map[string]string{
"Accept": request.JSONContent,
"Content-type": "application/vnd.vwg.mbb.carfinderservice_v1_0_0+json",
"X-App-Name": "foo", // required
"X-App-Version": "foo", // required
})
if err == nil {
err = v.DoJSON(req, &res)
}
if err != nil && res.Error != nil {
err = res.Error.Error()
}
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", v.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) (any, error) {
var res any
uri := fmt.Sprintf("%s/"+strings.TrimLeft(base, "/"), v.baseURI, v.brand, v.country, vin)
err := v.GetJSON(uri, &res)
return res, err
}

View file

@ -1,204 +0,0 @@
package vw
import (
"cmp"
"fmt"
"os"
"slices"
"strconv"
"strings"
"text/tabwriter"
"time"
"github.com/evcc-io/evcc/api"
"github.com/evcc-io/evcc/util"
"github.com/samber/lo"
)
// Provider implements the vehicle api
type Provider struct {
chargerG func() (ChargerResponse, error)
statusG func() (StatusResponse, error)
climateG func() (ClimaterResponse, error)
positionG func() (PositionResponse, error)
action func(action, value string) error
rr func() (RolesRights, error)
}
// NewProvider creates a vehicle api provider
func NewProvider(api *API, vin string, cache time.Duration) *Provider {
impl := &Provider{
chargerG: util.Cached(func() (ChargerResponse, error) {
return api.Charger(vin)
}, cache),
statusG: util.Cached(func() (StatusResponse, error) {
return api.Status(vin)
}, cache),
climateG: util.Cached(func() (ClimaterResponse, error) {
return api.Climater(vin)
}, cache),
positionG: util.Cached(func() (PositionResponse, error) {
return api.Position(vin)
}, cache),
action: func(action, value string) error {
return api.Action(vin, action, value)
},
rr: func() (RolesRights, error) {
return api.RolesRights(vin)
},
}
return impl
}
var _ api.Battery = (*Provider)(nil)
// Soc implements the api.Vehicle interface
func (v *Provider) Soc() (float64, error) {
res, err := v.chargerG()
if err == nil {
return float64(res.Charger.Status.BatteryStatusData.StateOfCharge.Content), 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 err == nil {
if res.Charger.Status.PlugStatusData.PlugState.Content == "connected" {
status = api.StatusB
}
if res.Charger.Status.ChargingStatusData.ChargingState.Content == "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 err == nil {
rct := res.Charger.Status.BatteryStatusData.RemainingChargingTime
// estimate not available
if rct.Content == 65535 {
return time.Time{}, api.ErrNotAvailable
}
return time.Now().Add(time.Duration(rct.Content) * time.Minute), nil
}
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 err == nil {
crsd := res.Charger.Status.CruisingRangeStatusData
rng = int64(crsd.PrimaryEngineRange.Content)
if crsd.EngineTypeFirstEngine.Content != "typeIsElectric" {
rng = int64(crsd.SecondaryEngineRange.Content)
}
}
return rng, err
}
var _ api.VehicleOdometer = (*Provider)(nil)
// Odometer implements the api.VehicleOdometer interface
func (v *Provider) Odometer() (float64, error) {
res, err := v.statusG()
if err == nil {
err = api.ErrNotAvailable
if sd := res.ServiceByID(ServiceOdometer); sd != nil {
if fd := sd.FieldByID(ServiceOdometer); fd != nil {
if val, err := strconv.ParseFloat(fd.Value, 64); err == nil {
return val, nil
}
}
}
}
return 0, err
}
var _ api.VehicleClimater = (*Provider)(nil)
// Climater implements the api.VehicleClimater interface
func (v *Provider) Climater() (bool, error) {
res, err := v.climateG()
if err == nil {
state := strings.ToLower(res.Climater.Status.ClimatisationStatusData.ClimatisationState.Content)
active := state != "off" && state != "invalid" && state != "error"
return active, nil
}
return false, err
}
var _ api.VehiclePosition = (*Provider)(nil)
// Position implements the api.VehiclePosition interface
func (v *Provider) Position() (float64, float64, error) {
res, err := v.positionG()
if err == nil {
coord := res.FindCarResponse.Position.CarCoordinate
return float64(coord.Latitude) / 1e6, float64(coord.Longitude) / 1e6, nil
}
return 0, 0, err
}
var _ api.ChargeController = (*Provider)(nil)
// ChargeEnable implements the api.ChargeController interface
func (v *Provider) ChargeEnable(enable bool) error {
action := map[bool]string{true: ActionChargeStart, false: ActionChargeStop}
return v.action(ActionCharge, action[enable])
}
var _ api.Diagnosis = (*Provider)(nil)
// Diagnose implements the api.Diagnosis interface
func (v *Provider) Diagnose() {
rr, err := v.rr()
if err != nil {
return
}
tw := tabwriter.NewWriter(os.Stdout, 0, 0, 1, ' ', 0)
slices.SortFunc(rr.OperationList.ServiceInfo, func(i, j ServiceInfo) int {
return cmp.Compare(i.ServiceId, j.ServiceId)
})
for _, si := range rr.OperationList.ServiceInfo {
if si.InvocationUrl.Content != "" {
fmt.Fprintf(tw, "%s:\t%s\n", si.ServiceId, si.InvocationUrl.Content)
}
}
// list remaining service
services := lo.FilterMap(rr.OperationList.ServiceInfo, func(si ServiceInfo, _ int) (string, bool) {
return si.ServiceId, si.InvocationUrl.Content == ""
})
fmt.Fprintf(tw, "without uri:\t%s\n", strings.Join(services, ","))
tw.Flush()
}

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -1,155 +0,0 @@
package vw
import (
"encoding/json"
"fmt"
"math"
"strconv"
"time"
)
type Error struct {
ErrorCode, Description string
}
func (e *Error) Error() error {
return fmt.Errorf("%s: %s", e.ErrorCode, e.Description)
}
// ChargerResponse is the /bs/batterycharge/v1/%s/%s/vehicles/%s/charger api
type ChargerResponse struct {
Charger struct {
Status struct {
BatteryStatusData struct {
StateOfCharge TimedInt
RemainingChargingTime TimedInt
}
ChargingStatusData struct {
ChargingState TimedString // off, charging
ChargingMode TimedString // invalid, AC
ChargingReason TimedString // invalid, immediate
ExternalPowerSupplyState TimedString // unavailable, available
EnergyFlow TimedString // on, off
}
PlugStatusData struct {
PlugState TimedString // connected
}
CruisingRangeStatusData struct {
EngineTypeFirstEngine TimedString // typeIsElectric, petrolGasoline
EngineTypeSecondEngine TimedString // typeIsElectric, petrolGasoline
PrimaryEngineRange TimedInt
SecondaryEngineRange TimedInt
HybridRange TimedInt
}
}
}
Error *Error // optional error
}
// ClimaterResponse is the /bs/climatisation/v1/%s/%s/vehicles/%s/climater api
type ClimaterResponse struct {
Climater struct {
Settings struct {
TargetTemperature TimedTemperature
HeaterSource TimedString
}
Status struct {
ClimatisationStatusData struct {
ClimatisationState TimedString
ClimatisationReason TimedString
RemainingClimatisationTime TimedInt
}
TemperatureStatusData struct {
OutdoorTemperature TimedTemperature
}
VehicleParkingClockStatusData struct {
VehicleParkingClock TimedString
}
}
}
Error *Error // optional error
}
// PositionResponse is the /bs/cf/v1/%s/%s/vehicles/%s/position api
type PositionResponse struct {
FindCarResponse struct {
Position struct {
TimestampCarSent string // "2021-12-12T16:42:44"
TimestampTssReceived time.Time
CarCoordinate struct {
Latitude int64
Longitude int64
}
TimestampCarSentUTC time.Time
TimestampCarCaptured string // "2021-12-12T16:42:44"
}
ParkingTimeUTC time.Time
}
Error *Error // optional error
}
// VehiclesResponse is the /usermanagement/users/v1/%s/%s/vehicles api
type VehiclesResponse struct {
UserVehicles struct {
Vehicle []string
}
Error *Error // optional error
}
// HomeRegion is the home region API response
type HomeRegion struct {
HomeRegion struct {
BaseURI struct {
SystemID string
Content string // api url
}
}
Error *Error // optional error
}
// TimedInt is an int value with timestamp
type TimedInt struct {
Content int
Timestamp string
}
// TimedString is a string value with timestamp
type TimedString struct {
Content string
Timestamp string
}
// TimedTemperature is the api temperature with timestamp
type TimedTemperature struct {
Content float64
Timestamp string
}
func (t *TimedTemperature) UnmarshalJSON(data []byte) error {
var temp struct {
Content json.RawMessage // handle "invalid"
Timestamp string
}
err := json.Unmarshal(data, &temp)
if err == nil {
t.Timestamp = temp.Timestamp
if val, err := strconv.Atoi(string(temp.Content)); err == nil {
t.Content = temp2Float(val)
} else {
t.Content = math.NaN()
}
}
return err
}
// temp2Float converts api temp to float value
func temp2Float(i int) float64 {
f := float64(i)
if f == 0 {
return math.NaN()
}
return f/10 - 273
}

View file

@ -1,39 +0,0 @@
package vw
const StatusService = "statusreport_v1"
// RolesRights is the /rolesrights/operationlist response
type RolesRights struct {
OperationList struct {
VIN, UserId, Role, Status string
ServiceInfo []ServiceInfo
}
}
func (rr RolesRights) ServiceByID(id string) *ServiceInfo {
for _, s := range rr.OperationList.ServiceInfo {
if s.ServiceId == id {
return &s
}
}
return nil
}
// ServiceInfo is the rolesrights service information
type ServiceInfo struct {
ServiceId string
ServiceType string
ServiceStatus struct {
Status string
}
LicenseRequired bool
CumulatedLicense map[string]any
PrimaryUserRequired bool
TermsAndConditionsRequired bool
ServiceEol string
RolesAndRightsRequired bool
InvocationUrl struct {
Content string
}
Operation []map[string]any
}

View file

@ -1,53 +0,0 @@
package vw
const ServiceOdometer = "0x0101010002"
type StatusResponse struct {
StoredVehicleDataResponse struct {
VIN string
VehicleData struct {
Data []ServiceDefinition
}
}
Error *Error
}
func (s *StatusResponse) ServiceByID(id string) *ServiceDefinition {
for _, d := range s.StoredVehicleDataResponse.VehicleData.Data {
if d.ID == id {
return &d
}
}
return nil
}
type ServiceDefinition struct {
ID string
Field []FieldDefinition
}
func (s *ServiceDefinition) FieldByID(id string) *FieldDefinition {
if s == nil {
return nil
}
for _, f := range s.Field {
if f.ID == id {
return &f
}
}
return nil
}
type FieldDefinition struct {
ID string // "0x0101010001",
TsCarSentUtc string // "2021-09-05T07:54:20Z",
TsCarSent string // "2021-09-05T07:54:19",
TsCarCaptured string // "2021-09-05T07:54:19",
TsTssReceivedUtc string // "2021-09-05T07:54:23Z",
MilCarCaptured int // 25009,
MilCarSent int // 25009,
Value string // "echo"
}

View file

@ -1,43 +0,0 @@
package vw
import (
"encoding/json"
"math"
"testing"
)
func TestTemp(t *testing.T) {
data := `[{
"content": 2930,
"timestamp": "time"
}, {
"content": "invalid",
"timestamp": "time"
}]`
var temps []TimedTemperature
if err := json.Unmarshal([]byte(data), &temps); err != nil {
t.Error(err)
} else {
if v := temps[0].Content; v != 20 {
t.Error("invalid temp 0", v)
}
if v := temps[1].Content; !math.IsNaN(v) {
t.Error("invalid temp 1", v)
}
}
}
func TestError(t *testing.T) {
data := `{"error":{"errorCode":"batterycharge.auth.forbidden","description":"The context has not gained a legitimation due to missing access rights."}}`
var res ChargerResponse
if err := json.Unmarshal([]byte(data), &res); err != nil {
t.Error(err)
}
if res.Error == nil {
t.Fatal("Error is nil")
}
if res.Error.ErrorCode == "" {
t.Error("ErrorCode is empty")
}
}

View file

@ -1,119 +0,0 @@
package weconnect
import (
"fmt"
"net/http"
"strings"
"github.com/evcc-io/evcc/util"
"github.com/evcc-io/evcc/util/request"
"golang.org/x/oauth2"
)
// https://identity-userinfo.vwgroup.io/oidc/userinfo
// https://customer-profile.apps.emea.vwapps.io/v1/customers/<userId>/realCarData
// BaseURL is the API base url
const BaseURL = "https://emea.bff.cariad.digital/vehicle/v1"
// API is an api.Vehicle implementation for VW ID cars
type API struct {
*request.Helper
}
// Actions and action values
const (
ActionCharge = "charging"
ActionChargeStart = "start"
ActionChargeStop = "stop"
ActionChargeSettings = "settings" // body: targetSOC_pct
ActionClimatisation = "climatisation"
ActionClimatisationStart = "start"
ActionClimatisationStop = "stop"
)
// 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() ([]Vehicle, error) {
var res Vehicles
uri := fmt.Sprintf("%s/vehicles", BaseURL)
req, err := request.New(http.MethodGet, uri, nil, request.AcceptJSON)
if err == nil {
err = v.DoJSON(req, &res)
}
return res.Data, err
}
// Status implements the /status response.
// It is callers responsibility to check for embedded (partial) errors.
func (v *API) Status(vin string) (res Status, err error) {
uri := fmt.Sprintf("%s/vehicles/%s/selectivestatus?jobs=charging,fuelStatus,climatisation,measurements", BaseURL, vin)
req, err := request.New(http.MethodGet, uri, nil, request.AcceptJSON)
if err == nil {
err = v.DoJSON(req, &res)
}
return res, err
}
// ParkingPosition implements the /parkingposition response
func (v *API) ParkingPosition(vin string) (ParkingPosition, error) {
var res ParkingPosition
uri := fmt.Sprintf("%s/vehicles/%s/parkingposition", BaseURL, vin)
req, err := request.New(http.MethodGet, uri, nil, request.AcceptJSON)
if err == nil {
err = v.DoJSON(req, &res)
}
return res, err
}
// Action implements vehicle actions
func (v *API) Action(vin, action, value string) error {
uri := fmt.Sprintf("%s/vehicles/%s/%s/%s", BaseURL, vin, action, value)
req, err := request.New(http.MethodPost, uri, nil, request.AcceptJSON)
if err == nil {
var res any
err = v.DoJSON(req, &res)
}
return err
}
// Any implements any api response
func (v *API) Any(uri, vin string) (any, error) {
if strings.Contains(uri, "%s") {
uri = fmt.Sprintf(uri, vin)
}
req, err := request.New(http.MethodGet, uri, nil, request.AcceptJSON)
var res any
if err == nil {
err = v.DoJSON(req, &res)
}
return res, err
}

View file

@ -1,71 +0,0 @@
package weconnect
import (
"net/http"
"net/url"
"strings"
"time"
"github.com/evcc-io/evcc/util"
"github.com/evcc-io/evcc/util/oauth"
"github.com/evcc-io/evcc/util/request"
"github.com/evcc-io/evcc/util/urlvalues"
"github.com/evcc-io/evcc/vehicle/vag/cariad"
"golang.org/x/oauth2"
)
const tokenURL = cariad.BaseURL + "/auth/v1/idk/oidc/token"
// ExchangeCode swaps the authorization code from the OIDC callback for an
// access/refresh token pair at the cariad BFF OIDC token endpoint. Replaces
// the legacy WeConnect SSO exchange (/user-login/login/v1), which VW removed
// in May 2026.
func ExchangeCode(log *util.Logger, q url.Values) (*oauth2.Token, error) {
if err := urlvalues.Require(q, "code", "code_verifier"); err != nil {
return nil, err
}
data := url.Values{
"grant_type": {"authorization_code"},
"code": {q.Get("code")},
"code_verifier": {q.Get("code_verifier")},
"redirect_uri": {"weconnect://authenticated"},
"client_id": {cariad.ClientID},
}
return postToken(log, data)
}
// TokenSource returns a refreshing oauth2.TokenSource that swaps refresh
// tokens for fresh access tokens at the same OIDC token endpoint.
func TokenSource(log *util.Logger, token *oauth2.Token) oauth2.TokenSource {
return oauth.RefreshTokenSource(token, func(t *oauth2.Token) (*oauth2.Token, error) {
data := url.Values{
"grant_type": {"refresh_token"},
"refresh_token": {t.RefreshToken},
"client_id": {cariad.ClientID},
}
return postToken(log, data)
})
}
func postToken(log *util.Logger, data url.Values) (*oauth2.Token, error) {
req, err := request.New(http.MethodPost, tokenURL, strings.NewReader(data.Encode()),
map[string]string{
"Content-Type": request.FormContent,
"Accept": request.JSONContent,
"User-Agent": cariad.UserAgent,
"x-android-package-name": cariad.AndroidPackageName,
})
if err != nil {
return nil, err
}
var token oauth2.Token
if err := request.NewHelper(log).DoJSON(req, &token); err != nil {
return nil, err
}
token.Expiry = time.Now().Add(time.Duration(token.ExpiresIn) * time.Second)
return &token, nil
}

View file

@ -1,18 +0,0 @@
package weconnect
import (
"net/url"
"github.com/evcc-io/evcc/vehicle/vag/cariad"
)
// AuthParams are the OIDC authorize parameters for the WeConnect ID client.
// The authorize endpoint is the legacy identity.vwgroup.io OIDC entry point
// (vwidentity.Config.AuthURL); the token endpoint is the cariad BFF (see
// oauth.go).
var AuthParams = url.Values{
"response_type": {"code id_token token"},
"client_id": {cariad.ClientID},
"redirect_uri": {"weconnect://authenticated"},
"scope": {"openid profile badge cars vin"}, // dealers
}

View file

@ -1,189 +0,0 @@
package weconnect
import (
"errors"
"strings"
"time"
"github.com/evcc-io/evcc/api"
"github.com/evcc-io/evcc/util"
)
// Provider is an api.Vehicle implementation for VW ID cars
type Provider struct {
statusG func() (Status, error)
positionG func() (ParkingPosition, error)
action func(action, value string) error
}
// NewProvider creates a vehicle api provider
func NewProvider(api *API, vin string, cache time.Duration) *Provider {
impl := &Provider{
statusG: util.Cached(func() (Status, error) {
return api.Status(vin)
}, cache),
positionG: util.Cached(func() (ParkingPosition, error) {
return api.ParkingPosition(vin)
}, cache),
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.statusG()
if err == nil && res.Charging == nil {
err = errors.New("missing charging status")
}
if err == nil {
return float64(res.Charging.BatteryStatus.Value.CurrentSOCPct), 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 err != nil {
return status, err
}
if res.Charging == nil {
return status, errors.New("missing charging status")
}
if res.Charging.PlugStatus.Value.PlugConnectionState == "connected" {
status = api.StatusB
}
if res.Charging.ChargingStatus.Value.ChargingState == "charging" {
status = api.StatusC
}
return status, nil
}
var _ api.VehicleFinishTimer = (*Provider)(nil)
// FinishTime implements the api.VehicleFinishTimer interface
func (v *Provider) FinishTime() (time.Time, error) {
res, err := v.statusG()
if err != nil {
return time.Time{}, err
}
if res.Charging == nil {
return time.Time{}, errors.New("missing charging status")
}
cst := res.Charging.ChargingStatus.Value
return cst.CarCapturedTimestamp.Add(time.Duration(cst.RemainingChargingTimeToCompleteMin) * time.Minute), nil
}
var _ api.VehicleRange = (*Provider)(nil)
// Range implements the api.VehicleRange interface
func (v *Provider) Range() (int64, error) {
res, err := v.statusG()
if err != nil {
return 0, err
}
if res.Charging == nil {
return 0, errors.New("missing charging status")
}
return int64(res.Charging.BatteryStatus.Value.CruisingRangeElectricKm), nil
}
var _ api.VehicleOdometer = (*Provider)(nil)
// Odometer implements the api.VehicleOdometer interface
func (v *Provider) Odometer() (float64, error) {
res, err := v.statusG()
if err == nil && res.Measurements == nil {
err = api.ErrNotAvailable
}
if err == nil {
return res.Measurements.OdometerStatus.Value.Odometer, nil
}
return 0, err
}
var _ api.VehicleClimater = (*Provider)(nil)
// Climater implements the api.VehicleClimater interface
func (v *Provider) Climater() (bool, error) {
res, err := v.statusG()
if err == nil && res.Climatisation == nil {
err = api.ErrNotAvailable
}
if err == nil {
state := strings.ToLower(res.Climatisation.ClimatisationStatus.Value.ClimatisationState)
if state == "" {
return false, api.ErrNotAvailable
}
active := state != "off" && state != "invalid" && state != "error"
return active, nil
}
return false, err
}
var _ api.SocLimiter = (*Provider)(nil)
// GetLimitSoc implements the api.SocLimiter interface
func (v *Provider) GetLimitSoc() (int64, error) {
res, err := v.statusG()
if err != nil || res.Charging == nil || res.Charging.ChargingSettings.Value.TargetSOCPct == nil {
return 0, api.ErrNotAvailable
}
return int64(*res.Charging.ChargingSettings.Value.TargetSOCPct), nil
}
var _ api.ChargeController = (*Provider)(nil)
// ChargeEnable implements the api.ChargeController interface
func (v *Provider) ChargeEnable(enable bool) error {
action := map[bool]string{true: ActionChargeStart, false: ActionChargeStop}
return v.action(ActionCharge, action[enable])
}
var _ api.VehiclePosition = (*Provider)(nil)
// Position implements the api.VehiclePosition interface
func (v *Provider) Position() (float64, float64, error) {
res, err := v.positionG()
if res.Latitude == 0 && res.Longitude == 0 {
err = api.ErrNotAvailable
}
if err != nil {
return 0, 0, err
}
return res.Latitude, res.Longitude, nil
}
var _ api.Resurrector = (*Provider)(nil)
// WakeUp implements the api.Resurrector interface
func (v *Provider) WakeUp() error {
return v.ChargeEnable(true)
}

View file

@ -1,380 +0,0 @@
package weconnect
import (
"encoding/json"
"errors"
"fmt"
"strings"
"time"
)
// Vehicles is the /vehicles api
type Vehicles struct {
Data []Vehicle
}
// Vehicle is the api vehicle
type Vehicle struct {
VIN string
Model string
Nickname string
}
// Status is the /status api
type Status struct {
Access *struct {
AccessStatus struct {
Value struct {
OverallStatus string `json:"overallStatus"`
CarCapturedTimestamp Timestamp `json:"carCapturedTimestamp"`
Doors []struct {
Name string `json:"name"`
Status []string `json:"status"`
} `json:"doors"`
Windows []struct {
Name string `json:"name"`
Status []string `json:"status"`
} `json:"windows"`
DoorLockStatus string `json:"doorLockStatus"`
} `json:"value"`
} `json:"accessStatus"`
} `json:"access"`
Automation *struct {
ClimatisationTimer struct {
Value struct {
Timers []struct {
ID int `json:"id"`
Enabled bool `json:"enabled"`
RecurringTimer struct {
StartTime string `json:"startTime"`
RecurringOn struct {
Mondays bool `json:"mondays"`
Tuesdays bool `json:"tuesdays"`
Wednesdays bool `json:"wednesdays"`
Thursdays bool `json:"thursdays"`
Fridays bool `json:"fridays"`
Saturdays bool `json:"saturdays"`
Sundays bool `json:"sundays"`
} `json:"recurringOn"`
} `json:"recurringTimer,omitempty"`
SingleTimer struct {
StartDateTime Timestamp `json:"startDateTime"`
} `json:"singleTimer,omitempty"`
} `json:"timers"`
CarCapturedTimestamp Timestamp `json:"carCapturedTimestamp"`
TimeInCar string `json:"timeInCar"`
} `json:"value"`
} `json:"climatisationTimer"`
ChargingProfiles *struct {
Value struct {
CarCapturedTimestamp Timestamp `json:"carCapturedTimestamp"`
TimeInCar string `json:"timeInCar"`
Profiles []any `json:"profiles"`
} `json:"value"`
} `json:"chargingProfiles"`
} `json:"automation"`
UserCapabilities *struct {
CapabilitiesStatus struct {
Value []struct {
ID string `json:"id"`
UserDisablingAllowed bool `json:"userDisablingAllowed"`
ExpirationDate Timestamp `json:"expirationDate,omitempty"`
Status []int `json:"status,omitempty"`
} `json:"value"`
} `json:"capabilitiesStatus"`
} `json:"userCapabilities"`
Charging *struct {
BatteryStatus struct {
Value struct {
CarCapturedTimestamp Timestamp `json:"carCapturedTimestamp"`
CurrentSOCPct int `json:"currentSOC_pct"`
CruisingRangeElectricKm int `json:"cruisingRangeElectric_km"`
} `json:"value"`
} `json:"batteryStatus"`
ChargingStatus struct {
Value struct {
CarCapturedTimestamp Timestamp `json:"carCapturedTimestamp"`
RemainingChargingTimeToCompleteMin int `json:"remainingChargingTimeToComplete_min"`
ChargingState string `json:"chargingState"` // readyForCharging/off
ChargeMode string `json:"chargeMode"` // invalid
ChargePowerKW float64 `json:"chargePower_kW"`
ChargeRateKmph float64 `json:"chargeRate_kmph"`
ChargeType string `json:"chargeType"`
ChargingSettings string `json:"chargingSettings"`
} `json:"value"`
} `json:"chargingStatus"`
ChargingSettings struct {
Value struct {
CarCapturedTimestamp Timestamp `json:"carCapturedTimestamp"`
MaxChargeCurrentAC string `json:"maxChargeCurrentAC"` // reduced, maximum
AutoUnlockPlugWhenCharged string `json:"autoUnlockPlugWhenCharged"`
AutoUnlockPlugWhenChargedAC string `json:"autoUnlockPlugWhenChargedAC"`
TargetSOCPct *int `json:"targetSOC_pct"`
} `json:"value"`
} `json:"chargingSettings"`
PlugStatus struct {
Value struct {
CarCapturedTimestamp Timestamp `json:"carCapturedTimestamp"`
PlugConnectionState string `json:"plugConnectionState"` // connected, disconnected
PlugLockState string `json:"plugLockState"` // locked, unlocked
ExternalPower string `json:"externalPower"`
LedColor string `json:"ledColor"`
} `json:"value"`
} `json:"plugStatus"`
ChargeMode struct {
Value struct {
PreferredChargeMode string `json:"preferredChargeMode"`
AvailableChargeModes []string `json:"availableChargeModes"`
} `json:"value"`
} `json:"chargeMode"`
ChargingCareSettings struct {
Value struct {
BatteryCareMode string `json:"batteryCareMode"`
} `json:"value"`
} `json:"chargingCareSettings"`
} `json:"charging"`
Climatisation *struct {
ClimatisationStatus struct {
Value struct {
CarCapturedTimestamp Timestamp `json:"carCapturedTimestamp"`
RemainingClimatisationTimeMin int `json:"remainingClimatisationTime_min"`
ClimatisationState string `json:"climatisationState"` // off
} `json:"value"`
} `json:"climatisationStatus"` // may be temporarily not available
ClimatisationSettings struct {
Value struct {
CarCapturedTimestamp Timestamp `json:"carCapturedTimestamp"`
TargetTemperatureC float64 `json:"targetTemperature_C"`
TargetTemperatureF float64 `json:"targetTemperature_F"`
UnitInCar string `json:"unitInCar"`
ClimatizationAtUnlock bool `json:"climatizationAtUnlock"` // ClimatizationAtUnlock?
WindowHeatingEnabled bool `json:"windowHeatingEnabled"`
ZoneFrontLeftEnabled bool `json:"zoneFrontLeftEnabled"`
ZoneFrontRightEnabled bool `json:"zoneFrontRightEnabled"`
} `json:"value"`
} `json:"climatisationSettings"`
WindowHeatingStatus struct {
Value struct {
CarCapturedTimestamp Timestamp `json:"carCapturedTimestamp"`
WindowHeatingStatus []struct {
WindowLocation string `json:"windowLocation"`
WindowHeatingState string `json:"windowHeatingState"`
} `json:"windowHeatingStatus"`
} `json:"value"`
} `json:"windowHeatingStatus"`
} `json:"climatisation"`
ClimatisationTimers *struct {
ClimatisationTimersStatus struct {
Value struct {
Timers []struct {
ID int `json:"id"`
Enabled bool `json:"enabled"`
RecurringTimer struct {
StartTime string `json:"startTime"`
RecurringOn struct {
Mondays bool `json:"mondays"`
Tuesdays bool `json:"tuesdays"`
Wednesdays bool `json:"wednesdays"`
Thursdays bool `json:"thursdays"`
Fridays bool `json:"fridays"`
Saturdays bool `json:"saturdays"`
Sundays bool `json:"sundays"`
} `json:"recurringOn"`
} `json:"recurringTimer,omitempty"`
SingleTimer struct {
StartDateTime Timestamp `json:"startDateTime"`
} `json:"singleTimer"`
} `json:"timers"`
CarCapturedTimestamp Timestamp `json:"carCapturedTimestamp"`
TimeInCar string `json:"timeInCar"`
} `json:"value"`
} `json:"climatisationTimersStatus"`
} `json:"climatisationTimers"`
VehicleLights *struct {
LightsStatus struct {
Value struct {
CarCapturedTimestamp Timestamp `json:"carCapturedTimestamp"`
Lights []struct {
Name string `json:"name"`
Status string `json:"status"`
} `json:"lights"`
} `json:"value"`
} `json:"lightsStatus"`
} `json:"vehicleLights"`
Measurements *struct {
RangeStatus struct {
Value struct {
CarCapturedTimestamp Timestamp `json:"carCapturedTimestamp"`
ElectricRange float64 `json:"electricRange"`
} `json:"value"`
} `json:"rangeStatus"`
OdometerStatus struct {
Value struct {
CarCapturedTimestamp Timestamp `json:"carCapturedTimestamp"`
Odometer float64 `json:"odometer"`
} `json:"value"`
} `json:"odometerStatus"`
} `json:"measurements"`
FuelStatus *FuelStatus `json:"fuelStatus"`
Readiness *struct {
ReadinessStatus struct {
Value struct {
ConnectionState struct {
IsOnline bool `json:"isOnline"`
IsActive bool `json:"isActive"`
BatteryPowerLevel string `json:"batteryPowerLevel"`
DailyPowerBudgetAvailable bool `json:"dailyPowerBudgetAvailable"`
} `json:"connectionState"`
ConnectionWarning struct {
InsufficientBatteryLevelWarning bool `json:"insufficientBatteryLevelWarning"`
DailyPowerBudgetWarning bool `json:"dailyPowerBudgetWarning"`
} `json:"connectionWarning"`
} `json:"value"`
} `json:"readinessStatus"`
} `json:"readiness"`
VehicleHealthWarnings *struct {
WarningLights struct {
Value struct {
CarCapturedTimestamp Timestamp `json:"carCapturedTimestamp"`
MileageKm int `json:"mileage_km"`
WarningLights []any `json:"warningLights"`
} `json:"value"`
} `json:"warningLights"`
} `json:"vehicleHealthWarnings"`
ChargingTimers *struct {
ChargingTimersStatus struct {
Value struct {
CarCapturedTimestamp Timestamp `json:"carCapturedTimestamp"`
TimeInCar string `json:"timeInCar"`
Timers []struct {
ID int `json:"id"`
Enabled bool `json:"enabled"`
Climatisation bool `json:"climatisation"`
RecurringTimer struct {
DepartureTime string `json:"departureTime"`
RepetitionDays []string `json:"repetitionDays"`
} `json:"recurringTimer"`
} `json:"timers"`
} `json:"value"`
} `json:"chargingTimersStatus"`
} `json:"chargingTimers"`
ChargingProfiles *struct {
ChargingProfilesStatus struct {
Value struct {
CarCapturedTimestamp Timestamp `json:"carCapturedTimestamp"`
TimeInCar string `json:"timeInCar"`
Profiles []struct {
ID int `json:"id"`
Name string `json:"name"`
MaxChargingCurrent string `json:"maxChargingCurrent"`
MinSOCPct int `json:"minSOC_pct"`
TargetSOCPct int `json:"targetSOC_pct"`
Options struct {
AutoUnlockPlugWhenCharged string `json:"autoUnlockPlugWhenCharged"`
} `json:"options"`
PreferredChargingTimes []struct {
ID int `json:"id"`
Enabled bool `json:"enabled"`
StartTime string `json:"startTime"`
EndTime string `json:"endTime"`
} `json:"preferredChargingTimes"`
Timers []any `json:"timers"`
MinSOCEnabled bool `json:"minSOC_enabled"`
} `json:"profiles"`
} `json:"value"`
} `json:"chargingProfilesStatus"`
} `json:"chargingProfiles"`
}
// FuelStatus is the engine range status
type FuelStatus struct {
RangeStatus struct {
Value struct {
CarCapturedTimestamp Timestamp `json:"carCapturedTimestamp"`
CarType string `json:"carType"`
PrimaryEngine EngineRangeStatus `json:"primaryEngine"`
SecondaryEngine EngineRangeStatus `json:"secondaryEngine"`
TotalRangeKm int `json:"totalRange_km"`
} `json:"value"`
} `json:"rangeStatus"`
}
func (f *FuelStatus) EngineRangeStatus(typ string) (EngineRangeStatus, error) {
if f == nil {
return EngineRangeStatus{}, errors.New("missing fuel status")
}
if f.RangeStatus.Value.PrimaryEngine.Type == typ {
return f.RangeStatus.Value.PrimaryEngine, nil
}
if f.RangeStatus.Value.SecondaryEngine.Type == typ {
return f.RangeStatus.Value.SecondaryEngine, nil
}
return EngineRangeStatus{}, fmt.Errorf("unknown engine type: %s, got [%s, %s]", typ, f.RangeStatus.Value.PrimaryEngine.Type, f.RangeStatus.Value.SecondaryEngine.Type)
}
// EngineRangeStatus is the engine range status
type EngineRangeStatus struct {
Type string `json:"type"`
CurrentSOCPct int `json:"currentSOC_pct"`
RemainingRangeKm int `json:"remainingRange_km"`
}
// ParkingPosition is the /parkingposition api response
type ParkingPosition struct {
Latitude float64
Longitude float64
CarCapturedTimestamp Timestamp
}
// UnmarshalJSON accepts both the latitude/longitude and the shorter lat/lon
// key variants the parkingposition endpoint may return.
func (p *ParkingPosition) UnmarshalJSON(data []byte) error {
var res struct {
Latitude *float64 `json:"latitude"`
Longitude *float64 `json:"longitude"`
Lat *float64 `json:"lat"`
Lon *float64 `json:"lon"`
CarCapturedTimestamp Timestamp `json:"carCapturedTimestamp"`
}
if err := json.Unmarshal(data, &res); err != nil {
return err
}
p.CarCapturedTimestamp = res.CarCapturedTimestamp
switch {
case res.Latitude != nil:
p.Latitude = *res.Latitude
case res.Lat != nil:
p.Latitude = *res.Lat
}
switch {
case res.Longitude != nil:
p.Longitude = *res.Longitude
case res.Lon != nil:
p.Longitude = *res.Lon
}
return nil
}
// Timestamp implements JSON unmarshal
type Timestamp struct {
time.Time
}
// UnmarshalJSON decodes string timestamp into time.Time
func (ct *Timestamp) UnmarshalJSON(data []byte) error {
s := strings.Trim(string(data), "\"")
t, err := time.Parse(time.RFC3339, s)
if err == nil {
ct.Time = t
}
return err
}