UserHandler.java 28 KB

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