56 lines
1.3 KiB
Go
56 lines
1.3 KiB
Go
package devices
|
|
|
|
import (
|
|
"log"
|
|
"time"
|
|
)
|
|
|
|
type Device interface {
|
|
// Retreive the status of the device.
|
|
// This is usually acheived by taking a reading from the power LED.
|
|
Status() (bool, error)
|
|
|
|
// Toggle the status of the device.
|
|
// This is usually achieved by pressing the power button.
|
|
ToggleStatus() error
|
|
}
|
|
|
|
func KeepDeviceInSync(logger *log.Logger, device Device, wantStatus func() (bool, error), exit <-chan bool) {
|
|
for {
|
|
select {
|
|
case <-exit:
|
|
break
|
|
default:
|
|
status, err := device.Status()
|
|
if err != nil {
|
|
logger.Printf("Failed to fetch device status, waiting 1 minute until next attempt: %s", err)
|
|
time.Sleep(1 * time.Minute)
|
|
continue
|
|
}
|
|
|
|
want, err := wantStatus()
|
|
if err != nil {
|
|
logger.Printf("Failed to fetch want status, waiting 1 minute until next attempt: %s", err)
|
|
time.Sleep(1 * time.Minute)
|
|
continue
|
|
}
|
|
|
|
if status == want {
|
|
// Don't lock up our single-threaded session storage too much
|
|
time.Sleep(2 * time.Second)
|
|
continue
|
|
}
|
|
|
|
err = device.ToggleStatus()
|
|
if err != nil {
|
|
logger.Printf("Failed to toggle device status, waiting 2 minutes until next attempt: %s", err)
|
|
// Cooldown to not overwhelm the device with start/stop requests
|
|
time.Sleep(2 * time.Minute)
|
|
return
|
|
}
|
|
|
|
logger.Printf("Toggled device status")
|
|
time.Sleep(2 * time.Minute)
|
|
}
|
|
}
|
|
}
|