PKGBUILD/pkg/sensor/sensor.go

116 lines
2.5 KiB
Go
Raw Normal View History

package sensor
2019-02-24 21:46:36 +00:00
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
2018-11-28 17:07:20 +00:00
}
2019-02-24 21:46:36 +00:00
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
}
}
}