UserHandler.java 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726
  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 com.alibaba.fastjson.JSONObject;
  12. import com.js.kbt.mapper.LonLatRecordMapper;
  13. import com.js.kbt.mapper.MouldCycleRuntimeMapper;
  14. import com.js.kbt.mapper.MouldDownPacketMapper;
  15. import com.js.kbt.mapper.MouldHistoryMapper;
  16. import com.js.kbt.mapper.MouldHistoryTimeMapper;
  17. import com.js.kbt.mapper.MouldHodingMapper;
  18. import com.js.kbt.mapper.RecDataLogMapper;
  19. import com.js.kbt.mapper.SensorThresholdMapper;
  20. import com.js.kbt.mapper.TbFactoryMapper;
  21. import com.js.kbt.mapper.TbMouldEquipmentMapper;
  22. import com.js.kbt.mapper.TbMouldMapper;
  23. import com.js.kbt.mapper.TimeCalibrationRecordMapper;
  24. import com.js.kbt.model.LonLatRecord;
  25. import com.js.kbt.model.LonLatRecordExample;
  26. import com.js.kbt.model.MouldCycleRuntime;
  27. import com.js.kbt.model.MouldCycleRuntimeExample;
  28. import com.js.kbt.model.MouldDownPacket;
  29. import com.js.kbt.model.MouldDownPacketExample;
  30. import com.js.kbt.model.MouldHistory;
  31. import com.js.kbt.model.MouldHistoryExample;
  32. import com.js.kbt.model.MouldHistoryTime;
  33. import com.js.kbt.model.MouldHistoryTimeExample;
  34. import com.js.kbt.model.RecDataLog;
  35. import com.js.kbt.model.SensorThreshold;
  36. import com.js.kbt.model.SensorThresholdExample;
  37. import com.js.kbt.model.TbMould;
  38. import com.js.kbt.model.TbMouldEquipment;
  39. import com.js.kbt.model.TbMouldEquipmentExample;
  40. import com.js.kbt.model.TbMouldExample;
  41. import com.js.kbt.model.TimeCalibrationRecord;
  42. import io.netty.buffer.ByteBuf;
  43. import io.netty.buffer.Unpooled;
  44. import io.netty.channel.ChannelHandlerContext;
  45. import io.netty.channel.SimpleChannelInboundHandler;
  46. import io.netty.handler.timeout.IdleState;
  47. import io.netty.handler.timeout.IdleStateEvent;
  48. @Service("userHandler")
  49. public class UserHandler extends SimpleChannelInboundHandler<String> {
  50. private static final Logger logger = Logger.getLogger(UserHandler.class);
  51. private ChannelHandlerContext ctx;
  52. @Resource
  53. private MouldHistoryMapper mouldHistoryMapper;
  54. @Resource
  55. private MouldHistoryTimeMapper mouldHistoryTimeMapper;
  56. @Resource
  57. private TbMouldMapper tbMouldMapper;
  58. @Resource
  59. private TbMouldEquipmentMapper tbMouldEquipmentMapper;
  60. @Resource
  61. private TbFactoryMapper tbFactoryMapper;
  62. @Resource
  63. private MouldHodingMapper mouldHodingMapper;
  64. @Resource
  65. private MouldDownPacketMapper mouldDownPacketMapper;
  66. @Resource
  67. private TimeCalibrationRecordMapper timeCalibrationRecordMapper;
  68. @Resource
  69. private MouldCycleRuntimeMapper mouldCycleRuntimeMapper;
  70. @Resource
  71. private SensorThresholdMapper sensorThresholdMapper;
  72. @Resource
  73. private RecDataLogMapper recDataLogMapper;
  74. @Resource
  75. private LonLatRecordMapper lonLatRecordMapper;
  76. @Override
  77. protected void channelRead0(ChannelHandlerContext arg0, String arg1) throws ParseException {
  78. String pack = "FAAF0007001e781e50003C37D5";
  79. // 校准时间
  80. timeCalibration();
  81. System.out.println("收到===" + arg1 + "\n");
  82. String equipmentNo = processMsg(arg1);
  83. // 以下是配置下行数据
  84. sendPackage(equipmentNo);
  85. }
  86. private String processMsg(String input) throws ParseException {
  87. String ret = "FA AF 00 07 02 1e 78 1e 50 00 3C";
  88. ret.replaceAll(" ", "");
  89. logger.info("=====接收到======" + input);
  90. if (!input.startsWith("FAAF")) {
  91. logger.info("非云模盒消息,不处理");
  92. return ret;
  93. }
  94. RecDataLog logItem = new RecDataLog();
  95. logItem.setRecData(input);
  96. recDataLogMapper.insertSelective(logItem);
  97. MouldHistory item = new MouldHistory();
  98. // 抽取手机号码4-5(预留)丢包情况硬件会上报状态01,服务器判断02时候下发printall
  99. String mobilePart = input.substring(4 * 2, 5 * 2);
  100. System.out.println("原始mobile=" + mobilePart);
  101. String mobile = getStringFromHexStr(mobilePart);
  102. System.out.println("手机号码为" + mobile);
  103. item.setSim(mobile);
  104. // 获取设备编码15-24
  105. String deviceNumPart = input.substring(5 * 2, 25 * 2);
  106. String deviceNum = getStringFromHexStr(deviceNumPart);
  107. System.out.println("设备No=" + deviceNum);
  108. item.setEquipmentNo(deviceNum);
  109. // 发送数据包
  110. MouldDownPacketExample pExp = new MouldDownPacketExample();
  111. pExp.createCriteria().andEquipmentNoEqualTo(deviceNum);
  112. List<MouldDownPacket> packetList = mouldDownPacketMapper.selectByExample(pExp);
  113. if (packetList.size() > 0) {
  114. MouldDownPacket packet = packetList.get(0);
  115. logger.info("开始下发数据包==>" + packet.getPacketStr());
  116. sendMsg(packet.getPacketStr());
  117. // 下发完就将数据删除(防止后续数据过大造成性能的影响)
  118. mouldDownPacketMapper.deleteByPrimaryKey(packet.getId());
  119. logger.info("判断是否开启或关闭已结束==>");
  120. }
  121. // 软件版本号25
  122. String version = input.substring(25 * 2, 26 * 2);
  123. System.out.println("软件版本号=" + version);
  124. item.setVersion(version);
  125. String status = input.substring(26 * 2, 27 * 2);
  126. System.out.println("工作状态=" + status);
  127. item.setStatus(Integer.decode("0x" + status).toString());
  128. // 经度27-37
  129. String longitude = getStringFromHexStr(input.substring(27 * 2, 38 * 2));
  130. System.out.println("经度=" + longitude);
  131. item.setLng(longitude);
  132. // 38-47纬度以 N 开头
  133. String latitude = getStringFromHexStr(input.substring(38 * 2, 48 * 2));
  134. System.out.println("纬度=" + latitude);
  135. item.setLat(latitude);
  136. System.out.println("==lac" + reverseParseHex(input.substring(48 * 2, 50 * 2)));
  137. System.out.println("==ci" + reverseParseHex(input.substring(50 * 2, 52 * 2)));
  138. item.setGprsLac("" + reverseParseHex(input.substring(48 * 2, 50 * 2)));
  139. item.setGprsCi("" + reverseParseHex(input.substring(50 * 2, 52 * 2)));
  140. item.setWifiBbsid(input.substring(52 * 2, 58 * 2));
  141. String temp = "0x" + input.substring(58 * 2, 59 * 2);
  142. System.out.println(temp);
  143. int i = Integer.decode(temp) - 40;
  144. System.out.println(i);
  145. logger.info("温度-----------》: " + i);
  146. item.setTemperature(i);
  147. item.setBattery(Integer.decode("0x" + input.substring(59 * 2, 60 * 2)));
  148. item.setSig2g(Integer.decode("0x" + input.substring(60 * 2, 61 * 2)));
  149. item.setSigNb(Integer.decode("0x" + input.substring(61 * 2, 62 * 2)));
  150. item.setSigWifi(Integer.decode("0x" + input.substring(62 * 2, 63 * 2)));
  151. item.setExt0("" + Integer.decode("0x" + input.substring(63 * 2, 64 * 2)));
  152. item.setAlarm(Integer.decode("0x" + input.substring(64 * 2, 65 * 2)));
  153. String str = input.substring(65 * 2, 69 * 2);
  154. item.setRunCnt(reverseParseHex(str));
  155. LonLatRecordExample rExp = new LonLatRecordExample();
  156. rExp.createCriteria()
  157. .andMccEqualTo("460").andMncEqualTo("0").andGprsCiEqualTo(item.getGprsCi()).andGprsLacEqualTo(item.getGprsLac());
  158. List<LonLatRecord> lRList = lonLatRecordMapper.selectByExample(rExp);
  159. if(lRList.size()>0){
  160. LonLatRecord lonLatRecord = lRList.get(0);
  161. item.setLng(lonLatRecord.getLng());
  162. item.setLat(lonLatRecord.getLat());
  163. }else{
  164. // 根据基站lac和ci获取经纬度
  165. String api = "http://api.cellocation.com:81/cell/?mcc=460&mnc=0&lac=" + item.getGprsLac() + "&ci="
  166. + item.getGprsCi() + "&output=json";
  167. String resp = com.js.kbt.util.HttpRequest.sendGet(api, null);
  168. JSONObject json = JSONObject.parseObject(resp);
  169. if (json != null && json.getInteger("errcode") == 0) {
  170. item.setLng(json.getDouble("lon") + "");
  171. item.setLat(json.getDouble("lat") + "");
  172. } else {
  173. logger.error("调用基站解析平台出错: " + resp);
  174. }
  175. LonLatRecord latRecord = new LonLatRecord();
  176. latRecord.setGprsCi(item.getGprsCi());
  177. latRecord.setMcc("460");
  178. latRecord.setMnc("0");
  179. latRecord.setGprsLac(item.getGprsLac());
  180. latRecord.setLat(item.getLat());
  181. latRecord.setLng(item.getLng());
  182. lonLatRecordMapper.insertSelective(latRecord);
  183. }
  184. String crcStr = input.substring(input.length() - 4);
  185. item.setCrcCode("" + reverseParseHex(crcStr));
  186. // 找寻上一条最新记录
  187. MouldHistoryExample mExp = new MouldHistoryExample();
  188. mExp.setOrderByClause("id desc limit 1");
  189. mExp.createCriteria().andEquipmentNoEqualTo(item.getEquipmentNo());
  190. // 存入数据库
  191. List<MouldHistory> newList = mouldHistoryMapper.selectByExample(mExp);
  192. mouldHistoryMapper.insertSelective(item);
  193. logger.info("添加数据完成了-----------》: " + item);
  194. // 模具开合记录
  195. int cnt = item.getRunCnt();
  196. int start = 69;
  197. logger.info("累计开合模次数=" + cnt);
  198. int end = input.length() - 4; // 最后2位 0xXX,0xXX ,是CRC校验位
  199. logger.info("时间信息==" + input.substring(start * 2, end));
  200. if (end - start * 2 >= 24) {// 时间最少6位,1位显示0x00,开合算两个时间,所以是6*2*2=24
  201. // 本次运行周期内的开合模次数
  202. int periodCnt = (end - start * 2) / 24;
  203. logger.info("本次开合模次数==" + periodCnt);
  204. long aHeadOpenTimeLongVal = 0L;
  205. for (int pos = 0; pos < periodCnt; pos++) {
  206. // 合模时间
  207. MouldHistoryTime time = new MouldHistoryTime();
  208. time.setHistoryId(item.getId());
  209. time.setEquipmentNo(item.getEquipmentNo());
  210. time.setSeq(pos + 1);
  211. Date closeTime = parseDate(input, start, pos, 0);
  212. time.setCloseTime(closeTime);
  213. // 开模时间
  214. Date openTime = parseDate(input, start, pos, 6);
  215. time.setOpenTime(openTime);
  216. if (pos == 0) {
  217. time.setTimeCost(0);
  218. } else {
  219. logger.info("本次开合周期--" + (openTime.getTime() - aHeadOpenTimeLongVal));
  220. time.setTimeCost((int) (openTime.getTime() - aHeadOpenTimeLongVal));
  221. }
  222. mouldHistoryTimeMapper.insertSelective(time);
  223. // 处理周期逻辑
  224. handleMouldCycleRuntimeLogic(openTime, item);
  225. logger.info("mouldHistoryTime数据添加完毕");
  226. aHeadOpenTimeLongVal = openTime.getTime();
  227. logger.info("上一包数据的开合时间戳--" + aHeadOpenTimeLongVal);
  228. }
  229. } else {
  230. logger.info("本次开合模次数==0");
  231. }
  232. // 统计该模盒的平均开合周期
  233. MouldHistoryExample exp = new MouldHistoryExample();
  234. exp.setOrderByClause("id");
  235. exp.createCriteria().andEquipmentNoEqualTo(item.getEquipmentNo()).andRunCntEqualTo(item.getRunCnt());
  236. // List<MouldHistoryTime> list =
  237. // mouldHistoryTimeMapper.selectByEquipmentNoAndThanZero(item.getEquipmentNo());
  238. List<MouldHistory> list = mouldHistoryMapper.selectByExample(exp);
  239. List<Long> historyIds = new ArrayList<>();
  240. historyIds.add(-1L);
  241. for (MouldHistory mouldHistory : list) {
  242. historyIds.add(mouldHistory.getId());
  243. }
  244. MouldHistoryTimeExample mtExp = new MouldHistoryTimeExample();
  245. mtExp.setOrderByClause("seq");
  246. mtExp.createCriteria().andHistoryIdIn(historyIds);
  247. List<MouldHistoryTime> historyList = mouldHistoryTimeMapper.selectByExample(mtExp);
  248. int avgTime = 0;
  249. int totalTime = 0;
  250. // if (historyList.size() == 1) {
  251. // // 证明盒子动了,找寻上一条记录
  252. // if (newList.size() > 0) {
  253. // MouldHistoryTime now = historyList.get(0);
  254. // MouldHistoryTime last =
  255. // mouldHistoryTimeMapper.getDateByHistory(newList.get(0).getId());
  256. // if (null != now && null != last) {
  257. // avgTime = (int)((now.getOpenTime().getTime()) -
  258. // (last.getOpenTime().getTime()));
  259. // }
  260. // }
  261. // } else {
  262. if (historyList.size() > 1) {
  263. for (int j = 0; j < historyList.size() - 1; j++) {
  264. totalTime += (historyList.get(j + 1).getOpenTime().getTime()
  265. - historyList.get(j).getOpenTime().getTime());
  266. }
  267. logger.info("totalTime" + totalTime);
  268. avgTime = (int) (totalTime / (historyList.size() - 1));
  269. }
  270. // }
  271. logger.info("avgTime-->" + avgTime);
  272. handleModLogic(item, avgTime);
  273. // 判断预留字节的
  274. if ("02".equals(mobilePart)) {
  275. // 丢包数据已占满缓存,调用读取命令
  276. String strHexStr16 = strHexStr16("#PRINTFALL;");
  277. logger.info("丢包数据已占满缓存下发调用读取命令#PRINTFALL;==>" + strHexStr16);
  278. sendMsg(strHexStr16);
  279. return deviceNum;
  280. }
  281. // 返回设备编号
  282. return deviceNum;
  283. }
  284. public void sendPackage(String equipmentNo) {
  285. if (equipmentNo.indexOf("FAAF") != -1) {
  286. logger.info("非法云模盒编号,不作下发处理");
  287. return;
  288. }
  289. MouldDownPacketExample exp = new MouldDownPacketExample();
  290. exp.createCriteria().andEquipmentNoEqualTo(equipmentNo);
  291. List<MouldDownPacket> list = mouldDownPacketMapper.selectByExample(exp);
  292. if (list.size() > 0) {
  293. MouldDownPacket packet = list.get(0);
  294. TbMouldEquipmentExample meqExp = new TbMouldEquipmentExample();
  295. meqExp.createCriteria().andEquipmentNoEqualTo(equipmentNo);
  296. long count = tbMouldEquipmentMapper.countByExample(meqExp);
  297. // 下发数据包,下发完后修改状态
  298. logger.info("开始下发数据包==>" + packet.getPacketStr());
  299. sendMsg(packet.getPacketStr());
  300. if(null != packet.getThreshold()){
  301. //下发阈值命令
  302. sendMsg(strHexStr16("#LIMIT VALUE="+packet.getThreshold()));
  303. }
  304. if (count > 0) {
  305. TbMouldEquipment me = tbMouldEquipmentMapper.selectByExample(meqExp).get(0);
  306. me.setIsUse(packet.getIsUse());
  307. tbMouldEquipmentMapper.updateByPrimaryKeySelective(me);
  308. }
  309. //下发完删除数据
  310. mouldDownPacketMapper.deleteByPrimaryKey(packet.getId());
  311. }
  312. }
  313. public void timeCalibration() {
  314. List<TimeCalibrationRecord> count = timeCalibrationRecordMapper.selectCountByToday();
  315. if (count.size() == 0) {
  316. Date date = new Date();
  317. SimpleDateFormat sdf = new SimpleDateFormat("yy-MM-dd,HH:mm:ss");
  318. String dateStr = sdf.format(date);
  319. dateStr = "#TIME=" + dateStr+";";
  320. // #TIME=18-03-06,15:31:48;
  321. logger.info("校准系统模块时间==>" + dateStr);
  322. // 将字符串转成16进制字符串
  323. String strHexStr16 = strHexStr16(dateStr);
  324. logger.info("校准系统模块时间转成16进制的字符串==>" + strHexStr16);
  325. sendMsg(strHexStr16);
  326. TimeCalibrationRecord timeCalibrationRecord = new TimeCalibrationRecord();
  327. timeCalibrationRecord.setIndate(new Date());
  328. timeCalibrationRecordMapper.insertSelective(timeCalibrationRecord);
  329. }
  330. }
  331. private void handleModLogic(MouldHistory item, int avgTime) {
  332. logger.info("进了handleModLogic逻辑--");
  333. logger.info("item==>" + item);
  334. TbMouldEquipmentExample meqExp = new TbMouldEquipmentExample();
  335. meqExp.createCriteria().andEquipmentNoEqualTo(item.getEquipmentNo());
  336. if (tbMouldEquipmentMapper.countByExample(meqExp) > 0) {
  337. TbMouldEquipment me = tbMouldEquipmentMapper.selectByExample(meqExp).get(0);
  338. me.setCurhillNumber(item.getBattery() + "");
  339. if (item.getLng() != null) {
  340. logger.info("更新经纬度:");
  341. me.setLng(Double.parseDouble(item.getLng()));
  342. me.setLat(Double.parseDouble(item.getLat()));
  343. }
  344. me.setCurtemperature(item.getTemperature());
  345. if (item.getAlarm() == 8) {
  346. me.setStage(3);// 安装被拆
  347. } else if (item.getAlarm() == 1) {
  348. me.setStage(2);// 低电量
  349. } else if (item.getAlarm() == 2) {
  350. me.setStage(1);// 高温
  351. } else {
  352. me.setStage(item.getAlarm());
  353. }
  354. // 处理报警
  355. if (item.getAlarm() > 0) {
  356. /**
  357. * 无报警 0; 低电量报警 1; 温度过热 2; 安装被拆 8。
  358. */
  359. logger.info("设备报警啦:" + item.getAlarm());
  360. }
  361. tbMouldEquipmentMapper.updateByPrimaryKeySelective(me);
  362. logger.info("更新完了tbMouldEquipment的状态和温度以及经纬度");
  363. TbMouldExample tExp = new TbMouldExample();
  364. tExp.setOrderByClause("id desc limit 1");
  365. tExp.createCriteria().andEquipmentIdEqualTo(me.getId());
  366. if (tbMouldMapper.countByExample(tExp) > 0) {
  367. logger.info("准备更新运行次数:");
  368. TbMould tm = tbMouldMapper.selectByExample(tExp).get(0);
  369. tm.setState(item.getStatus());
  370. // 云模盒运行次数+模具的历史运行次数
  371. tm.setRunTimes(item.getRunCnt() + tm.getHistoryRunTimes());
  372. tm.setLastRecTime(new Date());
  373. // 处理每模平均周期(单位秒)
  374. if (0 != avgTime) {
  375. logger.info("开始修改平均每模周期值为:" + avgTime);
  376. BigDecimal bd = new BigDecimal(avgTime * 1.00 / 1000);
  377. tm.setOcCycle(bd);
  378. }
  379. tbMouldMapper.updateByPrimaryKeySelective(tm);
  380. }
  381. }
  382. }
  383. /**
  384. * 低位在前的16进制解析
  385. *
  386. * @param rHex
  387. * @return
  388. */
  389. public static int reverseParseHex(String rHex) {
  390. int size = rHex.length() / 2;
  391. StringBuilder sb = new StringBuilder();
  392. for (int i = 0; i < size; i++) {
  393. sb.append(rHex.substring((size - i - 1) * 2, (size - i) * 2));
  394. }
  395. String str = sb.toString();
  396. return Integer.parseInt(str, 16);
  397. }
  398. private static Date parseDate(String input, int start, int pos, int dateStartPos) {
  399. // pos为开合的一组的下标,一个开合时间占位是12*2
  400. String year = input.substring((start + pos * 12 + dateStartPos) * 2, (start + pos * 12 + 1 + dateStartPos) * 2);
  401. String month = input.substring((start + pos * 12 + 1 + dateStartPos) * 2,
  402. (start + pos * 12 + 2 + dateStartPos) * 2);
  403. String day = input.substring((start + pos * 12 + 2 + dateStartPos) * 2,
  404. (start + pos * 12 + 3 + dateStartPos) * 2);
  405. String hh = input.substring((start + pos * 12 + 3 + dateStartPos) * 2,
  406. (start + pos * 12 + 4 + dateStartPos) * 2);
  407. String mm = input.substring((start + pos * 12 + 4 + dateStartPos) * 2,
  408. (start + pos * 12 + 5 + dateStartPos) * 2);
  409. String ss = input.substring((start + pos * 12 + 5 + dateStartPos) * 2,
  410. (start + pos * 12 + 6 + dateStartPos) * 2);
  411. StringBuilder sb = new StringBuilder();
  412. int yearInt = Integer.parseInt(year, 16);
  413. if (yearInt == 0) {
  414. sb.append("2019-01-01");
  415. } else {
  416. sb.append(yearInt < 100 ? "20" : "2");
  417. sb.append(yearInt).append("-");
  418. int monthInt = Integer.parseInt(month, 16);
  419. sb.append(monthInt < 10 ? "0" : "").append(monthInt).append("-");
  420. int dayInt = Integer.parseInt(day, 16);
  421. sb.append(dayInt < 10 ? "0" : "").append(dayInt);
  422. }
  423. Date parseDate = null;
  424. try {
  425. parseDate = new SimpleDateFormat("yyyy-MM-dd").parse(sb.toString());
  426. parseDate.setHours(Integer.parseInt(hh, 16));
  427. parseDate.setMinutes(Integer.parseInt(mm, 16));
  428. parseDate.setSeconds(Integer.parseInt(ss, 16));
  429. } catch (ParseException e) {
  430. e.printStackTrace();
  431. }
  432. return parseDate;
  433. }
  434. private void handleMouldCycleRuntimeLogic(Date openTime, MouldHistory item) throws ParseException {
  435. MouldCycleRuntime mcr = new MouldCycleRuntime();
  436. Integer hours = openTime.getHours();
  437. SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
  438. SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:");
  439. int housTime = openTime.getHours() - 1;
  440. openTime.setHours(housTime);
  441. String lastOpenTime = sdf.format(openTime);
  442. Date lastOpenTimeDate = sdf1.parse(lastOpenTime + "59:59");
  443. MouldHistoryTimeExample mExp = new MouldHistoryTimeExample();
  444. mExp.setOrderByClause("open_time desc limit 1");
  445. mExp.createCriteria().andEquipmentNoEqualTo(item.getEquipmentNo())
  446. .andOpenTimeLessThanOrEqualTo(lastOpenTimeDate);
  447. List<MouldHistoryTime> list = mouldHistoryTimeMapper.selectByExample(mExp);
  448. if (list.size() > 0) {
  449. MouldHistory mouldHistory = mouldHistoryMapper.selectByPrimaryKey(list.get(0).getHistoryId());
  450. logger.info("本次运行次数: " + item.getRunCnt()+" 上一小时的运行次数:"+mouldHistory.getRunCnt()+" 上一小时的historyId:"+mouldHistory.getId());
  451. mcr.setDateStr(sdf.format(openTime));
  452. mcr.setEquipmentNo(item.getEquipmentNo());
  453. mcr.setRuntime(item.getRunCnt() - mouldHistory.getRunCnt());
  454. if (hours == 0) {
  455. mcr.setTimeSlot("00:00-01:00");
  456. } else if (hours == 1) {
  457. mcr.setTimeSlot("01:00-02:00");
  458. } else if (hours == 2) {
  459. mcr.setTimeSlot("02:00-03:00");
  460. } else if (hours == 3) {
  461. mcr.setTimeSlot("03:00-04:00");
  462. } else if (hours == 4) {
  463. mcr.setTimeSlot("04:00-05:00");
  464. } else if (hours == 5) {
  465. mcr.setTimeSlot("05:00-06:00");
  466. } else if (hours == 6) {
  467. mcr.setTimeSlot("06:00-07:00");
  468. } else if (hours == 7) {
  469. mcr.setTimeSlot("07:00-08:00");
  470. } else if (hours == 8) {
  471. mcr.setTimeSlot("08:00-09:00");
  472. } else if (hours == 9) {
  473. mcr.setTimeSlot("09:00-10:00");
  474. } else if (hours == 10) {
  475. mcr.setTimeSlot("10:00-11:00");
  476. } else if (hours == 11) {
  477. mcr.setTimeSlot("11:00-12:00");
  478. } else if (hours == 12) {
  479. mcr.setTimeSlot("12:00-13:00");
  480. } else if (hours == 13) {
  481. mcr.setTimeSlot("13:00-14:00");
  482. } else if (hours == 14) {
  483. mcr.setTimeSlot("14:00-15:00");
  484. } else if (hours == 15) {
  485. mcr.setTimeSlot("15:00-16:00");
  486. } else if (hours == 16) {
  487. mcr.setTimeSlot("16:00-17:00");
  488. } else if (hours == 17) {
  489. mcr.setTimeSlot("17:00-18:00");
  490. } else if (hours == 18) {
  491. mcr.setTimeSlot("18:00-19:00");
  492. } else if (hours == 19) {
  493. mcr.setTimeSlot("19:00-20:00");
  494. } else if (hours == 20) {
  495. mcr.setTimeSlot("20:00-21:00");
  496. } else if (hours == 21) {
  497. mcr.setTimeSlot("21:00-22:00");
  498. } else if (hours == 22) {
  499. mcr.setTimeSlot("22:00-23:00");
  500. } else if (hours == 23) {
  501. mcr.setTimeSlot("23:00-00:00");
  502. }
  503. MouldCycleRuntimeExample mcrExp = new MouldCycleRuntimeExample();
  504. mcrExp.createCriteria().andDateStrEqualTo(mcr.getDateStr()).andEquipmentNoEqualTo(item.getEquipmentNo())
  505. .andTimeSlotEqualTo(mcr.getTimeSlot());
  506. List<MouldCycleRuntime> mList = mouldCycleRuntimeMapper.selectByExample(mcrExp);
  507. if (mList.size() > 0) {
  508. mcr.setId(mList.get(0).getId());
  509. mouldCycleRuntimeMapper.updateByPrimaryKeySelective(mcr);
  510. } else {
  511. mouldCycleRuntimeMapper.insertSelective(mcr);
  512. }
  513. }
  514. }
  515. private static String getStringFromHexStr(String hexStr) {
  516. StringBuilder sb = new StringBuilder();
  517. for (int i = 0; i < hexStr.length() / 2; i++) {
  518. String str = "0x" + hexStr.substring(i * 2, i * 2 + 2);
  519. int intVal = Integer.decode(str).intValue();
  520. char c = (char) intVal;
  521. sb.append(c);
  522. }
  523. return sb.toString();
  524. }
  525. public void close() {
  526. ctx.close();
  527. }
  528. public void sendMsg(String hexString) {
  529. System.out.println("发送消息==" + hexString);
  530. byte[] buffer = hexStrToBinaryStr(hexString);
  531. ByteBuf bf = Unpooled.buffer(hexString.length() / 2);
  532. bf.writeBytes(buffer);
  533. ctx.writeAndFlush(bf);
  534. // ctx.close();
  535. }
  536. /**
  537. * channel被激活时调用
  538. */
  539. @Override
  540. public void channelActive(ChannelHandlerContext ctx) {
  541. // TODO Auto-generated method stub
  542. this.ctx = ctx;
  543. System.out.println("==========Active=========" + ctx.channel().localAddress().toString() + ", connection num="
  544. + HelloServer.deviceMap.size());
  545. }
  546. @Override
  547. public void channelInactive(ChannelHandlerContext ctx) throws Exception {
  548. super.channelInactive(ctx);
  549. System.out.println("==========Inactive=========");
  550. }
  551. @Override
  552. public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
  553. // TODO Auto-generated method stub
  554. super.handlerRemoved(ctx);
  555. System.out.println("[YunSu]handlerRemoved=掉线了===");
  556. }
  557. @Override
  558. public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
  559. // TODO Auto-generated method stub
  560. super.exceptionCaught(ctx, cause);
  561. System.out.println("我捕捉到异常信息了");
  562. }
  563. @Override
  564. public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
  565. if (evt instanceof IdleStateEvent) {
  566. IdleStateEvent event = (IdleStateEvent) evt;
  567. if (event.state().equals(IdleState.READER_IDLE)) {
  568. } else if (event.state().equals(IdleState.WRITER_IDLE)) {
  569. // System.out.println("WRITER_IDLE=="+userInfo.getWxName());
  570. // logger.debug(ctx.channel().remoteAddress().toString()+
  571. // "WRITER_IDLE");
  572. // 超时关闭channel
  573. // ctx.close();
  574. } else if (event.state().equals(IdleState.ALL_IDLE)) {
  575. // 发送心跳
  576. ctx.channel().writeAndFlush("$&_".toString());
  577. }
  578. }
  579. // super.userEventTriggered(ctx, evt);
  580. }
  581. /**
  582. * 将十六进制的字符串转换成字节数组
  583. *
  584. * @param hexString
  585. * @return
  586. */
  587. public static byte[] hexStrToBinaryStr(String hexString) {
  588. if (hexString == null || "".contentEquals(hexString)) {
  589. return null;
  590. }
  591. hexString = hexString.replaceAll(" ", "");
  592. int len = hexString.length();
  593. int index = 0;
  594. byte[] bytes = new byte[len / 2];
  595. while (index < len) {
  596. String sub = hexString.substring(index, index + 2);
  597. bytes[index / 2] = (byte) Integer.parseInt(sub, 16);
  598. index += 2;
  599. }
  600. return bytes;
  601. }
  602. /**
  603. * 将字节数组转换成十六进制的字符串
  604. *
  605. * @return
  606. */
  607. public static String BinaryToHexString(byte[] bytes) {
  608. String hexStr = "0123456789ABCDEF";
  609. String result = "";
  610. String hex = "";
  611. for (byte b : bytes) {
  612. hex = String.valueOf(hexStr.charAt((b & 0xF0) >> 4));
  613. hex += String.valueOf(hexStr.charAt(b & 0x0F));
  614. result += hex + " ";
  615. }
  616. return result;
  617. }
  618. /**
  619. * 普通字符串转16进制字符串
  620. *
  621. * @param str
  622. * @return
  623. */
  624. public static String strHexStr16(String str) {
  625. char[] chars = "0123456789ABCDEF".toCharArray();
  626. StringBuilder sb = new StringBuilder("");
  627. byte[] bs = str.getBytes();
  628. int bit;
  629. for (int i = 0; i < bs.length; i++) {
  630. bit = (bs[i] & 0x0f0) >> 4;
  631. sb.append(chars[bit]);
  632. bit = bs[i] & 0x0f;
  633. sb.append(chars[bit]);
  634. // sb.append(' ');
  635. }
  636. return sb.toString().trim();
  637. }
  638. public static void main(String[] args) throws ParseException {
  639. // UserHandler h = new UserHandler();
  640. // h.timeCalibration();
  641. String a = "00:25:32";
  642. SimpleDateFormat s = new SimpleDateFormat("HH:mm:ss");
  643. Date d = new Date();
  644. // System.out.println(s.parse(a).getHours());
  645. // Date date = new Date();
  646. // SimpleDateFormat sdf = new SimpleDateFormat("yy-MM-dd,HH:mm:ss");
  647. // String dateStr = sdf.format(date);
  648. // dateStr = "#TIME="+dateStr+";";
  649. // System.out.println(dateStr);
  650. // //#TIME=18-03-06,15:31:48;
  651. // logger.info("校准系统模块时间==>"+dateStr);
  652. // String reverseParseHex = strHexStr16(dateStr);
  653. // System.out.println("reverseParseHex-----"+reverseParseHex);
  654. // String str = "1F51";
  655. String input = "FAAF530000000000000000000000003137333030303239343310010000000000000000000"
  656. + "000000000000000000000001F51E85F00000000000045004A" + "54000100110000001308160F171F1308160F2D188FCA";
  657. // String temp = "0x"+str;
  658. // int i = Integer.decode(temp);
  659. // System.out.println(i);
  660. // int p = reverseParseHex(str);
  661. // System.out.println(p);
  662. // int start = 69;
  663. // System.out.println(str.substring(69*2));
  664. // Date d = parseDate(str, start, 0, 0);
  665. // System.out.println(d.toGMTString());
  666. // int start = 69;
  667. // int end = input.length() - 4; // 最后2位 0xXX,0xXX ,是CRC校验位
  668. // logger.info("时间信息==" + input.substring(start * 2, end));
  669. // if (end - start * 2 >= 24) {// 时间最少6位,1位显示0x00,开合算两个时间,所以是6*2*2=24
  670. // // 本次运行周期内的开合模次数
  671. // int periodCnt = (end - start * 2) / 24;
  672. // logger.info("本次开合模次数==" + periodCnt);
  673. // for (int pos = 0; pos < periodCnt; pos++) {
  674. // // 合模时间
  675. // MouldHistoryTime time = new MouldHistoryTime();
  676. // time.setSeq(pos + 1);
  677. // Date closeTime = parseDate(input, start, pos, 0);
  678. // System.out.println(closeTime);
  679. // time.setCloseTime(closeTime);
  680. // // 开模时间
  681. // Date openTime = parseDate(input, start, pos, 6);
  682. // time.setOpenTime(openTime);
  683. // System.out.println(openTime);
  684. // int timeCost = (int) (openTime.getTime() - closeTime.getTime());
  685. // time.setTimeCost(timeCost);
  686. // }
  687. // } else {
  688. // logger.info("本次开合模次数==0");
  689. // }
  690. }
  691. }