carwings

package module
v0.0.0-...-195f7e1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 25, 2023 License: MIT Imports: 14 Imported by: 6

README

Carwings

GoDoc

carwings is a Go package and command-line tool providing access to the Nissan Leaf Carwings API.

Through the Carwings API you can ask your vehicle for the latest data, see current battery and charging statuses, see the current climate control state, start or stop climate control remotely, and remotely start charging.

Command-line tool

The carwings tool can be installed with:

go install github.com/joeshaw/carwings/cmd/carwings@latest

Run carwings by itself to see full usage information.

To update vehicle information:

carwings -username <username> -password <password> -region <region code> update

To get latest battery status:

carwings -username <username> -password <password> -region <region code> battery

This will print something like:

Logging into Carwings...
Getting latest retrieved battery status...
Battery status as of 2017-08-06 15:43:00 -0400 EDT:
  Capacity: 240 / 240 (92%)
  Crusing range: 114 miles (107 mi with AC)
  Plug-in state: not connected
  Charging status: not charging
  Time to full:
    Level 1 charge: 8h30m0s
    Level 2 charge: 3h0m0s
    Level 2 at 6 kW: 2h30m0s

For some people the username is an email address. For others it's a distinct username.

The regions are:

Nissan Region Carwings Region Code
USA NNA
Europe NE
Canada NCI
Australia NMA
Japan NML

Config values can be provided through environment variables (such as CARWINGS_USERNAME) or in a ~/.carwings file in the format:

username <username>
password <password>
region NA

Server mode

When carwings server is run, an HTTP server is started with endpoints for retrieving battery and climate info, and for starting charging and toggling the climate control system. This can be handy for building home automation workflows. I use this with IFTTT so that I can use the Google Assistant to start warming up my car.

The endpoints are:

GET /battery
GET /climate
POST /charging/on
POST /climate/on
POST /climate/off

The POST endpoints take no request body.

Carwings protocol

Josh Perry's protocol reference was incredibly helpful for the development of this library.

Josh also has an implementation in Javascript: https://github.com/joshperry/carwings

Jason Horne has a Python implementation: https://github.com/jdhorne/pycarwings2

Phil Cole has taken it, ported it to Python 3, and is carrying it forward: https://github.com/filcole/pycarwings2

Guillaume Boudreau has a PHP implementation: https://github.com/gboudreau/nissan-connect-php

Scott Helme created a Javascript Alexa skill: https://github.com/ScottHelme/AlexaNissanLeaf

Tobias Westergaard Kjeldsen has created a Dart library for carwings as well as an Android app.

A new North America-only API is being tracked in issue #3, and more information is available there.

Contributing

Issues and pull requests are welcome. When filing a PR, please make sure the code has been run through gofmt.

License

Copyright 2017-2020 Joe Shaw

carwings is licensed under the MIT License. See the LICENSE file for details.

Documentation

Index

Constants

View Source
const (
	RegionUSA       = "NNA"
	RegionEurope    = "NE"
	RegionCanada    = "NCI"
	RegionAustralia = "NMA"
	RegionJapan     = "NML"
)
View Source
const (
	// Not connected to a charger
	NotConnected = PluginState("NOT_CONNECTED")

	// Connected to a normal J1772 Level 1 or 2 charger
	Connected = PluginState("CONNECTED")

	// Connected to a high voltage DC quick charger (ChaDeMo)
	QCConnected = PluginState("QC_CONNECTED")

	// Invalid state, when updating data from the vehicle fails.
	InvalidPluginState = PluginState("INVALID")
)
View Source
const (
	// Not charging
	NotCharging = ChargingStatus("NOT_CHARGING")

	// Normal charging from a Level 1 or 2 EVSE
	NormalCharging = ChargingStatus("NORMAL_CHARGING")

	// Rapidly charging from a ChaDeMo DC quick charger
	RapidlyCharging = ChargingStatus("RAPIDLY_CHARGING")

	// Invalid state, when updating data from the vehicle fails.
	InvalidChargingStatus = ChargingStatus("INVALID")
)

Variables

View Source
var (
	// ErrNotLoggedIn is returned whenever an operation is run and
	// the user has not let logged in.
	ErrNotLoggedIn = errors.New("not logged in")

	// ErrUpdateFailed indicates an error talking to the Carwings
	// service when fetching updated vehicle data.
	ErrUpdateFailed = errors.New("failed to retrieve updated info from vehicle")

	// ErrClimateStatusUnavailable is returned from the
	// ClimateStatus method when no data is available.
	ErrClimateStatusUnavailable = errors.New("climate status unavailable")

	// ErrBatteryStatusUnavailable is returned from the
	// BatteryStatus method when no data is available.
	ErrBatteryStatusUnavailable = errors.New("battery status unavailable")

	// ErrVehicleInfoUnavailable is returned when vehicle information is
	// not available when logging in.
	ErrVehicleInfoUnavailable = errors.New("vehicle info unavailable")

	// Debug indiciates whether to log HTTP responses to stderr
	Debug = false

	// Default URL for connecting to Carwings service.  This is
	// changed by Nissan from time to time, so it's helpful to
	// have it be configurable.
	BaseURL = "https://gdcportalgw.its-mo.com/api_v200413_NE/gdc/"

	// Http client used for api requests
	Client = http.DefaultClient
)

