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
package com.dy.pipIrrGlobal.command;
 
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.dy.common.mw.protocol.Command;
import com.dy.common.mw.protocol.CommandType;
import com.dy.common.mw.protocol.Data;
import com.dy.common.webUtil.BaseResponse;
import com.dy.common.webUtil.BaseResponseUtils;
import com.dy.pipIrrGlobal.command.dto.Param;
import com.dy.pipIrrGlobal.command.enums.LastOperateENUM;
import com.dy.pipIrrGlobal.command.result.CommandResultCode;
import com.dy.pipIrrGlobal.daoBa.BaSettingsMapper;
import com.dy.pipIrrGlobal.daoPr.PrControllerMapper;
import com.dy.pipIrrGlobal.daoRm.RmCommandHistoryMapper;
import com.dy.pipIrrGlobal.daoSe.SeVirtualCardMapper;
import com.dy.pipIrrGlobal.pojoPr.PrController;
import com.dy.pipIrrGlobal.pojoRm.RmCommandHistory;
import com.dy.pipIrrGlobal.pojoSe.SeVirtualCard;
import jakarta.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;
 
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
 
/**
 * @author ZhuBaoMin
 * @date 2024-05-30 15:45
 * @LastEditTime 2024-05-30 15:45
 * @Description 命令支撑类
 */
 
//@Component
//@DependsOn({"baSettingsMapper", "prControllerMapper"})
public class ComSupport {
    protected static String mwUrlSendCom = "http://127.0.0.1:8070/rtuMw/com/send" ;
 
    protected static String controllerType = null;
    protected static Integer projectNo = null;
    protected String commandTypeOuter = CommandType.outerCommand;
 
    // 存储实例化的 CompletableFuture<Data> 对象
    protected static Map<Long, Object> features = new HashMap<>();
    protected static Boolean setuped = false;
 
    @Autowired
    private RestTemplate restTemplate;
 
    @Autowired
    private BaSettingsMapper baSettingsMapper;
 
    @Autowired
    private PrControllerMapper prControllerMapper;
 
    @Autowired
    private RmCommandHistoryMapper rmCommandHistoryMapper;
 
    @Autowired
    private SeVirtualCardMapper seVirtualCardMapper;
 
    public static ComSupport comSupport;
 
    /**
     * 引入BaSettingsMapper
     */
    @PostConstruct
    public void init() {
        comSupport = this;
        comSupport.baSettingsMapper = this.baSettingsMapper;
        comSupport.prControllerMapper = this.prControllerMapper;
    }
 
    /**
     * 获取系统配置参数
     */
    public void setUp() {
        controllerType = comSupport.baSettingsMapper.getItemValue("controllerType");
        projectNo = Integer.parseInt(comSupport.baSettingsMapper.getItemValue("projectNo"));
        setuped = true;
    }
 
    /**
     * 生成订单号
     * @return
     */
    public String generateOrderNo() {
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyMMddHHmmss");
        LocalDateTime dateTime = LocalDateTime.now();
        Random random = new Random();
        String CHARACTERS = "0123456789";
        StringBuilder sb = new StringBuilder(4);
        for (int i = 0; i < 4; i++) {
            int index = random.nextInt(CHARACTERS.length());
            sb.append(CHARACTERS.charAt(index));
        }
        return dtf.format(dateTime) + sb.toString();
    }
 
    /**
     * 根据取水口ID或阀控器地址获取阀控器对象
     * @param intakeId
     * @return
     */
    public JSONObject getRtu(Long intakeId, String rtuAddr) {
        PrController prController = prControllerMapper.getRtu(intakeId, rtuAddr);
        if(prController == null) {
            return null;
        }
        JSONObject job_rtu = new JSONObject();
        job_rtu.put("rtuAddr", prController.getRtuAddr());
        job_rtu.put("protocol", prController.getProtocol());
        job_rtu.put("intakeId", prController.getIntakeId());
 
        return job_rtu;
    }
 
