PKGBUILD/pkg/sensor/ds18b20.go
Markus Pesch 43e9d00dcb
fix: implement repository test
changes:
- Implement repository test for the sqlite backend
- Add testutils package to start container images
- Remove deprecated till_date in measured values
- Renamed columns of the table humidities, pressures and temperatures
2020-06-01 00:56:04 +02:00

70 lines
1.4 KiB
Go

package sensor
import (
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strconv"
"strings"
"sync"
uuid "github.com/satori/go.uuid"
"github.com/volker-raschek/flucky/pkg/internal/format"
"github.com/volker-raschek/flucky/pkg/types"
)
// 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
}