Functions

func MetersToMiles

func MetersToMiles(meters int) int

MetersToMiles converts Carwings distances (in meters) to miles.

Types

type BatteryStatus

type BatteryStatus struct {
	// Date and time this battery status was retrieved from the
	// vehicle.
	Timestamp time.Time

	// Total capacity of the battery.  Units unknown.
	Capacity int

	// Remaining battery level.  Units unknown, but same as Capacity.
	Remaining int

	// Remaining battery level in Watt Hours.
	RemainingWH int

	// Current state of charge.  In percent, should be roughly
	// equivalent to Remaining / Capacity * 100.
	StateOfCharge int // percent

	// Estimated cruising range with climate control on, in
	// meters.
	CruisingRangeACOn int

	// Estimated cruising range with climate control off, in
	// meters.
	CruisingRangeACOff int

	// Current plugged-in state
	PluginState PluginState

	// Current charging status
	ChargingStatus ChargingStatus

	// Amount of time remaining until battery is fully charged,
	// using different possible charging methods.
	TimeToFull TimeToFull
}

BatteryStatus contains information about the vehicle's state of charge, current plugged-in state, charging status, and the time to charge the battery to full.

type ChargingStatus

type ChargingStatus string

ChargingStatus indicates whether and how the vehicle is charging.

func (ChargingStatus) String

func (cs ChargingStatus) String() string

type ClimateStatus

type ClimateStatus struct {
	// Date and time this status was retrieved from the vehicle.
	LastOperationTime time.Time

	// The current climate control operation status.
	Running bool

	// Current plugged-in state
	PluginState PluginState

	// The amount of time the climate control system will run
	// while on battery power, in seconds.
	BatteryDuration int

	// The amount of time the climate control system will run
	// while plugged in, in seconds.
	PluggedDuration int

	// The climate preset temperature unit, F or C
	TemperatureUnit string

	// The climate preset temperature value
	Temperature int

	// Time the AC was stopped, or is scheduled to stop
	ACStopTime time.Time

	// Estimated cruising range with climate control on, in
	// meters.
	CruisingRangeACOn int

	// Estimated cruising range with climate control off, in
	// meters.
	CruisingRangeACOff int
}

ClimateStatus contains information about the vehicle's climate control (AC or heater) status.

type DailyStatistics

type DailyStatistics struct {
	TargetDate              time.Time
	EfficiencyScale         string
	Efficiency              float64 `json:",string"`
	EfficiencyLevel         int     `json:",string"`
	PowerConsumedMotor      float64 `json:",string"`
	PowerConsumedMotorLevel int     `json:",string"`
	PowerRegeneration       float64 `json:",string"`
	PowerRegenerationLevel  int     `json:",string"`
	PowerConsumedAUX        float64 `json:",string"`
	PowerConsumedAUXLevel   int     `json:",string"`
}

DailyStatistics holds the statistics for a day

type DateDetail

type DateDetail struct {
	TargetDate string
	Trips      []TripDetail
}

DateDetail is the detail for a single date

type MonthlyStatistics

type MonthlyStatistics struct {
	EfficiencyScale string
	ElectricityRate float64
	ElectricityBill float64
	Dates           []DateDetail
	Total           MonthlyTotals
}

MonthlyStatistics is the structure returned which includes all of the trips and all of the totals as well as the electricity rate informtion that has been supplied to CarWings.

type MonthlyTotals

type MonthlyTotals struct {
	Trips              int     `json:"TotalNumberOfTrips,string"`
	PowerConsumed      float64 `json:"TotalPowerConsumptTotal,string"`
	PowerConsumedMotor float64 `json:"TotalPowerConsumptMoter,string"`
	PowerRegenerated   float64 `json:"TotalPowerConsumptMinus,string"`
	MetersTravelled    int     `json:"TotalTravelDistance,string"`
	Efficiency         float64 `json:"TotalElectricMileage,string"`
	CO2Reduction       int     `json:"TotalCO2Reductiont,string"`
}

MonthlyTotals holds the various totals of things for the whole month

type PluginState

type PluginState string

PluginState indicates whether and how the vehicle is plugged in. It is separate from ChargingStatus, because the vehicle can be plugged in but not actively charging.

func (PluginState) String

func (ps PluginState) String() string

type Session

type Session struct {
	// Region is one of the predefined region codes where this car operates.
	Region string

	// Filename is an optional file to load and save an existing session to.
	Filename string

	VIN string
	// contains filtered or unexported fields
}

Session defines a one or more connections to the Carwings service

func (*Session) BatteryStatus

func (s *Session) BatteryStatus() (BatteryStatus, error)

BatteryStatus returns the most recent battery status from the Carwings service. Note that this data is not real-time: it is cached from the last time the vehicle data was updated. Use UpdateStatus method to update vehicle data.

func (*Session) CabinTempRequest

