103 lines
2.5 KiB
Go
103 lines
2.5 KiB
Go
package controllers
|
|
|
|
import (
|
|
"errors"
|
|
"hr_receiver/models"
|
|
"hr_receiver/mqtt"
|
|
"hr_receiver/util"
|
|
"net/http"
|
|
"strings"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
"github.com/gorilla/websocket"
|
|
)
|
|
|
|
type SystemDebugController struct{}
|
|
|
|
type mqttDebugStartRequest struct {
|
|
PersistToDatabase bool `json:"persistToDatabase"`
|
|
}
|
|
|
|
var debugUpgrader = websocket.Upgrader{
|
|
CheckOrigin: func(r *http.Request) bool {
|
|
return true
|
|
},
|
|
}
|
|
|
|
func NewSystemDebugController() *SystemDebugController {
|
|
return &SystemDebugController{}
|
|
}
|
|
|
|
func (sc *SystemDebugController) MqttStatus(c *gin.Context) {
|
|
service := mqtt.GetDebugService()
|
|
if service == nil {
|
|
writeError(c, http.StatusServiceUnavailable, "mqtt debug service unavailable")
|
|
return
|
|
}
|
|
writeSuccess(c, http.StatusOK, "query success", service.Status())
|
|
}
|
|
|
|
func (sc *SystemDebugController) StartMqtt(c *gin.Context) {
|
|
service := mqtt.GetDebugService()
|
|
if service == nil {
|
|
writeError(c, http.StatusServiceUnavailable, "mqtt debug service unavailable")
|
|
return
|
|
}
|
|
var payload mqttDebugStartRequest
|
|
if err := c.ShouldBindJSON(&payload); err != nil && !errors.Is(err, http.ErrBodyNotAllowed) {
|
|
writeError(c, http.StatusBadRequest, err.Error())
|
|
return
|
|
}
|
|
if err := service.Start(payload.PersistToDatabase); err != nil {
|
|
writeError(c, http.StatusInternalServerError, err.Error())
|
|
return
|
|
}
|
|
writeSuccess(c, http.StatusOK, "start success", service.Status())
|
|
}
|
|
|
|
func (sc *SystemDebugController) StopMqtt(c *gin.Context) {
|
|
service := mqtt.GetDebugService()
|
|
if service == nil {
|
|
writeError(c, http.StatusServiceUnavailable, "mqtt debug service unavailable")
|
|
return
|
|
}
|
|
service.Stop()
|
|
writeSuccess(c, http.StatusOK, "stop success", service.Status())
|
|
}
|
|
|
|
func (sc *SystemDebugController) MqttWebSocket(c *gin.Context) {
|
|
service := mqtt.GetDebugService()
|
|
if service == nil {
|
|
c.JSON(http.StatusServiceUnavailable, gin.H{"error": "mqtt debug service unavailable"})
|
|
return
|
|
}
|
|
|
|
token := strings.TrimSpace(c.Query("token"))
|
|
if token == "" {
|
|
c.JSON(http.StatusUnauthorized, gin.H{"error": "missing token"})
|
|
return
|
|
}
|
|
claims, err := util.ParseToken(token)
|
|
if err != nil {
|
|
c.JSON(http.StatusUnauthorized, gin.H{"error": "invalid token"})
|
|
return
|
|
}
|
|
if claims.Role != models.UserRoleSuperAdmin {
|
|
c.JSON(http.StatusForbidden, gin.H{"error": "super admin required"})
|
|
return
|
|
}
|
|
|
|
conn, err := debugUpgrader.Upgrade(c.Writer, c.Request, nil)
|
|
if err != nil {
|
|
return
|
|
}
|
|
service.AddSubscriber(conn)
|
|
defer service.RemoveSubscriber(conn)
|
|
|
|
for {
|
|
if _, _, err := conn.ReadMessage(); err != nil {
|
|
break
|
|
}
|
|
}
|
|
}
|