#
vincentlu
2026-04-07 cc69250f7766581dbfd38f500021d03b29f0a4e0
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
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
package com.zy.acs.manager.core.service;
 
import com.alibaba.fastjson.JSON;
import com.zy.acs.common.enums.AgvStatusType;
import com.zy.acs.common.hk.action.type.HkActionType;
import com.zy.acs.common.hk.state.*;
import com.zy.acs.common.hk.state.type.HkActionStatusType;
import com.zy.acs.common.hk.state.type.HkEStopType;
import com.zy.acs.common.utils.News;
import com.zy.acs.framework.common.Cools;
import com.zy.acs.framework.common.DateUtils;
import com.zy.acs.manager.common.config.HikOrderProperties;
import com.zy.acs.manager.core.constant.MapDataConstant;
import com.zy.acs.manager.core.domain.BackpackDto;
import com.zy.acs.manager.core.service.astart.MapDataDispatcher;
import com.zy.acs.manager.core.utils.AgvAngleUtils;
import com.zy.acs.manager.manager.entity.AgvDetail;
import com.zy.acs.manager.manager.entity.Code;
import com.zy.acs.manager.manager.service.AgvDetailService;
import com.zy.acs.manager.manager.service.AgvService;
import com.zy.acs.manager.manager.service.CodeService;
import com.zy.acs.manager.manager.service.JamService;
import com.zy.acs.manager.manager.service.impl.CodeServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
 
import java.util.*;
 
/**
 * 海康 state 主题数据适配为内部 AgvDetail。
 */
@Slf4j
@Service
public class HkAgvDataService {
 
    private static final boolean PRINT_LOG = false;
 
    private static final double DEFAULT_POSITION_MATCH_TOLERANCE = 0.05D;
 
    @Autowired
    private AgvService agvService;
    @Autowired
    private AgvDetailService agvDetailService;
    @Autowired
    private CodeService codeService;
    @Autowired
    private MapService mapService;
    @Autowired
    private ThreadPoolRegulator threadPoolRegulator;
    @Autowired
    private JamService jamService;
    @Autowired
    private HkOrderStateClosureService hkOrderStateClosureService;
    @Autowired
    private HikOrderProperties hikOrderProperties;
    @Autowired
    private MapDataDispatcher mapDataDispatcher;
 
    @Async
    public void dataProcess(HkState state) {
        if (state == null || Cools.isEmpty(state.getSerialNumber())) {
            log.warn("ignore empty hk state message: {}", JSON.toJSONString(state));
            return;
        }
 
        String agvNo = state.getSerialNumber();
        Long agvId = agvService.getAgvId(agvNo);
        if (agvId == null) {
            News.warn("Hk Agv [{}] 尚未鉴权 !!!", agvNo);
            return;
        }
 
        AgvDetail detail = agvDetailService.selectByAgvId(agvId);
        if (detail == null) {
            detail = new AgvDetail();
            detail.setAgvId(agvId);
            if (!agvDetailService.save(detail)) {
                News.error("Hk Agv [{}] 详情初始化失败 !!!", agvNo);
                return;
            }
        }
 
        Date now = new Date();
        detail.setUpdateTime(now);
 
        PositionResolution positionResolution = resolvePosition(state);
        syncPosition(detail, positionResolution);
        syncPose(detail, state);
        syncBattery(detail, state);
        syncBackpack(detail, agvId, state.getLoads());
        detail.setStatus(resolveStatus(state));
        syncError(detail, state, now);
 
        if (!Cools.isEmpty(positionResolution.recentCodeData)) {
            mapService.unlockPath(agvNo, positionResolution.recentCodeData);
            threadPoolRegulator.getInstance()
                    .execute(() -> jamService.checkIfFinish(agvId, positionResolution.recentCodeData));
        }
 
        if (!agvDetailService.updateById(detail)) {
            News.error("Hk Agv [{}] 详情更新失败 !!!", agvNo);
            return;
        }
 
        hkOrderStateClosureService.process(state);
 
        if (PRINT_LOG) {
            News.info("Hk Agv [{}] state ===>> {}", agvNo, JSON.toJSONString(state));
        }
    }
 
