73 lines
1.6 KiB
Go
73 lines
1.6 KiB
Go
package services
|
|
|
|
import (
|
|
"database/sql"
|
|
"time"
|
|
)
|
|
|
|
type SensorValuesService struct {
|
|
ctx *Context
|
|
}
|
|
|
|
type sensorValue struct {
|
|
Timestamp int64 `json:"timestamp"`
|
|
Value float64 `json:"value"`
|
|
}
|
|
|
|
func (s *SensorValuesService) Push(sensorId int64, value float64) (int64, error) {
|
|
res, err := s.ctx.DB.Exec("INSERT INTO sensor_values (timestamp, sensor_id, value) VALUES (?, ?, ?)", time.Now().Unix(), sensorId, value)
|
|
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
|
|
return res.LastInsertId()
|
|
}
|
|
|
|
func (s *SensorValuesService) GetList(sensorId int64, from int64, to int64) ([]sensorValue, error) {
|
|
var value float64
|
|
var timestamp int64
|
|
values := make([]sensorValue, 0)
|
|
|
|
rows, err := s.ctx.DB.Query("SELECT timestamp, value FROM sensor_values WHERE sensor_id = ? AND timestamp > ? AND timestamp < ? ORDER BY timestamp ASC", sensorId, from, to)
|
|
|
|
if err != nil {
|
|
if err == sql.ErrNoRows {
|
|
return values, nil
|
|
}
|
|
|
|
return nil, err
|
|
}
|
|
|
|
defer rows.Close()
|
|
|
|
for rows.Next() {
|
|
err := rows.Scan(×tamp, &value)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
values = append(values, sensorValue{Timestamp: timestamp, Value: value})
|
|
}
|
|
|
|
err = rows.Err()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return values, nil
|
|
}
|
|
|
|
func (s *SensorValuesService) GetLatest(sensorId int64, to int64) (*sensorValue, error) {
|
|
var value = sensorValue{}
|
|
|
|
row := s.ctx.DB.QueryRow("SELECT timestamp, value FROM sensor_values WHERE sensor_id = ? AND timestamp < ? ORDER BY timestamp DESC LIMIT 1", sensorId, to)
|
|
|
|
err := row.Scan(&value.Timestamp, &value.Value)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return &value, nil
|
|
}
|