Go-E: add local api caching (#2657)

Co-authored-by: Tommy-LSA <pirat@stadtweg.de>
This commit is contained in:
Waldmensch1 2022-02-28 09:41:06 +01:00 • committed by GitHub
parent fbaee234e8
commit f0dc811224
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 24 additions and 15 deletions

View file

@ -74,7 +74,7 @@ func NewGoE(uri, token string, cache time.Duration) (api.Charger, error) {
if token != "" {
c.api = goe.NewCloud(log, token, cache)
} else {
c.api = goe.NewLocal(log, util.DefaultScheme(uri, "http"))
c.api = goe.NewLocal(log, util.DefaultScheme(uri, "http"), cache)
}
if c.api.IsV2() {

View file

@ -32,19 +32,23 @@ type API interface {
type LocalAPI struct {
*request.Helper
uri string
v2 bool
uri string
v2 bool
status Response
updated time.Time
cache time.Duration
}
var _ API = (*LocalAPI)(nil)
func NewLocal(log *util.Logger, uri string) *LocalAPI {
func NewLocal(log *util.Logger, uri string, cache time.Duration) *LocalAPI {
uri = strings.TrimRight(uri, "/")
uri = strings.TrimSuffix(uri, "/api")
api := &LocalAPI{
Helper: request.NewHelper(log),
uri: uri,
cache: cache,
}
api.upgradeV2()
@ -78,20 +82,25 @@ func (c *LocalAPI) response(partial string, res interface{}) error {
}
// Status reads a v1/v2 api response
func (c *LocalAPI) Status() (Response, error) {
if c.v2 {
res := new(StatusResponse2)
err := c.response("status?filter=alw,car,eto,nrg,wh,trx,cards", &res)
return res, err
func (c *LocalAPI) Status() (res Response, err error) {
if time.Since(c.updated) > c.cache {
if c.v2 {
c.status = new(StatusResponse2)
err = c.response("status?filter=alw,car,eto,nrg,wh,trx,cards", &c.status)
} else {
c.status = new(StatusResponse)
err = c.response("status", &c.status)
}
if err == nil {
c.updated = time.Now()
}
}
res := new(StatusResponse)
err := c.response("status", &res)
return res, err
return c.status, err
}
// Update executes a v1/v2 api update and returns the response
func (c *LocalAPI) Update(payload string) error {
c.updated = time.Time{}
res := new(UpdateResponse)
if c.v2 {

View file

@ -37,7 +37,7 @@ func TestLocalV1(t *testing.T) {
srv := httptest.NewServer(h)
// h.expect("/api/status?filter=alw")
local := NewLocal(util.NewLogger("foo"), srv.URL)
local := NewLocal(util.NewLogger("foo"), srv.URL, 0)
h.expect("/status")
if _, err := local.Status(); err != nil {
@ -54,7 +54,7 @@ func TestLocalV2(t *testing.T) {
srv := httptest.NewServer(h)
h.expect("/api/status?filter=alw")
local := NewLocal(util.NewLogger("foo"), srv.URL)
local := NewLocal(util.NewLogger("foo"), srv.URL, 0)
h.expect("/api/status?filter=alw,car,eto,nrg,wh,trx,cards")
if _, err := local.Status(); err != nil {