forked from evcc-io/evcc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsma.go
100 lines (81 loc) · 1.92 KB
/
sma.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
package provider
import (
"errors"
"fmt"
"github.com/evcc-io/evcc/provider/sma"
"github.com/evcc-io/evcc/util"
"gitlab.com/bboehmke/sunny"
)
// SMA provider
type SMA struct {
device *sma.Device
value sunny.ValueID
scale float64
}
func init() {
registry.Add("sma", NewSMAFromConfig)
}
// NewSMAFromConfig creates SMA provider
func NewSMAFromConfig(other map[string]interface{}) (Provider, error) {
cc := struct {
URI, Password, Interface string
Serial uint32
Value string
Scale float64
}{
Password: "0000",
Scale: 1,
}
if err := util.DecodeOther(other, &cc); err != nil {
return nil, err
}
discoverer, err := sma.GetDiscoverer(cc.Interface)
if err != nil {
return nil, fmt.Errorf("failed to get discoverer failed: %w", err)
}
provider := &SMA{
scale: cc.Scale,
}
switch {
case cc.URI != "":
provider.device, err = discoverer.DeviceByIP(cc.URI, cc.Password)
if err != nil {
return nil, err
}
case cc.Serial > 0:
provider.device = discoverer.DeviceBySerial(cc.Serial, cc.Password)
if provider.device == nil {
return nil, fmt.Errorf("device not found: %d", cc.Serial)
}
default:
return nil, errors.New("missing uri or serial")
}
provider.value, err = sunny.ValueIDString(cc.Value)
if err != nil {
return nil, err
}
return provider, err
}
var _ FloatProvider = (*SMA)(nil)
// FloatGetter creates handler for float64
func (p *SMA) FloatGetter() (func() (float64, error), error) {
return func() (float64, error) {
values, err := p.device.Values()
if err != nil {
return 0, err
}
return sma.AsFloat(values[p.value]) * p.scale, nil
}, nil
}
var _ IntProvider = (*SMA)(nil)
// IntGetter creates handler for int64
func (p *SMA) IntGetter() (func() (int64, error), error) {
g, err := p.FloatGetter()
return func() (int64, error) {
f, err := g()
if err != nil {
return 0, err
}
return int64(f), nil
}, err
}