Pārlūkot izejas kodu

[功能修复]兼容1.5和1.6

liuf 1 gadu atpakaļ
vecāks
revīzija
0a9e954e6d
21 mainītis faili ar 1466 papildinājumiem un 711 dzēšanām
  1. 2 0
      src/main/java/com/tmzn/devicelinkykc/entity/BillingModel.java
  2. 1 1
      src/main/java/com/tmzn/devicelinkykc/frameMsg/FrameDataSplicing.java
  3. 138 0
      src/main/java/com/tmzn/devicelinkykc/frameMsg/frameType/BillingModelFrame.java
  4. 5 4
      src/main/java/com/tmzn/devicelinkykc/frameMsg/frameType/LoginFrame.java
  5. 509 5
      src/main/java/com/tmzn/devicelinkykc/frameMsg/frameType/TransactionFlowPushFrame.java
  6. 25 23
      src/main/java/com/tmzn/devicelinkykc/message/DeviceMsgHandle.java
  7. 150 193
      src/main/java/com/tmzn/devicelinkykc/message/YkcMsgHandle.java
  8. 1 0
      src/main/java/com/tmzn/devicelinkykc/msgEnum/DeviceSendYkc.java
  9. 2 0
      src/main/java/com/tmzn/devicelinkykc/msgEnum/YkcSendDevice.java
  10. 3 0
      src/main/java/com/tmzn/devicelinkykc/socket/SocketHandle.java
  11. 11 0
      src/main/java/com/tmzn/devicelinkykc/taskQueue/HeartTask.java
  12. 0 2
      src/main/java/com/tmzn/devicelinkykc/taskQueue/StartTask.java
  13. 134 134
      src/main/java/com/tmzn/devicelinkykc/taskQueue/TransCheckTask.java
  14. 3 4
      src/main/java/com/tmzn/devicelinkykc/taskQueue/queue/MsgCharngingQueue.java
  15. 3 4
      src/main/java/com/tmzn/devicelinkykc/taskQueue/queue/MsgFreeQueue.java
  16. 5 5
      src/main/java/com/tmzn/devicelinkykc/taskQueue/queue/MsgHeartQueue.java
  17. 3 2
      src/main/java/com/tmzn/devicelinkykc/taskQueue/queue/MsgTranscationQueue.java
  18. 16 334
      src/main/java/com/tmzn/devicelinkykc/taskQueue/queue/TaskRunner.java
  19. 170 0
      src/main/java/com/tmzn/devicelinkykc/taskQueue/runner/MsgFreeRunner.java
  20. 120 0
      src/main/java/com/tmzn/devicelinkykc/taskQueue/runner/MsgHeartRunner.java
  21. 165 0
      src/main/java/com/tmzn/devicelinkykc/taskQueue/runner/MsgTranscationRunner.java

+ 2 - 0
src/main/java/com/tmzn/devicelinkykc/entity/BillingModel.java

