zhangnaisong
2024-07-30 6bce1b35246ed695a4272c24254c7073a524818a
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
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
/**
 * <p>Description: </p>
 * <p>Copyright: Copyright (c) 2020</p>
 * <p>Company: www.31gps.net</p>
 * @author chencq
 * @version 1.0
 */
package com.ruoyi.sy.gps31;
 
import com.alibaba.fastjson2.JSON;
import com.gps31.push.netty.PushClient;
import com.gps31.push.netty.PushMsg;
import com.gps31.push.netty.client.TcpClient;
import com.gps31.push.util.MapUtil;
import com.ruoyi.common.core.domain.entity.SysConfig;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.sy.domain.ArdSyCarLock;
import com.ruoyi.sy.domain.ArdSyCarRtu;
import com.ruoyi.sy.domain.ArdTankLock;
import com.ruoyi.sy.domain.ArdTankLockState;
import com.ruoyi.sy.service.ArdSyCarLockService;
import com.ruoyi.sy.service.ArdSyCarRtuService;
import com.ruoyi.sy.service.impl.*;
import com.ruoyi.system.service.impl.SysConfigServiceImpl;
import com.ruoyi.utils.forest.SYClient;
import com.ruoyi.utils.qymqtt.newM.EmqClient;
import com.ruoyi.utils.qymqtt.newM.QosEnum;
import lombok.extern.slf4j.Slf4j;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.eclipse.paho.client.mqttv3.MqttException;
 
import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
 
/**
 * <p>Description: </p>
 * <p>Copyright: Copyright (c) 2020</p>
 * <p>Company: www.31gps.net</p>
 * @author chencq
 * @version 1.0
 */
public class PushClientImplSerialPort extends PushClient implements Runnable {
 
    private static final Log log = LogFactory.getLog(PushClientImplSerialPort.class);
 
    private static String ip;
 
    private static String userId;
 
    private static String password;
 
    public PushClientImplSerialPort(String ip, String userId, String password) {
        this.ip = ip;
        this.userId = userId;
        this.password = password;
    }
 
    public PushClientImplSerialPort() {
 
    }
 
