From 5801072c73d481973755883e787db15b2f676467 Mon Sep 17 00:00:00 2001 From: andig Date: Tue, 19 Jan 2021 17:21:06 +0100 Subject: [PATCH] Add volvo api (#334) --- README.md | 3 +- vehicle/volvo.go | 201 +++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 203 insertions(+), 1 deletion(-) create mode 100644 vehicle/volvo.go diff --git a/README.md b/README.md index e5d901c6f..1b8539e82 100644 --- a/README.md +++ b/README.md @@ -18,7 +18,7 @@ EVCC is an extensible EV Charge Controller with PV integration implemented in [G - simple and clean user interface - multiple [chargers](#charger): Wallbe, Phoenix (includes ESL Walli), go-eCharger, NRGkick (direct Bluetooth or via Connect device), SimpleEVSE, EVSEWifi, KEBA/BMW, openWB, Mobile Charger Connect, and any other charger using scripting - multiple [meters](#meter): ModBus (Eastron SDM, MPM3PM, SBC ALE3 and many more), Discovergy (using HTTP plugin), SMA Home Manager 2.0 and SMA Energy Meter, KOSTAL Smart Energy Meter (KSEM, EMxx), any Sunspec-compatible inverter or home battery devices (Fronius, SMA, SolarEdge, KOSTAL, STECA, E3DC), Tesla PowerWall -- wide support of vendor-specific [vehicles](#vehicle) interfaces (remote charge, battery and preconditioning status): Audi, BMW, Ford, Tesla, Nissan, Renault, Porsche, Volkswagen and any other vehicle using scripting +- wide support of vendor-specific [vehicles](#vehicle) interfaces (remote charge, battery and preconditioning status): Audi, BMW, Ford, Tesla, Nissan, Renault, Porsche, Volkswagen, Volvo and any other vehicle using scripting - [plugins](#plugins) for integrating with hardware devices and home automation: Modbus (meters and grid inverters), HTTP, MQTT, Javascript, WebSockets and shell scripts - status notifications using [Telegram](https://telegram.org) and [PushOver](https://pushover.net) - logging using [InfluxDB](https://www.influxdata.com) and [Grafana](https://grafana.com/grafana/) @@ -231,6 +231,7 @@ Available vehicle remote interface implementations are: - `porsche`: Porsche (Taycan) - `vw`: Volkswagen (eGolf, eUp) - `id`: Volkswagen (ID.3, ID.4) +- `volvo`: Volvo - `default`: default vehicle implementation using configurable [plugins](#plugins) for integrating any type of vehicle Configuration examples are documented at [andig/evcc-config#vehicles](https://github.com/andig/evcc-config#vehicles) diff --git a/vehicle/volvo.go b/vehicle/volvo.go new file mode 100644 index 000000000..4454c2b10 --- /dev/null +++ b/vehicle/volvo.go @@ -0,0 +1,201 @@ +package vehicle + +import ( + "encoding/base64" + "fmt" + "net/http" + "time" + + "github.com/andig/evcc/api" + "github.com/andig/evcc/provider" + "github.com/andig/evcc/util" + "github.com/andig/evcc/util/request" +) + +const ( + volvoAPI = "https://vocapi.wirelesscar.net/customerapi/rest/v3.0" +) + +type volvoAccountResponse struct { + FirstName string `json:"firstName"` + LastName string `json:"lastName"` + VehicleRelations []string `json:"accountVehicleRelations"` +} + +type volvoVehicleRelation struct { + Account string `json:"account"` + AccountID string `json:"accountId"` + Vehicle string `json:"vehicle"` + AccountVehicleRelation string `json:"accountVehicleRelation"` + VehicleID string `json:"vehicleId"` + Username string `json:"username"` + Status string `json:"status"` + CustomerVehicleRelationID int `json:"customerVehicleRelationId"` +} + +type volvoStatus struct { + AverageFuelConsumption float32 `json:"averageFuelConsumption"` + AverageFuelConsumptionTimestamp string `json:"averageFuelConsumptionTimestamp"` + AverageSpeed int `json:"averageSpeed"` + AverageSpeedTimestamp string `json:"averageSpeedTimestamp"` + BrakeFluid string `json:"brakeFluid"` + BrakeFluidTimestamp string `json:"brakeFluidTimestamp"` + CarLocked bool `json:"carLocked"` + CarLockedTimestamp string `json:"carLockedTimestamp"` + ConnectionStatus string `json:"connectionStatus"` + ConnectionStatusTimestamp string `json:"connectionStatusTimestamp"` + DistanceToEmpty int `json:"distanceToEmpty"` + DistanceToEmptyTimestamp string `json:"distanceToEmptyTimestamp"` + EngineRunning bool `json:"engineRunning"` + EngineRunningTimestamp string `json:"engineRunningTimestamp"` + FuelAmount int `json:"fuelAmount"` + FuelAmountLevel int `json:"fuelAmountLevel"` + FuelAmountLevelTimestamp string `json:"fuelAmountLevelTimestamp"` + FuelAmountTimestamp string `json:"fuelAmountTimestamp"` + HvBattery struct { + HvBatteryChargeStatusDerived string `json:"hvBatteryChargeStatusDerived"` // "CablePluggedInCar_Charging", + HvBatteryChargeStatusDerivedTimestamp string `json:"hvBatteryChargeStatusDerivedTimestamp"` // "2021-01-19T14:44:02+0000", + HvBatteryChargeModeStatus string `json:"hvBatteryChargeModeStatus"` // null, + HvBatteryChargeModeStatusTimestamp string `json:"hvBatteryChargeModeStatusTimestamp"` // null, + HvBatteryChargeStatus string `json:"hvBatteryChargeStatus"` // "ChargeProgress", + HvBatteryChargeStatusTimestamp string `json:"hvBatteryChargeStatusTimestamp"` // "2021-01-19T14:44:02+0000", + HvBatteryLevel int `json:"hvBatteryLevel"` // 72, + HvBatteryLevelTimestamp string `json:"hvBatteryLevelTimestamp"` // "2021-01-19T14:44:02+0000", + DistanceToHVBatteryEmpty int `json:"distanceToHVBatteryEmpty"` // 28, + DistanceToHVBatteryEmptyTimestamp string `json:"distanceToHVBatteryEmptyTimestamp"` // "2021-01-19T14:44:02+0000", + TimeToHVBatteryFullyCharged int `json:"timeToHVBatteryFullyCharged"` // 60, + TimeToHVBatteryFullyChargedTimestamp string `json:"timeToHVBatteryFullyChargedTimestamp"` // "2021-01-19T14:44:02+0000" + } `json:"hvBattery"` + Odometer int `json:"odometer"` + OdometerTimestamp string `json:"odometerTimestamp"` + PrivacyPolicyEnabled bool `json:"privacyPolicyEnabled"` + PrivacyPolicyEnabledTimestamp string `json:"privacyPolicyEnabledTimestamp"` + RemoteClimatizationStatus string `json:"remoteClimatizationStatus"` + RemoteClimatizationStatusTimestamp string `json:"remoteClimatizationStatusTimestamp"` + ServiceWarningStatus string `json:"serviceWarningStatus"` + ServiceWarningStatusTimestamp string `json:"serviceWarningStatusTimestamp"` + TimeFullyAccessibleUntil string `json:"timeFullyAccessibleUntil"` + TimePartiallyAccessibleUntil string `json:"timePartiallyAccessibleUntil"` + TripMeter1 int `json:"tripMeter1"` + TripMeter1Timestamp string `json:"tripMeter1Timestamp"` + TripMeter2 int `json:"tripMeter2"` + TripMeter2Timestamp string `json:"tripMeter2Timestamp"` +} + +// Volvo is an api.Vehicle implementation for Volvo cars +type Volvo struct { + *embed + *request.Helper + user, password, vin string + statusG func() (interface{}, error) +} + +func init() { + registry.Add("volvo", NewVolvoFromConfig) +} + +// NewVolvoFromConfig creates a new vehicle +func NewVolvoFromConfig(other map[string]interface{}) (api.Vehicle, error) { + cc := struct { + Title string + Capacity int64 + User, Password, VIN string + Cache time.Duration + }{ + Cache: interval, + } + + if err := util.DecodeOther(other, &cc); err != nil { + return nil, err + } + + log := util.NewLogger("volvo") + + v := &Volvo{ + embed: &embed{cc.Title, cc.Capacity}, + Helper: request.NewHelper(log), + user: cc.User, + password: cc.Password, + vin: cc.VIN, + } + + v.statusG = provider.NewCached(v.status, cc.Cache).InterfaceGetter() + + var err error + if cc.VIN == "" { + v.vin, err = findVehicle(v.vehicles()) + if err == nil { + log.DEBUG.Printf("found vehicle: %v", v.vin) + } + } + + return v, err +} + +func (v *Volvo) request(uri string) (*http.Request, error) { + basicAuth := base64.StdEncoding.EncodeToString([]byte(v.user + ":" + v.password)) + + return request.New(http.MethodGet, uri, nil, map[string]string{ + "Authorization": fmt.Sprintf("Basic %s", basicAuth), + "Content-Type": "application/json", + "X-Device-Id": "Device", + "X-OS-Type": "Android", + "X-Originator-Type": "App", + "X-OS-Version": "22", + }) +} + +// vehicles implements returns the list of user vehicles +func (v *Volvo) vehicles() ([]string, error) { + var vehicles []string + + req, err := v.request(fmt.Sprintf("%s/customeraccounts", volvoAPI)) + if err == nil { + var res volvoAccountResponse + err = v.DoJSON(req, &res) + + for _, rel := range res.VehicleRelations { + var vehicle volvoVehicleRelation + if req, err := v.request(rel); err == nil { + if err = v.DoJSON(req, &vehicle); err != nil { + return vehicles, err + } + + vehicles = append(vehicles, vehicle.VehicleID) + } + } + } + + return vehicles, err +} + +func (v *Volvo) status() (volvoStatus, error) { + var res volvoStatus + + req, err := v.request(fmt.Sprintf("%s/vehicles/%s/status", volvoAPI, v.vin)) + if err == nil { + err = v.DoJSON(req, &res) + } + + return res, err +} + +// ChargeState implements the Vehicle.ChargeState interface +func (v *Volvo) ChargeState() (float64, error) { + res, err := v.statusG() + if res, ok := res.(volvoStatus); err == nil && ok { + return float64(res.HvBattery.HvBatteryLevel), nil + } + + return 0, err +} + +// VehicleRange implements the VehicleRange interface +func (v *Volvo) VehicleRange() (int64, error) { + res, err := v.statusG() + if res, ok := res.(volvoStatus); err == nil && ok { + return int64(res.HvBattery.DistanceToHVBatteryEmpty), nil + } + + return 0, err +}