@@ -49,6 +49,8 @@ public class BillingModel implements Serializable {
     private BigDecimal flatServiceFee=BigDecimal.ZERO;
     private BigDecimal valleyPrice=BigDecimal.ZERO;
     private BigDecimal valleyServiceFee=BigDecimal.ZERO;
+    private BigDecimal deepValleyPrice=BigDecimal.ZERO;
+    private BigDecimal deepValleyServiceFee=BigDecimal.ZERO;
     private int lossRatio;
     private String timeSlot;
     private long updateTime;

+ 1 - 1
src/main/java/com/tmzn/devicelinkykc/frameMsg/FrameDataSplicing.java

@@ -36,7 +36,7 @@ public class FrameDataSplicing {
         outBuf[index++] = (byte) frameType;
         System.arraycopy(data, 0, outBuf, index, length);
         index += length;
-        int crc = 0;
+        int crc;
         if(is18){
              crc = modbusCRC(Arrays.copyOfRange(outBuf, 2, index), index - 2);
         }else{

+ 138 - 0
src/main/java/com/tmzn/devicelinkykc/frameMsg/frameType/BillingModelFrame.java

@@ -1,10 +1,13 @@
 package com.tmzn.devicelinkykc.frameMsg.frameType;
 
+import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
 import com.tmzn.devicelinkykc.constant.RedisConstant;
+import com.tmzn.devicelinkykc.entity.BillingModel;
 import com.tmzn.devicelinkykc.frameMsg.DataConversion;
 import com.tmzn.devicelinkykc.frameMsg.FrameDataSplicing;
 import com.tmzn.devicelinkykc.msgEnum.DeviceSendYkc;
 import com.tmzn.devicelinkykc.redis.RedisCache;
+import com.tmzn.devicelinkykc.service.BillingModelService;
 import com.tmzn.devicelinkykc.socket.DeviceConnectionMsg;
 import com.tmzn.devicelinkykc.util.Encrytion;
 import lombok.extern.slf4j.Slf4j;
@@ -12,6 +15,8 @@ import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Component;
 
 import java.io.IOException;
+import java.math.BigDecimal;
+import java.util.Arrays;
 
 /**
  * @author xp
@@ -24,6 +29,8 @@ public class BillingModelFrame {
     @Autowired
     private RedisCache redisCache;
 
+    @Autowired
+    private BillingModelService billingModelService;
 
     /**
      * 校验计费模型
@@ -156,5 +163,136 @@ public class BillingModelFrame {
         return msg;
     }
 
+    /**
+     * 计费模型请求处理,需要将获取到的云快充计费模型保存到数据库中
+     * @param deviceConnectionMsg
+     * @param respone_msg
+     */
+    public void setSgBillingModel(DeviceConnectionMsg deviceConnectionMsg, byte[] respone_msg)  throws Exception{
+        int index=7;
+        int a=0;
+        byte[] modelNum = Arrays.copyOfRange(respone_msg, index, index+2);
+        index+=2;
+        byte[] j = Arrays.copyOfRange(respone_msg, index, index+4);
+        index+=4;
+        byte[] jf = Arrays.copyOfRange(respone_msg, index, index+4);
+        index+=4;
+        byte[]  f= Arrays.copyOfRange(respone_msg, index, index+4);
+        index+=4;
+        byte[] ff = Arrays.copyOfRange(respone_msg, index, index+4);
+        index+=4;
+        byte[] p = Arrays.copyOfRange(respone_msg, index, index+4);
+        index+=4;
+        byte[] pf = Arrays.copyOfRange(respone_msg, index, index+4);
+        index+=4;
+        byte[] g = Arrays.copyOfRange(respone_msg, index, index+4);
+        index+=4;
+        byte[] gf = Arrays.copyOfRange(respone_msg, index, index+4);
+        index+=4;
+
+        byte[] dg = Arrays.copyOfRange(respone_msg, index, index+4);
+        index+=4;
+        byte[] dgf = Arrays.copyOfRange(respone_msg, index, index+4);
+        index+=4;
+
+        byte[] solt = Arrays.copyOfRange(respone_msg, index, index+1);
+        index++;
+        byte[] shiduan  = Arrays.copyOfRange(respone_msg, index, respone_msg.length);
+        QueryWrapper<BillingModel> billingModelQueryWrapper = new QueryWrapper<>();
+        billingModelQueryWrapper.eq("pile_code",deviceConnectionMsg.getDeviceId());
+        BillingModel one = billingModelService.getOne(billingModelQueryWrapper);
+        if (one==null){
+            one = new BillingModel();
+        }
+        BigDecimal bigDecimal = DataConversion.arrToBigDec(modelNum, 0,0);
+        int intValue = bigDecimal.intValue();
+        one.setDeviceImei(deviceConnectionMsg.getImei());
+        one.setDeviceSn(deviceConnectionMsg.getDeviceSn());
+        one.setPileCode(deviceConnectionMsg.getDeviceId());
+        one.setModelNo(intValue);
+        one.setSharpPrice(DataConversion.arrToBigDec(j,5,5));         //尖
+        one.setSharpServiceFee(DataConversion.arrToBigDec(jf,5,5));   //尖服
+        one.setPeakPrice(DataConversion.arrToBigDec(f,5,5));          //峰
+        one.setPeakServiceFee(DataConversion.arrToBigDec(ff,5,5));    //峰服
+        one.setFlatPrice(DataConversion.arrToBigDec(p,5,5));         //平
+        one.setFlatServiceFee(DataConversion.arrToBigDec(pf,5,5));   //平服
+        one.setValleyPrice(DataConversion.arrToBigDec(g,5,5));          //谷
+        one.setValleyServiceFee(DataConversion.arrToBigDec(gf,5,5));    //谷服
+        one.setDeepValleyPrice(DataConversion.arrToBigDec(dg,5,5)); //深谷
+        one.setDeepValleyServiceFee(DataConversion.arrToBigDec(dgf,5,5));//深谷服
+
+        int integer= Integer.valueOf(Byte.toString(solt[0]));  //计损比例
+        one.setLossRatio(integer);                                               //时间段
+        StringBuilder stringBuilder = new StringBuilder();
+        for (byte b : shiduan) {
+            stringBuilder.append(String.valueOf(b));
+        }
+        String s = stringBuilder.toString();
+        one.setTimeSlot(s);
+        one.setUpdateTime(System.currentTimeMillis());//更新时间
+        billingModelService.saveOrUpdate(one);
+    }
+
+    /**
+     * 计费模型请求处理,需要将获取到的云快充计费模型保存到数据库中
+     * @param deviceConnectionMsg
+     * @param respone_msg
+     */
+    public void setBillingModel(DeviceConnectionMsg deviceConnectionMsg, byte[] respone_msg)  throws Exception{
+        int index=7;
+        int a=0;
+        byte[] modelNum = Arrays.copyOfRange(respone_msg, index, index+2);
+        index+=2;
+        byte[] j = Arrays.copyOfRange(respone_msg, index, index+4);
+        index+=4;
+        byte[] jf = Arrays.copyOfRange(respone_msg, index, index+4);
+        index+=4;
+        byte[]  f= Arrays.copyOfRange(respone_msg, index, index+4);
+        index+=4;
+        byte[] ff = Arrays.copyOfRange(respone_msg, index, index+4);
+        index+=4;
+        byte[] p = Arrays.copyOfRange(respone_msg, index, index+4);
+        index+=4;
+        byte[] pf = Arrays.copyOfRange(respone_msg, index, index+4);
+        index+=4;
+        byte[] g = Arrays.copyOfRange(respone_msg, index, index+4);
+        index+=4;
+        byte[] gf = Arrays.copyOfRange(respone_msg, index, index+4);
+        index+=4;
+        byte[] solt = Arrays.copyOfRange(respone_msg, index, index+1);
+        index++;
+        byte[] shiduan  = Arrays.copyOfRange(respone_msg, index, respone_msg.length);
+        QueryWrapper<BillingModel> billingModelQueryWrapper = new QueryWrapper<>();
+        billingModelQueryWrapper.eq("pile_code",deviceConnectionMsg.getDeviceId());
+        BillingModel one = billingModelService.getOne(billingModelQueryWrapper);
+        if (one==null){
+            one = new BillingModel();
+        }
+        BigDecimal bigDecimal = DataConversion.arrToBigDec(modelNum, 0,0);
+        int intValue = bigDecimal.intValue();
+        one.setDeviceImei(deviceConnectionMsg.getImei());
+        one.setDeviceSn(deviceConnectionMsg.getDeviceSn());
+        one.setPileCode(deviceConnectionMsg.getDeviceId());
+        one.setModelNo(intValue);
+        one.setSharpPrice(DataConversion.arrToBigDec(j,5,5));         //尖
+        one.setSharpServiceFee(DataConversion.arrToBigDec(jf,5,5));   //尖服
+        one.setPeakPrice(DataConversion.arrToBigDec(f,5,5));          //峰
+        one.setPeakServiceFee(DataConversion.arrToBigDec(ff,5,5));    //峰服
+        one.setFlatPrice(DataConversion.arrToBigDec(p,5,5));         //平
+        one.setFlatServiceFee(DataConversion.arrToBigDec(pf,5,5));   //平服
+        one.setValleyPrice(DataConversion.arrToBigDec(g,5,5));          //谷
+        one.setValleyServiceFee(DataConversion.arrToBigDec(gf,5,5));    //谷服
+        int integer= Integer.valueOf(Byte.toString(solt[0]));  //计损比例
+        one.setLossRatio(integer);                                               //时间段
+        StringBuilder stringBuilder = new StringBuilder();
+        for (byte b : shiduan) {
+            stringBuilder.append(String.valueOf(b));
+        }
+        String s = stringBuilder.toString();
+        one.setTimeSlot(s);
+        one.setUpdateTime(System.currentTimeMillis());//更新时间
+        billingModelService.saveOrUpdate(one);
+    }
+
 
 }

+ 5 - 4
src/main/java/com/tmzn/devicelinkykc/frameMsg/frameType/LoginFrame.java

@@ -35,25 +35,27 @@ public class LoginFrame {
     @Autowired
     private RedisCache redisCache;
 
+    @Autowired
+    private BillingModelFrame billingModelFrame;
+
+
     @Autowired
     private GdDispostionService gdDispostionService;
 
     public void loginMsgSend(DeviceConnectionMsg deviceConnectionMsg,Device device){
         byte[] send = new byte[0];
         try {
-
             if(deviceConnectionMsg.getIs18()){
                 send = loginMsg18(device);
             }else{
                 send = loginMsgNot18(device);
             }
-
         } catch (Exception e) {
             log.info("pileCode:"+device.getPileCode()+" login params Exception:");
             e.printStackTrace();
         }
         if (send.length>0) {
-            log.info("loginMsgSend>设备登录消息上送>>>"+DataConversion.bytesToHexString(send));
+            log.info("{}>设备登录消息上送>>>"+DataConversion.bytesToHexString(send),device.getPileCode());
             byte[] bytes = FrameDataSplicing.spliceing(deviceConnectionMsg.getMessageCount(), DeviceSendYkc.LOGIN.getFrameType(), DeviceSendYkc.LOGIN.getEncryptFlag(), send, send.length, deviceConnectionMsg.getIs18());
             try {
                 deviceConnectionMsg.getOutputStream().write(bytes);
@@ -65,7 +67,6 @@ public class LoginFrame {
                 //发送异常直接停止
                 socketHandle.removeDeviceConnection(device.getPileCode());
             }
-
         }else {
             log.info("pileCode:"+device.getPileCode()+" login params null");
         }

+ 509 - 5
src/main/java/com/tmzn/devicelinkykc/frameMsg/frameType/TransactionFlowPushFrame.java

@@ -68,9 +68,9 @@ public class TransactionFlowPushFrame {
 
                 //log.info("sendTrans>订单上送>>>"+DataConversion.bytesToHexString(params));
                 String key = redisCache.getCacheObject(RedisConstant.KEYS+deviceConnectionMsg.getDeviceId());
-                log.info("key>订单消息加密密钥>>>"+key);
+                log.info("key>{}订单消息加密密钥>>>"+key,deviceConnectionMsg.getDeviceId());
                 encrypt = Encrytion.aesEncrypt(params, key.getBytes());
-                log.info("msg>订单加密消息>>>"+DataConversion.bytesToHexString(encrypt));
+                log.info("msg>{}订单加密消息>>>"+DataConversion.bytesToHexString(encrypt),deviceConnectionMsg.getDeviceId());
             } catch (Exception e) {
                 log.info("pileCode:" + pileCode + " TransactionFlowPush params Exception");
                 e.printStackTrace();
@@ -98,12 +98,24 @@ public class TransactionFlowPushFrame {
             return encrypt;
         }
 
+        //todo 深谷5档位模型
+        byte[] params;
+        int frameType;
+        if(billingModel.getDeepValleyPrice().compareTo(BigDecimal.ZERO)>0 || billingModel.getDeepValleyServiceFee().compareTo(BigDecimal.ZERO)>0){
+            //5档计费
+             params = paramsSg(transOrder, pileCode, gunPort, createTime, endTime, billingModel, card, map,reason);
+             frameType = DeviceSendYkc.TRANSACTION_RECORDS_REQUEST_SG.getFrameType();
+        }else{
+            //4档计费
+             params = params16(transOrder, pileCode, gunPort, createTime, endTime, billingModel, card, map,reason);
+             frameType = DeviceSendYkc.TRANSACTION_RECORDS_REQUEST_16.getFrameType();
+        }
+
         byte[] encrypt = new byte[0];
         // 缓存上报的订单,上报失败30秒重试,
         TransCheck transCheck = new TransCheck();
         try {
             //密钥变化这里存订单明文
-            byte[] params = params(transOrder, pileCode, gunPort, createTime, endTime, billingModel, card, map,reason);
             transCheck.setTrans(params);
             transCheck.setCheck_time(0);
             transCheck.setTime(System.currentTimeMillis());
@@ -114,14 +126,13 @@ public class TransactionFlowPushFrame {
             return pileCode.getBytes();
         }
         if (encrypt.length > 0) {
-            byte[] bytes = FrameDataSplicing.spliceing(deviceConnectionMsg.getMessageCount(), DeviceSendYkc.TRANSACTION_RECORDS_REQUEST_16.getFrameType(), 0, encrypt, encrypt.length, deviceConnectionMsg.getIs18());
+            byte[] bytes = FrameDataSplicing.spliceing(deviceConnectionMsg.getMessageCount(),frameType , 0, encrypt, encrypt.length, deviceConnectionMsg.getIs18());
             try {
                 //outputStream..write(bytes)
                 //log.info("bytes>上送订单加密消息>>>"+DataConversion.bytesToHexString(bytes));
                 // log.info("bytes.length>上送订单加密length>>>"+bytes.length);
                 deviceConnectionMsg.getOutputStream().write(bytes);
                 deviceConnectionMsg.getOutputStream().flush();
-
                 //只有发送了才将校验订单写到redis里
                 redisCache.setCacheObject(RedisConstant.NO_RESPONSE_WAS_RECEIVED+pileCode,transCheck,6,TimeUnit.MINUTES);
             } catch (IOException e) {
@@ -137,6 +148,499 @@ public class TransactionFlowPushFrame {
 
     }
 
+    public byte[] paramsSg(byte[] transOrder, String pileCode, byte gunPort, long createTime, long endTime, BillingModel billingModel, byte[] card, Map<String, BigDecimal> map,int reason) {
+        //订单创建时间0和预留原因不存库
+        if (createTime > 0||reason!=TransConstant.START_FAIL) {
+            try {
+                //TODO:测试存订单
+                byte[] transOrders = new byte[8];
+                System.arraycopy(transOrder, 8, transOrders, 0, transOrders.length);
+                QueryWrapper<TransOrder> transOrderQueryWrapper = new QueryWrapper<>();
+                transOrderQueryWrapper.eq("trans", DataConversion.bytesToHexString(transOrders)).eq("pile_code", pileCode);
+                TransOrder transOrderServiceOne = transOrderService.getOne(transOrderQueryWrapper);
+                transOrderServiceOne.setStartTime(new Date(createTime));
+                transOrderServiceOne.setEndTime(new Date(endTime));
+                transOrderServiceOne.setSharpElec(map.get("elec1"));
+                transOrderServiceOne.setSharpMoney(map.get("money1"));
+                transOrderServiceOne.setPeakElec(map.get("elec2"));
+                transOrderServiceOne.setPeakMoney(map.get("money2"));
+                transOrderServiceOne.setFlatElec(map.get("elec3"));
+                transOrderServiceOne.setFlatMoney(map.get("money3"));
+                transOrderServiceOne.setValleyElec(map.get("elec4"));
+                transOrderServiceOne.setValleyMoney(map.get("money4"));
+                transOrderServiceOne.setElec(map.get("elec"));
+                transOrderServiceOne.setMoney(map.get("money"));
+                transOrderServiceOne.setReasonStopCharging(reason);
+                transOrderService.updateById(transOrderServiceOne);
+                //TODO:测试存订单
+            }catch(Exception e){
+                e.printStackTrace();
+            }
+            redisCache.deleteObject(RedisConstant.DEVICE_CHARNGING_INFO + pileCode + gunPort);
+        }
+        int index = 0;
+        byte[] msg = new byte[174];
+        //1.交易流水
+        byte[] trans = new byte[16];
+        System.arraycopy(transOrder, 0, trans, 0, transOrder.length);
+        System.arraycopy(trans, 0, msg, index, trans.length);
+        index += trans.length;
+
+        //2. 桩编码 BCD
+        byte[] pile_code = new byte[7];
+        System.arraycopy(DataConversion.bcdToBytes(pileCode, 7), 0, msg, index, pile_code.length);
+        index += pile_code.length;
+//3.枪号
+        byte[] guns = {gunPort};
+        System.arraycopy(guns, 0, msg, index, guns.length);
+        index += guns.length;
+
+        //4.开始时间
+        Date sdate = new Date(createTime);
+        byte[] startTime = new byte[7];
+        SimpleDateFormat se = new SimpleDateFormat("SS-ss-mm-HH-dd-MM-yy");
+        String sformat = se.format(sdate).substring(1);
+        startTime = CP56Time2a.timeCP56Time2a(sformat);
+        System.arraycopy(startTime, 0, msg, index, startTime.length);
+        index += startTime.length;
+
+        //5.结束时间
+        Date date = new Date(endTime);
+        byte[] time = new byte[7];
+        String format = se.format(date).substring(1);
+        time = CP56Time2a.timeCP56Time2a(format);
+        System.arraycopy(time, 0, msg, index, time.length);
+        index += time.length;
+
+
+        //   10 尖单价 BIN 4 精确到小数点后五位(尖电费 + 尖 服务费,见费率帧)
+        byte[] bytes4 = DataConversion.bin4Tofiv((billingModel.getSharpPrice().add(billingModel.getSharpServiceFee())).setScale(5));
+        //bytes4 = Transaction.temp(bytes4);
+        System.arraycopy(bytes4, 0, msg, index, bytes4.length);
+        index += bytes4.length;
+
+        //   11 尖电量 BIN 4 精确到小数点后四位
+        byte[] bytes5 = DataConversion.bin4Tofour(map.get("elec1").setScale(4));
+        //bytes5 = Transaction.temp(bytes5);
+        System.arraycopy(bytes5, 0, msg, index, bytes5.length);
+        index += bytes5.length;
+
+        //   12 计损尖电量 BIN 4 精确到小数点后四位
+        byte[] bytes6 = DataConversion.bin4Tofour(zero);
+        //  bytes6 = Transaction.temp(bytes6);
+        System.arraycopy(bytes6, 0, msg, index, bytes6.length);
+        index += bytes6.length;
+
+        //   13 尖金额 BIN 4 精确到小数点后四位
+        byte[] bytes7 = new byte[4];
+        bytes7 = DataConversion.bin4Tofour(map.get("money1").setScale(4));
+        System.arraycopy(bytes7, 0, msg, index, bytes7.length);
+        index += bytes7.length;
+
+        //   14 峰单价 BIN 4 精确到小数点后五位(峰电费 + 峰 服务费)
+        byte[] bytes8 = DataConversion.bin4Tofiv((billingModel.getPeakPrice().add(billingModel.getPeakServiceFee())).setScale(5));
+        // bytes8 = Transaction.temp(bytes8);
+        System.arraycopy(bytes8, 0, msg, index, bytes8.length);
+        index += bytes8.length;
+
+        //   15 峰电量 BIN 4 精确到小数点后四位
+        byte[] bytes9 = DataConversion.bin4Tofour(map.get("elec2").setScale(4));
+        //bytes9 = Transaction.temp(bytes9);
+        System.arraycopy(bytes9, 0, msg, index, bytes9.length);
+        index += bytes9.length;
+
+        //   16 计损峰电量 BIN 4 精确到小数点后四位
+        byte[] bytesa = DataConversion.bin4Tofour(zero);
+        //bytesa = Transaction.temp(bytesa);
+        System.arraycopy(bytesa, 0, msg, index, bytesa.length);
+        index += bytesa.length;
+
+        //   17 峰金额 BIN 4 精确到小数点后四位
+        byte[] bytesb = DataConversion.bin4Tofour(map.get("money2").setScale(4));
+        // bytesb = Transaction.temp(bytesb);
+        System.arraycopy(bytesb, 0, msg, index, bytesb.length);
+        index += bytesb.length;
+
+        //   18 平单价 BIN 4 精确到小数点后五位(平电费 + 平 服务费)
+
+        byte[] bytesc = DataConversion.bin4Tofiv((billingModel.getFlatPrice().add(billingModel.getFlatServiceFee())).setScale(5));
+        //bytesc = Transaction.temp(bytesc);
+        System.arraycopy(bytesc, 0, msg, index, bytesc.length);
+        index += bytesc.length;
+
+        //   19 平电量 BIN 4 精确到小数点后四位
+        byte[] bytesd = new byte[4];
+
+        bytesd = DataConversion.bin4Tofour(map.get("elec3").setScale(4));
+        // bytesd = Transaction.temp(bytesd);
+        System.arraycopy(bytesd, 0, msg, index, bytesd.length);
+        index += bytesd.length;
+
+        //   20 计损平电量 BIN 4 精确到小数点后四位
+        byte[] bytese = DataConversion.bin4Tofour(zero);
+        //bytese = Transaction.temp(bytese);
+        System.arraycopy(bytese, 0, msg, index, bytese.length);
+        index += bytese.length;
+
+        //   21 平金额 BIN 4 精确到小数点后四位
+        byte[] bytesf = new byte[4];
+
+        bytesf = DataConversion.bin4Tofour(map.get("money3").setScale(4).setScale(4));
+        // bytesf = Transaction.temp(bytesf);
+        System.arraycopy(bytesf, 0, msg, index, bytesf.length);
+        index += bytesf.length;
+
+        //   22 谷单价 BIN 4 精确到小数点后五位(谷电费 + 谷 服务费)
+        byte[] bytesg = DataConversion.bin4Tofiv((billingModel.getValleyPrice().add(billingModel.getValleyServiceFee())).setScale(5));
+        //  bytesg = Transaction.temp(bytesg);
+        System.arraycopy(bytesg, 0, msg, index, bytesg.length);
+        index += bytesg.length;
+
+        //   23 谷电量 BIN 4 精确到小数点后四位
+        byte[] bytesh = new byte[4];
+        bytesh = DataConversion.bin4Tofour(map.get("elec4").setScale(4));//测试
+
+        //byte[] bytesh = DataConversion.four(transaction.getValleyElec());
+        System.arraycopy(bytesh, 0, msg, index, bytesh.length);
+        index += bytesh.length;
+
+        //   24 计损谷电量 BIN 4 精确到小数点后四位
+        byte[] bytesi = DataConversion.bin4Tofour(zero);
+        // bytesi = Transaction.temp(bytesi);
+        System.arraycopy(bytesi, 0, msg, index, bytesi.length);
+        index += bytesi.length;
+
+        //   25 谷金额 BIN 4 精确到小数点后四位
+        byte[] bytesj = new byte[4];
+        bytesj = DataConversion.bin4Tofour(map.get("money4").setScale(4));
+        //byte[] bytesj = DataConversion.four(transaction.getValleyMoney());
+        System.arraycopy(bytesj, 0, msg, index, bytesj.length);
+        index += bytesj.length;
+
+
+        //   22 深谷单价 BIN 4 精确到小数点后五位(深谷电费 + 深谷 服务费)
+        byte[] bytesdg = DataConversion.bin4Tofiv((billingModel.getDeepValleyPrice().add(billingModel.getDeepValleyServiceFee())).setScale(5));
+        System.arraycopy(bytesdg, 0, msg, index, bytesdg.length);
+        index += bytesdg.length;
+
+        //   23 深谷电量 BIN 4 精确到小数点后四位
+        byte[] byteshh = new byte[4];
+        byteshh = DataConversion.bin4Tofour(map.get("elec5").setScale(4));//测试
+        System.arraycopy(byteshh, 0, msg, index, byteshh.length);
+        index += byteshh.length;
+
+        //   24 计损谷电量 BIN 4 精确到小数点后四位
+        byte[] bytedsi = DataConversion.bin4Tofour(zero);
+        // bytesi = Transaction.temp(bytesi);
+        System.arraycopy(bytedsi, 0, msg, index, bytedsi.length);
+        index += bytedsi.length;
+
+        //   25 深谷金额 BIN 4 精确到小数点后四位
+        byte[] bytedsj = new byte[4];
+        bytedsj = DataConversion.bin4Tofour(map.get("money5").setScale(4));
+        //byte[] bytesj = DataConversion.four(transaction.getValleyMoney());
+        System.arraycopy(bytedsj, 0, msg, index, bytedsj.length);
+        index += bytedsj.length;
+
+        //   26 电表总起值 BIN 5 精确到小数点后四位
+        byte[] bytesk = DataConversion.bin5Tofour(new BigDecimal("0.0001").setScale(4)); //测试
+        System.arraycopy(bytesk, 0, msg, index, bytesk.length);
+        index += bytesk.length;
+
+
+        //   27 电表总止值 BIN 5 精确到小数点后四位
+        byte[] bytesl = new byte[5];
+        bytesl = DataConversion.bin5Tofour(new BigDecimal("0.0001").add(map.get("elec")).setScale(4)); //测试
+        System.arraycopy(bytesl, 0, msg, index, bytesl.length);
+        index += bytesl.length;
+
+        //   28 总电量 BIN 4 精确到小数点后四位
+        byte[] bytesm = new byte[4];
+        bytesm = DataConversion.bin4Tofour(map.get("elec").setScale(4));//测试
+        System.arraycopy(bytesm, 0, msg, index, bytesm.length);
+        index += bytesm.length;
+
+
+        //   29 计损总电量 BIN 4 精确到小数点后四位
+        byte[] bytesn = DataConversion.bin4Tofour(zero);
+        //  bytesn = Transaction.temp(bytesn);
+        System.arraycopy(bytesn, 0, msg, index, bytesn.length);
+        index += bytesn.length;
+
+        //   30 消费金额 BIN 4 精确到小数点后四位,包含电费、服务费
+
+        byte[] byteso = DataConversion.bin4Tofour(map.get("money").setScale(4));
+        System.arraycopy(byteso, 0, msg, index, byteso.length);
+        index += byteso.length;
+
+//   31 电动汽车唯一标识 ASCII 17 VIN 码,此处 VIN 码和充电时 VIN 码不同,正序直接上传,无需补 0 和反序
+        byte[] bytesp = new byte[17];
+        bytesp = DataConversion.temp(bytesp);
+        System.arraycopy(bytesp, 0, msg, index, bytesp.length);
+        index += bytesp.length;
+
+        //   32 交易标识 BIN 1 0x01:app 启动 0x02:卡启动 0x04:离线卡启动 0x05:vin 码启动充电
+        byte[] bytesq = new byte[]{TransConstant.APP_START};
+        System.arraycopy(bytesq, 0, msg, index, bytesq.length);
+        index += bytesq.length;
+
+        //   33 交易日期、时间 BIN 7 CP56Time2a 格式
+        byte[] timej = new byte[7];
+//        SimpleDateFormat ses = new SimpleDateFormat("yy-MM-dd-HH-mm-ss-SS");
+//        String format1 = ses.format(new Date(System.currentTimeMillis()));
+//        timej = CP56Time2a.timeCP56Time2a(format1.substring(0, format1.length() - 1));
+        System.arraycopy(time, 0, msg, index, timej.length);
+        index += timej.length;
+
+        //   34 停止原因 BIN 1 见附录 11.1
+        byte[] bytesr = new byte[]{(byte) reason};
+        log.info("订单>>>>停止原因>>>"+reason);
+        System.arraycopy(bytesr, 0, msg, index, bytesr.length);
+        index += bytesr.length;
+
+        //    35 物理卡号 BIN 码 8 不足 8 位补 0
+        byte[] bytess = new byte[8];
+        System.arraycopy(card, 0, bytess, 0, bytess.length);
+        System.arraycopy(bytess, 0, msg, index, bytess.length);
+        index += bytess.length;
+        return msg;
+    }
+
+    public byte[] params16(byte[] transOrder, String pileCode, byte gunPort, long createTime, long endTime, BillingModel billingModel, byte[] card, Map<String, BigDecimal> map,int reason) {
+        //订单创建时间0和预留原因不存库
+        if (createTime > 0||reason!=TransConstant.START_FAIL) {
+            try {
+                //TODO:测试存订单
+                byte[] transOrders = new byte[8];
+                System.arraycopy(transOrder, 8, transOrders, 0, transOrders.length);
+                QueryWrapper<TransOrder> transOrderQueryWrapper = new QueryWrapper<>();
+                transOrderQueryWrapper.eq("trans", DataConversion.bytesToHexString(transOrders)).eq("pile_code", pileCode);
+                TransOrder transOrderServiceOne = transOrderService.getOne(transOrderQueryWrapper);
+                transOrderServiceOne.setStartTime(new Date(createTime));
+                transOrderServiceOne.setEndTime(new Date(endTime));
+                transOrderServiceOne.setSharpElec(map.get("elec1"));
+                transOrderServiceOne.setSharpMoney(map.get("money1"));
+                transOrderServiceOne.setPeakElec(map.get("elec2"));
+                transOrderServiceOne.setPeakMoney(map.get("money2"));
+                transOrderServiceOne.setFlatElec(map.get("elec3"));
+                transOrderServiceOne.setFlatMoney(map.get("money3"));
+                transOrderServiceOne.setValleyElec(map.get("elec4"));
+                transOrderServiceOne.setValleyMoney(map.get("money4"));
+                transOrderServiceOne.setElec(map.get("elec"));
+                transOrderServiceOne.setMoney(map.get("money"));
+                transOrderServiceOne.setReasonStopCharging(reason);
+                transOrderService.updateById(transOrderServiceOne);
+                //TODO:测试存订单
+            }catch(Exception e){
+                e.printStackTrace();
+            }
+            redisCache.deleteObject(RedisConstant.DEVICE_CHARNGING_INFO + pileCode + gunPort);
+        }
+        int index = 0;
+        byte[] msg = new byte[158];
+        //1.交易流水
+        byte[] trans = new byte[16];
+        System.arraycopy(transOrder, 0, trans, 0, transOrder.length);
+        System.arraycopy(trans, 0, msg, index, trans.length);
+        index += trans.length;
+
+        //2. 桩编码 BCD
+        byte[] pile_code = new byte[7];
+        System.arraycopy(DataConversion.bcdToBytes(pileCode, 7), 0, msg, index, pile_code.length);
+        index += pile_code.length;
+//3.枪号
+        byte[] guns = {gunPort};
+        System.arraycopy(guns, 0, msg, index, guns.length);
+        index += guns.length;
+
+        //4.开始时间
+        Date sdate = new Date(createTime);
+        byte[] startTime = new byte[7];
+        SimpleDateFormat se = new SimpleDateFormat("SS-ss-mm-HH-dd-MM-yy");
+        String sformat = se.format(sdate).substring(1);
+        startTime = CP56Time2a.timeCP56Time2a(sformat);
+        System.arraycopy(startTime, 0, msg, index, startTime.length);
+        index += startTime.length;
+
+        //5.结束时间
+        Date date = new Date(endTime);
+        byte[] time = new byte[7];
+        String format = se.format(date).substring(1);
+        time = CP56Time2a.timeCP56Time2a(format);
+        System.arraycopy(time, 0, msg, index, time.length);
+        index += time.length;
+
+
+        //   10 尖单价 BIN 4 精确到小数点后五位(尖电费 + 尖 服务费,见费率帧)
+        byte[] bytes4 = DataConversion.bin4Tofiv((billingModel.getSharpPrice().add(billingModel.getSharpServiceFee())).setScale(5));
+        //bytes4 = Transaction.temp(bytes4);
+        System.arraycopy(bytes4, 0, msg, index, bytes4.length);
+        index += bytes4.length;
+
+        //   11 尖电量 BIN 4 精确到小数点后四位
+        byte[] bytes5 = DataConversion.bin4Tofour(map.get("elec1").setScale(4));
+        //bytes5 = Transaction.temp(bytes5);
+        System.arraycopy(bytes5, 0, msg, index, bytes5.length);
+        index += bytes5.length;
+
+        //   12 计损尖电量 BIN 4 精确到小数点后四位
+        byte[] bytes6 = DataConversion.bin4Tofour(zero);
+        //  bytes6 = Transaction.temp(bytes6);
+        System.arraycopy(bytes6, 0, msg, index, bytes6.length);
+        index += bytes6.length;
+
+        //   13 尖金额 BIN 4 精确到小数点后四位
+        byte[] bytes7 = new byte[4];
+        bytes7 = DataConversion.bin4Tofour(map.get("money1").setScale(4));
+        System.arraycopy(bytes7, 0, msg, index, bytes7.length);
+        index += bytes7.length;
+
+        //   14 峰单价 BIN 4 精确到小数点后五位(峰电费 + 峰 服务费)
+        byte[] bytes8 = DataConversion.bin4Tofiv((billingModel.getPeakPrice().add(billingModel.getPeakServiceFee())).setScale(5));
+        // bytes8 = Transaction.temp(bytes8);
+        System.arraycopy(bytes8, 0, msg, index, bytes8.length);
+        index += bytes8.length;
+
+        //   15 峰电量 BIN 4 精确到小数点后四位
+        byte[] bytes9 = DataConversion.bin4Tofour(map.get("elec2").setScale(4));
+        //bytes9 = Transaction.temp(bytes9);
+        System.arraycopy(bytes9, 0, msg, index, bytes9.length);
+        index += bytes9.length;
+
+        //   16 计损峰电量 BIN 4 精确到小数点后四位
+        byte[] bytesa = DataConversion.bin4Tofour(zero);
+        //bytesa = Transaction.temp(bytesa);
+        System.arraycopy(bytesa, 0, msg, index, bytesa.length);
+        index += bytesa.length;
+
+        //   17 峰金额 BIN 4 精确到小数点后四位
+        byte[] bytesb = DataConversion.bin4Tofour(map.get("money2").setScale(4));
+        // bytesb = Transaction.temp(bytesb);
+        System.arraycopy(bytesb, 0, msg, index, bytesb.length);
+        index += bytesb.length;
+
+        //   18 平单价 BIN 4 精确到小数点后五位(平电费 + 平 服务费)
+
+        byte[] bytesc = DataConversion.bin4Tofiv((billingModel.getFlatPrice().add(billingModel.getFlatServiceFee())).setScale(5));
+        //bytesc = Transaction.temp(bytesc);
+        System.arraycopy(bytesc, 0, msg, index, bytesc.length);
+        index += bytesc.length;
+
+        //   19 平电量 BIN 4 精确到小数点后四位
+        byte[] bytesd = new byte[4];
+
+        bytesd = DataConversion.bin4Tofour(map.get("elec3").setScale(4));
+        // bytesd = Transaction.temp(bytesd);
+        System.arraycopy(bytesd, 0, msg, index, bytesd.length);
+        index += bytesd.length;
+
+        //   20 计损平电量 BIN 4 精确到小数点后四位
+        byte[] bytese = DataConversion.bin4Tofour(zero);
+        //bytese = Transaction.temp(bytese);
+        System.arraycopy(bytese, 0, msg, index, bytese.length);
+        index += bytese.length;
+
+        //   21 平金额 BIN 4 精确到小数点后四位
+        byte[] bytesf = new byte[4];
+
+        bytesf = DataConversion.bin4Tofour(map.get("money3").setScale(4).setScale(4));
+        // bytesf = Transaction.temp(bytesf);
+        System.arraycopy(bytesf, 0, msg, index, bytesf.length);
+        index += bytesf.length;
+
+        //   22 谷单价 BIN 4 精确到小数点后五位(谷电费 + 谷 服务费)
+        byte[] bytesg = DataConversion.bin4Tofiv((billingModel.getValleyPrice().add(billingModel.getValleyServiceFee())).setScale(5));
+        //  bytesg = Transaction.temp(bytesg);
+        System.arraycopy(bytesg, 0, msg, index, bytesg.length);
+        index += bytesg.length;
+
+        //   23 谷电量 BIN 4 精确到小数点后四位
+        byte[] bytesh = new byte[4];
+        bytesh = DataConversion.bin4Tofour(map.get("elec4").setScale(4));//测试
+
+        //byte[] bytesh = DataConversion.four(transaction.getValleyElec());
+        System.arraycopy(bytesh, 0, msg, index, bytesh.length);
+        index += bytesh.length;
+
+        //   24 计损谷电量 BIN 4 精确到小数点后四位
+        byte[] bytesi = DataConversion.bin4Tofour(zero);
+        // bytesi = Transaction.temp(bytesi);
+        System.arraycopy(bytesi, 0, msg, index, bytesi.length);
+        index += bytesi.length;
+
+        //   25 谷金额 BIN 4 精确到小数点后四位
+        byte[] bytesj = new byte[4];
+        bytesj = DataConversion.bin4Tofour(map.get("money4").setScale(4));
+        //byte[] bytesj = DataConversion.four(transaction.getValleyMoney());
+        System.arraycopy(bytesj, 0, msg, index, bytesj.length);
+        index += bytesj.length;
+
+
+
+        //   26 电表总起值 BIN 5 精确到小数点后四位
+        byte[] bytesk = DataConversion.bin5Tofour(new BigDecimal("0.0001").setScale(4)); //测试
+        System.arraycopy(bytesk, 0, msg, index, bytesk.length);
+        index += bytesk.length;
+
+
+        //   27 电表总止值 BIN 5 精确到小数点后四位
+        byte[] bytesl = new byte[5];
+        bytesl = DataConversion.bin5Tofour(new BigDecimal("0.0001").add(map.get("elec")).setScale(4)); //测试
+        System.arraycopy(bytesl, 0, msg, index, bytesl.length);
+        index += bytesl.length;
+
+        //   28 总电量 BIN 4 精确到小数点后四位
+        byte[] bytesm = new byte[4];
+        bytesm = DataConversion.bin4Tofour(map.get("elec").setScale(4));//测试
+        System.arraycopy(bytesm, 0, msg, index, bytesm.length);
+        index += bytesm.length;
+
+
+        //   29 计损总电量 BIN 4 精确到小数点后四位
+        byte[] bytesn = DataConversion.bin4Tofour(zero);
+        //  bytesn = Transaction.temp(bytesn);
+        System.arraycopy(bytesn, 0, msg, index, bytesn.length);
+        index += bytesn.length;
+
+        //   30 消费金额 BIN 4 精确到小数点后四位,包含电费、服务费
+
+        byte[] byteso = DataConversion.bin4Tofour(map.get("money").setScale(4));
+        System.arraycopy(byteso, 0, msg, index, byteso.length);
+        index += byteso.length;
+
+//   31 电动汽车唯一标识 ASCII 17 VIN 码,此处 VIN 码和充电时 VIN 码不同,正序直接上传,无需补 0 和反序
+        byte[] bytesp = new byte[17];
+        bytesp = DataConversion.temp(bytesp);
+        System.arraycopy(bytesp, 0, msg, index, bytesp.length);
+        index += bytesp.length;
+
+        //   32 交易标识 BIN 1 0x01:app 启动 0x02:卡启动 0x04:离线卡启动 0x05:vin 码启动充电
+        byte[] bytesq = new byte[]{TransConstant.APP_START};
+        System.arraycopy(bytesq, 0, msg, index, bytesq.length);
+        index += bytesq.length;
+
+        //   33 交易日期、时间 BIN 7 CP56Time2a 格式
+        byte[] timej = new byte[7];
+//        SimpleDateFormat ses = new SimpleDateFormat("yy-MM-dd-HH-mm-ss-SS");
+//        String format1 = ses.format(new Date(System.currentTimeMillis()));
+//        timej = CP56Time2a.timeCP56Time2a(format1.substring(0, format1.length() - 1));
+        System.arraycopy(time, 0, msg, index, timej.length);
+        index += timej.length;
+
+        //   34 停止原因 BIN 1 见附录 11.1
+        byte[] bytesr = new byte[]{(byte) reason};
+        log.info("订单>>>>停止原因>>>"+reason);
+        System.arraycopy(bytesr, 0, msg, index, bytesr.length);
+        index += bytesr.length;
+
+        //    35 物理卡号 BIN 码 8 不足 8 位补 0
+        byte[] bytess = new byte[8];
+        System.arraycopy(card, 0, bytess, 0, bytess.length);
+        System.arraycopy(bytess, 0, msg, index, bytess.length);
+        index += bytess.length;
+        return msg;
+    }
+
     public byte[] params(byte[] transOrder, String pileCode, byte gunPort, long createTime, long endTime, BillingModel billingModel, byte[] card, Map<String, BigDecimal> map,int reason) {
         //订单创建时间0和预留原因不存库
         if (createTime > 0||reason!=TransConstant.START_FAIL) {

+ 25 - 23
src/main/java/com/tmzn/devicelinkykc/message/DeviceMsgHandle.java

@@ -417,7 +417,7 @@ public class DeviceMsgHandle {
             try {
 
                 JSONObject data = jsonObject.getJSONObject("real_data");
-                logger.info("接收到设备上送113停止充电msg>>" + jsonObject.toString());
+                logger.info("{}接收到设备上送113停止充电msg>>" + jsonObject.toString(),imei);
                 int port = data.getIntValue("port");
                 byte reson = data.getByte("reason");
                 QueryWrapper<OrderStatus> orderStatusQueryWrapper = new QueryWrapper<>();
@@ -540,17 +540,16 @@ public class DeviceMsgHandle {
             statusServiceOne.setEndTime(System.currentTimeMillis());
             DeviceConnectionMsg deviceConnection = socketHandle.getDeviceConnection(statusServiceOne.getPileCode());
             if (status == 1) {
+                logger.info(statusServiceOne.getPileCode() + ":急停停充>>>上报交易记录>>>");
                 byte[] encrypt = new byte[0];
                 if (port == 1) {
                     //急停停充:急停状态下:1.向设备发起结束充电,结算交易订单(交给结束充电处理;但是要考虑是急停的原因),2.上报的充电结束的订单式
 
                     Map<String, BigDecimal> map = transMoney.compute(1, model, statusServiceOne.getCreateTime(), statusServiceOne.getEndTime(), true);
 
-                    logger.info(statusServiceOne.getPileCode() + ":急停停充>>>上报交易记录>>>");
                     encrypt = transactionFlowPushFrame.sendTrans(deviceConnection, statusServiceOne.getTransOrder(), statusServiceOne.getPileCode(), (byte) 1, statusServiceOne.getCreateTime(), statusServiceOne.getEndTime(), model, statusServiceOne.getCard(), map, TransConstant.EMERGENCY_STOP_EXCEPTION_STOP);
                 } else if (port == 2) {
                     //TODO:这里还是模拟数据上报
-                    DeviceStatus deviceStatus = redisCache.getCacheMapValue(RedisConstant.ONLINE_DEVICE_TWO, statusServiceOne.getPileCode());
 
                     Map<String, BigDecimal> map = transMoney.compute(2, model, statusServiceOne.getCreateTime(), statusServiceOne.getEndTime(), true);
                     //模拟3.5千瓦
@@ -808,6 +807,9 @@ public class DeviceMsgHandle {
                 logger.info("{}设备上线>>>>>>",device.getPileCode());
                 socketHandle.addDeviceConnection(device.getIp(),device.getPort(),statusServiceOne.getPileCode(), statusServiceOne.getDeviceImei(), statusServiceOne.getDeviceSn(),device.getCommProtocolVer());
                 loginFrame.loginMsgSend(socketHandle.getDeviceConnection(statusServiceOne.getPileCode()), device);
+
+
+
                 //从新登录可能造成通讯上的问题,这里不在往下进行状态操作
                // return;
             } catch (IOException e) {
@@ -827,31 +829,31 @@ public class DeviceMsgHandle {
                 }
             }
         }
-        logger.info("设备原状态>>>" + statusServiceOneTemp.toString());
+        logger.info("{}设备原状态>>>" + statusServiceOneTemp.toString(),imei);
         statusServiceOne.setGunStatus(gunsStatus);
         statusServiceOne.setInsertGunStatus(insertGunStatus);
         statusServiceOne.setOnlineStatus(DeviceOnlineStatus.ONLINE);
         statusServiceOne.setUpdateTime(System.currentTimeMillis());
         deviceStatusService.updateById(statusServiceOne);
-        logger.info("设备状态持久化>>>" + statusServiceOne.toString());
+        logger.info("{}设备状态持久化>>>" + statusServiceOne.toString(),imei);
 
         //1.redis也更新掉
+//        if (port == 1) {
+//            if (redisCache.hasKey(RedisConstant.ONLINE_DEVICE_ONE)) {
+//                DeviceStatus ds = redisCache.getCacheMapValue(RedisConstant.ONLINE_DEVICE_ONE, statusServiceOne.getPileCode());
+//                if (ds != null) {
+//                    redisCache.deleteCacheMapValue(RedisConstant.ONLINE_DEVICE_ONE, statusServiceOne.getPileCode());
+//                }
+//            }
+//        } else if (port == 2) {
+//            if (redisCache.hasKey(RedisConstant.ONLINE_DEVICE_TWO)) {
+//                DeviceStatus ds = redisCache.getCacheMapValue(RedisConstant.ONLINE_DEVICE_TWO, statusServiceOne.getPileCode());
+//                if (ds != null) {
+//                    redisCache.deleteCacheMapValue(RedisConstant.ONLINE_DEVICE_TWO, statusServiceOne.getPileCode());
+//                }
+//            }
+//        }
 
-        if (port == 1) {
-            if (redisCache.hasKey(RedisConstant.ONLINE_DEVICE_ONE)) {
-                DeviceStatus ds = redisCache.getCacheMapValue(RedisConstant.ONLINE_DEVICE_ONE, statusServiceOne.getPileCode());
-                if (ds != null) {
-                    redisCache.deleteCacheMapValue(RedisConstant.ONLINE_DEVICE_ONE, statusServiceOne.getPileCode());
-                }
-            }
-        } else if (port == 2) {
-            if (redisCache.hasKey(RedisConstant.ONLINE_DEVICE_TWO)) {
-                DeviceStatus ds = redisCache.getCacheMapValue(RedisConstant.ONLINE_DEVICE_TWO, statusServiceOne.getPileCode());
-                if (ds != null) {
-                    redisCache.deleteCacheMapValue(RedisConstant.ONLINE_DEVICE_TWO, statusServiceOne.getPileCode());
-                }
-            }
-        }
         redisCache.setCacheMapValue(port == 1 ? RedisConstant.ONLINE_DEVICE_ONE : RedisConstant.ONLINE_DEVICE_TWO, statusServiceOne.getPileCode(), statusServiceOne);
         redisCache.expire(port == 1 ? RedisConstant.ONLINE_DEVICE_ONE : RedisConstant.ONLINE_DEVICE_TWO, 60 * 1001 * 20, TimeUnit.MILLISECONDS);
 
@@ -881,7 +883,7 @@ public class DeviceMsgHandle {
                     byte[] transactionNum = one.getTransOrder();
 
                     if (one.getChargingInitStatus() == StatusConstant.CHARGING_INIT_STATUS_NO) {
-                        logger.info("变位为充电中且当前订单还没首次上报过初始状态:" + DataConversion.bytesToHexString(transactionNum));
+                        logger.info("{}变位为充电中且当前订单还没首次上报过初始状态:" + DataConversion.bytesToHexString(transactionNum),imei);
                         realTimeStatusPushFrame.deviceStatusPush(deviceConnectionMsg, transactionNum, statusServiceOneTemp.getPileCode(), (byte) port, gunsStatus, insertGunStatus, 0, 0, zero, zero, 0);
                     }
                     //这里上报开始充电初始化状态并记录已经上报首次状态
@@ -915,8 +917,8 @@ public class DeviceMsgHandle {
                     //急停状态下不管是断网时急停还是直接按的急停都按急停处理,不按手动处理;
                     //TODO:急停情况已经上报交易,其他从充电变成非已充电全部上报交易记录
                     //原枪状态是充电中,现在不是根据状态上报
-                    logger.info("原本状态>>>>>>>>>>>>>>>>>"+statusServiceOneTemp.toString());
-                    logger.info("当前状态状态>>>>>>>>>>>>>>>>>"+statusServiceOne.toString());
+                    logger.info("{}原本状态>>>>>>>>>>>>>>>>>"+statusServiceOneTemp.toString(),imei);
+                    logger.info("{}当前状态状态>>>>>>>>>>>>>>>>>"+statusServiceOne.toString(),imei);
                     if (statusServiceOneTemp.getGunStatus()==StatusConstant.CHARGING&&statusServiceOne.getGunStatus()!=StatusConstant.CHARGING){
                         QueryWrapper<BillingModel> billingModelQueryWrapper = new QueryWrapper<>();
                         billingModelQueryWrapper.eq("device_imei", imei);

+ 150 - 193
src/main/java/com/tmzn/devicelinkykc/message/YkcMsgHandle.java

@@ -52,7 +52,7 @@ import java.util.stream.Collectors;
 public class YkcMsgHandle {
 
     private static final Logger logger = LoggerFactory.getLogger(YkcMsgHandle.class);
-    private static final BigDecimal zero=new BigDecimal("0");
+    private static final BigDecimal zero = new BigDecimal("0");
 
     @Autowired
     private RedisCache redisCache;
@@ -89,7 +89,7 @@ public class YkcMsgHandle {
     public void startListening(DeviceConnectionMsg deviceConnectionMsg) {
 
         Runnable listener = () -> {
-            boolean temp=true;
+            boolean temp = true;
             while (temp) {
                 // 接收数据帧
                 byte[] receiveData = new byte[1024];
@@ -106,7 +106,7 @@ public class YkcMsgHandle {
                 } catch (IOException e) {
                     //e.printStackTrace();
                     String message = e.getMessage();
-                    logger.info(deviceConnectionMsg.getDeviceId()+":Receive YKC dataMsg IOException !!!!!!!:" + message+"!!!!!!!!"+ message+"!!!!!!!!"+ message+"!!!!!!!!"+ message+"!!!!!!!!");
+                    logger.info(deviceConnectionMsg.getDeviceId() + ":Receive YKC dataMsg IOException !!!!!!!:" + message + "!!!!!!!!" + message + "!!!!!!!!" + message + "!!!!!!!!" + message + "!!!!!!!!");
                     //异常后操作删除所有的缓存,重新获取
                     DataParam dataParam = new DataParam();
                     dataParam.setDeviceId(deviceConnectionMsg.getImei());
@@ -115,7 +115,7 @@ public class YkcMsgHandle {
                     dataParam.setData(object1);
                     dataParam.setType(OperEnum.PortDetail.getType());
                     msgService.sendMsg(dataParam);
-                    temp=false;
+                    temp = false;
                     continue;
                 }
                 byte[] response = new byte[length];
@@ -127,108 +127,127 @@ public class YkcMsgHandle {
 
                 //消息体
                 byte[] respone_msg = Arrays.copyOfRange(response, 6, response.length - 2);
-                logger.info("framType:" + framType + "||" + response[5] + "应答消息类型>>>" + s);
                 if (encry == 0) {
-                    logger.info("respone_msg>" + DataConversion.bytesToHexString(respone_msg));
+                    logger.info("{},未加密消息,frame:{},data:{}",deviceConnectionMsg.getDeviceId(),framType, DataConversion.bytesToHexString(respone_msg));
                 } else {
                     try {
-                        String key = redisCache.getCacheObject(RedisConstant.KEYS+deviceConnectionMsg.getDeviceId());
-                        respone_msg = Encrytion.decrypt(respone_msg,key.getBytes());
-                        logger.info("respone_msg_enc>" + DataConversion.bytesToHexString(respone_msg));
+                        String key = redisCache.getCacheObject(RedisConstant.KEYS + deviceConnectionMsg.getDeviceId());
+                        respone_msg = Encrytion.decrypt(respone_msg, key.getBytes());
+
+                        logger.info("{},加密消息,frame:{},data:{}",deviceConnectionMsg.getDeviceId(),framType, DataConversion.bytesToHexString(respone_msg));
                     } catch (Exception e) {
-                        logger.info("ykc->msg decrypt Exception");
+                        logger.info("{},ykc->msg decrypt Exception",deviceConnectionMsg.getDeviceId());
                         e.printStackTrace();
                     }
                 }
                 if (framType == YkcSendDevice.LOGIN_RESPONSE.getFrameType()) {
-                    logger.info("ykc->dev:"+deviceConnectionMsg.getDeviceId()+"↓↓↓↓↓↓↓↓↓↓↓↓↓登录认证应答消息↓↓↓↓↓↓↓↓↓↓↓↓↓"+framType);
+                    logger.info("↓↓↓↓↓"+deviceConnectionMsg.getDeviceId()+"登录认证应答"+framType);
                     //处理登录成功与否
-                    loginResponse(deviceConnectionMsg, respone_msg);
+                    boolean res = loginResponse(deviceConnectionMsg, respone_msg);
                     //计费模型请求
-                    billingModelFrame.checkBillingModel(deviceConnectionMsg);
-                    logger.info("===========登录认证应答============over");
+                    if(res){
+                        logger.info("↓↓↓↓↓"+deviceConnectionMsg.getDeviceId()+"请求计费模型");
+                        billingModelFrame.checkBillingModel(deviceConnectionMsg);
+                    }
 
                 } else if (framType == YkcSendDevice.HEART_RESPONSE.getFrameType()) {
                     //TODO:个人理解,枪不管故障还是正常都会有心跳,心跳应答正常说明设备是正常的状态,所以这里不管是同一设备的几号枪心跳都缓存下来心跳应答时间
-                  //  logger.info("ykc->dev"+deviceConnectionMsg.getDeviceId()+"↓↓↓↓↓↓↓↓↓↓↓↓↓心跳包应答消息↓↓↓↓↓↓↓↓↓↓↓↓↓"+framType);
+                    //  logger.info("ykc->dev"+deviceConnectionMsg.getDeviceId()+"↓↓↓↓↓↓↓↓↓↓↓↓↓心跳包应答消息↓↓↓↓↓↓↓↓↓↓↓↓↓"+framType);
                     deviceConnectionMsg.setHeartTime(System.currentTimeMillis());
-                    logger.info("===========心跳包应答============over");
+//                    logger.info("===========心跳包应答============over");
 
                 } else if (framType == YkcSendDevice.BILLING_MODEL_VALIDATE_RESPONSE.getFrameType()) {
-                    logger.info("ykc->dev↓↓↓↓↓↓↓↓↓↓↓↓↓计费模型验证请求应答↓↓↓↓↓↓↓↓↓↓↓↓↓"+framType);
-                    billingModelHandle(deviceConnectionMsg,respone_msg);
+                    billingModelHandle(deviceConnectionMsg, respone_msg);
 
                 } else if (framType == YkcSendDevice.BILLING_MODEL_RESPONSE.getFrameType()) {
-                    logger.info("ykc->dev"+deviceConnectionMsg.getDeviceId()+"↓↓↓↓↓↓↓↓↓↓↓↓↓计费模型请求应答↓↓↓↓↓↓↓↓↓↓↓↓↓"+framType);
+                    logger.info("↓↓↓↓↓" + deviceConnectionMsg.getDeviceId() + "计费模型请求应答" + framType);
                     try {
-                        getBillingModelHandle(deviceConnectionMsg,respone_msg);
+                        billingModelFrame.setBillingModel(deviceConnectionMsg, respone_msg);
                     } catch (Exception e) {
                         e.printStackTrace();
                     }
 
+                } else if (framType == YkcSendDevice.BILLING_MODEL_VALIDATE_RESPONSE_SG.getFrameType()) {
+                    logger.info("↓↓↓↓↓" + deviceConnectionMsg.getDeviceId() + "深谷计费模型请求应答" + framType);
+                    try {
+                        billingModelFrame.setSgBillingModel(deviceConnectionMsg, respone_msg);
+                    } catch (Exception e) {
+                        e.printStackTrace();
+                    }
                 } else if (framType == YkcSendDevice.TRANSACTION_RECORDS_RESPONSE.getFrameType()) {
-                    logger.info("ykc->dev"+deviceConnectionMsg.getDeviceId()+"↓↓↓↓↓↓↓↓↓↓↓↓↓交易记录确认↓↓↓↓↓↓↓↓↓↓↓↓↓");
+                    logger.info("↓↓↓↓↓" + deviceConnectionMsg.getDeviceId() + "交易记录确认");
                     byte[] trans = Arrays.copyOfRange(respone_msg, 0, 16);
                     byte[] reason = Arrays.copyOfRange(respone_msg, 16, 17);
                     QueryWrapper<OrderStatus> orderStatusQueryWrapper = new QueryWrapper<>();
-                    orderStatusQueryWrapper.eq("trans_order",trans);
+                    orderStatusQueryWrapper.eq("trans_order", trans);
                     OrderStatus one = orderStatusService.getOne(orderStatusQueryWrapper);
 
                     QueryWrapper<TransOrder> transOrderQueryWrapper = new QueryWrapper<>();
-                    transOrderQueryWrapper.eq("trans_order",trans);
+                    transOrderQueryWrapper.eq("trans_order", trans);
                     TransOrder transOrderServiceOne = transOrderService.getOne(transOrderQueryWrapper);
 
-                    if (reason[0]==0x00){
+                    if (reason[0] == 0x00) {
                         one.setTransactionOrderReplyStatus(StatusConstant.TRANSACTION_ORDER_REPLY_STATUS_SUCC);
                         transOrderServiceOne.setFlage(StatusConstant.TRANSACTION_ORDER_REPLY_STATUS_SUCC);
-                    }else if (reason[0]==0x01){
+                    } else if (reason[0] == 0x01) {
                         one.setTransactionOrderReplyStatus(StatusConstant.TRANSACTION_ORDER_REPLY_STATUS_FAIL);
-                    }else if (reason[0]==0x02){
+                    } else if (reason[0] == 0x02) {
                         one.setTransactionOrderReplyStatus(StatusConstant.TRANSACTION_ORDER_REPLY_STATUS_ILLEGAL);
                     }
                     //接收到后将订单校验从redis剔除
-                    redisCache.deleteObject(RedisConstant.NO_RESPONSE_WAS_RECEIVED+one.getPileCode());
+                    redisCache.deleteObject(RedisConstant.NO_RESPONSE_WAS_RECEIVED + one.getPileCode());
                     orderStatusService.updateById(one);
                     transOrderService.updateById(transOrderServiceOne);
                 } else if (framType == YkcSendDevice.DEVICE_STATUS_REQUEST.getFrameType()) {
-                    logger.info("ykc->dev↓↓↓↓↓↓↓↓↓↓↓↓↓读取实时监测数据↓↓↓↓↓↓↓↓↓↓↓↓↓");
+                    logger.info("↓↓↓↓↓{}读取实时监测数据",deviceConnectionMsg.getDeviceId());
 
-                } else if (framType == YkcSendDevice.START_CHARNGING_REQUEST.getFrameType() || framType==YkcSendDevice.START_CHARNGING_REQUEST_16.getFrameType()) {
-                    logger.info("ykc->dev↓↓↓↓↓↓↓↓↓↓↓↓↓运营平台远程控制启机↓↓↓↓↓↓↓↓↓↓↓↓↓"+framType);
+                } else if (framType == YkcSendDevice.START_CHARNGING_REQUEST.getFrameType() || framType == YkcSendDevice.START_CHARNGING_REQUEST_16.getFrameType()) {
+                    logger.info("↓↓↓↓↓{}运营平台远程控制启机" + framType,deviceConnectionMsg.getDeviceId());
                     startChargingRequest(deviceConnectionMsg, respone_msg);
 
                 } else if (framType == YkcSendDevice.STOP_CHARNGING_REQUEST.getFrameType()) {
-                    logger.info("ykc->dev↓↓↓↓↓↓↓↓↓↓↓↓↓运营平台远程停机↓↓↓↓↓↓↓↓↓↓↓↓↓");
-                    stopChargingRequest(deviceConnectionMsg,respone_msg);
+                    logger.info("↓↓↓↓↓{}运营平台远程停机",deviceConnectionMsg.getDeviceId());
+                    stopChargingRequest(deviceConnectionMsg, respone_msg);
 
                 } else if (framType == YkcSendDevice.UPDATE_BALANCE.getFrameType()) {
-                    logger.info("ykc->dev↓↓↓↓↓↓↓↓↓↓↓↓↓远程更新余额↓↓↓↓↓↓↓↓↓↓↓↓↓");
+                    logger.info("↓↓↓↓↓{}远程更新余额",deviceConnectionMsg.getDeviceId());
                     try {
-                        remoteBalanceUpdate(deviceConnectionMsg,respone_msg);
+                        remoteBalanceUpdate(deviceConnectionMsg, respone_msg);
                     } catch (Exception e) {
                         e.printStackTrace();
                     }
 
                 } else if (framType == YkcSendDevice.CHECKTIME.getFrameType()) {
-                    logger.info("ykc->dev↓↓↓↓↓↓↓↓↓↓↓↓↓对时设置↓↓↓↓↓↓↓↓↓↓↓↓↓"+framType);
+                    logger.info("↓↓↓↓↓{}对时设置" + framType,deviceConnectionMsg.getDeviceId());
                     checkTime.checkTimeSend(deviceConnectionMsg);
 
+                } else if (framType == YkcSendDevice.BILLING_MODEL_SETTING_SG.getFrameType()) {
+                    logger.info("↓↓↓↓↓{}深谷计费模型设置",deviceConnectionMsg.getDeviceId());
+                    try {
+                        //有异常就是失败
+                        billingModelFrame.setSgBillingModel(deviceConnectionMsg, respone_msg);
+                        billingModelFrame.resp(deviceConnectionMsg, (byte) 1);
+                    } catch (Exception e) {
+                        billingModelFrame.resp(deviceConnectionMsg, (byte) 0);
+                        e.printStackTrace();
+                    }
+
                 } else if (framType == YkcSendDevice.BILLING_MODEL_SETTING.getFrameType()) {
-                    logger.info("ykc->dev↓↓↓↓↓↓↓↓↓↓↓↓↓计费模型设置↓↓↓↓↓↓↓↓↓↓↓↓↓");
+                    logger.info("↓↓↓↓↓{}计费模型设置",deviceConnectionMsg.getDeviceId());
                     try {
                         //有异常就是失败
-                        getBillingModelHandle(deviceConnectionMsg,respone_msg);
-                        billingModelFrame.resp(deviceConnectionMsg,(byte) 1);
+                        billingModelFrame.setBillingModel(deviceConnectionMsg, respone_msg);
+                        billingModelFrame.resp(deviceConnectionMsg, (byte) 1);
                     } catch (Exception e) {
-                        billingModelFrame.resp(deviceConnectionMsg,(byte) 0);
+                        billingModelFrame.resp(deviceConnectionMsg, (byte) 0);
                         e.printStackTrace();
                     }
 
                 } else if (framType == YkcSendDevice.REMOTE_REBOOT.getFrameType()) {
-                    logger.info("ykc->dev↓↓↓↓↓↓↓↓↓↓↓↓↓远程重启↓↓↓↓↓↓↓↓↓↓↓↓↓");
+                    logger.info("↓↓↓↓↓{}远程重启",deviceConnectionMsg.getDeviceId());
 
                 } else if (framType == YkcSendDevice.UPLOAD_FILE_UPDATE.getFrameType()) {
-                    logger.info("ykc->dev↓↓↓↓↓↓↓↓↓↓↓↓↓远程更新↓↓↓↓↓↓↓↓↓↓↓↓↓");
+                    logger.info("↓↓↓↓↓{}远程更新",deviceConnectionMsg.getDeviceId());
 
                 }
             }
@@ -243,16 +262,18 @@ public class YkcMsgHandle {
      * @param deviceConnectionMsg
      * @param respone_msg
      */
-    private void loginResponse(DeviceConnectionMsg deviceConnectionMsg, byte[] respone_msg) {
+    private boolean loginResponse(DeviceConnectionMsg deviceConnectionMsg, byte[] respone_msg) {
         int login_result = respone_msg[7] & 0xFF;
         if (ResultUtil.isSuccess(login_result)) {
             //登录成功,相当于初始化心跳包接收时间更新,初始化心跳包时间相当于登录成功,心跳包能正常上传
-            logger.info("{}login successfully",deviceConnectionMsg.getImei());
+            logger.info("{}login successfully", deviceConnectionMsg.getDeviceId());
             deviceConnectionMsg.setHeartTime(System.currentTimeMillis());
             deviceConnectionMsg.setLoginStatus(Constant.DEVICE_LOGIN_STATUS);
+            return true;
         } else {
-            logger.info("{}login failed ,waitting for retry",deviceConnectionMsg.getImei());
+            logger.info("{}login failed ,waitting for retry", deviceConnectionMsg.getDeviceId());
             //登录失败等心跳包10秒后进行重试
+            return false;
         }
     }
 
@@ -262,7 +283,7 @@ public class YkcMsgHandle {
      * @param deviceConnectionMsg
      * @param respone_msg
      */
-    private void startChargingRequest(DeviceConnectionMsg deviceConnectionMsg, byte[] respone_msg){
+    private void startChargingRequest(DeviceConnectionMsg deviceConnectionMsg, byte[] respone_msg) {
 
         try {
             //1.解析出启动充电流水号
@@ -276,77 +297,69 @@ public class YkcMsgHandle {
             //切出订单号,保存在连接的该设备中
             byte[] transOrder = Arrays.copyOfRange(respone_msg, 0, 16);
             //测试
-            t=transOrder;
+            t = transOrder;
             byte[] guns = Arrays.copyOfRange(respone_msg, 23, 24);
             byte[] card = Arrays.copyOfRange(respone_msg, 32, 40);
             byte[] logCard = Arrays.copyOfRange(respone_msg, 24, 32);
-            byte[] startMoney = Arrays.copyOfRange(respone_msg, respone_msg.length-6, respone_msg.length-2);
-            boolean temp=false;
-            int result=0x00;    //失败
-            int reason=0x00;   //无
-            if (guns[0]==1){
+            byte[] startMoney = Arrays.copyOfRange(respone_msg, respone_msg.length - 6, respone_msg.length - 2);
+            boolean temp = false;
+            int result = 0x00;    //失败
+            int reason = 0x00;   //无
+            if (guns[0] == 1) {
                 DeviceStatus oneDeviceStatus = redisCache.getCacheMapValue(RedisConstant.ONLINE_DEVICE_ONE, deviceConnectionMsg.getDeviceId());
                 logger.info(oneDeviceStatus.toString());
-                if (oneDeviceStatus.getOnlineStatus()==StatusConstant.OFFLINE||StatusConstant.OFFLINE==oneDeviceStatus.getGunStatus()){
+                if (oneDeviceStatus.getOnlineStatus() == StatusConstant.OFFLINE || StatusConstant.OFFLINE == oneDeviceStatus.getGunStatus()) {
                     //离线上报
-                    reason=0x04;
-                    temp=true;
-                    logger.info("reson>"+reason);
-                }else if (StatusConstant.CHARGING==oneDeviceStatus.getGunStatus()){
+                    reason = 0x04;
+                    temp = true;
+                } else if (StatusConstant.CHARGING == oneDeviceStatus.getGunStatus()) {
                     //枪已在充电中
-                    reason=0x02;
-                    temp=true;
-                    logger.info("reson>"+reason);
-                }else if (StatusConstant.FAULT==oneDeviceStatus.getGunStatus()){
+                    reason = 0x02;
+                    temp = true;
+                } else if (StatusConstant.FAULT == oneDeviceStatus.getGunStatus()) {
                     //枪故障
-                    reason=0x03;
-                    temp=true;
-                    logger.info("reson>"+reason);
-                }else if (StatusConstant.INSERT_GUNS_NO==oneDeviceStatus.getInsertGunStatus()){
+                    reason = 0x03;
+                    temp = true;
+                } else if (StatusConstant.INSERT_GUNS_NO == oneDeviceStatus.getInsertGunStatus()) {
                     //未插枪
-                    reason=0x05;
-                    temp=false;
-                    logger.info("reson>"+reason);
-                }else if (PortStatusConstant.EMERGENCY_STOP==oneDeviceStatus.getGunStatus()){
+                    reason = 0x05;
+                    temp = false;
+                } else if (PortStatusConstant.EMERGENCY_STOP == oneDeviceStatus.getGunStatus()) {
                     //急停没复位,也是启充失败
-                    temp=true;
+                    temp = true;
                 }
-            }else if(guns[0]==2){
+            } else if (guns[0] == 2) {
                 DeviceStatus twoDeviceStatus = redisCache.getCacheMapValue(RedisConstant.ONLINE_DEVICE_TWO, deviceConnectionMsg.getDeviceId());
-                if (twoDeviceStatus.getOnlineStatus()==StatusConstant.OFFLINE||StatusConstant.OFFLINE==twoDeviceStatus.getGunStatus()){
+                if (twoDeviceStatus.getOnlineStatus() == StatusConstant.OFFLINE || StatusConstant.OFFLINE == twoDeviceStatus.getGunStatus()) {
                     //离线上报
-                    reason=0x04;
-                    temp=true;
-                    logger.info("reson>"+reason);
-                }else if (StatusConstant.CHARGING==twoDeviceStatus.getGunStatus()){
+                    reason = 0x04;
+                    temp = true;
+                } else if (StatusConstant.CHARGING == twoDeviceStatus.getGunStatus()) {
                     //枪已在充电中
-                    reason=0x02;
-                    temp=true;
-                    logger.info("reson>"+reason);
-                }else if (StatusConstant.FAULT==twoDeviceStatus.getGunStatus()){
+                    reason = 0x02;
+                    temp = true;
+                } else if (StatusConstant.FAULT == twoDeviceStatus.getGunStatus()) {
                     //枪故障
-                    reason=0x03;
-                    temp=true;
-                    logger.info("reson>"+reason);
-                }else if (StatusConstant.INSERT_GUNS_NO==twoDeviceStatus.getInsertGunStatus()){
+                    reason = 0x03;
+                    temp = true;
+                } else if (StatusConstant.INSERT_GUNS_NO == twoDeviceStatus.getInsertGunStatus()) {
                     //未插枪
-                    reason=0x05;
-                    temp=false;
-                    logger.info("reson>"+reason);
-                }else if (PortStatusConstant.EMERGENCY_STOP==twoDeviceStatus.getGunStatus()){
+                    reason = 0x05;
+                    temp = false;
+                } else if (PortStatusConstant.EMERGENCY_STOP == twoDeviceStatus.getGunStatus()) {
                     //急停没复位,也是启充失败
-                    temp=true;
+                    temp = true;
                 }
             }
-            logger.info("reson>"+reason);
-        if (temp){
-            charngingPushFrame.startStatus(deviceConnectionMsg,transOrder,guns[0],result,reason );
-            Map<String, BigDecimal> compute = transMoney.compute(guns[0], new BillingModel(), 0L, 0L, false);
-            transactionFlowPushFrame.sendTrans(deviceConnectionMsg,transOrder, deviceStatus.getPileCode(),guns[0],System.currentTimeMillis(),System.currentTimeMillis(),new BillingModel(),card,compute,TransConstant.START_FAIL);
-            return;
-        }
-            BigDecimal bigDecimalmoney = DataConversion.arrToBigDec(startMoney, 2,2).setScale(2,BigDecimal.ROUND_UP);
-            logger.info("startMoney"+bigDecimalmoney+"sbyt+"+DataConversion.bytesToHexString(startMoney));
+            if (temp) {
+                logger.info("启动失败{}:reason:{}" ,deviceConnectionMsg.getDeviceId(), reason);
+                charngingPushFrame.startStatus(deviceConnectionMsg, transOrder, guns[0], result, reason);
+                Map<String, BigDecimal> compute = transMoney.compute(guns[0], new BillingModel(), 0L, 0L, false);
+                transactionFlowPushFrame.sendTrans(deviceConnectionMsg, transOrder, deviceStatus.getPileCode(), guns[0], System.currentTimeMillis(), System.currentTimeMillis(), new BillingModel(), card, compute, TransConstant.START_FAIL);
+                return;
+            }
+            BigDecimal bigDecimalmoney = DataConversion.arrToBigDec(startMoney, 2, 2).setScale(2, BigDecimal.ROUND_UP);
+            logger.info("{}开始充电,startMoney" + bigDecimalmoney + "sbyt+" + DataConversion.bytesToHexString(startMoney),deviceConnectionMsg.getDeviceId());
             OrderStatus orderStatus = new OrderStatus();
             orderStatus.setDeviceSn(deviceStatus.getDeviceSn());
             orderStatus.setDeviceImei(deviceConnectionMsg.getImei());
@@ -361,30 +374,32 @@ public class YkcMsgHandle {
             this.saveOrder(orderStatus);
             //setMoney(orderStatus);//让设备记余额不足情况,启充时要传启充金额money,传0就是启充默认值
             //3.向设备发送启机指令
-            if (reason==0x05){
+            if (reason == 0x05) {
                 //未插枪不启充设备,但是返回未插枪
-                logger.info("未插枪等待充电订单:"+DataConversion.bytesToHexString(transOrder));
-                charngingPushFrame.startStatus(deviceConnectionMsg,transOrder,guns[0],result,reason );
-                redisCache.setCacheObject(RedisConstant.NO_INSERT_GUN_YKC+deviceStatus.getPileCode(),DataConversion.bytesToHexString(transOrder),60*1000, TimeUnit.MILLISECONDS);
-            }else {
-                deviceControlerService.startCharge(deviceStatus.getDeviceImei(), deviceStatus.getDeviceImei(), (int) guns[0],0);
+                logger.info("{}未插枪等待充电订单:" + DataConversion.bytesToHexString(transOrder),deviceConnectionMsg.getDeviceId());
+                charngingPushFrame.startStatus(deviceConnectionMsg, transOrder, guns[0], result, reason);
+                redisCache.setCacheObject(RedisConstant.NO_INSERT_GUN_YKC + deviceStatus.getPileCode(), DataConversion.bytesToHexString(transOrder), 60 * 1000, TimeUnit.MILLISECONDS);
+            } else {
+                deviceControlerService.startCharge(deviceStatus.getDeviceImei(), deviceStatus.getDeviceImei(), (int) guns[0], 0);
             }
 
             String gunCode = String.valueOf(guns[0]);
             //标记最后订单时间 5分钟内不上报空闲状态 避免刚下单状态还没更新就被freeTask任务给顶掉了
-            redisCache.setCacheMapValue(RedisConstant.PILE_GUN_PAY_TIME, orderStatus.getPileCode()+"_"+gunCode,System.currentTimeMillis());
-
+            redisCache.setCacheMapValue(RedisConstant.PILE_GUN_PAY_TIME, orderStatus.getPileCode() + "_" + gunCode, System.currentTimeMillis());
 
 
             //TODO:在处理设备消息的地方需要处理设备启动充电是否成功
             //TODO:保存交易流水时保存一个交易订单
 
         } catch (Exception e) {
-            realTimeStatusPushFrame.deviceStatusPush(deviceConnectionMsg, t, deviceConnectionMsg.getDeviceId(), (byte) 1, (byte)2, (byte)1, 0,0 , zero , zero , 0);
+            logger.info("{}启动充电异常,{}",deviceConnectionMsg.getDeviceId(),e.getMessage());
+            realTimeStatusPushFrame.deviceStatusPush(deviceConnectionMsg, t, deviceConnectionMsg.getDeviceId(), (byte) 1, (byte) 2, (byte) 1, 0, 0, zero, zero, 0);
             e.printStackTrace();
         }
     }
-private  static  byte[] t=new byte[16];
+
+    private static byte[] t = new byte[16];
+
     /**
      * 计费模型校验应答处理
      *
@@ -394,81 +409,22 @@ private  static  byte[] t=new byte[16];
     private void billingModelHandle(DeviceConnectionMsg deviceConnectionMsg, byte[] respone_msg) {
         byte[] modelNum = Arrays.copyOfRange(respone_msg, 7, 9);
         byte[] result = Arrays.copyOfRange(respone_msg, 9, 10);
-        logger.info("计费模型验证应答"+deviceConnectionMsg.getDeviceId()+">>modelNum:"+DataConversion.bytesToHexString(modelNum) +";result:"+DataConversion.bytesToHexString(result));
+        logger.info("计费模型验证应答" + deviceConnectionMsg.getDeviceId() + ">>modelNum:" + DataConversion.bytesToHexString(modelNum) + ";result:" + DataConversion.bytesToHexString(result));
         if (result[0] == BillingModelConst.DIFFERENT) {
-            logger.info("获取计费模型{}",deviceConnectionMsg.getDeviceId());
+            logger.info("获取计费模型{}", deviceConnectionMsg.getDeviceId());
             //不一致请求计费模型,再向平台请求计费模型0x09
             billingModelFrame.getBillingModel(deviceConnectionMsg);
         }
     }
 
-    /**
-     * 计费模型请求处理,需要将获取到的云快充计费模型保存到数据库中
-     * @param deviceConnectionMsg
-     * @param respone_msg
-     */
-    private void getBillingModelHandle(DeviceConnectionMsg deviceConnectionMsg, byte[] respone_msg)  throws Exception{
-        int index=7;
-        int a=0;
-        byte[] modelNum = Arrays.copyOfRange(respone_msg, index, index+2);
-        index+=2;
-        byte[] j = Arrays.copyOfRange(respone_msg, index, index+4);
-        index+=4;
-        byte[] jf = Arrays.copyOfRange(respone_msg, index, index+4);
-        index+=4;
-        byte[]  f= Arrays.copyOfRange(respone_msg, index, index+4);
-        index+=4;
-        byte[] ff = Arrays.copyOfRange(respone_msg, index, index+4);
-        index+=4;
-        byte[] p = Arrays.copyOfRange(respone_msg, index, index+4);
-        index+=4;
-        byte[] pf = Arrays.copyOfRange(respone_msg, index, index+4);
-        index+=4;
-        byte[] g = Arrays.copyOfRange(respone_msg, index, index+4);
-        index+=4;
-        byte[] gf = Arrays.copyOfRange(respone_msg, index, index+4);
-        index+=4;
-        byte[] solt = Arrays.copyOfRange(respone_msg, index, index+1);
-        index++;
-        byte[] shiduan  = Arrays.copyOfRange(respone_msg, index, respone_msg.length);
-        QueryWrapper<BillingModel> billingModelQueryWrapper = new QueryWrapper<>();
-        billingModelQueryWrapper.eq("pile_code",deviceConnectionMsg.getDeviceId());
-        BillingModel one = billingModelService.getOne(billingModelQueryWrapper);
-        if (one==null){
-            one = new BillingModel();
-        }
-        BigDecimal bigDecimal = DataConversion.arrToBigDec(modelNum, 0,0);
-        int intValue = bigDecimal.intValue();
-        one.setDeviceImei(deviceConnectionMsg.getImei());
-        one.setDeviceSn(deviceConnectionMsg.getDeviceSn());
-        one.setPileCode(deviceConnectionMsg.getDeviceId());
-        one.setModelNo(intValue);
-        one.setSharpPrice(DataConversion.arrToBigDec(j,5,5));         //尖
-        one.setSharpServiceFee(DataConversion.arrToBigDec(jf,5,5));   //尖服
-        one.setPeakPrice(DataConversion.arrToBigDec(f,5,5));          //峰
-        one.setPeakServiceFee(DataConversion.arrToBigDec(ff,5,5));    //峰服
-        one.setFlatPrice(DataConversion.arrToBigDec(p,5,5));         //平
-        one.setFlatServiceFee(DataConversion.arrToBigDec(pf,5,5));   //平服
-        one.setValleyPrice(DataConversion.arrToBigDec(g,5,5));          //谷
-        one.setValleyServiceFee(DataConversion.arrToBigDec(gf,5,5));    //谷服
-        int integer= Integer.valueOf(Byte.toString(solt[0]));  //计损比例
-        one.setLossRatio(integer);                                               //时间段
-        StringBuilder stringBuilder = new StringBuilder();
-        for (byte b : shiduan) {
-            stringBuilder.append(String.valueOf(b));
-        }
-        String s = stringBuilder.toString();
-        one.setTimeSlot(s);
-        one.setUpdateTime(System.currentTimeMillis());//更新时间
-        billingModelService.saveOrUpdate(one);
-    }
 
     /**
      * 停机指令处理
+     *
      * @param deviceConnectionMsg
      * @param respone_msg
      */
-    private void stopChargingRequest(DeviceConnectionMsg deviceConnectionMsg,byte[] respone_msg){
+    private void stopChargingRequest(DeviceConnectionMsg deviceConnectionMsg, byte[] respone_msg) {
         byte[] guns = Arrays.copyOfRange(respone_msg, 7, 8);
         //查询设备sn和imie
         QueryWrapper<DeviceStatus> deviceStatusQueryWrapper = new QueryWrapper<>();
@@ -483,7 +439,7 @@ private  static  byte[] t=new byte[16];
         }
         RpcResult rpcResult = deviceControlerService.stopCharge(deviceStatus.getDeviceImei(), deviceStatus.getDeviceImei(), (int) guns[0]);
 
-        if (rpcResult.isOk()){
+        if (rpcResult.isOk()) {
             //发送停充成功,一般没有指令发送成功设备不执行
          /*   //deviceStatus.setGunStatus((byte) PortStatusConstant.INSERT_GUN);
             deviceStatus.setOnlineStatus(DeviceOnlineStatus.ONLINE);
@@ -497,22 +453,22 @@ private  static  byte[] t=new byte[16];
             orderStatusService.updateById(statusServiceOne);
             if (guns[0] == 1) {
                 if (redisCache.hasKey(RedisConstant.ONLINE_DEVICE_ONE)) {
-                    DeviceStatus ds= redisCache.getCacheMapValue(RedisConstant.ONLINE_DEVICE_ONE,deviceStatus.getPileCode());
-                    if (ds!=null){
-                        redisCache.deleteCacheMapValue(RedisConstant.ONLINE_DEVICE_ONE,deviceStatus.getPileCode());
+                    DeviceStatus ds = redisCache.getCacheMapValue(RedisConstant.ONLINE_DEVICE_ONE, deviceStatus.getPileCode());
+                    if (ds != null) {
+                        redisCache.deleteCacheMapValue(RedisConstant.ONLINE_DEVICE_ONE, deviceStatus.getPileCode());
                     }
                 }
             } else if (guns[0] == 2) {
                 if (redisCache.hasKey(RedisConstant.ONLINE_DEVICE_TWO)) {
-                    DeviceStatus ds= redisCache.getCacheMapValue(RedisConstant.ONLINE_DEVICE_TWO,deviceStatus.getPileCode());
-                    if (ds!=null){
-                        redisCache.deleteCacheMapValue(RedisConstant.ONLINE_DEVICE_TWO,deviceStatus.getPileCode());
+                    DeviceStatus ds = redisCache.getCacheMapValue(RedisConstant.ONLINE_DEVICE_TWO, deviceStatus.getPileCode());
+                    if (ds != null) {
+                        redisCache.deleteCacheMapValue(RedisConstant.ONLINE_DEVICE_TWO, deviceStatus.getPileCode());
                     }
                 }
             }
-            redisCache.setCacheMapValue(guns[0] == 1 ? RedisConstant.ONLINE_DEVICE_ONE : RedisConstant.ONLINE_DEVICE_TWO, deviceStatus.getPileCode(),deviceStatus);
-        }else {
-            logger.info("stop charging  device:"+deviceStatus.getDeviceSn()+";port:"+guns[0]+"stop charnging fail");
+            redisCache.setCacheMapValue(guns[0] == 1 ? RedisConstant.ONLINE_DEVICE_ONE : RedisConstant.ONLINE_DEVICE_TWO, deviceStatus.getPileCode(), deviceStatus);
+        } else {
+            logger.info("stop charging  device:" + deviceStatus.getDeviceSn() + ";port:" + guns[0] + "stop charnging fail");
         }
         //发出结束充电指令
         DeviceParam deviceParam = new DeviceParam();
@@ -526,52 +482,53 @@ private  static  byte[] t=new byte[16];
      * @param deviceConnectionMsg
      * @param respone_msg
      */
-    private void remoteBalanceUpdate(DeviceConnectionMsg deviceConnectionMsg,byte[] respone_msg)  throws Exception{
+    private void remoteBalanceUpdate(DeviceConnectionMsg deviceConnectionMsg, byte[] respone_msg) throws Exception {
         byte[] pileCode = Arrays.copyOfRange(respone_msg, 0, 7);
         byte[] guns = Arrays.copyOfRange(respone_msg, 7, 8);
         byte[] card = Arrays.copyOfRange(respone_msg, 8, 16);
-        byte[] balance=Arrays.copyOfRange(respone_msg, 16, 20);
+        byte[] balance = Arrays.copyOfRange(respone_msg, 16, 20);
         BigDecimal bigDecimal = DataConversion.arrToBigDec(balance, 2, 2);
 
-        String pile=DataConversion.bytesToHexString(pileCode);
+        String pile = DataConversion.bytesToHexString(pileCode);
 
-        logger.info("更新余额>>"+bigDecimal+";pileCode:"+pile);
+        logger.info("更新余额>>" + bigDecimal + ";pileCode:" + pile);
         //TODO:1.这里更新的余额需要针对充电桩使用的人员进行修改;(考虑后台计费);2.更新操作完成时候响应云快充更新结果
         //拿当前的订单去更新余额
         QueryWrapper<OrderStatus> orderStatusQueryWrapper = new QueryWrapper<>();
-        orderStatusQueryWrapper.eq("pile_code", pile).eq("guns_code", guns[0]).eq("card",card).orderByDesc("create_time").last("limit 1");
+        orderStatusQueryWrapper.eq("pile_code", pile).eq("guns_code", guns[0]).eq("card", card).orderByDesc("create_time").last("limit 1");
         OrderStatus statusServiceOne = orderStatusService.getOne(orderStatusQueryWrapper);
 
         QueryWrapper<BillingModel> billingModelQueryWrapper = new QueryWrapper<>();
-        billingModelQueryWrapper.eq("pile_code",pile);
+        billingModelQueryWrapper.eq("pile_code", pile);
         BillingModel model = billingModelService.getOne(billingModelQueryWrapper);
 
         //后台计费
-        Map<String, BigDecimal> map = transMoney.compute(1, model, statusServiceOne.getCreateTime(), System.currentTimeMillis(),true);
+        Map<String, BigDecimal> map = transMoney.compute(1, model, statusServiceOne.getCreateTime(), System.currentTimeMillis(), true);
         BigDecimal money = statusServiceOne.getStartMoney().subtract(map.get("money")).setScale(4, BigDecimal.ROUND_DOWN);
         BigDecimal add = money.add(bigDecimal);
         statusServiceOne.setStartMoney(add);
         orderStatusService.updateById(statusServiceOne);
         //这里测试默认更新成功
-        remoteBalanceUpdatePushFrame.updateBalance(deviceConnectionMsg,card, (byte) 0x00);
+        remoteBalanceUpdatePushFrame.updateBalance(deviceConnectionMsg, card, (byte) 0x00);
 
     }
 
     //保存订单开始状态,记录充电的交易流水
-    private void saveOrder(OrderStatus orderStatus){
+    private void saveOrder(OrderStatus orderStatus) {
         TransOrder transOrder = transMapping.orderStatusToTransOrder(orderStatus);
         byte[] transOrders = new byte[8];
         System.arraycopy(orderStatus.getTransOrder(), 8, transOrders, 0, transOrders.length);
         //为了云快充app显示的订单号一致,将订单号格式转化一下
         transOrder.setTrans(DataConversion.bytesToHexString(transOrders));
         boolean b = transOrderService.saveOrUpdate(transOrder);
-        logger.info("保存订单>>>>>"+DataConversion.bytesToHexString(orderStatus.getTransOrder())+"结果:"+b);
+        logger.info("保存订单>>>>>" + DataConversion.bytesToHexString(orderStatus.getTransOrder()) + "结果:" + b);
     }
+
     //余额不足解决办法,将下发的余额和尖峰平谷中最贵的价格发送到主板参数中,配合主板参数进行余额不足判定
-    private void setMoney(OrderStatus orderStatus){
+    private void setMoney(OrderStatus orderStatus) {
 
         QueryWrapper<BillingModel> orderStatusQueryWrapper = new QueryWrapper<>();
-        orderStatusQueryWrapper.eq("pile_code",orderStatus.getPileCode());
+        orderStatusQueryWrapper.eq("pile_code", orderStatus.getPileCode());
         BillingModel billingModel = billingModelService.getOne(orderStatusQueryWrapper);
         MainBoard mainBoard = new MainBoard();
         mainBoard.setBottomPrice(billingModel.getSharpPrice().add(billingModel.getSharpServiceFee()).intValue());
@@ -582,7 +539,7 @@ private  static  byte[] t=new byte[16];
         mainBoard.setBottomEnd(24);
         mainBoard.setFeeType(0x00);
         //设置主板参数
-        deviceControlerService.setMainBoard(orderStatus.getDeviceImei(),orderStatus.getDeviceImei(),mainBoard);
+        deviceControlerService.setMainBoard(orderStatus.getDeviceImei(), orderStatus.getDeviceImei(), mainBoard);
 
     }
 

+ 1 - 0
src/main/java/com/tmzn/devicelinkykc/msgEnum/DeviceSendYkc.java

@@ -12,6 +12,7 @@ public enum DeviceSendYkc {
     BILLING_MODEL_REQUEST(0x09,0x01,"充电桩计费模型请求"),
     TRANSACTION_RECORDS_REQUEST(0x3D,0x01,"交易记录"),
     TRANSACTION_RECORDS_REQUEST_16(0x3B,0x01,"交易记录"),
+    TRANSACTION_RECORDS_REQUEST_SG(0xB3,0x00,"深谷交易记录"),
 
     // 0x31-0x34 报文变更为 0xA5-0xA8 报文
     UPLOAD_DEVICE_STATUS_RESPONSE(0x13,0x01,"设备上报平台状态"),

+ 2 - 0
src/main/java/com/tmzn/devicelinkykc/msgEnum/YkcSendDevice.java

@@ -9,6 +9,7 @@ public enum YkcSendDevice {
     LOGIN_RESPONSE(0x02,0x00,"登录应答"),
     HEART_RESPONSE(0x04,0x00," 心跳包应答"),
     BILLING_MODEL_VALIDATE_RESPONSE(0x06,0x01,"计费模型验证请求应答"),
+    BILLING_MODEL_VALIDATE_RESPONSE_SG(0x0B,0x01,"深谷计费模型验证请求应答"),
     BILLING_MODEL_RESPONSE(0x0A,0x01,"计费模型请求应答"),
     TRANSACTION_RECORDS_RESPONSE(0x40,0x01,"交易记录确认"),
 
@@ -18,6 +19,7 @@ public enum YkcSendDevice {
     UPDATE_BALANCE(0x42,0x01,"远程更新余额"),
     CHECKTIME(0x56,0x00," 对时设置"),
     BILLING_MODEL_SETTING(0x58,0x01," 计费模型设置"),
+    BILLING_MODEL_SETTING_SG(0x85,0x01," 计费模型设置"),
     REMOTE_REBOOT(0x92,0x01," 远程重启"),
 
     START_CHARNGING_REQUEST_16(0x34,0x01,"运营平台远程控制启机"),

+ 3 - 0
src/main/java/com/tmzn/devicelinkykc/socket/SocketHandle.java

@@ -3,6 +3,7 @@ package com.tmzn.devicelinkykc.socket;
 import com.sun.org.apache.xpath.internal.operations.Bool;
 import com.tmzn.devicelinkykc.message.DeviceMsgHandle;
 import com.tmzn.devicelinkykc.message.YkcMsgHandle;
+import lombok.extern.slf4j.Slf4j;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.beans.factory.annotation.Value;
 import org.springframework.stereotype.Component;
@@ -17,6 +18,7 @@ import java.util.concurrent.ConcurrentHashMap;
  * @date 2024/3/14
  * @explain "  "
  */
+@Slf4j
 @Component
 public class SocketHandle {
     private  Map<String, DeviceConnectionMsg> deviceConnectionMsgMap = new ConcurrentHashMap<>();
@@ -31,6 +33,7 @@ public class SocketHandle {
 
     public synchronized void addDeviceConnection(String ip, int port, String deviceId, String imei, String deviceSn, String ver) throws IOException {
         if (deviceConnectionMsgMap.containsKey(deviceId)) {
+            log.info("已存在登录{}",imei);
             return;
         }
         //思考:这里的Socket的IP和端口从数据库查询到,云快充的device库中加字段保存IP和地址,根据桩后台传的设备SN码确定设备是对接的那个厂家的平台

+ 11 - 0
src/main/java/com/tmzn/devicelinkykc/taskQueue/HeartTask.java

@@ -1,10 +1,14 @@
 package com.tmzn.devicelinkykc.taskQueue;
 
 import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
+import com.tmzn.devicelinkykc.constant.Constant;
+import com.tmzn.devicelinkykc.constant.DeviceOnlineStatus;
 import com.tmzn.devicelinkykc.constant.RedisConstant;
 import com.tmzn.devicelinkykc.entity.Device;
 import com.tmzn.devicelinkykc.entity.DeviceStatus;
 import com.tmzn.devicelinkykc.entity.param.TransCheck;
+import com.tmzn.devicelinkykc.frameMsg.frameType.HeartFrameSend;
+import com.tmzn.devicelinkykc.frameMsg.frameType.LoginFrame;
 import com.tmzn.devicelinkykc.redis.RedisCache;
 import com.tmzn.devicelinkykc.service.DeviceService;
 import com.tmzn.devicelinkykc.service.DeviceStatusService;
@@ -13,6 +17,7 @@ import com.tmzn.devicelinkykc.socket.SocketHandle;
 import com.tmzn.devicelinkykc.taskQueue.queue.MsgHeartQueue;
 import lombok.extern.slf4j.Slf4j;
 import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.scheduling.annotation.Async;
 import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
 import org.springframework.stereotype.Component;
 
@@ -38,6 +43,8 @@ public class HeartTask {
     @Autowired
     private MsgHeartQueue msgHeartQueue;
 
+
+
     //理解:云快充的心跳30s未收到设备需要重新登录,这里直接拿连接socket的设备上报消息
     public void start(){
         ScheduledExecutorService scheduler = new ScheduledThreadPoolExecutor(1);
@@ -51,4 +58,8 @@ public class HeartTask {
         scheduler.scheduleAtFixedRate(task,0,10*1000, TimeUnit.MILLISECONDS);
 
     }
+
+
+
+
 }

+ 0 - 2
src/main/java/com/tmzn/devicelinkykc/taskQueue/StartTask.java

@@ -40,8 +40,6 @@ public class StartTask {
     private DeviceOnlineTask deviceOnlineTask;
     @Autowired
     private MsgService msgService;
-    @Autowired
-    private TransCheckTask transCheckTask;
 
     //协议层启动后执行,连接前准备
     @PostConstruct

+ 134 - 134
src/main/java/com/tmzn/devicelinkykc/taskQueue/TransCheckTask.java

@@ -1,134 +1,134 @@
-package com.tmzn.devicelinkykc.taskQueue;
-
-import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
-import com.tmzn.devicelinkykc.constant.RedisConstant;
-import com.tmzn.devicelinkykc.entity.Device;
-import com.tmzn.devicelinkykc.entity.param.TransCheck;
-import com.tmzn.devicelinkykc.frameMsg.DataConversion;
-import com.tmzn.devicelinkykc.frameMsg.FrameDataSplicing;
-import com.tmzn.devicelinkykc.msgEnum.DeviceSendYkc;
-import com.tmzn.devicelinkykc.redis.RedisCache;
-import com.tmzn.devicelinkykc.service.DeviceService;
-import com.tmzn.devicelinkykc.service.DeviceStatusService;
-import com.tmzn.devicelinkykc.socket.DeviceConnectionMsg;
-import com.tmzn.devicelinkykc.socket.SocketHandle;
-import com.tmzn.devicelinkykc.taskQueue.queue.MsgHeartQueue;
-import com.tmzn.devicelinkykc.util.Encrytion;
-import lombok.extern.slf4j.Slf4j;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Component;
-
-import java.io.IOException;
-import java.util.List;
-import java.util.Map;
-import java.util.Optional;
-import java.util.Set;
-import java.util.concurrent.ScheduledExecutorService;
-import java.util.concurrent.ScheduledThreadPoolExecutor;
-import java.util.concurrent.TimeUnit;
-
-/**
- * @author xp
- * @date 2024/7/23
- * @explain "  "
- */
-@Component
-@Slf4j
-public class TransCheckTask {
-    @Autowired
-    private SocketHandle socketHandle;
-    @Autowired
-    private RedisCache redisCache;
-    @Autowired
-    private DeviceService deviceService;
-    @Autowired
-    private MsgHeartQueue msgHeartQueue;
-
-    //30s没收到订单回复再次上送,上送三次就结束将订单改为
-    public void start(){
-        ScheduledExecutorService scheduler = new ScheduledThreadPoolExecutor(1);
-        Runnable task = new Runnable() {
-            @Override
-            public void run() {
-                try {
-                    log.info("check Trans>>>>>>>>>>>>>>>>>>>");
-                    Map<String, DeviceConnectionMsg> deviceConnectionMsgMap = socketHandle.getDeviceConnectionMsgMap();
-                    Set<String> imeis = redisCache.getCacheObject(RedisConstant.DEVICE_INFO);
-                    imeis.stream().forEach(s -> {
-                        QueryWrapper<Device> deviceQueryWrapper = new QueryWrapper<>();
-                        QueryWrapper<Device> device_imei = deviceQueryWrapper.eq("device_imei", s);
-                        Device one = deviceService.getOne(device_imei);
-                        if (one != null) {
-                            if (deviceConnectionMsgMap.containsKey(one.getPileCode())) {
-                                //在线且链接,
-                                TransCheck transCheck = redisCache.getCacheObject(RedisConstant.NO_RESPONSE_WAS_RECEIVED + one.getPileCode());
-
-                                if (transCheck.getCheck_time() == 0) {
-                                    if ((System.currentTimeMillis() - transCheck.getTime()) > 30 * 1000) {
-                                        log.info(one.getPileCode() + "Transchek>>>>>>>checkTime:" + transCheck.getCheck_time());
-                                        upTrans(deviceConnectionMsgMap.get(one.getPileCode()), transCheck.getTrans());
-                                        transCheck.setCheck_time(1);
-                                        redisCache.setCacheObject(RedisConstant.NO_RESPONSE_WAS_RECEIVED+one.getPileCode(),transCheck);
-                                    }
-                                } else if (transCheck.getCheck_time() == 1) {
-                                    if ((System.currentTimeMillis() - transCheck.getTime()) > 60 * 1000) {
-                                        log.info(one.getPileCode() + "Transchek>>>>>>>checkTime:" + transCheck.getCheck_time());
-                                        upTrans(deviceConnectionMsgMap.get(one.getPileCode()), transCheck.getTrans());
-                                        transCheck.setCheck_time(2);
-                                        redisCache.setCacheObject(RedisConstant.NO_RESPONSE_WAS_RECEIVED+one.getPileCode(),transCheck);
-                                    }
-                                } else if (transCheck.getCheck_time() == 2) {
-                                    if ((System.currentTimeMillis() - transCheck.getTime()) > 90 * 1000) {
-                                        log.info(one.getPileCode() + "Transchek>>>>>>>checkTime:" + transCheck.getCheck_time());
-                                        upTrans(deviceConnectionMsgMap.get(one.getPileCode()), transCheck.getTrans());
-                                        transCheck.setCheck_time(3);
-                                        redisCache.setCacheObject(RedisConstant.NO_RESPONSE_WAS_RECEIVED+one.getPileCode(),transCheck);
-                                    }
-                                } else {
-                                    redisCache.deleteObject(RedisConstant.NO_RESPONSE_WAS_RECEIVED + one.getPileCode());
-                                }
-                            }
-                        }
-                    });
-                }catch (Exception e){
-
-                }
-            }
-        };
-        scheduler.scheduleAtFixedRate(task,1,5*1000, TimeUnit.MILLISECONDS);
-
-    }
-    private void upTrans(DeviceConnectionMsg deviceConnectionMsg,byte[] bytes){
-        if(deviceConnectionMsg.getIs18()){
-            try {
-
-                String key = redisCache.getCacheObject(RedisConstant.KEYS+deviceConnectionMsg.getDeviceId());
-                byte[] rsaEncrypt = Encrytion.aesEncrypt(bytes, key.getBytes());
-                byte[] msg = FrameDataSplicing.spliceing(deviceConnectionMsg.getMessageCount(), DeviceSendYkc.TRANSACTION_RECORDS_REQUEST.getFrameType(), DeviceSendYkc.TRANSACTION_RECORDS_REQUEST.getEncryptFlag(), rsaEncrypt, rsaEncrypt.length, deviceConnectionMsg.getIs18());
-                deviceConnectionMsg.getOutputStream().write(msg);
-                deviceConnectionMsg.getOutputStream().flush();
-                log.info(deviceConnectionMsg.getDeviceId() + "Trans_chek,rsaEncrypt:"+DataConversion.bytesToHexString(rsaEncrypt));
-            } catch (IOException e) {
-                log.info("TransCheck:>>pileCode:" + deviceConnectionMsg.getDeviceId() + " ,TransactionFlow push frame Exception");
-                e.printStackTrace();
-            } catch (Exception e) {
-                e.printStackTrace();
-            }
-            deviceConnectionMsg.incrementMessageCount();
-            return;
-        }
-        try {
-            byte[] msg = FrameDataSplicing.spliceing(deviceConnectionMsg.getMessageCount(), DeviceSendYkc.TRANSACTION_RECORDS_REQUEST.getFrameType(), DeviceSendYkc.TRANSACTION_RECORDS_REQUEST.getEncryptFlag(), bytes, bytes.length, deviceConnectionMsg.getIs18());
-            deviceConnectionMsg.getOutputStream().write(msg);
-            deviceConnectionMsg.getOutputStream().flush();
-            log.info(deviceConnectionMsg.getDeviceId() + "Trans_chek:"+DataConversion.bytesToHexString(bytes));
-        } catch (IOException e) {
-            log.info("TransCheck:>>pileCode:" + deviceConnectionMsg.getDeviceId() + " ,TransactionFlow push frame Exception");
-            e.printStackTrace();
-        } catch (Exception e) {
-            e.printStackTrace();
-        }
-        deviceConnectionMsg.incrementMessageCount();
-
-    }
-}
+//package com.tmzn.devicelinkykc.taskQueue;
+//
+//import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
+//import com.tmzn.devicelinkykc.constant.RedisConstant;
+//import com.tmzn.devicelinkykc.entity.Device;
+//import com.tmzn.devicelinkykc.entity.param.TransCheck;
+//import com.tmzn.devicelinkykc.frameMsg.DataConversion;
+//import com.tmzn.devicelinkykc.frameMsg.FrameDataSplicing;
+//import com.tmzn.devicelinkykc.msgEnum.DeviceSendYkc;
+//import com.tmzn.devicelinkykc.redis.RedisCache;
+//import com.tmzn.devicelinkykc.service.DeviceService;
+//import com.tmzn.devicelinkykc.service.DeviceStatusService;
+//import com.tmzn.devicelinkykc.socket.DeviceConnectionMsg;
+//import com.tmzn.devicelinkykc.socket.SocketHandle;
+//import com.tmzn.devicelinkykc.taskQueue.queue.MsgHeartQueue;
+//import com.tmzn.devicelinkykc.util.Encrytion;
+//import lombok.extern.slf4j.Slf4j;
+//import org.springframework.beans.factory.annotation.Autowired;
+//import org.springframework.stereotype.Component;
+//
+//import java.io.IOException;
+//import java.util.List;
+//import java.util.Map;
+//import java.util.Optional;
+//import java.util.Set;
+//import java.util.concurrent.ScheduledExecutorService;
+//import java.util.concurrent.ScheduledThreadPoolExecutor;
+//import java.util.concurrent.TimeUnit;
+//
+///**
+// * @author xp
+// * @date 2024/7/23
+// * @explain "  "
+// */
+//@Component
+//@Slf4j
+//public class TransCheckTask {
+//    @Autowired
+//    private SocketHandle socketHandle;
+//    @Autowired
+//    private RedisCache redisCache;
+//    @Autowired
+//    private DeviceService deviceService;
+//    @Autowired
+//    private MsgHeartQueue msgHeartQueue;
+//
+//    //30s没收到订单回复再次上送,上送三次就结束将订单改为
+//    public void start(){
+//        ScheduledExecutorService scheduler = new ScheduledThreadPoolExecutor(1);
+//        Runnable task = new Runnable() {
+//            @Override
+//            public void run() {
+//                try {
+//                    log.info("check Trans>>>>>>>>>>>>>>>>>>>");
+//                    Map<String, DeviceConnectionMsg> deviceConnectionMsgMap = socketHandle.getDeviceConnectionMsgMap();
+//                    Set<String> imeis = redisCache.getCacheObject(RedisConstant.DEVICE_INFO);
+//                    imeis.stream().forEach(s -> {
+//                        QueryWrapper<Device> deviceQueryWrapper = new QueryWrapper<>();
+//                        QueryWrapper<Device> device_imei = deviceQueryWrapper.eq("device_imei", s);
+//                        Device one = deviceService.getOne(device_imei);
+//                        if (one != null) {
+//                            if (deviceConnectionMsgMap.containsKey(one.getPileCode())) {
+//                                //在线且链接,
+//                                TransCheck transCheck = redisCache.getCacheObject(RedisConstant.NO_RESPONSE_WAS_RECEIVED + one.getPileCode());
+//
+//                                if (transCheck.getCheck_time() == 0) {
+//                                    if ((System.currentTimeMillis() - transCheck.getTime()) > 30 * 1000) {
+//                                        log.info(one.getPileCode() + "Transchek>>>>>>>checkTime:" + transCheck.getCheck_time());
+//                                        upTrans(deviceConnectionMsgMap.get(one.getPileCode()), transCheck.getTrans());
+//                                        transCheck.setCheck_time(1);
+//                                        redisCache.setCacheObject(RedisConstant.NO_RESPONSE_WAS_RECEIVED+one.getPileCode(),transCheck);
+//                                    }
+//                                } else if (transCheck.getCheck_time() == 1) {
+//                                    if ((System.currentTimeMillis() - transCheck.getTime()) > 60 * 1000) {
+//                                        log.info(one.getPileCode() + "Transchek>>>>>>>checkTime:" + transCheck.getCheck_time());
+//                                        upTrans(deviceConnectionMsgMap.get(one.getPileCode()), transCheck.getTrans());
+//                                        transCheck.setCheck_time(2);
+//                                        redisCache.setCacheObject(RedisConstant.NO_RESPONSE_WAS_RECEIVED+one.getPileCode(),transCheck);
+//                                    }
+//                                } else if (transCheck.getCheck_time() == 2) {
+//                                    if ((System.currentTimeMillis() - transCheck.getTime()) > 90 * 1000) {
+//                                        log.info(one.getPileCode() + "Transchek>>>>>>>checkTime:" + transCheck.getCheck_time());
+//                                        upTrans(deviceConnectionMsgMap.get(one.getPileCode()), transCheck.getTrans());
+//                                        transCheck.setCheck_time(3);
+//                                        redisCache.setCacheObject(RedisConstant.NO_RESPONSE_WAS_RECEIVED+one.getPileCode(),transCheck);
+//                                    }
+//                                } else {
+//                                    redisCache.deleteObject(RedisConstant.NO_RESPONSE_WAS_RECEIVED + one.getPileCode());
+//                                }
+//                            }
+//                        }
+//                    });
+//                }catch (Exception e){
+//
+//                }
+//            }
+//        };
+//        scheduler.scheduleAtFixedRate(task,1,5*1000, TimeUnit.MILLISECONDS);
+//
+//    }
+//    private void upTrans(DeviceConnectionMsg deviceConnectionMsg,byte[] bytes){
+//        if(deviceConnectionMsg.getIs18()){
+//            try {
+//
+//                String key = redisCache.getCacheObject(RedisConstant.KEYS+deviceConnectionMsg.getDeviceId());
+//                byte[] rsaEncrypt = Encrytion.aesEncrypt(bytes, key.getBytes());
+//                byte[] msg = FrameDataSplicing.spliceing(deviceConnectionMsg.getMessageCount(), DeviceSendYkc.TRANSACTION_RECORDS_REQUEST.getFrameType(), DeviceSendYkc.TRANSACTION_RECORDS_REQUEST.getEncryptFlag(), rsaEncrypt, rsaEncrypt.length, deviceConnectionMsg.getIs18());
+//                deviceConnectionMsg.getOutputStream().write(msg);
+//                deviceConnectionMsg.getOutputStream().flush();
+//                log.info(deviceConnectionMsg.getDeviceId() + "Trans_chek,rsaEncrypt:"+DataConversion.bytesToHexString(rsaEncrypt));
+//            } catch (IOException e) {
+//                log.info("TransCheck:>>pileCode:" + deviceConnectionMsg.getDeviceId() + " ,TransactionFlow push frame Exception");
+//                e.printStackTrace();
+//            } catch (Exception e) {
+//                e.printStackTrace();
+//            }
+//            deviceConnectionMsg.incrementMessageCount();
+//            return;
+//        }
+//        try {
+//            byte[] msg = FrameDataSplicing.spliceing(deviceConnectionMsg.getMessageCount(), DeviceSendYkc.TRANSACTION_RECORDS_REQUEST.getFrameType(), DeviceSendYkc.TRANSACTION_RECORDS_REQUEST.getEncryptFlag(), bytes, bytes.length, deviceConnectionMsg.getIs18());
+//            deviceConnectionMsg.getOutputStream().write(msg);
+//            deviceConnectionMsg.getOutputStream().flush();
+//            log.info(deviceConnectionMsg.getDeviceId() + "Trans_chek:"+DataConversion.bytesToHexString(bytes));
+//        } catch (IOException e) {
+//            log.info("TransCheck:>>pileCode:" + deviceConnectionMsg.getDeviceId() + " ,TransactionFlow push frame Exception");
+//            e.printStackTrace();
+//        } catch (Exception e) {
+//            e.printStackTrace();
+//        }
+//        deviceConnectionMsg.incrementMessageCount();
+//
+//    }
+//}

+ 3 - 4
src/main/java/com/tmzn/devicelinkykc/taskQueue/queue/MsgCharngingQueue.java

@@ -1,14 +1,13 @@
 package com.tmzn.devicelinkykc.taskQueue.queue;
 
-import com.tmzn.devicelinkykc.entity.Device;
 import com.tmzn.devicelinkykc.socket.DeviceConnectionMsg;
+import com.tmzn.devicelinkykc.taskQueue.runner.MsgCharngingRunner;
 import lombok.extern.slf4j.Slf4j;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.boot.ApplicationArguments;
 import org.springframework.boot.ApplicationRunner;
 import org.springframework.stereotype.Component;
 
-import java.util.List;
 import java.util.Map;
 import java.util.concurrent.ArrayBlockingQueue;
 import java.util.concurrent.BlockingQueue;
@@ -21,7 +20,7 @@ public class MsgCharngingQueue  extends Thread implements ApplicationRunner {
 
 
     @Autowired
-    private TaskRunner taskRunner;
+    private MsgCharngingRunner msgCharngingRunner;
 
     public void add(Map<String, DeviceConnectionMsg> object){
         try {
@@ -37,7 +36,7 @@ public class MsgCharngingQueue  extends Thread implements ApplicationRunner {
         while (true){
             try {
                 Map<String, DeviceConnectionMsg> charnging = charngingQueue.take();
-                    taskRunner.chargingMsg(charnging);
+                msgCharngingRunner.chargingMsg(charnging);
             } catch (Exception e) {
                 e.printStackTrace();
                 log.error("执行异常",e);

+ 3 - 4
src/main/java/com/tmzn/devicelinkykc/taskQueue/queue/MsgFreeQueue.java

@@ -1,14 +1,13 @@
 package com.tmzn.devicelinkykc.taskQueue.queue;
 
-import com.tmzn.devicelinkykc.entity.Device;
 import com.tmzn.devicelinkykc.socket.DeviceConnectionMsg;
+import com.tmzn.devicelinkykc.taskQueue.runner.MsgFreeRunner;
 import lombok.extern.slf4j.Slf4j;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.boot.ApplicationArguments;
 import org.springframework.boot.ApplicationRunner;
 import org.springframework.stereotype.Component;
 
-import java.util.List;
 import java.util.Map;
 import java.util.concurrent.ArrayBlockingQueue;
 import java.util.concurrent.BlockingQueue;
@@ -21,7 +20,7 @@ public class MsgFreeQueue extends Thread implements ApplicationRunner {
 
 
     @Autowired
-    private TaskRunner taskRunner;
+    private MsgFreeRunner msgFreeRunner;
 
     public void add(Map<String, DeviceConnectionMsg> object) {
         try {
@@ -37,7 +36,7 @@ public class MsgFreeQueue extends Thread implements ApplicationRunner {
         while (true) {
             try {
                 Map<String, DeviceConnectionMsg> free = freeQueue.take();
-                taskRunner.freeMsg(free);
+                msgFreeRunner.freeMsg(free);
             } catch (Exception e) {
                 e.printStackTrace();
                 log.error("执行异常", e);

+ 5 - 5
src/main/java/com/tmzn/devicelinkykc/taskQueue/queue/MsgHeartQueue.java

@@ -1,14 +1,13 @@
 package com.tmzn.devicelinkykc.taskQueue.queue;
 
-import com.tmzn.devicelinkykc.entity.Device;
 import com.tmzn.devicelinkykc.socket.DeviceConnectionMsg;
+import com.tmzn.devicelinkykc.taskQueue.runner.MsgHeartRunner;
 import lombok.extern.slf4j.Slf4j;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.boot.ApplicationArguments;
 import org.springframework.boot.ApplicationRunner;
 import org.springframework.stereotype.Component;
 
-import java.util.List;
 import java.util.Map;
 import java.util.concurrent.ArrayBlockingQueue;
 import java.util.concurrent.BlockingQueue;
@@ -21,8 +20,7 @@ public class MsgHeartQueue extends Thread implements ApplicationRunner {
 
 
     @Autowired
-    private TaskRunner taskRunner;
-
+    MsgHeartRunner msgHeartRunner;
     public void add(Map<String, DeviceConnectionMsg> map){
         try {
                 heartQueue.put(map);
@@ -37,7 +35,7 @@ public class MsgHeartQueue extends Thread implements ApplicationRunner {
        while (true){
            try {
                Map<String, DeviceConnectionMsg> map= heartQueue.take();
-               taskRunner.heartMsg(map);
+               msgHeartRunner.heartMsg(map);
            } catch (Exception e) {
                e.printStackTrace();
                log.error("执行异常",e);
@@ -51,4 +49,6 @@ public class MsgHeartQueue extends Thread implements ApplicationRunner {
             this.start();
             log.info("处理器启动");
     }
+
+
 }

+ 3 - 2
src/main/java/com/tmzn/devicelinkykc/taskQueue/queue/MsgTranscationQueue.java

@@ -1,6 +1,7 @@
 package com.tmzn.devicelinkykc.taskQueue.queue;
 
 import com.tmzn.devicelinkykc.socket.DeviceConnectionMsg;
+import com.tmzn.devicelinkykc.taskQueue.runner.MsgTranscationRunner;
 import lombok.extern.slf4j.Slf4j;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.boot.ApplicationArguments;
@@ -24,7 +25,7 @@ public class MsgTranscationQueue extends Thread implements ApplicationRunner {
 
 
     @Autowired
-    private TaskRunner taskRunner;
+    private MsgTranscationRunner msgTranscationRunner;
 
     public void add(Map<String, DeviceConnectionMsg> object){
         try {
@@ -40,7 +41,7 @@ public class MsgTranscationQueue extends Thread implements ApplicationRunner {
         while (true){
             try {
                 Map<String, DeviceConnectionMsg> map = freeQueue.take();
-                taskRunner.transactionMsg(map);
+                msgTranscationRunner.transactionMsg(map);
             } catch (Exception e) {
                 e.printStackTrace();
                 log.error("执行异常",e);

+ 16 - 334
src/main/java/com/tmzn/devicelinkykc/taskQueue/queue/TaskRunner.java

@@ -1,63 +1,55 @@
-package com.tmzn.devicelinkykc.taskQueue.queue;
+package com.tmzn.devicelinkykc.taskQueue.runner;
 
 import com.alibaba.fastjson2.JSONObject;
 import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
-import com.sun.org.apache.xpath.internal.operations.Or;
 import com.tmzn.devicelinkykc.constant.Constant;
 import com.tmzn.devicelinkykc.constant.DeviceOnlineStatus;
-import com.tmzn.devicelinkykc.constant.PortStatusConstant;
 import com.tmzn.devicelinkykc.constant.RedisConstant;
-import com.tmzn.devicelinkykc.constant.ykc.BillingModelConst;
 import com.tmzn.devicelinkykc.constant.ykc.StatusConstant;
 import com.tmzn.devicelinkykc.constant.ykc.TransConstant;
 import com.tmzn.devicelinkykc.entity.BillingModel;
 import com.tmzn.devicelinkykc.entity.Device;
 import com.tmzn.devicelinkykc.entity.DeviceStatus;
 import com.tmzn.devicelinkykc.entity.OrderStatus;
-import com.tmzn.devicelinkykc.frameMsg.DataConversion;
-import com.tmzn.devicelinkykc.frameMsg.FrameDataSplicing;
 import com.tmzn.devicelinkykc.frameMsg.TransMoney;
 import com.tmzn.devicelinkykc.frameMsg.frameType.HeartFrameSend;
 import com.tmzn.devicelinkykc.frameMsg.frameType.LoginFrame;
 import com.tmzn.devicelinkykc.frameMsg.frameType.RealTimeStatusPushFrame;
 import com.tmzn.devicelinkykc.frameMsg.frameType.TransactionFlowPushFrame;
-import com.tmzn.devicelinkykc.msgEnum.DeviceSendYkc;
 import com.tmzn.devicelinkykc.redis.RedisCache;
 import com.tmzn.devicelinkykc.service.*;
 import com.tmzn.devicelinkykc.socket.DeviceConnectionMsg;
 import com.tmzn.devicelinkykc.socket.SocketHandle;
 import com.tmzn.devicelinkykc.transdata.entity.DeviceParam;
-import com.tmzn.devicelinkykc.util.Encrytion;
 import lombok.extern.slf4j.Slf4j;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.scheduling.annotation.Async;
 import org.springframework.stereotype.Component;
 
-import java.io.IOException;
 import java.math.BigDecimal;
-import java.time.*;
-import java.time.temporal.ChronoUnit;
-import java.util.*;
+import java.time.Instant;
+import java.time.ZoneId;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
 import java.util.concurrent.TimeUnit;
 import java.util.stream.Collectors;
 
-/**
- * @author xp
- * @date 2024/3/13
- * @explain " 任务执行 "
- */
+
 @Component
-@Slf4j(topic = "TaskRunner")
-public class TaskRunner {
+@Slf4j(topic = "MsgHeartRunner")
+public class MsgCharngingRunner {
 
     @Autowired
-    private HeartFrameSend heartFrameSend;
-    @Autowired
-    private RedisCache redisCache;
+    private DeviceService deviceService;
+
     @Autowired
     private LoginFrame loginFrame;
+
     @Autowired
-    private DeviceService deviceService;
+    private RedisCache redisCache;
+
+
     @Autowired
     private RealTimeStatusPushFrame realTimeStatusPushFrame;
     @Autowired
@@ -71,6 +63,7 @@ public class TaskRunner {
     @Autowired
     private SocketHandle socketHandle;
 
+
     @Autowired
     private DeviceControlerService deviceControlerService;
     @Autowired
@@ -78,91 +71,6 @@ public class TaskRunner {
 
     private static final BigDecimal zero = new BigDecimal("0");
 
-    @Async("heartTaskAsyncPool")
-    public void heartMsg(Map<String, DeviceConnectionMsg> map) throws Exception {
-        log.info("======Heart beat task starting=====");
-        //todo return
-        //任务处理
-        //map拿出来进行心跳包上报,1:直接检查心跳时间是否大于三十秒
-        Set<String> devicePileCodes = map.keySet();
-        log.info("heart.deviceConnectionSize>>"+devicePileCodes.size());
-        devicePileCodes.stream().forEach(devicePileCode -> {
-            try{
-                DeviceConnectionMsg deviceConnectionMsg = map.get(devicePileCode);
-                Long heartTime = deviceConnectionMsg.getHeartTime();
-                //log.info("heartTime>>>" + new Date(heartTime));
-
-                //拿到1枪设备状态
-                // log.info("↑↑↑↑↑↑↑↑↑↑");
-                if (redisCache.hasKey(RedisConstant.ONLINE_DEVICE_ONE)) {
-
-                    //1:当上一次的心跳和本次的心跳相差大于30秒证明已经3次没收到心跳回复了,进行重新登录
-                    //2:设备第一次上线时未触发过登录,设备连接集合中初始话的心跳时间还是0,符合该判断,进行登录
-                    QueryWrapper<Device> deviceQueryWrapper = new QueryWrapper<>();
-                    deviceQueryWrapper.eq("pile_code", devicePileCode).eq("disabled", DeviceOnlineStatus.NORMAL);
-                    Device device = deviceService.getOne(deviceQueryWrapper);
-                    DeviceStatus oneDs = redisCache.getCacheMapValue(RedisConstant.ONLINE_DEVICE_ONE, devicePileCode);
-                    if (deviceConnectionMsg.getLoginStatus()== Constant.DEVICE_NOT_LOGIN_STATUS) {
-                        //
-                        if (oneDs != null&&oneDs.getOnlineStatus() == DeviceOnlineStatus.ONLINE && (System.currentTimeMillis() - heartTime) > 50 * 1000L) {
-                            log.info("heartTaskAsyncPool-1>not longin and heart normal>>" + devicePileCode);
-                            loginFrame.loginMsgSend(deviceConnectionMsg,device);
-                            return;
-                        }
-                    }
-                    //log.info("↑1↑1↑1↑1↑1↑1↑1↑1↑1↑1");
-                    if (oneDs != null) {
-                        //  log.info("oneDes-heart>>>>>>>" + oneDs.toString());
-                        if (oneDs.getOnlineStatus() == DeviceOnlineStatus.ONLINE && (System.currentTimeMillis() - heartTime) > 50 * 1000L) {
-                            log.info("pileCode:" + devicePileCode + " loging... ..." + (System.currentTimeMillis() - heartTime));
-                            int a = 0;
-                            if (redisCache.hasKey(RedisConstant.DEVICE_LOGIN_YKC + devicePileCode)) {
-                                //如果登录次数30秒内登三次就算断开
-                                a = redisCache.getCacheObject(RedisConstant.DEVICE_LOGIN_YKC + devicePileCode);
-                                if (a > 3) {
-                                    socketHandle.removeDeviceConnection(devicePileCode);
-                                } else {
-                                    loginFrame.loginMsgSend(deviceConnectionMsg, device);
-                                }
-                                a++;
-                                redisCache.setCacheObject(RedisConstant.DEVICE_LOGIN_YKC + devicePileCode, a,32 * 1000, TimeUnit.MILLISECONDS);
-                            } else {
-                                redisCache.setCacheObject(RedisConstant.DEVICE_LOGIN_YKC + devicePileCode, a, 32 * 1000, TimeUnit.MILLISECONDS);
-                            }
-                        }else {
-                            //存在设备在线状态的,上送心跳
-                          //  log.info("heartSend-1>>>"+devicePileCode);
-                            heartFrameSend.heartSend(deviceConnectionMsg, oneDs);
-                        }
-                    }
-                }
-                //拿到2枪设备状态
-                if (redisCache.hasKey(RedisConstant.ONLINE_DEVICE_TWO)) {
-                    DeviceStatus twoDs = redisCache.getCacheMapValue(RedisConstant.ONLINE_DEVICE_TWO, devicePileCode);
-                    if (twoDs != null) {
-                        log.info("twoDes-heart>>>>>>>" + twoDs.toString());
-                        if (twoDs.getOnlineStatus() == DeviceOnlineStatus.ONLINE && (System.currentTimeMillis() - heartTime) > 50 * 1000L) {
-                            log.info("twoDs:pileCode:" + devicePileCode + " loging... ..." + (System.currentTimeMillis() - heartTime));
-                            //1:当上一次的心跳和本次的心跳相差大于30秒证明已经3次没收到心跳回复了,进行重新登录
-                            //2:设备第一次上线时未触发过登录,设备连接集合中初始话的心跳时间还是0,符合该判断,进行登录
-                            QueryWrapper<Device> deviceQueryWrapper = new QueryWrapper<>();
-                            deviceQueryWrapper.eq("pile_code", devicePileCode).eq("disabled", DeviceOnlineStatus.NORMAL);
-                            Device device = deviceService.getOne(deviceQueryWrapper);
-
-                            loginFrame.loginMsgSend(deviceConnectionMsg, device);
-                        }
-                        //存在设备在线状态的,上送心跳
-                      //  log.info("heartSend-2>>>"+devicePileCode);
-                        heartFrameSend.heartSend(deviceConnectionMsg, twoDs);
-                    }
-                }
-            }catch (Exception e){
-                log.info("Heart beat task exception"+e.toString());
-                e.printStackTrace();
-            }
-        });
-        log.info("======Heart beat task ending=====");
-    }
 
     @Async("charngingTaskAsyncPool")
     public void chargingMsg(Map<String, DeviceConnectionMsg> map) {
@@ -431,231 +339,5 @@ public class TaskRunner {
         log.info("======Charging status push task ending=====");
     }
 
-    @Async("freeTaskAsyncPool")
-    public void freeMsg(Map<String, DeviceConnectionMsg> map) throws Exception {
-        log.info("======Free status push task starting=====");
-
-        //任务处理
-        //redis取出在线设备集合
-        Set<String> devicePileCodes = map.keySet();
-        log.info("free.deviceConnectionSize>>"+devicePileCodes.size());
-        devicePileCodes.stream().forEach(devicePileCode -> {
-            try{
-
-
-                if (redisCache.hasKey(RedisConstant.ONLINE_DEVICE_ONE)) {
-                    DeviceStatus deviceStatus = redisCache.getCacheMapValue(RedisConstant.ONLINE_DEVICE_ONE, devicePileCode);
-                    if (deviceStatus != null) {
-                        if (deviceStatus.getGunStatus() == StatusConstant.CHARGING) {
-                            log.info("freeMsg>>>deviceguns status>>"+deviceStatus.getGunStatus());
-                        }
-
-                        //标记最后订单时间 5分钟内不上报空闲状态 避免刚下单状态还没更新就被freeTask任务给顶掉了
-                        try{
-                            long ts = redisCache.getCacheMapValue(RedisConstant.PILE_GUN_PAY_TIME, devicePileCode+"_1");
-                            if(ts!=0){
-                                long ts1 = System.currentTimeMillis();
-                                if((ts1-ts)<300*1000){
-                                    log.info("{}下单时间未超过5分钟不上报空闲状态",devicePileCode+"_1");
-                                    return;
-                                }
-                            }
-                        }catch (Exception e){
-
-                        }
-
-
-                        //存在设备在线状态的上送空闲状态
-                        DeviceConnectionMsg deviceConnectionMsg = map.get(devicePileCode);
-                        if (deviceConnectionMsg.getLoginStatus()== Constant.DEVICE_NOT_LOGIN_STATUS){
-                            //
-                            QueryWrapper<Device> deviceQueryWrapper = new QueryWrapper<>();
-                            deviceQueryWrapper.eq("pile_code", devicePileCode).eq("disabled", DeviceOnlineStatus.NORMAL);
-                            Device device = deviceService.getOne(deviceQueryWrapper);
-                            Long heartTime = deviceConnectionMsg.getHeartTime();
-                            if (deviceStatus.getOnlineStatus() == DeviceOnlineStatus.ONLINE && (System.currentTimeMillis() - heartTime) > 50 * 1000L) {
-                                log.info("heartTaskAsyncPool-1>not longin and heart normal>>" + devicePileCode);
-                                // loginFrame.loginMsgSend(deviceConnectionMsg,device);
-                            }
-                            return;
-                        }
-                        if (deviceStatus.getGunStatus() != StatusConstant.CHARGING) {
-                            if (deviceConnectionMsg.getLoginStatus() == 1) {
-                                log.info("↑↑↑↑↑↑↑↑↑↑↑↑↑空闲实时状态上报1111↑↑↑↑↑↑↑↑↑↑↑↑↑ " + deviceStatus.getGunStatus() + "<>" + (deviceStatus.getGunStatus() == PortStatusConstant.EMERGENCY_STOP));
-                                if (deviceStatus.getGunStatus() == PortStatusConstant.EMERGENCY_STOP) {
-                                    //急停中也是空闲状态上报
-                                    deviceStatus.setGunStatus(StatusConstant.FREE);
-                                }
-                                realTimeStatusPushFrame.deviceStatusPush(deviceConnectionMsg, FrameDataSplicing.
-                                        transactionNum(deviceStatus.getPileCode(), deviceConnectionMsg.getMessageCount()), deviceStatus.getPileCode(), deviceStatus.getGunPort(), deviceStatus.getGunStatus(), deviceStatus.getInsertGunStatus(), 0, 0, zero, zero, 0);
-                            }
-                        }
-                    }
-                }
-                if (redisCache.hasKey(RedisConstant.ONLINE_DEVICE_TWO)) {
-                    DeviceStatus deviceStatus = redisCache.getCacheMapValue(RedisConstant.ONLINE_DEVICE_TWO, devicePileCode);
-
-                    if (deviceStatus != null) {
-
-                        try{
-                            long ts = redisCache.getCacheMapValue(RedisConstant.PILE_GUN_PAY_TIME, devicePileCode+"_2");
-                            if(ts!=0){
-                                long ts1 = System.currentTimeMillis();
-                                if((ts1-ts)<300*1000){
-                                    log.info("{}下单时间未超过5分钟不主动上报空闲状态",devicePileCode+"_2");
-                                    return;
-                                }
-                            }
-                        }catch (Exception e){
-
-                        }
-
-                        //标记最后订单时间 5分钟内不上报空闲状态 避免刚下单状态还没更新就被freeTask任务给顶掉了
-                        //存在设备在线状态的上送空闲状态
-                        DeviceConnectionMsg deviceConnectionMsg = map.get(devicePileCode);
-                        if (deviceConnectionMsg.getLoginStatus()== Constant.DEVICE_NOT_LOGIN_STATUS){
-                            //
-                            QueryWrapper<Device> deviceQueryWrapper = new QueryWrapper<>();
-                            deviceQueryWrapper.eq("pile_code", devicePileCode).eq("disabled", DeviceOnlineStatus.NORMAL);
-                            Device device = deviceService.getOne(deviceQueryWrapper);
-                            Long heartTime = deviceConnectionMsg.getHeartTime();
-                            if (deviceStatus.getOnlineStatus() == DeviceOnlineStatus.ONLINE && (System.currentTimeMillis() - heartTime) > 50 * 1000L) {
-                                log.info("heartTaskAsyncPool-1>not longin and heart normal>>" + devicePileCode);
-                                loginFrame.loginMsgSend(deviceConnectionMsg,device);
-                            }
-                            return;
-                        }
-                        if (deviceStatus.getGunStatus() != StatusConstant.CHARGING) {
-                            if (deviceConnectionMsg.getLoginStatus() == 1) {
-                                if (deviceStatus.getGunStatus() == PortStatusConstant.EMERGENCY_STOP) {
-                                    //急停中也是空闲状态上报
-                                    deviceStatus.setGunStatus(StatusConstant.FREE);
-                                }
-                                log.info("↑↑↑↑↑↑↑↑↑↑↑↑↑空闲实时状态上报2222↑↑↑↑↑↑↑↑↑↑↑↑↑ ");
-                                realTimeStatusPushFrame.deviceStatusPush(deviceConnectionMsg, FrameDataSplicing.
-                                        transactionNum(deviceStatus.getPileCode(), deviceConnectionMsg.getMessageCount()), deviceStatus.getPileCode(), deviceStatus.getGunPort(), deviceStatus.getGunStatus(), deviceStatus.getInsertGunStatus(), 0, 0, zero, zero, 0);
-                            }
-                        }
-                    }
-                }
-            }catch (Exception e){
-                log.info("======Free msg exception ===="+e.toString());
-                e.printStackTrace();
-            }
-
-        });
-
-        log.info("======Free status push task ending=====");
-    }
-
-    @Async("transactionTaskAsyncPool")
-    public void transactionMsg(Map<String, DeviceConnectionMsg> map) throws Exception {
-        log.info("======transaction push task starting=====");
-        //任务处理 1.上报交易流水消息后没有响应回复的情况,30秒上送一次三次后停止,五分钟后上送最后一次,不管是否成功都不再上送:有结束时间,充电状态是结束充电的
-        QueryWrapper<OrderStatus> queryWrapper = new QueryWrapper<>();
-        queryWrapper.eq("now_order_status", 1); //充电完成
-        queryWrapper.eq("transaction_order_reporting_action_status", 1); //未上报
-        queryWrapper.eq("transaction_order_reply_status", 0); //未上报
-
-        List<OrderStatus> list = orderStatusService.list(queryWrapper);
-
-//        System.out.println(list);
-
-        Map<String, OrderStatus> orderStatusMap = list.stream()
-                .collect(Collectors.toMap(
-                        OrderStatus::getPileCode, orderStatus
-                                -> orderStatus,(existing, replacement)
-                                -> (Instant.ofEpochMilli(existing.getCreateTime())
-                                .atZone(ZoneId.systemDefault()).toLocalDateTime())
-                                .isAfter(Instant.ofEpochMilli(replacement.getCreateTime())
-                                        .atZone(ZoneId.systemDefault()).toLocalDateTime())
-                                ? existing : replacement));
-        List<OrderStatus> orderStatuses = orderStatusMap.values().stream()
-                .collect(Collectors.toList());
-
-        //过滤充电状态是结束的且已经上送未收到订单恢复的,说明交易订单上报没收到云快充消息,如果时间充电结束时间到现在大于30秒上送
-        List<OrderStatus> collect = orderStatuses.stream().filter(orderStatus -> orderStatus.getNowOrderStatus() == 1 && orderStatus.getTransactionOrderReplyStatus() == 0 && orderStatus.getTransactionOrderReportingActionStatus() == 1).collect(Collectors.toList());
-        //看订单时间进行重新上送
-        if (collect.size() > 0) {
-            collect.stream().forEach(orderStatus -> {
-                //上送订单并且订单上送大于5分钟但是没有变成充电状态的订单,当成空上报一次
-
-               /* if ((((System.currentTimeMillis()-orderStatus.getEndTime())/1000) / 30 )==1||(((System.currentTimeMillis()-orderStatus.getEndTime()) /1000) / 60 )==1||(((System.currentTimeMillis()-orderStatus.getEndTime()) /1000) / 90)==1){
-                    //各上送一次订单记录
-                    DeviceConnectionMsg deviceConnectionMsg = map.get(orderStatus.getPileCode());
-                    try {
-                        String bytes = redisCache.getCacheObject(orderStatus.getPileCode());
-                        byte[] bytes1 = Encrytion.aesEncrypt(orderStatus.getOriginalText(), bytes.getBytes());
-                        deviceConnectionMsg.getOutputStream().write(bytes1);
-                        deviceConnectionMsg.getOutputStream().flush();
-                        deviceConnectionMsg.incrementMessageCount();
-                    } catch (Exception e) {
-                        e.printStackTrace();
-                    }
-                }else*/
-                if ((System.currentTimeMillis() - orderStatus.getEndTime()) > 5 * 60 * 1000 && orderStatus.getTransactionOrderReplyStatus() != 5) {
-                    //五分钟上送最后一次结束,上送
-                    DeviceConnectionMsg deviceConnectionMsg = map.get(orderStatus.getPileCode());
-                    if (deviceConnectionMsg!=null&&deviceConnectionMsg.getLoginStatus()== Constant.DEVICE_NOT_LOGIN_STATUS){
-                        //wshizhengjuezhe zhewanyier meishajishuhanlian danshi zhedongxi  queshi xilan
-                        return;
-                    }
-                    try {
-                        //String bytes = redisCache.getCacheObject(orderStatus.getPileCode());
-                        //byte[] bytes1 = Encrytion.aesEncrypt(orderStatus.getOriginalText(), bytes.getBytes());
-
-                        //byte[] spliceing = FrameDataSplicing.spliceing(deviceConnectionMsg.getMessageCount(), DeviceSendYkc.TRANSACTION_RECORDS_REQUEST.getFrameType(), DeviceSendYkc.TRANSACTION_RECORDS_REQUEST.getEncryptFlag(), bytes1, bytes1.length);
-
-                        deviceConnectionMsg.getOutputStream().write(orderStatus.getOriginalText());
-                        deviceConnectionMsg.getOutputStream().flush();
-                        deviceConnectionMsg.incrementMessageCount();
-                    } catch (Exception e) {
-                        e.printStackTrace();
-                    }
-                    //将恢复结果状态转成5,记录为充电记录上传5分钟后失败
-                    orderStatus.setTransactionOrderReplyStatus((byte) 5);
-                    orderStatusService.updateById(orderStatus);
-                    log.info("最新未收到上报的订单list5分钟推送最后一次>>" + orderStatuses.toString());
-                }
-            });
-        }
-//        List<OrderStatus> collects = list.stream().filter(orderStatus -> orderStatus.getOriginalText()==null||orderStatus.getEndTime()==0).collect(Collectors.toList());
-//        if (collects.size()>0){
-//            collects.forEach(orderStatus -> {
-//            log.info(orderStatus.getPileCode()+":检查订单状态>orderStatus.getOriginalText()==null||orderStatus.getEndTime()==0>>"+orderStatus.getCreateTime());
-//            QueryWrapper<DeviceStatus> queryWrapper = new QueryWrapper<>();
-//            queryWrapper.eq("pile_code",orderStatus.getPileCode());
-//            DeviceStatus one = deviceStatusService.getOne(queryWrapper);
-//
-//            QueryWrapper<Device> deviceQueryWrapper = new QueryWrapper<>();
-//            deviceQueryWrapper.eq("pile_code", orderStatus.getPileCode()).eq("disabled", DeviceOnlineStatus.NORMAL);
-//            Device device = deviceService.getOne(deviceQueryWrapper);
-//
-//            QueryWrapper<BillingModel> billingModelQueryWrapper = new QueryWrapper<>();
-//            billingModelQueryWrapper.eq("pile_code", orderStatus.getPileCode());
-//            BillingModel model = billingModelService.getOne(billingModelQueryWrapper);
-//
-//            if ((System.currentTimeMillis() - orderStatus.getCreateTime()) > 5 * 60 * 1000 && (one.getGunStatus()!=StatusConstant.CHARGING)) {
-//                log.info(orderStatus.getPileCode()+":上送订单并且订单上送大于5分钟但是没有变成充电状态的订单,当成空上报一次>"+orderStatus.getCreateTime());
-//                DeviceConnectionMsg deviceConnectionMsg = map.get(orderStatus.getPileCode());
-//                try {
-//                    Map<String, BigDecimal> compute = transMoney.compute(1, new BillingModel(), 0L, 0L, false);
-//                    byte[] e=transactionFlowPushFrame.sendTrans(deviceConnectionMsg, orderStatus.getTransOrder(), orderStatus.getPileCode(), (byte) 1, orderStatus.getCreateTime(), System.currentTimeMillis() + 3 * 60 * 1000, model, orderStatus.getCard(), compute, TransConstant.OTHER_STOP);
-//                    orderStatus.setOriginalText(e);
-//                    orderStatus.setEndTime(1);
-//                    orderStatus.setNowOrderStatus(StatusConstant.NOW_ORDER_STATUS_CHARGING_ENDING);
-//                    orderStatus.setReasonStopCharging(TransConstant.OTHER_STOP);
-//                    orderStatusService.updateById(orderStatus);
-//
-//                } catch (Exception e) {
-//                    e.printStackTrace();
-//                }
-//            }
-//            });
-//        }
-
-        log.info("======transaction push task ending=====");
-    }
-
 
 }

+ 170 - 0
src/main/java/com/tmzn/devicelinkykc/taskQueue/runner/MsgFreeRunner.java

@@ -0,0 +1,170 @@
+package com.tmzn.devicelinkykc.taskQueue.runner;
+
+import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
+import com.tmzn.devicelinkykc.constant.Constant;
+import com.tmzn.devicelinkykc.constant.DeviceOnlineStatus;
+import com.tmzn.devicelinkykc.constant.PortStatusConstant;
+import com.tmzn.devicelinkykc.constant.RedisConstant;
+import com.tmzn.devicelinkykc.constant.ykc.StatusConstant;
+import com.tmzn.devicelinkykc.entity.Device;
+import com.tmzn.devicelinkykc.entity.DeviceStatus;
+import com.tmzn.devicelinkykc.frameMsg.FrameDataSplicing;
+import com.tmzn.devicelinkykc.frameMsg.TransMoney;
+import com.tmzn.devicelinkykc.frameMsg.frameType.HeartFrameSend;
+import com.tmzn.devicelinkykc.frameMsg.frameType.LoginFrame;
+import com.tmzn.devicelinkykc.frameMsg.frameType.RealTimeStatusPushFrame;
+import com.tmzn.devicelinkykc.frameMsg.frameType.TransactionFlowPushFrame;
+import com.tmzn.devicelinkykc.redis.RedisCache;
+import com.tmzn.devicelinkykc.service.*;
+import com.tmzn.devicelinkykc.socket.DeviceConnectionMsg;
+import com.tmzn.devicelinkykc.socket.SocketHandle;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.scheduling.annotation.Async;
+import org.springframework.stereotype.Component;
+
+import java.math.BigDecimal;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.TimeUnit;
+
+
+@Component
+@Slf4j(topic = "MsgHeartRunner")
+public class MsgFreeRunner {
+
+    @Autowired
+    private DeviceService deviceService;
+
+    @Autowired
+    private LoginFrame loginFrame;
+
+    @Autowired
+    private RedisCache redisCache;
+
+    @Autowired
+    private RealTimeStatusPushFrame realTimeStatusPushFrame;
+
+
+    private static final BigDecimal zero = new BigDecimal("0");
+
+
+    @Async("freeTaskAsyncPool")
+    public void freeMsg(Map<String, DeviceConnectionMsg> map) throws Exception {
+        log.info("======Free status push task starting=====");
+
+        //任务处理
+        //redis取出在线设备集合
+        Set<String> devicePileCodes = map.keySet();
+        log.info("free.deviceConnectionSize>>"+devicePileCodes.size());
+        devicePileCodes.stream().forEach(devicePileCode -> {
+            try{
+
+
+                if (redisCache.hasKey(RedisConstant.ONLINE_DEVICE_ONE)) {
+                    DeviceStatus deviceStatus = redisCache.getCacheMapValue(RedisConstant.ONLINE_DEVICE_ONE, devicePileCode);
+                    if (deviceStatus != null) {
+                        if (deviceStatus.getGunStatus() == StatusConstant.CHARGING) {
+                            log.info("freeMsg>>>deviceguns status>>"+deviceStatus.getGunStatus());
+                        }
+
+                        //标记最后订单时间 5分钟内不上报空闲状态 避免刚下单状态还没更新就被freeTask任务给顶掉了
+                        try{
+                            long ts = redisCache.getCacheMapValue(RedisConstant.PILE_GUN_PAY_TIME, devicePileCode+"_1");
+                            if(ts!=0){
+                                long ts1 = System.currentTimeMillis();
+                                if((ts1-ts)<300*1000){
+                                    log.info("{}下单时间未超过5分钟不上报空闲状态",devicePileCode+"_1");
+                                    return;
+                                }
+                            }
+                        }catch (Exception e){
+
+                        }
+
+
+                        //存在设备在线状态的上送空闲状态
+                        DeviceConnectionMsg deviceConnectionMsg = map.get(devicePileCode);
+                        if (deviceConnectionMsg.getLoginStatus()== Constant.DEVICE_NOT_LOGIN_STATUS){
+                            //
+                            QueryWrapper<Device> deviceQueryWrapper = new QueryWrapper<>();
+                            deviceQueryWrapper.eq("pile_code", devicePileCode).eq("disabled", DeviceOnlineStatus.NORMAL);
+                            Device device = deviceService.getOne(deviceQueryWrapper);
+                            Long heartTime = deviceConnectionMsg.getHeartTime();
+                            if (deviceStatus.getOnlineStatus() == DeviceOnlineStatus.ONLINE && (System.currentTimeMillis() - heartTime) > 50 * 1000L) {
+                                log.info("heartTaskAsyncPool-1>not longin and heart normal>>" + devicePileCode);
+                                // loginFrame.loginMsgSend(deviceConnectionMsg,device);
+                            }
+                            return;
+                        }
+                        if (deviceStatus.getGunStatus() != StatusConstant.CHARGING) {
+                            if (deviceConnectionMsg.getLoginStatus() == 1) {
+                                log.info("↑↑↑↑↑↑↑↑↑↑↑↑↑空闲实时状态上报1111↑↑↑↑↑↑↑↑↑↑↑↑↑ " + deviceStatus.getGunStatus() + "<>" + (deviceStatus.getGunStatus() == PortStatusConstant.EMERGENCY_STOP));
+                                if (deviceStatus.getGunStatus() == PortStatusConstant.EMERGENCY_STOP) {
+                                    //急停中也是空闲状态上报
+                                    deviceStatus.setGunStatus(StatusConstant.FREE);
+                                }
+                                realTimeStatusPushFrame.deviceStatusPush(deviceConnectionMsg, FrameDataSplicing.
+                                        transactionNum(deviceStatus.getPileCode(), deviceConnectionMsg.getMessageCount()), deviceStatus.getPileCode(), deviceStatus.getGunPort(), deviceStatus.getGunStatus(), deviceStatus.getInsertGunStatus(), 0, 0, zero, zero, 0);
+                            }
+                        }
+                    }
+                }
+                if (redisCache.hasKey(RedisConstant.ONLINE_DEVICE_TWO)) {
+                    DeviceStatus deviceStatus = redisCache.getCacheMapValue(RedisConstant.ONLINE_DEVICE_TWO, devicePileCode);
+
+                    if (deviceStatus != null) {
+
+                        try{
+                            long ts = redisCache.getCacheMapValue(RedisConstant.PILE_GUN_PAY_TIME, devicePileCode+"_2");
+                            if(ts!=0){
+                                long ts1 = System.currentTimeMillis();
+                                if((ts1-ts)<300*1000){
+                                    log.info("{}下单时间未超过5分钟不主动上报空闲状态",devicePileCode+"_2");
+                                    return;
+                                }
+                            }
+                        }catch (Exception e){
+
+                        }
+
+                        //标记最后订单时间 5分钟内不上报空闲状态 避免刚下单状态还没更新就被freeTask任务给顶掉了
+                        //存在设备在线状态的上送空闲状态
+                        DeviceConnectionMsg deviceConnectionMsg = map.get(devicePileCode);
+                        if (deviceConnectionMsg.getLoginStatus()== Constant.DEVICE_NOT_LOGIN_STATUS){
+                            //
+                            QueryWrapper<Device> deviceQueryWrapper = new QueryWrapper<>();
+                            deviceQueryWrapper.eq("pile_code", devicePileCode).eq("disabled", DeviceOnlineStatus.NORMAL);
+                            Device device = deviceService.getOne(deviceQueryWrapper);
+                            Long heartTime = deviceConnectionMsg.getHeartTime();
+                            if (deviceStatus.getOnlineStatus() == DeviceOnlineStatus.ONLINE && (System.currentTimeMillis() - heartTime) > 50 * 1000L) {
+                                log.info("heartTaskAsyncPool-1>not longin and heart normal>>" + devicePileCode);
+                                loginFrame.loginMsgSend(deviceConnectionMsg,device);
+                            }
+                            return;
+                        }
+                        if (deviceStatus.getGunStatus() != StatusConstant.CHARGING) {
+                            if (deviceConnectionMsg.getLoginStatus() == 1) {
+                                if (deviceStatus.getGunStatus() == PortStatusConstant.EMERGENCY_STOP) {
+                                    //急停中也是空闲状态上报
+                                    deviceStatus.setGunStatus(StatusConstant.FREE);
+                                }
+                                log.info("↑↑↑↑↑↑↑↑↑↑↑↑↑空闲实时状态上报2222↑↑↑↑↑↑↑↑↑↑↑↑↑ ");
+                                realTimeStatusPushFrame.deviceStatusPush(deviceConnectionMsg, FrameDataSplicing.
+                                        transactionNum(deviceStatus.getPileCode(), deviceConnectionMsg.getMessageCount()), deviceStatus.getPileCode(), deviceStatus.getGunPort(), deviceStatus.getGunStatus(), deviceStatus.getInsertGunStatus(), 0, 0, zero, zero, 0);
+                            }
+                        }
+                    }
+                }
+            }catch (Exception e){
+                log.info("======Free msg exception ===="+e.toString());
+                e.printStackTrace();
+            }
+
+        });
+
+        log.info("======Free status push task ending=====");
+    }
+
+
+}

+ 120 - 0
src/main/java/com/tmzn/devicelinkykc/taskQueue/runner/MsgHeartRunner.java

@@ -0,0 +1,120 @@
+package com.tmzn.devicelinkykc.taskQueue.runner;
+
+import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
+import com.tmzn.devicelinkykc.constant.Constant;
+import com.tmzn.devicelinkykc.constant.DeviceOnlineStatus;
+import com.tmzn.devicelinkykc.constant.RedisConstant;
+import com.tmzn.devicelinkykc.entity.Device;
+import com.tmzn.devicelinkykc.entity.DeviceStatus;
+import com.tmzn.devicelinkykc.frameMsg.frameType.HeartFrameSend;
+import com.tmzn.devicelinkykc.frameMsg.frameType.LoginFrame;
+import com.tmzn.devicelinkykc.redis.RedisCache;
+import com.tmzn.devicelinkykc.service.DeviceService;
+import com.tmzn.devicelinkykc.socket.DeviceConnectionMsg;
+import com.tmzn.devicelinkykc.socket.SocketHandle;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.scheduling.annotation.Async;
+import org.springframework.stereotype.Component;
+
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.TimeUnit;
+
+
+@Component
+@Slf4j(topic = "MsgHeartRunner")
+public class MsgHeartRunner {
+
+    @Autowired
+    private DeviceService deviceService;
+
+    @Autowired
+    private LoginFrame loginFrame;
+
+    @Autowired
+    private RedisCache redisCache;
+
+    @Autowired
+    private HeartFrameSend heartFrameSend;
+
+    @Autowired
+    private SocketHandle socketHandle;
+
+
+
+    @Async("heartTaskAsyncPool")
+    public void heartMsg(Map<String, DeviceConnectionMsg> map) throws Exception {
+        log.info("======Heart beat task starting=====");
+        //todo return
+        //任务处理
+        //map拿出来进行心跳包上报,1:直接检查心跳时间是否大于三十秒
+        Set<String> devicePileCodes = map.keySet();
+        log.info("heart.deviceConnectionSize>>"+devicePileCodes.size());
+        devicePileCodes.stream().forEach(devicePileCode -> {
+            try{
+                DeviceConnectionMsg deviceConnectionMsg = map.get(devicePileCode);
+                handlePort(1,devicePileCode,deviceConnectionMsg);
+            }catch (Exception e){
+                log.info("{}Heart beat task exception"+e.toString(),devicePileCode);
+                e.printStackTrace();
+            }
+        });
+        log.info("======Heart beat task ending=====");
+    }
+
+    public void handlePort(int portId,String devicePileCode,DeviceConnectionMsg deviceConnectionMsg){
+
+        Long heartTime = deviceConnectionMsg.getHeartTime();
+        String portStatusCacheKey = portId==1?RedisConstant.ONLINE_DEVICE_ONE:RedisConstant.ONLINE_DEVICE_TWO;
+        //1:当上一次的心跳和本次的心跳相差大于30秒证明已经3次没收到心跳回复了,进行重新登录
+        //2:设备第一次上线时未触发过登录,设备连接集合中初始话的心跳时间还是0,符合该判断,进行登录
+        DeviceStatus oneDs = redisCache.getCacheMapValue(portStatusCacheKey, devicePileCode);
+
+        if (deviceConnectionMsg.getLoginStatus()== Constant.DEVICE_NOT_LOGIN_STATUS) {
+            if (oneDs != null && oneDs.getOnlineStatus() == DeviceOnlineStatus.ONLINE && (System.currentTimeMillis() - heartTime) > 50 * 1000L) {
+                QueryWrapper<Device> deviceQueryWrapper = new QueryWrapper<>();
+                deviceQueryWrapper.eq("pile_code", devicePileCode).eq("disabled", DeviceOnlineStatus.NORMAL);
+                Device device = deviceService.getOne(deviceQueryWrapper);
+                if(device!=null){
+                    loginFrame.loginMsgSend(deviceConnectionMsg,device);
+                }
+                log.info("heartTaskAsyncPool-1>not longin and heart normal>>" + devicePileCode);
+                return;
+            }
+        }
+        if(oneDs==null){
+            return;
+        }
+
+        if (oneDs.getOnlineStatus() == DeviceOnlineStatus.ONLINE && (System.currentTimeMillis() - heartTime) > 50 * 1000L) {
+            log.info("pileCode:" + devicePileCode + " loging... ..." + (System.currentTimeMillis() - heartTime));
+            int a = 0;
+            if (redisCache.hasKey(RedisConstant.DEVICE_LOGIN_YKC + devicePileCode)) {
+                //如果登录次数30秒内登三次就算断开
+                a = redisCache.getCacheObject(RedisConstant.DEVICE_LOGIN_YKC + devicePileCode);
+                if (a > 3) {
+                    socketHandle.removeDeviceConnection(devicePileCode);
+                } else {
+                    QueryWrapper<Device> deviceQueryWrapper = new QueryWrapper<>();
+                    deviceQueryWrapper.eq("pile_code", devicePileCode).eq("disabled", DeviceOnlineStatus.NORMAL);
+                    Device device = deviceService.getOne(deviceQueryWrapper);
+                    if(device!=null){
+                        loginFrame.loginMsgSend(deviceConnectionMsg, device);
+                    }
+                }
+                a++;
+                redisCache.setCacheObject(RedisConstant.DEVICE_LOGIN_YKC + devicePileCode, a,32 * 1000, TimeUnit.MILLISECONDS);
+            } else {
+                redisCache.setCacheObject(RedisConstant.DEVICE_LOGIN_YKC + devicePileCode, a, 32 * 1000, TimeUnit.MILLISECONDS);
+            }
+        }else {
+            //存在设备在线状态的,上送心跳
+            //  log.info("heartSend-1>>>"+devicePileCode);
+            heartFrameSend.heartSend(deviceConnectionMsg, oneDs);
+        }
+
+    }
+
+
+}

+ 165 - 0
src/main/java/com/tmzn/devicelinkykc/taskQueue/runner/MsgTranscationRunner.java

@@ -0,0 +1,165 @@
+package com.tmzn.devicelinkykc.taskQueue.runner;
+
+import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
+import com.tmzn.devicelinkykc.constant.Constant;
+import com.tmzn.devicelinkykc.constant.DeviceOnlineStatus;
+import com.tmzn.devicelinkykc.constant.RedisConstant;
+import com.tmzn.devicelinkykc.entity.Device;
+import com.tmzn.devicelinkykc.entity.DeviceStatus;
+import com.tmzn.devicelinkykc.entity.OrderStatus;
+import com.tmzn.devicelinkykc.frameMsg.frameType.HeartFrameSend;
+import com.tmzn.devicelinkykc.frameMsg.frameType.LoginFrame;
+import com.tmzn.devicelinkykc.redis.RedisCache;
+import com.tmzn.devicelinkykc.service.DeviceService;
+import com.tmzn.devicelinkykc.service.OrderStatusService;
+import com.tmzn.devicelinkykc.socket.DeviceConnectionMsg;
+import com.tmzn.devicelinkykc.socket.SocketHandle;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.scheduling.annotation.Async;
+import org.springframework.stereotype.Component;
+
+import java.time.Instant;
+import java.time.ZoneId;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.TimeUnit;
+import java.util.stream.Collectors;
+
+
+@Component
+@Slf4j(topic = "MsgHeartRunner")
+public class MsgTranscationRunner {
+
+    @Autowired
+    private DeviceService deviceService;
+
+    @Autowired
+    private LoginFrame loginFrame;
+
+    @Autowired
+    private RedisCache redisCache;
+
+    @Autowired
+    private HeartFrameSend heartFrameSend;
+
+    @Autowired
+    private SocketHandle socketHandle;
+
+    @Autowired
+    private OrderStatusService orderStatusService;
+
+
+    @Async("transactionTaskAsyncPool")
+    public void transactionMsg(Map<String, DeviceConnectionMsg> map) throws Exception {
+        log.info("======transaction push task starting=====");
+        //任务处理 1.上报交易流水消息后没有响应回复的情况,30秒上送一次三次后停止,五分钟后上送最后一次,不管是否成功都不再上送:有结束时间,充电状态是结束充电的
+        QueryWrapper<OrderStatus> queryWrapper = new QueryWrapper<>();
+        queryWrapper.eq("now_order_status", 1); //充电完成
+        queryWrapper.eq("transaction_order_reporting_action_status", 1); //未上报
+        queryWrapper.eq("transaction_order_reply_status", 0); //未上报
+
+        List<OrderStatus> list = orderStatusService.list(queryWrapper);
+
+//        System.out.println(list);
+
+        Map<String, OrderStatus> orderStatusMap = list.stream()
+                .collect(Collectors.toMap(
+                        OrderStatus::getPileCode, orderStatus
+                                -> orderStatus,(existing, replacement)
+                                -> (Instant.ofEpochMilli(existing.getCreateTime())
+                                .atZone(ZoneId.systemDefault()).toLocalDateTime())
+                                .isAfter(Instant.ofEpochMilli(replacement.getCreateTime())
+                                        .atZone(ZoneId.systemDefault()).toLocalDateTime())
+                                ? existing : replacement));
+        List<OrderStatus> orderStatuses = orderStatusMap.values().stream()
+                .collect(Collectors.toList());
+
+        //过滤充电状态是结束的且已经上送未收到订单恢复的,说明交易订单上报没收到云快充消息,如果时间充电结束时间到现在大于30秒上送
+        List<OrderStatus> collect = orderStatuses.stream().filter(orderStatus -> orderStatus.getNowOrderStatus() == 1 && orderStatus.getTransactionOrderReplyStatus() == 0 && orderStatus.getTransactionOrderReportingActionStatus() == 1).collect(Collectors.toList());
+        //看订单时间进行重新上送
+        if (collect.size() > 0) {
+            collect.stream().forEach(orderStatus -> {
+                //上送订单并且订单上送大于5分钟但是没有变成充电状态的订单,当成空上报一次
+
+               /* if ((((System.currentTimeMillis()-orderStatus.getEndTime())/1000) / 30 )==1||(((System.currentTimeMillis()-orderStatus.getEndTime()) /1000) / 60 )==1||(((System.currentTimeMillis()-orderStatus.getEndTime()) /1000) / 90)==1){
+                    //各上送一次订单记录
+                    DeviceConnectionMsg deviceConnectionMsg = map.get(orderStatus.getPileCode());
+                    try {
+                        String bytes = redisCache.getCacheObject(orderStatus.getPileCode());
+                        byte[] bytes1 = Encrytion.aesEncrypt(orderStatus.getOriginalText(), bytes.getBytes());
+                        deviceConnectionMsg.getOutputStream().write(bytes1);
+                        deviceConnectionMsg.getOutputStream().flush();
+                        deviceConnectionMsg.incrementMessageCount();
+                    } catch (Exception e) {
+                        e.printStackTrace();
+                    }
+                }else*/
+                if ((System.currentTimeMillis() - orderStatus.getEndTime()) > 5 * 60 * 1000 && orderStatus.getTransactionOrderReplyStatus() != 5) {
+                    //五分钟上送最后一次结束,上送
+                    DeviceConnectionMsg deviceConnectionMsg = map.get(orderStatus.getPileCode());
+                    if (deviceConnectionMsg!=null&&deviceConnectionMsg.getLoginStatus()== Constant.DEVICE_NOT_LOGIN_STATUS){
+                        //wshizhengjuezhe zhewanyier meishajishuhanlian danshi zhedongxi  queshi xilan
+                        return;
+                    }
+                    try {
+                        //String bytes = redisCache.getCacheObject(orderStatus.getPileCode());
+                        //byte[] bytes1 = Encrytion.aesEncrypt(orderStatus.getOriginalText(), bytes.getBytes());
+
+                        //byte[] spliceing = FrameDataSplicing.spliceing(deviceConnectionMsg.getMessageCount(), DeviceSendYkc.TRANSACTION_RECORDS_REQUEST.getFrameType(), DeviceSendYkc.TRANSACTION_RECORDS_REQUEST.getEncryptFlag(), bytes1, bytes1.length);
+
+                        deviceConnectionMsg.getOutputStream().write(orderStatus.getOriginalText());
+                        deviceConnectionMsg.getOutputStream().flush();
+                        deviceConnectionMsg.incrementMessageCount();
+                    } catch (Exception e) {
+                        e.printStackTrace();
+                    }
+                    //将恢复结果状态转成5,记录为充电记录上传5分钟后失败
+                    orderStatus.setTransactionOrderReplyStatus((byte) 5);
+                    orderStatusService.updateById(orderStatus);
+                    log.info("最新未收到上报的订单list5分钟推送最后一次>>" + orderStatuses.toString());
+                }
+            });
+        }
+//        List<OrderStatus> collects = list.stream().filter(orderStatus -> orderStatus.getOriginalText()==null||orderStatus.getEndTime()==0).collect(Collectors.toList());
+//        if (collects.size()>0){
+//            collects.forEach(orderStatus -> {
+//            log.info(orderStatus.getPileCode()+":检查订单状态>orderStatus.getOriginalText()==null||orderStatus.getEndTime()==0>>"+orderStatus.getCreateTime());
+//            QueryWrapper<DeviceStatus> queryWrapper = new QueryWrapper<>();
+//            queryWrapper.eq("pile_code",orderStatus.getPileCode());
+//            DeviceStatus one = deviceStatusService.getOne(queryWrapper);
+//
+//            QueryWrapper<Device> deviceQueryWrapper = new QueryWrapper<>();
+//            deviceQueryWrapper.eq("pile_code", orderStatus.getPileCode()).eq("disabled", DeviceOnlineStatus.NORMAL);
+//            Device device = deviceService.getOne(deviceQueryWrapper);
+//
+//            QueryWrapper<BillingModel> billingModelQueryWrapper = new QueryWrapper<>();
+//            billingModelQueryWrapper.eq("pile_code", orderStatus.getPileCode());
+//            BillingModel model = billingModelService.getOne(billingModelQueryWrapper);
+//
+//            if ((System.currentTimeMillis() - orderStatus.getCreateTime()) > 5 * 60 * 1000 && (one.getGunStatus()!=StatusConstant.CHARGING)) {
+//                log.info(orderStatus.getPileCode()+":上送订单并且订单上送大于5分钟但是没有变成充电状态的订单,当成空上报一次>"+orderStatus.getCreateTime());
+//                DeviceConnectionMsg deviceConnectionMsg = map.get(orderStatus.getPileCode());
+//                try {
+//                    Map<String, BigDecimal> compute = transMoney.compute(1, new BillingModel(), 0L, 0L, false);
+//                    byte[] e=transactionFlowPushFrame.sendTrans(deviceConnectionMsg, orderStatus.getTransOrder(), orderStatus.getPileCode(), (byte) 1, orderStatus.getCreateTime(), System.currentTimeMillis() + 3 * 60 * 1000, model, orderStatus.getCard(), compute, TransConstant.OTHER_STOP);
+//                    orderStatus.setOriginalText(e);
+//                    orderStatus.setEndTime(1);
+//                    orderStatus.setNowOrderStatus(StatusConstant.NOW_ORDER_STATUS_CHARGING_ENDING);
+//                    orderStatus.setReasonStopCharging(TransConstant.OTHER_STOP);
+//                    orderStatusService.updateById(orderStatus);
+//
+//                } catch (Exception e) {
+//                    e.printStackTrace();
+//                }
+//            }
+//            });
+//        }
+
+        log.info("======transaction push task ending=====");
+    }
+
+
+
+}