    /**
     * 创建命令日志对象
     * @param comId 主键
     * @param commandCode 功能码
     * @param rtuAddr 阀控器地址
     * @param protocol 通讯协议名称
     * @param param 参数数据
     * @param operator 操作员
     * @return
     */
    protected RmCommandHistory getComHistory(Long comId, String commandCode, String commandName, Long intakeId, String rtuAddr, String protocol, Object param, Long operator ) {
        RmCommandHistory rmCommandHistory = new RmCommandHistory();
        rmCommandHistory.setId(comId);
        rmCommandHistory.setCommandCode(commandCode);
        //rmCommandHistory.setCommandName(CodeV202404.getCodeName(commandCode));
        rmCommandHistory.setCommandName(commandName);
        rmCommandHistory.setIntakeId(intakeId);
        rmCommandHistory.setRtuAddr(rtuAddr);
        rmCommandHistory.setProtocol(protocol);
        rmCommandHistory.setParam((JSONObject) JSON.toJSON(param));
        rmCommandHistory.setSendTime(new Date());
        rmCommandHistory.setOperator(operator);
        return rmCommandHistory;
    }
 
    /**
     * 构造命令对象
     * @param comId 命令ID
     * @param commandCode 功能码
     * @param rtuAddr RTU地址
     * @param param 参数数据
     * @return 构造好的命令对象
     */
    protected Command command(Long comId, String commandCode, String rtuAddr, String protocol, String rtuResultSendWebUrl, Object param){
        Command com = new Command() ;
        com.id = String.valueOf(comId);
        com.code = commandCode ;
        com.rtuAddr = rtuAddr ;
 
        com.protocol = protocol;
        com.type = commandTypeOuter;
        com.rtuResultSendWebUrl = rtuResultSendWebUrl ;
 
        com.param = param ;
 
        return com ;
    }
 
