smartcar

package module
Version: v1.4.0 Latest Latest
Warning

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

Go to latest
Published: Apr 24, 2021 License: MIT Imports: 14 Imported by: 0

README

Smartcar Go SDK

GoDoc

Overview

The Smartcar API lets you read vehicle data (location, odometer, fuel, etc.) and send commands to vehicles (lock, unlock) using HTTP requests.

Installation

Install the smartcar package if you are not using Go modules:

go get -u github.com/smartcar/go-sdk

Import it using:

import smartcar "github.com/smartcar/go-sdk"

Getting Started Guide

  1. Initialize a Smartcar Client.

    // A smartcar Client is needed to talk to any of the methods in the SDK
    smartcarClient := smartcar.NewClient()
    

    ``

  2. Initialize an Auth Client struct with your client id, client secret, redirect URI, the scopes you want, flags, and test mode.

    // An Auth Client is used to generate a smartcar connect url, authenticate with smartcar, and check compatibility
    authClient := smartcarClient.NewAuth(&smartcar.AuthParams{
    	ClientID:     "<CLIENT_ID>",
    	ClientSecret: "<CLIENT_SECRET>",
    	RedirectURI:  "<REDIRECT_URI>",
    	Flags:      "<Optional Flags>",
    	Scope:        []string{"read_vehicle_info"},
    	TestMode:     true,
    })
    

    ``

  3. Get an auth URL and then redirect user to that URL.

    authURL, err := authClient.GetAuthURL(&smartcar.AuthURLParams{})
    
    // redirect user here.
    
    /*
    	If using the net/http library, you can use http.Redirect.
    	In order for the next line to work you need to have an endpoint that
    	has access to a http.ResponseWriter and http.Request.
    */
    http.Redirect(w, req, authURL, http.StatusSeeOther)
    

    ``

  4. Setup up a redirectURI endpoint to receive authorization code. Exchange auth code for an authorization.

    // Exchange initial authorization code
    token, err := authClient.ExchangeCode(
    	context.TODO(),
    	&smartcar.ExchangeCodeParams{Code: code},
    )
    
    // When your token expires, you can exchange it by sending your refresh token for continued access.
    token, err := authClient.ExchangeRefreshToken(
    	context.TODO(),
    	&smartcar.ExchangeRefreshTokenParams{Token: token.Refresh},
    )
    
    // You can check the validity of your token by callint the IsTokenExpired method
    isExpired := smartcarClient.IsTokenExpired(&smartcarClient.TokenExpiredParams{
    	Expiry: token.AccessExpiry,
    })
    

    ``

  5. In order to send a request to a vehicle, you need to create a smartcar.Vehicle, and for that you need a vehicle ID. You can get a vehicleID by sending a request to smartcar.GetVehicleIDs, which will return a list of vehicleIDs associated with an access token.

    vehicleIDs, err := smartcar.GetVehicleIDs(
    	context.TODO(),
    	&smartcar.VehicleIDsParams{Access: token.Access},
    )
    

    ``

  6. Construct vehicle with an ID, and an AccessToken, a UnitSystem is optional

    vehicleParams := smartcarClient.VehicleParams{
    	ID: (*vehicleIDs)[0],
    	AccessToken: token.Access,
    }
    vehicle := smartcarClient.NewVehicle(&vehicleParams)
    

    ``

  7. Send request to vehicle. The following endpoints are available. (check the go documentation for the most up to date list.)

    // Vehicle Endpoints
    battery, err := vehicle.GetBattery(context.TODO())
    batteryCapacity, err := vehicle.GetBatteryCapacity(context.TODO())
    charge, err := vehicle.GetCharge(context.TODO())
    disconnect, err := vehicle.Disconnect(context.TODO())
    fuel, err := vehicle.GetFuel(context.TODO())
    info, err := vehicle.GetInfo(context.TODO())
    location, err := vehicle.GetLocation(context.TODO())
    lock, err := vehicle.Lock(context.TODO())
    odometer, err := vehicle.GetOdometer(context.TODO())
    oil, err := vehicle.GetOil(context.TODO())
    permissions, err := vehicle.GetPermissions(context.TODO())
    tirePressure, err := vehicle.GetTiresPressue(context.TODO())
    unlock, err := vehicle.Unlock(context.TODO())
    vin, err := vehicle.GetVIN(context.TODO())
    
    // You can change the unit systems of a vehicle at any point by doing.
    err := vehicle.SetUnits(smartcar.UnitsParams{Unit: smartcar.UnitSystemMetric})
    

    ``

