-
Notifications
You must be signed in to change notification settings - Fork 4
/
wheel.go
106 lines (88 loc) · 1.48 KB
/
wheel.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
101
102
103
104
105
106
package main
import (
"time"
)
const (
binaryDetectCnt = 4
initialMaxDelta = 10
)
type wheelType int
const (
wheelTypeNone wheelType = iota
wheelTypeBinary
wheelTypeContinuous
)
type wheelNormalizer struct {
init bool
eventCnt int
wheelType wheelType
maxDelta float64
binaryCnt int
binaryAbs float64
timePrev time.Time
dSum float64
}
func (n *wheelNormalizer) Normalize(d float64) (float64, bool) {
if n.eventCnt > binaryDetectCnt {
n.init = true
} else {
n.eventCnt++
}
dAbs := d
if dAbs < 0 {
dAbs = -d
}
if dAbs == 0 {
return 0, n.init
}
if n.binaryAbs == dAbs {
n.binaryCnt++
} else {
n.binaryCnt = 0
}
n.binaryAbs = dAbs
typePrev := n.wheelType
if n.binaryCnt > binaryDetectCnt {
n.wheelType = wheelTypeBinary
if n.binaryAbs != dAbs {
n.maxDelta = initialMaxDelta
}
} else {
n.wheelType = wheelTypeContinuous
}
if n.wheelType != typePrev {
n.maxDelta = initialMaxDelta
}
now := time.Now()
dt := now.Sub(n.timePrev).Seconds()
if dt > 0 {
if dt > 0.1 {
dt = 0.1
}
n.dSum += d
dps := n.dSum / dt
n.dSum = 0
n.timePrev = now
dpsAbs := dps
if dpsAbs < 0 {
dpsAbs = -dps
}
if n.maxDelta < dpsAbs {
// LPF to suppress spikes
n.maxDelta = n.maxDelta*0.5 + dpsAbs*0.5
}
n.maxDelta *= 0.95
} else {
n.dSum += d
}
if n.maxDelta < 1 {
n.maxDelta = 1
}
if n.wheelType == wheelTypeBinary {
if d < 0 {
return -1, n.init
}
return 1, n.init
}
return d * 250 / n.maxDelta, n.init
}