carwings

package module
v0.0.0-...-6e3f498 Latest Latest
Warning

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

Go to latest
Published: Dec 2, 2019 License: MIT Imports: 13 Imported by: 0

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, remotely start charging, and retrieve the last known location of the vehicle.

Command-line tool

The carwings tool can be installed with:

go get github.com/joeshaw/carwings/cmd/carwings

Run carwings by itself to see full usage information.

To update vehicle information:

carwings -username <username> -password <password> update

To get latest battery status:

carwings -username <username> -password <password> 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 mi (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.

Usernames and passwords can also be provided through the environment variables CARWINGS_USERNAME, CARWINGS_PASSWORD and CARWINGS_REGION or in a ~/.carwingsrc file in the format:

username=<username>
password=<password>
region=<eu|au|jp|ca|us>
sessionfile=<filename for saving sessions>
units=<km|miles>

If the sessionfile is set in the configuration then the session data will be read from that file, if present, and written to it if it is missing.

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

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: https://gitlab.com/tobiaswkjeldsen/dartcarwings https://gitlab.com/tobiaswkjeldsen/carwingsflutter

Contributing

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

License

Copyright 2017-2018 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"
)

Regions available

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")
)

The various possible plugin states

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")
)

The various possible charging states

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")

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

Functions

This section is empty.

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

	// 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 Config

type Config struct {
	Username    string
	Password    string
	Region      string
	SiUnits     bool
	SessionFile string
	TimeZone    string
}

Config defines the structure of the config file

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 PollCheckFunction

type PollCheckFunction func(string) (bool, error)

PollCheckFunction is a type definining a poll

type ScheduledClimate

type ScheduledClimate struct {
	ExecuteTime time.Time
}

ScheduledClimate is a future climate control on

type Session

type Session struct {
	VIN string
	// contains filtered or unexported fields
}

Session defines a one or more connections to the Carwings service

func Connect

func Connect(cfg Config) (*Session, error)

Connect loads an existing saved session, or initialises a new one

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) CancelScheduledClimateControl

func (s *Session) CancelScheduledClimateControl(scheduleAt time.Time) error

CancelScheduledClimateControl cancels scheduled climate control I believe this time is specified in GMT, despite the "tz" parameter

func (*Session) ChargingRequest

func (s *Session) ChargingRequest() error

ChargingRequest begins charging a plugged-in vehicle.

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) CheckLocateRequest

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

CheckLocateRequest returns whether the LocateRequest 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) DistancePowerToEfficiency

func (s Session) DistancePowerToEfficiency(meters int, power float64) float64

DistancePowerToEfficiency converts Carwings distances(m) and power(kWh) to kWh/100(miles|km) as configured

func (Session) EfficiencyUnitsName

func (s Session) EfficiencyUnitsName() string

EfficiencyUnitsName returns the name of the units

func (*Session) GetClimateControlSchedule

func (s *Session) GetClimateControlSchedule() (ScheduledClimate, error)

GetClimateControlSchedule retrieves any previously scheduled climate control I believe this time is specified in GMT, despite the "tz" parameter

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) Load

func (s *Session) Load(fileName string) error

Load loads the session information

func (*Session) LocateRequest

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

LocateRequest sends a request to locate the vehicle. This is an asynchronous operation: it returns a "result key" that can be used to poll for status with the CheckLocateRequest method.

func (*Session) LocateVehicle

func (s *Session) LocateVehicle() (VehicleLocation, error)

LocateVehicle requests the last-known location of the vehicle from the Carwings service. This data is not real-time. A timestamp of the most recent update is available in the returned VehicleLocation value.

func (*Session) Login

func (s *Session) Login() error

Login handles the session login

func (Session) MetersToUnits

func (s Session) MetersToUnits(meters int) float64

MetersToUnits converts Carwings distances (in meters) to miles|km as configured

func (Session) Save

func (s Session) Save(fileName string) error

Save saves the session information

func (*Session) ScheduleClimateControl

func (s *Session) ScheduleClimateControl(scheduleAt time.Time) error

ScheduleClimateControl schedules climate control for some future time I believe this time is specified in GMT, despite the "tz" parameter

func (Session) UnitsName

func (s Session) UnitsName() string

UnitsName returns the name of the units

func (*Session) UpdateScheduledClimateControl

func (s *Session) UpdateScheduledClimateControl(scheduleAt time.Time) error

UpdateScheduledClimateControl updates scheduled climate control I believe this time is specified in GMT, despite the "tz" parameter

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 can be used to poll for status with the CheckUpdate method.

func (*Session) WaitForResult

func (s *Session) WaitForResult(key string, method PollCheckFunction) error

WaitForResult will poll using the supplied method until either success or error

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.

Jump to

Keyboard shortcuts

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