Pro Features

Compatibility

Compatibility allows you to verify if a particular VIN is compatible with a scope of permissions. This method should be used prior to directing a user to the Smartcar Connect flow. Learn more on our doc center.. For details on how to specify country code strings refer to ISO 3166-1 alpha-2

isCompatible, err := smartcarClient.IsVINCompatible(context.TODO(), &smartcar.VINCompatibleParams{
	VIN: "<VIN>",
	Scope: []string{"<Scope>"},
	Country: "<Country Code>",
	ClientID:     "<CLIENT_ID>",
	ClientSecret: "<CLIENT_SECRET>",
})
Batch

Batch allows you to send make requests to multiple endpoints in a single request.

batch, err := vehicle.Batch(
	context.TODO(),
	smartcar.BatteryPath,
	smartcar.InfoPath,
	smartcar.LocationPath,
	smartcar.OdometerPath,
)
battery := batch.Battery
info := batch.Info
location := batch.Location
odometer := batch.Odometer

Documentation

Overview

Package smartcar is the official Go SDK of the Smartcar API. Smartcar is the only vehicle API built for developers, by developers. Learn more about Smartcar here, https://smartcar.com/

Index

Constants

This section is empty.

Variables

View Source
var APIVersion string = "1.0"

APIVersion is the default version of API to use

Functions

This section is empty.

Types

type Auth

type Auth interface {
	GetAuthURL(*AuthURLParams) (string, error)
	ExchangeCode(context.Context, *ExchangeCodeParams) (*Token, error)
	ExchangeRefreshToken(context.Context, *ExchangeRefreshTokenParams) (*Token, error)
}

Auth interface is a...

type AuthParams

type AuthParams struct {
	ClientID     string
	ClientSecret string
	RedirectURI  string
	Scope        []string
	TestMode     bool
}

AuthParams is a param in client.NewAuth

type AuthURLParams

type AuthURLParams struct {
	ForceApproval bool
	State         string
	Flags         []string
	MakeBypass
	SingleSelect
}

AuthURLParams contains the AuthClient, Pro authorization features and all fields that can be used to construct an auth URL.

type Battery

type Battery struct {
	PercentRemaining float64 `json:"percentRemaining"`
	Range            float64 `json:"range"`
	ResponseHeaders
}

Battery formats response returned from vehicle.GetBattery().

type BatteryCapacity added in v1.3.0

type BatteryCapacity struct {
	Capacity float64 `json:"capacity"`
	ResponseHeaders
}

BatteryCapacity formats response returned from vehicle.GetBatteryCapacity().

type Charge

type Charge struct {
	IsPluggedIn bool   `json:"isPluggedIn"`
	State       string `json:"state"`
	ResponseHeaders
}

Charge formats response returned from vehicle.GetCharge().

type ChargeControl

type ChargeControl struct {
	Status string `json:"status"`
	ResponseHeaders
}

ChargeControl Charge formats response returned from the vehicle.StartCharge(), vehicle.StopCharge().

type Client

type Client interface {
	GetUserID(context.Context, *UserIDParams) (*string, error)
	GetVehicleIDs(context.Context, *VehicleIDsParams) (*[]string, error)
	IsTokenExpired(*TokenExpiredParams) bool
	IsVINCompatible(context.Context, *VINCompatibleParams) (bool, error)
	HasPermissions(context.Context, Vehicle, *PermissionsParams) (bool, error)
	NewAuth(*AuthParams) Auth
	NewVehicle(*VehicleParams) Vehicle
	SetAPIVersion(string)
}

