2022-04-29 19:02:33 +00:00
|
|
|
package tilt
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
2022-07-25 08:55:25 +00:00
|
|
|
"fmt"
|
2022-04-29 19:02:33 +00:00
|
|
|
"log"
|
|
|
|
"sync"
|
|
|
|
"time"
|
2022-07-25 08:55:25 +00:00
|
|
|
|
|
|
|
"github.com/getsentry/sentry-go"
|
2022-04-29 19:02:33 +00:00
|
|
|
)
|
|
|
|
|
2022-07-23 14:10:34 +00:00
|
|
|
var (
|
2022-07-25 08:55:25 +00:00
|
|
|
C chan Tilt
|
|
|
|
hub *sentry.Hub
|
2022-07-23 14:10:34 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
func init() {
|
2022-07-25 07:35:02 +00:00
|
|
|
C = make(chan Tilt, 10)
|
2022-07-25 08:55:25 +00:00
|
|
|
hub = sentry.CurrentHub().Clone()
|
2022-07-23 14:10:34 +00:00
|
|
|
}
|
|
|
|
|
2022-04-29 19:02:33 +00:00
|
|
|
func PollSensors(ctx context.Context, wg *sync.WaitGroup, interval time.Duration, scanDuration time.Duration) {
|
2022-07-23 23:16:40 +00:00
|
|
|
defer wg.Done()
|
2022-07-25 08:55:25 +00:00
|
|
|
defer hub.Flush(10 * time.Second)
|
2022-07-23 23:16:40 +00:00
|
|
|
|
2022-04-29 19:02:33 +00:00
|
|
|
if interval < scanDuration {
|
|
|
|
log.Fatal("Unable to use interval < scanDuration")
|
|
|
|
}
|
|
|
|
|
2022-07-25 07:35:02 +00:00
|
|
|
// Perform initial scan when booting
|
|
|
|
scan(ctx, scanDuration)
|
2022-04-29 19:02:33 +00:00
|
|
|
|
2022-07-25 07:35:02 +00:00
|
|
|
ticker := time.NewTicker(interval)
|
2022-04-29 19:02:33 +00:00
|
|
|
for {
|
|
|
|
select {
|
|
|
|
case <-ticker.C:
|
|
|
|
scan(ctx, scanDuration)
|
2022-07-23 23:16:40 +00:00
|
|
|
|
|
|
|
case <-ctx.Done():
|
|
|
|
return
|
2022-04-29 19:02:33 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func scan(ctx context.Context, timeout time.Duration) {
|
|
|
|
scanner := NewScanner()
|
|
|
|
scanner.Scan(ctx, timeout)
|
|
|
|
|
|
|
|
for _, t := range scanner.Tilts() {
|
|
|
|
color := string(t.Color())
|
|
|
|
metricGravity.WithLabelValues(color).Set(t.Gravity())
|
|
|
|
metricTemp.WithLabelValues(color).Set(t.Celsius())
|
2022-07-23 14:10:34 +00:00
|
|
|
|
2022-07-24 06:28:16 +00:00
|
|
|
// Log tilt readings
|
2022-07-25 07:35:02 +00:00
|
|
|
//t.Print()
|
2022-07-24 06:28:16 +00:00
|
|
|
|
2022-07-23 23:16:40 +00:00
|
|
|
select {
|
|
|
|
case C <- t:
|
|
|
|
// Message sent
|
2022-08-02 18:39:31 +00:00
|
|
|
|
2022-07-23 23:16:40 +00:00
|
|
|
default:
|
|
|
|
// No recipients on channel
|
2022-07-25 08:55:25 +00:00
|
|
|
err := fmt.Errorf("channel overflow on tilt reading channel")
|
|
|
|
hub.CaptureException(err)
|
|
|
|
log.Print(err)
|
2022-07-23 23:16:40 +00:00
|
|
|
}
|
2022-04-29 19:02:33 +00:00
|
|
|
}
|
|
|
|
}
|