2018-11-20 21:55:06 +00:00
|
|
|
package sensor
|
|
|
|
|
2019-02-24 21:46:36 +00:00
|
|
|
import (
|
2019-06-15 13:58:41 +00:00
|
|
|
"github.com/go-flucky/flucky/pkg/types"
|
2019-02-24 21:46:36 +00:00
|
|
|
)
|
|
|
|
|
2020-01-10 18:42:19 +00:00
|
|
|
func Read(sensors []Sensor, measuredValueType types.MeasuredValueType) ([]*types.MeasuredValue, error) {
|
2019-06-27 07:31:40 +00:00
|
|
|
|
2020-01-10 18:42:19 +00:00
|
|
|
type result struct {
|
|
|
|
measuredValues []*types.MeasuredValue
|
|
|
|
err error
|
2019-06-17 21:37:48 +00:00
|
|
|
}
|
|
|
|
|
2020-01-10 18:42:19 +00:00
|
|
|
resultChannel := make(chan *result, len(sensors))
|
|
|
|
|
|
|
|
// producers
|
|
|
|
// read measured values
|
|
|
|
for _, s := range sensors {
|
|
|
|
go func(s Sensor) {
|
|
|
|
measuredValues, err := s.Read()
|
|
|
|
resultChannel <- &result{
|
|
|
|
measuredValues: measuredValues,
|
|
|
|
err: err,
|
|
|
|
}
|
|
|
|
}(s)
|
2019-02-24 21:46:36 +00:00
|
|
|
}
|
2019-06-27 07:31:40 +00:00
|
|
|
|
2020-01-10 18:42:19 +00:00
|
|
|
// consumer
|
|
|
|
measuredValues := make([]*types.MeasuredValue, 0)
|
|
|
|
counter := len(sensors)
|
2019-06-13 19:25:32 +00:00
|
|
|
for {
|
2020-01-10 18:42:19 +00:00
|
|
|
if counter == 0 {
|
|
|
|
break
|
|
|
|
}
|
2019-06-17 21:37:48 +00:00
|
|
|
select {
|
2020-01-10 18:42:19 +00:00
|
|
|
case result := <-resultChannel:
|
|
|
|
counter--
|
|
|
|
if result.err != nil {
|
|
|
|
return nil, result.err
|
|
|
|
}
|
|
|
|
measuredValues = append(measuredValues, result.measuredValues...)
|
2019-06-17 21:37:48 +00:00
|
|
|
}
|
2019-02-24 21:46:36 +00:00
|
|
|
}
|
2020-01-10 18:42:19 +00:00
|
|
|
|
|
|
|
return types.SelectMeasuredValues(measuredValueType, measuredValues), nil
|
2019-06-13 19:25:32 +00:00
|
|
|
}
|