sampler-fork/data/sampler.go

65 lines
1.0 KiB
Go
Raw Normal View History

2019-01-31 00:02:38 +00:00
package data
import (
"time"
)
2019-02-03 04:11:26 +00:00
type Sampler struct {
consumer Consumer
items []Item
triggers []Trigger
triggersChannel chan Sample
2019-01-31 00:02:38 +00:00
}
func NewSampler(consumer Consumer, items []Item, triggers []Trigger, rateMs int) Sampler {
2019-01-31 00:02:38 +00:00
ticker := time.NewTicker(
time.Duration(rateMs * int(time.Millisecond)),
)
sampler := Sampler{
consumer,
items,
triggers,
make(chan Sample),
}
2019-01-31 00:02:38 +00:00
go func() {
for ; true; <-ticker.C {
for _, item := range sampler.items {
go sampler.sample(item)
}
}
}()
go func() {
for {
select {
case sample := <-sampler.triggersChannel:
for _, t := range sampler.triggers {
t.Execute(sample)
}
}
2019-01-31 00:02:38 +00:00
}
}()
2019-02-03 04:11:26 +00:00
return sampler
2019-01-31 00:02:38 +00:00
}
func (s *Sampler) sample(item Item) {
2019-03-09 01:00:13 +00:00
val, err := item.nextValue()
2019-03-09 01:00:13 +00:00
if err == nil {
2019-03-13 03:15:55 +00:00
sample := Sample{Label: item.Label, Value: val, Color: item.Color}
s.consumer.SampleChannel <- sample
s.triggersChannel <- sample
2019-03-08 04:04:46 +00:00
} else {
s.consumer.AlertChannel <- Alert{
Title: "SAMPLING FAILURE",
Text: err.Error(),
2019-03-13 03:15:55 +00:00
Color: item.Color,
}
2019-03-08 04:04:46 +00:00
}
2019-01-31 00:02:38 +00:00
}