graphicek/server/routes/mqtt.go

48 lines
1.0 KiB
Go
Raw Normal View History

2024-04-01 17:26:30 +02:00
package routes
import (
"basic-sensor-receiver/app"
"net/http"
"github.com/gin-gonic/gin"
)
type putMQTTPublishBody struct {
Server string `json:"server" binding:"required"`
2024-04-01 17:57:41 +02:00
ClientId string `json:"clientId"`
2024-04-01 17:26:30 +02:00
Username string `json:"username"`
Password string `json:"password"`
Retain *bool `json:"retain"`
Qos *float64 `json:"qos"`
Topic string `json:"topic" binding:"required"`
Message string `json:"message" binding:"required"`
}
func PutMQTTPublish(s *app.Server) gin.HandlerFunc {
return func(c *gin.Context) {
body := putMQTTPublishBody{}
if err := bindJSONBodyOrAbort(c, &body); err != nil {
return
}
qos := byte(0)
retain := false
if body.Retain != nil {
retain = *body.Retain
}
if body.Qos != nil {
qos = byte(*body.Qos)
}
if err := s.Services.MQTT.Publish(body.Server, body.Username, body.Password, body.ClientId, retain, qos, body.Topic, body.Message); err != nil {
c.AbortWithError(500, err)
return
}
c.Writer.WriteHeader(http.StatusOK)
}
}