package sensor import ( "fmt" "io/ioutil" "path/filepath" "strconv" "strings" "time" "github.com/go-flucky/flucky/pkg/internal/format" "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 } // GetID returns the sensor id func (s *DS18B20) GetID() string { return s.ID } // GetTicker returns a new ticker, which tick every when the sensor should be read func (s *DS18B20) GetTicker() *time.Ticker { duration, err := time.ParseDuration(s.TickDuration) if err != nil { duration = time.Minute } return time.NewTicker(duration) } // Read measured values func (s *DS18B20) Read() ([]*types.MeasuredValue, error) { 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")) if err != nil { return nil, fmt.Errorf("Can not read data from sensor %v", s.Name) } 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 } temperatureValue := c / 1000 measuredValues := []*types.MeasuredValue{ &types.MeasuredValue{ ID: uuid.NewV4().String(), Value: float64(temperatureValue), ValueType: types.MeasuredValueTypeTemperature, FromDate: format.FormatedTime(), TillDate: format.FormatedTime(), SensorID: s.ID, }, } return measuredValues, nil }