SerialPortUtils2.java 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  1. package com.mes.util;
  2. import com.alibaba.fastjson2.JSONObject;
  3. import com.fazecast.jSerialComm.SerialPort;
  4. import com.fazecast.jSerialComm.SerialPortDataListener;
  5. import com.fazecast.jSerialComm.SerialPortEvent;
  6. import com.mes.ui.DataUtil;
  7. import com.mes.ui.MesClient;
  8. import jdk.nashorn.internal.runtime.regexp.joni.Config;
  9. import org.slf4j.Logger;
  10. import org.slf4j.LoggerFactory;
  11. import java.awt.*;
  12. import java.text.DecimalFormat;
  13. import java.util.Arrays;
  14. public class SerialPortUtils2 {
  15. public static final Logger log = LoggerFactory.getLogger(SerialPortUtils2.class);
  16. public SerialPort serialPort;
  17. public String portName;
  18. public boolean isOpen;
  19. public boolean isStop;//是否结束
  20. public String oprno;
  21. public String oprnoName;
  22. public StringBuilder dataBuilder ;
  23. private static final byte[] buffer = new byte[1024* 5];
  24. private static int bufferEnd = 0;
  25. public String device;
  26. public SerialPortUtils2(String portName, String oprno, String oprnoName, String device) {
  27. try {
  28. this.portName = portName;
  29. this.oprnoName = oprnoName;
  30. this.oprno = oprno;
  31. // this.device = "innomatec";
  32. this.device = device;
  33. serialPort = SerialPort.getCommPort(portName);
  34. serialPort.setBaudRate(Integer.valueOf(MesClient.configParam.getBaudRate2()));
  35. serialPort.setNumDataBits(Integer.valueOf(MesClient.configParam.getDataBits2()));
  36. serialPort.setNumStopBits(Integer.valueOf(MesClient.configParam.getStopBit2()));
  37. if(MesClient.configParam.getCheckBit2().equals("ODD")){
  38. serialPort.setParity(SerialPort.ODD_PARITY);
  39. }else if(MesClient.configParam.getCheckBit2().equals("EVEN")){
  40. serialPort.setParity(SerialPort.EVEN_PARITY);
  41. }else if(MesClient.configParam.getCheckBit2().equals("MARK")){
  42. serialPort.setParity(SerialPort.MARK_PARITY);
  43. }else if(MesClient.configParam.getCheckBit2().equals("SPACE")){
  44. serialPort.setParity(SerialPort.SPACE_PARITY);
  45. }else{
  46. serialPort.setParity(SerialPort.NO_PARITY);
  47. }
  48. isOpen = openPort();
  49. if (isOpen) {
  50. if(device.equals("ateq")){
  51. serialPort.addDataListener(new SerialPortDataListener() {
  52. @Override
  53. public int getListeningEvents() {
  54. return SerialPort.LISTENING_EVENT_DATA_AVAILABLE;
  55. }
  56. @Override
  57. public void serialEvent(SerialPortEvent event) {
  58. if (event.getEventType() != SerialPort.LISTENING_EVENT_DATA_AVAILABLE) {
  59. return;
  60. }
  61. byte[] buffer = new byte[1024];
  62. int numBytesRead = serialPort.readBytes(buffer, buffer.length);
  63. for (int i = 0; i < numBytesRead; i++) {
  64. SerialPortUtils2.buffer[bufferEnd++] = buffer[i];
  65. }
  66. }
  67. });
  68. WorkTimer2.start();
  69. } else if (device.equals("innomatec")) {
  70. serialPort.addDataListener(new SerialPortDataListener() {
  71. StringBuilder stringBuilder = new StringBuilder();
  72. @Override
  73. public int getListeningEvents() {
  74. return SerialPort.LISTENING_EVENT_DATA_AVAILABLE;
  75. }
  76. @Override
  77. public void serialEvent(SerialPortEvent event) {
  78. if (event.getEventType() == SerialPort.LISTENING_EVENT_DATA_AVAILABLE) {
  79. byte[] newData = new byte[serialPort.bytesAvailable()];
  80. int numRead = serialPort.readBytes(newData, newData.length);
  81. stringBuilder.append(new String(newData, 0, numRead));
  82. // 检查是否包含换行符
  83. int index;
  84. while ((index = stringBuilder.indexOf("\n")) != -1) {
  85. String data = stringBuilder.substring(0, index + 1);
  86. log.info("收到数据:" + data);
  87. log.info("收到数据长度:" + data.length());
  88. if (data != null && MesClient.work_status2 == 1) {
  89. if (true) {
  90. // 选择程序
  91. // String readProgramNo = "PRG_"+String.format("%03d", Integer.parseInt(MesClient.configParam.getProgramNo2()));
  92. // sendData(readProgramNo);
  93. if (MesClient.tjFlag == 1) {
  94. if (data.trim().equals("RUN") || data.split("\t").length == 3) {
  95. log.info("运行开始了");
  96. MesClient.tjFlag = 2;
  97. }
  98. }
  99. if (MesClient.tjFlag2 == 2) {
  100. if (data.split("\t").length == 3) {//例 data= 2.5 1.1 0.000 时间(s) 压力(hpa) 压降(pa)
  101. String[] lists = data.split("\\s+"); // 使用空格进行分割,\\s+ 表示匹配一个或多个空白字符
  102. if (lists.length == 3) {
  103. double yali = Double.parseDouble(lists[1].trim());
  104. double dividedValue = yali / 10;
  105. // Format to 2 decimal places
  106. DecimalFormat df = new DecimalFormat("#.##");
  107. String result = df.format(dividedValue);
  108. MesClient.param3.setText(result);
  109. MesClient.param4.setText(lists[2]);
  110. //
  111. }
  112. } else if (data.length() == 97 || data.length() == 98) {//检测结束
  113. log.info("检测结束");
  114. //结果
  115. String result = null;
  116. String yaLi = null;
  117. String yaJiang = null;
  118. String leakRate = null;
  119. String leakRateUnit = null;
  120. try {
  121. result = data.substring(86, 98).trim(); // "PNE"(包含末尾的 E)
  122. yaLi = data.substring(35, 43).trim(); // "+ 224.58"(不变,已完整)
  123. String yaLiUnit = data.substring(45, 49).trim(); // "kPa"(不变)
  124. yaJiang = data.substring(51, 60).trim(); // "+ 0.00"(原缺最后一个 0,end+1)
  125. String yaJiangUnit = data.substring(61, 65).trim(); // "Pa"(不变)
  126. leakRate = data.substring(67, 76).trim(); // "+ 0.00"(原缺最后一个 0,end+1)
  127. leakRateUnit = data.substring(77, 85).trim(); // "ml/min"(原缺 n,end+1)
  128. MesClient.tjFlag2 = 3;
  129. // MesClient.setMenuStatus(MesClient.tjFlagText3,0);
  130. String leakValue = "";
  131. String leakValueUnit = "";
  132. if (MesClient.configParam.getLeakage2().equals("压降")) {
  133. leakValue = yaJiang;
  134. leakValueUnit = yaJiangUnit;
  135. } else {
  136. leakValue = leakRate;
  137. leakValueUnit = leakRateUnit;
  138. }
  139. MesClient.param3.setText(yaLi + yaLiUnit);
  140. MesClient.param4.setText(leakValue + leakRateUnit);
  141. String lastRet = "NG";
  142. if (result.equals("OK")) {
  143. MesClient.result2.setText("OK");
  144. MesClient.result2.setForeground(Color.GREEN);
  145. lastRet = "OK";
  146. } else {
  147. MesClient.result2.setText("NG");
  148. MesClient.result2.setForeground(Color.RED);
  149. }
  150. TestParam testParam = new TestParam();
  151. testParam.setSn(MesClient.product_sn2.getText().trim());
  152. testParam.setPressure(yaLi);
  153. testParam.setPressureUnit(yaLiUnit);
  154. testParam.setLeak(leakValue);
  155. testParam.setLeakUnit(leakValueUnit);
  156. testParam.setOprno(MesClient.configParam.getOprno2());
  157. testParam.setOprnoTitle(MesClient.configParam.getOprnoTitle2());
  158. testParam.setProgramNo(MesClient.configParam.getProgramNo2());
  159. testParam.setUcode(MesClient.user_menu.getText().trim());
  160. testParam.setResult(lastRet);
  161. if (lastRet.equals("NG")) {
  162. testParam.setRemark(result);
  163. }else {
  164. testParam.setRemark("");
  165. }
  166. String testDate = DateLocalUtils.getCurrentTime();
  167. testParam.setCreateTime(testDate);
  168. JdbcUtils.insertTestRecord(testParam);
  169. if (MesClient.configParam.getPrintLabel().equals("是") && lastRet.equals("OK")) {
  170. // 打印查询最新的一条总成的数据
  171. TestParam testParam2 = JdbcUtils.getTestBySn(testParam.getSn(), testParam.getCreateTime());
  172. if (testParam2 != null && testParam2.getResult().equals("OK")) {
  173. PrintUtil.printLabel(testParam.getSn(), testParam2.getLeak() + testParam2.getLeakUnit(), testParam.getLeak() + testParam.getLeakUnit(), testDate);
  174. }
  175. }
  176. // JSONObject retObj = DataUtil.qmresult("500002", testParam);
  177. JSONObject retObj = DataUtil.qmResultData(testParam);
  178. if (retObj == null || retObj.get("result") == null) {
  179. MesClient.setMenuStatus("液冷测试结果上传失败,请重试", -1);
  180. return;
  181. }
  182. if (retObj.get("result").toString().equalsIgnoreCase("true")) {
  183. MesClient.work_status2 = 0;
  184. MesClient.setMenuStatus("液冷测试结果上传成功,请扫下一件", 0);
  185. } else {
  186. MesClient.setMenuStatus("液冷测试结果上传失败,请重试", -1);
  187. return;
  188. }
  189. // MesClient.getUser();
  190. // Boolean sendret = DataUtil.sendQmQuality(MesClient.nettyClient,testParam.getSn(),lastRet,MesClient.user20);
  191. // if(!sendret){
  192. // MesClient.setMenuStatus("消息发送失败,请重试",-1);
  193. // return;
  194. // }
  195. // MesClient.resetScanA();
  196. // MesClient.scan_type = 1;
  197. // MesClient.scanBarcode();
  198. } catch (Exception e) {
  199. log.info(e.getMessage());
  200. }
  201. } else if (data.length() == 165 || data.contains("PARA_")) {//
  202. // String cq = data.substring(8, 13).trim();//充气
  203. // String by = data.substring(13, 18).trim();//保压
  204. // String cs = data.substring(18, 23).trim();//测试
  205. // MesClient.bao_ya_text.setText(by + "(s)");
  206. // MesClient.chong_qi_text.setText(cq + "(s)");
  207. // MesClient.ce_shi_text.setText(cs + "(s)");
  208. }
  209. }
  210. if (MesClient.tjFlag == 3) {
  211. //
  212. }
  213. }
  214. } else {
  215. // sendData("STOP");
  216. }
  217. // 移除已处理的数据
  218. stringBuilder.delete(0, index + 1);
  219. }
  220. }
  221. }
  222. });
  223. }
  224. }
  225. }catch (Exception e) {
  226. log.info("出现异常:" + e.getMessage());
  227. if (serialPort != null && isOpen) {
  228. closePort();
  229. }
  230. // 重新连接串口
  231. openPort();
  232. }
  233. }
  234. public boolean openPort() {
  235. if (!isOpen) {
  236. if (serialPort.openPort()) {
  237. log.info("串口已打开.");
  238. isOpen = true;
  239. return true;
  240. } else {
  241. log.info("无法打开串口.");
  242. return false;
  243. }
  244. } else {
  245. log.info("串口已经打开.");
  246. return true;
  247. }
  248. }
  249. public boolean closePort() {
  250. if (serialPort != null && serialPort.isOpen()) {
  251. if (serialPort.closePort()) {
  252. log.info("串口已关闭.");
  253. isOpen = false;
  254. return true;
  255. } else {
  256. log.info("无法关闭串口.");
  257. return false;
  258. }
  259. } else {
  260. log.info("串口已经关闭.");
  261. return true;
  262. }
  263. }
  264. public boolean sendData(String data) {
  265. if (isOpen) {
  266. serialPort.writeBytes(data.getBytes(), data.length());
  267. log.info("成品气密仪已发送数据:" + data);
  268. return true;
  269. } else {
  270. log.info("成品气密仪串口未打开,尝试重新打开串口...");
  271. MesClient.setMenuStatus("成品气密仪连接失败,请检查设备后重试",1);
  272. isOpen = openPort();
  273. return false;
  274. }
  275. }
  276. public String receiveData() {
  277. try {
  278. if (isOpen) {
  279. byte[] readBuffer = new byte[1024];
  280. int numBytes = serialPort.readBytes(readBuffer, readBuffer.length);
  281. if (numBytes > 0) {
  282. return new String(readBuffer, 0, numBytes);
  283. } else {
  284. log.info("未接收到数据.");
  285. return null;
  286. }
  287. } else {
  288. log.info("串口未打开,无法接收数据.");
  289. return null;
  290. }
  291. } catch (Exception e) {
  292. e.printStackTrace();
  293. return null;
  294. }
  295. }
  296. public synchronized byte[] read(String sendData) {
  297. byte[] bytesToSend = DataUtils.hexStringToByteArray(sendData);
  298. serialPort.writeBytes(bytesToSend, bytesToSend.length);
  299. try {
  300. Thread.sleep(80);
  301. } catch (InterruptedException e) {
  302. throw new RuntimeException(e);
  303. }
  304. byte[] copy = Arrays.copyOf(buffer, bufferEnd);
  305. bufferEnd = 0;
  306. return copy;
  307. }
  308. public boolean start() {
  309. if (isOpen) {
  310. if(device.equals("ateq")){
  311. String s1 = DataUtils.CRC16(ATEQ2.getStationNo()+" 05 00 01 FF 00");
  312. byte[] read = this.read(s1);
  313. boolean result = Arrays.equals(read, DataUtils.hexStringToByteArray(s1));
  314. log.info("气密仪开始{}", result ? "成功" : "失败");
  315. return result;
  316. }else if(device.equals("innomatec")){
  317. this.sendData("START");
  318. return true;
  319. }
  320. return true;
  321. } else {
  322. log.info("气密仪串口未打开,尝试重新打开串口...");
  323. MesClient.setMenuStatus("气密仪连接失败,请检查设备后重试",1);
  324. isOpen = openPort();
  325. return false;
  326. }
  327. }
  328. }