forked from evcc-io/evcc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
device.go
87 lines (74 loc) · 1.64 KB
/
device.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
package sma
import (
"fmt"
"sync"
"time"
"dario.cat/mergo"
"github.com/connectorjs/evcm/util"
"gitlab.com/bboehmke/sunny"
)
// Device holds information for a Device and provides interface to get values
type Device struct {
*sunny.Device
log *util.Logger
mux sync.Mutex
wait *util.Waiter
values map[sunny.ValueID]interface{}
once sync.Once
}
// StartUpdateLoop if not already started
func (d *Device) StartUpdateLoop() {
d.once.Do(func() {
go func() {
for range time.Tick(time.Second * 5) {
if err := d.UpdateValues(); err != nil {
d.log.ERROR.Println(err)
}
}
}()
})
}
func (d *Device) UpdateValues() error {
d.mux.Lock()
defer d.mux.Unlock()
values, err := d.Device.GetValues()
if err == nil {
err = mergo.Merge(&d.values, values, mergo.WithOverride)
d.wait.Update()
}
return err
}
func (d *Device) Values() (map[sunny.ValueID]interface{}, error) {
// ensure update loop was started
d.StartUpdateLoop()
d.mux.Lock()
defer d.mux.Unlock()
if late := d.wait.Overdue(); late > 0 {
return nil, fmt.Errorf("update timeout: %v", late.Truncate(time.Second))
}
// return a copy of the map to avoid race conditions
values := make(map[sunny.ValueID]interface{}, len(d.values))
for key, value := range d.values {
values[key] = value
}
return values, nil
}
func AsFloat(value interface{}) float64 {
switch v := value.(type) {
case float64:
return v
case int32:
return float64(v)
case int64:
return float64(v)
case uint32:
return float64(v)
case uint64:
return float64(v)
case nil:
return 0
default:
util.NewLogger("sma").WARN.Printf("unknown value type: %T", value)
return 0
}
}