package sensor import ( "fmt" "io/ioutil" "os" "path/filepath" "strconv" "strings" "sync" "git.cryptic.systems/volker.raschek/flucky/pkg/internal/format" "git.cryptic.systems/volker.raschek/flucky/pkg/types" uuid "github.com/satori/go.uuid" ) // DS18B20 is a sensor to measure humidity and temperature. type DS18B20 struct { *types.Sensor mutex *sync.Mutex } // Read measured values func (ds18b20 *DS18B20) Read() ([]*types.MeasuredValue, error) { // Lock multiple access ds18b20.mutex.Lock() defer ds18b20.mutex.Unlock() if ds18b20.WireID == nil { return nil, fmt.Errorf("WireID is not specified") } socketPath := filepath.Join("/sys/bus/w1/devices", *ds18b20.WireID, "/w1_slave") if _, err := os.Stat(socketPath); os.IsNotExist(err) { return nil, fmt.Errorf("Socket path not found: %v", socketPath) } data, err := ioutil.ReadFile(socketPath) if err != nil { return nil, fmt.Errorf("Can not read data from sensor %v", ds18b20.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{ { ID: uuid.NewV4().String(), Value: float64(temperatureValue), ValueType: "temperature", Date: format.FormatedTime(), SensorID: ds18b20.ID, }, } return measuredValues, nil }