-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsensor.go
More file actions
110 lines (84 loc) · 1.77 KB
/
sensor.go
File metadata and controls
110 lines (84 loc) · 1.77 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
package sensor
import (
"fmt"
"time"
)
type State uint
const (
Inactive State = iota + 1
Active
Outdated
)
type ISensor interface {
Reading() (float64, State, error)
ReadingAge() (time.Duration, error)
Name() string
}
type IReporter interface {
ReportTo()
SetValue(value float64)
}
type PropagateFunc func(sensor ISensor)
type Options struct {
Name string
MaxReadingAge time.Duration
}
type Sensor struct {
value float64
State State
UpdatedTime time.Time
options Options
Propagate PropagateFunc
}
func (s State) String() string {
switch s {
case Inactive:
return "inactive"
case Active:
return "active"
case Outdated:
return "outdated"
}
return "unknown"
}
func (s *Sensor) IsReadingValid() bool {
age, err := s.ReadingAge()
if err != nil {
return false
}
outdated := age - s.options.MaxReadingAge
if outdated.Seconds() > 0 {
return false
}
return true
}
func (s *Sensor) Reading() (float64, State, error) {
age, err := s.ReadingAge()
if err != nil {
return 0, s.State, err
}
outdated := age - s.options.MaxReadingAge
if outdated.Seconds() > 0 {
s.State = Outdated
// returns value anyway but with error message
return s.value, s.State, fmt.Errorf("time value outdated %d seconds for %s sensor", outdated.Seconds(), s.options.Name)
}
return s.value, s.State, nil
}
func (s *Sensor) ReadingAge() (time.Duration, error) {
if s.UpdatedTime.IsZero() {
return 0, fmt.Errorf("no sensor reading available (yet?) for sensor '%s'", s.options.Name)
}
return time.Now().Sub(s.UpdatedTime), nil
}
func (s *Sensor) Name() string {
return s.options.Name
}
func (s *Sensor) SetValue(value float64) {
s.UpdatedTime = time.Now()
s.State = Active
s.value = value
if s.Propagate != nil {
s.Propagate(s)
}
}