forked from evcc-io/evcc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconfig.go
71 lines (58 loc) · 1.66 KB
/
config.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
package vehicle
import (
"fmt"
"strings"
"time"
"github.com/evcc-io/evcc/api"
"github.com/evcc-io/evcc/util"
)
const (
expiry = 5 * time.Minute // maximum response age before refresh
interval = 15 * time.Minute // refresh interval when charging
)
type vehicleRegistry map[string]func(map[string]interface{}) (api.Vehicle, error)
func (r vehicleRegistry) Add(name string, factory func(map[string]interface{}) (api.Vehicle, error)) {
if _, exists := r[name]; exists {
panic(fmt.Sprintf("cannot register duplicate vehicle type: %s", name))
}
r[name] = factory
}
func (r vehicleRegistry) Get(name string) (func(map[string]interface{}) (api.Vehicle, error), error) {
factory, exists := r[name]
if !exists {
return nil, fmt.Errorf("vehicle type not registered: %s", name)
}
return factory, nil
}
var registry vehicleRegistry = make(map[string]func(map[string]interface{}) (api.Vehicle, error))
// Types returns the list of vehicle types
func Types() []string {
var res []string
for typ := range registry {
res = append(res, typ)
}
return res
}
// NewFromConfig creates vehicle from configuration
func NewFromConfig(typ string, other map[string]interface{}) (v api.Vehicle, err error) {
var cc struct {
Cloud bool
Other map[string]interface{} `mapstructure:",remain"`
}
if err := util.DecodeOther(other, &cc); err != nil {
return nil, err
}
if cc.Cloud {
cc.Other["brand"] = typ
typ = "cloud"
}
factory, err := registry.Get(strings.ToLower(typ))
if err == nil {
if v, err = factory(cc.Other); err != nil {
err = fmt.Errorf("cannot create vehicle '%s': %w", typ, err)
}
} else {
err = fmt.Errorf("invalid vehicle type: %s", typ)
}
return
}