PKGBUILD/pkg/sensor/sensor.go

47 lines
951 B
Go
Raw Normal View History

package sensor
2019-02-24 21:46:36 +00:00
import (
"github.com/volker-raschek/flucky/pkg/types"
2019-02-24 21:46:36 +00:00
)
func Read(sensors []Sensor, measuredValueType types.MeasuredValueType) ([]*types.MeasuredValue, error) {
type result struct {
measuredValues []*types.MeasuredValue
err error
}
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
}
// consumer
measuredValues := make([]*types.MeasuredValue, 0)
counter := len(sensors)
for {
if counter == 0 {
break
}
select {
case result := <-resultChannel:
counter--
if result.err != nil {
return nil, result.err
}
measuredValues = append(measuredValues, result.measuredValues...)
}
2019-02-24 21:46:36 +00:00
}
return types.SelectMeasuredValues(measuredValueType, measuredValues), nil
}