62,620
社区成员
发帖
与我相关
我的任务
分享
package com.century.chuangkou;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.TooManyListenersException;
import javax.comm.CommPortIdentifier;
import javax.comm.PortInUseException;
import javax.comm.SerialPort;
import javax.comm.SerialPortEvent;
import javax.comm.SerialPortEventListener;
import javax.comm.UnsupportedCommOperationException;
public class Read implements Runnable, SerialPortEventListener {
static CommPortIdentifier portId;
static Enumeration portList;
private java.io.FileOutputStream fos = null; // 定义日志函数
InputStream inputStream;
SerialPort serialPort;
Thread readThread;
private String portName;
public void readPort() {
portList = CommPortIdentifier.getPortIdentifiers();
System.out.println("interface:" + portList.hasMoreElements());
while (portList.hasMoreElements()) {
portId = (CommPortIdentifier) portList.nextElement();
if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
if (portId.getName().equals(portName)) {
// if (portId.getName().equals("/dev/term/a")) {
Read reader = new Read();
}
}
}
}
public Enumeration<?> getPortList() {
return CommPortIdentifier.getPortIdentifiers();
}
public Read() {
}
public void init() {
try {
serialPort = (SerialPort) portId.open("ReadApp", 2000);
} catch (PortInUseException e) {
System.out.print("串口打开失败");
}
try {
fos = new java.io.FileOutputStream("c:\\log.txt");// 建立日志文件
System.out.print("串口数据");
inputStream = serialPort.getInputStream();
} catch (IOException e) {
}
try {
serialPort.addEventListener(this);
} catch (TooManyListenersException e) {
}
serialPort.notifyOnDataAvailable(true);
try {
serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8,
SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
} catch (UnsupportedCommOperationException e) {
}
readThread = new Thread(this);
readThread.start();
}
public void run() {
try {
Thread.sleep(20000);
} catch (InterruptedException e) {
}
}
public void serialEvent(SerialPortEvent event) {
switch (event.getEventType()) {
case SerialPortEvent.BI:
case SerialPortEvent.OE:
case SerialPortEvent.FE:
case SerialPortEvent.PE:
case SerialPortEvent.CD:
case SerialPortEvent.CTS:
case SerialPortEvent.DSR:
case SerialPortEvent.RI:
case SerialPortEvent.OUTPUT_BUFFER_EMPTY:
break;
case SerialPortEvent.DATA_AVAILABLE:
byte[] readBuffer = new byte[8];
try {
while (inputStream.available() > 0) {
int numBytes = inputStream.read(readBuffer);
}
System.out.print(new String(readBuffer)); // 打印串口数据
fos.write(readBuffer); // 将读到的数据写到日志文件中
} catch (IOException e) {
}
break;
}
}
public String getPortName() {
return portName;
}
public void setPortName(String portName) {
this.portName = portName;
}
public static void main(String[] args) {
Read read = new Read();
while (read.getPortList().hasMoreElements()) {
portId = (CommPortIdentifier) read.getPortList().nextElement();
System.out.println("interface:" + portId.getName());
}
}
}