liuf 1 год назад
Родитель
Сommit
0cab5f7f11

+ 240 - 326
src/main/java/com/tmzn/devicelinkykc/message/DeviceMsgHandle.java

@@ -3,6 +3,7 @@ package com.tmzn.devicelinkykc.message;
 import com.alibaba.fastjson2.JSONArray;
 import com.alibaba.fastjson2.JSONObject;
 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;
@@ -23,6 +24,7 @@ import com.tmzn.devicelinkykc.socket.DeviceConnectionMsg;
 import com.tmzn.devicelinkykc.socket.SocketHandle;
 import com.tmzn.devicelinkykc.transdata.constant.NormalChargeConstant;
 import com.tmzn.devicelinkykc.transdata.entity.DeviceParam;
+import org.apache.logging.log4j.util.Strings;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.springframework.beans.BeanUtils;
@@ -77,12 +79,12 @@ public class DeviceMsgHandle {
     private static final Long gap = 1000 * 30L;
     private static final BigDecimal zero = new BigDecimal("0");
 
-    public void deviceMsg(String msg)  throws Exception{
+    public void deviceMsg(String msg) throws Exception {
         //必须过滤调非云快充设备
         //logger.info("redis中msg>>>" + msg);
         msg = msg.substring(1, msg.length() - 1);
         msg = msg.replace("\\", "");
-        checkActive(msg);
+        // checkActive(msg);
 
         JSONObject jsonObject = null;
         try {
@@ -94,31 +96,46 @@ public class DeviceMsgHandle {
             return;
             //e.printStackTrace();
         }
-        if (!redisCache.hasKey(RedisConstant.DEVICE_INFO)) {
+        String imei = jsonObject.getString("imei");
+        if (Strings.isEmpty(imei)) {
             return;
         }
-        Set<String> setImei = redisCache.getCacheObject(RedisConstant.DEVICE_INFO);
-        String imei = jsonObject.getString("imei");
-        if (!(imei != null && setImei.contains(imei))) {
+        String pileCode = "";
+        try {
+            pileCode = redisCache.getCacheMapValue(RedisConstant.DEVICE_IMEI_PILE_MAP, imei);
+            if (Strings.isEmpty(pileCode)) {
+                return;
+            }
+        } catch (Exception e) {
             return;
         }
-        logger.info("msg>>>" + msg);
+        logger.info("{},msg>>>" + msg, imei);
         //设备状态更新,true:没有type不是设备上送类型不往云快充处理 false:需要根据设备消息类型往下处理是不是需要上报云快充
-        try{
-            handleDeviceMsg(jsonObject);
-        }catch (Exception e){
-            logger.error("处理消息失败{},{}",imei,e.getMessage());
+        try {
+            handleDeviceMsg(jsonObject, pileCode);
+        } catch (Exception e) {
+            logger.error("处理消息失败{},{}", imei, e.getMessage());
             e.printStackTrace();
         }
-       
+
     }
 
     public void testMsg(String msg) throws Exception {
         logger.info("testmsg>>>" + msg);
         JSONObject jsonObject = null;
         jsonObject = JSONObject.parseObject(msg);
+        String imei = jsonObject.getString("imei");
+        try {
+            String pileCode = redisCache.getCacheMapValue(RedisConstant.DEVICE_IMEI_PILE_MAP, imei);
+            if (Strings.isEmpty(pileCode)) {
+                logger.info("非云快充设备");
+                return;
+            }
+            handleDeviceMsg(jsonObject, pileCode);
+        } catch (Exception e) {
+            return;
+        }
         //设备状态更新,true:没有type不是设备上送类型不往云快充处理 false:需要根据设备消息类型往下处理是不是需要上报云快充
-        handleDeviceMsg(jsonObject);
     }
 
     private void checkActive(String s) {
@@ -137,7 +154,7 @@ public class DeviceMsgHandle {
 
     //处理离线消息
     //查找所有端口状态置为下线 并推送状态给云快充
-    private void handleOffline(String imei){
+    private void handleOffline(String imei) {
         QueryWrapper<DeviceStatus> deviceStatusQueryWrapper = new QueryWrapper<>();
         deviceStatusQueryWrapper.eq("device_imei", imei);
         List<DeviceStatus> list = deviceStatusService.list(deviceStatusQueryWrapper);
@@ -164,24 +181,24 @@ public class DeviceMsgHandle {
         }
     }
 
-    private void checkAutoStop(int power, String imei, int portId){
+    private void checkNoPowerAutoStop(int power, String imei, int portId) {
 
-        try{
-            String hkey = imei+"_"+portId;
+        try {
+            String hkey = imei + "_" + portId;
             Integer lastPower0Times = 0;
-            if(power>0){
+            if (power > 0) {
 
-            }else{
-                lastPower0Times = redisCache.getCacheMapValue(RedisConstant.POWER_ZERO_TIMES,hkey);
-                if(lastPower0Times == null){
+            } else {
+                lastPower0Times = redisCache.getCacheMapValue(RedisConstant.POWER_ZERO_TIMES, hkey);
+                if (lastPower0Times == null) {
                     lastPower0Times = 0;
                 }
-                lastPower0Times = lastPower0Times+1;
+                lastPower0Times = lastPower0Times + 1;
             }
 
-            redisCache.setCacheMapValue(RedisConstant.POWER_ZERO_TIMES,hkey,lastPower0Times);
+            redisCache.setCacheMapValue(RedisConstant.POWER_ZERO_TIMES, hkey, lastPower0Times);
 
-            if(lastPower0Times<5){
+            if (lastPower0Times < 5) {
                 return;
             }
 
@@ -189,30 +206,60 @@ public class DeviceMsgHandle {
             QueryWrapper<OrderStatus> orderStatusQueryWrapper = new QueryWrapper<>();
             orderStatusQueryWrapper.eq("device_imei", imei).eq("guns_code", portId).orderByDesc("create_time").last("limit 1");
             OrderStatus one = orderStatusService.getOne(orderStatusQueryWrapper);
-            if(one.getNowOrderStatus()!=StatusConstant.NOW_ORDER_STATUS_CHARGING){
+            if (one.getNowOrderStatus() != StatusConstant.NOW_ORDER_STATUS_CHARGING) {
                 return;
             }
-            if((System.currentTimeMillis()- one.getCreateTime())<120*1000){
+            if ((System.currentTimeMillis() - one.getCreateTime()) < 120 * 1000) {
                 return;
             }
 
             //连续3次功率0 就要停止充电
             RpcResult rpcResult = deviceControlerService.stopCharge(imei, imei, (int) portId);
-            logger.info("{}-{}触发无功率自停{}",imei,portId,lastPower0Times);
-        }catch (Exception e){
-            logger.error("无功率检测异常{}",e.getMessage());
+            logger.info("{}-{}触发无功率自停{}", imei, portId, lastPower0Times);
+        } catch (Exception e) {
+            logger.error("无功率检测异常{}", e.getMessage());
             e.printStackTrace();
         }
 
 
     }
 
+
+    private void checkConnection(String pileCode, String imei) throws IOException {
+        boolean needLogin = false;
+        if (!socketHandle.existDeviceConnection(pileCode)) {
+            needLogin = true;
+        } else {
+            DeviceConnectionMsg deviceConnection = socketHandle.getDeviceConnection(pileCode);
+            if (!deviceConnection.getSocket().isConnected()) {
+                socketHandle.removeDeviceConnection(pileCode);
+                needLogin = true;
+            }
+        }
+
+        if (!needLogin) {
+            return;
+        }
+        logger.info("桩上线{}", imei);
+        QueryWrapper<Device> deviceQueryWrapper = new QueryWrapper<>();
+        deviceQueryWrapper.eq("pile_code", pileCode).eq("disabled", DeviceOnlineStatus.NORMAL);
+        Device device = deviceService.getOne(deviceQueryWrapper);
+        if (device == null) {
+            logger.info("{}已禁用{}", imei, pileCode);
+            return;
+        }
+        socketHandle.addDeviceConnection(device.getIp(), device.getPort(), device.getPileCode(), device.getDeviceImei(), device.getDeviceSn(), device.getCommProtocolVer());
+        loginFrame.loginMsgSend(socketHandle.getDeviceConnection(device.getPileCode()), device);
+
+    }
+
     /**
      * 设备状态按照设备上报和设备心跳上送时间校验修改,这里就必须更新状态的修改时间;通过定时任务判断在线设备接收心跳包超10分钟改为离线
      *
      * @param jsonObject
      */
-    private void handleDeviceMsg(JSONObject jsonObject) throws Exception {
+    private void handleDeviceMsg(JSONObject jsonObject, String pileCode) throws Exception {
+
         String imei = jsonObject.getString("imei");
         Integer cmd = jsonObject.getInteger("cmd");
         if (!jsonObject.containsKey("type")) {
@@ -225,15 +272,21 @@ public class DeviceMsgHandle {
             return;
         }
 
+        try {
+            checkConnection(pileCode, imei);
+        } catch (Exception e) {
+            logger.info("桩{}连接异常", imei);
+        }
+
         Integer type = jsonObject.getInteger("type");
 
-        if(!NormalChargeConstant.CMD_SET_MAINBOARD.equals(cmd)){
+        if (!NormalChargeConstant.CMD_SET_MAINBOARD.equals(cmd)) {
 //            logger.error("不支持的命令");
             return;
         }
 
         //端口状态
-        if(NormalChargeConstant.KEY_PORT_DETAIL.equals(type)){
+        if (NormalChargeConstant.KEY_PORT_DETAIL.equals(type)) {
             handle103(jsonObject, imei, type);
             return;
         }
@@ -242,6 +295,8 @@ public class DeviceMsgHandle {
             //116端口详情也会变化
             JSONArray data = jsonObject.getJSONArray("data");
             checkPort(data.getInteger(4), data.getInteger(3), imei, type);
+
+
             return;
         }
 
@@ -267,12 +322,12 @@ public class DeviceMsgHandle {
         // 1.设备消息cmd:75960设备上报消息是的命令,只要设备报的不是离线当做设备在线
         // 2.设备上报指令后根据type类型来分类处理消息包括:设备设为在线 是否插枪状态 枪状态(端口状态)
         if (NormalChargeConstant.EMERGENCY_STOP_CHARGING.equals(type)) {
-            handleEmergency(jsonObject,imei);
+            handleEmergency(jsonObject, imei);
             return;
         }
 
-         if (NormalChargeConstant.REPORT_PORT_STATUS.equals(type)) {
-                //114设备主动上报
+        if (NormalChargeConstant.REPORT_PORT_STATUS.equals(type)) {
+            //114设备主动上报
             JSONArray data = jsonObject.getJSONArray("data");
             Integer integer = data.getInteger(2);
             if (integer > 5) {
@@ -283,7 +338,7 @@ public class DeviceMsgHandle {
                 checkPort(data.getInteger(7), 1, imei, type);
             }
 
-         }
+        }
     }
 
 
@@ -337,7 +392,7 @@ public class DeviceMsgHandle {
     }
 
     //启动充电
-    private void handle104(JSONObject jsonObject, String imei){
+    private void handle104(JSONObject jsonObject, String imei) {
         //开启充电设备上报结果
         JSONObject data = jsonObject.getJSONObject("real_data");
         Integer result = data.getInteger("result");
@@ -353,13 +408,13 @@ public class DeviceMsgHandle {
         if (result == 0x01) {
             //启充成功上报充电开启成功
             charngingPushFrame.startStatus(deviceConnection, bytes, port, result, 0x00);
-            logger.info("上报启动充电成功{},{}",statusServiceOne.getId(),statusServiceOne.getPileCode());
+            logger.info("上报启动充电成功{},{}", statusServiceOne.getId(), statusServiceOne.getPileCode());
         } else {
             //启机不成功,根据设备状态判断,并且要结束充电并上报订单
             String cacheKey;
-            if(port==1){
+            if (port == 1) {
                 cacheKey = RedisConstant.ONLINE_DEVICE_ONE;
-            }else{
+            } else {
                 cacheKey = RedisConstant.ONLINE_DEVICE_TWO;
             }
             if (redisCache.hasKey(cacheKey)) {
@@ -372,7 +427,7 @@ public class DeviceMsgHandle {
                     reson = 0x02;
                 }
                 charngingPushFrame.startStatus(deviceConnection, bytes, port, result, reson);
-                logger.info("上报启动充电失败{},{}",statusServiceOne.getId(),statusServiceOne.getPileCode());
+                logger.info("上报启动充电失败{},{}", statusServiceOne.getId(), statusServiceOne.getPileCode());
             }
         }
         new Thread(() -> {
@@ -382,16 +437,17 @@ public class DeviceMsgHandle {
                 dataParam.setDeviceId(imei);
                 dataParam.setCcid(imei);
                 deviceControlerService.sendPortDetailCmd(dataParam);
-                logger.info(statusServiceOne.getPileCode() + ":延迟主动下发103消息"+imei);
+                logger.info(statusServiceOne.getPileCode() + ":延迟主动下发103消息" + imei);
             } catch (Exception e) {
-                logger.info(statusServiceOne.getPileCode() + ":延迟主动下发103消息异常" + e.getMessage()+imei);
+                logger.info(statusServiceOne.getPileCode() + ":延迟主动下发103消息异常" + e.getMessage() + imei);
             }
         }).start();
     }
 
+
     //单个端口状态
     private void handle101(JSONObject jsonObject, String imei, int type) {
-        try{
+        try {
             //状态查询101
             JSONObject data = jsonObject.getJSONObject("real_data");
             Integer port_first_status = data.getInteger("port_first_status");
@@ -402,8 +458,8 @@ public class DeviceMsgHandle {
             if (port_second_status != null) {
                 checkPort(port_second_status, 2, imei, type);
             }
-        }catch (Exception e){
-            logger.info("处理101失败{}",imei);
+        } catch (Exception e) {
+            logger.info("处理101失败{}", imei);
         }
 
     }
@@ -425,60 +481,63 @@ public class DeviceMsgHandle {
 
         //判断连续无功率就自动停止
 
-        redisCache.setCacheObject(RedisConstant.DEVICE_PORT_STATUS + imei, data, 15, TimeUnit.MINUTES);
+        redisCache.setCacheObject(RedisConstant.DEVICE_PORT_STATUS + imei, data, 30, TimeUnit.MINUTES);
         if (port_first_status != null) {
-            if(port_first_status==PortStatusConstant.CHARGING){
-                checkAutoStop(power,imei,1);
-            }
+
             checkPort(port_first_status, 1, imei, type);
+
+            if (port_first_status == PortStatusConstant.CHARGING) {
+                checkNoPowerAutoStop(power, imei, 1);
+            }
         }
         if (port_second_status != null) {
-            if(port_second_status==PortStatusConstant.CHARGING){
-                checkAutoStop(power,imei,2);
-            }
             checkPort(port_second_status, 2, imei, type);
+
+            if (port_second_status == PortStatusConstant.CHARGING) {
+                checkNoPowerAutoStop(power, imei, 2);
+            }
         }
 
     }
 
 
     //处理停止充电情况
-    private void handle113(JSONObject jsonObject, String imei){
+    private void handle113(JSONObject jsonObject, String imei) {
         //停止充电通知触发情况:1.急停,收到停充时主动要去发停充,所以这里不能处理急停的交易订单;2.手动停充,正常的远程停止指令
         // 1.设备已经在接收到云快充指令的时候进行了停充操作,2.结算订单,上报云快充停止回复
         try {
             JSONObject data = jsonObject.getJSONObject("real_data");
-            logger.info("{}接收到设备上送113停止充电msg>>" + jsonObject.toString(),imei);
+            logger.info("{}接收到设备上送113停止充电msg>>" + jsonObject.toString(), imei);
             int port = data.getIntValue("port");
             byte reson = data.getByte("reason");
             QueryWrapper<OrderStatus> orderStatusQueryWrapper = new QueryWrapper<>();
             orderStatusQueryWrapper.eq("device_imei", imei).eq("guns_code", port).orderByDesc("create_time").last("limit 1");
             OrderStatus statusServiceOne = orderStatusService.getOne(orderStatusQueryWrapper);
-            if(statusServiceOne==null){
-                logger.info("没有待处理订单{}",imei);
+            if (statusServiceOne == null) {
+                logger.info("没有待处理订单{}", imei);
                 return;
             }
 
-            if(statusServiceOne.getTransactionOrderReplyStatus() == StatusConstant.TRANSACTION_ORDER_REPLY_STATUS_SUCC){
-                logger.info("订单状态已上报成功{},id:{}",imei,statusServiceOne.getId());
+            if (statusServiceOne.getTransactionOrderReplyStatus() == StatusConstant.TRANSACTION_ORDER_REPLY_STATUS_SUCC) {
+                logger.info("订单状态已上报成功{},id:{}", imei, statusServiceOne.getId());
                 return;
             }
 
             //如果是用户手动停止充电 则不处理状态
-            if(statusServiceOne.getReasonStopCharging()==TransConstant.APP_REMOTE_STOP){
+            if (statusServiceOne.getReasonStopCharging() == TransConstant.APP_REMOTE_STOP) {
                 logger.info(statusServiceOne.getPileCode() + ":云快充>>>>>>远程停充>>>>");
-            }else{
+            } else {
                 //不处理急停
-                if(reson == 0x01){
+                if (reson == 0x01) {
                     logger.info(statusServiceOne.getPileCode() + ":用户主动停充>>>>>>停充>>>>");
                     statusServiceOne.setReasonStopCharging(TransConstant.APP_REMOTE_STOP);
-                }else if(reson==0x00){
+                } else if (reson == 0x00) {
                     logger.info(statusServiceOne.getPileCode() + ":设备余额不足>>>>>>停充>>>>");
                     statusServiceOne.setReasonStopCharging(TransConstant.INSUFFICIENT_BALANCE_EXCEPTION_STOP);
-                }else if(reson == 0x03){
+                } else if (reson == 0x03) {
                     logger.info(statusServiceOne.getPileCode() + ":设备充电充满>>>>>>停充>>>>");
                     statusServiceOne.setReasonStopCharging(TransConstant.SOC_FULL_OF_STOP);
-                }else{
+                } else {
                     logger.info(statusServiceOne.getPileCode() + ":设备充电停止>>>>其他>>>");
                     statusServiceOne.setReasonStopCharging(TransConstant.OTHER_STOP);
                 }
@@ -489,10 +548,10 @@ public class DeviceMsgHandle {
             statusServiceOne.setNowOrderStatus(StatusConstant.NOW_ORDER_STATUS_CHARGING_ENDING);
             DeviceConnectionMsg deviceConnection = socketHandle.getDeviceConnection(statusServiceOne.getPileCode());
 
-            if(deviceConnection==null || deviceConnection.getLoginStatus()!=1){
+            if (deviceConnection == null || deviceConnection.getLoginStatus() != 1) {
                 //未上报
                 statusServiceOne.setTransactionOrderReportingActionStatus(StatusConstant.TRANSACTION_ORDER_REPORTING_ACTION_STATUS_NO);
-                logger.info("socket 未连接 需要重新上报异常上报{}",statusServiceOne.getPileCode());
+                logger.info("socket 未连接 需要重新上报异常上报{}", statusServiceOne.getPileCode());
                 orderStatusService.updateById(statusServiceOne);
                 return;
             }
@@ -506,29 +565,31 @@ public class DeviceMsgHandle {
             logger.info(statusServiceOne.getPileCode() + "计算电费" + DataConversion.bytesToHexString(statusServiceOne.getTransOrder()));
             encrypt = transactionFlowPushFrame.sendTrans(deviceConnection, statusServiceOne.getTransOrder(), statusServiceOne.getPileCode(), statusServiceOne.getGunsCode(), statusServiceOne.getCreateTime(), statusServiceOne.getEndTime(), model, statusServiceOne.getCard(), map, statusServiceOne.getReasonStopCharging());
 
-            if(encrypt==null || encrypt.length<=0){
+            if (encrypt == null || encrypt.length <= 0) {
+                logger.info("订单上送消息异常 需要重新上报{}", statusServiceOne.getPileCode());
+                orderStatusService.updateById(statusServiceOne);
                 return;
-            }else{
+            } else {
+                logger.info("订单上送成功{}", statusServiceOne.getPileCode());
                 statusServiceOne.setTransactionOrderReportingActionStatus(StatusConstant.TRANSACTION_ORDER_REPORTING_ACTION_STATUS_OK);
                 statusServiceOne.setOriginalText(encrypt);
             }
-            boolean res =charngingPushFrame.endStatus(deviceConnection, port, 0x01, 0x00);
-            if(res){
+            boolean res = charngingPushFrame.endStatus(deviceConnection, port, 0x01, 0x00);
+            if (res) {
                 //更新远程停止充电
-                logger.info("停止充电回复成功{}",imei);
+                logger.info("停止充电回复成功{}", imei);
                 statusServiceOne.setStopChargingReply(StatusConstant.STOP_CHARGING_REPLY_OK);
-            }else{
-                logger.info("停止充电回复失败{}",imei);
+            } else {
+                logger.info("停止充电回复失败{}", imei);
             }
             orderStatusService.updateById(statusServiceOne);
-
-            //获取一设备状态
-            DeviceParam dataParam = new DeviceParam();
-            dataParam.setDeviceId(imei);
-            dataParam.setCcid(imei);
-            deviceControlerService.sendPortDetailCmd(dataParam);
+//            //获取一设备状态
+//            DeviceParam dataParam = new DeviceParam();
+//            dataParam.setDeviceId(imei);
+//            dataParam.setCcid(imei);
+//            deviceControlerService.sendPortDetailCmd(dataParam);
         } catch (Exception e) {
-            logger.info("{}处理113消息异常{}",imei,e.getMessage());
+            logger.info("{}处理113消息异常{}", imei, e.getMessage());
 //            DeviceConnectionMsg deviceConnection = socketHandle.getDeviceConnection(imei);
 //            realTimeStatusPushFrame.deviceStatusPush(deviceConnection, FrameDataSplicing.transactionNum(deviceConnection.getDeviceId(), deviceConnection.getMessageCount()), deviceConnection.getDeviceId(), (byte) 1, StatusConstant.FREE, StatusConstant.CHARGING_INIT_STATUS_OK, 0, 0, zero, zero, 0);
             e.printStackTrace();
@@ -542,37 +603,38 @@ public class DeviceMsgHandle {
      * @param port
      * @param imei
      */
-    private void checkPort(Integer portStatus, int port, String imei, int type)  throws Exception{
+    private void checkPort(Integer portStatus, int port, String imei, int type) throws Exception {
+
         if (portStatus.equals(PortStatusConstant.FREE)) {
-            if (type == NormalChargeConstant.PORT_STATUS) {
-                //这里116状态是1可能是直接拔枪时的操作,直接拔枪时结束充电消息会直接上送,这里只记录停止原因不做交易订单上送
-                handleStatus7(imei, port, (byte) PortStatusConstant.FREE, StatusConstant.INSERT_GUNS_NO, type);
-            }
             //处理特殊情况之后还要看枪状态变位上送
-            deviceOnline(imei, port, StatusConstant.FREE, StatusConstant.INSERT_GUNS_NO);
-        } else if (portStatus.equals(PortStatusConstant.CHARGING)) {
-            deviceOnline(imei, port, StatusConstant.CHARGING, StatusConstant.INSERT_GUNS_YES);
-        } else if (portStatus.equals(PortStatusConstant.DISABLED) || portStatus.equals(PortStatusConstant.FAULT)) {
+            deviceOnline(portStatus, imei, port, StatusConstant.FREE, StatusConstant.INSERT_GUNS_NO);
+            return;
+        }
+
+        if (portStatus.equals(PortStatusConstant.CHARGING)) {
+            deviceOnline(portStatus, imei, port, StatusConstant.CHARGING, StatusConstant.INSERT_GUNS_YES);
+            return;
+        }
+
+        if (portStatus.equals(PortStatusConstant.DISABLED) || portStatus.equals(PortStatusConstant.FAULT)) {
             //禁用或故障上报云快充为故障信息
-            deviceOnline(imei, port, StatusConstant.FAULT, StatusConstant.NO);
-        } else if (portStatus.equals(PortStatusConstant.INSERT_GUN) || portStatus.equals(PortStatusConstant.BOOKED)) {
-            deviceOnline(imei, port, StatusConstant.FREE, StatusConstant.INSERT_GUNS_YES);
-        } else if (portStatus.equals(PortStatusConstant.CHARGING_END)) {
-            //充电完成状态是7,先处理一波
-            logger.info("charnging Portstatus>>" + portStatus + ";type:" + type);
-
-            if (handleStatus7(imei, port, (byte) PortStatusConstant.CHARGING_END, StatusConstant.INSERT_GUNS_YES, type)){
-                //状态是7时,处理过订单返回才是true
-                return;
-            }
+            deviceOnline(portStatus, imei, port, StatusConstant.FAULT, StatusConstant.NO);
+            return;
+        }
 
-            logger.info("charnging Port>>b>>>>");
-            //再去保证设备状态变化处理7为空闲插枪
-            deviceOnline(imei, port, (byte) StatusConstant.FREE, StatusConstant.INSERT_GUNS_NO);
+        if (portStatus.equals(PortStatusConstant.INSERT_GUN) || portStatus.equals(PortStatusConstant.BOOKED)) {
+            deviceOnline(portStatus, imei, port, StatusConstant.FREE, StatusConstant.INSERT_GUNS_YES);
+            return;
+        }
 
-        } else if (portStatus.equals(PortStatusConstant.EMERGENCY_STOP)) {
+        if (portStatus.equals(PortStatusConstant.CHARGING_END)) {
+            deviceOnline(portStatus, imei, port, (byte) StatusConstant.FREE, StatusConstant.INSERT_GUNS_NO);
+            return;
+        }
+
+        if (portStatus.equals(PortStatusConstant.EMERGENCY_STOP)) {
             //急停中按要求需要上报空闲状态;急停保存原始状态
-            deviceOnline(imei, port, (byte) PortStatusConstant.EMERGENCY_STOP, StatusConstant.INSERT_GUNS_NO);
+            deviceOnline(portStatus, imei, port, (byte) PortStatusConstant.EMERGENCY_STOP, StatusConstant.INSERT_GUNS_NO);
         }
     }
 
@@ -585,7 +647,7 @@ public class DeviceMsgHandle {
      * @param insertGunStatus
      * @param type            指令类型
      */
-    private boolean handleStatus7(String imei, int port, byte gunsStatus, byte insertGunStatus, int type)  throws Exception{
+    private boolean handleStatus7(String imei, int port, byte gunsStatus, byte insertGunStatus, int type) throws Exception {
         logger.info("处理7状态>>>>>>");
         QueryWrapper<BillingModel> billingModelQueryWrapper = new QueryWrapper<>();
         billingModelQueryWrapper.eq("device_imei", imei);
@@ -612,28 +674,10 @@ public class DeviceMsgHandle {
             orderStatusQueryWrapper.eq("device_imei", imei).eq("guns_code", port).orderByDesc("create_time").last("limit 1");
             OrderStatus one = orderStatusService.getOne(orderStatusQueryWrapper);
 
-            //可能会触发不了上线
-            if (!socketHandle.existDeviceConnection(one.getPileCode())) {
-                try {
-                    logger.info("{}重新登录>>>>>>",one.getPileCode());
-                    QueryWrapper<Device> deviceQueryWrapper = new QueryWrapper<>();
-                    deviceQueryWrapper.eq("pile_code", one.getPileCode()).eq("disabled", DeviceOnlineStatus.NORMAL);
-                    Device device = deviceService.getOne(deviceQueryWrapper);
-                    socketHandle.addDeviceConnection(device.getIp(),port,one.getPileCode(), one.getDeviceImei(), one.getDeviceSn(),device.getCommProtocolVer());
-                    loginFrame.loginMsgSend(socketHandle.getDeviceConnection(one.getPileCode()), device);
-                    //从新登录可能造成通讯上的问题,这里不在往下进行状态操作
-                } catch (IOException e) {
-                    logger.info("device:" + one.getDeviceSn() + " open socket Exception!!!");
-                    e.printStackTrace();
-                }
-            }else{
-                logger.info("{}设备在线>>>>>>",one.getPileCode());
-            }
-
 
             //7状态小于30秒内且订单原因不是远程停充
-            if((System.currentTimeMillis()- one.getCreateTime())<60*1000
-                    &&one.getReasonStopCharging()!=TransConstant.APP_REMOTE_STOP){
+            if ((System.currentTimeMillis() - one.getCreateTime()) < 60 * 1000
+                    && one.getReasonStopCharging() != TransConstant.APP_REMOTE_STOP) {
                 logger.info("启动状态还没变化--->当前7状态不处理");
 
 //                //发送一条103消息
@@ -651,8 +695,8 @@ public class DeviceMsgHandle {
             }
 
             //7状态:充电完成未拔枪会一直上报,只有当订单完成并回复解析订单成功,7状态当空闲状态上报
-            if (one.getTransactionOrderReportingActionStatus()==StatusConstant.TRANSACTION_ORDER_REPORTING_ACTION_STATUS_OK
-                    &&one.getTransactionOrderReplyStatus()==StatusConstant.TRANSACTION_ORDER_REPLY_STATUS_SUCC){
+            if (one.getTransactionOrderReportingActionStatus() == StatusConstant.TRANSACTION_ORDER_REPORTING_ACTION_STATUS_OK
+                    && one.getTransactionOrderReplyStatus() == StatusConstant.TRANSACTION_ORDER_REPLY_STATUS_SUCC) {
                 return false;
             }
 
@@ -678,7 +722,7 @@ public class DeviceMsgHandle {
             //Map<String, BigDecimal> start = transMoney.compute(port, model, one.getCreateTime(), one.getEndTime(),true);
             //byte[] encrypt = transactionFlowPushFrame.sendTrans(deviceConnection, one.getTransOrder(), one.getPileCode(), (byte) port, one.getCreateTime(), one.getEndTime(), model, one.getCard(), start, TransConstant.SOC_FULL_OF_STOP);
             //one.setOriginalText(encrypt);
-            if (one.getReasonStopCharging()==0) {
+            if (one.getReasonStopCharging() == 0) {
                 one.setReasonStopCharging(TransConstant.SOC_FULL_OF_STOP);//充满
             }
             one.setNowOrderStatus(StatusConstant.NOW_ORDER_STATUS_CHARGING_ENDING);//已结束
@@ -716,31 +760,24 @@ public class DeviceMsgHandle {
      * @param port       设备port(枪号)
      * @param gunsStatus 枪状态
      */
-    private void deviceOnline(String imei, int port, byte gunsStatus, byte insertGunStatus)  throws Exception{
+    private void deviceOnline(int portStatus, String imei, int port, byte gunsStatus, byte insertGunStatus) throws Exception {
+
         QueryWrapper<DeviceStatus> deviceStatusQueryWrapper = new QueryWrapper<>();
         deviceStatusQueryWrapper.eq("device_imei", imei).eq("gun_port", port);
         DeviceStatus statusServiceOne = deviceStatusService.getOne(deviceStatusQueryWrapper);
         DeviceStatus statusServiceOneTemp = new DeviceStatus();
+
+        //创建设备端口号
         if (statusServiceOne != null) {
             BeanUtils.copyProperties(statusServiceOne, statusServiceOneTemp);
         } else {
             //禁用的设备不再上线,只看正常设备
-
-//            if ("864606063793920".equals(imei)){
-//                QueryWrapper<Device> deviceQueryWrapper = new QueryWrapper<>();
-//                QueryWrapper<Device> device_imei = deviceQueryWrapper.eq("device_imei", imei);
-//                Device a = deviceService.getOne(device_imei);
-//                logger.info("a>>"+a.toString());
-//            }
-
             QueryWrapper<Device> deviceQueryWrapper = new QueryWrapper<>();
             QueryWrapper<Device> device_imei = deviceQueryWrapper.eq("device_imei", imei).eq("disabled", DeviceOnlineStatus.NORMAL);
             Device one = deviceService.getOne(device_imei);
             if (one == null) {
                 logger.info("当前设备imei:" + imei + ",没有绑定ykc桩编码!!!!!!!!!!!!!!!!!!");
                 return;
-            }else{
-
             }
             statusServiceOne = new DeviceStatus();
             statusServiceOne.setDeviceImei(imei);
@@ -749,209 +786,86 @@ public class DeviceMsgHandle {
             statusServiceOne.setGunPort((byte) port);
             statusServiceOne.setCreateTime(System.currentTimeMillis());
             statusServiceOne.setUpdateTime(System.currentTimeMillis());
+            statusServiceOne.setOnlineStatus(DeviceOnlineStatus.ONLINE);
+            statusServiceOne.setUpdateTime(System.currentTimeMillis());
             deviceStatusService.saveOrUpdate(statusServiceOne);
         }
-        QueryWrapper<Device> deviceQueryWrapper = new QueryWrapper<>();
-        deviceQueryWrapper.eq("pile_code", statusServiceOne.getPileCode()).eq("disabled", DeviceOnlineStatus.NORMAL);
-        Device device = deviceService.getOne(deviceQueryWrapper);
-
-        if (!socketHandle.existDeviceConnection(statusServiceOne.getPileCode())) {
-            try {
-
-                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) {
-                logger.info("device:" + statusServiceOne.getDeviceSn() + " open socket Exception!!!");
-                e.printStackTrace();
-            }
-        } else {
-            //存在连接校验socket连接是否正常
-            DeviceConnectionMsg deviceConnection = socketHandle.getDeviceConnection(statusServiceOne.getPileCode());
-            if (!deviceConnection.getSocket().isConnected()) {
-                //不正常,移除再连接
-                socketHandle.removeDeviceConnection(statusServiceOne.getPileCode());
-                try {
-                    socketHandle.addDeviceConnection(device.getIp(),device.getPort(),statusServiceOne.getPileCode(), statusServiceOne.getDeviceImei(), statusServiceOne.getDeviceSn(),device.getCommProtocolVer());
-                } catch (IOException e) {
-                    e.printStackTrace();
-                }
-            }
-        }
-//        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(),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());
-//                }
-//            }
-//        }
+        logger.info("{}设备状态持久化>>>" + statusServiceOne.toString(), imei);
 
         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);
 
-        //2.状态变位上送,状态变化需要上送一个实时状态帧;前提是已经在云快充登录成功
-        if (statusServiceOneTemp.getGunStatus() != gunsStatus || statusServiceOneTemp.getInsertGunStatus() != insertGunStatus) {
-            if (!socketHandle.existDeviceConnection(statusServiceOne.getPileCode())) {
-                try {
-                    socketHandle.addDeviceConnection(device.getIp(),device.getPort(),statusServiceOne.getPileCode(), statusServiceOne.getDeviceImei(), statusServiceOne.getDeviceSn(),device.getCommProtocolVer());
-                } catch (IOException e) {
-                    e.printStackTrace();
-                }
-            }
-            DeviceConnectionMsg deviceConnectionMsg = socketHandle.getDeviceConnection(statusServiceOne.getPileCode());
-            if (deviceConnectionMsg.getLoginStatus() == 1) { //设备登录成功才会有其他的操作,登录没成功无法变位上送
-                QueryWrapper<OrderStatus> orderStatusQueryWrapper = new QueryWrapper<>();
-                orderStatusQueryWrapper.eq("device_imei", imei).eq("guns_code", port).orderByDesc("create_time").last("limit 1");
-                OrderStatus one = orderStatusService.getOne(orderStatusQueryWrapper);
-
-                if (one==null){
-                    logger.info("orderStatus is null ,status ↑↑↑↑");
-                    realTimeStatusPushFrame.deviceStatusPush(deviceConnectionMsg, FrameDataSplicing.transactionNum(null,0), statusServiceOne.getPileCode(), (byte) port, gunsStatus, insertGunStatus, 0, 0, zero, zero, 0);
-                    return;
-                }
-                //判断区分是因为充电中流水和待机状态流水号不同
-                if (gunsStatus == StatusConstant.CHARGING) {
-                    //这里的变位是变为充电中需要注意交易流水号的变更问题,流水号在云快充启充指令时获得并已经持久化到数据库中
-                    byte[] transactionNum = one.getTransOrder();
-
-                    if (one.getChargingInitStatus() == StatusConstant.CHARGING_INIT_STATUS_NO) {
-                        logger.info("{}变位为充电中且当前订单还没首次上报过初始状态:" + DataConversion.bytesToHexString(transactionNum),imei);
-                        realTimeStatusPushFrame.deviceStatusPush(deviceConnectionMsg, transactionNum, statusServiceOneTemp.getPileCode(), (byte) port, gunsStatus, insertGunStatus, 0, 0, zero, zero, 0);
-                    }
-                    //这里上报开始充电初始化状态并记录已经上报首次状态
-                    one.setNowOrderStatus(StatusConstant.NOW_ORDER_STATUS_CHARGING);
-                    one.setChargingInitStatus(StatusConstant.CHARGING_INIT_STATUS_OK);
-                    orderStatusService.updateById(one);
-                } else {
-                    logger.info(statusServiceOne.getPileCode() + ":除了充电变位的其他状态>>>>>>" + gunsStatus);
-                    //这里的状态变位是除了充电中以外的情况
-                    byte[] transactionNum = FrameDataSplicing.transactionNum(statusServiceOneTemp.getPileCode(), deviceConnectionMsg.getMessageCount());
-                    if (gunsStatus == PortStatusConstant.EMERGENCY_STOP) {
-                        //  急停后库里记录的是急停状态,但是上报的时候需上报云快充一次故障状态;所以临时为故障上报
-                        gunsStatus = StatusConstant.FAULT;
-                        logger.info(statusServiceOne.getPileCode() + ":状态变位为急停时需要一次故障状态:" + gunsStatus);
-                    } else if (gunsStatus == PortStatusConstant.CHARGING_END&&one.getReasonStopCharging()==0) {
-                        //状态是7充电完成
-                        gunsStatus = StatusConstant.FREE;
-                    }else if (one.getReasonStopCharging()==0){
-                        one.setReasonStopCharging(TransConstant.MANUAL_STOP);
-                    }
-                    //状态未知按手动停充
+        //为啥要过期20分
+        redisCache.expire(port == 1 ? RedisConstant.ONLINE_DEVICE_ONE : RedisConstant.ONLINE_DEVICE_TWO, 60 * 1001 * 20, TimeUnit.MILLISECONDS);
 
-//                    如果断网后在断网时进行的停充,那么现在情况->1.设备状态离线2.订单记录还是 : 充电中0,没有停止指令上送0,交易记录也没有上送0,停止原因也是0,结束时间是null
-                    //TODO:停止充电时间怎么算:目前考虑的是检测到离线的时间就说device中的updateTime来当结束充电时间
+        DeviceConnectionMsg deviceConnectionMsg = socketHandle.getDeviceConnection(statusServiceOne.getPileCode());
+        if (deviceConnectionMsg == null || deviceConnectionMsg.getLoginStatus() != Constant.DEVICE_LOGIN_STATUS) {
+            logger.info("设备{}未登录成功不上报", statusServiceOne.getDeviceImei());
+            return;
+        }
 
-                    String transOrder = "";
-                    if (redisCache.hasKey(RedisConstant.NO_INSERT_GUN_YKC + statusServiceOneTemp.getPileCode())) {
-                        //未插枪启充的操作会保存订单,但是订单号不是因为断网中停充造成的订单结束原因是0,所以redis有当前设备的订单值,就不是结束充电
-                        transOrder = redisCache.getCacheObject(RedisConstant.NO_INSERT_GUN_YKC + statusServiceOneTemp.getPileCode());
-                    }
-                    //急停状态下不管是断网时急停还是直接按的急停都按急停处理,不按手动处理;
-                    //TODO:急停情况已经上报交易,其他从充电变成非已充电全部上报交易记录
-                    //原枪状态是充电中,现在不是根据状态上报
-                    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);
-                        BillingModel model = billingModelService.getOne(billingModelQueryWrapper);
-
-                        byte[] encrypt = new byte[0];
-                        Long endTime=System.currentTimeMillis();
-                        if (port == 1) {
-                            logger.info("订单状态orderStatus>>"+one.toString());
-                            Map<String, BigDecimal> map = transMoney.compute(1, model, one.getCreateTime(), endTime + 3 * 60 * 1000);
-                            //logger.info("断网中停充>>>上报交易记录>>>");
-                            encrypt = transactionFlowPushFrame.sendTrans(deviceConnectionMsg, one.getTransOrder(), statusServiceOne.getPileCode(), (byte) 1, one.getCreateTime(), statusServiceOneTemp.getUpdateTime() + 3 * 60 * 1000, model, one.getCard(), map, one.getReasonStopCharging());
-                        } else if (port == 2) {
-
-                            Map<String, BigDecimal> map = transMoney.compute(2, model, one.getCreateTime(), endTime + 3 * 60 * 1000);
-                            BigDecimal elec = map.get("elec");
-                            BigDecimal money = map.get("money");
-                            encrypt = transactionFlowPushFrame.sendTrans(deviceConnectionMsg, one.getTransOrder(), statusServiceOne.getPileCode(), (byte) 2, one.getCreateTime(), statusServiceOneTemp.getUpdateTime() + 3 * 60 * 1000, model, one.getCard(), map, statusServiceOneTemp.getFlage() == 2 ? TransConstant.CHARGING_STATION_POWER_OUTAGE : TransConstant.EMERGENCY_STOP_EXCEPTION_STOP);
-                        }
-                    /*    if (port == 1) {
-                            Map<String, BigDecimal> map = transMoney.compute(1, model, one.getCreateTime(), endTime + 3 * 60 * 1000, true);
-                            //logger.info("断网中停充>>>上报交易记录>>>");
-                            encrypt = transactionFlowPushFrame.sendTrans(deviceConnectionMsg, one.getTransOrder(), statusServiceOne.getPileCode(), (byte) 1, one.getCreateTime(), statusServiceOneTemp.getUpdateTime() + 3 * 60 * 1000, model, one.getCard(), map, statusServiceOneTemp.getFlage() == 2 ? TransConstant.CHARGING_STATION_POWER_OUTAGE : TransConstant.EMERGENCY_STOP_EXCEPTION_STOP);
-                        } else if (port == 2) {
-
-                            Map<String, BigDecimal> map = transMoney.compute(2, model, one.getCreateTime(), endTime + 3 * 60 * 1000, true);
-                            BigDecimal elec = map.get("elec");
-                            BigDecimal money = map.get("money");
-                            encrypt = transactionFlowPushFrame.sendTrans(deviceConnectionMsg, one.getTransOrder(), statusServiceOne.getPileCode(), (byte) 2, one.getCreateTime(), statusServiceOneTemp.getUpdateTime() + 3 * 60 * 1000, model, one.getCard(), map, statusServiceOneTemp.getFlage() == 2 ? TransConstant.CHARGING_STATION_POWER_OUTAGE : TransConstant.EMERGENCY_STOP_EXCEPTION_STOP);
-                        }*/
-                        one.setEndTime(endTime+ 3 * 60 * 1000);
-                        //手动停充
-                        one.setOriginalText(encrypt);
-                        //one.setReasonStopCharging(one);
-                        one.setNowOrderStatus(StatusConstant.NOW_ORDER_STATUS_CHARGING_ENDING);
-                        one.setStopChargingReply(StatusConstant.STOP_CHARGING_REPLY_OK);//停止指令回复云快充(模拟的)
-                        one.setTransactionOrderReportingActionStatus(StatusConstant.TRANSACTION_ORDER_REPORTING_ACTION_STATUS_OK);
-                        orderStatusService.updateById(one);
-                    }
+        QueryWrapper<OrderStatus> orderStatusQueryWrapper = new QueryWrapper<>();
+        orderStatusQueryWrapper.eq("device_imei", imei).eq("guns_code", port).orderByDesc("create_time").last("limit 1");
+        OrderStatus one = orderStatusService.getOne(orderStatusQueryWrapper);
 
-            /*        if (statusServiceOne.getGunStatus() != PortStatusConstant.EMERGENCY_STOP && one != null && !(transOrder.equals(DataConversion.bytesToHexString(one.getTransOrder()))) && one.getReasonStopCharging() == 0 && one.getNowOrderStatus() == StatusConstant.NOW_ORDER_STATUS_CHARGING && one.getStopChargingReply() == StatusConstant.STOP_CHARGING_REPLY_NO && one.getTransactionOrderReportingActionStatus() == StatusConstant.TRANSACTION_ORDER_REPORTING_ACTION_STATUS_NO ) {
-                        //这里需要查下103因为断网中停充可能103没有上来
-                        DeviceParam deviceParam = new DeviceParam();
-                        deviceParam.setDeviceId(imei);
-                        deviceParam.setCcid(imei);
-                        deviceControlerService.sendPortDetailCmd(deviceParam);
-                        *//*QueryWrapper<BillingModel> billingModelQueryWrapper = new QueryWrapper<>();
-                        billingModelQueryWrapper.eq("device_imei", imei);
-                        BillingModel model = billingModelService.getOne(billingModelQueryWrapper);
-                        byte[] encrypt = new byte[0];
-                        if (port == 1) {
-                            Map<String, BigDecimal> map = transMoney.compute(1, model, one.getCreateTime(), statusServiceOneTemp.getUpdateTime() + 3 * 60 * 1000, true);
-                            //logger.info("断网中停充>>>上报交易记录>>>");
-                            encrypt = transactionFlowPushFrame.sendTrans(deviceConnectionMsg, one.getTransOrder(), statusServiceOne.getPileCode(), (byte) 1, one.getCreateTime(), statusServiceOneTemp.getUpdateTime() + 3 * 60 * 1000, model, one.getCard(), map, statusServiceOneTemp.getFlage() == 2 ? TransConstant.CHARGING_STATION_POWER_OUTAGE : TransConstant.EMERGENCY_STOP_EXCEPTION_STOP);
-                        } else if (port == 2) {
-
-                            Map<String, BigDecimal> map = transMoney.compute(2, model, one.getCreateTime(), statusServiceOneTemp.getUpdateTime() + 3 * 60 * 1000, true);
-                            BigDecimal elec = map.get("elec");
-                            BigDecimal money = map.get("money");
-                            encrypt = transactionFlowPushFrame.sendTrans(deviceConnectionMsg, one.getTransOrder(), statusServiceOne.getPileCode(), (byte) 2, one.getCreateTime(), statusServiceOneTemp.getUpdateTime() + 3 * 60 * 1000, model, one.getCard(), map, statusServiceOneTemp.getFlage() == 2 ? TransConstant.CHARGING_STATION_POWER_OUTAGE : TransConstant.EMERGENCY_STOP_EXCEPTION_STOP);
-                        }*//*
-                        //订单断网停充上送交易订单
+        //没有充电中的订单
+        if (one == null || one.getNowOrderStatus() != StatusConstant.NOW_ORDER_STATUS_CHARGING) {
+            logger.info("没有订单上报空闲{}", imei);
+            realTimeStatusPushFrame.deviceStatusPush(deviceConnectionMsg, FrameDataSplicing.transactionNum(null, 0), statusServiceOne.getPileCode(), (byte) port, gunsStatus, insertGunStatus, 0, 0, zero, zero, 0);
+            return;
+        }
 
+        //充电中
+        if (portStatus == PortStatusConstant.CHARGING) {
+            byte[] transactionNum = one.getTransOrder();
+            if (one.getChargingInitStatus() == StatusConstant.CHARGING_INIT_STATUS_NO) {
+                logger.info("{}变位为充电中且当前订单还没首次上报过初始状态:" + DataConversion.bytesToHexString(transactionNum), imei);
+                realTimeStatusPushFrame.deviceStatusPush(deviceConnectionMsg, transactionNum, statusServiceOneTemp.getPileCode(), (byte) port, gunsStatus, insertGunStatus, 0, 0, zero, zero, 0);
+                //这里上报开始充电初始化状态并记录已经上报首次状态
+                one.setChargingInitStatus(StatusConstant.CHARGING_INIT_STATUS_OK);
+                orderStatusService.updateById(one);
+            }
+            return;
+        }
 
-                    }
-                  */  //插枪状态变化需要看是不是有启充时没插枪的情况
-                    if (insertGunStatus == StatusConstant.INSERT_GUNS_YES && gunsStatus == StatusConstant.FREE) {
-                        if (redisCache.hasKey(RedisConstant.NO_INSERT_GUN_YKC + statusServiceOneTemp.getPileCode())) {
-                            //有择发启充设备,然后移除掉redis
-                            logger.info(statusServiceOne.getPileCode() + ":云快充启动时未插枪>检测到插枪启动>>>订单>>" + DataConversion.bytesToHexString(one.getTransOrder()));
-                            deviceControlerService.startCharge(statusServiceOneTemp.getDeviceImei(), statusServiceOneTemp.getDeviceImei(), port, 0);
-                            charngingPushFrame.startStatus(deviceConnectionMsg, one.getTransOrder(), port, 0x01, 0x00);
-                            redisCache.deleteObject(RedisConstant.NO_INSERT_GUN_YKC + statusServiceOneTemp.getPileCode());
-                        }
-                    }
-                    logger.info(statusServiceOne.getPileCode() + ":设备变位状态上送枪状态>>>" + gunsStatus + ";插枪状态:" + insertGunStatus);
-                    realTimeStatusPushFrame.deviceStatusPush(deviceConnectionMsg, transactionNum, statusServiceOne.getPileCode(), (byte) port, gunsStatus, insertGunStatus, 0, 0, zero, zero, 0);
+        //充电结束
+        if (portStatus == PortStatusConstant.CHARGING_END) {
+            //7状态小于30秒内且订单原因不是远程停充
+            if (one.getNowOrderStatus() == StatusConstant.NOW_ORDER_STATUS_CHARGING) {
+                if ((System.currentTimeMillis() - one.getCreateTime()) < 60 * 1000 && one.getReasonStopCharging() != TransConstant.APP_REMOTE_STOP) {
+                    logger.info("订单60秒内{}不处理7这个状态", one.getPileCode());
+                    return;
+                } else {
+                    //充电已完成
+                    //发送结束充电命令 顺利的话113会收到 状态还是7
+                    logger.info("订单60秒后{}7状态发送止充电指令", one.getPileCode());
+                    //标记订单为已停充 标记为未上送
+                    one.setNowOrderStatus(StatusConstant.NOW_ORDER_STATUS_CHARGING_ENDING);
+                    one.setEndTime(System.currentTimeMillis());
+                    one.setReasonStopCharging(TransConstant.SOC_FULL_OF_STOP);
+                    orderStatusService.updateById(one);
+                    RpcResult rpcResult = deviceControlerService.stopCharge(imei, imei, port);
+                    return;
                 }
             }
+            return;
+        }
+
+        //订单还在充电中 但是枪不在充电中状态 就结束订单
+        if (one.getNowOrderStatus() == StatusConstant.NOW_ORDER_STATUS_CHARGING) {
+            logger.info("{}枪非充电中状态,结束订单状态 等待任务重试上报订单", one.getPileCode());
+            one.setNowOrderStatus(StatusConstant.NOW_ORDER_STATUS_CHARGING_ENDING);
+            one.setEndTime(System.currentTimeMillis());
+            one.setReasonStopCharging(TransConstant.OTHER_STOP);
+            orderStatusService.updateById(one);
         }
+        logger.info("上传空闲状态{}",imei);
+        realTimeStatusPushFrame.deviceStatusPush(deviceConnectionMsg, FrameDataSplicing.transactionNum(null, 0), statusServiceOne.getPileCode(), (byte) port, gunsStatus, insertGunStatus, 0, 0, zero, zero, 0);
+
     }
 }

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

@@ -346,7 +346,7 @@ public class YkcMsgHandle {
                 } else if (StatusConstant.INSERT_GUNS_NO == twoDeviceStatus.getInsertGunStatus()) {
                     //未插枪
                     reason = 0x05;
-                    temp = false;
+                    temp = true;
                 } else if (PortStatusConstant.EMERGENCY_STOP == twoDeviceStatus.getGunStatus()) {
                     //急停没复位,也是启充失败
                     temp = true;

+ 7 - 0
src/main/java/com/tmzn/devicelinkykc/service/DeviceControlerService.java

@@ -130,6 +130,13 @@ public class DeviceControlerService {
     }
 
 
+    public void sendImeiDetail(String imei){
+        DeviceParam dataParam = new DeviceParam();
+        dataParam.setDeviceId(imei);
+        dataParam.setCcid(imei);
+        sendPortDetailCmd(dataParam);
+    }
+
     /**
      * 发送获取端口状态指令
      * @param deviceParam

+ 49 - 50
src/main/java/com/tmzn/devicelinkykc/taskQueue/runner/DeviceOnlineRunner.java

@@ -29,9 +29,7 @@ import org.springframework.stereotype.Component;
 
 import java.io.IOException;
 import java.math.BigDecimal;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
+import java.util.*;
 import java.util.stream.Collectors;
 
 
@@ -69,66 +67,67 @@ public class DeviceOnlineRunner {
             deviceQueryWrapper.eq("disabled", DeviceOnlineStatus.NORMAL);
             List<Device> list = deviceService.list(deviceQueryWrapper);
             logger.info("查询到设备" + list.size());
-            //云快充设备缓存过滤订阅消息
-            Set<String> imeiList = list.stream().map(device->{
-                      //缓存一下设备的序列号
-                      redisCache.setCacheMapValue(RedisConstant.DEVICE_IMEI_PILE_MAP,device.getDeviceImei(),device.getPileCode());
-                      return  device.getDeviceImei();
-                    }
-            ).collect(Collectors.toSet());
 
-            redisCache.setCacheObject(RedisConstant.DEVICE_INFO, imeiList);
+            Set<String> imeiList = new HashSet<>();
+            Map<String,Device> deviceMap = new HashMap<>();
+            list.forEach(device->{
+                imeiList.add(device.getDeviceImei());
+                redisCache.setCacheMapValue(RedisConstant.DEVICE_IMEI_PILE_MAP,device.getDeviceImei(),device.getPileCode());
+                deviceMap.put(device.getDeviceImei(),device);
+            });
 
 
+            redisCache.setCacheObject(RedisConstant.DEVICE_INFO, imeiList);
+
             QueryWrapper<DeviceStatus> deviceStatusQueryWrapper = new QueryWrapper<>();
             deviceStatusQueryWrapper.eq("online_status", DeviceOnlineStatus.ONLINE);
             List<DeviceStatus> onlineList = deviceStatusService.list(deviceStatusQueryWrapper);
 
-            List<DeviceStatus> newOnlineList = onlineList.stream().map(deviceStatus -> {
-                long updateTime = deviceStatus.getUpdateTime();
-                long nowTime = System.currentTimeMillis();
-                if ((nowTime - updateTime) > GAP_TIME) {
-                    if (socketHandle.existDeviceConnection(deviceStatus.getPileCode())) {
+            onlineList.forEach(deviceStatus->{
+                try{
+                    long updateTime = deviceStatus.getUpdateTime();
+                    long nowTime = System.currentTimeMillis();
+                    //超过20秒没有更新端口消息的 置为已下线
+                    if ((nowTime - updateTime) > GAP_TIME) {
+                        logger.info("{}更新时间已超时,下线",deviceStatus.getPileCode());
+                        if (socketHandle.existDeviceConnection(deviceStatus.getPileCode())) {
 //                        redisCache.deleteObject(RedisConstant.KEYS + deviceStatus.getPileCode());
-                        redisCache.deleteCacheMapValue(RedisConstant.YKC_KEY_MAP,deviceStatus.getPileCode());
-                        socketHandle.removeDeviceConnection(deviceStatus.getPileCode());
+                            redisCache.deleteCacheMapValue(RedisConstant.YKC_KEY_MAP,deviceStatus.getPileCode());
+                            socketHandle.removeDeviceConnection(deviceStatus.getPileCode());
+                        }
+                        deviceStatus.setOnlineStatus(DeviceOnlineStatus.OFFLINE);
+                        deviceStatusService.updateById(deviceStatus);
+                        return;
                     }
-                    deviceStatus.setOnlineStatus(DeviceOnlineStatus.OFFLINE);
-                    //deviceStatus.setGunStatus(StatusConstant.OFFLINE);
-                }
-                return deviceStatus;
-            }).collect(Collectors.toList());
-
-            if (redisCache.hasKey(RedisConstant.DEVICE_INFO)) {
-                Set<String> imeis = redisCache.getCacheObject(RedisConstant.DEVICE_INFO);
-                logger.info("redis-imei>>>" + imeis.size());
-            }
-            logger.info("dataBase device status change:" + newOnlineList.size());
-            deviceStatusService.updateBatchById(newOnlineList);
-
-            Map<String, Device> collect = list.stream().collect(Collectors.toMap(device -> device.getDeviceImei(), device -> device, (exis, repl) -> exis));
-
-            newOnlineList.stream().forEach(deviceStatus -> {
-                //logger.info(" newOnlineList.stream().forEach");
-                if (!socketHandle.existDeviceConnection(deviceStatus.getPileCode())) {
-                    try {
-                        Device device = collect.get(deviceStatus.getDeviceImei());
-                        socketHandle.addDeviceConnection(device.getIp(), device.getPort(), deviceStatus.getPileCode(), deviceStatus.getDeviceImei(), deviceStatus.getDeviceSn(), device.getCommProtocolVer());
-                    } catch (IOException e) {
-                        e.printStackTrace();
+
+                    Device device = deviceMap.get(deviceStatus.getDeviceImei());
+                    if(device==null){
+                        return;
                     }
-                }
-                DeviceConnectionMsg deviceConnection = socketHandle.getDeviceConnection(deviceStatus.getPileCode());
-                //logger.info("deviceConnection");
-                if (deviceConnection.getLoginStatus() == Constant.DEVICE_NOT_LOGIN_STATUS && deviceStatus.getOnlineStatus() == DeviceOnlineStatus.ONLINE) {
-                    //logger.info("DEVICE_NOT_LOGIN_STATUS");
-                    List<Device> collect1 = list.stream().filter(device -> device.getPileCode().equals(deviceConnection.getDeviceId())).collect(Collectors.toList());
-                    if (collect1.size() > 0) {
-                        logger.info("设备连接检查login>>>" + collect1.get(0).getDeviceSn());
-                        loginFrame.loginMsgSend(deviceConnection, collect1.get(0));
+                    boolean needLogin = false;
+                    if (!socketHandle.existDeviceConnection(deviceStatus.getPileCode())) {
+                        needLogin = true;
+                    }else{
+                        DeviceConnectionMsg deviceConnection = socketHandle.getDeviceConnection(deviceStatus.getPileCode());
+                        if (!deviceConnection.getSocket().isConnected()) {
+                            socketHandle.removeDeviceConnection(deviceStatus.getPileCode());
+                            needLogin = true;
+                        }
+                    }
+                    if(!needLogin){
+                        return ;
                     }
+                    logger.info("桩检测需要自动上线{}",device.getPileCode());
+                    socketHandle.addDeviceConnection(device.getIp(),device.getPort(),device.getPileCode(), device.getDeviceImei(), device.getDeviceSn(),device.getCommProtocolVer());
+                    loginFrame.loginMsgSend(socketHandle.getDeviceConnection(device.getPileCode()), device);
+//                    deviceControlerService.sendImeiDetail(device.getDeviceImei());
+                }catch (Exception e){
+
                 }
+
             });
+
+
         } catch (Exception e) {
             e.printStackTrace();
         }