powerwall

package module
v0.20.0 Latest Latest
Warning

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

Go to latest
Published: Sep 3, 2023 License: MIT Imports: 14 Imported by: 1

README

go-powerwall

A Go library for communicating with Tesla Powerwall appliances via the local-network API.


Many thanks to Vince Loschiavo and other contributors to https://github.com/vloschiavo/powerwall2 for providing a lot of the information to make this possible!

Note: The Tesla powerwall interface is an undocumented API which is not supported by Tesla, and could change at any time. This library has been tested on devices running version 21.39 and 21.44 of the firmware only, at this time.

This library is incomplete. Pull requests to add support for more functions are always welcome!


This library is intended to allow clients to easily pull information from and send commands to a Tesla Powerwall via a Tesla Home Energy Gateway 2. Note that this is the internal local-network API exposed by the device itself. It is not the same as the Tesla Owner API, which allows you to control the device via Tesla's servers over the Internet. To use this API, your Powerwall Energy Gateway must be connected to a local network via WiFi or Ethernet, and accessible via that network.

Basic Usage

First, create a new client instance by calling powerwall.NewClient, providing the hostname or IP address of the gateway appliance, along with the email address and password which should be used to login. (If you have not already, it is recommended that you first login to the device using a web browser and change your password, as detailed on Tesla's website.) Once you have a client object, you can use its various functions to retrieve information from the device, etc.

import (
	"fmt"
	"github.com/foogod/go-powerwall"
)

func main() {
	client := powerwall.NewClient("192.168.123.45", "teslaguy@example.com", "MySuperSecretPassword!")
	result, err := client.GetStatus()
	if err != nil {
		panic(err)
	}
	fmt.Printf("The gateway's ID number is: %s\nIt is running version: %s\n", result.Din, result.Version)
}

The client will automatically login to the device as needed, and will remember and re-use the auth-token between calls. It will also automatically re-login if necessary (i.e. if the token expires).

TLS Certificates

The Tesla gateway uses a self-signed certificate, which means that it shows up as invalid by default (because it is not signed by any known authority). For this reason, the default behavior of the client is to not try to validate the TLS certificate when connecting. This works, but it is insecure, as it is possible for someone else to impersonate the gateway instead (a "man in the middle attack"). If a more secure configuration is desired, the library does support a way to do full TLS validation, but you will need to provide it with a copy of the certificate to validate against after creating the client, using the SetTLSCert function.

	client := powerwall.NewClient("192.168.123.45", "someguy@example.com", "MySuperSecretPassword!")
	client.SetTLSCert(cert)

The certificate can be obtained using command-line utilities such as openssl; however, the client does also have a handy function for retrieving the certificate from a Powerwall gateway directly, as well:

	cert, err := client.FetchTLSCert()

The typical use-case of this would be to provide a special option or command in your program to fetch and store the certificate in a file initially, and from then on read it from the file and use that to set the certificate when creating any new clients going forward, before performing any API calls. For an example of this, see the --certfile and fetchcert options of the powerwall-cmd sample program in this repo.

Retrying requests

Tesla's Powerwall appliances seem to have some issues staying reliably connected to WiFi networks (for me, at least), and will periodically become disconnected for a few seconds and then reconnect. This can cause a problem if you happen to hit your API request at the wrong time, as you will just end up with a network error instead.

To work around this, the client can be configured to retry HTTP requests for a given amount of time before actually giving up, if they are failing because of network connection errors. This can be done by calling the SetRetry function with the desired retry interval and timeout:

	// Retry attempts every second, giving up after a minute of failed attempts.
	interval := time.ParseDuration("1s")
	timeout := time.ParseDuration("60s")
	client.SetRetry(interval, timeout)

The client will wait at least the specified interval between attempts (but it may sometimes be longer if, for example, a connection timeout takes longer than that interval just to return the error). It will keep trying until the timeout has been exceeded (doing however many retries it can fit within that period).

This behavior is disabled by default. Setting the timeout to zero (or negative) will also disable all retries. (Note that setting interval to zero (or negative) is also allowed, but will result in the library attempting to retry as fast as possible, which may produce excessive network traffic or CPU usage, so it is not generally advised.)

Saving and re-using the auth token

If you are making a program which needs to regularly create new clients (such as a command-line utility which gets run on a regular basis to collect stats and then exit, etc), it may be desirable to save the auth token after login so that it can be re-used later. This can be done using the GetAuthToken and SetAuthToken functions:

	token := client.GetAuthToken()
	client.SetAuthToken(token)

(Note that the client must have already performed a login before you will be able to retrieve a valid token with GetAuthToken. This will happen automatically if you attempt to fetch from an API which requires authentication, or you can use DoLogin initially to force a login operation first.)

Keep in mind that the client will automatically re-login (and thus generate a new auth token) if the provided one is invalid (it has expired, etc). It is therefore a good idea to check periodically whether the token has changed (using GetAuthToken), and if so update your saved copy as well.

For an example of this, see the --authcache option of the powerwall-cmd sample program in this repo.

Logging

If something is not working properly, it may be useful to get debug logging of what the powerwall library is doing behind the scenes (including HTTP requests/responses, etc). You can register a logging function for this purpose using powerwall.SetLogFunc:

func myLogFunc(v ...interface{}) {
        msg := fmt.Sprintf(v...)
	fmt.Printf("powerwall: %s\n", msg)
}

func main() {
	powerwall.SetLogFunc(logDebug)

	(...)
}

(The arguments to the log function are the same as for Sprintf/etc. Note, however, that generated log lines are not terminated with "\n", so you will need to add a newline if you are sending them to something like fmt.Printf directly.)

Documentation

Overview

Package powerwall implements an interface for accessing Tesla Powerwall devices via the local-network API.

Note: This API is currently undocumented, and all information about it has been obtained through reverse-engineering. Some information here may therefore be incomplete or incorrect at this time, and it is also possible that the API will change without warning.

Much of the information used to build this library was obtained from https://github.com/vloschiavo/powerwall2. If you have additional information about any of this, please help by contributing what you know to that project.

General usage:

First, you will need to create a new powerwall.Client object using the NewClient function. After that has been done, you can use any of the following functions on that object to interact with the Powerwall gateway.

Functions for authentication and login:

(Note: DoLogin generally does not need to be called explicitly)

(*Client) DoLogin()
(*Client) GetAuthToken()
(*Client) SetAuthToken(token string)

Functions for configuring the client object:

(*Client) FetchTLSCert()
(*Client) SetTLSCert(cert)

Functions for reading power meter data:

(*Client) GetMeters(category string)
(*Client) GetMetersAggregates()

Functions for reading network interface info:

(*Client) GetNetworks()

Functions for getting general info about the gateway and site:

(*Client) GetStatus()
(*Client) GetSiteInfo()
(*Client) GetSitemaster()

Functions for getting info about the system state:

(*Client) GetSystemStatus()
(*Client) GetGridFaults()
(*Client) GetGridStatus()
(*Client) GetSOE()
(*Client) GetOperation()

Index

Constants

View Source
const (
	SitemasterStatusUp   = "StatusUp"
	SitemasterStatusDown = "StatusDown"
)

Possible values for the Status field of the SitemasterData struct:

View Source
const (
	SitemasterRebootOK           = "Yes"
	SitemasterRebootPowerTooHigh = "Power flow is too high"
)

Known possible values returned for the CanReboot field of the SitemasterData struct:

(Note that this list is almost certainly incomplete at this point)

View Source
const (
	GridStatusConnected  = "SystemGridConnected"
	GridStatusIslanded   = "SystemIslandedActive"
	GridStatusTransition = "SystemTransitionToGrid"
)

Possible options for the GridStatus field of GridStatusData:

The powerwall can be in one of three states. "Connected" indicates that it is receiving power from the utility and functioning normally. "Islanded" means that it has gone off-grid and is generating power entirely independently of the utility power (if utility power has been lost, or if it has been put into "off-grid" mode). "Transitioning" means that it is in the process of going from being off-grid to back on-grid, which can take a little bit of time to verify the supplied power is clean and synchronize with it, etc.

View Source
const (
	OperationModeSelf      = "self_consumption" // Reported as "Self Powered" in the app
	OperationModeTimeBased = "autonomous"       // Reported as "Time-Based Control" in the app
)

Possible options for the RealMode field of OperationData:

Variables

This section is empty.

Functions

func SetErrFunc

func SetErrFunc(f func(string, error))

SetErrFunc registers a callback function which will be called with additional information when certain errors occur. This can be useful if you don't want full debug logging, but still want to log additional information that might be helpful when troubleshooting, for example, API message format errors, etc.

func SetLogFunc

func SetLogFunc(f func(...interface{}))

SetLogFunc registers a callback function which can be used for debug logging of the powerwall library. The provided function should accept arguments in the same format as Printf/Sprintf/etc. Note that log lines passed to this function are *not* newline-terminated, so you will need to add newlines if you want to put them out directly to stdout/stderr, etc.

Types

type ApiError

type ApiError struct {
	URL        url.URL
	StatusCode int
	Body       []byte
}

ApiError indicates that something unexpected occurred with the HTTP API call. This usually occurs when the endpoint returns an unexpected status code.

func (ApiError) Error

func (e ApiError) Error() string

type AuthFailure

type AuthFailure struct {
	URL       url.URL
	ErrorText string
	Message   string
}

AuthFailure is returned when the client was unable to perform a request because it was not able to login using the provided email and password.

func (AuthFailure) Error

func (e AuthFailure) Error() string

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client represents a connection to a Tesla Energy Gateway (Powerwall controller).

func NewClient

func NewClient(gatewayAddress string, gatewayLoginEmail string, gatewayLoginPassword string) *Client

NewClient creates a new Client object. gatewayAddress should be the IP address or hostname of the Tesla Energy Gateway (TEG) device which is connected to the network. gatewayLoginEmail and gatewayLoginPassword are the same as the email address and password which would be used for a "customer" login, when logging in via the web interface (Note: This is not necessarily the same password as used to login to Tesla's servers via the app, which can be different)

For more information on logging into an Energy Gateway, see https://www.tesla.com/support/energy/powerwall/own/monitoring-from-home-network

func (*Client) DoLogin

func (c *Client) DoLogin() error

DoLogin logs into the Powerwall gateway and obtains an auth token which can be used for subsequent API calls. Note that you should not normally need to call this explicitly. The library will automatically attempt to login anyway if a call is made which requires authentication and it is not already successfully logged in.

func (*Client) FetchTLSCert

func (c *Client) FetchTLSCert() (*x509.Certificate, error)

FetchTLSCert queries the gateway and returns a copy of the TLS certificate it is currently presenting for connections. This is useful for saving and later using with `SetTLSCert` to validate future connections.

func (*Client) GetAuthToken

func (c *Client) GetAuthToken() string

GetAuthToken returns the current auth token in use. This can be saved and then passed to SetAuthToken on later connections to re-use the same token across Clients.

func (*Client) GetGridFaults

func (c *Client) GetGridFaults() (*[]GridFaultData, error)

GetGridFaults returns a list of any current "grid fault" events detected by the system. These generally indicate some issue with the utility power, such as being over or undervoltage, etc.

This same information is also returned by GetSystemStatus in the GridFaults field.

See the GridFaultData type for more information on what fields this returns.

func (*Client) GetGridStatus

func (c *Client) GetGridStatus() (*GridStatusData, error)

GetGridStatus returns information about the current state of the Powerwall's connection to the utility power grid.

See the GridStatusData type for more information on what fields this returns.

func (*Client) GetMeters

func (c *Client) GetMeters(category string) (*[]MeterData, error)

GetMeters fetches detailed meter data for each meter under the specified category. Note that as of this writing, only the "site" and "solar" categories appear to return any data.

If the API returns no data (i.e. an unsupported category name was provided), this will return nil.

See the MeterData type for more information on what fields this returns.

func (*Client) GetMetersAggregates

func (c *Client) GetMetersAggregates() (*map[string]MeterAggregatesData, error)

GetMetersAggregates fetches aggregated meter data for power transferred to/from each category of connection ("site", "solar", "battery", "load", etc).

See the MetersAggregatesData type for more information on what fields this returns.

func (*Client) GetNetworks

func (c *Client) GetNetworks() (*[]NetworkData, error)

GetNetworks returns information about all of the network interfaces in the system, and their statuses.

See the NetworkData type for more information on what fields this returns.

func (*Client) GetOperation

func (c *Client) GetOperation() (*OperationData, error)

GetOperation returns information about the current operation mode configuration. This includes whether the Powerwall is configured for "Self Powered" mode or "Time Based Control", how much of the battery is reserved for backup use, etc.

See the OperationData type for more information on what fields this returns.

func (*Client) GetProblems

func (c *Client) GetProblems() (*TroubleshootingProblemsData, error)

GetProblems returns info about "troubleshooting problems" currently reported by the Powerwall gateway. The format of these reports is currently not documented, but it can potentially still be useful to determine whether the list is non-empty (and thus some investigation is required) or not.

See the TroubleshootingProblemsData type for more information on what fields this returns.

func (*Client) GetSOE

func (c *Client) GetSOE() (*SOEData, error)

GetSOE returns information about the current "State Of Energy" of the system. That is, how much total charge (as a percentage) is present across all batteries.

See the SOEData type for more information on what fields this returns.

func (*Client) GetSiteInfo

func (c *Client) GetSiteInfo() (*SiteInfoData, error)

GetSiteInfo returns information about the "site". This includes general information about the installation, configuration of the hardware, utility grid it is connected to, etc.

See the SiteInfoData type for more information on what fields this returns.

func (*Client) GetSitemaster

func (c *Client) GetSitemaster() (*SitemasterData, error)

GetSitemaster returns information about the Powerwall gateway's "sitemaster" process, which handles most of the normal day-to-day tasks of the system (monitoring power, directing it to the right places, etc).

See the SitemasterData type for more information on what fields this returns.

func (*Client) GetStatus

func (c *Client) GetStatus() (*StatusData, error)

GetStatus performs a "status" API call to fetch basic information about the system, such as the device identification number (part number + serial number), software version, uptime, device type, etc.

Note that this is one of the only API calls which can be made without logging in first.

See the StatusData type for more information on what fields this returns.

func (*Client) GetSystemStatus

func (c *Client) GetSystemStatus() (*SystemStatusData, error)

GetSystemStatus performs a "system_status" API call to fetch general information about the system operation and state.

See the SystemStatusData type for more information on what fields this returns.

func (*Client) SetAuthToken

func (c *Client) SetAuthToken(token string)

SetAuthToken sets the provided string as the new auth token to use for subsequent API calls.

func (*Client) SetRetry

func (c *Client) SetRetry(interval time.Duration, timeout time.Duration)

SetRetry sets the retry interval and timeout used when making HTTP requests. Setting timeout to zero (or negative) will disable retries (default).

(Note: The client will only attempt retries on network errors (connection timed out, etc), not other issues)

func (*Client) SetTLSCert

func (c *Client) SetTLSCert(cert *x509.Certificate)

SetTLSCert sets the TLS certificate which should be used for validating the certificate presented when connecting to the gateway is correct. You can obtain the current certificate in use by the gateway initially via `FetchTLSCert`, and then supply it via this function whenever creating a new connection to ensure the certificate matches the previously fetched one.

type DecodedAlert

type DecodedAlert map[string]string

The DecodedAlert type is used for unpacking values in the "decoded_alert" field of GridFault structures. These are actually encoded as a string, which itself contains a JSON representation of a list of maps, each one containing a "name" and "value". For example:

"[{\"name\":\"PINV_alertID\",\"value\":\"PINV_a008_vfCheckRocof\"},{\"name\":\"PINV_alertType\",\"value\":\"Warning\"}]"

Needless to say, this encoding is rather cumbersome and redundant, so we instead provide a custom JSON decoder to decode these into a string/string map in the form 'name: value'.

func (*DecodedAlert) UnmarshalJSON

func (v *DecodedAlert) UnmarshalJSON(data []byte) error

type Duration

type Duration struct {
	time.Duration
}

Durations in the API are typically represented as strings in duration-string format ("1h23m45.67s", etc). Go's time.Duration type actually produces this format natively, yet will not parse it as an input when unmarshalling JSON (grr), so we need a custom type (with a custom UnmarshalJSON function) to handle this.

func (*Duration) MarshalJSON

func (v *Duration) MarshalJSON() ([]byte, error)

func (*Duration) UnmarshalJSON

func (v *Duration) UnmarshalJSON(p []byte) error

type GridFaultData

type GridFaultData struct {
	Timestamp              int64        `json:"timestamp"`
	AlertName              string       `json:"alert_name"`
	AlertIsFault           bool         `json:"alert_is_fault"`
	DecodedAlert           DecodedAlert `json:"decoded_alert"`
	AlertRaw               int64        `json:"alert_raw"`
	GitHash                string       `json:"git_hash"`
	SiteUID                string       `json:"site_uid"`
	EcuType                string       `json:"ecu_type"`
	EcuPackagePartNumber   string       `json:"ecu_package_part_number"`
	EcuPackageSerialNumber string       `json:"ecu_package_serial_number"`
}

GridFaultData contains fields returned by the "system_status/grid_faults" API call.

This structure is returned by the GetSystemStatus and GetGridFaults functions.

type GridStatusData

type GridStatusData struct {
	GridStatus         string `json:"grid_status"`
	GridServicesActive bool   `json:"grid_services_active"`
}

GridStatusData contains fields returned by the "system_status/grid_status" API call.

This structure is returned by the GetGridStatus function.

type MeterAggregatesData

type MeterAggregatesData struct {
	LastCommunicationTime             time.Time `json:"last_communication_time"`
	InstantPower                      float32   `json:"instant_power"`
	InstantReactivePower              float32   `json:"instant_reactive_power"`
	InstantApparentPower              float32   `json:"instant_apparent_power"`
	Frequency                         float32   `json:"frequency"`
	EnergyExported                    float32   `json:"energy_exported"`
	EnergyImported                    float32   `json:"energy_imported"`
	InstantAverageVoltage             float32   `json:"instant_average_voltage"`
	InstantAverageCurrent             float32   `json:"instant_average_current"`
	IACurrent                         float32   `json:"i_a_current"`
	IBCurrent                         float32   `json:"i_b_current"`
	ICCurrent                         float32   `json:"i_c_current"`
	LastPhaseVoltageCommunicationTime time.Time `json:"last_phase_voltage_communication_time"`
	LastPhasePowerCommunicationTime   time.Time `json:"last_phase_power_communication_time"`
	Timeout                           int       `json:"timeout"`
	NumMetersAggregated               int       `json:"num_meters_aggregated"`
	InstantTotalCurrent               float32   `json:"instant_total_current"`
}

MeterAggregatesData contains fields returned by the "meters/aggregates" API call. This reflects statistics collected across all of the meters in a given category (e.g. "site", "solar", "battery", "load", etc).

This structure is returned by the GetMetersAggregates function.

type MeterData

type MeterData struct {
	ID         int    `json:"id"`
	Location   string `json:"location"`
	Type       string `json:"type"`
	Cts        []bool `json:"cts"`
	Inverted   []bool `json:"inverted"`
	Connection struct {
		ShortID      string `json:"short_id"`
		DeviceSerial string `json:"device_serial"`
		HTTPSConf    struct {
			ClientCert          string `json:"client_cert"`
			ClientKey           string `json:"client_key"`
			ServerCaCert        string `json:"server_ca_cert"`
			MaxIdleConnsPerHost int    `json:"max_idle_conns_per_host"`
		} `json:"https_conf"`
	} `json:"connection"`
	RealPowerScaleFactor float32 `json:"real_power_scale_factor"`
	CachedReadings       struct {
		LastCommunicationTime             time.Time `json:"last_communication_time"`
		InstantPower                      float32   `json:"instant_power"`
		InstantReactivePower              float32   `json:"instant_reactive_power"`
		InstantApparentPower              float32   `json:"instant_apparent_power"`
		Frequency                         float32   `json:"frequency"`
		EnergyExported                    float32   `json:"energy_exported"`
		EnergyImported                    float32   `json:"energy_imported"`
		InstantAverageVoltage             float32   `json:"instant_average_voltage"`
		InstantAverageCurrent             float32   `json:"instant_average_current"`
		IACurrent                         float32   `json:"i_a_current"`
		IBCurrent                         float32   `json:"i_b_current"`
		ICCurrent                         float32   `json:"i_c_current"`
		VL1N                              float32   `json:"v_l1n"`
		VL2N                              float32   `json:"v_l2n"`
		LastPhaseVoltageCommunicationTime time.Time `json:"last_phase_voltage_communication_time"`
		RealPowerA                        float32   `json:"real_power_a"`
		RealPowerB                        float32   `json:"real_power_b"`
		ReactivePowerA                    float32   `json:"reactive_power_a"`
		ReactivePowerB                    float32   `json:"reactive_power_b"`
		LastPhasePowerCommunicationTime   time.Time `json:"last_phase_power_communication_time"`
		SerialNumber                      string    `json:"serial_number"`
		Timeout                           int       `json:"timeout"`
		InstantTotalCurrent               float32   `json:"instant_total_current"`
	} `json:"Cached_readings"`
	CtVoltageReferences struct {
		Ct1 string `json:"ct1"`
		Ct2 string `json:"ct2"`
		Ct3 string `json:"ct3"`
	} `json:"ct_voltage_references"`
}

MeterData contains fields returned by the "meters/<category>" API call, which returns information for each individual meter within that category.

A list of this structure is returned by the GetMeters function.

type NetworkData

type NetworkData struct {
	NetworkName string `json:"network_name"`
	Interface   string `json:"interface"`
	Dhcp        bool   `json:"dhcp"`
	Enabled     bool   `json:"enabled"`
	ExtraIps    []struct {
		IP      string `json:"ip"`
		Netmask int    `json:"netmask"`
	} `json:"extra_ips,omitempty"`
	Active                bool `json:"active"`
	Primary               bool `json:"primary"`
	LastTeslaConnected    bool `json:"lastTeslaConnected"`
	LastInternetConnected bool `json:"lastInternetConnected"`
	IfaceNetworkInfo      struct {
		NetworkName string `json:"network_name"`
		IPNetworks  []struct {
			IP   string `json:"ip"`
			Mask string `json:"mask"`
		} `json:"ip_networks"`
		Gateway        string `json:"gateway"`
		Interface      string `json:"interface"`
		State          string `json:"state"`
		StateReason    string `json:"state_reason"`
		SignalStrength int    `json:"signal_strength"`
		HwAddress      string `json:"hw_address"`
	} `json:"iface_network_info"`
	SecurityType string `json:"security_type"`
	Username     string `json:"username"`
}

NetworkData contains information returned by the "networks" API call for a particular network interface.

A list of this structure is returned by the GetNetworks function.

type NonIsoTime

type NonIsoTime struct {
	time.Time
}

Most time values in the API are produced in standard ISO-8601 format, which works just fine for unmarshalling to time.Time as well. However, the "start_time" field of the status API call is not returned in this format for some reason and thus will not unmarshal directly to a time.Time value. We provide a custom type to handle this case.

func (*NonIsoTime) UnmarshalJSON

func (v *NonIsoTime) UnmarshalJSON(p []byte) error

type OperationData

type OperationData struct {
	RealMode                string  `json:"real_mode"`
	BackupReservePercent    float32 `json:"backup_reserve_percent"`
	FreqShiftLoadShedSoe    float32 `json:"freq_shift_load_shed_soe"`
	FreqShiftLoadShedDeltaF float64 `json:"freq_shift_load_shed_delta_f"`
}

OperationData contains fields returned by the "operation" API call.

This structure is returned by the GetOperation function.

type SOEData

type SOEData struct {
	Percentage float32 `json:"percentage"`
}

SOEData contains fields returned by the "system_status/soe" API call. This currently just returns a single "Percentage" field, indicating the total amount of charge across all batteries.

This structure is returned by the GetSOE function.

type SiteInfoData

type SiteInfoData struct {
	SiteName               string  `json:"site_name"`
	TimeZone               string  `json:"timezone"`
	MaxSiteMeterPowerKW    int     `json:"max_site_meter_power_kW"`
	MinSiteMeterPowerKW    int     `json:"min_site_meter_power_kW"`
	MeasuredFrequency      float32 `json:"measured_frequency"`
	MaxSystemEnergyKWH     float32 `json:"max_system_energy_kWh"`
	MaxSystemPowerKW       float32 `json:"max_system_power_kW"`
	NominalSystemEnergyKWH float32 `json:"nominal_system_energy_kWh"`
	NominalSystemPowerKW   float32 `json:"nominal_system_power_kW"`
	GridData               struct {
		GridCode           string `json:"grid_code"`
		GridVoltageSetting int    `json:"grid_voltage_setting"`
		GridFreqSetting    int    `json:"grid_freq_setting"`
		GridPhaseSetting   string `json:"grid_phase_setting"`
		Country            string `json:"country"`
		State              string `json:"state"`
		Distributor        string `json:"distributor"`
		Utility            string `json:"utility"`
		Retailer           string `json:"retailer"`
		Region             string `json:"region"`
	} `json:"grid_code"`
}

SiteInfoData contains information returned by the "site_info" API call.

This structure is returned by the GetSiteInfo function.

type SitemasterData

type SitemasterData struct {
	Status           string `json:"status"`
	Running          bool   `json:"running"`
	ConnectedToTesla bool   `json:"connected_to_tesla"`
	PowerSupplyMode  bool   `json:"power_supply_mode"`
	CanReboot        string `json:"can_reboot"`
}

SitemasterData contains information returned by the "sitemaster" API call.

The CanReboot field indicates whether the sitemaster can be stopped/restarted without disrupting anything or not. It will be either "Yes", or it will be a string indicating the reason why it can't be stopped right now (such as "Power flow is too high"). (see the SitemasterReboot* constants for known possible values)

Note that it is still possible to stop the sitemaster even under these conditions, but it is necessary to set the "force" option to true when calling the "sitemaster/stop" API in that case.

This structure is returned by the GetSitemaster function.

type StatusData

type StatusData struct {
	Din              string      `json:"din"`
	StartTime        NonIsoTime  `json:"start_time"`
	UpTime           Duration    `json:"up_time_seconds"`
	IsNew            bool        `json:"is_new"`
	Version          string      `json:"version"`
	GitHash          string      `json:"git_hash"`
	CommissionCount  int         `json:"commission_count"`
	DeviceType       string      `json:"device_type"`
	SyncType         string      `json:"sync_type"`
	Leader           string      `json:"leader"`
	Followers        interface{} `json:"followers"` // TODO: Unsure what type this returns when present
	CellularDisabled bool        `json:"cellular_disabled"`
}

StatusData contains general system information returned by the "status" API call, such as the device identification number, type, software version, etc.

This structure is returned by the GetStatus function.

type SystemStatusData

type SystemStatusData struct {
	CommandSource                  string  `json:"command_source"`
	BatteryTargetPower             float32 `json:"battery_target_power"`
	BatteryTargetReactivePower     float32 `json:"battery_target_reactive_power"`
	NominalFullPackEnergy          float32 `json:"nominal_full_pack_energy"`
	NominalEnergyRemaining         float32 `json:"nominal_energy_remaining"`
	MaxPowerEnergyRemaining        float32 `json:"max_power_energy_remaining"`
	MaxPowerEnergyToBeCharged      float32 `json:"max_power_energy_to_be_charged"`
	MaxChargePower                 float32 `json:"max_charge_power"`
	MaxDischargePower              float32 `json:"max_discharge_power"`
	MaxApparentPower               float32 `json:"max_apparent_power"`
	InstantaneousMaxDischargePower float32 `json:"instantaneous_max_discharge_power"`
	InstantaneousMaxChargePower    float32 `json:"instantaneous_max_charge_power"`
	GridServicesPower              float32 `json:"grid_services_power"`
	SystemIslandState              string  `json:"system_island_state"`
	AvailableBlocks                int     `json:"available_blocks"`
	BatteryBlocks                  []struct {
		Type                   string        `json:"Type"`
		PackagePartNumber      string        `json:"PackagePartNumber"`
		PackageSerialNumber    string        `json:"PackageSerialNumber"`
		DisabledReasons        []interface{} `json:"disabled_reasons"` // TODO: Unclear what type these entries are when present.
		PinvState              string        `json:"pinv_state"`
		PinvGridState          string        `json:"pinv_grid_state"`
		NominalEnergyRemaining float32       `json:"nominal_energy_remaining"`
		NominalFullPackEnergy  float32       `json:"nominal_full_pack_energy"`
		POut                   float32       `json:"p_out"`
		QOut                   float32       `json:"q_out"`
		VOut                   float32       `json:"v_out"`
		FOut                   float32       `json:"f_out"`
		IOut                   float32       `json:"i_out"`
		EnergyCharged          float32       `json:"energy_charged"`
		EnergyDischarged       float32       `json:"energy_discharged"`
		OffGrid                bool          `json:"off_grid"`
		VfMode                 bool          `json:"vf_mode"`
		WobbleDetected         bool          `json:"wobble_detected"`
		ChargePowerClamped     bool          `json:"charge_power_clamped"`
		BackupReady            bool          `json:"backup_ready"`
		OpSeqState             string        `json:"OpSeqState"`
		Version                string        `json:"version"`
	} `json:"battery_blocks"`
	FfrPowerAvailabilityHigh   float32         `json:"ffr_power_availability_high"`
	FfrPowerAvailabilityLow    float32         `json:"ffr_power_availability_low"`
	LoadChargeConstraint       float32         `json:"load_charge_constraint"`
	MaxSustainedRampRate       float32         `json:"max_sustained_ramp_rate"`
	GridFaults                 []GridFaultData `json:"grid_faults"`
	CanReboot                  string          `json:"can_reboot"`
	SmartInvDeltaP             float32         `json:"smart_inv_delta_p"`
	SmartInvDeltaQ             float32         `json:"smart_inv_delta_q"`
	LastToggleTimestamp        time.Time       `json:"last_toggle_timestamp"`
	SolarRealPowerLimit        float64         `json:"solar_real_power_limit"`
	Score                      float32         `json:"score"`
	BlocksControlled           int             `json:"blocks_controlled"`
	Primary                    bool            `json:"primary"`
	AuxiliaryLoad              float32         `json:"auxiliary_load"`
	AllEnableLinesHigh         bool            `json:"all_enable_lines_high"`
	InverterNominalUsablePower float32         `json:"inverter_nominal_usable_power"`
	ExpectedEnergyRemaining    float32         `json:"expected_energy_remaining"`
}

SystemStatusData contains fields returned by the "system_status" API call. This contains a lot of information about the general state of the system and how it is operating, such as battery charge, utility power status, etc.

This structure is returned by the GetSystemStatus function.

type TroubleshootingProblemsData

type TroubleshootingProblemsData struct {
	Problems []interface{} `json:"problems"` // TODO: Unsure what type these values are when present
}

TroubleshootingProblemsData contains info returned by the "troubleshooting/problems" API call.

The format of the entries in the Problems list is currently unknown. If you have any examples, please let us know!

This structure is returned by the GetProblems function.

Jump to

Keyboard shortcuts

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