forked from evcc-io/evcc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathoctopus.go
109 lines (88 loc) · 2.16 KB
/
octopus.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
package tariff
import (
"errors"
"sync"
"time"
"github.com/evcc-io/evcc/api"
"github.com/evcc-io/evcc/tariff/octopus"
"github.com/evcc-io/evcc/util"
"github.com/evcc-io/evcc/util/request"
"golang.org/x/exp/slices"
)
type Octopus struct {
mux sync.Mutex
log *util.Logger
uri string
region string
data api.Rates
updated time.Time
}
var _ api.Tariff = (*Octopus)(nil)
func init() {
registry.Add("octopusenergy", NewOctopusFromConfig)
}
func NewOctopusFromConfig(other map[string]interface{}) (api.Tariff, error) {
var cc struct {
Region string
Tariff string
}
if err := util.DecodeOther(other, &cc); err != nil {
return nil, err
}
if cc.Region == "" {
return nil, errors.New("missing region")
}
if cc.Tariff == "" {
return nil, errors.New("missing tariff code")
}
t := &Octopus{
log: util.NewLogger("octopus"),
uri: octopus.ConstructRatesAPI(cc.Tariff, cc.Region),
region: cc.Tariff,
}
done := make(chan error)
go t.run(done)
err := <-done
return t, err
}
func (t *Octopus) run(done chan error) {
var once sync.Once
client := request.NewHelper(t.log)
for ; true; <-time.Tick(time.Hour) {
var res octopus.UnitRates
if err := client.GetJSON(t.uri, &res); err != nil {
once.Do(func() { done <- err })
t.log.ERROR.Println(err)
continue
}
once.Do(func() { close(done) })
t.mux.Lock()
t.updated = time.Now()
t.data = make(api.Rates, 0, len(res.Results))
for _, r := range res.Results {
ar := api.Rate{
Start: r.ValidityStart,
End: r.ValidityEnd,
// UnitRates are supplied inclusive of tax, though this could be flipped easily with a config flag.
Price: r.PriceInclusiveTax / 1e2,
}
t.data = append(t.data, ar)
}
t.mux.Unlock()
}
}
// Unit implements the api.Tariff interface
// Stubbed because supplier always works in GBP
func (t *Octopus) Unit() string {
return "GBP"
}
// Rates implements the api.Tariff interface
func (t *Octopus) Rates() (api.Rates, error) {
t.mux.Lock()
defer t.mux.Unlock()
return slices.Clone(t.data), outdatedError(t.updated, time.Hour)
}
// IsDynamic implements the api.Tariff interface
func (t *Octopus) IsDynamic() bool {
return true
}