package sensor import ( "sync" "git.cryptic.systems/fh-trier/go-flucky/pkg/internal/errutils" "git.cryptic.systems/fh-trier/go-flucky/pkg/types" ) type HumiditySensor interface { ReadHumidity() (*types.Humidity, error) } type TemperatureSensor interface { ReadTemperature() (*types.Temperature, error) } func ReadHumidities(humiditySensors []HumiditySensor) ([]*types.Humidity, error) { wg := new(sync.WaitGroup) wg.Add(len(humiditySensors)) errChannel := make(chan error, len(humiditySensors)) humidityChannel := make(chan *types.Humidity, len(humiditySensors)) for _, humiditySensor := range humiditySensors { go func(hs HumiditySensor) { defer wg.Done() humidity, err := hs.ReadHumidity() if err != nil { errChannel <- err humidityChannel <- nil } errChannel <- nil humidityChannel <- humidity }(humiditySensor) } wg.Wait() errorList := errutils.CollectErrors(errChannel) if err := errutils.FormatErrors(errorList); err != nil { return nil, err } humidityList := collectHumidities(humidityChannel) return humidityList, nil } func ReadTemperatures(temperatureSensors []TemperatureSensor) ([]*types.Temperature, error) { wg := new(sync.WaitGroup) wg.Add(len(temperatureSensors)) errChannel := make(chan error, len(temperatureSensors)) temperatureChannel := make(chan *types.Temperature, len(temperatureSensors)) for _, temperatureSensor := range temperatureSensors { go func(ts TemperatureSensor) { defer wg.Done() temperature, err := ts.ReadTemperature() if err != nil { errChannel <- err } temperatureChannel <- temperature }(temperatureSensor) } wg.Wait() errorList := errutils.CollectErrors(errChannel) if err := errutils.FormatErrors(errorList); err != nil { return nil, err } temperatureList := collectTemperatures(temperatureChannel) return temperatureList, nil } func collectHumidities(humChan <-chan *types.Humidity) []*types.Humidity { humidityList := make([]*types.Humidity, 0) for { select { case hum, more := <-humChan: if more { humidityList = append(humidityList, hum) continue } return nil default: return humidityList } } } func collectTemperatures(tempChan <-chan *types.Temperature) []*types.Temperature { temperatureList := make([]*types.Temperature, 0) for { select { case temp, more := <-tempChan: if more { temperatureList = append(temperatureList, temp) continue } return nil default: return temperatureList } } }