diff --git a/README.md b/README.md index 017880b67..a763f6f1a 100644 --- a/README.md +++ b/README.md @@ -2,41 +2,50 @@ [![Build Status](https://travis-ci.org/andig/evcc.svg?branch=master)](https://travis-ci.org/andig/evcc) -EVCC is an EV Charge Controller implemented in [Go](2). It comes with a bundled implementation for Wallbe chargers but supports any type of charger or meter through scripting and integration with MQTT. +EVCC is an extensible EV Charge Controller with PV integration implemented in [Go](2). -Features: +### Features -- support for Wallbe chargers -- support for any charger, meter or EV using scripting +- simple and clean user interface +- support for multiple chargers: + - Wallbe (tested with Wallbe Eco S) + - Phoenix (similar to Wallbe) + - NRGKick (experimental) + - Go-E (experimental) + - SimpleEVSE (experimental) + - any other charger using scripting +- notifications using [Telegram](https://telegram.org) and [PushOver](https://pushover.net) - integration with home automation - supports shell scripts and MQTT -- soft ramp-up/ramp-down of charge current +- logging using [InfluxDB](https://www.influxdata.com) +- soft ramp-up/ramp-down of charge current ensures contactor only switched at minimum current - electric contactor protection -- clean, non-bloat user interface +- REST API ![Screenshot](docs/screenshot.png) -**NOTE:** You are using this software **entirely** at your own risk. It is your responsibility to verify it is working as intended. - -## Background +### Background EVCC is heavily inspired by [OpenWB](1). However, I found OpenWB's architecture slightly intimidating with everything basically global state and heavily relying on shell scripting. On the other side, especially the scripting aspect is one that contributes to [OpenWB's](1) flexibility. Hence, for a simplified and stricter implementation of an EV charge controller, the design goals for EVCC were: - typed language with ability for systematic testing - achieved by using [Go](2) -- structured cnofiguration - supports YAML-based [config file](evcc.dist.yaml) +- structured configuration - supports YAML-based [config file](evcc.dist.yaml) - avoidance of feature bloat, simple and clean UI - utilizes [Bootstrap](3) -- containerized operation beyond Raspbery Pi - provide multi-arch [Docker Image](4) +- containerized operation beyond Raspberry Pi - provide multi-arch [Docker Image](4) - support for multiple load points - tbd +### Note + +EVCC comes without any guarantee. You are using this software **entirely** at your own risk. It is your responsibility to verify it is working as intended. +EVCC requires a supported charger and a combination of grid, PV and charge meter. +Charger and meters **must** be installed by a certified professional. + ## Installation ### Hardware -EVCC requires a supported charger and a combination of grid, PV and charge meter. -Charger and meters MUST be professionally installed. - -#### Wallbe Charger +#### Wallbe and Phoenix Chargers Wallbe chargers are supported out of the box. The Wallbe must be connected using Ethernet. If not configured, the default address `192.168.0.8:502` is used. @@ -46,6 +55,10 @@ To allow controlling charge start/stop, the Wallbe physical configuration must b More information on interacting with Wallbe chargers can be found at [GoingElectric](https://www.goingelectric.de/forum/viewtopic.php?p=1212583). Use with care. +#### NRGKick + +NRGKick is supported with additional NRGConnect for interfacing. + ### Software The preferred way of running EVCC is using the docker image: @@ -87,13 +100,9 @@ For both PV modes, EVCC needs to assess how much residual PV power is available The *Residual Power* is a configurable assumption how much power remaining facilities beside the charger use. -- **Grid meter**: Configuring a *grid meter* is the preferred option. The *grid meter* is expected to be a two-way meter (import+export) and return the current amount of grid export as negative value measured in kWh. The charger is then allowed to consume: +- **Grid meter**: Configuring a *grid meter* is the preferred option. The *grid meter* is expected to be a two-way meter (import+export) and return the current amount of grid export as negative value measured in Watt (W). The charger is then allowed to consume: - Δ Charge Power = Grid Meter Power - Residual Power - - rounded down and capped at zero and - - Charge Power = Current Charge Power + Δ Charge Power + Charge Power = Current Charge Power - Grid Meter Power - Residual Power In this setup, *residual power* is used as margin to account for fluctuations in PV production that may be faster than EVCC's control loop. @@ -101,7 +110,7 @@ For both PV modes, EVCC needs to assess how much residual PV power is available When using a *grid meter* for accurate control of PV utilization, EVCC needs to be able to determine the current charge power. There are two configurations for determining the *current charge power*: -- **Charge meter**: A *charge meter* is often integrated into the charger but can also be installed separately. EVCC expects the *charge meter* to supply *charge power* and preferably also *total energy*. +- **Charge meter**: A *charge meter* is often integrated into the charger but can also be installed separately. EVCC expects the *charge meter* to supply *charge power* in Watt (W) and preferably *total energy* in kWh. If *total energy* is supplied, it can be used to calculate the *charged energy* for the current charging cycle. - **No charge meter**: If no charge meter is installed, *charge power* is deducted from *charge current* as controlled by the charger. This method is less accurate than using a *charge meter* since the EV may chose to use less power than EVCC has allowed for consumption. @@ -109,14 +118,14 @@ If the charger supplies *total energy* for the charging cycle this value is pref ## Implementation -EVCC consists of four basic elements: *Charger*, *Meter*, *SoC* and *Loadpoint*. Their APIs are decribed in [api/api.go](https://github.com/andig/evcc/blob/master/api/api.go) +EVCC consists of four basic elements: *Charger*, *Meter*, *SoC* and *Loadpoint*. Their APIs are described in [api/api.go](https://github.com/andig/evcc/blob/master/api/api.go) ### Charger -Charger is reponsible for EV state handling: +Charger is responsible for EV state handling: - `Status()`: get charge controller status (`A...F`) -- `Enabled()`: get charger availablity +- `Enabled()`: get charger availability - `Enable()`: set charger availability - `MaxCurrent()`: set maximum allowed charge current in A @@ -132,7 +141,7 @@ Meters provide data about power and energy consumption: - `CurrentPower()`: power in W - `TotalEnergy()`: energy in kWh (optional) -Meter has a single implementaton where meter readings- power and energy- can be configured to be delivered by plugin. +Meter has a single implementation where meter readings- power and energy- can be configured to be delivered by plugin. ### SoC @@ -144,7 +153,7 @@ If SoC is configured and assigned to the charger, charge status and remaining ch ### Loadpoint -Loadpoint controls the Charger behaviour according to the operations mode- *off*, *now*, *PV + minimum* or *PV only*. +Loadpoint controls the Charger behavior according to the operations mode- *off*, *now*, *PV + minimum* or *PV only*. ## Plugins diff --git a/charger/charger.go b/charger/charger.go index ddbb280bc..72afb9a0b 100644 --- a/charger/charger.go +++ b/charger/charger.go @@ -13,12 +13,12 @@ type Charger struct { maxCurrentS provider.IntSetter } -// NewChargerFromConfig creates a new configurable charger -func NewChargerFromConfig(log *api.Logger, other map[string]interface{}) api.Charger { +// NewConfigurableFromConfig creates a new configurable charger +func NewConfigurableFromConfig(log *api.Logger, other map[string]interface{}) api.Charger { cc := struct{ Status, Enable, Enabled, MaxCurrent *provider.Config }{} decodeOther(log, other, &cc) - charger := NewCharger( + charger := NewConfigurable( provider.NewStringGetterFromConfig(cc.Status), provider.NewBoolGetterFromConfig(cc.Enabled), provider.NewBoolSetterFromConfig("enable", cc.Enable), @@ -28,8 +28,8 @@ func NewChargerFromConfig(log *api.Logger, other map[string]interface{}) api.Cha return charger } -// NewCharger creates a new charger -func NewCharger( +// NewConfigurable creates a new charger +func NewConfigurable( statusG provider.StringGetter, enabledG provider.BoolGetter, enableS provider.BoolSetter, diff --git a/charger/config.go b/charger/config.go new file mode 100644 index 000000000..92c9ad665 --- /dev/null +++ b/charger/config.go @@ -0,0 +1,79 @@ +package charger + +import ( + "bytes" + "encoding/json" + "fmt" + "io/ioutil" + "net/http" + + "github.com/andig/evcc/api" +) + +type apiFunction string + +// NewFromConfig creates charger from configuration +func NewFromConfig(log *api.Logger, typ string, other map[string]interface{}) api.Charger { + var c api.Charger + + switch typ { + case "wallbe": + c = NewWallbeFromConfig(log, other) + case "phoenix": + c = NewPhoenixFromConfig(log, other) + case "nrgkick", "nrg", "kick": + c = NewNRGKickFromConfig(log, other) + case "go-e", "goe": + c = NewGoEFromConfig(log, other) + case "simpleevse", "evse": + c = NewSimpleEVSEFromConfig(log, other) + case "default", "configurable": + c = NewConfigurableFromConfig(log, other) + default: + log.FATAL.Fatalf("invalid charger type '%s'", typ) + } + + return c +} + +func getJSON(url string, result interface{}) (*http.Response, []byte, error) { + resp, err := http.Get(url) + if err != nil { + return resp, []byte{}, err + } + defer resp.Body.Close() + + body, err := ioutil.ReadAll(resp.Body) + if err != nil { + return resp, body, err + } + + if resp.StatusCode == http.StatusOK { + err = json.Unmarshal(body, &result) + return resp, body, err + } + + return resp, body, fmt.Errorf("unexpected status %d", resp.StatusCode) +} + +func putJSON(url string, request interface{}) (*http.Response, []byte, error) { + data, err := json.Marshal(request) + if err != nil { + return nil, []byte{}, err + } + + client := &http.Client{} + req, err := http.NewRequest(http.MethodPut, url, bytes.NewBuffer(data)) + if err != nil { + return nil, []byte{}, err + } + + resp, err := client.Do(req) + if err != nil { + return resp, []byte{}, err + } + defer resp.Body.Close() + + body, err := ioutil.ReadAll(resp.Body) + return resp, body, err +} diff --git a/charger/go-e.go b/charger/go-e.go new file mode 100644 index 000000000..abedcfc5a --- /dev/null +++ b/charger/go-e.go @@ -0,0 +1,140 @@ +package charger + +import ( + "encoding/json" + "fmt" + "strings" + + "github.com/andig/evcc/api" +) + +const ( + goeStatus apiFunction = "status" +) + +// goeStatusResponse is the API response if status not OK +type goeStatusResponse struct { + Car uint `yaml:"car"` // car status + Alw uint `yaml:"alw"` // allow charging + Amp uint `yaml:"amp"` // current [A] + Err uint `yaml:"err"` + Stp uint `yaml:"stp"` + Tmp uint `yaml:"tmp"` + Dws uint `yaml:"dws"` // energy [Ws] + Nrg []uint `yaml:"nrg"` // voltage, current, power +} + +// GoE charger implementation +type GoE struct { + log *api.Logger + URI string +} + +// NewGoEFromConfig creates a go-e charger from generic config +func NewGoEFromConfig(log *api.Logger, other map[string]interface{}) api.Charger { + cc := struct{ URI string }{} + decodeOther(log, other, &cc) + + return NewGoE(cc.URI) +} + +// NewGoE creates GoE charger +func NewGoE(URI string) *GoE { + c := &GoE{ + URI: URI, + log: api.NewLogger("go-e"), + } + + c.log.WARN.Println("-- experimental --") + + return c +} + +func (c *GoE) apiURL(api apiFunction) string { + return fmt.Sprintf("%s/%s", strings.TrimRight(c.URI, "/"), api) +} + +func (c *GoE) getJSON(url string, result interface{}) error { + resp, body, err := getJSON(url, result) + c.log.TRACE.Printf("GET %s: %s", url, string(body)) + + if err != nil && len(body) == 0 { + return err + } + + var error goeStatusResponse + _ = json.Unmarshal(body, &error) + + return fmt.Errorf("api %d: %d", resp.StatusCode, error.Err) +} + +// Status implements the Charger.Status interface +func (c *GoE) Status() (api.ChargeStatus, error) { + var status goeStatusResponse + err := c.getJSON(c.apiURL(goeStatus), status) + + switch status.Car { + case 1: + return api.StatusA, err + case 2: + return api.StatusC, err + case 3: + return api.StatusB, err + case 4: + return api.StatusB, err + } + + return api.StatusNone, fmt.Errorf("unknown result %d", status.Car) +} + +// Enabled implements the Charger.Enabled interface +func (c *GoE) Enabled() (bool, error) { + var status goeStatusResponse + err := c.getJSON(c.apiURL(goeStatus), status) + + switch status.Alw { + case 0: + return false, err + case 1: + return true, err + } + + return false, fmt.Errorf("unknown result %d", status.Alw) +} + +// Enable implements the Charger.Enable interface +func (c *GoE) Enable(enable bool) error { + var status goeStatusResponse + + uri := c.apiURL(goeStatus) + "/mqtt?alw=" + if enable { + uri += "1" + } else { + uri += "0" + } + + return c.getJSON(uri, status) +} + +// MaxCurrent implements the Charger.MaxCurrent interface +func (c *GoE) MaxCurrent(current int64) error { + var status goeStatusResponse + uri := fmt.Sprintf(c.apiURL(goeStatus)+"/mqtt?amp=%d", current) + return c.getJSON(uri, status) +} + +// CurrentPower implements the Meter interface. +func (c *GoE) CurrentPower() (float64, error) { + var status goeStatusResponse + err := c.getJSON(c.apiURL(goeStatus), status) + power := float64(status.Nrg[11]) * 10 + return power, err +} + +// ChargedEnergy implements the ChargeRater interface. +func (c *GoE) ChargedEnergy() (float64, error) { + var status goeStatusResponse + err := c.getJSON(c.apiURL(goeStatus), status) + energy := float64(status.Dws) / 3.6e6 + return energy, err +} diff --git a/charger/nrgkick.go b/charger/nrgkick.go new file mode 100644 index 000000000..b2671d1b9 --- /dev/null +++ b/charger/nrgkick.go @@ -0,0 +1,171 @@ +package charger + +import ( + "encoding/json" + "fmt" + "net/http" + + "github.com/andig/evcc/api" +) + +const ( + apiSettings apiFunction = "settings" + apiMeasurements apiFunction = "measurements" +) + +// NRGResponse is the API response if status not OK +type NRGResponse struct { + Message string +} + +// NRGMeasurements is the /api/measurements response +type NRGMeasurements struct { + ChargingEnergy float64 + ChargingPower float64 +} + +// NRGSettings is the /api/setings request/response +type NRGSettings struct { + Info NRGInfo `json:"omitempty"` + Values NRGValues +} + +// NRGInfo is NRGSettings.Info +type NRGInfo struct { + Connected bool `json:"omitempty"` +} + +// NRGValues is NRGSettings.Values +type NRGValues struct { + ChargingStatus NRGChargingStatus + ChargingCurrent NRGChargingCurrent + DeviceMetadata NRGDeviceMetadata +} + +// NRGChargingStatus is NRGSettings.Values.ChargingStatus +type NRGChargingStatus struct { + Charging *bool `json:"omitempty"` // use pointer to allow omitting false +} + +// NRGChargingCurrent is NRGSettings.Values.ChargingCurrent +type NRGChargingCurrent struct { + Value float64 `json:"omitempty"` +} + +// NRGDeviceMetadata is NRGSettings.Values.DeviceMetadata +type NRGDeviceMetadata struct { + Password string +} + +// NRGKick charger implementation +type NRGKick struct { + log *api.Logger + IP string + MacAddress string + Password string +} + +// NewNRGKickFromConfig creates a NRGKick charger from generic config +func NewNRGKickFromConfig(log *api.Logger, other map[string]interface{}) api.Charger { + cc := struct{ IP, MacAddress, Password string }{} + decodeOther(log, other, &cc) + + return NewNRGKick(cc.IP, cc.MacAddress, cc.Password) +} + +// NewNRGKick creates NRGKick charger +func NewNRGKick(IP, MacAddress, Password string) *NRGKick { + nrg := &NRGKick{ + IP: IP, + MacAddress: MacAddress, + Password: Password, + log: api.NewLogger("kick"), + } + + nrg.log.WARN.Println("-- experimental --") + + return nrg +} + +func (nrg *NRGKick) apiURL(api apiFunction) string { + return fmt.Sprintf("%s/api/%s/%s", nrg.IP, api, nrg.MacAddress) +} + +func (nrg *NRGKick) getJSON(url string, result interface{}) error { + resp, body, err := getJSON(url, result) + nrg.log.TRACE.Printf("GET %s: %s", url, string(body)) + + if err != nil && len(body) == 0 { + return err + } + + var error NRGResponse + _ = json.Unmarshal(body, &error) + + return fmt.Errorf("api %d: %s", resp.StatusCode, error.Message) +} + +func (nrg *NRGKick) putJSON(url string, request interface{}) error { + resp, body, err := putJSON(url, request) + nrg.log.TRACE.Printf("PUT %v: %s", resp, string(body)) + + if err != nil && len(body) == 0 { + return err + } + + if resp.StatusCode == http.StatusOK || resp.StatusCode == http.StatusNoContent { + return nil + } + + var error NRGResponse + _ = json.Unmarshal(body, &error) + + return fmt.Errorf("api %d: %s", resp.StatusCode, error.Message) +} + +// Status implements the Charger.Status interface +func (nrg *NRGKick) Status() (api.ChargeStatus, error) { + return api.StatusC, nil +} + +// Enabled implements the Charger.Enabled interface +func (nrg *NRGKick) Enabled() (bool, error) { + var settings NRGSettings + err := nrg.getJSON(nrg.apiURL(apiSettings), settings) + + return *settings.Values.ChargingStatus.Charging, err +} + +// Enable implements the Charger.Enable interface +func (nrg *NRGKick) Enable(enable bool) error { + settings := NRGSettings{} + settings.Values.DeviceMetadata.Password = nrg.Password + settings.Values.ChargingStatus.Charging = &enable + + return nrg.putJSON(nrg.apiURL(apiSettings), settings) +} + +// MaxCurrent implements the Charger.MaxCurrent interface +func (nrg *NRGKick) MaxCurrent(current int64) error { + settings := NRGSettings{} + settings.Values.DeviceMetadata.Password = nrg.Password + settings.Values.ChargingCurrent.Value = float64(current) + + return nrg.putJSON(nrg.apiURL(apiSettings), settings) +} + +// CurrentPower implements the Meter interface. +func (nrg *NRGKick) CurrentPower() (float64, error) { + var measurements NRGMeasurements + err := nrg.getJSON(nrg.apiURL(apiMeasurements), measurements) + + return 1000 * measurements.ChargingPower, err +} + +// ChargedEnergy implements the ChargeRater interface. +func (nrg *NRGKick) ChargedEnergy() (float64, error) { + var measurements NRGMeasurements + err := nrg.getJSON(nrg.apiURL(apiMeasurements), measurements) + + return measurements.ChargingEnergy, err +} diff --git a/charger/phoenix.go b/charger/phoenix.go new file mode 100644 index 000000000..59855bc87 --- /dev/null +++ b/charger/phoenix.go @@ -0,0 +1,124 @@ +package charger + +import ( + "fmt" + "time" + + "github.com/andig/evcc/api" + "github.com/grid-x/modbus" +) + +const ( + phRegStatus = 100 // Input + phRegChargeTime = 102 // Input + phRegMaxCurrent = 300 // Holding + phRegEnable = 400 // Coil +) + +// Phoenix is an api.ChargeController implementation for Phoenix wallboxes. +// It uses Modbus TCP to communicate with the wallbox at modbus client id 255. +type Phoenix struct { + log *api.Logger + client modbus.Client + handler *modbus.TCPClientHandler +} + +// NewPhoenixFromConfig creates a Phoenix charger from generic config +func NewPhoenixFromConfig(log *api.Logger, other map[string]interface{}) api.Charger { + cc := struct{ URI string }{} + decodeOther(log, other, &cc) + + return NewPhoenix(cc.URI) +} + +// NewPhoenix creates a Phoenix charger +func NewPhoenix(conn string) api.Charger { + log := api.NewLogger("phoe") + if conn == "" { + log.FATAL.Fatal("missing connection") + } + + handler := modbus.NewTCPClientHandler(conn) + client := modbus.NewClient(handler) + + handler.SlaveID = slaveID + handler.Timeout = timeout + handler.ProtocolRecoveryTimeout = protocolTimeout + + wb := &Phoenix{ + log: log, + client: client, + handler: handler, + } + + return wb +} + +// Status implements the Charger.Status interface +func (wb *Phoenix) Status() (api.ChargeStatus, error) { + b, err := wb.client.ReadInputRegisters(phRegStatus, 1) + wb.log.TRACE.Printf("read status (%d): %0 X", phRegStatus, b) + if err != nil { + wb.handler.Close() + return api.StatusNone, err + } + + return api.ChargeStatus(string(b[1])), nil +} + +// Enabled implements the Charger.Enabled interface +func (wb *Phoenix) Enabled() (bool, error) { + b, err := wb.client.ReadCoils(phRegEnable, 1) + wb.log.TRACE.Printf("read charge enable (%d): %0 X", phRegEnable, b) + if err != nil { + wb.handler.Close() + return false, err + } + + return b[0] == 1, nil +} + +// Enable implements the Charger.Enable interface +func (wb *Phoenix) Enable(enable bool) error { + var u uint16 + if enable { + u = 0xFF00 + } + + b, err := wb.client.WriteSingleCoil(phRegEnable, u) + wb.log.TRACE.Printf("write charge enable %d %0X: %0 X", phRegEnable, u, b) + if err != nil { + wb.handler.Close() + } + + return err +} + +// MaxCurrent implements the Charger.MaxCurrent interface +func (wb *Phoenix) MaxCurrent(current int64) error { + if current < 6 { + return fmt.Errorf("invalid current %d", current) + } + + b, err := wb.client.WriteSingleRegister(phRegMaxCurrent, uint16(current)) + wb.log.TRACE.Printf("write max current %d %0X: %0 X", phRegMaxCurrent, current, b) + if err != nil { + wb.handler.Close() + } + + return err +} + +// ChargingTime yields current charge run duration +func (wb *Phoenix) ChargingTime() (time.Duration, error) { + b, err := wb.client.ReadInputRegisters(phRegChargeTime, 2) + wb.log.TRACE.Printf("read charge time (%d): %0 X", phRegChargeTime, b) + if err != nil { + wb.handler.Close() + return 0, err + } + + // 2 words, least significant word first + secs := uint64(b[3])<<16 | uint64(b[2])<<24 | uint64(b[1]) | uint64(b[0])<<8 + return time.Duration(time.Duration(secs) * time.Second), nil +} diff --git a/charger/simpleevse.go b/charger/simpleevse.go new file mode 100644 index 000000000..28600cf74 --- /dev/null +++ b/charger/simpleevse.go @@ -0,0 +1,141 @@ +package charger + +import ( + "errors" + "time" + + "github.com/andig/evcc/api" + "github.com/grid-x/modbus" +) + +// SimpleEVSE charger implementation +type SimpleEVSE struct { + log *api.Logger + client modbus.Client + handler modbus.ClientHandler +} + +const ( + evseRegAmpsConfig = 1000 + evseRegVehicleStatus = 1002 + evseRegTurnOff = 1004 +) + +// NewSimpleEVSEFromConfig creates a SimpleEVSE charger from generic config +func NewSimpleEVSEFromConfig(log *api.Logger, other map[string]interface{}) api.Charger { + cc := struct{ URI, Device string }{} + decodeOther(log, other, &cc) + + return NewSimpleEVSE(cc.URI, cc.Device) +} + +// NewSimpleEVSE creates SimpleEVSE charger +func NewSimpleEVSE(conn, device string) api.Charger { + log := api.NewLogger("evse") + + var handler modbus.ClientHandler + if conn != "" && device != "" { + log.FATAL.Fatal("cannot define uri and device both") + } + if conn != "" { + handler = modbus.NewTCPClientHandler(conn) + handler.(*modbus.TCPClientHandler).Timeout = time.Second + handler.(*modbus.TCPClientHandler).SlaveID = 1 + } + if device != "" { + handler = modbus.NewRTUClientHandler(device) + handler.(*modbus.RTUClientHandler).BaudRate = 9600 + handler.(*modbus.RTUClientHandler).DataBits = 8 + handler.(*modbus.RTUClientHandler).StopBits = 1 + handler.(*modbus.RTUClientHandler).Parity = "N" + handler.(*modbus.RTUClientHandler).Timeout = time.Second + handler.(*modbus.RTUClientHandler).SlaveID = 1 + } + if handler == nil { + log.FATAL.Fatal("most define either uri or device") + } + + evse := &SimpleEVSE{ + log: log, + client: modbus.NewClient(handler), + handler: handler, + } + + evse.log.WARN.Println("-- experimental --") + + return evse +} + +// Status implements the Charger.Status interface +func (evse *SimpleEVSE) Status() (api.ChargeStatus, error) { + b, err := evse.client.ReadHoldingRegisters(evseRegVehicleStatus, 1) + evse.log.TRACE.Printf("read charge enable (%d): %0 X", evseRegVehicleStatus, b) + if err != nil { + evse.handler.Close() + return api.StatusNone, err + } + + switch b[0] { + case 1: // ready + return api.StatusA, nil + case 2: // EV is present + return api.StatusB, nil + case 3: // charging + return api.StatusC, nil + case 4: // charging with ventilation + return api.StatusD, nil + case 5: // failure (e.g. diode check, RCD failure) + return api.StatusE, nil + default: + return api.StatusNone, errors.New("invalid response") + } +} + +// Enabled implements the Charger.Enabled interface +func (evse *SimpleEVSE) Enabled() (bool, error) { + b, err := evse.client.ReadHoldingRegisters(evseRegTurnOff, 1) + evse.log.TRACE.Printf("read charge enable (%d): %0 X", evseRegTurnOff, b) + if err != nil { + evse.handler.Close() + return false, err + } + + return b[0] == 1, nil +} + +// Enable implements the Charger.Enable interface +func (evse *SimpleEVSE) Enable(enable bool) error { + b, err := evse.client.ReadHoldingRegisters(evseRegTurnOff, 1) + evse.log.TRACE.Printf("read charge enable (%d): %0 X", evseRegTurnOff, b) + if err != nil { + evse.handler.Close() + return err + } + + if enable { + b[0] |= 1 + } else { + b[0] &= ^byte(1) + } + + b, err = evse.client.WriteMultipleRegisters(evseRegTurnOff, 1, b) + evse.log.TRACE.Printf("write charge enable %d %0X: %0 X", evseRegTurnOff, b, b) + if err != nil { + evse.handler.Close() + } + + return err +} + +// MaxCurrent implements the Charger.MaxCurrent interface +func (evse *SimpleEVSE) MaxCurrent(current int64) error { + u := uint16(current) + + b, err := evse.client.WriteSingleRegister(evseRegAmpsConfig, u) + evse.log.TRACE.Printf("write max current %d %0X: %0 X", evseRegAmpsConfig, u, b) + if err != nil { + evse.handler.Close() + } + + return err +} diff --git a/cmd/setup.go b/cmd/setup.go index 94915edcd..dfeacc57b 100644 --- a/cmd/setup.go +++ b/cmd/setup.go @@ -43,18 +43,7 @@ func configureMeters(conf config) (meters map[string]api.Meter) { func configureChargers(conf config) (chargers map[string]api.Charger) { chargers = make(map[string]api.Charger) for _, cc := range conf.Chargers { - var c api.Charger - - switch cc.Type { - case "wallbe": - c = charger.NewWallbeFromConfig(log, cc.Other) - case "default", "configurable": - c = charger.NewChargerFromConfig(log, cc.Other) - default: - log.FATAL.Fatalf("invalid charger type '%s'", cc.Type) - } - - chargers[cc.Name] = c + chargers[cc.Name] = charger.NewFromConfig(log, cc.Type, cc.Other) } return } diff --git a/core/loadpoint.go b/core/loadpoint.go index 8e98fb79f..d94639d74 100644 --- a/core/loadpoint.go +++ b/core/loadpoint.go @@ -60,7 +60,7 @@ type LoadPoint struct { ResidualPower float64 // PV meter only: household usage. Grid meter: household safety margin // cached state - Mode api.ChargeMode // Charge mode, garded by mux + Mode api.ChargeMode // Charge mode, guarded by mutex status api.ChargeStatus // Charger status targetCurrent int64 // Allowed current. Between MinCurrent and MaxCurrent. enabled bool // Charger enabled state