liusuyi
2025-12-05 fc7cd4be1d6335cd3497fe5b1bed1d23eb8d9303
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
package com.ard.work.service.impl;
 
import com.alibaba.fastjson2.JSONObject;
import com.ard.common.annotation.DataScope;
import com.ard.common.constant.CacheConstants;
import com.ard.common.core.redis.RedisCache;
import com.ard.common.exception.ServiceException;
import com.ard.common.utils.DateUtils;
import com.ard.common.utils.uuid.IdUtils;
import com.ard.system.authorize.service.AuthorizeService;
import com.ard.work.domain.dto.BoxSettingsDTO;
import com.ard.work.domain.entity.ArdDroneInfo;
import com.ard.work.domain.receiver.BoxInfoReceiver;
import com.ard.work.domain.receiver.BoxStreamUrlReceiver;
import com.ard.work.mapper.ArdDroneInfoMapper;
import com.ard.work.service.IArdDroneInfoService;
import com.ard.work.service.ITyService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
 
import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
 
/**
 * 无人机盒子Service业务层处理
 *
 * @author ard
 * @date 2025-03-04
 */
@Slf4j
@Service
public class ArdDroneInfoServiceImpl implements IArdDroneInfoService {
 
    @Resource
    private ArdDroneInfoMapper ArdDroneInfoMapper;
 
    @Resource
    private ITyService tyService;
 
    @Resource
    private AuthorizeService authorizeService;
 
    @Resource
    private RedisCache redisCache;
 
    /**
     * 查询无人机盒子
     *
     * @param id 无人机盒子主键
     * @return 无人机盒子
     */
    @Override
    public ArdDroneInfo selectArdDroneById(String id) {
        return ArdDroneInfoMapper.selectArdDroneById(id);
    }
 
    /**
     * 查询无人机盒子
     *
     * @param boxSn 盒子编码
     * @return 无人机盒子
     */
    @Override
    public ArdDroneInfo selectArdDroneByboxSn(String boxSn) {
        return ArdDroneInfoMapper.selectArdDroneByBoxSn(boxSn);
    }
 
    /**
     * 查询无人机盒子列表
     *
     * @param ardDroneInfo 无人机盒子
     * @return 无人机盒子
     */
    @Override
    @DataScope(deptAlias = "d", userAlias = "u")
    public List<ArdDroneInfo> selectArdDroneList(ArdDroneInfo ardDroneInfo) {
        List<ArdDroneInfo> ardDroneInfos = ArdDroneInfoMapper.selectArdDroneList(ardDroneInfo);
        // 使用传统的 for 循环避免 forEach 带来的性能开销
        for (ArdDroneInfo uav : ardDroneInfos) {
            try {
                BoxStreamUrlReceiver boxLiveUrl = tyService.getBoxLiveUrl(uav.getBoxSn());
                if (boxLiveUrl != null) {
                    uav.setWebrtcUrl(boxLiveUrl.getRtc());
                }
            } catch (Exception e) {
                log.error("获取设备 {} 的直播地址失败", uav.getBoxSn(), e);
            }
        }
        return ardDroneInfos;
    }
 
    /**
     * 新增无人机盒子
     *
     * @param ardDroneInfo 无人机盒子
     * @return 结果
     */
    @Override
    public int insertArdDrone(ArdDroneInfo ardDroneInfo) {
        ardDroneInfo.setId(IdUtils.fastUUID());
        ardDroneInfo.setCreateTime(DateUtils.getNowDate());
        return ArdDroneInfoMapper.insertArdDrone(ardDroneInfo);
    }
 
    /**
     * 修改无人机盒子
     *
     * @param ArdDroneInfo 无人机盒子
     * @return 结果
     */
    @Override
    public int updateArdDrone(ArdDroneInfo ArdDroneInfo) {
        Boolean b = tyService.updateBoxSettings(BoxSettingsDTO.builder().boxSn(ArdDroneInfo.getBoxSn()).boxName(ArdDroneInfo.getBoxName()).build());
        if (!b) {
            throw new ServiceException("修改无人机盒子名称失败");
        }
        ArdDroneInfo.setUpdateTime(DateUtils.getNowDate());
        return ArdDroneInfoMapper.updateArdDrone(ArdDroneInfo);
    }
 
    /**
     * 批量删除无人机盒子
     *
     * @param ids 需要删除的无人机盒子主键
     * @return 结果
     */
    @Override
    public int deleteArdDroneByIds(String[] ids) {
        return ArdDroneInfoMapper.deleteArdDroneByIds(ids);
    }
 
    /**
     * 删除无人机盒子信息
     *
     * @param id 无人机盒子主键
     * @return 结果
     */
    @Override
    public int deleteArdDroneById(String id) {
        return ArdDroneInfoMapper.deleteArdDroneById(id);
    }
 
    /**
     * 批量新增无人机盒子
     *
     * @param boxSn  盒子编码数组
     * @param deptId 部门ID
     * @return 成功插入的记录数
     */
    @Override
    public int insertArdDroneLs(String[] boxSn, Long deptId) {
        // 参数校验
        if (boxSn == null || boxSn.length == 0) {
            log.warn("传入的盒子编码为空");
            return 1;
        }
        if (deptId == null) {
            throw new IllegalArgumentException("部门ID不能为空");
        }
        try {
            // 1. 检查已存在的无人机盒子
            List<ArdDroneInfo> existingDrones = getExistingDrones(boxSn);
            // 2. 授权数量验证
            validateAuthorization(existingDrones.size(), boxSn.length);
            // 3. 获取并组装新的无人机信息
            List<ArdDroneInfo> newDrones = assembleNewDrones(boxSn, deptId);
            // 4. 批量插入
            return batchInsertDrones(newDrones);
        } catch (Exception e) {
            log.error("批量新增无人机盒子失败, boxSn: {}, deptId: {}", Arrays.toString(boxSn), deptId, e);
            throw new ServiceException("批量新增无人机盒子失败: " + e.getMessage());
        }
    }
 
