#
vincentlu
昨天 6a19c21930c9fef7fe1dd3aaa35133f68375300a
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
package com.zy.acs.manager.core.integrate.wms;
 
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.zy.acs.framework.common.Cools;
import com.zy.acs.framework.common.R;
import com.zy.acs.framework.common.SnowflakeIdWorker;
import com.zy.acs.manager.common.config.UplinkProperties;
import com.zy.acs.manager.common.constant.Constants;
import com.zy.acs.manager.common.utils.HttpGo;
import com.zy.acs.manager.core.domain.type.NamespaceType;
import com.zy.acs.manager.core.integrate.dto.HttpResult;
import com.zy.acs.manager.core.integrate.dto.TaskUplinkParam;
import com.zy.acs.manager.core.service.ThreadPoolRegulator;
import com.zy.acs.manager.manager.entity.Bus;
import com.zy.acs.manager.manager.entity.IntegrationRecord;
import com.zy.acs.manager.manager.entity.Task;
import com.zy.acs.manager.manager.enums.IntegrationDirectionType;
import com.zy.acs.manager.manager.enums.StatusType;
import com.zy.acs.manager.manager.enums.TaskStsType;
import com.zy.acs.manager.manager.enums.TaskUplinkStateType;
import com.zy.acs.manager.manager.service.BusService;
import com.zy.acs.manager.manager.service.IntegrationRecordService;
import com.zy.acs.manager.manager.service.TaskService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
 
import javax.annotation.PostConstruct;
import java.time.Duration;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
 
@Slf4j
@Service
public class TaskReportService {
 
    @Autowired
    private UplinkProperties uplinkProperties;
    @Autowired
    private TaskService taskService;
    @Autowired
    private ThreadPoolRegulator threadPoolRegulator;
    @Autowired
    private BusService busService;
    @Autowired
    private SnowflakeIdWorker snowflakeIdWorker;
    @Autowired
    private IntegrationRecordService integrationRecordService;
 
    private HttpGo http;
 
    @PostConstruct
    public void init() {
        int timeoutSeconds = uplinkProperties.getTimeout() / 1000;
        this.http = HttpGo.builder()
                .connectTimeout(Duration.ofSeconds(timeoutSeconds))
                .readTimeout(Duration.ofSeconds(timeoutSeconds))
//                .defaultHeader("User-Agent", "HttpGo/1.0")
//                .trustAllSsl(true) // ONLY if you really need it (self-signed internal)
                .build();
    }
 
    public boolean reportFinished(Task task) {
        if (Cools.isEmpty(task)) {
            return false;
        }
        if (!uplinkProperties.getEnabled()) {
            return false;
        }
        if (!task.getTaskSts().equals(TaskStsType.COMPLETE.val())) {
            return false;
        }
        TaskUplinkStateType uplinkStateType = TaskUplinkStateType.of(task.getUplinkSts());
        if (!uplinkStateType.equals(TaskUplinkStateType.PENDING)
                && !uplinkStateType.equals(TaskUplinkStateType.SENDING)
                && !uplinkStateType.equals(TaskUplinkStateType.FAILED)
        ) {
            return false;
        }
        Date now = new Date();
        // block
//        Future<R> future = threadPoolRegulator.getInstance().submit(() -> {
//            mapDataDispatcher.modifyDynamicMatrix(null, null, param.getAgvNo(), true);
//            return success();
//        });
//        System.out.println(JSON.toJSONString(future.get()));
 
        // non-block
        CompletableFuture<?> completableFuture = CompletableFuture.supplyAsync(() -> {
//            mapDataDispatcher.modifyDynamicMatrix(null, null, param.getAgvNo(), true);
//            avoidWaveCalculator.calcDynamicNodeByVehicle(agv, null);
            return R.ok();
        }, threadPoolRegulator.getInstance());
 
        // url
        String url = this.http.buildUrl(uplinkProperties.getHost(), uplinkProperties.getPort(), uplinkProperties.getUrl());
        // headers
        Map<String, String> headers = new HashMap<>();
        // params
        TaskUplinkParam param = new TaskUplinkParam();
        if (null != task.getBusId()) {
            Bus bus = busService.getById(task.getBusId());
            param.setBatchNo(bus.getBusNo());
        }
        param.setTaskNo(task.getSeqNum());
        param.setTimestamp(null == task.getEndTime() ? System.currentTimeMillis() : task.getEndTime().getTime());
 
        IntegrationRecord integrationRecord = new IntegrationRecord(
                String.valueOf(snowflakeIdWorker.nextId()).substring(3),    // 编号
                NamespaceType.RCS_TASK_REPORT.name,    // 名称空间
                uplinkProperties.getUrl(),    // 接口地址
                null,    // 平台密钥
                Constants.RCS,    // 调用方标识
                IntegrationDirectionType.OUTBOUND.value,    // 方向[非空]
                String.valueOf(now.getTime()),    // 时间戳
                uplinkProperties.getHost(),    // 客户端IP
                JSON.toJSONString(param),    // 请求内容
                null,    // 响应内容
                null,    // 异常内容
                0,    // 结果
                null,    // 耗时
                StatusType.ENABLE.val,    // 状态
                now,    // 添加时间[非空]
                now,    // 修改时间[非空]
                null    // 备注
        );
        HttpResult<?> result;
        try {
            result = postForResult(url, headers, param);
            integrationRecord.setResponse(JSON.toJSONString(result));
 
            Integer code = result.getCode();
            if (null == code || 200 != code) {
                return false;
            }
//            Object data = result.getData();
//            if (Cools.isEmpty(data)) {
//                return false;
//            }
 
            integrationRecord.setResult(1);
        } catch (Exception e) {
            log.error("Uplink report failed, taskId={}",
                    JSON.toJSONString(task),
                    e);
            integrationRecord.setErr(e.getMessage());
            return false;
        } finally {
            integrationRecord.setCostMs((int) (System.currentTimeMillis() - now.getTime()));
            integrationRecordService.syncRecord(integrationRecord);
        }
        return true;
    }
 
    private HttpResult<?> postForResult(String url, Map<String, String> headers, TaskUplinkParam param) throws Exception {
        String json = JSON.toJSONString(param);
        HttpGo.HttpResponse response = this.http.postJson(url, headers, json);
 
        int status = response.statusCode();
        if (status != 200) {
            throw new RuntimeException("Uplink HTTP error: status=" + status + ", body=" + response.body());
        }
 
        String body = response.body();
        if (Cools.isEmpty(body)) {
            throw new RuntimeException("Uplink empty response body.");
        }
 
        HttpResult<?> result = JSON.parseObject(body, new TypeReference<HttpResult<?>>() {});
        if (result == null) {
            throw new RuntimeException("Uplink parse HttpResult failed: body=" + body);
        }
        return result;
    }
 
 
}