Client exposes methods that allow you to interact with Smartcar's API that are not part of Vehicle or Auth.

func NewClient

func NewClient() Client

NewClient creates new SmartcarClient. This is the entry point for communicating with Smartcar's API. Note: You cannot use any of the methods on this SDK if you don't call this method.

type Data

type Data struct {
	Battery         *Battery         `json:"battery,omitempty"`
	BatteryCapacity *BatteryCapacity `json:"batteryCapacity,omitempty"`
	Charge          *Charge          `json:"charge,omitempty"`
	Fuel            *Fuel            `json:"fuel,omitempty"`
	Info            *Info            `json:"info,omitempty"`
	Location        *Location        `json:"location,omitempty"`
	Odometer        *Odometer        `json:"odometer,omitempty"`
	Oil             *Oil             `json:"oil,omitempty"`
	Permissions     *Permissions     `json:"permissions,omitempty"`
	TirePressure    *TirePressure    `json:"tirePressure,omitempty"`
	VIN             *VIN             `json:"vin,omitempty"`
}

Data formats responses returned from vehicle.Batch().

type Disconnect

type Disconnect struct {
	Status string `json:"status"`
	ResponseHeaders
}

Disconnect formats response returned from vehicle.Disconnect().

type ExchangeCodeParams

type ExchangeCodeParams struct {
	Code string
}

ExchangeCodeParams struct

type ExchangeRefreshTokenParams

type ExchangeRefreshTokenParams struct {
	Token string
}

ExchangeRefreshTokenParams struct

type Fuel

type Fuel struct {
	AmountRemaining  float64 `json:"amountRemaining"`
	PercentRemaining float64 `json:"percentRemaining"`
	Range            float64 `json:"range"`
	ResponseHeaders
}

Fuel formats response returned from vehicle.GetFuel().

type Info

type Info struct {
	ID    string `json:"id"`
	Make  string `json:"make"`
	Model string `json:"model"`
	Year  int    `json:"year"`
	ResponseHeaders
}

Info formats response returned from vehicle.GetInfo().

type Key

type Key string

Key is a type to used for API endpoints

const (
	BatteryPath         Key = "/battery"
	BatteryCapacityPath Key = "/battery/capacity"
	ChargePath          Key = "/charge"
	FuelPath            Key = "/fuel"
	InfoPath            Key = "/"
	LocationPath        Key = "/location"
	OdometerPath        Key = "/odometer"
	OilPath             Key = "/engine/oil"
	PermissionsPath     Key = "/permissions"
	TirePressurePath    Key = "/tires/pressure"
	VINPath             Key = "/vin"
)

Helper types to use in vehicle.Batch()

type Location

type Location struct {
	Latitude  float64 `json:"latitude"`
	Longitude float64 `json:"longitude"`
	ResponseHeaders
}

Location formats response returned from vehicle.GetLocation().

type MakeBypass

type MakeBypass struct {
	Make string
}

MakeBypass uses a make to bypass the Smartcar Connect brand selector. Smartcar Pro feature.

type Odometer

type Odometer struct {
	Distance float64 `json:"distance"`
	ResponseHeaders
}

Odometer formats response returned from vehicle.GetOdometer().

type Oil

type Oil struct {
	LifeRemaining float64 `json:"lifeRemaining"`
	ResponseHeaders
}

Oil formats response returned from vehicle.GetOil().

type Permissions

type Permissions struct {
	Permissions []string `json:"permissions"`
	ResponseHeaders
}

Permissions formats response returned from vehicle.GetPermissions().

type PermissionsParams

type PermissionsParams struct {
	Permissions []string
}

PermissionsParams is a param in client.HasPermissions

type ResponseHeaders

