openevse

package module
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Sep 8, 2026 License: MIT Imports: 15 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

go-openevse

Go client for the OpenEVSE WiFi firmware (4.1.9 or later).

  • State is received over the firmware's /ws websocket: the full status document on connect, then diffs with only the changed keys. The client merges them into one Status and reconnects with backoff if the connection drops.
  • Control goes through the firmware's claims API (POST/DELETE /claims/{client}) at the firmware's fixed API priority (500). The charger's own manual override, RFID, OCPP and limits win over the client; the client wins over the built-in solar divert, schedules and boost. The claim is re-asserted after a reconnect (a firmware reboot clears claims) and deleted on Close.
  • Optional 1p/3p phase switching for modified three-phase controllers that answer the $G7/$S7 RAPI commands. Stock OpenEVSE controllers do not.
c, err := openevse.New("http://openevse.local",
	openevse.WithHTTPClient(httpClient), // carries basic auth, if any
	openevse.WithLogger(logger),
)
if err != nil {
	return err
}

if err := c.Connect(ctx); err != nil { // waits for the first status frame
	return err
}
defer c.Close() // releases the claim

status, err := c.Status()  // ErrNotConnected while the websocket is down
err = c.SetCurrent(16)     // A
err = c.Enable(true)

info := c.Info()           // /config: WiFi firmware version, controller firmware, build, hostname
claims, err := c.Claims()  // every claim on the charger; claims[i].Name() names the holder

Connect reads /config first and fails with ErrFirmwareTooOld on WiFi firmware older than 4.1.9, so users get told why instead of a silent timeout. Development builds without a version number (master_abc123) are not checked.

Options: WithHTTPClient, WithLogger, WithClientID, WithStatusHandler (called with every merged frame), and WithPingInterval, WithReadTimeout, WithReadyTimeout, WithStableAfter for the timings.

The default client id is 262145 (vendor 0x0004 = evcc, client 0x0001), registered as EvseClient_evcc in the firmware. Other projects should use their own id (WithClientID) so they do not fight evcc for the same claim slot. A leftover claim after an unclean shutdown is removed with DeleteClaim, or DELETE /claims/<id>.

When a claim is written while the charger's manual override is active, one warning is logged naming every claim that outranks this client, for example outranked by manual override (priority 1000), limit (priority 1100).

CLI

go install github.com/OpenEVSE/go-openevse/cmd/openevse@latest

openevse -uri http://openevse.local [-user u -password p] status   # /config and current status
openevse ... watch                                                  # print every status change
openevse ... claims                                                 # list claims and who holds them
openevse ... claim -current 16 -enable                              # write a claim (persists after exit)
openevse ... release                                                # delete the claim
openevse ... rapi '$GV'                                             # raw RAPI command

OPENEVSE_URI, OPENEVSE_USER and OPENEVSE_PASSWORD are read as defaults.

Tests run against a fake firmware; go test -race ./....

Documentation

Overview

Package openevse is a client for the OpenEVSE WiFi firmware (4.1.9 or later).

State is received over the firmware's /ws websocket: the full status document on connect, then partial documents with only the changed keys. Control goes through the firmware's claims API (POST/DELETE /claims/{client}) at the firmware's fixed API priority, so the charger's own manual override, RFID, OCPP and limits still win while the client wins over the built-in solar divert and schedules.

Index

Constants

View Source
const (
	Enabled  = "active"
	Disabled = "disabled"
)

Claim states

View Source
const (
	// DefaultPingInterval is the keepalive interval. The firmware answers {"ping":1}
	// with {"pong":1}, so a healthy connection delivers a frame at least this often.
	DefaultPingInterval = 30 * time.Second

	// DefaultReadTimeout bounds every read. Without it a half-open TCP connection
	// blocks the reader forever while the charger keeps reporting stale state.
	DefaultReadTimeout = 2*DefaultPingInterval + 15*time.Second

	// DefaultReadyTimeout is how long Connect waits for the first status frame.
	DefaultReadyTimeout = 10 * time.Second

	// DefaultStableAfter is how long a connection must deliver state before a
	// drop counts as a fresh failure (reset backoff) rather than flapping (grow it).
	DefaultStableAfter = time.Minute

	// MaxBackoff is the longest wait between reconnect attempts.
	MaxBackoff = 30 * time.Second
)

Defaults

View Source
const ClientID = 0x00040001

ClientID is the default claim client id: vendor 0x0004 (evcc), client 0x0001, registered as EvseClient_evcc in the firmware's src/evse_man.h. Other projects should pick their own id with WithClientID so they do not fight evcc for the same claim slot.