    private void syncPosition(AgvDetail detail, PositionResolution positionResolution) {
        if (positionResolution.code == null) {
            return;
        }
 
        if (positionResolution.onNode) {
            detail.setCode(positionResolution.code.getId());
            detail.setLastCode(null);
            detail.setPos(1);
            return;
        }
 
        detail.setCode(null);
        detail.setLastCode(positionResolution.code.getId());
        detail.setPos(0);
    }
 
    private void syncPose(AgvDetail detail, HkState state) {
        HkStateAgvPosition agvPosition = state.getAgvPosition();
        HkStateVelocity velocity = state.getVelocity();
 
        if (agvPosition != null && agvPosition.getTheta() != null) {
            double angle = normalizeAngle(AgvAngleUtils.fromRadians(agvPosition.getTheta()));
            detail.setAgvAngle(angle);
            detail.setGyroAngle(angle);
            detail.setEncoderAngle(angle);
        }
 
//        if (velocity != null) {
//            detail.setStraightVal(Math.hypot(defaultDouble(velocity.getVx()), defaultDouble(velocity.getVy())));
//        }
//
//        if (agvPosition != null || velocity != null) {
//            Map<String, Object> snapshot = new LinkedHashMap<>();
//            if (agvPosition != null) {
//                snapshot.put("x", agvPosition.getX());
//                snapshot.put("y", agvPosition.getY());
//                snapshot.put("theta", agvPosition.getTheta());
//                snapshot.put("mapId", agvPosition.getMapId());
//                snapshot.put("positionInitialized", agvPosition.getPositionInitialized());
//                snapshot.put("localizationScore", agvPosition.getLocalizationScore());
//            }
//            if (velocity != null) {
//                snapshot.put("vx", velocity.getVx());
//                snapshot.put("vy", velocity.getVy());
//                snapshot.put("omega", velocity.getOmega());
//            }
//            detail.setCodeOffsert(JSON.toJSONString(snapshot));
//        }
    }
 
    private void syncBattery(AgvDetail detail, HkState state) {
        HkStateBatteryState batteryState = state.getBatteryState();
        if (batteryState == null) {
            return;
        }
 
        if (batteryState.getBatteryCharge() != null) {
            detail.setSoc((int) Math.round(batteryState.getBatteryCharge()));
        }
        if (batteryState.getBatteryVoltage() != null) {
            detail.setVol((int) Math.round(batteryState.getBatteryVoltage()));
        }
    }
 
    private void syncBackpack(AgvDetail detail, Long agvId, List<HkStateLoad> loads) {
        int loadCount = loads == null ? 0 : loads.size();
        Integer backpackCap = agvService.getBackpack(agvId);
        int slotCount = Math.max(loadCount, backpackCap == null ? 0 : backpackCap);
 
        List<BackpackDto> backpackDtoList = new ArrayList<>();
        for (int i = 0; i < slotCount; i++) {
            backpackDtoList.add(new BackpackDto(i + 1, i < loadCount));
        }
        detail.setBackpack(JSON.toJSONString(backpackDtoList));
    }
 
    private void syncError(AgvDetail detail, HkState state, Date now) {
        String errorMessage = buildErrorMessage(state);
        if (!Cools.isEmpty(errorMessage)) {
            detail.setError(errorMessage);
            detail.setErrorTime(now);
            return;
        }
 
        if (!Cools.isEmpty(detail.realError()) && detail.getErrorTime() != null
                && DateUtils.diffToSeconds(detail.getErrorTime(), now) > 10) {
            detail.setError(MapDataConstant.EMPTY_OF_ERROR);
        }
    }
 
