2018-11-20 21:55:06 +00:00
|
|
|
package sensor
|
|
|
|
|
2019-02-24 21:46:36 +00:00
|
|
|
import (
|
2019-06-17 21:37:48 +00:00
|
|
|
"context"
|
|
|
|
"fmt"
|
2019-02-24 21:46:36 +00:00
|
|
|
"sync"
|
|
|
|
|
2019-06-15 13:58:41 +00:00
|
|
|
"github.com/go-flucky/flucky/pkg/internal/collect"
|
|
|
|
"github.com/go-flucky/flucky/pkg/internal/prittyprint"
|
|
|
|
"github.com/go-flucky/flucky/pkg/types"
|
2019-02-24 21:46:36 +00:00
|
|
|
)
|
|
|
|
|
2019-06-25 20:22:34 +00:00
|
|
|
// Read measured values from sensors
|
2019-06-25 20:56:09 +00:00
|
|
|
func Read(sensors []Sensor) ([]types.MeasuredValue, error) {
|
|
|
|
measuredValueChannel := make(chan types.MeasuredValue, 0)
|
|
|
|
errorChannel := make(chan error, 0)
|
2019-06-17 21:37:48 +00:00
|
|
|
|
|
|
|
wg := new(sync.WaitGroup)
|
2019-06-25 20:22:34 +00:00
|
|
|
wg.Add(len(sensors))
|
2019-02-24 21:46:36 +00:00
|
|
|
|
2019-06-25 20:22:34 +00:00
|
|
|
for _, sensor := range sensors {
|
2019-06-25 20:56:09 +00:00
|
|
|
go sensor.ReadChannel(measuredValueChannel, errorChannel, wg)
|
2019-06-13 19:25:32 +00:00
|
|
|
}
|
2019-02-24 21:46:36 +00:00
|
|
|
|
2019-06-17 21:37:48 +00:00
|
|
|
wg.Wait()
|
|
|
|
|
|
|
|
errors := collect.Errors(errorChannel)
|
|
|
|
if len(errors) > 0 {
|
|
|
|
return nil, prittyprint.FormatErrors(errors)
|
|
|
|
}
|
|
|
|
|
2019-06-25 20:22:34 +00:00
|
|
|
measuredValues := collect.MeasuredValues(measuredValueChannel)
|
2019-06-17 21:37:48 +00:00
|
|
|
|
2019-06-25 20:22:34 +00:00
|
|
|
return measuredValues, nil
|
2019-06-13 19:25:32 +00:00
|
|
|
}
|
2019-02-24 21:46:36 +00:00
|
|
|
|
2019-06-25 20:22:34 +00:00
|
|
|
// 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)
|
2019-02-24 21:46:36 +00:00
|
|
|
}
|
2019-06-13 19:25:32 +00:00
|
|
|
}
|
2019-02-24 21:46:36 +00:00
|
|
|
|
2019-06-25 20:22:34 +00:00
|
|
|
// 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) {
|
2019-06-13 19:25:32 +00:00
|
|
|
for {
|
2019-06-17 21:37:48 +00:00
|
|
|
select {
|
|
|
|
case <-ctx.Done():
|
|
|
|
errorChannel <- fmt.Errorf("Context closed: %v", ctx.Err())
|
|
|
|
return
|
|
|
|
default:
|
2019-06-25 20:22:34 +00:00
|
|
|
ReadChannel(ctx, sensors, measuredValueChannel, errorChannel, nil)
|
2019-06-17 21:37:48 +00:00
|
|
|
}
|
2019-02-24 21:46:36 +00:00
|
|
|
}
|
2019-06-13 19:25:32 +00:00
|
|
|
}
|