forked from evcc-io/evcc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsetup.go
342 lines (276 loc) · 8.37 KB
/
setup.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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
package cmd
import (
"errors"
"fmt"
"strconv"
"strings"
"time"
paho "github.com/eclipse/paho.mqtt.golang"
"github.com/evcc-io/evcc/api"
"github.com/evcc-io/evcc/charger/eebus"
"github.com/evcc-io/evcc/cmd/shutdown"
"github.com/evcc-io/evcc/core"
"github.com/evcc-io/evcc/core/site"
"github.com/evcc-io/evcc/hems"
"github.com/evcc-io/evcc/provider/golang"
"github.com/evcc-io/evcc/provider/javascript"
"github.com/evcc-io/evcc/provider/mqtt"
"github.com/evcc-io/evcc/push"
"github.com/evcc-io/evcc/server"
"github.com/evcc-io/evcc/server/db"
"github.com/evcc-io/evcc/server/db/settings"
"github.com/evcc-io/evcc/tariff"
"github.com/evcc-io/evcc/util"
"github.com/evcc-io/evcc/util/locale"
"github.com/evcc-io/evcc/util/machine"
"github.com/evcc-io/evcc/util/pipe"
"github.com/evcc-io/evcc/util/request"
"github.com/evcc-io/evcc/util/sponsor"
"github.com/libp2p/zeroconf/v2"
"github.com/spf13/cobra"
"github.com/spf13/viper"
"golang.org/x/exp/maps"
"golang.org/x/exp/slices"
"golang.org/x/text/currency"
)
var cp = new(ConfigProvider)
func loadConfigFile(conf *config) error {
err := viper.ReadInConfig()
if cfgFile = viper.ConfigFileUsed(); cfgFile == "" {
return err
}
log.INFO.Println("using config file:", cfgFile)
if err == nil {
if err = viper.UnmarshalExact(&conf); err != nil {
err = fmt.Errorf("failed parsing config file: %w", err)
}
}
// parse log levels after reading config
if err == nil {
parseLogLevels()
}
return err
}
func configureEnvironment(cmd *cobra.Command, conf config) (err error) {
// full http request log
if cmd.Flags().Lookup(flagHeaders).Changed {
request.LogHeaders = true
}
// setup machine id
if conf.Plant != "" {
err = machine.CustomID(conf.Plant)
}
// setup sponsorship (allow env override)
if err == nil && conf.SponsorToken != "" {
err = sponsor.ConfigureSponsorship(conf.SponsorToken)
}
// setup translations
if err == nil {
err = locale.Init()
}
// setup persistence
if err == nil && conf.Database.Dsn != "" {
err = configureDatabase(conf.Database)
}
// setup mqtt client listener
if err == nil && conf.Mqtt.Broker != "" {
err = configureMQTT(conf.Mqtt)
}
// setup javascript VMs
if err == nil {
err = configureJavascript(conf.Javascript)
}
// setup go VMs
if err == nil {
err = configureGo(conf.Go)
}
// setup EEBus server
if err == nil && conf.EEBus != nil {
err = configureEEBus(conf.EEBus)
}
return
}
// configureDatabase configures session database
func configureDatabase(conf dbConfig) error {
if err := db.NewInstance(conf.Type, conf.Dsn); err != nil {
return err
}
if err := settings.Init(); err != nil {
return err
}
shutdown.Register(func() {
if err := settings.Persist(); err != nil {
log.ERROR.Println("cannot save settings:", err)
}
})
return nil
}
// configureInflux configures influx database
func configureInflux(conf server.InfluxConfig, site site.API, in <-chan util.Param) {
influx := server.NewInfluxClient(
conf.URL,
conf.Token,
conf.Org,
conf.User,
conf.Password,
conf.Database,
)
// eliminate duplicate values
dedupe := pipe.NewDeduplicator(30*time.Minute, "vehicleCapacity", "vehicleSoc", "vehicleRange", "vehicleOdometer", "chargedEnergy", "chargeRemainingEnergy")
in = dedupe.Pipe(in)
go influx.Run(site, in)
}
// setup mqtt
func configureMQTT(conf mqttConfig) error {
log := util.NewLogger("mqtt")
var err error
if mqtt.Instance, err = mqtt.RegisteredClient(log, conf.Broker, conf.User, conf.Password, conf.ClientID, 1, conf.Insecure, func(options *paho.ClientOptions) {
topic := fmt.Sprintf("%s/status", strings.Trim(conf.Topic, "/"))
options.SetWill(topic, "offline", 1, true)
}); err != nil {
return fmt.Errorf("failed configuring mqtt: %w", err)
}
return nil
}
// setup javascript
func configureJavascript(conf []javascriptConfig) error {
for _, cc := range conf {
if _, err := javascript.RegisteredVM(cc.VM, cc.Script); err != nil {
return fmt.Errorf("failed configuring javascript: %w", err)
}
}
return nil
}
// setup go
func configureGo(conf []goConfig) error {
for _, cc := range conf {
if _, err := golang.RegisteredVM(cc.VM, cc.Script); err != nil {
return fmt.Errorf("failed configuring go: %w", err)
}
}
return nil
}
// setup HEMS
func configureHEMS(conf typedConfig, site *core.Site, httpd *server.HTTPd) error {
hems, err := hems.NewFromConfig(conf.Type, conf.Other, site, httpd)
if err != nil {
return fmt.Errorf("failed configuring hems: %w", err)
}
go hems.Run()
return nil
}
// setup MDNS
func configureMDNS(conf networkConfig) error {
host := strings.TrimSuffix(conf.Host, ".local")
zc, err := zeroconf.RegisterProxy("EV Charge Controller", "_http._tcp", "local.", conf.Port, host, nil, []string{}, nil)
if err != nil {
return fmt.Errorf("mDNS announcement: %w", err)
}
shutdown.Register(zc.Shutdown)
return nil
}
// setup EEBus
func configureEEBus(conf map[string]interface{}) error {
var err error
if eebus.Instance, err = eebus.NewServer(conf); err != nil {
return fmt.Errorf("failed configuring eebus: %w", err)
}
eebus.Instance.Run()
shutdown.Register(eebus.Instance.Shutdown)
return nil
}
// setup messaging
func configureMessengers(conf messagingConfig, valueChan chan util.Param, cache *util.Cache) (chan push.Event, error) {
messageChan := make(chan push.Event, 1)
messageHub, err := push.NewHub(conf.Events, cache)
if err != nil {
return messageChan, fmt.Errorf("failed configuring push services: %w", err)
}
for _, service := range conf.Services {
impl, err := push.NewFromConfig(service.Type, service.Other)
if err != nil {
return messageChan, fmt.Errorf("failed configuring push service %s: %w", service.Type, err)
}
messageHub.Add(impl)
}
go messageHub.Run(messageChan, valueChan)
return messageChan, nil
}
func configureTariffs(conf tariffConfig) (tariff.Tariffs, error) {
var grid, feedin, planner api.Tariff
var currencyCode currency.Unit = currency.EUR
var err error
if conf.Currency != "" {
currencyCode = currency.MustParseISO(conf.Currency)
}
if conf.Grid.Type != "" {
grid, err = tariff.NewFromConfig(conf.Grid.Type, conf.Grid.Other)
if err != nil {
grid = nil
log.ERROR.Printf("failed configuring grid tariff: %v", err)
}
}
if conf.FeedIn.Type != "" {
feedin, err = tariff.NewFromConfig(conf.FeedIn.Type, conf.FeedIn.Other)
if err != nil {
feedin = nil
log.ERROR.Printf("failed configuring feed-in tariff: %v", err)
}
}
if conf.Planner.Type != "" {
planner, err = tariff.NewFromConfig(conf.Planner.Type, conf.Planner.Other)
if err != nil {
planner = nil
log.ERROR.Printf("failed configuring planner tariff: %v", err)
}
}
tariffs := tariff.NewTariffs(currencyCode, grid, feedin, planner)
return *tariffs, nil
}
func configureSiteAndLoadpoints(conf config) (*core.Site, error) {
if err := cp.configure(conf); err != nil {
return nil, err
}
loadpoints, err := configureLoadpoints(conf, cp)
if err != nil {
return nil, fmt.Errorf("failed configuring loadpoints: %w", err)
}
tariffs, err := configureTariffs(conf.Tariffs)
if err != nil {
return nil, err
}
// list of vehicles ordered by name
keys := maps.Keys(cp.vehicles)
slices.Sort(keys)
vehicles := make([]api.Vehicle, 0, len(cp.vehicles))
for _, k := range keys {
vehicles = append(vehicles, cp.vehicles[k])
}
return configureSite(conf.Site, cp, loadpoints, vehicles, tariffs)
}
func configureSite(conf map[string]interface{}, cp *ConfigProvider, loadpoints []*core.Loadpoint, vehicles []api.Vehicle, tariffs tariff.Tariffs) (*core.Site, error) {
site, err := core.NewSiteFromConfig(log, cp, conf, loadpoints, vehicles, tariffs)
if err != nil {
return nil, fmt.Errorf("failed configuring site: %w", err)
}
return site, nil
}
func configureLoadpoints(conf config, cp *ConfigProvider) (loadpoints []*core.Loadpoint, err error) {
lpInterfaces, ok := viper.AllSettings()["loadpoints"].([]interface{})
if !ok || len(lpInterfaces) == 0 {
return nil, errors.New("missing loadpoints")
}
for id, lpcI := range lpInterfaces {
var lpc map[string]interface{}
if err := util.DecodeOther(lpcI, &lpc); err != nil {
return nil, fmt.Errorf("failed decoding loadpoint configuration: %w", err)
}
log := util.NewLogger("lp-" + strconv.Itoa(id+1))
lp, err := core.NewLoadpointFromConfig(log, cp, lpc)
if err != nil {
return nil, fmt.Errorf("failed configuring loadpoint: %w", err)
}
loadpoints = append(loadpoints, lp)
}
return loadpoints, nil
}