    /**
     * 处理回调内容
     * @param comId
     * @return
     */
    protected BaseResponse<Data> dealWithCallBack(Long comId) {
        CompletableFuture<Data> featureObject = new CompletableFuture<>();
        features.put(comId, featureObject);
        try {
            CompletableFuture<Data> feature = (CompletableFuture<Data>) features.get(comId);
            System.out.println("receive result ID:" + comId);
            Data resultData = feature.get(180, TimeUnit.SECONDS);
            features.remove(comId);
            Long commandId = Long.parseLong(resultData.getCommandId());
            if(commandId.equals(comId)) {
                return BaseResponseUtils.buildSuccess(resultData);
            }else {
                return BaseResponseUtils.buildSuccess();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
            return BaseResponseUtils.buildFail(CommandResultCode.GET_RESULT_ERROR.getMessage());
        } catch (ExecutionException e) {
            e.printStackTrace();
            return BaseResponseUtils.buildFail(CommandResultCode.GET_RESULT_ERROR.getMessage());
        } catch (TimeoutException e) {
            return BaseResponseUtils.buildSuccess(CommandResultCode.GET_RESULT_IN_ONE_MINUTE.getMessage());
        }
    }
 
    /**
     * 发送命令
     * @return
     */
    protected BaseResponse sendCom2Mw(Command com){
        String url = UriComponentsBuilder.fromUriString(mwUrlSendCom)
                .build()
                .toUriString();
        HttpHeaders headers = new HttpHeaders();
        HttpEntity<Command> httpEntity = new HttpEntity<>(com, headers);
        ResponseEntity<BaseResponse> response = null;
        try {
            // 通过Post方式调用接口
            response = restTemplate.exchange(url, HttpMethod.POST, httpEntity, BaseResponse.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return response.getBody();
    }
 
    /**
     * 构造命令、发送命令并处理请求结果及执行结果
     * @param po
     * @return
     */
    protected BaseResponse<Boolean> dealWithCommandResult(Param po) {
        Long comId = po.getComId();
        Byte comType = po.getComType();
        String commandCode = po.getCommandCode();
        String commandName = po.getCommandName();
        Long intakeId = po.getIntakeId();
        String rtuAddr = po.getRtuAddr();
        String protocol = po.getProtocol();
        Long vcId = po.getVcId();
        Object param = po.getParam();
        String rtuResultSendWebUrl = po.getRtuResultSendWebUrl();
        Long operator = po.getOperator();
 
        // 构造命令
        Command com = command(comId, commandCode, rtuAddr, protocol, rtuResultSendWebUrl, param);
 
        // 发送命令
        JSONObject response_SendCom= (JSONObject) JSON.toJSON(sendCom2Mw(com));
        if(response_SendCom != null && response_SendCom.getString("code").equals("0001")) {
            // 请求成功
 
            // 创建命令日志对象并添加到数据库中
            RmCommandHistory rmCommandHistory = getComHistory(comId, commandCode, commandName, intakeId, rtuAddr, protocol, param, operator);
            rmCommandHistoryMapper.insert(rmCommandHistory);
 
            // 处理回调
            BaseResponse response_CallBack = dealWithCallBack(comId);
 
            // 回调异常
            if(!response_CallBack.getCode().equals("0001")) {
                // 命令日志执行结果改为失败
                rmCommandHistory = new RmCommandHistory();
                rmCommandHistory.setId(comId);
                rmCommandHistory.setResult((byte)0);
                rmCommandHistoryMapper.updateByPrimaryKeySelective(rmCommandHistory);
                return BaseResponseUtils.buildErrorMsg(response_CallBack.getContent().toString());
            }
 
            // 回调超时
            if (response_CallBack.getContent().toString().equals(CommandResultCode.GET_RESULT_IN_ONE_MINUTE.getMessage())) {
                /**
                 * 回调超时,暂时认为执行失败
                 * 命令置为失败
                 * 虚拟卡依旧保持使用中的状态
                 */
 
                rmCommandHistory = new RmCommandHistory();
                rmCommandHistory.setId(comId);
                rmCommandHistory.setResult((byte) 0);
                rmCommandHistoryMapper.updateByPrimaryKeySelective(rmCommandHistory);
                return BaseResponseUtils.buildErrorMsg(CommandResultCode.GET_RESULT_IN_ONE_MINUTE.getMessage());
            }
 
            // 回调成功,再判断执行是否成功
            JSONObject job_content = (JSONObject)JSON.toJSON(response_CallBack.getContent());
            System.out.println(job_content);
            JSONObject job_subData = (JSONObject) job_content.getJSONObject("subData").getJSONObject("subData");
            System.out.println(job_subData);
            Boolean dealResult = job_subData.getBoolean("success");
            if(!dealResult) {
                return BaseResponseUtils.buildFail(response_CallBack.getContent().toString());
            }
 
            /**
             * 执行成功,返回回调内容
             * 如果是开关阀:更改虚拟卡状态:是否使用中、最后操作、最后操作时间
             */
            if(comType != null) {
                SeVirtualCard virtualCard = new SeVirtualCard();
                virtualCard.setId(vcId);
                if(comType == 1) {
                    virtualCard.setInUse((byte) 1);
                }else {
                    virtualCard.setInUse((byte) 0);
                }
                virtualCard.setLastOperate(LastOperateENUM.OPEN_VALVE.getCode());
                virtualCard.setLastOperateTime(new Date());
                seVirtualCardMapper.updateByPrimaryKeySelective(virtualCard);
            }
 
 
            // 回调返回的内容
            Data myData = (Data)response_CallBack.getContent();
            return BaseResponseUtils.buildSuccess(myData) ;
        } else {
            // 请求失败
            JSONObject job_param = response_SendCom.getJSONObject("content").getJSONObject("param");
            return BaseResponseUtils.buildFail(job_param.getString("message"));
        }
    }
}