    @Override
    public void messageReceived(TcpClient tcpClient, PushMsg pushMsg)
            throws Exception {
        if("8001".equals(pushMsg.getCmd())) {//登录应答
            String rspResult = MapUtil.getStrVal(pushMsg.getJsonMap(),"rspResult","1");
            if("0".equals(rspResult)) {//登录成功,定阅动态消息
                Map<String,Object> map = new HashMap<String,Object>();
                map.put("seq", "1");
                map.put("action", "add");
                map.put("msgIds", JSON.toJSONString(getSubCmdSet()));
                PushMsg subMsg = getInstance("0003",map);
                sendMsg(subMsg);
            }
        }else if("8002".equals(pushMsg.getCmd())){//心跳应答
 
        }else if("8003".equals(pushMsg.getCmd())){//订阅动态消息应答
            String rspResult = MapUtil.getStrVal(pushMsg.getJsonMap(),"rspResult","1");
            //log.error(String.format("    订阅应答:%s", "0".equals(rspResult)?"成功":"失败"));
        }else if("0200".equals(pushMsg.getCmd())) {//定位信息
            Map<String,Object> gpsMap = pushMsg.getJsonMap();
            log.debug(String.format("   ---->----收到定位数据如下:%s",JSON.toJSONString(gpsMap)));
            /**
             *
             * 请加入三方集成方的业务逻辑
             *
             */
        }else if("0300".equals(pushMsg.getCmd())) {//报警消息
            Map<String,Object> alarmMap = pushMsg.getJsonMap();
            String carName = MapUtil.getStrVal(alarmMap, "carName","");//获取车牌号
            //log.error(String.format("   ---->收到报警数据:%s",JSON.toJSONString(alarmMap)));
            /**
             *
             * 请加入三方集成方的业务逻辑
             *
             */
        }else if("0401".equals(pushMsg.getCmd())) {//透传消息
            Map<String,Object> dataMap = pushMsg.getJsonMap();
            //String carName = MapUtil.getStrVal(dataMap, "carName","");//获取车牌号
            //log.error(String.format("   ---->收到透传数据:%s",JSON.toJSONString(dataMap)));
            Thread thread = new Thread(){
                @Override
                public void run() {
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    Date now = new Date();
                    try {
                        String data = (String) dataMap.get("data");
                        if(data.length() %2 != 0){//长度不是偶数,就返回
                            return;
                        }
 
                        Integer sum = 0;
                        for(int i = 0;i <= data.length() - 4;i = i + 2){
                            String str = data.substring(i, i + 2);
                            sum = sum + Integer.parseInt(str, 16);
                        }//求和
                        String checkNum = data.substring(data.length() - 2, data.length());
                        String checkNumComputed = Integer.toHexString(sum).toUpperCase();//计算校验
                        //当校验数据大于2个字符,截取最后两位
                        if(checkNumComputed.length() != 2){
                            checkNumComputed = checkNumComputed.substring(checkNumComputed.length() - 2,checkNumComputed.length());
                        }
                        if(!checkNum.equals(checkNumComputed)){//校验不通过,就返回
                            return;
                        }
 
                        String lockNum = data.substring(0, 4);
                        String code = data.substring(4, 6);
                        if(code.equals("01")){//功能码01为锁实时状态
                            String lockState = data.substring(6, 8);
                            String lockPositionState = data.substring(8, 10);
                            String lockShellState = data.substring(10, 12);
                            String restartState = data.substring(12, 14);
                            String batterVoltage = data.substring(14, 18);
                            String powerVoltage = data.substring(18, 22);
                            String time = data.substring(22, 34);
                            //计算时间
                            String year = time.substring(0, 2);
                            String month = time.substring(2, 4);
                            String day = time.substring(4, 6);
                            String hour = time.substring(6, 8);
                            String minute = time.substring(8, 10);
                            String second = time.substring(10, 12);
 
                            Integer yearNum = Integer.parseInt(year, 16);
                            if(yearNum <= 9){
                                time = "200" + yearNum + "-";
                            }else{
                                time = "20" + yearNum + "-";
                            }
 
                            Integer monthNum = Integer.parseInt(month, 16);
                            if(monthNum <= 9){
                                time = time + "0" + monthNum + "-";
                            }else{
                                time = time + monthNum + "-";
                            }
 
                            Integer dayNum = Integer.parseInt(day, 16);
                            if(dayNum <= 9){
                                time = time + "0" + dayNum + " ";
                            }else{
                                time = time + dayNum + " ";
                            }
 
                            Integer hourNum = Integer.parseInt(hour, 16);
                            if(hourNum <= 9){
                                time = time + "0" + hourNum + ":";
                            }else{
                                time = time + hourNum + ":";
                            }
 
                            Integer minuteNum = Integer.parseInt(minute, 16);
                            if(minuteNum <= 9){
                                time = time + "0" + minuteNum + ":";
                            }else{
                                time = time + minuteNum + ":";
                            }
 
                            Integer secondNum = Integer.parseInt(second, 16);
                            if(secondNum <= 9){
                                time = time + "0" + secondNum;
                            }else{
                                time = time + secondNum;
                            }
 
                            ArdTankLock ardTankLock = new ArdTankLock();
                            ardTankLock.setLockNum(lockNum);
                            List<ArdTankLock> ardTankLockResult = ((ArdTankLockServiceImpl)SpringUtils.getBean("ardTankLockServiceImpl")).selectArdTankLockList(ardTankLock);
 
                            if(ardTankLockResult.isEmpty()){//锁没有录入则返回
                                return;
                            }
 
                            long cha = now.getTime() - sdf.parse(time).getTime();
                            if(Math.abs(cha) >= 5 * 1000){
                                //时间校准
                                /*String url = "http://" + ip + ":9999";
                                String passwordMd5 = DigestUtils.md5Hex(password);
                                Map<String, Object> LogInResult = loginIn(url, userId, passwordMd5);
                                String sessionId = (String) LogInResult.get("sessionId");
                                //获取时间并拆分年月日时分秒
                                String nowTime = sdf.format(now);
                                String nowYear = nowTime.substring(2,4);
                                String nowMonth = nowTime.substring(5,7);
                                String nowDay = nowTime.substring(8,10);
                                String nowHour = nowTime.substring(11,13);
                                String nowMinute = nowTime.substring(14,16);
                                String nowSecond = nowTime.substring(17,19);
 
                                String nowYearHex = Integer.toHexString(Integer.parseInt(nowYear));
                                if(nowYearHex.length() == 1){
                                    nowYearHex = "0" + nowYearHex;
                                }
                                String nowMonthHex = Integer.toHexString(Integer.parseInt(nowMonth));
                                if(nowMonthHex.length() == 1){
                                    nowMonthHex = "0" + nowMonthHex;
                                }
                                String nowDayHex = Integer.toHexString(Integer.parseInt(nowDay));
                                if(nowDayHex.length() == 1){
                                    nowDayHex = "0" + nowDayHex;
                                }
                                String nowHourHex = Integer.toHexString(Integer.parseInt(nowHour));
                                if(nowHourHex.length() == 1){
                                    nowHourHex = "0" + nowHourHex;
                                }
                                String nowMinuteHex = Integer.toHexString(Integer.parseInt(nowMinute));
                                if(nowMinuteHex.length() == 1){
                                    nowMinuteHex = "0" + nowMinuteHex;
                                }
                                String nowSecondHex = Integer.toHexString(Integer.parseInt(nowSecond));
                                if(nowSecondHex.length() == 1){
                                    nowSecondHex = "0" + nowSecondHex;
                                }
                                //16进制时间
                                String timeHex = nowYearHex + nowMonthHex + nowDayHex + nowHourHex + nowMinuteHex + nowSecondHex;
                                String lockNumHead = ardTankLockResult.get(0).getLockNum().substring(0,2);
                                String lockNumTail = ardTankLockResult.get(0).getLockNum().substring(2,4);
                                //计算校验
                                String checkNum = Integer.toHexString(Integer.parseInt(lockNumHead, 16) + Integer.parseInt(lockNumTail, 16) + Integer.parseInt("08", 16) +
                                        Integer.parseInt(nowYearHex, 16) + Integer.parseInt(nowMonthHex, 16) + Integer.parseInt(nowDayHex, 16) +
                                        Integer.parseInt(nowHourHex, 16) + Integer.parseInt(nowMinuteHex, 16) + Integer.parseInt(nowSecondHex, 16));
                                if(checkNum.length() == 1){
                                    checkNum = "0" + checkNum;
                                }else if(checkNum.length() > 2){
                                    checkNum = checkNum.substring(checkNum.length() - 2,checkNum.length());
                                }
                                String paramsStr = "%7B%22type%22%3A%22ff%22%2C%22dataCnt%22%3A%22" + ardTankLock.getLockNum() + "08" + timeHex + checkNum + "%22%7D";
                                System.out.println(ardTankLock.getLockNum() + "08" + timeHex + checkNum);
                                sendCmd(url,userId,ardTankLockResult.get(0).getCarId(),199,"DataDownTransfer", paramsStr,sessionId);*/
                                return;
                            }else{
                                ArdTankLockState ardTankLockState = new ArdTankLockState();
                                ardTankLockState.setId(IdUtils.simpleUUID());
                                ardTankLockState.setLockId(ardTankLockResult.get(0).getId());
                                ardTankLockState.setLockNum(lockNum);
                                switch (lockState) {//锁芯状态
                                    case "01": ardTankLockState.setLockState("开锁状态");break;
                                    case "02": ardTankLockState.setLockState("关锁状态");break;
                                    case "03": ardTankLockState.setLockState("异常状态");break;
                                    case "04": ardTankLockState.setLockState("动作状态");break;
                                    default:
                                        break;
                                }
                                switch (lockPositionState) {//位置状态
                                    case "01": ardTankLockState.setLockPositionState("正常");break;
                                    case "02": ardTankLockState.setLockPositionState("异常");break;
                                    default:
                                        break;
                                }
                                switch (lockShellState) {//外壳状态
                                    case "01": ardTankLockState.setLockShellState("正常");break;
                                    case "02": ardTankLockState.setLockShellState("异常");break;
                                    default:
                                        break;
                                }
                                switch (restartState) {//复位状态
                                    case "01": ardTankLockState.setRestartState("开锁状态");break;
                                    case "02": ardTankLockState.setRestartState("关锁状态");break;
                                    default:
                                        break;
                                }
                                Number batterVoltageNum = Integer.parseInt(batterVoltage,16) * 0.1;
                                String batterVoltageStr = String.valueOf(batterVoltageNum);
                                if(batterVoltageStr.length() > 4){
                                    batterVoltageStr = batterVoltageStr.substring(0,4);
                                }
                                if(batterVoltageStr.contains(".")){//四舍五入
                                    String decimalPart = batterVoltageStr.split("\\.")[1];
                                    if(Integer.parseInt(decimalPart) > 5){
                                        batterVoltageStr = batterVoltageStr.split("\\.")[0] + ".5";
                                    }else if(Integer.parseInt(decimalPart) <= 5){
                                        batterVoltageStr = batterVoltageStr.split("\\.")[0] + ".0";
                                    }
                                }else{
                                    batterVoltageStr = batterVoltageStr + ".0";
                                }
                                ardTankLockState.setBatterVoltage(batterVoltageStr);
 
 
                                Number powerVoltageNum = Integer.parseInt(powerVoltage,16) * 0.1;
                                String powerVoltageStr = String.valueOf(powerVoltageNum);
                                if(powerVoltageStr.length() > 4){
                                    powerVoltageStr = powerVoltageStr.substring(0,4);
                                }
                                if(powerVoltageStr.contains(".")){//四舍五入
                                    String decimalPart = powerVoltageStr.split("\\.")[1];
                                    if(Integer.parseInt(decimalPart) > 5){
                                        powerVoltageStr = powerVoltageStr.split("\\.")[0] + ".5";
                                    }else if(Integer.parseInt(decimalPart) <= 5){
                                        powerVoltageStr = powerVoltageStr.split("\\.")[0] + ".0";
                                    }
                                }else{
                                    powerVoltageStr = powerVoltageStr + ".0";
                                }
                                ardTankLockState.setPowerVoltage(powerVoltageStr);
 
                                String uniqueMark = lockNum + "," + lockState + "," + lockPositionState + "," + lockShellState
                                        + "," + restartState + "," + batterVoltageStr + "," + powerVoltageStr;
 
                                ardTankLockState.setUploadTime(time);
                                ardTankLockState.setUniqueMark(uniqueMark);
                                ((ArdTankLockStateServiceImpl)SpringUtils.getBean("ardTankLockStateServiceImpl")).insertOrUpdateArdTankLockState(ardTankLockState);
                            }
                        }else if(code.equals("05")){//功能码05为读取锁密码
                            Set<String> passwordAndTimeSet = new HashSet();
                            for(int i = 1;i <= 10;i++){
                                String passwordAndTime = data.substring(6 + 24*(i - 1),6 + 24 * i);
                                passwordAndTimeSet.add(passwordAndTime);//拆分出密码和使用时间
                            }
                            if(passwordAndTimeSet.size() == 1){//全部为初始密码,则从新设置
                                Set<String> passwordSet = new HashSet();
                                while(passwordSet.size() != 10){
                                    String password = "";
                                    for(int i = 0;i <= 5;i++){
                                        password = password + String.valueOf(10 * Math.random()).split("\\.")[0];
                                    }
                                    passwordSet.add(password);
                                }
                                if(PositionContainer.getCarLockPasswordMap().get(lockNum) == null){
                                    PositionContainer.getCarLockPasswordMap().put(lockNum,passwordSet);
                                }
                            }else{//查看哪些密码使用过
                                for(String passwordAndTime : passwordAndTimeSet){
                                    String time = passwordAndTime.substring(12,24);
                                    if(!time.equals("FFFFFFFFFFFF")){
                                        String passwordHex = passwordAndTime.substring(0,12);//16进制密码
                                        String password = "";//实际密码
                                        for(int i = 0;i <= 10;i = i + 2){
                                            String passwordHexByte = passwordHex.substring(i, i+2);
                                            password = password + passwordHexByte.split("")[1];
                                        }
 
                                        String useTimeHex = passwordAndTime.substring(12,24);//16进制时间
                                        String yearHex = useTimeHex.substring(0, 2);
                                        String monthHex = useTimeHex.substring(2, 4);
                                        String dayHex = useTimeHex.substring(4, 6);
                                        String hourHex = useTimeHex.substring(6, 8);
                                        String minuteHex = useTimeHex.substring(8, 10);
                                        String secondHex = useTimeHex.substring(10, 12);
 
                                        String useTime = "";
                                        Integer yearNum = Integer.parseInt(yearHex, 16);
                                        if(yearNum <= 9){
                                            useTime = "200" + yearNum + "-";
                                        }else{
                                            useTime = "20" + yearNum + "-";
                                        }
 
                                        Integer monthNum = Integer.parseInt(monthHex, 16);
                                        if(monthNum <= 9){
                                            useTime = useTime + "0" + monthNum + "-";
                                        }else{
                                            useTime = useTime + monthNum + "-";
                                        }
 
                                        Integer dayNum = Integer.parseInt(dayHex, 16);
                                        if(dayNum <= 9){
                                            useTime = useTime + "0" + dayNum + " ";
                                        }else{
                                            useTime = useTime + dayNum + " ";
                                        }
 
                                        Integer hourNum = Integer.parseInt(hourHex, 16);
                                        if(hourNum <= 9){
                                            useTime = useTime + "0" + hourNum + ":";
                                        }else{
                                            useTime = useTime + hourNum + ":";
                                        }
 
                                        Integer minuteNum = Integer.parseInt(minuteHex, 16);
                                        if(minuteNum <= 9){
                                            useTime = useTime + "0" + minuteNum + ":";
                                        }else{
                                            useTime = useTime + minuteNum + ":";
                                        }
 
                                        Integer secondNum = Integer.parseInt(secondHex, 16);
                                        if(secondNum <= 9){
                                            useTime = useTime + "0" + secondNum;
                                        }else{
                                            useTime = useTime + secondNum;
                                        }
                                        ((ArdTankLockPasswordServiceImpl)SpringUtils.getBean("ardTankLockPasswordServiceImpl")).updateArdTankLockPasswordByLockNum(lockNum,password,useTime);
                                    }
                                }
                            }
                        }
                    }catch (Exception e){
                        e.printStackTrace();
                        return;//强转失败返回
                    }
                }
            };
            thread.start();
            /**
             *
             * 请加入三方集成方的业务逻辑
             *
             */
        }
    }
 
