pang.jiabao
昨天 15161de49e7f35e2fc926a20577905621f30554c
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
package com.zy.service.impl;
 
import com.alibaba.excel.util.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.core.common.Cools;
import com.zy.core.DevpThread;
import com.zy.core.cache.MessageQueue;
import com.zy.core.cache.SlaveConnection;
import com.zy.core.enums.SlaveType;
import com.zy.core.model.DevpSlave;
import com.zy.core.model.Task;
import com.zy.core.model.protocol.StaProtocol;
import com.zy.core.properties.SlaveProperties;
import com.zy.core.thread.SiemensDevpThread;
import com.zy.entity.*;
import com.zy.enums.RcsRetMethodEnum;
import com.zy.service.ApiLogService;
import com.zy.service.RcsService;
import com.zy.service.WrkDetlService;
import com.zy.service.WrkMastService;
import com.zy.utils.HttpHandler;
import com.zy.utils.News;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
 
import javax.annotation.Resource;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Objects;
 
import static com.zy.enums.RcsRetMethodEnum.APPLY_FROM_AGV;
 
@Slf4j
@Service
public class RcsServiceImpl implements RcsService {
 
    @Value("${dj.url}")
    public String DJ_URL;
 
    @Value("${hik.url}")
    private String HIK_URL;
 
    @Resource
    private WrkMastService wrkMastService;
 
    @Resource
    private WrkDetlService wrkDetlService;
 
    @Resource
    private SlaveProperties slaveProperties;
 