    private Integer resolveStatus(HkState state) {
        // todo
//        if (hasError(state)) {
//            return AgvStatusType.ERROR.val;
//        }
 
        HkStateBatteryState batteryState = state.getBatteryState();
        if (batteryState != null && Boolean.TRUE.equals(batteryState.getCharging())) {
            return AgvStatusType.CHARGE.val;
        }
 
        if (Boolean.TRUE.equals(state.getPaused())) {
            return AgvStatusType.PAUSE.val;
        }
 
        if (hasRunningAction(state, HkActionType.ROTATE_LOAD_LIFT.getCode())) {
            return AgvStatusType.TEMP.val;
        }
 
        if (hasRunningAction(state, HkActionType.PICK.getCode())
                || hasRunningAction(state, HkActionType.DROP.getCode())) {
            return AgvStatusType.MOTION.val;
        }
 
        if (Boolean.TRUE.equals(state.getDriving())) {
            HkStateVelocity velocity = state.getVelocity();
            double omega = velocity == null ? 0D : Math.abs(defaultDouble(velocity.getOmega()));
            return omega > 1e-4 ? AgvStatusType.TURN.val : AgvStatusType.STRAIGHT.val;
        }
 
        return AgvStatusType.IDLE.val;
    }
 
    private boolean hasRunningAction(HkState state, String actionType) {
        if (Cools.isEmpty(actionType) || Cools.isEmpty(state.getActionStates())) {
            return false;
        }
        for (HkStateActionState actionState : state.getActionStates()) {
            if (actionState == null || Cools.isEmpty(actionState.getActionType())) {
                continue;
            }
            if (!actionType.equalsIgnoreCase(actionState.getActionType())) {
                continue;
            }
            HkActionStatusType status = actionState.getActionStatus();
            if (status == HkActionStatusType.RUNNING
                    || status == HkActionStatusType.INITIALIZING
                    || status == HkActionStatusType.PAUSED) {
                return true;
            }
        }
        return false;
    }
 
    private boolean hasError(HkState state) {
        if (!Cools.isEmpty(state.getErrors())) {
            return true;
        }
        HkStateSafetyState safetyState = state.getSafetyState();
        if (safetyState == null) {
            return false;
        }
        if (Boolean.TRUE.equals(safetyState.getFieldViolation())) {
            return true;
        }
        return safetyState.getEStop() != null && safetyState.getEStop() != HkEStopType.NONE;
    }
 
    private String buildErrorMessage(HkState state) {
        List<String> errorParts = new ArrayList<>();
 
        if (!Cools.isEmpty(state.getErrors())) {
            for (HkStateError error : state.getErrors()) {
                if (error == null) {
                    continue;
                }
                StringBuilder builder = new StringBuilder();
                if (error.getErrorType() != null) {
                    builder.append(error.getErrorType().name());
                }
                if (!Cools.isEmpty(error.getErrorDescription())) {
                    if (builder.length() > 0) {
                        builder.append(": ");
                    }
                    builder.append(error.getErrorDescription());
                }
                if (!Cools.isEmpty(error.getErrorReferences())) {
                    List<String> refs = new ArrayList<>();
                    for (HkStateErrorReference ref : error.getErrorReferences()) {
                        if (ref == null || ref.getReferenceKey() == null || Cools.isEmpty(ref.getReferenceValue())) {
                            continue;
                        }
                        refs.add(ref.getReferenceKey().name() + "=" + ref.getReferenceValue());
                    }
                    if (!refs.isEmpty()) {
                        if (builder.length() > 0) {
                            builder.append(" ");
                        }
                        builder.append("(").append(String.join(", ", refs)).append(")");
                    }
                }
                if (builder.length() > 0) {
                    errorParts.add(builder.toString());
                }
            }
        }
 
        HkStateSafetyState safetyState = state.getSafetyState();
        if (safetyState != null) {
            if (safetyState.getEStop() != null && safetyState.getEStop() != HkEStopType.NONE) {
                errorParts.add("eStop=" + safetyState.getEStop().name());
            }
            if (Boolean.TRUE.equals(safetyState.getFieldViolation())) {
                errorParts.add("fieldViolation=true");
            }
        }
 
        return errorParts.isEmpty() ? "" : String.join("; ", errorParts);
    }
 
