PKGBUILD/pkg/sensor/ds18b20.go

70 lines
1.5 KiB
Go
Raw Permalink Normal View History

2019-02-22 12:08:58 +00:00
package sensor
import (
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strconv"
"strings"
"sync"
2019-02-22 12:08:58 +00:00
2020-06-10 19:13:05 +00:00
"git.cryptic.systems/volker.raschek/flucky/pkg/internal/format"
"git.cryptic.systems/volker.raschek/flucky/pkg/types"
uuid "github.com/satori/go.uuid"
2019-02-22 12:08:58 +00:00
)
// DS18B20 is a sensor to measure humidity and temperature.
2019-02-22 12:08:58 +00:00
type DS18B20 struct {
*types.Sensor
mutex *sync.Mutex
2019-02-22 12:08:58 +00:00
}
// 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")
}
2019-02-22 12:08:58 +00:00
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)
2019-06-27 07:17:34 +00:00
}
2021-05-16 21:02:46 +00:00
/* #nosec */
data, err := ioutil.ReadFile(socketPath)
2019-02-22 12:08:58 +00:00
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
2019-02-22 12:08:58 +00:00
}
temperatureValue := c / 1000
measuredValues := []*types.MeasuredValue{
{
ID: uuid.NewV4().String(),
Value: float64(temperatureValue),
ValueType: types.Temperature,
Date: format.FormatedTime(),
SensorID: ds18b20.ID,
},
2019-02-22 12:08:58 +00:00
}
return measuredValues, nil
}