package com.js.kbt.socket; import java.math.BigDecimal; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import javax.annotation.Resource; import org.apache.log4j.Logger; import org.springframework.stereotype.Service; import org.springframework.util.CollectionUtils; import com.alibaba.fastjson.JSONObject; import com.js.kbt.mapper.ChangeIpCommandMapper; import com.js.kbt.mapper.EquipmentSendCommandMapper; import com.js.kbt.mapper.LonLatRecordMapper; import com.js.kbt.mapper.MouldCycleRuntimeMapper; import com.js.kbt.mapper.MouldDownPacketMapper; import com.js.kbt.mapper.MouldHistoryMapper; import com.js.kbt.mapper.MouldHistoryTimeMapper; import com.js.kbt.mapper.MouldHodingMapper; import com.js.kbt.mapper.RecDataLogMapper; import com.js.kbt.mapper.SensorThresholdMapper; import com.js.kbt.mapper.TbFactoryMapper; import com.js.kbt.mapper.TbMouldEquipmentMapper; import com.js.kbt.mapper.TbMouldMapper; import com.js.kbt.mapper.TimeCalibrationRecordMapper; import com.js.kbt.model.ChangeIpCommand; import com.js.kbt.model.ChangeIpCommandExample; import com.js.kbt.model.LonLatRecord; import com.js.kbt.model.LonLatRecordExample; import com.js.kbt.model.MouldDownPacket; import com.js.kbt.model.MouldDownPacketExample; import com.js.kbt.model.MouldHistory; import com.js.kbt.model.MouldHistoryExample; import com.js.kbt.model.MouldHistoryTime; import com.js.kbt.model.MouldHistoryTimeExample; import com.js.kbt.model.RecDataLog; import com.js.kbt.model.TbMould; import com.js.kbt.model.TbMouldEquipment; import com.js.kbt.model.TbMouldEquipmentExample; import com.js.kbt.model.TbMouldExample; import com.js.kbt.model.TimeCalibrationRecord; import com.mysql.fabric.xmlrpc.base.Array; import edu.emory.mathcs.backport.java.util.concurrent.Executors; import edu.emory.mathcs.backport.java.util.concurrent.ScheduledExecutorService; import edu.emory.mathcs.backport.java.util.concurrent.TimeUnit; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.SimpleChannelInboundHandler; import io.netty.handler.timeout.IdleState; import io.netty.handler.timeout.IdleStateEvent; @Service("userHandler") public class UserHandler extends SimpleChannelInboundHandler { private static final Logger logger = Logger.getLogger(UserHandler.class); private ChannelHandlerContext ctx; @Resource private MouldHistoryMapper mouldHistoryMapper; @Resource private MouldHistoryTimeMapper mouldHistoryTimeMapper; @Resource private TbMouldMapper tbMouldMapper; @Resource private TbMouldEquipmentMapper tbMouldEquipmentMapper; @Resource private TbFactoryMapper tbFactoryMapper; @Resource private MouldHodingMapper mouldHodingMapper; @Resource private MouldDownPacketMapper mouldDownPacketMapper; @Resource private TimeCalibrationRecordMapper timeCalibrationRecordMapper; @Resource private MouldCycleRuntimeMapper mouldCycleRuntimeMapper; @Resource private SensorThresholdMapper sensorThresholdMapper; @Resource private RecDataLogMapper recDataLogMapper; @Resource private LonLatRecordMapper lonLatRecordMapper; @Resource private ChangeIpCommandMapper changeIpCommandMapper; @Resource private EquipmentSendCommandMapper equipmentSendCommandMapper; @Override protected void channelRead0(ChannelHandlerContext arg0, String arg1) throws ParseException { String pack = "FAAF0007001e781e50003C37D5"; // 验证是否需要切换ip // sendChangeIp(); logger.info("开始接受数据..."); System.out.println("收到===" + arg1 + "\n"); String equipmentNo = processMsg(arg1); // 校准时间 timeCalibration(equipmentNo); // 以下是配置下行数据 sendPackage(equipmentNo); } private String processMsg(String input) throws ParseException { // ScheduledExecutorService pool = Executors.newSingleThreadScheduledExecutor(); String ret = "FA AF 00 07 02 1e 78 1e 50 00 3C"; ret.replaceAll(" ", ""); logger.info("=====接收到======" + input); if (!input.startsWith("FAAF")) { logger.info("非云模盒消息,不处理"); return ret; } // 设备编号 String deviceNum = ""; // 创建一个字符串集合用于存储由于粘包需要拆分后的报文 ret = input; RecDataLog logItem = new RecDataLog(); logItem.setRecData(input); recDataLogMapper.insertSelective(logItem); List strList = new ArrayList<>(); while (ret.length() > 0) { String subStr = ret.substring(0, Integer.parseInt(highInFrontLowInBack(ret.substring((2) * 2, (4) * 2)), 16) * 2); strList.add(subStr); ret = ret.substring(subStr.length()); } logger.info("粘包集合的長度==>" + strList.size()); for (String string : strList) { MouldHistory item = new MouldHistory(); // 抽取手机号码4-5(预留)丢包情况硬件会上报状态01,服务器判断02时候下发printall String mobilePart = input.substring(4 * 2, 5 * 2); System.out.println("原始mobile=" + mobilePart); String mobile = getStringFromHexStr(mobilePart); System.out.println("手机号码为" + mobile); item.setSim(mobile); // 获取设备编码15-24 String deviceNumPart = input.substring(5 * 2, 25 * 2); deviceNum = getStringFromHexStr(deviceNumPart); logger.info("设备No=" + deviceNum); item.setEquipmentNo(deviceNum); // 发送数据包 MouldDownPacketExample pExp = new MouldDownPacketExample(); pExp.createCriteria().andEquipmentNoEqualTo(deviceNum).andPacketStrNotEqualTo("CLEAR_PROTOCOL"); List packetList = mouldDownPacketMapper.selectByExample(pExp); if (packetList.size() > 0) { MouldDownPacket packet = packetList.get(0); logger.info("开始下发数据包==>" + packet.getPacketStr()); sendMsg(packet.getPacketStr()); // 下发完就将数据删除(防止后续数据过大造成性能的影响) mouldDownPacketMapper.deleteByPrimaryKey(packet.getId()); } pExp.clear(); pExp.createCriteria().andEquipmentNoEqualTo(deviceNum).andPacketStrEqualTo("CLEAR_PROTOCOL"); List emptyPacketList = mouldDownPacketMapper.selectByExample(pExp); if (emptyPacketList.size() > 0) { MouldDownPacket packet = emptyPacketList.get(0); if (packet.getIsUse() == 0) { logger.info("开始下清空次数发数据包==>" + "#CLEAR_PROTOCOL"); logger.info("开始下清空次数转化为16进制==>" + strHexStr16("#CLEAR_PROTOCOL")); sendMsg(strHexStr16("#CLEAR_PROTOCOL;")); packet.setIsUse(1); mouldDownPacketMapper.updateByPrimaryKey(packet); logger.info("清空次数发送完毕==>"); } } // 软件版本号25 String version = input.substring(25 * 2, 26 * 2); System.out.println("软件版本号=" + version); item.setVersion(version); String status = input.substring(26 * 2, 27 * 2); System.out.println("工作状态=" + status); item.setStatus(Integer.decode("0x" + status).toString()); // 经度27-37 String longitude = getStringFromHexStr(input.substring(27 * 2, 38 * 2)); System.out.println("经度=" + longitude); item.setLng(longitude); // 38-47纬度以 N 开头 String latitude = getStringFromHexStr(input.substring(38 * 2, 48 * 2)); System.out.println("纬度=" + latitude); item.setLat(latitude); System.out.println("==lac" + reverseParseHex(input.substring(48 * 2, 50 * 2))); System.out.println("==ci" + reverseParseHex(input.substring(50 * 2, 52 * 2))); // 临时变更高低位不做转换(由于硬件转递数据高低位传反导致,具体以上面为准) // System.out.println("==lac" + Integer.parseInt(input.substring(48 // * 2, 50 * // 2),16)); // System.out.println("==ci" + Integer.parseInt(input.substring(50 * // 2, 52 * // 2),16)); item.setGprsLac("" + reverseParseHex(input.substring(48 * 2, 50 * 2))); item.setGprsCi("" + reverseParseHex(input.substring(50 * 2, 52 * 2))); // 临时变更高低位不做转换(由于硬件转递数据高低位传反导致,具体以上面为准) // item.setGprsLac("" + Integer.parseInt(input.substring(48 * 2, 50 // * 2),16)); // item.setGprsCi("" + Integer.parseInt(input.substring(50 * 2, 52 * // 2),16)); item.setWifiBbsid(input.substring(52 * 2, 58 * 2)); String temp = "0x" + input.substring(58 * 2, 59 * 2); System.out.println(temp); int i = Integer.decode(temp) - 40; System.out.println(i); logger.info("温度-----------》: " + i); item.setTemperature(i); item.setBattery(Integer.decode("0x" + input.substring(59 * 2, 60 * 2))); item.setSig2g(Integer.decode("0x" + input.substring(60 * 2, 61 * 2))); item.setSigNb(Integer.decode("0x" + input.substring(61 * 2, 62 * 2))); item.setSigWifi(Integer.decode("0x" + input.substring(62 * 2, 63 * 2))); item.setExt0("" + Integer.decode("0x" + input.substring(63 * 2, 64 * 2))); item.setAlarm(Integer.decode("0x" + input.substring(64 * 2, 65 * 2))); String str = input.substring(65 * 2, 69 * 2); item.setRunCnt(reverseParseHex(str)); LonLatRecordExample rExp = new LonLatRecordExample(); rExp.createCriteria().andMccEqualTo("460").andMncEqualTo("0").andGprsCiEqualTo(item.getGprsCi()) .andGprsLacEqualTo(item.getGprsLac()); List lRList = lonLatRecordMapper.selectByExample(rExp); if (lRList.size() > 0) { LonLatRecord lonLatRecord = lRList.get(0); item.setLng(lonLatRecord.getLng()); item.setLat(lonLatRecord.getLat()); } else { // 根据基站lac和ci获取经纬度 String api = "http://api.cellocation.com:81/cell/?mcc=460&mnc=0&lac=" + item.getGprsLac() + "&ci=" + item.getGprsCi() + "&output=json"; String resp = com.js.kbt.util.HttpRequest.sendGet(api, null); JSONObject json = JSONObject.parseObject(resp); if (json != null && json.getInteger("errcode") == 0) { item.setLng(json.getDouble("lon") + ""); item.setLat(json.getDouble("lat") + ""); } else { logger.error("调用基站解析平台出错: " + resp); } LonLatRecord latRecord = new LonLatRecord(); latRecord.setGprsCi(item.getGprsCi()); latRecord.setMcc("460"); latRecord.setMnc("0"); latRecord.setGprsLac(item.getGprsLac()); latRecord.setLat(item.getLat()); latRecord.setLng(item.getLng()); lonLatRecordMapper.insertSelective(latRecord); } String crcStr = input.substring(input.length() - 4); item.setCrcCode("" + reverseParseHex(crcStr)); // 找寻上一条最新记录 MouldHistoryExample mExp = new MouldHistoryExample(); mExp.setOrderByClause("id desc limit 1"); mExp.createCriteria().andEquipmentNoEqualTo(item.getEquipmentNo()); List newList = mouldHistoryMapper.selectByExample(mExp); // 存入数据库 mouldHistoryMapper.insertSelective(item); Integer differenceValue = 0; //计算本次的运行次数和上次的差值 if(newList.size()==0){ differenceValue = item.getRunCnt(); }else{ differenceValue = item.getRunCnt() - newList.get(0).getRunCnt(); } //发送清空次数和其他指定 // EquipmentSendCommandExample escExample = new EquipmentSendCommandExample(); // escExample.createCriteria().andEquipmentNoEqualTo(item.getEquipmentNo()).andIsSendEqualTo(0); // List sendCommandLists = equipmentSendCommandMapper.selectByExample(escExample); // if(sendCommandLists.size()>0){ // for (EquipmentSendCommand equipmentSendCommand : sendCommandLists) { // if(equipmentSendCommand.getState().intValue() == 0){ // //清空指定 // sendMsg(strHexStr16("#CLEAR_PROTOCOL;")); // equipmentSendCommand.setIsSend(1); // equipmentSendCommand.setSendTime(new Date()); // equipmentSendCommandMapper.updateByPrimaryKeySelective(equipmentSendCommand); // } // // } // } // 模具开合记录 int cnt = item.getRunCnt(); int start = 69; logger.info("累计开合模次数=" + cnt); int end = input.length() - 4; // 最后2位 0xXX,0xXX ,是CRC校验位 logger.info("时间信息==" + input.substring(start * 2, end)); Integer thisOpenCounts = 0; //用于接受上次最新的那一条开合数据 List historyList = new ArrayList<>(); //用于接受第一包的开合时间与上次最新一包的开合时间差值 long openTimeDiff = 0L; //用于接受第一包数据 // MouldHistoryTime firstMouldHistoryTime = new MouldHistoryTime(); if (end - start * 2 >= 24) {// 时间最少6位,1位显示0x00,开合算两个时间,所以是6*2*2=24 // 本次运行周期内的开合模次数 int periodCnt = (end - start * 2) / 24; thisOpenCounts = periodCnt; logger.info("本次开合模次数==" + periodCnt); long aHeadOpenTimeLongVal = 0L; //用于接收判断是不是有包在当前包之后但已经发上来了,如16:11的开和数据先于16:10的数据先发上来 // List GreaterThanOpenTimeList = new ArrayList<>(); for (int pos = 0; pos < periodCnt; pos++) { // 合模时间 MouldHistoryTime time = new MouldHistoryTime(); time.setHistoryId(item.getId()); time.setEquipmentNo(item.getEquipmentNo()); time.setSeq(pos + 1); Date closeTime = parseDate(input, start, pos, 0); time.setCloseTime(closeTime); // 开模时间 Date openTime = parseDate(input, start, pos, 6); time.setOpenTime(openTime); logger.info("第" + (pos + 1) + "包"); logger.info("本包开合时间戳--" + openTime.getTime()); if (pos == 0) { MouldHistoryTimeExample mhtExp = new MouldHistoryTimeExample(); //查询当前包是否是之前丢的包,判断依据,看看有没有比当前开合日期更后的开合数据 // mhtExp.setOrderByClause("open_time limit 1"); // mhtExp.createCriteria().andEquipmentNoEqualTo(item.getEquipmentNo()).andOpenTimeGreaterThanOrEqualTo(openTime).andIsTrueEqualTo(0); // GreaterThanOpenTimeList = mouldHistoryTimeMapper.selectByExample(mhtExp); // mhtExp.clear(); mhtExp.setOrderByClause("open_time desc limit 1"); mhtExp.createCriteria().andEquipmentNoEqualTo(item.getEquipmentNo()).andOpenTimeLessThanOrEqualTo(openTime); //小于当前开合时间的最新的一包开合数据 historyList = mouldHistoryTimeMapper.selectByExample(mhtExp); if (historyList.size() > 0) { openTimeDiff = openTime.getTime() - historyList.get(0).getOpenTime().getTime(); time.setTimeCost((int)openTimeDiff); } else { time.setTimeCost(0); } } else { logger.info("本次开合周期--" + (openTime.getTime() - aHeadOpenTimeLongVal)); time.setTimeCost((int) (openTime.getTime() - aHeadOpenTimeLongVal)); } mouldHistoryTimeMapper.insertSelective(time); // // 处理最后一包周期逻辑 aHeadOpenTimeLongVal = openTime.getTime(); // if(pos==0){ // firstMouldHistoryTime = time; // } } // if(GreaterThanOpenTimeList.size()>0){ // //当前数据为丢包重传的数据 // logger.info("此包为之前丢的包...需要修改之前的第一包周期"); // MouldHistoryTime mouldHistoryTime = GreaterThanOpenTimeList.get(0); // mouldHistoryTime.setTimeCost((int) (mouldHistoryTime.getOpenTime().getTime() - aHeadOpenTimeLongVal)); // MouldHistoryTimeExample mhtExp = new MouldHistoryTimeExample(); // mhtExp.createCriteria().andHistoryIdEqualTo(mouldHistoryTime.getHistoryId()).andOpenTimeEqualTo(mouldHistoryTime.getOpenTime()).andEquipmentNoEqualTo(mouldHistoryTime.getEquipmentNo()); // mouldHistoryTimeMapper.updateByExampleSelective(mouldHistoryTime, mhtExp); // } // //当前包为非丢包重传的数据 // Integer lossPacketCount = differenceValue - thisOpenCounts; // if(lossPacketCount>0){ // logger.info("本次丢包数---->"+lossPacketCount+"_上一包开合数据数:"+historyList.size()+"_两包之间的时间差值:"+openTimeDiff); // if(historyList.size()>0){ // //本次第一包开合时间与上一包最新开合数据的开合时间差值超过一分钟则判断为丢包了 // if(openTimeDiff>60000){ // logger.info("触发补充数据任务,时间:"+new SimpleDateFormat("yy-MM-dd,HH:mm:ss").format(new Date())); // //此时丢包了,丢了lossPacketCount个包,如果小于0则是第二包或者是之前的丢包补上来了 // examineTask(item.getEquipmentNo(),lossPacketCount,firstMouldHistoryTime,historyList.get(0),pool); // } // } // } } else { logger.info("本次开合模次数==0"); } // 统计该模盒的平均开合周期 // MouldHistoryExample exp = new MouldHistoryExample(); // exp.setOrderByClause("id"); // exp.createCriteria().andEquipmentNoEqualTo(item.getEquipmentNo()).andRunCntEqualTo(item.getRunCnt()); // List list = // mouldHistoryTimeMapper.selectByEquipmentNoAndThanZero(item.getEquipmentNo()); // List list = // mouldHistoryMapper.selectByExample(exp); // List historyIds = new ArrayList<>(); // historyIds.add(-1L); // for (MouldHistory mouldHistory : list) { // historyIds.add(mouldHistory.getId()); // } MouldHistoryTimeExample mtExp = new MouldHistoryTimeExample(); mtExp.setOrderByClause("seq"); mtExp.createCriteria().andHistoryIdEqualTo(item.getId()).andTimeCostGreaterThan(0); historyList = mouldHistoryTimeMapper.selectByExample(mtExp); int avgTime = 0; int totalTime = 0; // if (historyList.size() == 1) { // // 证明盒子动了,找寻上一条记录 // if (newList.size() > 0) { // MouldHistoryTime now = historyList.get(0); // MouldHistoryTime last = // mouldHistoryTimeMapper.getDateByHistory(newList.get(0).getId()); // if (null != now && null != last) { // avgTime = (int)((now.getOpenTime().getTime()) - // (last.getOpenTime().getTime())); // } // } // } else { if (historyList.size() > 1) { for (MouldHistoryTime mouldHistoryTime : historyList) { logger.info("totalTime" + totalTime); totalTime += mouldHistoryTime.getTimeCost(); } logger.info("totalTime" + totalTime); avgTime = (int) (totalTime / historyList.size()); } // } logger.info("avgTime-->" + avgTime); handleModLogic(item, avgTime, thisOpenCounts); // 判断预留字节的 if ("02".equals(mobilePart)) { // 丢包数据已占满缓存,调用读取命令 String strHexStr16 = strHexStr16("#PRINTFALL;"); logger.info("丢包数据已占满缓存下发调用读取命令#PRINTFALL;==>" + strHexStr16); sendMsg(strHexStr16); return deviceNum; } // //临时下发周期矫正fa af 00 03 01 05 08 14 50 00 14 a6 22 // sendMsg("fa af 00 03 01 05 08 14 50 00 14 a6 22"); // logger.info("临时下发周期矫正==>" + "fa af 00 03 01 05 08 14 50 00 14 a6 // 22"); // 返回设备编号 } return deviceNum; } // 下发切换服务器ip命令 public void sendChangeIp() { ChangeIpCommandExample example = new ChangeIpCommandExample(); example.createCriteria().andIsSendEqualTo(0); List list = changeIpCommandMapper.selectByExample(example); if (!CollectionUtils.isEmpty(list)) { ChangeIpCommand changeIpCommand = list.get(0); // #IPADDS=58.213.104.114:9090; // 下发切换服务器命令 StringBuffer sb = new StringBuffer(); sb.append("#IPADDS=").append(changeIpCommand.getIp()).append(":").append(changeIpCommand.getPort()) .append(";"); logger.info("开始下发切换服务器命令字符串为;==>" + sb.toString()); String strHexStr16 = strHexStr16(sb.toString()); logger.info("下发切换服务器ip转换后的16进制为;==>" + strHexStr16); sendMsg(strHexStr16); // 下发完修改状态为已下发 changeIpCommand.setIsSend(1); changeIpCommandMapper.updateByPrimaryKeySelective(changeIpCommand); } } public void sendPackage(String equipmentNo) { if (equipmentNo.indexOf("FAAF") != -1) { logger.info("非法云模盒编号,不作下发处理"); return; } MouldDownPacketExample exp = new MouldDownPacketExample(); exp.createCriteria().andEquipmentNoEqualTo(equipmentNo).andPacketStrNotEqualTo("CLEAR_PROTOCOL"); List list = mouldDownPacketMapper.selectByExample(exp); if (list.size() > 0) { MouldDownPacket packet = list.get(0); TbMouldEquipmentExample meqExp = new TbMouldEquipmentExample(); meqExp.createCriteria().andEquipmentNoEqualTo(equipmentNo); long count = tbMouldEquipmentMapper.countByExample(meqExp); // 下发数据包,下发完后修改状态 logger.info("开始下发数据包==>" + packet.getPacketStr()); sendMsg(packet.getPacketStr()); if (null != packet.getThreshold()) { // 下发阈值命令 sendMsg(strHexStr16("#LIMIT VALUE=" + packet.getThreshold())); } if (count > 0) { TbMouldEquipment me = tbMouldEquipmentMapper.selectByExample(meqExp).get(0); TbMouldEquipment tme = new TbMouldEquipment(); tme.setId(me.getId()); tme.setIsUse(packet.getIsUse()); tbMouldEquipmentMapper.updateByPrimaryKeySelective(tme); logger.info("将启用中的云模盒改为启用成功==>" + me.getEquipmentNo()); } // 下发完删除数据 mouldDownPacketMapper.deleteByPrimaryKey(packet.getId()); } } public void timeCalibration(String equipmentNo) { // logger.info("下发校准时间的云模盒equipmentNo"+equipmentNo); if (equipmentNo.indexOf("FAAF") != -1) { logger.info("非法云模盒编号,不作下发处理"); return; } List count = timeCalibrationRecordMapper.selectCountByToday(equipmentNo); // 今天未校准时间,下发时间校准,已经校准过了,则不再校准 if (count.size() == 0) { Date date = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("yy-MM-dd,HH:mm:ss"); String dateStr = sdf.format(date); dateStr = "#TIME=" + dateStr + ";"; // #TIME=18-03-06,15:31:48; logger.info("校准系统模块时间==>" + dateStr); // 将字符串转成16进制字符串 String strHexStr16 = strHexStr16(dateStr); logger.info("校准系统模块时间转成16进制的字符串==>" + strHexStr16); sendMsg(strHexStr16); TimeCalibrationRecord timeCalibrationRecord = new TimeCalibrationRecord(); timeCalibrationRecord.setIndate(new Date()); timeCalibrationRecord.setEquipmentNo(equipmentNo); timeCalibrationRecordMapper.insertSelective(timeCalibrationRecord); } } private void handleModLogic(MouldHistory item, int avgTime, Integer thisOpenCount) { logger.info("进了handleModLogic逻辑--"); logger.info("item==>" + item); TbMouldEquipmentExample meqExp = new TbMouldEquipmentExample(); meqExp.createCriteria().andEquipmentNoEqualTo(item.getEquipmentNo()); if (tbMouldEquipmentMapper.countByExample(meqExp) > 0) { TbMouldEquipment me = tbMouldEquipmentMapper.selectByExample(meqExp).get(0); me.setCurhillNumber(item.getBattery() + ""); if (item.getLng() != null) { logger.info("更新经纬度:"); me.setLng(Double.parseDouble(item.getLng())); me.setLat(Double.parseDouble(item.getLat())); } me.setCurtemperature(item.getTemperature()); if (item.getAlarm() == 8) { me.setStage(3);// 安装被拆 } else if (item.getAlarm() == 1) { me.setStage(2);// 低电量 } else if (item.getAlarm() == 2) { me.setStage(1);// 高温 } else { me.setStage(item.getAlarm()); } // 处理报警 if (item.getAlarm() > 0) { /** * 无报警 0; 低电量报警 1; 温度过热 2; 安装被拆 8。 */ logger.info("设备报警啦:" + item.getAlarm()); } tbMouldEquipmentMapper.updateByPrimaryKeySelective(me); logger.info("更新完了tbMouldEquipment的状态和温度以及经纬度"); TbMouldExample tExp = new TbMouldExample(); tExp.setOrderByClause("id desc limit 1"); tExp.createCriteria().andEquipmentIdEqualTo(me.getId()); if (tbMouldMapper.countByExample(tExp) > 0) { logger.info("准备更新运行次数:"); TbMould tm = tbMouldMapper.selectByExample(tExp).get(0); MouldHistoryTimeExample mhtExp = new MouldHistoryTimeExample(); // 一次接受到数据,超过5次开合标记为运行状态 if (thisOpenCount > 5) { tm.setState(item.getStatus()); } else { tm.setState("0"); } // 云模盒运行次数+模具的历史运行次数 tm.setRunTimes(item.getRunCnt() + tm.getHistoryRunTimes()); tm.setLastRecTime(new Date()); // 处理每模平均周期(单位秒) if (0 != avgTime) { logger.info("开始修改平均每模周期值为:" + avgTime); BigDecimal bd = new BigDecimal(avgTime * 1.00 / 1000); tm.setOcCycle(bd); } tbMouldMapper.updateByPrimaryKeySelective(tm); } } } /** * 低位在前的16进制解析 * * @param rHex * @return */ public static int reverseParseHex(String rHex) { int size = rHex.length() / 2; StringBuilder sb = new StringBuilder(); for (int i = 0; i < size; i++) { sb.append(rHex.substring((size - i - 1) * 2, (size - i) * 2)); } String str = sb.toString(); return Integer.parseInt(str, 16); } private static Date parseDate(String input, int start, int pos, int dateStartPos) { // pos为开合的一组的下标,一个开合时间占位是12*2 String year = input.substring((start + pos * 12 + dateStartPos) * 2, (start + pos * 12 + 1 + dateStartPos) * 2); String month = input.substring((start + pos * 12 + 1 + dateStartPos) * 2, (start + pos * 12 + 2 + dateStartPos) * 2); String day = input.substring((start + pos * 12 + 2 + dateStartPos) * 2, (start + pos * 12 + 3 + dateStartPos) * 2); String hh = input.substring((start + pos * 12 + 3 + dateStartPos) * 2, (start + pos * 12 + 4 + dateStartPos) * 2); String mm = input.substring((start + pos * 12 + 4 + dateStartPos) * 2, (start + pos * 12 + 5 + dateStartPos) * 2); String ss = input.substring((start + pos * 12 + 5 + dateStartPos) * 2, (start + pos * 12 + 6 + dateStartPos) * 2); StringBuilder sb = new StringBuilder(); int yearInt = Integer.parseInt(year, 16); if (yearInt == 0) { sb.append("2019-01-01"); } else { sb.append(yearInt < 100 ? "20" : "2"); sb.append(yearInt).append("-"); int monthInt = Integer.parseInt(month, 16); sb.append(monthInt < 10 ? "0" : "").append(monthInt).append("-"); int dayInt = Integer.parseInt(day, 16); sb.append(dayInt < 10 ? "0" : "").append(dayInt); } Date parseDate = null; try { parseDate = new SimpleDateFormat("yyyy-MM-dd").parse(sb.toString()); parseDate.setHours(Integer.parseInt(hh, 16)); parseDate.setMinutes(Integer.parseInt(mm, 16)); parseDate.setSeconds(Integer.parseInt(ss, 16)); } catch (ParseException e) { e.printStackTrace(); } return parseDate; } // private void handleMouldCycleRuntimeLogic(Date openTime, MouldHistory // item) throws ParseException { // System.out.println( // "开始handleMouldCycleRuntimeLogic逻辑开合时间" + new SimpleDateFormat("yyyy-MM-dd // HH:mm:ss").format(openTime)); // MouldCycleRuntime mcr = new MouldCycleRuntime(); // SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); // mcr.setDateStr(sdf.format(openTime)); // Integer hours = openTime.getHours(); // SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:"); // int housTime = openTime.getHours() - 1; // openTime.setHours(housTime); // String lastOpenTime = sdf1.format(openTime); // Date lastOpenTimeDate = sdf1.parse(lastOpenTime); // // 此处直接拼接字符串“59:59”会导致分和秒丢失,所以才去set的方法设置时分秒 // lastOpenTimeDate.setMinutes(59); // lastOpenTimeDate.setSeconds(59); // logger.info("当前开合时间减一小时的时间条件:" + new SimpleDateFormat("yyyy-MM-dd // HH:mm:ss").format(lastOpenTimeDate)); // MouldHistoryTimeExample mExp = new MouldHistoryTimeExample(); // mExp.setOrderByClause("open_time desc limit 1"); // mExp.createCriteria().andEquipmentNoEqualTo(item.getEquipmentNo()) // .andOpenTimeLessThanOrEqualTo(lastOpenTimeDate); // List list = // mouldHistoryTimeMapper.selectByExample(mExp); // logger.info("满足条件的上一个小数数据集合长度:" + list.size()); // if (list.size() > 0) { // MouldHistory mouldHistory = // mouldHistoryMapper.selectByPrimaryKey(list.get(0).getHistoryId()); // logger.info("本次运行次数: " + item.getRunCnt() + " 上一小时的运行次数:" + // mouldHistory.getRunCnt() + " 上一小时的historyId:" // + mouldHistory.getId()); // mcr.setEquipmentNo(item.getEquipmentNo()); // mcr.setRuntime(item.getRunCnt() - mouldHistory.getRunCnt()); // if (hours == 0) { // mcr.setTimeSlot("00:00-01:00"); // } else if (hours == 1) { // mcr.setTimeSlot("01:00-02:00"); // } else if (hours == 2) { // mcr.setTimeSlot("02:00-03:00"); // } else if (hours == 3) { // mcr.setTimeSlot("03:00-04:00"); // } else if (hours == 4) { // mcr.setTimeSlot("04:00-05:00"); // } else if (hours == 5) { // mcr.setTimeSlot("05:00-06:00"); // } else if (hours == 6) { // mcr.setTimeSlot("06:00-07:00"); // } else if (hours == 7) { // mcr.setTimeSlot("07:00-08:00"); // } else if (hours == 8) { // mcr.setTimeSlot("08:00-09:00"); // } else if (hours == 9) { // mcr.setTimeSlot("09:00-10:00"); // } else if (hours == 10) { // mcr.setTimeSlot("10:00-11:00"); // } else if (hours == 11) { // mcr.setTimeSlot("11:00-12:00"); // } else if (hours == 12) { // mcr.setTimeSlot("12:00-13:00"); // } else if (hours == 13) { // mcr.setTimeSlot("13:00-14:00"); // } else if (hours == 14) { // mcr.setTimeSlot("14:00-15:00"); // } else if (hours == 15) { // mcr.setTimeSlot("15:00-16:00"); // } else if (hours == 16) { // mcr.setTimeSlot("16:00-17:00"); // } else if (hours == 17) { // mcr.setTimeSlot("17:00-18:00"); // } else if (hours == 18) { // mcr.setTimeSlot("18:00-19:00"); // } else if (hours == 19) { // mcr.setTimeSlot("19:00-20:00"); // } else if (hours == 20) { // mcr.setTimeSlot("20:00-21:00"); // } else if (hours == 21) { // mcr.setTimeSlot("21:00-22:00"); // } else if (hours == 22) { // mcr.setTimeSlot("22:00-23:00"); // } else if (hours == 23) { // mcr.setTimeSlot("23:00-00:00"); // } // MouldCycleRuntimeExample mcrExp = new MouldCycleRuntimeExample(); // mcrExp.createCriteria().andDateStrEqualTo(mcr.getDateStr()).andEquipmentNoEqualTo(item.getEquipmentNo()) // .andTimeSlotEqualTo(mcr.getTimeSlot()); // List mList = // mouldCycleRuntimeMapper.selectByExample(mcrExp); // if (mList.size() > 0) { // mcr.setId(mList.get(0).getId()); // mouldCycleRuntimeMapper.updateByPrimaryKeySelective(mcr); // } else { // mouldCycleRuntimeMapper.insertSelective(mcr); // } // } // } private static String getStringFromHexStr(String hexStr) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < hexStr.length() / 2; i++) { String str = "0x" + hexStr.substring(i * 2, i * 2 + 2); int intVal = Integer.decode(str).intValue(); char c = (char) intVal; sb.append(c); } return sb.toString(); } public void close() { ctx.close(); } public void sendMsg(String hexString) { System.out.println("发送消息==" + hexString); byte[] buffer = hexStrToBinaryStr(hexString); ByteBuf bf = Unpooled.buffer(hexString.length() / 2); bf.writeBytes(buffer); ctx.writeAndFlush(bf); // ctx.close(); } //检查是否丢包,并插入丢包数据 /** * @param equipmentNo 云模合编号 * @param loseCount 丢包数量 * @param firstMouldHistoryTime 本次的第一条开合数据 * @param lastEndMouldHistoryTime 上一包最后一条开合数据 * @param pool 线程池 */ // public void examineTask(String equipmentNo,int loseCount,MouldHistoryTime firstMouldHistoryTime,MouldHistoryTime lastEndMouldHistoryTime,ScheduledExecutorService pool){ // pool.schedule(new Runnable() { // @Override // public void run() { // SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd,HH:mm:ss"); // logger.info("定时补充数据任务开始了,时间:"+sdf.format(new Date())); // MouldHistoryTimeExample mhtExp = new MouldHistoryTimeExample(); // mhtExp.createCriteria().andOpenTimeGreaterThan(lastEndMouldHistoryTime.getOpenTime()).andOpenTimeLessThan(firstMouldHistoryTime.getOpenTime()); // long count = mouldHistoryTimeMapper.countByExample(mhtExp); // logger.info(sdf.format(lastEndMouldHistoryTime.getOpenTime())+"--"+sdf.format(firstMouldHistoryTime.getOpenTime())+"时间段内丢包时间段上来了"+count+"条数据"); // if(count==loseCount){ // return; // }else{ // TbMouldEquipmentExample tExp = new TbMouldEquipmentExample(); // tExp.createCriteria().andEquipmentNoEqualTo(equipmentNo); // List equipments = tbMouldEquipmentMapper.selectByExample(tExp); // if(equipments.size()>0){ // TbMouldExample tmExp = new TbMouldExample(); // tmExp.createCriteria().andEquipmentIdEqualTo(equipments.get(0).getId()); // List moulds = tbMouldMapper.selectByExample(tmExp); // MouldHistoryTime newMouldHistoryTime = new MouldHistoryTime(); // if(moulds.size()>0){ // //平均开合周期 // int OcCycle = (int)moulds.get(0).getOcCycle().doubleValue()*1000; // long addPacketCount = loseCount-count; // logger.info("补包数->"+addPacketCount); // long openTime = 0L; // long closeTime = 0L; // if(addPacketCount newMouldHistoryTimes = mouldHistoryTimeMapper.selectByExample(mhtExp); // newMouldHistoryTime = newMouldHistoryTimes.get(0); // openTime = newMouldHistoryTime.getOpenTime().getTime(); // closeTime = newMouldHistoryTime.getCloseTime().getTime(); // }else{ // newMouldHistoryTime = lastEndMouldHistoryTime; // openTime = newMouldHistoryTime.getOpenTime().getTime(); // closeTime = newMouldHistoryTime.getCloseTime().getTime(); // } // for(int i=0;i> 4)); hex += String.valueOf(hexStr.charAt(b & 0x0F)); result += hex + " "; } return result; } /** * 普通字符串转16进制字符串 * * @param str * @return */ public static String strHexStr16(String str) { char[] chars = "0123456789ABCDEF".toCharArray(); StringBuilder sb = new StringBuilder(""); byte[] bs = str.getBytes(); int bit; for (int i = 0; i < bs.length; i++) { bit = (bs[i] & 0x0f0) >> 4; sb.append(chars[bit]); bit = bs[i] & 0x0f; sb.append(chars[bit]); // sb.append(' '); } return sb.toString().trim(); } // 转换16进制字符串低位在前,高位在后 成 高位在前,低位在后 public static String highInFrontLowInBack(String result) { return result.substring(2, 4) + result.substring(0, 2);// 高位在前,低位在后 } public static void main(String[] args) throws ParseException { // System.out.println(Integer.parseInt(getStringFromHexStr("0107"), // 16)); // UserHandler h = new UserHandler(); // h.timeCalibration(); // SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:"); // Date date = new Date(); // String lastOpenTime = sdf1.format(date); // System.out.println(lastOpenTime); // Date lastOpenTimeDate = sdf1.parse(lastOpenTime); // lastOpenTimeDate.setMinutes(59); // lastOpenTimeDate.setSeconds(59); // System.out.println(new SimpleDateFormat("yyyy-MM-dd // HH:mm:ss").format(lastOpenTimeDate)); // String a = "00:25:32"; // SimpleDateFormat s = new SimpleDateFormat("HH:mm:ss"); // Date d = new Date(); // System.out.println(s.parse(a).getHours()); // Date date = new Date(); // SimpleDateFormat sdf = new SimpleDateFormat("yy-MM-dd,HH:mm:ss"); // String dateStr = sdf.format(date); // dateStr = "#TIME="+dateStr+";"; // System.out.println(dateStr); // //#TIME=18-03-06,15:31:48; // logger.info("校准系统模块时间==>"+dateStr); // String reverseParseHex = strHexStr16(dateStr); // System.out.println("reverseParseHex-----"+reverseParseHex); // String str = "1F51"; // String input = // "FAAF530000000000000000000000003137333030303239343310010000000000000000000" // + "000000000000000000000001F51E85F00000000000045004A" + // "54000100110000001308160F171F1308160F2D188FCA"; // String temp = "0x"+str; // int i = Integer.decode(temp); // System.out.println(i); // int p = reverseParseHex(str); // System.out.println(p); // int start = 69; // System.out.println(str.substring(69*2)); // Date d = parseDate(str, start, 0, 0); // System.out.println(d.toGMTString()); // int start = 69; // int end = input.length() - 4; // 最后2位 0xXX,0xXX ,是CRC校验位 // logger.info("时间信息==" + input.substring(start * 2, end)); // if (end - start * 2 >= 24) {// 时间最少6位,1位显示0x00,开合算两个时间,所以是6*2*2=24 // // 本次运行周期内的开合模次数 // int periodCnt = (end - start * 2) / 24; // logger.info("本次开合模次数==" + periodCnt); // for (int pos = 0; pos < periodCnt; pos++) { // // 合模时间 // MouldHistoryTime time = new MouldHistoryTime(); // time.setSeq(pos + 1); // Date closeTime = parseDate(input, start, pos, 0); // System.out.println(closeTime); // time.setCloseTime(closeTime); // // 开模时间 // Date openTime = parseDate(input, start, pos, 6); // time.setOpenTime(openTime); // System.out.println(openTime); // int timeCost = (int) (openTime.getTime() - closeTime.getTime()); // time.setTimeCost(timeCost); // } // } else { // logger.info("本次开合模次数==0"); // } // String api = "http://api.cellocation.com:81/cell/?mcc=460&mnc=0&lac=" // + 21855 // + "&ci=" // + 4823 + "&output=json"; // String resp = com.js.kbt.util.HttpRequest.sendGet(api, null); // JSONObject json = JSONObject.parseObject(resp); // System.out.println(json); // if (json != null && json.getInteger("errcode") == 0) { // sys // item.setLng(json.getDouble("lon") + ""); // item.setLat(json.getDouble("lat") + ""); // } else { // logger.error("调用基站解析平台出错: " + resp); // } // String ret = // "FAAF070100383938363034313631323138383035383439363831010000000000000000000000000000000000000000005F55D7120600000000003D644734000200300100001204020F151D1204020F152F14010A00212914010A00220014010A00220214010A00221314010A00221514010A00222A14010A00222B14010A00230114010A00230314010A00231714010A00231A14010A00232A14010A00232C14010A00240514010A00241A14010A00242C14010A00242F14010A00250714010A00250A14010A00251C14010A00251D14010A00252F14010A00253114010A00260814010A00260A14010A00261C14010A00261E14010A00263114010A00263314010A00270BFA8E"; // List strList = new ArrayList<>(); // while (ret.length() > 0) { // String subStr = ret.substring(0, // Integer.parseInt(highInFrontLowInBack(ret.substring((2) * 2, (4) * // 2)), 16) * 2); // strList.add(subStr); // ret = ret.substring(subStr.length()); // System.out.println(ret); // } // System.out.println("while執行完了"); // System.out.println(strList); System.out.println(strHexStr16("#CLEAR_PROTOCOL")); } }