1. 程式人生 > >java監聽、讀取串列埠資料

java監聽、讀取串列埠資料

public class MainFrame extends JFrame implements ActionListener {


/**
* 程式介面寬度
*/
public static final int WIDTH = 500;


/**
* 程式介面高度
*/
public static final int HEIGHT = 360;


private JTextPane dataView = new JTextPane();
private JScrollPane scrollDataView = new JScrollPane(dataView);


// 串列埠設定面板
private JPanel serialPortPanel = new JPanel();
private JLabel serialPortLabel = new JLabel("串列埠");
private JLabel baudrateLabel = new JLabel("波特率");
private JComboBox commChoice = new JComboBox();
private JComboBox baudrateChoice = new JComboBox();


// 操作面板
private JPanel operatePanel = new JPanel();
private JTextArea dataInput = new JTextArea();
private JButton serialPortOpenBtn = new JButton("開啟串列埠");
private JButton sendDataBtn = new JButton("傳送資料");
private JButton openCmdButton = new JButton("開啟射頻");
private JButton closeCmdButton = new JButton("關閉射頻");


/**
* 正常的風格
*/
private final String STYLE_NORMAL = "normal";
/**
* 字型為紅色
*/
private final String STYLE_RED = "red";


private List<String> commList = null;
private SerialPort serialport;


public MainFrame() {
initView();
initComponents();
initData();
}


private void initView() {
// 關閉程式
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
// 禁止視窗最大化
setResizable(false);


// 設定程式視窗居中顯示
Point p = GraphicsEnvironment.getLocalGraphicsEnvironment().getCenterPoint();
setBounds(p.x - WIDTH / 2, p.y - HEIGHT / 2, 499, 455);
getContentPane().setLayout(null);


setTitle("串列埠通訊");
}


private void initComponents() {
// 資料顯示
dataView.setFocusable(false);
scrollDataView.setBounds(10, 10, 475, 200);
/* 資料區域的風格 */
Style def = dataView.getStyledDocument().addStyle(null, null);
StyleConstants.setFontFamily(def, "verdana");
StyleConstants.setFontSize(def, 12);
Style normal = dataView.addStyle(STYLE_NORMAL, def);
Style s = dataView.addStyle(STYLE_RED, normal);
StyleConstants.setForeground(s, Color.RED);
dataView.setParagraphAttributes(normal, true);


getContentPane().add(scrollDataView);


// 串列埠設定
serialPortPanel.setBorder(BorderFactory.createTitledBorder("串列埠設定"));
serialPortPanel.setBounds(10, 220, 170, 188);
serialPortPanel.setLayout(null);
getContentPane().add(serialPortPanel);


serialPortLabel.setForeground(Color.gray);
serialPortLabel.setBounds(10, 25, 40, 20);
serialPortPanel.add(serialPortLabel);


commChoice.setFocusable(false);
commChoice.setBounds(60, 25, 100, 20);
serialPortPanel.add(commChoice);


baudrateLabel.setForeground(Color.gray);
baudrateLabel.setBounds(10, 60, 40, 20);
serialPortPanel.add(baudrateLabel);


baudrateChoice.setFocusable(false);
baudrateChoice.setBounds(60, 60, 100, 20);
serialPortPanel.add(baudrateChoice);


// 操作
operatePanel.setBorder(BorderFactory.createTitledBorder("操作"));
operatePanel.setBounds(200, 220, 285, 188);
operatePanel.setLayout(null);
getContentPane().add(operatePanel);


dataInput.setBounds(25, 25, 235, 63);
operatePanel.add(dataInput);


serialPortOpenBtn.setFocusable(false);
serialPortOpenBtn.setBounds(45, 98, 90, 20);
serialPortOpenBtn.addActionListener(this);
operatePanel.add(serialPortOpenBtn);


sendDataBtn.setFocusable(false);
sendDataBtn.setBounds(155, 98, 90, 20);
sendDataBtn.addActionListener(this);
operatePanel.add(sendDataBtn);


openCmdButton.setBounds(45, 128, 90, 20);
openCmdButton.addActionListener(this);
operatePanel.add(openCmdButton);


closeCmdButton.setBounds(155, 128, 90, 20);
closeCmdButton.addActionListener(this);
operatePanel.add(closeCmdButton);


JButton btnNewButton = new JButton("clear");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dataView.setText("");
}
});
btnNewButton.setBounds(45, 158, 90, 20);
operatePanel.add(btnNewButton);


}


@SuppressWarnings("unchecked")
private void initData() {
commList = SerialPortManager.findPort();
// 檢查是否有可用串列埠,有則加入選項中
if (commList == null || commList.size() < 1) {
DialogShowUtils.warningMessage("沒有搜尋到有效串列埠!");
} else {
for (String s : commList) {
commChoice.addItem(s);
}
}


baudrateChoice.addItem("9600");
baudrateChoice.addItem("19200");
baudrateChoice.addItem("38400");
baudrateChoice.addItem("57600");
baudrateChoice.addItem("115200");
}




