Javaシリアルポートの読み出し方法
2861 ワード
Enumeration portList = CommPortIdentifier.getPortIdentifiers();
if (portList.hasMoreElements()) {
//
msgLabel.setText(" ");
} else {
msgLabel.setText(" ");
}
while (portList.hasMoreElements()) {
CommPortIdentifier portId = (CommPortIdentifier) portList.nextElement();
if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
comListCombo.add(portId.getName());
comListCombo.setText(portId.getName());
}
}
portList = CommPortIdentifier.getPortIdentifiers();
if (portList.hasMoreElements()) {
//
msgLabel.setText(" ");
} else {
msgLabel.setText(" ");
}
while (portList.hasMoreElements()) {
portId = (CommPortIdentifier) portList.nextElement();
if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
String selectedCom = comListCombo.getText();
if (portId.getName().equals(selectedCom)) { // //TODO
// if (portId.getName().equals("COM1")) { // //TODO
try {
serialPort = (SerialPort) portId.open("ReadComm", 10000);
serialPort.setSerialPortParams(115200, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
// setStatus(" COM7 , ..... ");
msgLabel.setText(" , .....");
// openComBtn.setEnabled(false);
openComBtn.setText(" ");
comPortIsOpened = true;
serialPort.addEventListener(new SerialPortEventListener() {
@Override
public void serialEvent(SerialPortEvent arg0) {
byte[] readBuffer = new byte[1024];
int numBytes = 0;
String readStr = "";
try {
inputStream = serialPort.getInputStream();
} catch (Exception e) {
e.printStackTrace();
}
try {
while (inputStream.available() > 0) {
numBytes = inputStream.read(readBuffer);
}
} catch (Exception e) {
// e.printStackTrace();
Display.getDefault().syncExec(new Runnable() {
public void run() {
macText.setText("ComOUT");
qrCodeText.setText("ComOUT");
openComBtn.setEnabled(true);
createQrCodeBtn.setEnabled(false);
btnmac.setEnabled(false);
// setStatus(" , ");
msgLabel.setText(" , ");
openComBtn.setText(" ");
qrCodeLabel.setImage(SWTResourceManager.getImage(MainWindow.class, "/"
+ ConfigUtil.dsmLogoImage));
};
});
serialPort.close();
outputStream = null;
inputStream = null;
comPortIsOpened = false;
}
}
});
serialPort.notifyOnDataAvailable(true);
} catch (Exception e5) {
e5.printStackTrace();
}
}
}
先に置いておきます.