Add offseconds, simplify state machine, add logging

This commit is contained in:
Ian Gulliver
2022-09-24 21:19:57 -07:00
parent 75d2df1aa5
commit 3e8af64cbc
2 changed files with 37 additions and 21 deletions

View File

@@ -1,7 +1,9 @@
package main package main
import "context" import "context"
import "encoding/json"
import "flag" import "flag"
import "log"
import "math" import "math"
import "os" import "os"
import "time" import "time"
@@ -21,6 +23,7 @@ type Config struct {
OffCM float64 OffCM float64
OnSeconds float64 OnSeconds float64
OffSeconds float64
} }
type Relay struct { type Relay struct {
@@ -62,6 +65,7 @@ func main() {
} }
onUntil := time.Time{} onUntil := time.Time{}
offUntil := time.Time{}
for { for {
// Fetch new values // Fetch new values
@@ -84,29 +88,25 @@ func main() {
} }
} }
// States: if !r.IsOn() && on > 0 && onUntil.IsZero() && offUntil.IsZero() {
// on 0, off *, r Off, onUntil zero -> stable // Not on, no timers, something detected
// on 1, off *, r Off, onUntil zero -> turn on
// on *, off *, r On, onUntil future -> stay on
// on *, off *, r On, onUntil past -> turn off
// on *, off all, r Off, onUntil past -> reset state
if on > 0 {
// At least one on, turn on
if onUntil.IsZero() {
r.On() r.On()
onUntil = time.Now().Add(time.Duration(cf.OnSeconds * float64(time.Second))) onUntil = time.Now().Add(time.Duration(cf.OnSeconds * float64(time.Second)))
} log.Printf("on %s", fmtDists(last))
} else if off == len(uss) {
// All off, turn off
if !r.IsOn() {
onUntil = time.Time{}
}
} }
// Time target expired if r.IsOn() && onUntil.Before(time.Now()) {
if !onUntil.IsZero() && onUntil.Before(time.Now()) { // On timer expired, turn off
r.Off() r.Off()
offUntil = time.Now().Add(time.Duration(cf.OffSeconds * float64(time.Second)))
log.Printf("off %s", fmtDists(last))
}
if !r.IsOn() && on == 0 && off == len(uss) && !offUntil.IsZero() && offUntil.Before(time.Now()) {
// All quiet and timers expired, reset state
onUntil = time.Time{}
offUntil = time.Time{}
log.Printf("reset %s", fmtDists(last))
} }
} }
} }
@@ -130,3 +130,18 @@ func readConf() (*Config, error) {
return c, nil return c, nil
} }
func fmtDists(dists []float64) string {
ints := make([]int, len(dists))
for i, d := range dists {
ints[i] = int(d)
}
b, err := json.Marshal(ints)
if err != nil {
panic(err)
}
return string(b)
}

View File

@@ -9,3 +9,4 @@ medianbuffer: 47
oncm: 50 oncm: 50
offcm: 70 offcm: 70
onseconds: 5 onseconds: 5
offseconds: 5