UserHandler.java 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031
  1. package com.js.kbt.socket;
  2. import java.math.BigDecimal;
  3. import java.text.ParseException;
  4. import java.text.SimpleDateFormat;
  5. import java.util.ArrayList;
  6. import java.util.Date;
  7. import java.util.List;
  8. import javax.annotation.Resource;
  9. import org.apache.log4j.Logger;
  10. import org.springframework.stereotype.Service;
  11. import org.springframework.util.CollectionUtils;
  12. import com.alibaba.fastjson.JSONObject;
  13. import com.js.kbt.mapper.ChangeIpCommandMapper;
  14. import com.js.kbt.mapper.EquipmentSendCommandMapper;
  15. import com.js.kbt.mapper.LonLatRecordMapper;
  16. import com.js.kbt.mapper.MouldCycleRuntimeMapper;
  17. import com.js.kbt.mapper.MouldDownPacketMapper;
  18. import com.js.kbt.mapper.MouldHistoryMapper;
  19. import com.js.kbt.mapper.MouldHistoryTimeMapper;
  20. import com.js.kbt.mapper.MouldHodingMapper;
  21. import com.js.kbt.mapper.RecDataLogMapper;
  22. import com.js.kbt.mapper.SensorThresholdMapper;
  23. import com.js.kbt.mapper.TbFactoryMapper;
  24. import com.js.kbt.mapper.TbMouldEquipmentMapper;
  25. import com.js.kbt.mapper.TbMouldMapper;
  26. import com.js.kbt.mapper.TimeCalibrationRecordMapper;
  27. import com.js.kbt.model.ChangeIpCommand;
  28. import com.js.kbt.model.ChangeIpCommandExample;
  29. import com.js.kbt.model.LonLatRecord;
  30. import com.js.kbt.model.LonLatRecordExample;
  31. import com.js.kbt.model.MouldDownPacket;
  32. import com.js.kbt.model.MouldDownPacketExample;
  33. import com.js.kbt.model.MouldHistory;
  34. import com.js.kbt.model.MouldHistoryExample;
  35. import com.js.kbt.model.MouldHistoryTime;
  36. import com.js.kbt.model.MouldHistoryTimeExample;
  37. import com.js.kbt.model.RecDataLog;
  38. import com.js.kbt.model.TbMould;
  39. import com.js.kbt.model.TbMouldEquipment;
  40. import com.js.kbt.model.TbMouldEquipmentExample;
  41. import com.js.kbt.model.TbMouldExample;
  42. import com.js.kbt.model.TimeCalibrationRecord;
  43. import com.mysql.fabric.xmlrpc.base.Array;
  44. import edu.emory.mathcs.backport.java.util.concurrent.Executors;
  45. import edu.emory.mathcs.backport.java.util.concurrent.ScheduledExecutorService;
  46. import edu.emory.mathcs.backport.java.util.concurrent.TimeUnit;
  47. import io.netty.buffer.ByteBuf;
  48. import io.netty.buffer.Unpooled;
  49. import io.netty.channel.ChannelHandlerContext;
  50. import io.netty.channel.SimpleChannelInboundHandler;
  51. import io.netty.handler.timeout.IdleState;
  52. import io.netty.handler.timeout.IdleStateEvent;
  53. @Service("userHandler")
  54. public class UserHandler extends SimpleChannelInboundHandler<String> {
  55. private static final Logger logger = Logger.getLogger(UserHandler.class);
  56. private ChannelHandlerContext ctx;
  57. @Resource
  58. private MouldHistoryMapper mouldHistoryMapper;
  59. @Resource
  60. private MouldHistoryTimeMapper mouldHistoryTimeMapper;
  61. @Resource
  62. private TbMouldMapper tbMouldMapper;
  63. @Resource
  64. private TbMouldEquipmentMapper tbMouldEquipmentMapper;
  65. @Resource
  66. private TbFactoryMapper tbFactoryMapper;
  67. @Resource
  68. private MouldHodingMapper mouldHodingMapper;
  69. @Resource
  70. private MouldDownPacketMapper mouldDownPacketMapper;
  71. @Resource
  72. private TimeCalibrationRecordMapper timeCalibrationRecordMapper;
  73. @Resource
  74. private MouldCycleRuntimeMapper mouldCycleRuntimeMapper;
  75. @Resource
  76. private SensorThresholdMapper sensorThresholdMapper;
  77. @Resource
  78. private RecDataLogMapper recDataLogMapper;
  79. @Resource
  80. private LonLatRecordMapper lonLatRecordMapper;
  81. @Resource
  82. private ChangeIpCommandMapper changeIpCommandMapper;
  83. @Resource
  84. private EquipmentSendCommandMapper equipmentSendCommandMapper;
  85. @Override
  86. protected void channelRead0(ChannelHandlerContext arg0, String arg1) throws ParseException {
  87. String pack = "FAAF0007001e781e50003C37D5";
  88. // 验证是否需要切换ip
  89. // sendChangeIp();
  90. logger.info("开始接受数据...");
  91. System.out.println("收到===" + arg1 + "\n");
  92. String equipmentNo = processMsg(arg1);
  93. // 校准时间
  94. timeCalibration(equipmentNo);
  95. // 以下是配置下行数据
  96. sendPackage(equipmentNo);
  97. }
  98. private String processMsg(String input) throws ParseException {
  99. // ScheduledExecutorService pool = Executors.newSingleThreadScheduledExecutor();
  100. String ret = "FA AF 00 07 02 1e 78 1e 50 00 3C";
  101. ret.replaceAll(" ", "");
  102. logger.info("=====接收到======" + input);
  103. if (!input.startsWith("FAAF")) {
  104. logger.info("非云模盒消息,不处理");
  105. return ret;
  106. }
  107. // 设备编号
  108. String deviceNum = "";
  109. // 创建一个字符串集合用于存储由于粘包需要拆分后的报文
  110. ret = input;
  111. RecDataLog logItem = new RecDataLog();
  112. logItem.setRecData(input);
  113. recDataLogMapper.insertSelective(logItem);
  114. List<String> strList = new ArrayList<>();
  115. while (ret.length() > 0) {
  116. String subStr = ret.substring(0,
  117. Integer.parseInt(highInFrontLowInBack(ret.substring((2) * 2, (4) * 2)), 16) * 2);
  118. strList.add(subStr);
  119. ret = ret.substring(subStr.length());
  120. }
  121. logger.info("粘包集合的長度==>" + strList.size());
  122. for (String string : strList) {
  123. MouldHistory item = new MouldHistory();
  124. // 抽取手机号码4-5(预留)丢包情况硬件会上报状态01,服务器判断02时候下发printall
  125. String mobilePart = input.substring(4 * 2, 5 * 2);
  126. System.out.println("原始mobile=" + mobilePart);
  127. String mobile = getStringFromHexStr(mobilePart);
  128. System.out.println("手机号码为" + mobile);
  129. item.setSim(mobile);
  130. // 获取设备编码15-24
  131. String deviceNumPart = input.substring(5 * 2, 25 * 2);
  132. deviceNum = getStringFromHexStr(deviceNumPart);
  133. logger.info("设备No=" + deviceNum);
  134. item.setEquipmentNo(deviceNum);
  135. // 发送数据包
  136. MouldDownPacketExample pExp = new MouldDownPacketExample();
  137. pExp.createCriteria().andEquipmentNoEqualTo(deviceNum).andPacketStrNotEqualTo("CLEAR_PROTOCOL");
  138. List<MouldDownPacket> packetList = mouldDownPacketMapper.selectByExample(pExp);
  139. if (packetList.size() > 0) {
  140. MouldDownPacket packet = packetList.get(0);
  141. logger.info("开始下发数据包==>" + packet.getPacketStr());
  142. sendMsg(packet.getPacketStr());
  143. // 下发完就将数据删除(防止后续数据过大造成性能的影响)
  144. mouldDownPacketMapper.deleteByPrimaryKey(packet.getId());
  145. }
  146. pExp.clear();
  147. pExp.createCriteria().andEquipmentNoEqualTo(deviceNum).andPacketStrEqualTo("CLEAR_PROTOCOL");
  148. List<MouldDownPacket> emptyPacketList = mouldDownPacketMapper.selectByExample(pExp);
  149. if (emptyPacketList.size() > 0) {
  150. MouldDownPacket packet = emptyPacketList.get(0);
  151. if (packet.getIsUse() == 0) {
  152. logger.info("开始下清空次数发数据包==>" + "#CLEAR_PROTOCOL");
  153. logger.info("开始下清空次数转化为16进制==>" + strHexStr16("#CLEAR_PROTOCOL"));
  154. sendMsg(strHexStr16("#CLEAR_PROTOCOL;"));
  155. packet.setIsUse(1);
  156. mouldDownPacketMapper.updateByPrimaryKey(packet);
  157. logger.info("清空次数发送完毕==>");
  158. }
  159. }
  160. // 软件版本号25
  161. String version = input.substring(25 * 2, 26 * 2);
  162. System.out.println("软件版本号=" + version);
  163. item.setVersion(version);
  164. String status = input.substring(26 * 2, 27 * 2);
  165. System.out.println("工作状态=" + status);
  166. item.setStatus(Integer.decode("0x" + status).toString());
  167. // 经度27-37
  168. String longitude = getStringFromHexStr(input.substring(27 * 2, 38 * 2));
  169. System.out.println("经度=" + longitude);
  170. item.setLng(longitude);
  171. // 38-47纬度以 N 开头
  172. String latitude = getStringFromHexStr(input.substring(38 * 2, 48 * 2));
  173. System.out.println("纬度=" + latitude);
  174. item.setLat(latitude);
  175. System.out.println("==lac" + reverseParseHex(input.substring(48 * 2, 50 * 2)));
  176. System.out.println("==ci" + reverseParseHex(input.substring(50 * 2, 52 * 2)));
  177. // 临时变更高低位不做转换(由于硬件转递数据高低位传反导致,具体以上面为准)
  178. // System.out.println("==lac" + Integer.parseInt(input.substring(48
  179. // * 2, 50 *
  180. // 2),16));
  181. // System.out.println("==ci" + Integer.parseInt(input.substring(50 *
  182. // 2, 52 *
  183. // 2),16));
  184. item.setGprsLac("" + reverseParseHex(input.substring(48 * 2, 50 * 2)));
  185. item.setGprsCi("" + reverseParseHex(input.substring(50 * 2, 52 * 2)));
  186. // 临时变更高低位不做转换(由于硬件转递数据高低位传反导致,具体以上面为准)
  187. // item.setGprsLac("" + Integer.parseInt(input.substring(48 * 2, 50
  188. // * 2),16));
  189. // item.setGprsCi("" + Integer.parseInt(input.substring(50 * 2, 52 *
  190. // 2),16));
  191. item.setWifiBbsid(input.substring(52 * 2, 58 * 2));
  192. String temp = "0x" + input.substring(58 * 2, 59 * 2);
  193. System.out.println(temp);
  194. int i = Integer.decode(temp) - 40;
  195. System.out.println(i);
  196. logger.info("温度-----------》: " + i);
  197. item.setTemperature(i);
  198. item.setBattery(Integer.decode("0x" + input.substring(59 * 2, 60 * 2)));
  199. item.setSig2g(Integer.decode("0x" + input.substring(60 * 2, 61 * 2)));
  200. item.setSigNb(Integer.decode("0x" + input.substring(61 * 2, 62 * 2)));
  201. item.setSigWifi(Integer.decode("0x" + input.substring(62 * 2, 63 * 2)));
  202. item.setExt0("" + Integer.decode("0x" + input.substring(63 * 2, 64 * 2)));
  203. item.setAlarm(Integer.decode("0x" + input.substring(64 * 2, 65 * 2)));
  204. String str = input.substring(65 * 2, 69 * 2);
  205. item.setRunCnt(reverseParseHex(str));
  206. LonLatRecordExample rExp = new LonLatRecordExample();
  207. rExp.createCriteria().andMccEqualTo("460").andMncEqualTo("0").andGprsCiEqualTo(item.getGprsCi())
  208. .andGprsLacEqualTo(item.getGprsLac());
  209. List<LonLatRecord> lRList = lonLatRecordMapper.selectByExample(rExp);
  210. if (lRList.size() > 0) {
  211. LonLatRecord lonLatRecord = lRList.get(0);
  212. item.setLng(lonLatRecord.getLng());
  213. item.setLat(lonLatRecord.getLat());
  214. } else {
  215. // 根据基站lac和ci获取经纬度
  216. String api = "http://api.cellocation.com:81/cell/?mcc=460&mnc=0&lac=" + item.getGprsLac() + "&ci="
  217. + item.getGprsCi() + "&output=json";
  218. String resp = com.js.kbt.util.HttpRequest.sendGet(api, null);
  219. JSONObject json = JSONObject.parseObject(resp);
  220. if (json != null && json.getInteger("errcode") == 0) {
  221. item.setLng(json.getDouble("lon") + "");
  222. item.setLat(json.getDouble("lat") + "");
  223. } else {
  224. logger.error("调用基站解析平台出错: " + resp);
  225. }
  226. LonLatRecord latRecord = new LonLatRecord();
  227. latRecord.setGprsCi(item.getGprsCi());
  228. latRecord.setMcc("460");
  229. latRecord.setMnc("0");
  230. latRecord.setGprsLac(item.getGprsLac());
  231. latRecord.setLat(item.getLat());
  232. latRecord.setLng(item.getLng());
  233. lonLatRecordMapper.insertSelective(latRecord);
  234. }
  235. String crcStr = input.substring(input.length() - 4);
  236. item.setCrcCode("" + reverseParseHex(crcStr));
  237. // 找寻上一条最新记录
  238. MouldHistoryExample mExp = new MouldHistoryExample();
  239. mExp.setOrderByClause("id desc limit 1");
  240. mExp.createCriteria().andEquipmentNoEqualTo(item.getEquipmentNo());
  241. List<MouldHistory> newList = mouldHistoryMapper.selectByExample(mExp);
  242. // 存入数据库
  243. mouldHistoryMapper.insertSelective(item);
  244. Integer differenceValue = 0;
  245. //计算本次的运行次数和上次的差值
  246. if(newList.size()==0){
  247. differenceValue = item.getRunCnt();
  248. }else{
  249. differenceValue = item.getRunCnt() - newList.get(0).getRunCnt();
  250. }
  251. //发送清空次数和其他指定
  252. // EquipmentSendCommandExample escExample = new EquipmentSendCommandExample();
  253. // escExample.createCriteria().andEquipmentNoEqualTo(item.getEquipmentNo()).andIsSendEqualTo(0);
  254. // List<EquipmentSendCommand> sendCommandLists = equipmentSendCommandMapper.selectByExample(escExample);
  255. // if(sendCommandLists.size()>0){
  256. // for (EquipmentSendCommand equipmentSendCommand : sendCommandLists) {
  257. // if(equipmentSendCommand.getState().intValue() == 0){
  258. // //清空指定
  259. // sendMsg(strHexStr16("#CLEAR_PROTOCOL;"));
  260. // equipmentSendCommand.setIsSend(1);
  261. // equipmentSendCommand.setSendTime(new Date());
  262. // equipmentSendCommandMapper.updateByPrimaryKeySelective(equipmentSendCommand);
  263. // }
  264. //
  265. // }
  266. // }
  267. // 模具开合记录
  268. int cnt = item.getRunCnt();
  269. int start = 69;
  270. logger.info("累计开合模次数=" + cnt);
  271. int end = input.length() - 4; // 最后2位 0xXX,0xXX ,是CRC校验位
  272. logger.info("时间信息==" + input.substring(start * 2, end));
  273. Integer thisOpenCounts = 0;
  274. //用于接受上次最新的那一条开合数据
  275. List<MouldHistoryTime> historyList = new ArrayList<>();
  276. //用于接受第一包的开合时间与上次最新一包的开合时间差值
  277. long openTimeDiff = 0L;
  278. //用于接受第一包数据
  279. // MouldHistoryTime firstMouldHistoryTime = new MouldHistoryTime();
  280. if (end - start * 2 >= 24) {// 时间最少6位,1位显示0x00,开合算两个时间,所以是6*2*2=24
  281. // 本次运行周期内的开合模次数
  282. int periodCnt = (end - start * 2) / 24;
  283. thisOpenCounts = periodCnt;
  284. logger.info("本次开合模次数==" + periodCnt);
  285. long aHeadOpenTimeLongVal = 0L;
  286. //用于接收判断是不是有包在当前包之后但已经发上来了,如16:11的开和数据先于16:10的数据先发上来
  287. // List<MouldHistoryTime> GreaterThanOpenTimeList = new ArrayList<>();
  288. for (int pos = 0; pos < periodCnt; pos++) {
  289. // 合模时间
  290. MouldHistoryTime time = new MouldHistoryTime();
  291. time.setHistoryId(item.getId());
  292. time.setEquipmentNo(item.getEquipmentNo());
  293. time.setSeq(pos + 1);
  294. Date closeTime = parseDate(input, start, pos, 0);
  295. time.setCloseTime(closeTime);
  296. // 开模时间
  297. Date openTime = parseDate(input, start, pos, 6);
  298. time.setOpenTime(openTime);
  299. logger.info("第" + (pos + 1) + "包");
  300. logger.info("本包开合时间戳--" + openTime.getTime());
  301. if (pos == 0) {
  302. MouldHistoryTimeExample mhtExp = new MouldHistoryTimeExample();
  303. //查询当前包是否是之前丢的包,判断依据,看看有没有比当前开合日期更后的开合数据
  304. // mhtExp.setOrderByClause("open_time limit 1");
  305. // mhtExp.createCriteria().andEquipmentNoEqualTo(item.getEquipmentNo()).andOpenTimeGreaterThanOrEqualTo(openTime).andIsTrueEqualTo(0);
  306. // GreaterThanOpenTimeList = mouldHistoryTimeMapper.selectByExample(mhtExp);
  307. // mhtExp.clear();
  308. mhtExp.setOrderByClause("open_time desc limit 1");
  309. mhtExp.createCriteria().andEquipmentNoEqualTo(item.getEquipmentNo()).andOpenTimeLessThanOrEqualTo(openTime);
  310. //小于当前开合时间的最新的一包开合数据
  311. historyList = mouldHistoryTimeMapper.selectByExample(mhtExp);
  312. if (historyList.size() > 0) {
  313. openTimeDiff = openTime.getTime() - historyList.get(0).getOpenTime().getTime();
  314. time.setTimeCost((int)openTimeDiff);
  315. } else {
  316. time.setTimeCost(0);
  317. }
  318. } else {
  319. logger.info("本次开合周期--" + (openTime.getTime() - aHeadOpenTimeLongVal));
  320. time.setTimeCost((int) (openTime.getTime() - aHeadOpenTimeLongVal));
  321. }
  322. mouldHistoryTimeMapper.insertSelective(time);
  323. // // 处理最后一包周期逻辑
  324. aHeadOpenTimeLongVal = openTime.getTime();
  325. // if(pos==0){
  326. // firstMouldHistoryTime = time;
  327. // }
  328. }
  329. // if(GreaterThanOpenTimeList.size()>0){
  330. // //当前数据为丢包重传的数据
  331. // logger.info("此包为之前丢的包...需要修改之前的第一包周期");
  332. // MouldHistoryTime mouldHistoryTime = GreaterThanOpenTimeList.get(0);
  333. // mouldHistoryTime.setTimeCost((int) (mouldHistoryTime.getOpenTime().getTime() - aHeadOpenTimeLongVal));
  334. // MouldHistoryTimeExample mhtExp = new MouldHistoryTimeExample();
  335. // mhtExp.createCriteria().andHistoryIdEqualTo(mouldHistoryTime.getHistoryId()).andOpenTimeEqualTo(mouldHistoryTime.getOpenTime()).andEquipmentNoEqualTo(mouldHistoryTime.getEquipmentNo());
  336. // mouldHistoryTimeMapper.updateByExampleSelective(mouldHistoryTime, mhtExp);
  337. // }
  338. // //当前包为非丢包重传的数据
  339. // Integer lossPacketCount = differenceValue - thisOpenCounts;
  340. // if(lossPacketCount>0){
  341. // logger.info("本次丢包数---->"+lossPacketCount+"_上一包开合数据数:"+historyList.size()+"_两包之间的时间差值:"+openTimeDiff);
  342. // if(historyList.size()>0){
  343. // //本次第一包开合时间与上一包最新开合数据的开合时间差值超过一分钟则判断为丢包了
  344. // if(openTimeDiff>60000){
  345. // logger.info("触发补充数据任务,时间:"+new SimpleDateFormat("yy-MM-dd,HH:mm:ss").format(new Date()));
  346. // //此时丢包了,丢了lossPacketCount个包,如果小于0则是第二包或者是之前的丢包补上来了
  347. // examineTask(item.getEquipmentNo(),lossPacketCount,firstMouldHistoryTime,historyList.get(0),pool);
  348. // }
  349. // }
  350. // }
  351. } else {
  352. logger.info("本次开合模次数==0");
  353. }
  354. // 统计该模盒的平均开合周期
  355. // MouldHistoryExample exp = new MouldHistoryExample();
  356. // exp.setOrderByClause("id");
  357. // exp.createCriteria().andEquipmentNoEqualTo(item.getEquipmentNo()).andRunCntEqualTo(item.getRunCnt());
  358. // List<MouldHistoryTime> list =
  359. // mouldHistoryTimeMapper.selectByEquipmentNoAndThanZero(item.getEquipmentNo());
  360. // List<MouldHistory> list =
  361. // mouldHistoryMapper.selectByExample(exp);
  362. // List<Long> historyIds = new ArrayList<>();
  363. // historyIds.add(-1L);
  364. // for (MouldHistory mouldHistory : list) {
  365. // historyIds.add(mouldHistory.getId());
  366. // }
  367. MouldHistoryTimeExample mtExp = new MouldHistoryTimeExample();
  368. mtExp.setOrderByClause("seq");
  369. mtExp.createCriteria().andHistoryIdEqualTo(item.getId()).andTimeCostGreaterThan(0);
  370. historyList = mouldHistoryTimeMapper.selectByExample(mtExp);
  371. int avgTime = 0;
  372. int totalTime = 0;
  373. // if (historyList.size() == 1) {
  374. // // 证明盒子动了,找寻上一条记录
  375. // if (newList.size() > 0) {
  376. // MouldHistoryTime now = historyList.get(0);
  377. // MouldHistoryTime last =
  378. // mouldHistoryTimeMapper.getDateByHistory(newList.get(0).getId());
  379. // if (null != now && null != last) {
  380. // avgTime = (int)((now.getOpenTime().getTime()) -
  381. // (last.getOpenTime().getTime()));
  382. // }
  383. // }
  384. // } else {
  385. if (historyList.size() > 1) {
  386. for (MouldHistoryTime mouldHistoryTime : historyList) {
  387. logger.info("totalTime" + totalTime);
  388. totalTime += mouldHistoryTime.getTimeCost();
  389. }
  390. logger.info("totalTime" + totalTime);
  391. avgTime = (int) (totalTime / historyList.size());
  392. }
  393. // }
  394. logger.info("avgTime-->" + avgTime);
  395. handleModLogic(item, avgTime, thisOpenCounts);
  396. // 判断预留字节的
  397. if ("02".equals(mobilePart)) {
  398. // 丢包数据已占满缓存,调用读取命令
  399. String strHexStr16 = strHexStr16("#PRINTFALL;");
  400. logger.info("丢包数据已占满缓存下发调用读取命令#PRINTFALL;==>" + strHexStr16);
  401. sendMsg(strHexStr16);
  402. return deviceNum;
  403. }
  404. // //临时下发周期矫正fa af 00 03 01 05 08 14 50 00 14 a6 22
  405. // sendMsg("fa af 00 03 01 05 08 14 50 00 14 a6 22");
  406. // logger.info("临时下发周期矫正==>" + "fa af 00 03 01 05 08 14 50 00 14 a6
  407. // 22");
  408. // 返回设备编号
  409. }
  410. return deviceNum;
  411. }
  412. // 下发切换服务器ip命令
  413. public void sendChangeIp() {
  414. ChangeIpCommandExample example = new ChangeIpCommandExample();
  415. example.createCriteria().andIsSendEqualTo(0);
  416. List<ChangeIpCommand> list = changeIpCommandMapper.selectByExample(example);
  417. if (!CollectionUtils.isEmpty(list)) {
  418. ChangeIpCommand changeIpCommand = list.get(0);
  419. // #IPADDS=58.213.104.114:9090;
  420. // 下发切换服务器命令
  421. StringBuffer sb = new StringBuffer();
  422. sb.append("#IPADDS=").append(changeIpCommand.getIp()).append(":").append(changeIpCommand.getPort())
  423. .append(";");
  424. logger.info("开始下发切换服务器命令字符串为;==>" + sb.toString());
  425. String strHexStr16 = strHexStr16(sb.toString());
  426. logger.info("下发切换服务器ip转换后的16进制为;==>" + strHexStr16);
  427. sendMsg(strHexStr16);
  428. // 下发完修改状态为已下发
  429. changeIpCommand.setIsSend(1);
  430. changeIpCommandMapper.updateByPrimaryKeySelective(changeIpCommand);
  431. }
  432. }
  433. public void sendPackage(String equipmentNo) {
  434. if (equipmentNo.indexOf("FAAF") != -1) {
  435. logger.info("非法云模盒编号,不作下发处理");
  436. return;
  437. }
  438. MouldDownPacketExample exp = new MouldDownPacketExample();
  439. exp.createCriteria().andEquipmentNoEqualTo(equipmentNo).andPacketStrNotEqualTo("CLEAR_PROTOCOL");
  440. List<MouldDownPacket> list = mouldDownPacketMapper.selectByExample(exp);
  441. if (list.size() > 0) {
  442. MouldDownPacket packet = list.get(0);
  443. TbMouldEquipmentExample meqExp = new TbMouldEquipmentExample();
  444. meqExp.createCriteria().andEquipmentNoEqualTo(equipmentNo);
  445. long count = tbMouldEquipmentMapper.countByExample(meqExp);
  446. // 下发数据包,下发完后修改状态
  447. logger.info("开始下发数据包==>" + packet.getPacketStr());
  448. sendMsg(packet.getPacketStr());
  449. if (null != packet.getThreshold()) {
  450. // 下发阈值命令
  451. sendMsg(strHexStr16("#LIMIT VALUE=" + packet.getThreshold()));
  452. }
  453. if (count > 0) {
  454. TbMouldEquipment me = tbMouldEquipmentMapper.selectByExample(meqExp).get(0);
  455. TbMouldEquipment tme = new TbMouldEquipment();
  456. tme.setId(me.getId());
  457. tme.setIsUse(packet.getIsUse());
  458. tbMouldEquipmentMapper.updateByPrimaryKeySelective(tme);
  459. logger.info("将启用中的云模盒改为启用成功==>" + me.getEquipmentNo());
  460. }
  461. // 下发完删除数据
  462. mouldDownPacketMapper.deleteByPrimaryKey(packet.getId());
  463. }
  464. }
  465. public void timeCalibration(String equipmentNo) {
  466. // logger.info("下发校准时间的云模盒equipmentNo"+equipmentNo);
  467. if (equipmentNo.indexOf("FAAF") != -1) {
  468. logger.info("非法云模盒编号,不作下发处理");
  469. return;
  470. }
  471. List<TimeCalibrationRecord> count = timeCalibrationRecordMapper.selectCountByToday(equipmentNo);
  472. // 今天未校准时间,下发时间校准,已经校准过了,则不再校准
  473. if (count.size() == 0) {
  474. Date date = new Date();
  475. SimpleDateFormat sdf = new SimpleDateFormat("yy-MM-dd,HH:mm:ss");
  476. String dateStr = sdf.format(date);
  477. dateStr = "#TIME=" + dateStr + ";";
  478. // #TIME=18-03-06,15:31:48;
  479. logger.info("校准系统模块时间==>" + dateStr);
  480. // 将字符串转成16进制字符串
  481. String strHexStr16 = strHexStr16(dateStr);
  482. logger.info("校准系统模块时间转成16进制的字符串==>" + strHexStr16);
  483. sendMsg(strHexStr16);
  484. TimeCalibrationRecord timeCalibrationRecord = new TimeCalibrationRecord();
  485. timeCalibrationRecord.setIndate(new Date());
  486. timeCalibrationRecord.setEquipmentNo(equipmentNo);
  487. timeCalibrationRecordMapper.insertSelective(timeCalibrationRecord);
  488. }
  489. }
  490. private void handleModLogic(MouldHistory item, int avgTime, Integer thisOpenCount) {
  491. logger.info("进了handleModLogic逻辑--");
  492. logger.info("item==>" + item);
  493. TbMouldEquipmentExample meqExp = new TbMouldEquipmentExample();
  494. meqExp.createCriteria().andEquipmentNoEqualTo(item.getEquipmentNo());
  495. if (tbMouldEquipmentMapper.countByExample(meqExp) > 0) {
  496. TbMouldEquipment me = tbMouldEquipmentMapper.selectByExample(meqExp).get(0);
  497. me.setCurhillNumber(item.getBattery() + "");
  498. if (item.getLng() != null) {
  499. logger.info("更新经纬度:");
  500. me.setLng(Double.parseDouble(item.getLng()));
  501. me.setLat(Double.parseDouble(item.getLat()));
  502. }
  503. me.setCurtemperature(item.getTemperature());
  504. if (item.getAlarm() == 8) {
  505. me.setStage(3);// 安装被拆
  506. } else if (item.getAlarm() == 1) {
  507. me.setStage(2);// 低电量
  508. } else if (item.getAlarm() == 2) {
  509. me.setStage(1);// 高温
  510. } else {
  511. me.setStage(item.getAlarm());
  512. }
  513. // 处理报警
  514. if (item.getAlarm() > 0) {
  515. /**
  516. * 无报警 0; 低电量报警 1; 温度过热 2; 安装被拆 8。
  517. */
  518. logger.info("设备报警啦:" + item.getAlarm());
  519. }
  520. tbMouldEquipmentMapper.updateByPrimaryKeySelective(me);
  521. logger.info("更新完了tbMouldEquipment的状态和温度以及经纬度");
  522. TbMouldExample tExp = new TbMouldExample();
  523. tExp.setOrderByClause("id desc limit 1");
  524. tExp.createCriteria().andEquipmentIdEqualTo(me.getId());
  525. if (tbMouldMapper.countByExample(tExp) > 0) {
  526. logger.info("准备更新运行次数:");
  527. TbMould tm = tbMouldMapper.selectByExample(tExp).get(0);
  528. MouldHistoryTimeExample mhtExp = new MouldHistoryTimeExample();
  529. // 一次接受到数据,超过5次开合标记为运行状态
  530. if (thisOpenCount > 5) {
  531. tm.setState(item.getStatus());
  532. } else {
  533. tm.setState("0");
  534. }
  535. // 云模盒运行次数+模具的历史运行次数
  536. tm.setRunTimes(item.getRunCnt() + tm.getHistoryRunTimes());
  537. tm.setLastRecTime(new Date());
  538. // 处理每模平均周期(单位秒)
  539. if (0 != avgTime) {
  540. logger.info("开始修改平均每模周期值为:" + avgTime);
  541. BigDecimal bd = new BigDecimal(avgTime * 1.00 / 1000);
  542. tm.setOcCycle(bd);
  543. }
  544. tbMouldMapper.updateByPrimaryKeySelective(tm);
  545. }
  546. }
  547. }
  548. /**
  549. * 低位在前的16进制解析
  550. *
  551. * @param rHex
  552. * @return
  553. */
  554. public static int reverseParseHex(String rHex) {
  555. int size = rHex.length() / 2;
  556. StringBuilder sb = new StringBuilder();
  557. for (int i = 0; i < size; i++) {
  558. sb.append(rHex.substring((size - i - 1) * 2, (size - i) * 2));
  559. }
  560. String str = sb.toString();
  561. return Integer.parseInt(str, 16);
  562. }
  563. private static Date parseDate(String input, int start, int pos, int dateStartPos) {
  564. // pos为开合的一组的下标,一个开合时间占位是12*2
  565. String year = input.substring((start + pos * 12 + dateStartPos) * 2, (start + pos * 12 + 1 + dateStartPos) * 2);
  566. String month = input.substring((start + pos * 12 + 1 + dateStartPos) * 2,
  567. (start + pos * 12 + 2 + dateStartPos) * 2);
  568. String day = input.substring((start + pos * 12 + 2 + dateStartPos) * 2,
  569. (start + pos * 12 + 3 + dateStartPos) * 2);
  570. String hh = input.substring((start + pos * 12 + 3 + dateStartPos) * 2,
  571. (start + pos * 12 + 4 + dateStartPos) * 2);
  572. String mm = input.substring((start + pos * 12 + 4 + dateStartPos) * 2,
  573. (start + pos * 12 + 5 + dateStartPos) * 2);
  574. String ss = input.substring((start + pos * 12 + 5 + dateStartPos) * 2,
  575. (start + pos * 12 + 6 + dateStartPos) * 2);
  576. StringBuilder sb = new StringBuilder();
  577. int yearInt = Integer.parseInt(year, 16);
  578. if (yearInt == 0) {
  579. sb.append("2019-01-01");
  580. } else {
  581. sb.append(yearInt < 100 ? "20" : "2");
  582. sb.append(yearInt).append("-");
  583. int monthInt = Integer.parseInt(month, 16);
  584. sb.append(monthInt < 10 ? "0" : "").append(monthInt).append("-");
  585. int dayInt = Integer.parseInt(day, 16);
  586. sb.append(dayInt < 10 ? "0" : "").append(dayInt);
  587. }
  588. Date parseDate = null;
  589. try {
  590. parseDate = new SimpleDateFormat("yyyy-MM-dd").parse(sb.toString());
  591. parseDate.setHours(Integer.parseInt(hh, 16));
  592. parseDate.setMinutes(Integer.parseInt(mm, 16));
  593. parseDate.setSeconds(Integer.parseInt(ss, 16));
  594. } catch (ParseException e) {
  595. e.printStackTrace();
  596. }
  597. return parseDate;
  598. }
  599. // private void handleMouldCycleRuntimeLogic(Date openTime, MouldHistory
  600. // item) throws ParseException {
  601. // System.out.println(
  602. // "开始handleMouldCycleRuntimeLogic逻辑开合时间" + new SimpleDateFormat("yyyy-MM-dd
  603. // HH:mm:ss").format(openTime));
  604. // MouldCycleRuntime mcr = new MouldCycleRuntime();
  605. // SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
  606. // mcr.setDateStr(sdf.format(openTime));
  607. // Integer hours = openTime.getHours();
  608. // SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:");
  609. // int housTime = openTime.getHours() - 1;
  610. // openTime.setHours(housTime);
  611. // String lastOpenTime = sdf1.format(openTime);
  612. // Date lastOpenTimeDate = sdf1.parse(lastOpenTime);
  613. // // 此处直接拼接字符串“59:59”会导致分和秒丢失,所以才去set的方法设置时分秒
  614. // lastOpenTimeDate.setMinutes(59);
  615. // lastOpenTimeDate.setSeconds(59);
  616. // logger.info("当前开合时间减一小时的时间条件:" + new SimpleDateFormat("yyyy-MM-dd
  617. // HH:mm:ss").format(lastOpenTimeDate));
  618. // MouldHistoryTimeExample mExp = new MouldHistoryTimeExample();
  619. // mExp.setOrderByClause("open_time desc limit 1");
  620. // mExp.createCriteria().andEquipmentNoEqualTo(item.getEquipmentNo())
  621. // .andOpenTimeLessThanOrEqualTo(lastOpenTimeDate);
  622. // List<MouldHistoryTime> list =
  623. // mouldHistoryTimeMapper.selectByExample(mExp);
  624. // logger.info("满足条件的上一个小数数据集合长度:" + list.size());
  625. // if (list.size() > 0) {
  626. // MouldHistory mouldHistory =
  627. // mouldHistoryMapper.selectByPrimaryKey(list.get(0).getHistoryId());
  628. // logger.info("本次运行次数: " + item.getRunCnt() + " 上一小时的运行次数:" +
  629. // mouldHistory.getRunCnt() + " 上一小时的historyId:"
  630. // + mouldHistory.getId());
  631. // mcr.setEquipmentNo(item.getEquipmentNo());
  632. // mcr.setRuntime(item.getRunCnt() - mouldHistory.getRunCnt());
  633. // if (hours == 0) {
  634. // mcr.setTimeSlot("00:00-01:00");
  635. // } else if (hours == 1) {
  636. // mcr.setTimeSlot("01:00-02:00");
  637. // } else if (hours == 2) {
  638. // mcr.setTimeSlot("02:00-03:00");
  639. // } else if (hours == 3) {
  640. // mcr.setTimeSlot("03:00-04:00");
  641. // } else if (hours == 4) {
  642. // mcr.setTimeSlot("04:00-05:00");
  643. // } else if (hours == 5) {
  644. // mcr.setTimeSlot("05:00-06:00");
  645. // } else if (hours == 6) {
  646. // mcr.setTimeSlot("06:00-07:00");
  647. // } else if (hours == 7) {
  648. // mcr.setTimeSlot("07:00-08:00");
  649. // } else if (hours == 8) {
  650. // mcr.setTimeSlot("08:00-09:00");
  651. // } else if (hours == 9) {
  652. // mcr.setTimeSlot("09:00-10:00");
  653. // } else if (hours == 10) {
  654. // mcr.setTimeSlot("10:00-11:00");
  655. // } else if (hours == 11) {
  656. // mcr.setTimeSlot("11:00-12:00");
  657. // } else if (hours == 12) {
  658. // mcr.setTimeSlot("12:00-13:00");
  659. // } else if (hours == 13) {
  660. // mcr.setTimeSlot("13:00-14:00");
  661. // } else if (hours == 14) {
  662. // mcr.setTimeSlot("14:00-15:00");
  663. // } else if (hours == 15) {
  664. // mcr.setTimeSlot("15:00-16:00");
  665. // } else if (hours == 16) {
  666. // mcr.setTimeSlot("16:00-17:00");
  667. // } else if (hours == 17) {
  668. // mcr.setTimeSlot("17:00-18:00");
  669. // } else if (hours == 18) {
  670. // mcr.setTimeSlot("18:00-19:00");
  671. // } else if (hours == 19) {
  672. // mcr.setTimeSlot("19:00-20:00");
  673. // } else if (hours == 20) {
  674. // mcr.setTimeSlot("20:00-21:00");
  675. // } else if (hours == 21) {
  676. // mcr.setTimeSlot("21:00-22:00");
  677. // } else if (hours == 22) {
  678. // mcr.setTimeSlot("22:00-23:00");
  679. // } else if (hours == 23) {
  680. // mcr.setTimeSlot("23:00-00:00");
  681. // }
  682. // MouldCycleRuntimeExample mcrExp = new MouldCycleRuntimeExample();
  683. // mcrExp.createCriteria().andDateStrEqualTo(mcr.getDateStr()).andEquipmentNoEqualTo(item.getEquipmentNo())
  684. // .andTimeSlotEqualTo(mcr.getTimeSlot());
  685. // List<MouldCycleRuntime> mList =
  686. // mouldCycleRuntimeMapper.selectByExample(mcrExp);
  687. // if (mList.size() > 0) {
  688. // mcr.setId(mList.get(0).getId());
  689. // mouldCycleRuntimeMapper.updateByPrimaryKeySelective(mcr);
  690. // } else {
  691. // mouldCycleRuntimeMapper.insertSelective(mcr);
  692. // }
  693. // }
  694. // }
  695. private static String getStringFromHexStr(String hexStr) {
  696. StringBuilder sb = new StringBuilder();
  697. for (int i = 0; i < hexStr.length() / 2; i++) {
  698. String str = "0x" + hexStr.substring(i * 2, i * 2 + 2);
  699. int intVal = Integer.decode(str).intValue();
  700. char c = (char) intVal;
  701. sb.append(c);
  702. }
  703. return sb.toString();
  704. }
  705. public void close() {
  706. ctx.close();
  707. }
  708. public void sendMsg(String hexString) {
  709. System.out.println("发送消息==" + hexString);
  710. byte[] buffer = hexStrToBinaryStr(hexString);
  711. ByteBuf bf = Unpooled.buffer(hexString.length() / 2);
  712. bf.writeBytes(buffer);
  713. ctx.writeAndFlush(bf);
  714. // ctx.close();
  715. }
  716. //检查是否丢包,并插入丢包数据
  717. /**
  718. * @param equipmentNo 云模合编号
  719. * @param loseCount 丢包数量
  720. * @param firstMouldHistoryTime 本次的第一条开合数据
  721. * @param lastEndMouldHistoryTime 上一包最后一条开合数据
  722. * @param pool 线程池
  723. */
  724. // public void examineTask(String equipmentNo,int loseCount,MouldHistoryTime firstMouldHistoryTime,MouldHistoryTime lastEndMouldHistoryTime,ScheduledExecutorService pool){
  725. // pool.schedule(new Runnable() {
  726. // @Override
  727. // public void run() {
  728. // SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd,HH:mm:ss");
  729. // logger.info("定时补充数据任务开始了,时间:"+sdf.format(new Date()));
  730. // MouldHistoryTimeExample mhtExp = new MouldHistoryTimeExample();
  731. // mhtExp.createCriteria().andOpenTimeGreaterThan(lastEndMouldHistoryTime.getOpenTime()).andOpenTimeLessThan(firstMouldHistoryTime.getOpenTime());
  732. // long count = mouldHistoryTimeMapper.countByExample(mhtExp);
  733. // logger.info(sdf.format(lastEndMouldHistoryTime.getOpenTime())+"--"+sdf.format(firstMouldHistoryTime.getOpenTime())+"时间段内丢包时间段上来了"+count+"条数据");
  734. // if(count==loseCount){
  735. // return;
  736. // }else{
  737. // TbMouldEquipmentExample tExp = new TbMouldEquipmentExample();
  738. // tExp.createCriteria().andEquipmentNoEqualTo(equipmentNo);
  739. // List<TbMouldEquipment> equipments = tbMouldEquipmentMapper.selectByExample(tExp);
  740. // if(equipments.size()>0){
  741. // TbMouldExample tmExp = new TbMouldExample();
  742. // tmExp.createCriteria().andEquipmentIdEqualTo(equipments.get(0).getId());
  743. // List<TbMould> moulds = tbMouldMapper.selectByExample(tmExp);
  744. // MouldHistoryTime newMouldHistoryTime = new MouldHistoryTime();
  745. // if(moulds.size()>0){
  746. // //平均开合周期
  747. // int OcCycle = (int)moulds.get(0).getOcCycle().doubleValue()*1000;
  748. // long addPacketCount = loseCount-count;
  749. // logger.info("补包数->"+addPacketCount);
  750. // long openTime = 0L;
  751. // long closeTime = 0L;
  752. // if(addPacketCount<loseCount){
  753. // mhtExp.clear();
  754. // mhtExp.setOrderByClause("open_time desc limit 1");
  755. // mhtExp.createCriteria().andOpenTimeGreaterThanOrEqualTo(lastEndMouldHistoryTime.getOpenTime()).andOpenTimeLessThan(firstMouldHistoryTime.getOpenTime());
  756. // List<MouldHistoryTime> newMouldHistoryTimes = mouldHistoryTimeMapper.selectByExample(mhtExp);
  757. // newMouldHistoryTime = newMouldHistoryTimes.get(0);
  758. // openTime = newMouldHistoryTime.getOpenTime().getTime();
  759. // closeTime = newMouldHistoryTime.getCloseTime().getTime();
  760. // }else{
  761. // newMouldHistoryTime = lastEndMouldHistoryTime;
  762. // openTime = newMouldHistoryTime.getOpenTime().getTime();
  763. // closeTime = newMouldHistoryTime.getCloseTime().getTime();
  764. // }
  765. // for(int i=0;i<addPacketCount;i++){
  766. // MouldHistoryTime m = new MouldHistoryTime();
  767. // m.setCloseTime(new Date(closeTime+OcCycle));
  768. // m.setOpenTime(new Date(openTime+OcCycle));
  769. // m.setIsTrue(1);
  770. // m.setEquipmentNo(equipmentNo);
  771. // m.setHistoryId(newMouldHistoryTime.getHistoryId());
  772. // m.setSeq(i+1);
  773. // m.setTimeCost(OcCycle);
  774. // mouldHistoryTimeMapper.insertSelective(m);
  775. // openTime = m.getOpenTime().getTime();
  776. // closeTime = m.getCloseTime().getTime();
  777. // if(i==addPacketCount-1){
  778. // MouldHistoryTime mouldHistoryTime = firstMouldHistoryTime;
  779. // mouldHistoryTime.setTimeCost((int) (mouldHistoryTime.getOpenTime().getTime() - m.getOpenTime().getTime()));
  780. // MouldHistoryTimeExample exp = new MouldHistoryTimeExample();
  781. // exp.createCriteria().andHistoryIdEqualTo(mouldHistoryTime.getHistoryId()).andOpenTimeEqualTo(mouldHistoryTime.getOpenTime()).andEquipmentNoEqualTo(mouldHistoryTime.getEquipmentNo());
  782. // mouldHistoryTimeMapper.updateByExampleSelective(mouldHistoryTime, exp);
  783. // }
  784. // }
  785. // }
  786. // }
  787. // }
  788. // }
  789. // }, 2, TimeUnit.HOURS);
  790. //
  791. // }
  792. /**
  793. * channel被激活时调用
  794. */
  795. @Override
  796. public void channelActive(ChannelHandlerContext ctx) {
  797. // TODO Auto-generated method stub
  798. this.ctx = ctx;
  799. System.out.println("==========Active=========" + ctx.channel().localAddress().toString() + ", connection num="
  800. + HelloServer.deviceMap.size());
  801. }
  802. @Override
  803. public void channelInactive(ChannelHandlerContext ctx) throws Exception {
  804. super.channelInactive(ctx);
  805. System.out.println("==========Inactive=========");
  806. }
  807. @Override
  808. public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
  809. // TODO Auto-generated method stub
  810. super.handlerRemoved(ctx);
  811. System.out.println("[YunSu]handlerRemoved=掉线了===");
  812. }
  813. @Override
  814. public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
  815. // TODO Auto-generated method stub
  816. super.exceptionCaught(ctx, cause);
  817. System.out.println("我捕捉到异常信息了");
  818. }
  819. @Override
  820. public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
  821. if (evt instanceof IdleStateEvent) {
  822. IdleStateEvent event = (IdleStateEvent) evt;
  823. if (event.state().equals(IdleState.READER_IDLE)) {
  824. } else if (event.state().equals(IdleState.WRITER_IDLE)) {
  825. // System.out.println("WRITER_IDLE=="+userInfo.getWxName());
  826. // logger.debug(ctx.channel().remoteAddress().toString()+
  827. // "WRITER_IDLE");
  828. // 超时关闭channel
  829. // ctx.close();
  830. } else if (event.state().equals(IdleState.ALL_IDLE)) {
  831. // 发送心跳
  832. ctx.channel().writeAndFlush("$&_".toString());
  833. }
  834. }
  835. // super.userEventTriggered(ctx, evt);
  836. }
  837. /**
  838. * 将十六进制的字符串转换成字节数组
  839. *
  840. * @param hexString
  841. * @return
  842. */
  843. public static byte[] hexStrToBinaryStr(String hexString) {
  844. if (hexString == null || "".contentEquals(hexString)) {
  845. return null;
  846. }
  847. hexString = hexString.replaceAll(" ", "");
  848. int len = hexString.length();
  849. int index = 0;
  850. byte[] bytes = new byte[len / 2];
  851. while (index < len) {
  852. String sub = hexString.substring(index, index + 2);
  853. bytes[index / 2] = (byte) Integer.parseInt(sub, 16);
  854. index += 2;
  855. }
  856. return bytes;
  857. }
  858. /**
  859. * 将字节数组转换成十六进制的字符串
  860. *
  861. * @return
  862. */
  863. public static String BinaryToHexString(byte[] bytes) {
  864. String hexStr = "0123456789ABCDEF";
  865. String result = "";
  866. String hex = "";
  867. for (byte b : bytes) {
  868. hex = String.valueOf(hexStr.charAt((b & 0xF0) >> 4));
  869. hex += String.valueOf(hexStr.charAt(b & 0x0F));
  870. result += hex + " ";
  871. }
  872. return result;
  873. }
  874. /**
  875. * 普通字符串转16进制字符串
  876. *
  877. * @param str
  878. * @return
  879. */
  880. public static String strHexStr16(String str) {
  881. char[] chars = "0123456789ABCDEF".toCharArray();
  882. StringBuilder sb = new StringBuilder("");
  883. byte[] bs = str.getBytes();
  884. int bit;
  885. for (int i = 0; i < bs.length; i++) {
  886. bit = (bs[i] & 0x0f0) >> 4;
  887. sb.append(chars[bit]);
  888. bit = bs[i] & 0x0f;
  889. sb.append(chars[bit]);
  890. // sb.append(' ');
  891. }
  892. return sb.toString().trim();
  893. }
  894. // 转换16进制字符串低位在前,高位在后 成 高位在前,低位在后
  895. public static String highInFrontLowInBack(String result) {
  896. return result.substring(2, 4) + result.substring(0, 2);// 高位在前,低位在后
  897. }
  898. public static void main(String[] args) throws ParseException {
  899. // System.out.println(Integer.parseInt(getStringFromHexStr("0107"),
  900. // 16));
  901. // UserHandler h = new UserHandler();
  902. // h.timeCalibration();
  903. // SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:");
  904. // Date date = new Date();
  905. // String lastOpenTime = sdf1.format(date);
  906. // System.out.println(lastOpenTime);
  907. // Date lastOpenTimeDate = sdf1.parse(lastOpenTime);
  908. // lastOpenTimeDate.setMinutes(59);
  909. // lastOpenTimeDate.setSeconds(59);
  910. // System.out.println(new SimpleDateFormat("yyyy-MM-dd
  911. // HH:mm:ss").format(lastOpenTimeDate));
  912. // String a = "00:25:32";
  913. // SimpleDateFormat s = new SimpleDateFormat("HH:mm:ss");
  914. // Date d = new Date();
  915. // System.out.println(s.parse(a).getHours());
  916. // Date date = new Date();
  917. // SimpleDateFormat sdf = new SimpleDateFormat("yy-MM-dd,HH:mm:ss");
  918. // String dateStr = sdf.format(date);
  919. // dateStr = "#TIME="+dateStr+";";
  920. // System.out.println(dateStr);
  921. // //#TIME=18-03-06,15:31:48;
  922. // logger.info("校准系统模块时间==>"+dateStr);
  923. // String reverseParseHex = strHexStr16(dateStr);
  924. // System.out.println("reverseParseHex-----"+reverseParseHex);
  925. // String str = "1F51";
  926. // String input =
  927. // "FAAF530000000000000000000000003137333030303239343310010000000000000000000"
  928. // + "000000000000000000000001F51E85F00000000000045004A" +
  929. // "54000100110000001308160F171F1308160F2D188FCA";
  930. // String temp = "0x"+str;
  931. // int i = Integer.decode(temp);
  932. // System.out.println(i);
  933. // int p = reverseParseHex(str);
  934. // System.out.println(p);
  935. // int start = 69;
  936. // System.out.println(str.substring(69*2));
  937. // Date d = parseDate(str, start, 0, 0);
  938. // System.out.println(d.toGMTString());
  939. // int start = 69;
  940. // int end = input.length() - 4; // 最后2位 0xXX,0xXX ,是CRC校验位
  941. // logger.info("时间信息==" + input.substring(start * 2, end));
  942. // if (end - start * 2 >= 24) {// 时间最少6位,1位显示0x00,开合算两个时间,所以是6*2*2=24
  943. // // 本次运行周期内的开合模次数
  944. // int periodCnt = (end - start * 2) / 24;
  945. // logger.info("本次开合模次数==" + periodCnt);
  946. // for (int pos = 0; pos < periodCnt; pos++) {
  947. // // 合模时间
  948. // MouldHistoryTime time = new MouldHistoryTime();
  949. // time.setSeq(pos + 1);
  950. // Date closeTime = parseDate(input, start, pos, 0);
  951. // System.out.println(closeTime);
  952. // time.setCloseTime(closeTime);
  953. // // 开模时间
  954. // Date openTime = parseDate(input, start, pos, 6);
  955. // time.setOpenTime(openTime);
  956. // System.out.println(openTime);
  957. // int timeCost = (int) (openTime.getTime() - closeTime.getTime());
  958. // time.setTimeCost(timeCost);
  959. // }
  960. // } else {
  961. // logger.info("本次开合模次数==0");
  962. // }
  963. // String api = "http://api.cellocation.com:81/cell/?mcc=460&mnc=0&lac="
  964. // + 21855
  965. // + "&ci="
  966. // + 4823 + "&output=json";
  967. // String resp = com.js.kbt.util.HttpRequest.sendGet(api, null);
  968. // JSONObject json = JSONObject.parseObject(resp);
  969. // System.out.println(json);
  970. // if (json != null && json.getInteger("errcode") == 0) {
  971. // sys
  972. // item.setLng(json.getDouble("lon") + "");
  973. // item.setLat(json.getDouble("lat") + "");
  974. // } else {
  975. // logger.error("调用基站解析平台出错: " + resp);
  976. // }
  977. // String ret =
  978. // "FAAF070100383938363034313631323138383035383439363831010000000000000000000000000000000000000000005F55D7120600000000003D644734000200300100001204020F151D1204020F152F14010A00212914010A00220014010A00220214010A00221314010A00221514010A00222A14010A00222B14010A00230114010A00230314010A00231714010A00231A14010A00232A14010A00232C14010A00240514010A00241A14010A00242C14010A00242F14010A00250714010A00250A14010A00251C14010A00251D14010A00252F14010A00253114010A00260814010A00260A14010A00261C14010A00261E14010A00263114010A00263314010A00270BFA8E";
  979. // List<String> strList = new ArrayList<>();
  980. // while (ret.length() > 0) {
  981. // String subStr = ret.substring(0,
  982. // Integer.parseInt(highInFrontLowInBack(ret.substring((2) * 2, (4) *
  983. // 2)), 16) * 2);
  984. // strList.add(subStr);
  985. // ret = ret.substring(subStr.length());
  986. // System.out.println(ret);
  987. // }
  988. // System.out.println("while執行完了");
  989. // System.out.println(strList);
  990. System.out.println(strHexStr16("#CLEAR_PROTOCOL"));
  991. }
  992. }