91 lines
2.0 KiB
Go
91 lines
2.0 KiB
Go
package sensor
|
|
|
|
import (
|
|
"fmt"
|
|
"sync"
|
|
|
|
"github.com/d2r2/go-bsbmp"
|
|
"github.com/d2r2/go-i2c"
|
|
"github.com/d2r2/go-logger"
|
|
uuid "github.com/satori/go.uuid"
|
|
|
|
"git.cryptic.systems/volker.raschek/flucky/pkg/internal/format"
|
|
"git.cryptic.systems/volker.raschek/flucky/pkg/types"
|
|
)
|
|
|
|
// BME280 is a sensor to measure humidity and temperature.
|
|
type BME280 struct {
|
|
*types.Sensor
|
|
mutex *sync.Mutex
|
|
}
|
|
|
|
// Read measured values
|
|
func (bme280 *BME280) Read() ([]*types.MeasuredValue, error) {
|
|
|
|
// Lock multiple access
|
|
bme280.mutex.Lock()
|
|
defer bme280.mutex.Unlock()
|
|
|
|
// Create new connection to i2c-bus on 1 line with address 0x76.
|
|
// Use i2cdetect utility to find device address over the i2c-bus
|
|
i2c, err := i2c.NewI2C(*bme280.I2CAddress, *bme280.I2CBus)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer i2c.Close()
|
|
|
|
// Reduce loglevel
|
|
for _, pkg := range []string{"bsbmp", "i2c"} {
|
|
err = logger.ChangePackageLogLevel(pkg, logger.InfoLevel)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("Failed to change package log level: %v", err)
|
|
}
|
|
}
|
|
|
|
sensor, err := bsbmp.NewBMP(bsbmp.BME280, i2c)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
temperatureValue, err := sensor.ReadTemperatureC(bsbmp.ACCURACY_STANDARD)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
pressureValue, err := sensor.ReadPressurePa(bsbmp.ACCURACY_STANDARD)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
_, humidityValue, err := sensor.ReadHumidityRH(bsbmp.ACCURACY_STANDARD)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
measuredValues := []*types.MeasuredValue{
|
|
{
|
|
ID: uuid.NewV4().String(),
|
|
Value: float64(humidityValue),
|
|
ValueType: "humidity",
|
|
Date: format.FormatedTime(),
|
|
SensorID: bme280.ID,
|
|
},
|
|
{
|
|
ID: uuid.NewV4().String(),
|
|
Value: float64(pressureValue),
|
|
ValueType: "pressure",
|
|
Date: format.FormatedTime(),
|
|
SensorID: bme280.ID,
|
|
},
|
|
{
|
|
ID: uuid.NewV4().String(),
|
|
Value: float64(temperatureValue),
|
|
ValueType: "temperature",
|
|
Date: format.FormatedTime(),
|
|
SensorID: bme280.ID,
|
|
},
|
|
}
|
|
|
|
return measuredValues, nil
|
|
}
|