Files
pig-farm-controller/internal/app/controller/device/device_controller.go

332 lines
12 KiB
Go
Raw Normal View History

2025-09-12 17:18:14 +08:00
package device
import (
2025-09-20 17:11:04 +08:00
"encoding/json"
2025-09-12 17:18:14 +08:00
"errors"
2025-09-20 17:11:04 +08:00
"fmt"
2025-09-12 17:18:14 +08:00
"strconv"
"strings"
2025-09-12 17:43:42 +08:00
"time"
2025-09-12 17:18:14 +08:00
"git.huangwc.com/pig/pig-farm-controller/internal/app/controller"
"git.huangwc.com/pig/pig-farm-controller/internal/infra/logs"
"git.huangwc.com/pig/pig-farm-controller/internal/infra/models"
"git.huangwc.com/pig/pig-farm-controller/internal/infra/repository"
"github.com/gin-gonic/gin"
"gorm.io/gorm"
)
// Controller 设备控制器,封装了所有与设备相关的业务逻辑
type Controller struct {
repo repository.DeviceRepository
logger *logs.Logger
}
// NewController 创建一个新的设备控制器实例
func NewController(repo repository.DeviceRepository, logger *logs.Logger) *Controller {
return &Controller{
repo: repo,
logger: logger,
}
}
2025-09-12 17:43:42 +08:00
// --- Request DTOs ---
2025-09-12 17:18:14 +08:00
// CreateDeviceRequest 定义了创建设备时需要传入的参数
type CreateDeviceRequest struct {
2025-09-20 17:11:04 +08:00
Name string `json:"name" binding:"required"`
Type models.DeviceType `json:"type" binding:"required"`
SubType models.DeviceSubType `json:"sub_type,omitempty"`
ParentID *uint `json:"parent_id,omitempty"`
Location string `json:"location,omitempty"`
Properties map[string]interface{} `json:"properties,omitempty"`
2025-09-12 17:18:14 +08:00
}
// UpdateDeviceRequest 定义了更新设备时需要传入的参数
type UpdateDeviceRequest struct {
2025-09-20 17:11:04 +08:00
Name string `json:"name" binding:"required"`
Type models.DeviceType `json:"type" binding:"required"`
SubType models.DeviceSubType `json:"sub_type,omitempty"`
ParentID *uint `json:"parent_id,omitempty"`
Location string `json:"location,omitempty"`
Properties map[string]interface{} `json:"properties,omitempty"`
2025-09-12 17:43:42 +08:00
}
// --- Response DTOs ---
// DeviceResponse 定义了返回给客户端的单个设备信息的结构
type DeviceResponse struct {
2025-09-20 17:11:04 +08:00
ID uint `json:"id"`
Name string `json:"name"`
Type models.DeviceType `json:"type"`
SubType models.DeviceSubType `json:"sub_type"`
ParentID *uint `json:"parent_id"`
Location string `json:"location"`
Properties map[string]interface{} `json:"properties"`
CreatedAt string `json:"created_at"`
UpdatedAt string `json:"updated_at"`
2025-09-12 17:43:42 +08:00
}
// --- DTO 转换函数 ---
// newDeviceResponse 从数据库模型创建一个新的设备响应 DTO
2025-09-20 17:11:04 +08:00
func newDeviceResponse(device *models.Device) (*DeviceResponse, error) {
2025-09-12 17:43:42 +08:00
if device == nil {
2025-09-20 17:11:04 +08:00
return nil, nil
2025-09-12 17:43:42 +08:00
}
2025-09-20 17:11:04 +08:00
var props map[string]interface{}
if len(device.Properties) > 0 && string(device.Properties) != "null" {
if err := device.ParseProperties(&props); err != nil {
2025-09-20 17:11:04 +08:00
return nil, fmt.Errorf("解析设备属性失败 (ID: %d): %w", device.ID, err)
}
}
2025-09-12 17:43:42 +08:00
return &DeviceResponse{
ID: device.ID,
Name: device.Name,
Type: device.Type,
SubType: device.SubType,
ParentID: device.ParentID,
Location: device.Location,
2025-09-20 17:11:04 +08:00
Properties: props,
2025-09-12 17:43:42 +08:00
CreatedAt: device.CreatedAt.Format(time.RFC3339),
UpdatedAt: device.UpdatedAt.Format(time.RFC3339),
2025-09-20 17:11:04 +08:00
}, nil
2025-09-12 17:43:42 +08:00
}
// newListDeviceResponse 从数据库模型切片创建一个新的设备列表响应 DTO 切片
2025-09-20 17:11:04 +08:00
func newListDeviceResponse(devices []*models.Device) ([]*DeviceResponse, error) {
2025-09-12 17:43:42 +08:00
list := make([]*DeviceResponse, 0, len(devices))
for _, device := range devices {
2025-09-20 17:11:04 +08:00
resp, err := newDeviceResponse(device)
if err != nil {
return nil, err
}
list = append(list, resp)
2025-09-12 17:43:42 +08:00
}
2025-09-20 17:11:04 +08:00
return list, nil
2025-09-12 17:18:14 +08:00
}
// --- Controller Methods ---
// CreateDevice godoc
// @Summary 创建新设备
2025-09-12 17:43:42 +08:00
// @Description 根据提供的信息创建一个新设备
2025-09-12 17:18:14 +08:00
// @Tags 设备管理
// @Accept json
// @Produce json
// @Param device body CreateDeviceRequest true "设备信息"
2025-09-19 23:51:13 +08:00
// @Success 200 {object} controller.Response{data=DeviceResponse}
2025-09-19 15:55:56 +08:00
// @Router /api/v1/devices [post]
2025-09-12 17:18:14 +08:00
func (c *Controller) CreateDevice(ctx *gin.Context) {
var req CreateDeviceRequest
if err := ctx.ShouldBindJSON(&req); err != nil {
c.logger.Errorf("创建设备: 参数绑定失败: %v", err)
2025-09-28 01:23:50 +08:00
controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, err.Error(), "创建设备", "请求体绑定失败", req)
2025-09-12 17:18:14 +08:00
return
}
2025-09-20 17:11:04 +08:00
propertiesJSON, err := json.Marshal(req.Properties)
if err != nil {
c.logger.Errorf("创建设备: 序列化属性失败: %v", err)
2025-09-28 01:23:50 +08:00
controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "属性字段格式错误", "创建设备", "属性序列化失败", req.Properties)
2025-09-20 17:11:04 +08:00
return
}
2025-09-12 17:18:14 +08:00
device := &models.Device{
Name: req.Name,
Type: req.Type,
SubType: req.SubType,
ParentID: req.ParentID,
Location: req.Location,
2025-09-20 17:11:04 +08:00
Properties: propertiesJSON,
2025-09-12 17:18:14 +08:00
}
// 在创建设备前进行自检
if !device.SelfCheck() {
c.logger.Errorf("创建设备: 设备属性自检失败: %v", device)
2025-09-28 01:23:50 +08:00
controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "设备属性不符合要求", "创建设备", "设备属性自检失败", device)
return
}
2025-09-12 17:18:14 +08:00
if err := c.repo.Create(device); err != nil {
c.logger.Errorf("创建设备: 数据库操作失败: %v", err)
2025-09-28 01:23:50 +08:00
controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "创建设备失败", "创建设备", "数据库创建失败", device)
2025-09-12 17:18:14 +08:00
return
}
2025-09-20 17:11:04 +08:00
resp, err := newDeviceResponse(device)
if err != nil {
c.logger.Errorf("创建设备: 序列化响应失败: %v", err)
2025-09-28 01:23:50 +08:00
controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "设备创建成功,但响应生成失败", "创建设备", "响应序列化失败", device)
2025-09-20 17:11:04 +08:00
return
}
2025-09-28 01:23:50 +08:00
controller.SendSuccessWithAudit(ctx, controller.CodeCreated, "设备创建成功", resp, "创建设备", "设备创建成功", resp)
2025-09-12 17:18:14 +08:00
}
// GetDevice godoc
// @Summary 获取设备信息
// @Description 根据设备ID获取单个设备的详细信息
// @Tags 设备管理
// @Produce json
// @Param id path string true "设备ID"
2025-09-19 23:51:13 +08:00
// @Success 200 {object} controller.Response{data=DeviceResponse}
2025-09-19 15:55:56 +08:00
// @Router /api/v1/devices/{id} [get]
2025-09-12 17:18:14 +08:00
func (c *Controller) GetDevice(ctx *gin.Context) {
deviceID := ctx.Param("id")
device, err := c.repo.FindByIDString(deviceID)
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
2025-09-28 01:23:50 +08:00
controller.SendErrorWithAudit(ctx, controller.CodeNotFound, "设备未找到", "获取设备", "设备不存在", deviceID)
2025-09-12 17:18:14 +08:00
return
}
if strings.Contains(err.Error(), "无效的设备ID格式") {
2025-09-28 01:23:50 +08:00
controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, err.Error(), "获取设备", "设备ID格式错误", deviceID)
2025-09-12 17:18:14 +08:00
return
}
c.logger.Errorf("获取设备: 数据库操作失败: %v", err)
2025-09-28 01:23:50 +08:00
controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "获取设备信息失败", "获取设备", "数据库查询失败", deviceID)
2025-09-12 17:18:14 +08:00
return
}
2025-09-20 17:11:04 +08:00
resp, err := newDeviceResponse(device)
if err != nil {
c.logger.Errorf("获取设备: 序列化响应失败: %v", err)
2025-09-28 01:23:50 +08:00
controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "获取设备信息失败: 内部数据格式错误", "获取设备", "响应序列化失败", device)
2025-09-20 17:11:04 +08:00
return
}
2025-09-28 01:23:50 +08:00
controller.SendSuccessWithAudit(ctx, controller.CodeSuccess, "获取设备信息成功", resp, "获取设备", "获取设备信息成功", resp)
2025-09-12 17:18:14 +08:00
}
// ListDevices godoc
// @Summary 获取设备列表
// @Description 获取系统中所有设备的列表
// @Tags 设备管理
// @Produce json
2025-09-19 23:51:13 +08:00
// @Success 200 {object} controller.Response{data=[]DeviceResponse}
2025-09-19 15:55:56 +08:00
// @Router /api/v1/devices [get]
2025-09-12 17:18:14 +08:00
func (c *Controller) ListDevices(ctx *gin.Context) {
devices, err := c.repo.ListAll()
if err != nil {
c.logger.Errorf("获取设备列表: 数据库操作失败: %v", err)
2025-09-28 01:23:50 +08:00
controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "获取设备列表失败", "获取设备列表", "数据库查询失败", nil)
2025-09-12 17:18:14 +08:00
return
}
2025-09-20 17:11:04 +08:00
resp, err := newListDeviceResponse(devices)
if err != nil {
c.logger.Errorf("获取设备列表: 序列化响应失败: %v", err)
2025-09-28 01:23:50 +08:00
controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "获取设备列表失败: 内部数据格式错误", "获取设备列表", "响应序列化失败", devices)
2025-09-20 17:11:04 +08:00
return
}
2025-09-28 01:23:50 +08:00
controller.SendSuccessWithAudit(ctx, controller.CodeSuccess, "获取设备列表成功", resp, "获取设备列表", "获取设备列表成功", resp)
2025-09-12 17:18:14 +08:00
}
// UpdateDevice godoc
// @Summary 更新设备信息
// @Description 根据设备ID更新一个已存在的设备信息
// @Tags 设备管理
// @Accept json
// @Produce json
// @Param id path string true "设备ID"
// @Param device body UpdateDeviceRequest true "要更新的设备信息"
2025-09-19 23:51:13 +08:00
// @Success 200 {object} controller.Response{data=DeviceResponse}
2025-09-19 15:55:56 +08:00
// @Router /api/v1/devices/{id} [put]
2025-09-12 17:18:14 +08:00
func (c *Controller) UpdateDevice(ctx *gin.Context) {
deviceID := ctx.Param("id")
// 1. 检查设备是否存在
existingDevice, err := c.repo.FindByIDString(deviceID)
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
2025-09-28 01:23:50 +08:00
controller.SendErrorWithAudit(ctx, controller.CodeNotFound, "设备未找到", "更新设备", "设备不存在", deviceID)
2025-09-12 17:18:14 +08:00
return
}
if strings.Contains(err.Error(), "无效的设备ID格式") {
2025-09-28 01:23:50 +08:00
controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, err.Error(), "更新设备", "设备ID格式错误", deviceID)
2025-09-12 17:18:14 +08:00
return
}
c.logger.Errorf("更新设备: 查找设备失败: %v", err)
2025-09-28 01:23:50 +08:00
controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "更新设备失败", "更新设备", "数据库查询失败", deviceID)
2025-09-12 17:18:14 +08:00
return
}
// 2. 绑定请求参数
var req UpdateDeviceRequest
if err := ctx.ShouldBindJSON(&req); err != nil {
c.logger.Errorf("更新设备: 参数绑定失败: %v", err)
2025-09-28 01:23:50 +08:00
controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, err.Error(), "更新设备", "请求体绑定失败", req)
2025-09-12 17:18:14 +08:00
return
}
2025-09-20 17:11:04 +08:00
propertiesJSON, err := json.Marshal(req.Properties)
if err != nil {
c.logger.Errorf("更新设备: 序列化属性失败: %v", err)
2025-09-28 01:23:50 +08:00
controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "属性字段格式错误", "更新设备", "属性序列化失败", req.Properties)
2025-09-20 17:11:04 +08:00
return
}
2025-09-12 17:51:09 +08:00
// 3. 更新从数据库中查出的现有设备对象的字段
2025-09-12 17:18:14 +08:00
existingDevice.Name = req.Name
existingDevice.Type = req.Type
existingDevice.SubType = req.SubType
existingDevice.ParentID = req.ParentID
existingDevice.Location = req.Location
2025-09-20 17:11:04 +08:00
existingDevice.Properties = propertiesJSON
2025-09-12 17:18:14 +08:00
// 在更新设备前进行自检
if !existingDevice.SelfCheck() {
c.logger.Errorf("更新设备: 设备属性自检失败: %v", existingDevice)
2025-09-28 01:23:50 +08:00
controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "设备属性不符合要求", "更新设备", "设备属性自检失败", existingDevice)
return
}
2025-09-12 17:51:09 +08:00
// 4. 将修改后的 existingDevice 对象保存回数据库
2025-09-12 17:18:14 +08:00
if err := c.repo.Update(existingDevice); err != nil {
c.logger.Errorf("更新设备: 数据库操作失败: %v", err)
2025-09-28 01:23:50 +08:00
controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "更新设备失败", "更新设备", "数据库更新失败", existingDevice)
2025-09-12 17:18:14 +08:00
return
}
2025-09-20 17:11:04 +08:00
resp, err := newDeviceResponse(existingDevice)
if err != nil {
c.logger.Errorf("更新设备: 序列化响应失败: %v", err)
2025-09-28 01:23:50 +08:00
controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "设备更新成功,但响应生成失败", "更新设备", "响应序列化失败", existingDevice)
2025-09-20 17:11:04 +08:00
return
}
2025-09-28 01:23:50 +08:00
controller.SendSuccessWithAudit(ctx, controller.CodeSuccess, "设备更新成功", resp, "更新设备", "设备更新成功", resp)
2025-09-12 17:18:14 +08:00
}
// DeleteDevice godoc
// @Summary 删除设备
// @Description 根据设备ID删除一个设备软删除
// @Tags 设备管理
// @Produce json
// @Param id path string true "设备ID"
2025-09-19 23:51:13 +08:00
// @Success 200 {object} controller.Response
2025-09-19 15:55:56 +08:00
// @Router /api/v1/devices/{id} [delete]
2025-09-12 17:18:14 +08:00
func (c *Controller) DeleteDevice(ctx *gin.Context) {
deviceID := ctx.Param("id")
// 我们需要先将字符串ID转换为uint因为Delete方法需要uint类型
idUint, err := strconv.ParseUint(deviceID, 10, 64)
if err != nil {
2025-09-28 01:23:50 +08:00
controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "无效的设备ID格式", "删除设备", "设备ID格式错误", deviceID)
2025-09-12 17:18:14 +08:00
return
}
if err := c.repo.Delete(uint(idUint)); err != nil {
c.logger.Errorf("删除设备: 数据库操作失败: %v", err)
2025-09-28 01:23:50 +08:00
controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "删除设备失败", "删除设备", "数据库删除失败", deviceID)
2025-09-12 17:18:14 +08:00
return
}
2025-09-28 01:23:50 +08:00
controller.SendSuccessWithAudit(ctx, controller.CodeSuccess, "设备删除成功", nil, "删除设备", "设备删除成功", deviceID)
2025-09-12 17:18:14 +08:00
}