PKGBUILD/pkg/sensor/ds18b20.go

109 lines
2.4 KiB
Go
Raw Normal View History

2019-02-22 12:08:58 +00:00
package sensor
import (
"context"
2019-02-22 12:08:58 +00:00
"fmt"
"io/ioutil"
"path/filepath"
"strconv"
"strings"
"sync"
"time"
2019-02-22 12:08:58 +00:00
2019-08-20 19:37:45 +00:00
"github.com/go-flucky/flucky/pkg/internal/format"
2019-06-15 13:58:41 +00:00
"github.com/go-flucky/flucky/pkg/types"
2019-02-22 12:08:58 +00:00
uuid "github.com/satori/go.uuid"
)
// DS18B20 is a sensor to measure humidity and temperature.
2019-02-22 12:08:58 +00:00
type DS18B20 struct {
*types.Sensor
}
func (s *DS18B20) ID() string {
return s.SensorID
}
// Read measured values
func (s *DS18B20) Read() ([]*types.MeasuredValue, error) {
2019-02-22 12:08:58 +00:00
2019-06-27 07:17:34 +00:00
if s.WireID == nil {
return nil, fmt.Errorf("WireID is not specified for sensor %v", s.Name())
}
data, err := ioutil.ReadFile(filepath.Join("/sys/bus/w1/devices", *s.WireID, "/w1_slave"))
2019-02-22 12:08:58 +00:00
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, errorReadData
}
c, err := strconv.ParseFloat(raw[i+2:len(raw)-1], 64)
if err != nil {
return nil, errorParseData
2019-02-22 12:08:58 +00:00
}
temperatureValue := c / 1000
measuredValues := []*types.MeasuredValue{
&types.MeasuredValue{
ID: uuid.NewV4().String(),
Value: float64(temperatureValue),
ValueType: types.MeasuredValueTypeTemperature,
2019-08-20 19:37:45 +00:00
FromDate: format.FormatedTime(),
TillDate: format.FormatedTime(),
SensorID: s.SensorID,
},
2019-02-22 12:08:58 +00:00
}
return measuredValues, nil
2019-02-22 12:08:58 +00:00
}
// ReadChannel reads the measured values from the sensor and writes them to a
// channel.
func (s *DS18B20) ReadChannel(measuredValueChannel chan<- *types.MeasuredValue, errorChannel chan<- error, wg *sync.WaitGroup) {
if wg != nil {
defer wg.Done()
}
measuredValues, err := s.Read()
if err != nil {
errorChannel <- err
return
}
for _, measuredValue := range measuredValues {
measuredValueChannel <- measuredValue
}
}
// ReadContinously reads the measured values continously from the sensor and
// writes them to a channel.
func (s *DS18B20) ReadContinously(ctx context.Context, measuredValueChannel chan<- *types.MeasuredValue, errorChannel chan<- error) {
for {
select {
case <-ctx.Done():
errorChannel <- fmt.Errorf("%v: Context closed: %v", s.SensorName, ctx.Err())
return
default:
s.ReadChannel(measuredValueChannel, errorChannel, nil)
}
}
}
// Ticker returns a new ticker, which tick every when the sensor should be read
func (s *DS18B20) Ticker() *time.Ticker {
duration, err := time.ParseDuration(s.TickDuration)
if err != nil {
duration = time.Minute
}
return time.NewTicker(duration)
}