    private PositionResolution resolvePosition(HkState state) {
        Code code = resolveCodeByDispatcher(state.getAgvPosition());
        if (code == null) {
            code = resolveCodeByPosition(state.getAgvPosition());
        }
        if (code == null) {
            code = resolveCodeByNodeId(state.getLastNodeId());
        }
        boolean onNode = code != null && !Boolean.TRUE.equals(state.getDriving());
        String recentCodeData = code == null ? null : code.getData();
        return new PositionResolution(code, onNode, recentCodeData);
    }
 
    private Code resolveCodeByNodeId(String nodeId) {
        if (Cools.isEmpty(nodeId)) {
            return null;
        }
 
        Code code = codeService.getCacheByData(nodeId);
        if (code != null) {
            return code;
        }
 
        int idx = nodeId.lastIndexOf('-');
        if (idx < 0 || idx >= nodeId.length() - 1) {
            return null;
        }
        return codeService.getCacheByData(nodeId.substring(idx + 1));
    }
 
    private Code resolveCodeByDispatcher(HkStateAgvPosition agvPosition) {
        if (agvPosition == null
                || !Boolean.TRUE.equals(agvPosition.getPositionInitialized())
                || agvPosition.getX() == null
                || agvPosition.getY() == null) {
            return null;
        }
 
        String codeData = mapDataDispatcher.resolveNearestCodeByCoordinate(
                null,
                revertCoordinate(agvPosition.getX()),
                revertCoordinate(agvPosition.getY()),
                resolvePositionTolerance()
        );
        if (Cools.isEmpty(codeData)) {
            return null;
        }
        return codeService.getCacheByData(codeData);
    }
 
    private Code resolveCodeByPosition(HkStateAgvPosition agvPosition) {
        if (agvPosition == null
                || !Boolean.TRUE.equals(agvPosition.getPositionInitialized())
                || agvPosition.getX() == null
                || agvPosition.getY() == null) {
            return null;
        }
 
        double x = revertCoordinate(agvPosition.getX());
        double y = revertCoordinate(agvPosition.getY());
        Code nearest = null;
        double minDistance = Double.MAX_VALUE;
 
        for (Code code : getAllCodes()) {
            if (code == null || code.getX() == null || code.getY() == null) {
                continue;
            }
            double distance = Math.hypot(code.getX() - x, code.getY() - y);
            if (distance < minDistance) {
                minDistance = distance;
                nearest = code;
            }
        }
 
        return nearest != null && minDistance <= resolvePositionTolerance() ? nearest : null;
    }
 
    private double revertCoordinate(Double value) {
        double scale = hikOrderProperties.getCoordinateScale();
        if (scale == 0D) {
            return value;
        }
        return value / scale;
    }
 
    private double resolvePositionTolerance() {
        double scale = hikOrderProperties.getCoordinateScale();
        return Math.max(DEFAULT_POSITION_MATCH_TOLERANCE, hikOrderProperties.getDefaultAllowedDeviationXY()) / scale;
    }
 
    private Collection<Code> getAllCodes() {
        if (!Cools.isEmpty(CodeServiceImpl.CODE_DATA_CACHE)) {
            return CodeServiceImpl.CODE_DATA_CACHE.values();
        }
        return codeService.list();
    }
 
    private double defaultDouble(Double value) {
        return value == null ? 0D : value;
    }
 
    private double normalizeAngle(double angle) {
        return (angle % 360 + 360) % 360;
    }
 
    private static class PositionResolution {
 
        private final Code code;
 
        private final boolean onNode;
 
        private final String recentCodeData;
 
        private PositionResolution(Code code, boolean onNode, String recentCodeData) {
            this.code = code;
            this.onNode = onNode;
            this.recentCodeData = recentCodeData;
        }
    }
}