    public void sendMassage() {
        try {
            PushClientImplSerialPort client = new PushClientImplSerialPort();
            client.setLog(false);//是否打印明文
            client.setHost(this.ip);//服务器IP
            client.setPort(10100);//服务器端口
            client.setUserName(this.userId);//系统用户名
            client.setPwd(this.password);//系统用户密码
            client.setSubMsgIds("0401");//订阅的动态消息,多个动态消息使用|辟分,当前示例是订阅  定位消息(0x0200)和报警消息(0x0300)
            client.setDesc("测试客户端");//客户端的描述,
            client.start();
            while(true) {
                Thread.sleep(1000);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
 
    @Override
    public void run() {
        sendMassage();
    }
 
    public static Map<String,Object> loginIn(String syURL,String userId,String password){//登录
        OkHttpClient okHttpClient = new OkHttpClient();
 
        String passwordMd5 = DigestUtils.md5Hex(password);
 
        Request request = new Request.Builder()
                .url(syURL + "/gps-web/api/login.jsp?"+"password="+passwordMd5+"&userId="+userId+"&loginType=user&loginWay=interface&loginLang=zh_CN")
                .build();
        Response response = null;
        try {
            response = okHttpClient.newCall(request).execute();
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
 
        response.headers(); //响应头
 
        okhttp3.ResponseBody responseBody = response.body();
 
        try {
            String message = responseBody.string();// 响应体
            Map<String,Object> map = (Map<String, Object>) JSON.parse(message);
            map.put("passwordMd5", passwordMd5);
            //System.out.println(message);
            return map;
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return new HashMap();
        }
    }
 
    public Map<String,Object> sendCmd(String syURL,String userId,String carId,Integer cmdId,String cmd,String paramsStr,String sessionId){
        OkHttpClient okHttpClient = new OkHttpClient();
 
        Request request = new Request.Builder()
                .url(syURL + "/gps-web/api/send_cmd.jsp?params="+paramsStr+"&userId="+userId+"&carId="+carId+"&cmdId="+cmdId+"&cmd="+cmd+"&sessionId="+sessionId)
                .build();
        //System.out.println("url = " + syURL + "/gps-web/api/send_cmd.jsp?params="+paramsStr+"&userId="+userId+"&carId="+carId+"&cmdId="+cmdId+"&cmd="+cmd+"&sessionId="+sessionId);
        Response response = null;
        try {
            response = okHttpClient.newCall(request).execute();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
 
        okhttp3.ResponseBody responseBody = response.body();
 
        try {
            String message = responseBody.string();// 响应体
            Map<String,Object> map = (Map<String, Object>) JSON.parse(message);
            return map;
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return new HashMap();
        }
    }
 
}