videoplayer/handler/device.go

109 lines
2.5 KiB
Go
Raw Normal View History

package handler
import (
"github.com/gin-gonic/gin"
"net/http"
"videoplayer/service"
)
2024-05-20 11:16:53 +08:00
type DeviceAddReq struct {
DeviceName string `json:"device_name"`
DeviceIP string `json:"device_ip"`
DeviceStatus string `json:"device_status"`
AuthID int `json:"auth_id"`
DeviceInfo string `json:"device_info"`
DeviceType string `json:"device_type"`
DeviceLocation string `json:"device_location"`
}
type DeviceStatus struct {
IP string `json:"ip"`
Status string `json:"status"`
ID int `json:"id"`
}
func SetUpDeviceGroup(router *gin.Engine) {
2024-05-20 11:16:53 +08:00
deviceGroup := router.Group("/device")
deviceGroup.POST("/get_device_list", GetDeviceList)
deviceGroup.POST("/restart", RestartDevice)
deviceGroup.POST("/add_device", AddDevice)
deviceGroup.POST("/set_device_status", SetDeviceStatus)
}
func SetDeviceStatus(c *gin.Context) {
var req DeviceStatus
if err := c.ShouldBindJSON(&req); err == nil {
if req.IP != "" {
if service.SetDeviceStatus(req.Status, req.ID, c.GetInt("id")) {
c.JSON(200, gin.H{"code": 0, "message": "success"})
} else {
c.JSON(400, gin.H{"code": 1, "message": "failed"})
}
}
}
c.JSON(400, gin.H{"code": 1, "message": "failed"})
}
func AddDevice(c *gin.Context) {
var req DeviceAddReq
if err := c.ShouldBindJSON(&req); err == nil {
user_id := c.GetInt("id")
device_id := service.AddDevice(req.DeviceName, req.DeviceIP, req.DeviceStatus, req.DeviceInfo, req.DeviceType, req.DeviceLocation, user_id)
if device_id != 0 {
c.JSON(200, gin.H{
"code": 0,
"message": "success",
"device_id": device_id,
})
} else {
c.JSON(400, gin.H{
"code": 1,
"message": "failed",
})
}
} else {
c.JSON(400, gin.H{
"code": 1,
"message": "failed",
})
}
}
func GetDeviceList(c *gin.Context) {
devices := service.GetDeviceList(c.GetInt("id"))
c.JSON(200, gin.H{
"code": 0,
"message": "success",
"devices": devices,
})
}
func RestartDevice(c *gin.Context) {
user_id := c.GetInt("id")
device_id := c.GetInt("device_id")
device := service.GetDevice(device_id, user_id)
if device.ID != 0 {
if device.DeviceIP != "" {
if Restart(device.DeviceIP) {
c.JSON(200, gin.H{"code": 0, "message": "success"})
} else {
c.JSON(400, gin.H{"code": 1, "message": "failed"})
}
}
}
c.JSON(400, gin.H{"code": 1, "message": "failed"})
}
func Restart(ip string) bool {
url := "http://" + ip + "/restart"
resp, err := http.Get(url)
if err != nil {
return false
}
defer resp.Body.Close()
if resp.StatusCode == 200 {
return true
}
return false
}