package org.example.cmd; import gnu.io.SerialPort; import org.example.opc.GlobalVariable; import org.example.opc.unit.DateTool; import static org.example.cmd.SerialPortUtil.bytes2HexString; import static org.example.cmd.SerialPortUtil.hexStr2Bytes; public class COMThread extends Thread { private boolean s = false;// 点击暂停 private boolean locked = false;// 判断是否被锁住lock //public float t=0; Object lock = new Object();// 线程锁住的对象 public void run() { synchronized (lock) { GlobalVariable.textArea.append("开始执行" + "\n"); String msg = ""; try { SerialPortUtil COM1=new SerialPortUtil(); SerialPort serialPort1=COM1.openPort("COM2",57600,8,0,1); GlobalVariable.textArea.append(DateTool.getLocalTimeForDate()+": "+"serialPort1:" + serialPort1+ "\n"); while(true && null != serialPort1) { System.out.println("取噪音已经关闭!"+ "\n"); //GlobalVariable.textArea.append(DateTool.getLocalTimeForDate()+": "+"开始取噪音的值:" + GlobalVariable.isSendValue + "\n"); if (GlobalVariable.isSendValue){ byte[] HEX = hexStr2Bytes("1c"); COM1.sendToPort(serialPort1, HEX); byte[] cache = COM1.readFromPort(serialPort1); //GlobalVariable.textArea.append("当前测得的燥音值为 cache:" + cache + "\n"); if(cache!=null) { String[] data = bytes2HexString(cache).split(" "); String d = String.valueOf(data[1] + data[0]); int b = Integer.parseInt(d, 16); float c = (float) b / 10; if(c>GlobalVariable.zyyMaxValue){ GlobalVariable.zyyMaxValue = c; } GlobalVariable.zyyValue = c; //GlobalVariable.textArea.append("当前测得的燥音值为:" + c + "\n"); } try { sleep(1000); } catch (InterruptedException e) { } }else{ System.out.println("取噪音已经关闭!"+ "\n"); } } } catch (Exception e) { msg = e.getMessage(); }finally { GlobalVariable.textArea.append(DateTool.getLocalTimeForDate()+": "+"报错:" + msg + "\n"); } } } }