PKGBUILD/pkg/sensor/sensor.go

58 lines
1.5 KiB
Go

package sensor
import (
"context"
"fmt"
"sync"
"github.com/go-flucky/flucky/pkg/internal/collect"
"github.com/go-flucky/flucky/pkg/internal/prittyprint"
"github.com/go-flucky/flucky/pkg/types"
)
// Read measured values from sensors
func Read(sensors []Sensor) ([]types.MeasuredValue, error) {
measuredValueChannel := make(chan types.MeasuredValue, 0)
errorChannel := make(chan error, 0)
wg := new(sync.WaitGroup)
wg.Add(len(sensors))
for _, sensor := range sensors {
go sensor.ReadChannel(measuredValueChannel, errorChannel, wg)
}
wg.Wait()
errors := collect.Errors(errorChannel)
if len(errors) > 0 {
return nil, prittyprint.FormatErrors(errors)
}
measuredValues := collect.MeasuredValues(measuredValueChannel)
return measuredValues, nil
}
// ReadChannel reads the measured values from sensors and writes them to a
// channel.
func ReadChannel(ctx context.Context, sensors []Sensor, measuredValueChannel chan<- types.MeasuredValue, errorChannel chan<- error, wg *sync.WaitGroup) {
for _, sensor := range sensors {
sensor.ReadChannel(measuredValueChannel, errorChannel, wg)
}
}
// ReadContinuously reads the measured values continously from sensors and writes
// them to a channel.
func ReadContinuously(ctx context.Context, sensors []Sensor, measuredValueChannel chan<- types.MeasuredValue, errorChannel chan<- error) {
for {
select {
case <-ctx.Done():
errorChannel <- fmt.Errorf("Context closed: %v", ctx.Err())
return
default:
ReadChannel(ctx, sensors, measuredValueChannel, errorChannel, nil)
}
}
}