type ResponseHeaders struct {
	// Deprecated: Should use DataAge instead of Age
	Age        string     `json:"age,omitempty"`
	DataAge    string     `json:"dataAge,omitempty"`
	RequestID  string     `json:"requestId,omitempty"`
	UnitSystem UnitSystem `json:"unitSystem,omitempty"`
}

ResponseHeaders is a struct that has Smartcar's API response headers.

type Security

type Security struct {
	Status string `json:"status"`
	ResponseHeaders
}

Security formats response returned from the vehicle.Lock(), vehicle.Unlock().

type SingleSelect

type SingleSelect struct {
	Enabled bool
	VIN     string
}

SingleSelect will only authorize vehicles that match the given properties. Smartcar Pro feature.

type TirePressure

type TirePressure struct {
	FrontLeft  float64 `json:"frontLeft"`
	FrontRight float64 `json:"frontRight"`
	BackLeft   float64 `json:"backLeft"`
	BackRight  float64 `json:"backRight"`
	ResponseHeaders
}

TirePressure formats response returned from vehicle.GetTirePressure().

type Token

type Token struct {
	Access        string    `json:"access_token"`
	AccessExpiry  time.Time `json:"access_expiry"`
	Refresh       string    `json:"refresh_token"`
	RefreshExpiry time.Time `json:"refresh_expiry"`
	ExpiresIn     int       `json:"expires_in"`
}

Token is returned by auth.ExchangeCode and auth.ExchangeRefreshToken.

type TokenExpiredParams

type TokenExpiredParams struct {
	Expiry time.Time
}

TokenExpiredParams is a param in client.IsTokenExpired

type UnitSystem

type UnitSystem string

UnitSystem type that will have either imperic or metric.

const (
	Metric   UnitSystem = "metric"
	Imperial UnitSystem = "imperial"
)

/ UnitSystem constants that initialize metric or imperial.

type UnitsParams

type UnitsParams struct {
	Units UnitSystem
}

UnitsParams struct is UnitsParam is a param in vehicle.SetUnitSystem

type UserIDParams

type UserIDParams struct {
	Access string
}

UserIDParams is a param in client.GetUserID

type VIN

type VIN struct {
	VIN string `json:"vin"`
	ResponseHeaders
}

VIN formats response returned from vehicle.GetVIN().

type VINCompatibleParams

type VINCompatibleParams struct {
	VIN          string
	Scope        []string
	Country      string
	ClientID     string
	ClientSecret string
}

VINCompatibleParams is a param in client.IsVINCompatible

type Vehicle

type Vehicle interface {
	Batch(context.Context, ...Key) (*Data, error)
	Disconnect(context.Context) (*Disconnect, error)
	GetBattery(context.Context) (*Battery, error)
	GetBatteryCapacity(context.Context) (*BatteryCapacity, error)
	GetCharge(context.Context) (*Charge, error)
	GetFuel(context.Context) (*Fuel, error)
	GetInfo(context.Context) (*Info, error)
	GetLocation(context.Context) (*Location, error)
	GetOdometer(context.Context) (*Odometer, error)
	GetOil(context.Context) (*Oil, error)
	GetPermissions(context.Context) (*Permissions, error)
	GetTiresPressure(context.Context) (*TirePressure, error)
	GetVIN(context.Context) (*VIN, error)
	Lock(context.Context) (*Security, error)
	SetUnitSystem(*UnitsParams) error
	Unlock(context.Context) (*Security, error)
	StartCharge(context.Context) (*ChargeControl, error)
	StopCharge(context.Context) (*ChargeControl, error)
}

Vehicle is an interface that contains all public methods available for vehicle. vehicle needs to implement this methods to be able to expose them.

type VehicleIDsParams

type VehicleIDsParams struct {
	Access string
}

VehicleIDsParams is a param in client.GetVehicleIDs

type VehicleParams

type VehicleParams struct {
	ID          string
	AccessToken string
	UnitSystem  UnitSystem
}

VehicleParams is a param in client.NewVehicle

Jump to

Keyboard shortcuts

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