View Source
const ManualOverrideWarning = "" /* 134-byte string literal not displayed */

ManualOverrideWarning is logged once when a claim is written while the charger's manual override is active; it repeats only after the override has been observed inactive in between. When the claim list can be read the warning also names every claim outranking this client.

View Source
const MinVersion = "4.1.9"

MinVersion is the oldest WiFi firmware Connect accepts: /ws, /claims and the power and energy keys used here all exist from 4.1.9 on.

View Source
const PhaseSwitchWarning = "" /* 163-byte string literal not displayed */

PhaseSwitchWarning is logged when phase switching is enabled.

View Source
const Priority = 500

Priority is the firmware's fixed priority for claims written through the API (EvseManager_Priority_API). Manual override (1000), RFID (1030), OCPP (1050) and limits (1100) outrank it; divert (50), timers (100) and boost (200) do not.

Variables

View Source
var (
	// ErrNotConnected is returned by Status while the websocket is down.
	ErrNotConnected = errors.New("websocket not connected")

	// ErrTimeout is returned by Connect when no status frame arrived in time.
	ErrTimeout = errors.New("timeout waiting for status")

	// ErrFirmwareTooOld is returned by Connect when the WiFi firmware is older than MinVersion.
	ErrFirmwareTooOld = errors.New("wifi firmware too old")
)

Functions

func ClientName

func ClientName(id uint32) string

ClientName names a claim client id: the firmware's built-in clients by function, anything else by id.

Types

type Claim

type Claim struct {
	State         string `json:"state"`                    // active or disabled
	ChargeCurrent int    `json:"charge_current,omitempty"` // A, 0 = not set
}

Claim is the body of POST /claims/{client}

type ClaimInfo

type ClaimInfo struct {
	Client        uint32 `json:"client"`
	Priority      int    `json:"priority"`
	State         string `json:"state,omitempty"`
	ChargeCurrent int    `json:"charge_current,omitempty"` // A
	MaxCurrent    int    `json:"max_current,omitempty"`    // A
	EnergyLimit   int    `json:"energy_limit,omitempty"`   // Wh
	TimeLimit     int    `json:"time_limit,omitempty"`     // s
	AutoRelease   bool   `json:"auto_release"`
}

ClaimInfo is one entry of GET /claims

func (ClaimInfo) Name

func (c ClaimInfo) Name() string

Name is the claim holder's name, see ClientName

type Client

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

Client talks to one charger. Create it with New and start it with Connect.

func New

func New(uri string, opts ...Option) (*Client, error)

