@@ -61,7 +61,11 @@ func UpdateDeviceByMap(deviceID string, deviceMap map[string]interface{}) (*mode
6161}
6262
6363// 更新设备状态
64- func UpdateDeviceStatus (deviceId string , status int16 ) error {
64+ // 返回值: (是否真的更新了状态, error)
65+ // 如果状态没有变化,返回 (false, nil)
66+ // 如果状态真的更新了,返回 (true, nil)
67+ // 如果发生错误,返回 (false, error)
68+ func UpdateDeviceStatus (deviceId string , status int16 ) (bool , error ) {
6569 // 1. 先从 Redis 缓存读取设备信息,缓存未命中则从数据库加载
6670 var device * model.Device
6771 result , err := global .REDIS .Get (context .Background (), deviceId ).Result ()
@@ -78,15 +82,15 @@ func UpdateDeviceStatus(deviceId string, status int16) error {
7882 device , err = query .Device .Where (query .Device .ID .Eq (deviceId )).First ()
7983 if err != nil {
8084 logrus .WithError (err ).WithField ("device_id" , deviceId ).Error ("Failed to get device info" )
81- return err
85+ return false , err
8286 }
8387 }
8488
8589 // 2. 检查状态是否发生变化,如果没变化则不更新
8690 currentStatus := device .IsOnline
8791 if currentStatus == status {
8892 // 状态未变化,不需要更新
89- return nil
93+ return false , nil
9094 }
9195
9296 // 3. 更新设备状态
@@ -100,20 +104,20 @@ func UpdateDeviceStatus(deviceId string, status int16) error {
100104 })
101105 if err != nil {
102106 logrus .Error (err )
103- return err
107+ return false , err
104108 }
105109 if info .RowsAffected == 0 {
106- return fmt .Errorf ("update device status failed, no rows affected" )
110+ return false , fmt .Errorf ("update device status failed, no rows affected" )
107111 }
108112 } else {
109113 // 设备上线时,只更新is_online字段
110114 info , err := query .Device .Where (query .Device .ID .Eq (deviceId )).Update (query .Device .IsOnline , status )
111115 if err != nil {
112116 logrus .Error (err )
113- return err
117+ return false , err
114118 }
115119 if info .RowsAffected == 0 {
116- return fmt .Errorf ("update device status failed, no rows affected" )
120+ return false , fmt .Errorf ("update device status failed, no rows affected" )
117121 }
118122 }
119123
@@ -133,7 +137,7 @@ func UpdateDeviceStatus(deviceId string, status int16) error {
133137 }
134138 }()
135139
136- return nil
140+ return true , nil
137141}
138142
139143func DeleteDevice (id string , tenantID string ) error {
0 commit comments