/**
* 開啟串列埠

*/
private void openSerialPort() {




// 獲取串列埠名稱
String commName = (String) commChoice.getSelectedItem();
// 獲取波特率
int baudrate = 9600;
String bps = (String) baudrateChoice.getSelectedItem();
baudrate = Integer.parseInt(bps);


// 檢查串列埠名稱是否獲取正確
if (commName == null || commName.equals("")) {
DialogShowUtils.warningMessage("沒有搜尋到有效串列埠!");
} else {
try {
serialport = SerialPortManager.openPort(commName, baudrate);
if (serialport != null) {
dataShow("串列埠已開啟",STYLE_RED);
serialPortOpenBtn.setText("關閉串列埠");
}
} catch (SerialPortParameterFailure e) {
e.printStackTrace();
} catch (NotASerialPort e) {
e.printStackTrace();
} catch (NoSuchPort e) {
e.printStackTrace();
} catch (PortInUse e) {
e.printStackTrace();
DialogShowUtils.warningMessage("串列埠已被佔用!");
}
}


try {
SerialPortManager.addListener(serialport, new SerialListener());
} catch (TooManyListeners e) {
e.printStackTrace();
}
}

/**
* 關閉串列埠

*/
private void closeSerialPort() {
SerialPortManager.closePort(serialport);
dataShow("已經關閉串列埠",STYLE_RED);
serialPortOpenBtn.setText("開啟串列埠");
serialport = null;
}

/**
* 列印資料到面板上

*/
private void dataShow(String text,String style) {
StringBuilder builderData = new StringBuilder();
builderData.setLength(0);
builderData.append(MyUtils.formatDateStr_ss()).append("\r\n").append(text).append("\r\n");
try {
Document document = dataView.getDocument();
if(STYLE_RED.equals(style))
dataView.getDocument().insertString(document.getLength(), builderData.toString(),
dataView.getStyle(style));
else
dataView.getDocument().insertString(document.getLength(), builderData.toString(),
dataView.getStyle(STYLE_NORMAL));
dataView.setCaretPosition(document.getLength());
} catch (BadLocationException e) {
e.printStackTrace();
}
}




/**
* 傳送指定資料

*/
private void sendData(String data) {
try {
SerialPortManager.sendToPort(serialport, MyUtils.HexString2Bytes(data));
dataShow(data,STYLE_RED);
} catch (SendDataToSerialPortFailure e) {
e.printStackTrace();
} catch (SerialPortOutputStreamCloseFailure e) {
e.printStackTrace();

}


private class SerialListener implements SerialPortEventListener {
/**
* 處理監控到的串列埠事件
*/
public void serialEvent(SerialPortEvent serialPortEvent) {


switch (serialPortEvent.getEventType()) {


case SerialPortEvent.BI: // 10 通訊中斷
DialogShowUtils.errorMessage("與串列埠裝置通訊中斷");
break;


case SerialPortEvent.OE: // 7 溢位(溢位)錯誤


case SerialPortEvent.FE: // 9 幀錯誤


case SerialPortEvent.PE: // 8 奇偶校驗錯誤


case SerialPortEvent.CD: // 6 載波檢測


case SerialPortEvent.CTS: // 3 清除待發送資料


case SerialPortEvent.DSR: // 4 待發送資料準備好了


case SerialPortEvent.RI: // 5 振鈴指示


case SerialPortEvent.OUTPUT_BUFFER_EMPTY: // 2 輸出緩衝區已清空
break;


case SerialPortEvent.DATA_AVAILABLE: // 1 串列埠存在可用資料
byte[] data = null;
try {
if (serialport == null) {
DialogShowUtils.errorMessage("串列埠物件為空!監聽失敗!");
} else {
// 讀取串列埠資料
data = SerialPortManager.readFromPort(serialport);
dataShow(MyUtils.byteArray2HexString(data, data.length, true), STYLE_NORMAL);
}
} catch (Exception e) {
DialogShowUtils.errorMessage(e.toString());
// 發生讀取錯誤時顯示錯誤資訊後退出系統
System.exit(0);
}
break;
}
}
}


public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new MainFrame().setVisible(true);
}
});
}


@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == serialPortOpenBtn) {
if (serialport == null) {
openSerialPort();
} else {
closeSerialPort();
}
} else if (e.getSource() == sendDataBtn) {
String data = dataInput.getText().toString();
if(MyUtils.isEmpty(data))
return;
sendData(data);
} else if (e.getSource() == openCmdButton) {
// 0x02 0x05 0x01 0xaa 0x03 --> "0x02 0x05 0x01 0x06 0x03"
String data = "020501aa03";
sendData(data);


} else if (e.getSource() == closeCmdButton) {
// 0x02 0x05 0x02 0xaa 0x03 --> "0x02 0x05 0x02 0x05 0x03"
String data = "020502aa03";
sendData(data);
}
}

}