func (s *Session) CabinTempRequest() (string, error)

CabinTempRequest sends a request to get the cabin temperature. This is an asynchronous operation: it returns a "result key" that can be used to poll for status with the CheckCabinTempRequest method.

func (*Session) ChargingRequest

func (s *Session) ChargingRequest() error

ChargingRequest begins charging a plugged-in vehicle.

func (*Session) CheckCabinTempRequest

func (s *Session) CheckCabinTempRequest(resultKey string) (bool, error)

CheckCabinTempRequest returns whether the CabinTempRequest has finished.

func (*Session) CheckClimateOffRequest

func (s *Session) CheckClimateOffRequest(resultKey string) (bool, error)

CheckClimateOffRequest returns whether the ClimateOffRequest has finished.

func (*Session) CheckClimateOnRequest

func (s *Session) CheckClimateOnRequest(resultKey string) (bool, error)

CheckClimateOnRequest returns whether the ClimateOnRequest has finished.

func (*Session) CheckUpdate

func (s *Session) CheckUpdate(resultKey string) (bool, error)

CheckUpdate returns whether the update corresponding to the provided result key has finished.

func (*Session) ClimateControlStatus

func (s *Session) ClimateControlStatus() (ClimateStatus, error)

ClimateControlStatus returns the most recent climate control status from the Carwings service.

func (*Session) ClimateOffRequest

func (s *Session) ClimateOffRequest() (string, error)

ClimateOffRequest sends a request to turn off the climate control system. This is an asynchronous operation: it returns a "result key" that can be used to poll for status with the CheckClimateOffRequest method.

func (*Session) ClimateOnRequest

func (s *Session) ClimateOnRequest() (string, error)

ClimateOnRequest sends a request to turn on the climate control system. This is an asynchronous operation: it returns a "result key" that can be used to poll for status with the CheckClimateOnRequest method.

func (*Session) Connect

func (s *Session) Connect(username, password string) error

Connect establishes a new authenticated Session with the Carwings service.

func (*Session) GetCabinTemp

func (s *Session) GetCabinTemp() int

GetCabinTemp returns the latest cached cabin temperature result.

func (*Session) GetDailyStatistics

func (s *Session) GetDailyStatistics(day time.Time) (DailyStatistics, error)

GetDailyStatistics returns the statistics for a specified Date^W^W^Wtoday

func (*Session) GetMonthlyStatistics

func (s *Session) GetMonthlyStatistics(month time.Time) (MonthlyStatistics, error)

GetMonthlyStatistics gets the statistics for a particular month

func (*Session) Login

func (s *Session) Login() error

func (*Session) UpdateStatus

func (s *Session) UpdateStatus() (string, error)

UpdateStatus asks the Carwings service to request an update from the vehicle. This is an asynchronous operation: it returns a "result key" that must be used to poll for status with the CheckUpdate method.

type TimeToFull

type TimeToFull struct {
	// Time to fully charge the battery using a 1.4 kW Level 1
	// (120V 12A) trickle charge.
	Level1 time.Duration

	// Time to fully charge the battery using a 3.3 kW Level 2
	// (240V ~15A) charge.
	Level2 time.Duration

	// Time to fully charge the battery using a 6.6 kW Level 2
	// (240V ~30A) charge.
	Level2At6kW time.Duration
}

TimeToFull contains information about how long it will take to charge the battery to full via different charging methods.

type TripDetail

type TripDetail struct {
	//              "PriceSimulatorDetailInfoTrip": [
	//                {
	//                  "TripId": "1",
	//                  "PowerConsumptTotal": "2461.12",
	//                  "PowerConsumptMoter": "3812.22",
	//                  "PowerConsumptMinus": "1351.1",
	//                  "TravelDistance": "17841",
	//                  "ElectricMileage": "13.8",
	//                  "CO2Reduction": "3",
	//                  "MapDisplayFlg": "NONACTIVE",
	//                  "GpsDatetime": "2018-08-05T10:18:47"
	//                },
	TripId             int       `json:",string"`
	PowerConsumedTotal float64   `json:"PowerConsumptTotal,string"`
	PowerConsumedMotor float64   `json:"PowerConsumptMoter,string"`
	PowerRegenerated   float64   `json:"PowerConsumptMinus,string"`
	Meters             int       `json:"TravelDistance,string"`
	Efficiency         float64   `json:"ElectricMileage,string"`
	CO2Reduction       int       `json:",string"`
	MapDisplayFlag     string    `json:"MapDisplayFlg"`
	GPSDateTime        cwTime    `json:"GpsDatetime"`
	Started            time.Time `json:",omitempty"`
}

TripDetail holds the details of each trip. All of the parsed detail is used in both the response and the MonthlyStatistics.

type VehicleLocation

type VehicleLocation struct {
	// Timestamp of the last time vehicle location was updated.
	Timestamp time.Time

	// Latitude of the vehicle
	Latitude string

	// Longitude of the vehicle
	Longitude string
}

VehicleLocation indicates the vehicle's current location.

Directories

Path Synopsis
cmd

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL