Super explicit states
This commit is contained in:
@@ -35,6 +35,14 @@ type Ultrasonic struct {
|
|||||||
Echo int
|
Echo int
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type state int
|
||||||
|
|
||||||
|
const (
|
||||||
|
onTimer state = iota
|
||||||
|
offTimer
|
||||||
|
watching
|
||||||
|
)
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
flag.Parse()
|
flag.Parse()
|
||||||
|
|
||||||
@@ -64,8 +72,8 @@ func main() {
|
|||||||
last[i] = math.MaxFloat64
|
last[i] = math.MaxFloat64
|
||||||
}
|
}
|
||||||
|
|
||||||
onUntil := time.Time{}
|
var st state = watching
|
||||||
offUntil := time.Time{}
|
var onUntil, offUntil time.Time
|
||||||
|
|
||||||
for {
|
for {
|
||||||
// Fetch new values
|
// Fetch new values
|
||||||
@@ -88,25 +96,28 @@ func main() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if !r.IsOn() && on > 0 && onUntil.IsZero() && offUntil.IsZero() {
|
switch st {
|
||||||
// Not on, no timers, something detected
|
case watching:
|
||||||
r.On()
|
if on > 0 {
|
||||||
onUntil = time.Now().Add(time.Duration(cf.OnSeconds * float64(time.Second)))
|
log.Printf("on %s", fmtDists(last))
|
||||||
log.Printf("on %s", fmtDists(last))
|
r.On()
|
||||||
}
|
onUntil = time.Now().Add(time.Duration(cf.OnSeconds * float64(time.Second)))
|
||||||
|
st = onTimer
|
||||||
|
}
|
||||||
|
|
||||||
if r.IsOn() && onUntil.Before(time.Now()) {
|
case onTimer:
|
||||||
// On timer expired, turn off
|
if time.Now().After(onUntil) {
|
||||||
r.Off()
|
log.Printf("off %s", fmtDists(last))
|
||||||
offUntil = time.Now().Add(time.Duration(cf.OffSeconds * float64(time.Second)))
|
r.Off()
|
||||||
log.Printf("off %s", fmtDists(last))
|
offUntil = time.Now().Add(time.Duration(cf.OffSeconds * float64(time.Second)))
|
||||||
}
|
st = offTimer
|
||||||
|
}
|
||||||
|
|
||||||
if !r.IsOn() && on == 0 && off == len(uss) && !offUntil.IsZero() && offUntil.Before(time.Now()) {
|
case offTimer:
|
||||||
// All quiet and timers expired, reset state
|
if time.Now().After(offUntil) && on == 0 && off == len(uss) {
|
||||||
onUntil = time.Time{}
|
log.Printf("reset %s", fmtDists(last))
|
||||||
offUntil = time.Time{}
|
st = watching
|
||||||
log.Printf("reset %s", fmtDists(last))
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user