113 lines
2.0 KiB
Go
113 lines
2.0 KiB
Go
package routes
|
|
|
|
import (
|
|
"basic-sensor-receiver/app"
|
|
"database/sql"
|
|
"net/http"
|
|
"strconv"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
)
|
|
|
|
type postSensorValueBody struct {
|
|
Value float64 `json:"value"`
|
|
}
|
|
|
|
type getSensorValuesQuery struct {
|
|
From int64 `form:"from"`
|
|
To int64 `form:"to"`
|
|
}
|
|
|
|
type getLatestSensorValueQuery struct {
|
|
To int64 `form:"to"`
|
|
}
|
|
|
|
func PostSensorValues(s *app.Server) gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
var newValue postSensorValueBody
|
|
|
|
if err := c.BindJSON(&newValue); err != nil {
|
|
c.AbortWithError(400, err)
|
|
return
|
|
}
|
|
|
|
sensorId, err := getSensorId(c)
|
|
|
|
if err != nil {
|
|
c.AbortWithError(400, err)
|
|
return
|
|
}
|
|
|
|
if _, err := s.Services.SensorValues.Push(sensorId, newValue.Value); err != nil {
|
|
c.AbortWithError(400, err)
|
|
return
|
|
}
|
|
|
|
c.JSON(http.StatusCreated, newValue)
|
|
}
|
|
}
|
|
|
|
func GetSensorValues(s *app.Server) gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
var query getSensorValuesQuery
|
|
|
|
sensorId, err := getSensorId(c)
|
|
|
|
if err != nil {
|
|
c.AbortWithError(400, err)
|
|
return
|
|
}
|
|
|
|
if err := c.BindQuery(&query); err != nil {
|
|
c.AbortWithError(500, err)
|
|
return
|
|
}
|
|
|
|
values, err := s.Services.SensorValues.GetList(sensorId, query.From, query.To)
|
|
|
|
if err != nil {
|
|
c.AbortWithError(500, err)
|
|
return
|
|
}
|
|
c.JSON(http.StatusOK, values)
|
|
}
|
|
}
|
|
|
|
func GetSensorLatestValue(s *app.Server) gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
var query getLatestSensorValueQuery
|
|
|
|
sensorId, err := getSensorId(c)
|
|
|
|
if err != nil {
|
|
c.AbortWithError(400, err)
|
|
return
|
|
}
|
|
|
|
if err := c.BindQuery(&query); err != nil {
|
|
c.AbortWithError(500, err)
|
|
return
|
|
}
|
|
|
|
value, err := s.Services.SensorValues.GetLatest(sensorId, query.To)
|
|
|
|
if err != nil {
|
|
if err == sql.ErrNoRows {
|
|
c.AbortWithError(404, err)
|
|
return
|
|
}
|
|
|
|
c.AbortWithError(500, err)
|
|
return
|
|
}
|
|
|
|
c.JSON(http.StatusOK, value)
|
|
}
|
|
}
|
|
|
|
func getSensorId(c *gin.Context) (int64, error) {
|
|
sensor := c.Param("sensor")
|
|
|
|
return strconv.ParseInt(sensor, 10, 64)
|
|
}
|