-
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Expand file tree
/
Copy pathsetup.go
More file actions
1394 lines (1135 loc) Β· 34.5 KB
/
setup.go
File metadata and controls
1394 lines (1135 loc) Β· 34.5 KB
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
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package cmd
import (
"cmp"
"context"
"errors"
"fmt"
"os"
"regexp"
"slices"
"strconv"
"strings"
"sync"
"time"
paho "github.com/eclipse/paho.mqtt.golang"
"github.com/evcc-io/evcc/api"
"github.com/evcc-io/evcc/api/globalconfig"
"github.com/evcc-io/evcc/charger"
"github.com/evcc-io/evcc/charger/ocpp"
"github.com/evcc-io/evcc/cmd/shutdown"
"github.com/evcc-io/evcc/core"
"github.com/evcc-io/evcc/core/circuit"
"github.com/evcc-io/evcc/core/keys"
"github.com/evcc-io/evcc/core/loadpoint"
coresettings "github.com/evcc-io/evcc/core/settings"
"github.com/evcc-io/evcc/hems"
hemsapi "github.com/evcc-io/evcc/hems/hems"
"github.com/evcc-io/evcc/hems/shm"
"github.com/evcc-io/evcc/messenger"
"github.com/evcc-io/evcc/meter"
"github.com/evcc-io/evcc/plugin/golang"
"github.com/evcc-io/evcc/plugin/javascript"
"github.com/evcc-io/evcc/plugin/mqtt"
"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/server/eebus"
"github.com/evcc-io/evcc/server/modbus"
"github.com/evcc-io/evcc/server/providerauth"
"github.com/evcc-io/evcc/tariff"
"github.com/evcc-io/evcc/util"
"github.com/evcc-io/evcc/util/config"
"github.com/evcc-io/evcc/util/locale"
"github.com/evcc-io/evcc/util/machine"
"github.com/evcc-io/evcc/util/request"
_ "github.com/evcc-io/evcc/util/service"
"github.com/evcc-io/evcc/util/sponsor"
"github.com/evcc-io/evcc/util/templates"
"github.com/evcc-io/evcc/vehicle"
"github.com/gorilla/handlers"
"github.com/gorilla/mux"
"github.com/libp2p/zeroconf/v2"
"github.com/samber/lo"
"github.com/spf13/cast"
"github.com/spf13/cobra"
vpr "github.com/spf13/viper"
"golang.org/x/sync/errgroup"
"golang.org/x/text/currency"
)
var conf = globalconfig.All{
Interval: 30 * time.Second,
Log: "info",
Network: globalconfig.Network{
Host: "",
Port: 7070,
},
Ocpp: ocpp.Config{
Port: 8887,
},
Mqtt: globalconfig.Mqtt{
Topic: "evcc",
},
EEBus: eebus.Config{
Port: 4712,
},
Database: globalconfig.DB{
Type: "sqlite",
Dsn: "",
},
}
var yamlSource struct {
sponsor globalconfig.YamlSource
hems globalconfig.YamlSource
eebus globalconfig.YamlSource
tariffs globalconfig.YamlSource
messaging globalconfig.YamlSource
circuits globalconfig.YamlSource
}
var nameRE = regexp.MustCompile(`^[a-zA-Z0-9_.:-]+$`)
func nameValid(name string) error {
if !nameRE.MatchString(name) {
return fmt.Errorf("name must not contain special characters or spaces: %s", name)
}
return nil
}
func loadConfigFile(conf *globalconfig.All, checkDB bool) error {
if err := viper.ReadInConfig(); err != nil {
if _, ok := errors.AsType[vpr.ConfigFileNotFoundError](err); !ok {
return fmt.Errorf("failed reading config file: %w", err)
}
}
if cfgFile := viper.ConfigFileUsed(); cfgFile != "" {
log.INFO.Println("using config file:", cfgFile)
} else {
log.INFO.Println("config file not found, database-only mode")
}
if err := viper.UnmarshalExact(conf); err != nil {
return fmt.Errorf("failed parsing config file: %w", err)
}
// user did not specify a database path
if conf.Database.Dsn == "" && checkDB {
// check if service database exists
if _, err := os.Stat(serviceDB); err == nil {
// service database found, ask user what to do
sudo := ""
if !isWritable(serviceDB) {
sudo = "sudo "
}
log.FATAL.Fatal(`
Found systemd service database at "` + serviceDB + `", evcc has been invoked with no explicit database path.
Running the same config with multiple databases can lead to expiring vehicle tokens.
If you want to use the existing service database run the following command:
` + sudo + `evcc --database ` + serviceDB + `
If you want to create a new user-space database run the following command:
evcc --database ~/.evcc/evcc.db
If you know what you're doing, you can skip the database check with the --ignore-db flag.
`)
}
}
// parse log levels after reading config
parseLogLevels()
return nil
}
func isWritable(filePath string) bool {
file, err := os.OpenFile(filePath, os.O_WRONLY, 0o666)
if err != nil {
return false
}
file.Close()
return true
}
func configureCircuits(conf *[]config.Named) error {
// yaml config from file
if len(*conf) != 0 {
yamlSource.circuits = globalconfig.YamlSourceFile
}
// yaml config from db (deprecated)
if settings.Exists(keys.Circuits) {
if yamlSource.circuits == globalconfig.YamlSourceFile {
// just warn, no error to not break previous behavior
log.WARN.Println("circuits configured via UI yaml; evcc.yaml config will be ignored")
}
*conf = []config.Named{}
if err := settings.Yaml(keys.Circuits, new([]map[string]any), &conf); err != nil {
return err
}
yamlSource.circuits = globalconfig.YamlSourceDb
}
// load configCircuits devices from database
configurable, err := config.ConfigurationsByClass(templates.Circuit)
if err != nil {
return err
}
// device config from db
if yamlSource.circuits != globalconfig.YamlSourceNone && len(configurable) > 0 {
return errors.New("circuits are configured via UI; having an additional yaml config is not allowed")
}
if err := validateStaticCircuits(slices.Clone(*conf)); err != nil {
return err
}
if err := validateConfigurableCircuits(configurable); err != nil {
return err
}
for _, c := range configurable {
*conf = append(*conf, c.Named())
}
return nil
}
// validateCircuitConfigs validates circuit configurations with support for both static and configurable types
func validateCircuitConfigs[T any](children []T, getConfigAndLogger func(T) (config.Named, *util.Logger), getDevice func(T, api.Circuit) config.Device[api.Circuit]) error {
// TODO check for circular references
NEXT:
for i, child := range children {
cc, log := getConfigAndLogger(child)
if cc.Name == "" {
return fmt.Errorf("cannot create circuit: missing name")
}
if err := nameValid(cc.Name); err != nil {
return fmt.Errorf("cannot create circuit: duplicate name: %s", cc.Name)
}
if parent := cast.ToString(cc.Property("parent")); parent != "" {
if _, err := config.Circuits().ByName(parent); err != nil {
continue
}
}
typ, other, err := config.CustomDevice(cc.Type, cc.Other)
if err != nil {
return fmt.Errorf("cannot decode custom circuit '%s': %w", cc.Name, err)
}
ctx := util.WithLogger(context.TODO(), log)
instance, err := circuit.NewFromConfig(ctx, typ, other)
if err != nil {
return fmt.Errorf("cannot create circuit '%s': %w", cc.Name, err)
}
// ensure config has title
if instance.GetTitle() == "" {
//lint:ignore SA1019 as Title is safe on ascii
instance.SetTitle(strings.Title(cc.Name))
}
if err := config.Circuits().Add(getDevice(child, instance)); err != nil {
return err
}
children = slices.Delete(children, i, i+1)
goto NEXT
}
if len(children) > 0 {
cn, _ := getConfigAndLogger(children[0])
return fmt.Errorf("circuit is missing parent: %s", cn.Name)
}
var rootFound bool
for _, dev := range config.Circuits().Devices() {
c := dev.Instance()
if c.GetParent() == nil {
if rootFound {
return errors.New("cannot have multiple root circuits")
}
rootFound = true
}
}
if !rootFound && len(config.Circuits().Devices()) > 0 {
return errors.New("root circuit required")
}
return nil
}
func validateStaticCircuits(children []config.Named) error {
return validateCircuitConfigs(
children,
func(cc config.Named) (config.Named, *util.Logger) { return cc, util.NewLogger(cc.Name) },
func(cc config.Named, instance api.Circuit) config.Device[api.Circuit] {
return config.NewStaticDevice(cc, instance)
},
)
}
func validateConfigurableCircuits(children []config.Config) error {
return validateCircuitConfigs(
children,
func(cc config.Config) (config.Named, *util.Logger) { return cc.Named(), loggerForConfig(&cc) },
func(cc config.Config, instance api.Circuit) config.Device[api.Circuit] {
return config.NewConfigurableDevice(&cc, instance)
},
)
}
type newFromConfFunc[T any] func(context.Context, string, map[string]any) (T, error)
func staticInstance[T any](typ string, cc config.Named, newFromConf newFromConfFunc[T], h config.Handler[T]) error {
ctx, cancel := context.WithCancel(util.WithLogger(context.TODO(), util.NewLogger(cc.Name))) //nolint:govet
instance, err := newFromConf(ctx, cc.Type, cc.Other)
if err != nil {
err = &DeviceError{cc.Name, fmt.Errorf("cannot create %s '%s': %w", typ, cc.Name, err)}
}
if e := h.Add(config.NewStaticDevice(cc, instance)); e != nil && err == nil {
err = &DeviceError{cc.Name, e}
}
// release resources
if err != nil {
cancel()
}
return err //nolint:govet
}
// loggerForConfig creates a logger with sensible name for (custom) configurable device
func loggerForConfig(conf *config.Config) *util.Logger {
res := conf.Named().Name
if t := conf.Title; t != "" && t != res {
res += "-" + t
}
return util.NewLogger(res)
}
func configurableInstance[T any](typ string, conf *config.Config, newFromConf newFromConfFunc[T], h config.Handler[T]) error {
cc := conf.Named()
ctx, cancel := context.WithCancel(util.WithLogger(context.TODO(), loggerForConfig(conf))) //nolint:govet
typ, other, err := config.CustomDevice(cc.Type, cc.Other)
if err != nil {
err = &DeviceError{cc.Name, fmt.Errorf("cannot decode custom %s '%s': %w", typ, cc.Name, err)}
}
var instance T
if err == nil && !conf.Disable {
instance, err = newFromConf(ctx, typ, other)
if err != nil {
err = &DeviceError{cc.Name, fmt.Errorf("cannot create %s '%s': %w", typ, cc.Name, err)}
}
}
if e := h.Add(config.NewConfigurableDevice(conf, instance)); e != nil && err == nil {
err = &DeviceError{cc.Name, e}
}
// release resources
if err != nil {
cancel()
}
return err //nolint:govet
}
func configureMeters(static []config.Named, names ...string) error {
var eg errgroup.Group
for i, cc := range static {
if cc.Name == "" {
return fmt.Errorf("cannot create meter %d: missing name", i+1)
}
// configure all, if no name refs are given
if len(names) > 0 && !slices.Contains(names, cc.Name) {
continue
}
if err := nameValid(cc.Name); err != nil {
log.WARN.Printf("create meter %d: %v", i+1, err)
}
eg.Go(func() error {
return staticInstance("meter", cc, meter.NewFromConfig, config.Meters())
})
}
// append devices from database
configurable, err := config.ConfigurationsByClass(templates.Meter)
if err != nil {
return err
}
for _, conf := range configurable {
eg.Go(func() error {
cc := conf.Named()
// always skip unreferenced db devices
if !slices.Contains(names, cc.Name) {
return nil
}
return configurableInstance("meter", &conf, meter.NewFromConfig, config.Meters())
})
}
return eg.Wait()
}
func configureChargers(static []config.Named, names ...string) error {
var eg errgroup.Group
for i, cc := range static {
if cc.Name == "" {
return fmt.Errorf("cannot create charger %d: missing name", i+1)
}
// configure all, if no name refs are given
if len(names) > 0 && !slices.Contains(names, cc.Name) {
continue
}
if err := nameValid(cc.Name); err != nil {
log.WARN.Printf("create charger %d: %v", i+1, err)
}
eg.Go(func() error {
return staticInstance("charger", cc, charger.NewFromConfig, config.Chargers())
})
}
// append devices from database
configurable, err := config.ConfigurationsByClass(templates.Charger)
if err != nil {
return err
}
for _, conf := range configurable {
eg.Go(func() error {
cc := conf.Named()
// always skip unreferenced db devices
if !slices.Contains(names, cc.Name) {
return nil
}
return configurableInstance("charger", &conf, charger.NewFromConfig, config.Chargers())
})
}
return eg.Wait()
}
func vehicleInstance(cc config.Named) (api.Vehicle, error) {
ctx := util.WithLogger(context.TODO(), util.NewLogger(cc.Name))
typ, other, err := config.CustomDevice(cc.Type, cc.Other)
var instance api.Vehicle
if err == nil {
instance, err = vehicle.NewFromConfig(ctx, typ, other)
}
if err != nil {
if _, ok := errors.AsType[*util.ConfigError](err); ok {
return nil, err
}
// wrap non-config vehicle errors to prevent fatals
log.ERROR.Printf("creating vehicle %s failed: %v", cc.Name, err)
instance = vehicle.NewWrapper(cc.Name, cc.Type, cc.Other, err)
}
// ensure vehicle config has title
if instance.GetTitle() == "" {
//lint:ignore SA1019 as Title is safe on ascii
instance.SetTitle(strings.Title(cc.Name))
}
return instance, nil
}
func configureVehicles(static []config.Named, names ...string) error {
var mu sync.Mutex
var eg errgroup.Group
// stable-sort vehicles by name
devs1 := make([]config.Device[api.Vehicle], 0, len(static))
for i, cc := range static {
if cc.Name == "" {
return fmt.Errorf("cannot create vehicle %d: missing name", i+1)
}
if len(names) > 0 && !slices.Contains(names, cc.Name) {
continue
}
if err := nameValid(cc.Name); err != nil {
return fmt.Errorf("cannot create vehicle %d: %w", i+1, err)
}
eg.Go(func() error {
instance, err := vehicleInstance(cc)
if err != nil {
return fmt.Errorf("cannot create vehicle '%s': %w", cc.Name, err)
}
mu.Lock()
defer mu.Unlock()
devs1 = append(devs1, config.NewStaticDevice(cc, instance))
return nil
})
}
// append devices from database
configurable, err := config.ConfigurationsByClass(templates.Vehicle)
if err != nil {
return err
}
// stable-sort vehicles by id
devs2 := make([]config.ConfigurableDevice[api.Vehicle], 0, len(configurable))
for _, conf := range configurable {
eg.Go(func() error {
cc := conf.Named()
if len(names) > 0 && !slices.Contains(names, cc.Name) {
return nil
}
instance, err := vehicleInstance(cc)
if err != nil {
return fmt.Errorf("cannot create vehicle '%s': %w", cc.Name, err)
}
mu.Lock()
defer mu.Unlock()
devs2 = append(devs2, config.NewConfigurableDevice(&conf, instance))
return nil
})
}
if err := eg.Wait(); err != nil {
return err
}
slices.SortFunc(devs1, func(i, j config.Device[api.Vehicle]) int {
return cmp.Compare(strings.ToLower(i.Config().Name), strings.ToLower(j.Config().Name))
})
for _, dev := range devs1 {
if err := config.Vehicles().Add(dev); err != nil {
return err
}
}
slices.SortFunc(devs2, func(i, j config.ConfigurableDevice[api.Vehicle]) int {
return cmp.Compare(i.ID(), j.ID())
})
for _, dev := range devs2 {
if err := config.Vehicles().Add(dev); err != nil {
return err
}
}
return nil
}
func configureSponsorship(token string) (err error) {
if settings.Exists(keys.SponsorToken) {
if token, err = settings.String(keys.SponsorToken); err != nil {
return err
}
} else if token != "" {
yamlSource.sponsor = globalconfig.YamlSourceFile
}
return sponsor.ConfigureSponsorship(token)
}
func configureEnvironment(cmd *cobra.Command, conf *globalconfig.All) error {
// full http request log
if cmd.Flag(flagHeaders).Changed {
request.LogHeaders = true
}
// setup persistence
err := wrapErrorWithClass(ClassDatabase, configureDatabase(conf.Database))
// configure network
if err == nil {
err = networkSettings(&conf.Network)
}
// setup additional templates
if err == nil {
if cmd.Flags().Changed(flagTemplate) {
class, err := templates.ClassString(cmd.Flags().Lookup(flagTemplateType).Value.String())
if err != nil {
return err
}
if err := templates.Register(class, cmd.Flag(flagTemplate).Value.String()); err != nil {
return err
}
}
}
// setup translations
if err == nil {
// TODO decide wrapping
err = locale.Init()
}
// setup machine id
if err == nil && conf.Plant != "" {
// TODO decide wrapping
err = machine.CustomID(conf.Plant)
}
// setup sponsorship (allow env override)
if err == nil {
err = wrapErrorWithClass(ClassSponsorship, configureSponsorship(conf.SponsorToken))
}
// setup mqtt client listener
if err == nil {
err = wrapErrorWithClass(ClassMqtt, configureMqtt(&conf.Mqtt))
}
// setup OCPP server
if err == nil {
configureOCPP(&conf.Ocpp, conf.Network.ExternalUrl)
}
// setup EEBus server
if err == nil {
err = wrapErrorWithClass(ClassEEBus, configureEEBus(&conf.EEBus))
}
// setup javascript VMs
if err == nil {
err = wrapErrorWithClass(ClassJavascript, configureJavascript(conf.Javascript))
}
// setup go VMs
if err == nil {
err = wrapErrorWithClass(ClassGo, configureGo(conf.Go))
}
return err
}
// configureDatabase configures session database
func configureDatabase(conf globalconfig.DB) error {
if conf.Dsn == "" {
conf.Dsn = userDB
}
if err := db.NewInstance(conf.Type, conf.Dsn); err != nil {
return err
}
persistSettings := func() {
if err := settings.Persist(); err != nil {
log.ERROR.Println("cannot save settings:", err)
}
}
// persist unsaved settings on shutdown
shutdown.Register(persistSettings)
// persist unsaved settings every 30 minutes
go func() {
for range time.Tick(time.Minute) {
persistSettings()
}
}()
return nil
}
// configureInflux configures influx database
func configureInflux(conf *globalconfig.Influx) (*server.Influx, error) {
// read settings
if settings.Exists(keys.Influx) {
if err := settings.Json(keys.Influx, &conf); err != nil {
return nil, err
}
}
if conf.URL == "" {
return nil, nil
}
influx := server.NewInfluxClient(
conf.URL,
conf.Token,
conf.Org,
conf.User,
conf.Password,
conf.Database,
conf.Insecure,
)
return influx, nil
}
// setup mqtt
func configureMqtt(conf *globalconfig.Mqtt) error {
// migrate settings
if settings.Exists(keys.Mqtt) {
if err := settings.Json(keys.Mqtt, &conf); err != nil {
return err
}
}
if conf.Broker == "" {
return nil
}
log := util.NewLogger("mqtt")
instance, err := mqtt.RegisteredClient(log, conf.Broker, conf.User, conf.Password, conf.ClientID, 1, conf.Insecure, conf.CaCert, conf.ClientCert, conf.ClientKey, func(options *paho.ClientOptions) {
if !runAsService || conf.Topic == "" {
return
}
topic := fmt.Sprintf("%s/status", strings.Trim(conf.Topic, "/"))
options.SetWill(topic, "offline", 1, true)
oc := options.OnConnect
options.SetOnConnectHandler(func(client paho.Client) {
oc(client) // original handler
_ = client.Publish(topic, 1, true, "online") // alive - not logged
})
})
if err != nil {
return fmt.Errorf("failed configuring mqtt: %w", err)
}
mqtt.Instance = instance
return nil
}
// setup SHM
func configureSHM(conf *shm.Config, externalUrl string, site *core.Site, httpd *server.HTTPd) error {
if settings.Exists(keys.Shm) {
if err := settings.Json(keys.Shm, &conf); err != nil {
return err
}
}
if err := shm.NewFromConfig(*conf, externalUrl, site, httpd.Addr, httpd.Router()); err != nil {
return fmt.Errorf("failed configuring shm: %w", err)
}
return nil
}
// setup javascript
func configureJavascript(conf []globalconfig.Javascript) 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 []globalconfig.Go) 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 *globalconfig.Hems, site *core.Site) (hemsapi.API, error) {
// use yaml if configured
if conf.Type == "" {
if settings.Exists(keys.Hems) {
*conf = globalconfig.Hems{}
if err := settings.Yaml(keys.Hems, new(map[string]any), &conf); err != nil {
return nil, err
}
yamlSource.hems = globalconfig.YamlSourceDb
}
} else {
yamlSource.hems = globalconfig.YamlSourceFile
}
if conf.Type == "" {
return nil, nil
}
typ, other, err := config.CustomDevice(conf.Type, conf.Other)
if err != nil {
return nil, fmt.Errorf("cannot decode custom hems '%s': %w", conf.Type, err)
}
hems, err := hems.NewFromConfig(context.TODO(), typ, other, site)
if err != nil {
return nil, fmt.Errorf("failed configuring hems: %w", err)
}
go hems.Run()
return hems, nil
}
// networkSettings reads/migrates network settings
func networkSettings(conf *globalconfig.Network) error {
if settings.Exists(keys.Network) {
return settings.Json(keys.Network, &conf)
}
return nil
}
// setup MDNS
func configureMDNS(conf globalconfig.Network) error {
host := strings.TrimSuffix(conf.Host, ".local")
if host == "" {
host = "evcc"
}
internalURL := conf.InternalURL()
text := []string{"path=/", "internal_url=" + internalURL}
if externalURL := conf.ExternalURL(); externalURL != internalURL {
text = append(text, "external_url="+externalURL)
}
zc, err := zeroconf.RegisterProxy("evcc", "_http._tcp", "local.", conf.Port, host, nil, text, nil)
if err != nil {
return err
}
shutdown.Register(zc.Shutdown)
return nil
}
// setup OCPP
func configureOCPP(cfg *ocpp.Config, externalUrl string) {
ocpp.Init(*cfg, externalUrl)
}
// setup EEBus
func configureEEBus(conf *eebus.Config) error {
// migrate settings
if settings.Exists(keys.EEBus) {
if err := migrateYamlToJson(keys.EEBus, conf); err != nil {
return err
}
} else if conf.IsConfigured() {
yamlSource.eebus = globalconfig.YamlSourceFile
}
if !conf.IsConfigured() {
cc, err := eebus.DefaultConfig(conf)
if err != nil {
return err
}
*conf = *cc
if err := settings.SetJson(keys.EEBus, conf); err != nil {
return err
}
}
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
}
func configureMessengers(confMessaging *globalconfig.Messaging, confEvents *globalconfig.MessagingEvents, vehicles messenger.Vehicles, valueChan chan<- util.Param, cache *util.ParamCache) (chan messenger.Event, error) {
// yaml config from file
if len(confMessaging.Events) != 0 || len(confMessaging.Services) != 0 {
yamlSource.messaging = globalconfig.YamlSourceFile
}
// yaml config from db (deprecated)
if settings.Exists(keys.Messaging) {
if yamlSource.messaging == globalconfig.YamlSourceFile {
// just warn, no error to not break previous behavior
log.WARN.Println("messaging configured via UI yaml; evcc.yaml config will be ignored")
}
*confMessaging = globalconfig.Messaging{}
if err := settings.Yaml(keys.Messaging, new(map[string]any), &confMessaging); err != nil {
return nil, err
}
yamlSource.messaging = globalconfig.YamlSourceDb
}
if settings.Exists(keys.MessagingEvents) {
*confEvents = globalconfig.MessagingEvents{}
if err := settings.Json(keys.MessagingEvents, &confEvents); err != nil {
return nil, err
}
if yamlSource.messaging != globalconfig.YamlSourceNone && confEvents != nil {
return nil, errors.New("yaml and device config exists for messaging; remove yaml config")
}
}
messageChan := make(chan messenger.Event, 1)
var eg errgroup.Group
for i, cc := range confMessaging.Services {
// add name for meter/charger parity
cc := config.Named{
Name: fmt.Sprintf("push-%d", i+1),
Type: cc.Type,
Other: cc.Other,
}
eg.Go(func() error {
return staticInstance("messenger", cc, messenger.NewFromConfig, config.Messengers())
})
}
// append devices from database
configurable, err := config.ConfigurationsByClass(templates.Messenger)
if err != nil {
return messageChan, err
}
for _, conf := range configurable {
eg.Go(func() error {
return configurableInstance("messenger", &conf, messenger.NewFromConfig, config.Messengers())
})
}
if err := eg.Wait(); err != nil {
return messageChan, &ClassError{ClassMessenger, err}
}
var events globalconfig.MessagingEvents
if len(*confEvents) > 0 {
events = conf.MessagingEvents
} else {
events = confMessaging.Events
}
messageHub, err := messenger.NewHub(events, vehicles, cache)
if err != nil {
return messageChan, fmt.Errorf("failed configuring push services: %w", err)
}
for _, dev := range config.Messengers().Devices() {
if inst := dev.Instance(); inst != nil {
messageHub.Add(inst)
}
}
go messageHub.Run(messageChan, valueChan)
return messageChan, nil
}
func tariffInstance(name string, conf config.Typed) (api.Tariff, error) {
ctx := util.WithLogger(context.TODO(), util.NewLogger(name))
typ, other, err := config.CustomDevice(conf.Type, conf.Other)
if err != nil {
return nil, fmt.Errorf("cannot decode custom tariff '%s': %w", name, err)
}
instance, err := tariff.NewFromConfig(ctx, typ, other)
if err != nil {
if _, ok := errors.AsType[*util.ConfigError](err); ok {
return nil, err
}
// wrap non-config tariff errors to prevent fatals
log.ERROR.Printf("creating tariff %s failed: %v", name, err)
instance = tariff.NewWrapper(conf.Type, conf.Other, err)
}
return instance, nil
}
func configureSolarTariff(conf []config.Typed, t *api.Tariff) error {
var eg errgroup.Group
tt := make([]api.Tariff, len(conf))
for i, conf := range conf {
eg.Go(func() error {
if conf.Type == "" {
return errors.New("missing type")
}
name := fmt.Sprintf("%s-%s-%d", api.TariffUsageSolar, tariff.Name(conf), i)