    /**
     * 修改无人机状态
     */
    @Override
    public int updateDroneStatus(String serverId, String status) {
        return ArdDroneInfoMapper.updateDroneStatus(serverId, status);
    }
 
    /**
     * 获取已存在的无人机信息
     */
    private List<ArdDroneInfo> getExistingDrones(String[] boxSn) {
        return Arrays.stream(boxSn)
                .map(ArdDroneInfoMapper::selectArdDroneByBoxSn)
                .filter(Objects::nonNull)
                .collect(Collectors.toList());
    }
 
    /**
     * 验证授权数量
     */
    private void validateAuthorization(int existingCount, int newCount) {
        int totalCount = existingCount + newCount;
 
        JSONObject authInfo = authorizeService.getAuthorizationInfo();
        String authType = authInfo.getString("Type");
 
        switch (authType) {
            case "normal":
                int allowedDroneNum = authInfo.getIntValue("droneNum");
                if (totalCount > allowedDroneNum) {
                    throw new RuntimeException(String.format(
                            "授权数量%d,当前操作将导致总数达到%d,超过授权限制",
                            allowedDroneNum, totalCount));
                }
                break;
            case "expired":
                throw new RuntimeException("授权文件已过期");
            case "mismatch":
                throw new RuntimeException("授权文件不匹配");
            default:
                throw new RuntimeException("未知的授权类型: " + authType);
        }
    }
 
    /**
     * 组装新的无人机信息
     */
    private List<ArdDroneInfo> assembleNewDrones(String[] boxSn, Long deptId) {
        List<BoxInfoReceiver> allBoxes = tyService.getBoxList();
        Set<String> targetBoxSnSet = new HashSet<>(Arrays.asList(boxSn));
        return allBoxes.stream()
                .filter(box -> targetBoxSnSet.contains(box.getBoxSn()))
                .map(box -> createDroneInfo(box, deptId))
                .collect(Collectors.toList());
    }
 
    /**
     * 创建无人机信息对象
     */
    private ArdDroneInfo createDroneInfo(BoxInfoReceiver box, Long deptId) {
        ArdDroneInfo drone = new ArdDroneInfo();
        drone.setId(IdUtils.simpleUUID());
        drone.setBoxSn(box.getBoxSn());
        drone.setBoxName(box.getBoxName());
        drone.setStartTime(new Date());
        drone.setOnLine(box.getOnLine());
        drone.setVideoServer(box.getVideoServer());
        drone.setVideoPort(box.getVideoPort());
        drone.setLastTaskId(box.getLastTaskId());
        drone.setDeptId(deptId);
 
        // 设置创建信息和更新信息
        setCreateAndUpdateInfo(drone);
 
        return drone;
    }
 
    /**
     * 设置创建和更新信息
     */
    private void setCreateAndUpdateInfo(ArdDroneInfo drone) {
        Date currentTime = new Date();
        drone.setCreateTime(currentTime);
        drone.setUpdateTime(currentTime);
    }
 
    /**
     * 批量插入无人机信息
     */
    private int batchInsertDrones(List<ArdDroneInfo> drones) {
        if (drones.isEmpty()) {
            return 0;
        }
        return ArdDroneInfoMapper.insertArdDroneLs(drones);
    }
 
    /**
     * 同步盒子属性
     */
    @Scheduled(fixedRate = 1000 * 5)
    public void syncBoxInfo() {
        List<ArdDroneInfo> localList = selectArdDroneList(new ArdDroneInfo() {{
            setUseDataScope(false);
        }});
        Map<String, ArdDroneInfo> localMap = localList.stream()
                .collect(Collectors.toMap(ArdDroneInfo::getBoxSn, drone -> drone));
 
        tyService.getBoxList().forEach(remote -> {
            String boxSn = remote.getBoxSn();
 
            // ✅ 维护在线状态缓存
            // 只有在线的无人机才存 Redis
            String redisKey = CacheConstants.UAV_ONLINE_KEY + boxSn;
            if (remote.getOnLine() == 1) {
                redisCache.setCacheObject(redisKey, remote, 30, TimeUnit.SECONDS);
            } else {
                redisCache.deleteObject(CacheConstants.UAV_ONLINE_KEY + boxSn);
            }
            // 数据库同步
            ArdDroneInfo local = localMap.get(boxSn);
            if (local != null && !local.isSameAs(remote)) {
                updateChangedAttributes(local, remote);
                updateArdDrone(local);
            }
        });
    }
 
    // 更新变化的属性
    private void updateChangedAttributes(ArdDroneInfo localBoxInfo, BoxInfoReceiver remoteArdDrone) {
        if (!Objects.equals(localBoxInfo.getBoxName(), remoteArdDrone.getBoxName())) {
            localBoxInfo.setBoxName(remoteArdDrone.getBoxName());
        }
        if (!Objects.equals(localBoxInfo.getBoxVersion(), remoteArdDrone.getBoxVersion())) {
            localBoxInfo.setBoxVersion(remoteArdDrone.getBoxVersion());
        }
        if (!Objects.equals(localBoxInfo.getLastTaskId(), remoteArdDrone.getLastTaskId())) {
            localBoxInfo.setLastTaskId(remoteArdDrone.getLastTaskId());
        }
        if (!Objects.equals(localBoxInfo.getOnLine(), remoteArdDrone.getOnLine())) {
            localBoxInfo.setOnLine(remoteArdDrone.getOnLine());
        }
        // 更新其他属性
    }
}