    @Resource
    private ApiLogService apiLogService;
    /**
     * 2.2.1任务执行回馈
     * 厂家:海量、华晓
     *
     * @param rcsReporterTask
     * @return
     */
    public RcsReturn reporterTask(RcsReporterTask rcsReporterTask) {
 
        RcsReturn rcsReturn = new RcsReturn();
 
        String robotTaskCode = rcsReporterTask.getRobotTaskCode();
        String singleRobotCode = rcsReporterTask.getSingleRobotCode();
        JSONObject values = rcsReporterTask.getExtra().getJSONObject("values");
        String method = values.getString("method");
        Date now = new Date();
 
        try {
            if (singleRobotCode.equals("14") || singleRobotCode.equals("15")) { // 两台CTU库机器人编号
                WrkMast wrkMast = wrkMastService.selectOne(new EntityWrapper<WrkMast>().eq("task_no", robotTaskCode));
                if (wrkMast != null) {
                    if (Objects.requireNonNull(RcsRetMethodEnum.getEnum(method)) == RcsRetMethodEnum.TASK_START) {
                        // 开始
                        wrkMast.setModiTime(now);
                        wrkMastService.updateById(wrkMast);
                    } else if (Objects.requireNonNull(RcsRetMethodEnum.getEnum(method)) == RcsRetMethodEnum.PICK_COMPLETE) {
                        // 取货完成,清除输送线任务号
                        SiemensDevpThread siemensDevpThread = (SiemensDevpThread) SlaveConnection.get(SlaveType.Devp, 1);
                        StaProtocol staProtocol = siemensDevpThread.getStation().get(106).clone();
                        // 取货完成清除输送线任务号
                        if (Objects.equals(staProtocol.getWorkNo(), wrkMast.getWrkNo())) {
                            staProtocol.setWorkNo(0);
                            staProtocol.setStaNo((short) 0);
                            boolean result = MessageQueue.offer(SlaveType.Devp, 1, new Task(2, staProtocol));
                            News.info("CTU取货完成,给站点写0工作号,下发任务:{},站点:{},agv任务号:{}", result, 106, robotTaskCode);
                            if (!result) {
                                rcsReturn.setCode("Err_Internal");
                                rcsReturn.setMessage("清除输送线任务号命令下发失败");
                                JSONObject data = new JSONObject();
                                data.put("robotTaskCode", robotTaskCode);
                                rcsReturn.setData(data);
                                return rcsReturn;
                            }
                        } else {
                            News.warn("CTU取货完成任务号{},清除输送线任务号:{},任务号不同", wrkMast.getWrkNo(), staProtocol.getWorkNo());
                        }
                    } else if (method.equals(APPLY_FROM_AGV.getCode())) {
                        // 放货申请
                        SiemensDevpThread siemensDevpThread = (SiemensDevpThread) SlaveConnection.get(SlaveType.Devp, 1);
                        StaProtocol staProtocol = siemensDevpThread.getStation().get(101).clone();
                        if (staProtocol == null) {
                            rcsReturn.setCode("Err_Internal");
                            rcsReturn.setMessage("101站点线程为空");
                            JSONObject data = new JSONObject();
                            data.put("robotTaskCode", robotTaskCode);
                            rcsReturn.setData(data);
                            return rcsReturn;
                        }
                        if (staProtocol.isOutEnable() && staProtocol.isAutoing() && !staProtocol.isLoading() && staProtocol.getWorkNo() == 0) { // 可出
                            RcsTaskContinue rcsTaskContinue = new RcsTaskContinue();
                            rcsTaskContinue.setRobotTaskCode(robotTaskCode);
                            rcsTaskContinue.setTriggerType("TASK");
                            rcsTaskContinue.setTriggerCode(robotTaskCode);
 
                            String url = HIK_URL + "api/robot/controller/task/extend/continue";
                            String response = sendPost(url, JSONObject.toJSONString(rcsTaskContinue));
                            if (!StringUtils.isEmpty(response) && response.contains("code")) {
                                RcsReturn rcsReturn1 = JSONObject.parseObject(response, RcsReturn.class);
                                if (!"SUCCESS".equals(rcsReturn1.getCode())) {
                                    // 返回RCS
                                    rcsReturn.setCode("Err_Internal");
                                    rcsReturn.setMessage("返回继续执行失败");
                                    JSONObject data = new JSONObject();
                                    data.put("robotTaskCode", robotTaskCode);
                                    rcsReturn.setData(data);
                                    return rcsReturn;
                                }
                            }
                        } else {
                            News.warn("站点{}不满足放货条件,自动:{},无物:{},可出:{},任务号:{}",
                                    101, staProtocol.isAutoing(), staProtocol.isLoading(), staProtocol.isOutEnable(), staProtocol.getWorkNo());
                            rcsReturn.setCode("Err_Internal");
                            rcsReturn.setMessage("站点不满足放货条件");
                            JSONObject data = new JSONObject();
                            data.put("robotTaskCode", robotTaskCode);
                            rcsReturn.setData(data);
                            return rcsReturn;
                        }
                    } else if (Objects.requireNonNull(RcsRetMethodEnum.getEnum(method)) == RcsRetMethodEnum.TASK_END) {
                        // 任务完成
                        Integer ioType = wrkMast.getIoType();
                        if (ioType == 1 || ioType == 10 || ioType == 53 || ioType == 57) {
                            wrkMast.setWrkSts(4L);
                            wrkMast.setCrnEndTime(now);
                            wrkMast.setModiTime(now);
                            wrkMastService.updateById(wrkMast);
                        } else if ((ioType == 101 || ioType == 110 || ioType == 103 || ioType == 107) && wrkMast.getWrkSts() == 12) {
                            // 给输送线下发命令
                            for (DevpSlave devp : slaveProperties.getDevp()) {
                                DevpThread devpThread = (DevpThread) SlaveConnection.get(SlaveType.Devp, devp.getId());
                                StaProtocol staProtocol = devpThread.getStation().get(wrkMast.getSourceStaNo()).clone();
                                staProtocol.setWorkNo(wrkMast.getWrkNo());
                                staProtocol.setStaNo(wrkMast.getStaNo().shortValue());
                                boolean result = MessageQueue.offer(SlaveType.Devp, devp.getId(), new Task(2, staProtocol));
                                if (result) {
                                    News.info("RCS给WCS反馈end,输送线命令下发成功:{}", wrkMast.getWrkNo());
                                } else {
                                    rcsReturn.setCode("Err_Internal");
                                    rcsReturn.setMessage("RCS给WCS反馈end,输送线命令下发失败");
                                    JSONObject data = new JSONObject();
                                    data.put("robotTaskCode", robotTaskCode);
                                    rcsReturn.setData(data);
                                    return rcsReturn;
                                }
                            }
                            wrkMast.setWrkSts(14L);
                            wrkMast.setCrnEndTime(now);
                            wrkMast.setModiTime(now);
                            wrkMastService.updateById(wrkMast);
                            // 给TMS反馈出库货物信息
                            List<WrkDetl> wrkDetls = wrkDetlService.selectList(new EntityWrapper<WrkDetl>().eq("wrk_no", wrkMast.getWrkNo()));
                            if (!wrkDetls.isEmpty()) {
                                WrkDetl wrkDetl = wrkDetls.get(0);
                                String orderNo = wrkDetl.getOrderNo();
                                if (!Cools.isEmpty(orderNo)) {
                                    // 构造请求参数
                                    JSONObject jsonObject = new JSONObject();
                                    jsonObject.put("billType", wrkDetl.getThreeCode());
                                    jsonObject.put("orderNo", wrkDetl.getOrderNo());
                                    jsonObject.put("createTime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(now));
                                    JSONArray jsonArray = new JSONArray();
                                    for (WrkDetl detl : wrkDetls) {
                                        JSONObject object = new JSONObject();
                                        object.put("itemNo", detl.getMatnr());
                                        object.put("anfme", detl.getAnfme());
                                        jsonArray.add(object);
                                    }
                                    jsonObject.put("details", jsonArray);
                                    String url = DJ_URL + "api/OutboundOrder/WmsOutFinish";
                                    String request = jsonObject.toJSONString();
                                    String response = "";
                                    boolean success = false;
                                    try {
                                        response = new HttpHandler.Builder()
                                                .setUri(DJ_URL)
                                                .setPath("api/OutboundOrder/WmsOutFinish")
                                                .setJson(request)
                                                .build()
                                                .doPost();
                                        JSONObject responseJson = JSON.parseObject(response);
                                        if (responseJson.getString("Success").equals("1")) {
                                            success = true;
                                            log.info("CTU出库反馈end,上报TMS成功,工作号:{},明细:{}", wrkMast.getWrkNo(), request);
                                        } else {
                                            log.error("CTU出库反馈end,上报TMS失败!,工作号:{},明细:{}", wrkMast.getWrkNo(), request);
                                            log.error("出库完成上报TMS失败!url:{};request:{};response:{}", url, request, response);
                                        }
                                    } catch (Exception e) {
                                        log.error("出库完成上报TMS异常,request:{}", request);
                                        e.printStackTrace();
                                    } finally {
                                        try {
                                            // 保存接口日志
                                            apiLogService.save(
                                                    "出库完成上报TMS",
                                                    url,
                                                    null,
                                                    "127.0.0.1",
                                                    request,
                                                    response,
                                                    success
                                            );
                                        } catch (Exception e) {
                                            log.error("入库保存接口日志异常", e);
                                        }
                                    }
                                }
                            }
                        } else {
                            log.error("{}ioType{}不在end反馈处理中", wrkMast.getWrkNo(), ioType);
                        }
                    }
                }
            }
            // 返回RCS
            rcsReturn.setCode("SUCCESS");
            rcsReturn.setMessage("");
            JSONObject data = new JSONObject();
            data.put("robotTaskCode", robotTaskCode);
            rcsReturn.setData(data);
        } catch (Exception e) {
            log.error("RCS反馈任务进度处理异常 - {}", rcsReporterTask, e);
            rcsReturn.setCode("Err_Internal");
            rcsReturn.setMessage("内部处理异常");
            JSONObject data = new JSONObject();
            data.put("robotTaskCode", robotTaskCode);
            rcsReturn.setData(data);
        }
 
        return rcsReturn;
    }
 
    @Override
    public RcsReturn reporterEqpt(ReporterEqpt param) {
        String robotTaskCode = param.getTaskCode();
        String method = param.getMethod();
        RcsReturn rcsReturn = new RcsReturn();
        if (method.equals(APPLY_FROM_AGV.getCode())) {
            SiemensDevpThread siemensDevpThread = (SiemensDevpThread) SlaveConnection.get(SlaveType.Devp, 1);
            StaProtocol staProtocol = siemensDevpThread.getStation().get(101).clone();
            if (staProtocol == null) {
                rcsReturn.setCode("Err_Internal");
                rcsReturn.setMessage("101站点线程为空");
                JSONObject data = new JSONObject();
                data.put("robotTaskCode", robotTaskCode);
                rcsReturn.setData(data);
                return rcsReturn;
            }
            if (staProtocol.isOutEnable() && staProtocol.isAutoing() && !staProtocol.isLoading() && staProtocol.getWorkNo() == 0) { // 可出
                EqptNotify eqptNotify = new EqptNotify(param.getEqptCode(), robotTaskCode, "6", "101");
                String url = HIK_URL + "spi/wcs/robot/eqpt/notify";
                String response = sendPost(url, JSONObject.toJSONString(eqptNotify));
                if (!StringUtils.isEmpty(response) && response.contains("code")) {
                    RcsReturn rcsReturn1 = JSONObject.parseObject(response, RcsReturn.class);
                    if (!"0".equals(rcsReturn1.getCode())) {
                        // 返回RCS
                        rcsReturn.setCode("Err_Internal");
                        rcsReturn.setMessage("通知RCS继续放货失败");
                        JSONObject data = new JSONObject();
                        data.put("robotTaskCode", robotTaskCode);
                        rcsReturn.setData(data);
                        return rcsReturn;
                    }
                } else {
                    rcsReturn.setCode("Err_Internal");
                    rcsReturn.setMessage("请求url" + url + "失败");
                    JSONObject data = new JSONObject();
                    data.put("robotTaskCode", robotTaskCode);
                    rcsReturn.setData(data);
                    return rcsReturn;
                }
            } else {
                News.warn("站点{}不满足放货条件,自动:{},无物:{},可出:{},任务号:{}",
                        101, staProtocol.isAutoing(), staProtocol.isLoading(), staProtocol.isOutEnable(), staProtocol.getWorkNo());
                rcsReturn.setCode("Err_Internal");
                rcsReturn.setMessage("站点不满足放货条件");
                JSONObject data = new JSONObject();
                data.put("robotTaskCode", robotTaskCode);
                rcsReturn.setData(data);
                return rcsReturn;
            }
        }
        rcsReturn.setCode("SUCCESS");
        rcsReturn.setMessage("成功!");
        JSONObject data = new JSONObject();
        data.put("extra", "null");
        rcsReturn.setData(data);
        log.info("agv放货请求返回:{}", JSONObject.toJSONString(rcsReturn));
        return rcsReturn;
    }
 
    /**
     * 向指定 URL 发送POST方法的请求
     *
     * @param url   发送请求的 URL
     * @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
     * @return 所代表远程资源的响应结果
     */
    public static String sendPost(String url, String param) {
        PrintWriter out = null;
        BufferedReader in = null;
        StringBuilder result = new StringBuilder();
        try {
            log.info("sendPost - {} - {}", url, param);
            URL realUrl = new URL(url);
            URLConnection conn = realUrl.openConnection();
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setRequestProperty("Content-Length", "<calculated when request is sent>");
            conn.setRequestProperty("Host", "<calculated when request is sent>");
            conn.setRequestProperty("Accept", "*/*");
            conn.setRequestProperty("Accept-Encoding", "gzip, deflate, br");
            conn.setRequestProperty("Connection", "keep-alive");
 
            conn.setRequestProperty("X-lr-request-id", String.valueOf(new Date().getTime()));
            conn.setRequestProperty("X-lr-version", "4.3");
            conn.setConnectTimeout(5000);
            conn.setReadTimeout(5000);
            conn.setDoOutput(true);
            conn.setDoInput(true);
            out = new PrintWriter(conn.getOutputStream());
            out.print(param);
            out.flush();
            in = new BufferedReader(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8));
            String line;
            while ((line = in.readLine()) != null) {
                result.append(line);
            }
            log.info("recv - {}", result);
        } catch (ConnectException e) {
            log.error("调用HttpUtils.sendPost ConnectException, url=" + url + ",param=" + param, e);
        } catch (SocketTimeoutException e) {
            log.error("调用HttpUtils.sendPost SocketTimeoutException, url=" + url + ",param=" + param, e);
        } catch (IOException e) {
            log.error("调用HttpUtils.sendPost IOException, url=" + url + ",param=" + param, e);
        } catch (Exception e) {
            log.error("调用HttpsUtil.sendPost Exception, url=" + url + ",param=" + param, e);
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                log.error("调用in.close Exception, url=" + url + ",param=" + param, ex);
            }
        }
        return result.toString();
    }
 
}