PKGBUILD/pkg/sensor/ds18b20.go

98 lines
2.2 KiB
Go

package sensor
import (
"context"
"fmt"
"io/ioutil"
"math"
"path/filepath"
"strconv"
"strings"
"sync"
"time"
"github.com/go-flucky/flucky/pkg/types"
uuid "github.com/satori/go.uuid"
)
// DS18B20 is a sensor to measure humidity and temperature.
type DS18B20 struct {
*types.Sensor
}
// GetSensorModel returns the sensor model
func (s *DS18B20) GetSensorModel() types.SensorModel {
return s.Sensor.SensorModel
}
// GetSensor return the sensor struct
func (s *DS18B20) GetSensor() *types.Sensor {
return s.Sensor
}
// ReadTemperature measure the temperature
func (s *DS18B20) ReadTemperature(round float64) (*types.Temperature, error) {
data, err := ioutil.ReadFile(filepath.Join("/sys/bus/w1/devices", *s.WireID, "/w1_slave"))
if err != nil {
return nil, fmt.Errorf("Can not read data from sensor %v", s.SensorName)
}
raw := string(data)
i := strings.LastIndex(raw, "t=")
if i == -1 {
return nil, ErrReadSensor
}
c, err := strconv.ParseFloat(raw[i+2:len(raw)-1], 64)
if err != nil {
return nil, ErrParseData
}
temperatureValue := c / 1000
// round
if round != 0 {
temperatureValue = math.Round(temperatureValue/round) * round
}
temperature := &types.Temperature{
TemperatureID: uuid.NewV4().String(),
TemperatureValue: temperatureValue,
TemperatureFromDate: time.Now(),
TemperatureTillDate: time.Now(),
SensorID: s.SensorID,
}
return temperature, nil
}
// ReadTemperatureWriteIntoChannel and write values into a channel
func (s *DS18B20) ReadTemperatureWriteIntoChannel(round float64, temperatureChannel chan<- *types.Temperature, errorChannel chan<- error, wg *sync.WaitGroup) {
if wg != nil {
defer wg.Done()
}
temperature, err := s.ReadTemperature(round)
if err != nil {
errorChannel <- err
return
}
temperatureChannel <- temperature
}
// ReadTemperatureContinously into a channel until context closed
func (s *DS18B20) ReadTemperatureContinously(ctx context.Context, round float64, temperatureChannel chan<- *types.Temperature, errorChannel chan<- error) {
for {
select {
case <-ctx.Done():
errorChannel <- fmt.Errorf("%v: Context closed: %v", s.SensorName, ctx.Err())
return
default:
s.ReadTemperatureWriteIntoChannel(round, temperatureChannel, errorChannel, nil)
}
}
}