issue-18 优化代码(只保证编译通过没检查)

This commit is contained in:
2025-09-26 22:50:08 +08:00
parent d9fe1683d2
commit 23b7f66d74
17 changed files with 767 additions and 251 deletions

View File

@@ -87,6 +87,10 @@ type Device struct {
// Location 描述了设备的物理安装位置,例如 "1号猪舍东侧",方便运维。建立索引以优化按位置查询。
Location string `gorm:"index" json:"location"`
// Command 存储了与设备交互所需的具体指令。
// 例如,对于传感器,这里存储 Modbus 采集指令;对于开关和区域主控,这里可以为空。
Command string `gorm:"type:varchar(255)" json:"command"`
// Properties 用于存储特定类型设备的独有属性采用JSON格式。
// 建议在应用层为不同子类型的设备定义专用的属性结构体(如 LoraProperties, BusProperties以保证数据一致性。
Properties datatypes.JSON `json:"properties"`
@@ -114,26 +118,48 @@ func (d *Device) ParseProperties(v interface{}) error {
// 方法会根据自身类型进行参数检查, 参数不全时返回false
// TODO 没写单测
func (d *Device) SelfCheck() bool {
properties := make(map[string]interface{})
if err := d.ParseProperties(&properties); err != nil {
return false
}
has := func(key string) bool {
_, ok := properties[key]
return ok
}
switch d.SubType {
case SubTypeFan:
if !has(BusNumber) || !has(BusAddress) || !has(RelayChannel) {
// 使用清晰的 switch 结构,确保所有情况都被覆盖
switch d.Type {
case DeviceTypeAreaController:
props := make(map[string]interface{})
if err := d.ParseProperties(&props); err != nil {
return false
}
_, ok := props[LoRaAddress].(string)
return ok
case DeviceTypeDevice:
// 所有普通设备都必须有父级
if d.ParentID == nil || *d.ParentID == 0 {
return false
}
props := make(map[string]interface{})
if err := d.ParseProperties(&props); err != nil {
return false
}
// 检查通用属性是否存在
has := func(key string) bool {
_, ok := props[key]
return ok
}
// 根据子类型进行具体校验
switch d.SubType {
// 所有传感器类型都必须有 Command 和总线信息
case SubTypeSensorTemp, SubTypeSensorHumidity, SubTypeSensorWeight, SubTypeSensorAmmonia:
return d.Command != "" && has(BusNumber) && has(BusAddress)
// 所有开关类型都必须有继电器和总线信息
case SubTypeFan, SubTypeWaterCurtain, SubTypeValveFeed:
return has(BusNumber) && has(BusAddress) && has(RelayChannel)
// 如果是未知的子类型,或者没有子类型,则认为自检失败
default:
return false
}
// 如果设备类型不是已知的任何一种,则自检失败
default:
// 不应该有类型未知的设备
return false
}
return true
}