New creates a client for the charger at uri (host, or http(s)://host[/path]). It does not connect; call Connect.

func (*Client) Claims

func (c *Client) Claims() ([]ClaimInfo, error)

Claims lists every claim on the charger (GET /claims)

func (*Client) Close

func (c *Client) Close()

Close stops the websocket reader and releases the claim so the charger falls back to its own defaults. It returns once the claim has been deleted (or the delete has failed) and is safe to call more than once.

func (*Client) Connect

func (c *Client) Connect(ctx context.Context) error

Connect reads /config, rejects WiFi firmware older than MinVersion, then starts the websocket reader, which keeps reconnecting with backoff until ctx is cancelled or Close is called, and waits for the first status frame. A wrong host, wrong password or a firmware without the push channel fails here instead of silently never delivering state. Cancelling ctx later stops the reader and releases the claim, same as Close.

func (*Client) Connected

func (c *Client) Connected() bool

Connected reports whether the websocket is up and Status is readable

func (*Client) DeleteClaim

func (c *Client) DeleteClaim() error

DeleteClaim deletes this client's claim on the charger even if it was written by another process, for example a leftover from an unclean shutdown.

func (*Client) Enable

func (c *Client) Enable(enable bool) error

Enable sets the claim's charging state and writes the claim

func (*Client) EnablePhaseSwitching

func (c *Client) EnablePhaseSwitching() error

EnablePhaseSwitching prepares a modified three-phase controller for SetThreePhase: it verifies that the controller answers $G7 and disables the controller's own 1p/3p auto-switching with $S8 0. Stock OpenEVSE controllers answer $NK to $G7, and WiFi firmware builds without ENABLE_FULL_RAPI (Ethernet, TFT) block the $S8 write; both are reported as errors.

func (*Client) Info

func (c *Client) Info() Info

Info returns the /config properties read by Connect

func (*Client) RAPI

func (c *Client) RAPI(command string) (string, error)

RAPI sends a raw RAPI command through the firmware's /r endpoint and returns the controller's answer. It fails if the WiFi firmware blocks the command (builds without ENABLE_FULL_RAPI answer 400 to anything but $G reads) or the controller does not acknowledge it with $OK.

func (*Client) ReleaseClaim

func (c *Client) ReleaseClaim() error

ReleaseClaim deletes the claim so the charger falls back to its own defaults. It does nothing if no claim has been written since the last release.

func (*Client) SetCurrent

func (c *Client) SetCurrent(current int) error

SetCurrent sets the claim's charge current in A and writes the claim

func (*Client) SetThreePhase

func (c *Client) SetThreePhase(threePhase bool) error

SetThreePhase switches a modified three-phase controller between one and three phases with $S7. Call EnablePhaseSwitching first.

func (*Client) Status

func (c *Client) Status() (Status, error)

Status returns the last received status, or ErrNotConnected while the websocket is down

type Info

type Info struct {
	Version    string `json:"version"`     // WiFi firmware, e.g. 5.1.5 or master_cc434801 for development builds
	Firmware   string `json:"firmware"`    // controller (open_evse) firmware, e.g. 8.2.3
	BuildEnv   string `json:"buildenv"`    // e.g. openevse_wifi_v1
	Hostname   string `json:"hostname"`    // mDNS name
	WifiSerial string `json:"wifi_serial"` // serial of the WiFi module
}

Info keeps the interesting properties of the /config document

type Logger

type Logger interface {
	Tracef(format string, args ...any)
	Debugf(format string, args ...any)
	Warnf(format string, args ...any)
	Errorf(format string, args ...any)
}

Logger receives the client's log output. All methods are Printf-style.

type Option

type Option func(*Client)

Option configures a Client

func WithClientID

func WithClientID(id uint32) Option

WithClientID sets the claim client id (default ClientID). Register new ids with the firmware project; vendor 0xFFFE is reserved for unregistered use.

func WithHTTPClient

func WithHTTPClient(hc *http.Client) Option

WithHTTPClient sets the http client used for the websocket handshake, claims and RAPI requests. Use it to add basic auth or logging through a transport.

func WithLogger

func WithLogger(log Logger) Option

WithLogger sets the logger; the default discards all output.

func WithPingInterval

func WithPingInterval(d time.Duration) Option

WithPingInterval sets the keepalive interval (see DefaultPingInterval)

func WithReadTimeout

func WithReadTimeout(d time.Duration) Option

WithReadTimeout sets the per-read deadline (see DefaultReadTimeout)

func WithReadyTimeout

func WithReadyTimeout(d time.Duration) Option

WithReadyTimeout sets how long Connect waits for the first frame (see DefaultReadyTimeout)

func WithStableAfter

func WithStableAfter(d time.Duration) Option

WithStableAfter sets the stability window (see DefaultStableAfter)

func WithStatusHandler

func WithStatusHandler(fn func(Status)) Option

WithStatusHandler installs a callback that receives every merged status frame. It runs on the reader goroutine, so it must return quickly.

type Status

type Status struct {
	Amp           float64 `json:"amp"`            // charge current in mA
	Voltage       float64 `json:"voltage"`        // V
	Power         float64 `json:"power"`          // W, honours the firmware's is_threephase setting
	Pilot         float64 `json:"pilot"`          // pilot current in A
	Elapsed       float64 `json:"elapsed"`        // session duration in seconds
	SessionEnergy float64 `json:"session_energy"` // Wh
	TotalEnergy   float64 `json:"total_energy"`   // kWh
	State         int     `json:"state"`          // 1=A 2=B 3=C 4=D 5-11=F 254=sleeping 255=disabled
	Status        string  `json:"status"`         // active, disabled, none, unknown
	Vehicle       int     `json:"vehicle"`        // 0=not connected, 1=connected
	// ManualOverride is 1 when the firmware's manual override claim (priority 1000,
	// set by the charger's own UI/button) is active. It outranks this client's
	// claim (priority 500), so claim writes have no effect until it is cleared.
	ManualOverride int `json:"manual_override"`
	// RfidAuth is the RFID tag uid that authorised the current session, present
	// only when RFID is enabled on the charger. It is empty when no card has
	// authorised the session.
	RfidAuth string `json:"rfid_auth"`
}

Status keeps the interesting properties of the /status document. The /ws endpoint sends the full document on connect and afterwards only the changed keys, so frames are merged into one Status by json.Unmarshal.

Directories

Path Synopsis
cmd
openevse command
Command openevse is a small diagnostic tool for the OpenEVSE WiFi firmware.
Command openevse is a small diagnostic tool for the OpenEVSE WiFi firmware.

Jump to

Keyboard shortcuts

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