Java源码示例:gnu.io.CommPort
示例1
@Override
public void connect() throws SwegonVentilationException {
try {
CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(portName);
CommPort commPort = portIdentifier.open(this.getClass().getName(), 2000);
serialPort = (SerialPort) commPort;
serialPort.setSerialPortParams(BAUDRATE, SerialPort.DATABITS_8, SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
in = serialPort.getInputStream();
logger.debug("Swegon ventilation Serial Port message listener started");
} catch (Exception e) {
throw new SwegonVentilationException(e);
}
}
示例2
@Override
public void connect(String device)
throws NoSuchPortException, PortInUseException, UnsupportedCommOperationException, IOException {
CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(device);
CommPort commPort = portIdentifier.open(this.getClass().getName(), 2000);
serialPort = (SerialPort) commPort;
serialPort.setSerialPortParams(38400, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
serialPort.enableReceiveThreshold(1);
serialPort.disableReceiveTimeout();
in = serialPort.getInputStream();
out = serialPort.getOutputStream();
out.flush();
if (in.markSupported()) {
in.reset();
}
readerThread = new SerialReader(in);
readerThread.start();
}
示例3
@Override
protected void doConnect(SocketAddress remoteAddress, SocketAddress localAddress) throws Exception {
RxtxDeviceAddress remote = (RxtxDeviceAddress) remoteAddress;
final CommPortIdentifier cpi = CommPortIdentifier.getPortIdentifier(remote.value());
final CommPort commPort = cpi.open(getClass().getName(), 1000);
commPort.enableReceiveTimeout(config().getOption(READ_TIMEOUT));
deviceAddress = remote;
serialPort = (SerialPort) commPort;
}
示例4
/**
* 打开串口
*
* @param portName
* 端口名称
* @param baudrate
* 波特率
* @return 串口对象
* @throws PortInUseException
* 串口已被占用
*/
public static final SerialPort openPort(String portName, int baudrate) throws PortInUseException {
try {
// 通过端口名识别端口
CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(portName);
// 打开端口,并给端口名字和一个timeout(打开操作的超时时间)
CommPort commPort = portIdentifier.open(portName, 2000);
// 判断是不是串口
if (commPort instanceof SerialPort) {
SerialPort serialPort = (SerialPort) commPort;
try {
// 设置一下串口的波特率等参数
// 数据位:8
// 停止位:1
// 校验位:None
serialPort.setSerialPortParams(baudrate, SerialPort.DATABITS_8, SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
} catch (UnsupportedCommOperationException e) {
e.printStackTrace();
}
return serialPort;
}
} catch (NoSuchPortException e1) {
e1.printStackTrace();
}
return null;
}
示例5
public void handleEvent() {
try {
CommPortIdentifier portId = CommPortIdentifier.getPortIdentifier(SerialConf.WINDOWS_PORT);
if (portId.isCurrentlyOwned()) { //端口已开启
System.out.println("Port busy!");
} else {
CommPort commPort = portId.open("whatever it's name", SerialConf.TIME_OUT);
if (commPort instanceof SerialPort) {
serialPort = (SerialPort) commPort;
//设置参数
serialPort.setSerialPortParams(SerialConf.BAUD,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_EVEN);
in = serialPort.getInputStream(); //接收数据
serialPort.notifyOnDataAvailable(true);
serialPort.addEventListener(this);
} else {
commPort.close();
System.out.println("the port is not serial!");
}
}
} catch (Exception e) {
serialPort.close();
System.out.println("Error: SerialOpen!!!");
e.printStackTrace();
}
}
示例6
@Override
public SerialPort open(String owner, int timeout) throws PortInUseException {
try {
final CommPort cp = id.open(owner, timeout);
if (cp instanceof gnu.io.SerialPort) {
return new RxTxSerialPort((gnu.io.SerialPort) cp);
} else {
throw new IllegalStateException(
String.format("We expect an serial port instead of '%s'", cp.getClass()));
}
} catch (gnu.io.PortInUseException e) {
throw new PortInUseException();
}
}
示例7
@Override
protected void doConnect(SocketAddress remoteAddress, SocketAddress localAddress) throws Exception {
RxtxDeviceAddress remote = (RxtxDeviceAddress) remoteAddress;
final CommPortIdentifier cpi = CommPortIdentifier.getPortIdentifier(remote.value());
final CommPort commPort = cpi.open(getClass().getName(), 1000);
commPort.enableReceiveTimeout(config().getOption(READ_TIMEOUT));
deviceAddress = remote;
serialPort = (SerialPort) commPort;
}
示例8
@Override
public SerialPort open(String owner, int timeout) throws PortInUseException {
try {
final CommPort cp = id.open(owner, timeout);
if (cp instanceof gnu.io.SerialPort) {
return new RxTxSerialPort((gnu.io.SerialPort) cp);
} else {
throw new IllegalStateException(
String.format("We expect an serial port instead of '%s'", cp.getClass()));
}
} catch (gnu.io.PortInUseException e) {
throw new PortInUseException();
}
}
示例9
@Override
protected void connectPort() throws Exception {
CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(device);
CommPort commPort = portIdentifier.open(this.getClass().getName(), 2000);
serialPort = (SerialPort) commPort;
setSerialPortParameters(baudrate);
in = serialPort.getInputStream();
out = new DataOutputStream(serialPort.getOutputStream());
}
示例10
/**
* <code>setCommPort</code> sets the comm port member and prepares the input
* and output streams to be used for reading from and writing to.
*
* @param cp the comm port to read from/write to.
* @throws IOException if an I/O related error occurs.
*/
public void setCommPort(CommPort cp) throws IOException {
// Close existing port, if any
close();
m_CommPort = cp;
if (cp != null) {
prepareStreams(cp.getInputStream(), cp.getOutputStream());
}
}
示例11
/**
* {@inheritDoc}
*/
@Override
public void connect() throws EpsonProjectorException {
try {
logger.debug("Open connection to serial port '{}'", serialPortName);
CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(serialPortName);
CommPort commPort = portIdentifier.open(this.getClass().getName(), 2000);
serialPort = (SerialPort) commPort;
serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
serialPort.enableReceiveThreshold(1);
serialPort.disableReceiveTimeout();
in = serialPort.getInputStream();
out = serialPort.getOutputStream();
out.flush();
if (in.markSupported()) {
in.reset();
}
// RXTX serial port library causes high CPU load
// Start event listener, which will just sleep and slow down event loop
serialPort.addEventListener(this);
serialPort.notifyOnDataAvailable(true);
} catch (Exception e) {
throw new EpsonProjectorException(e);
}
}
示例12
/**
* {@inheritDoc}
**/
public void open() {
try {
CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(serialPortName);
CommPort commPort = portIdentifier.open(this.getClass().getName(), 2000);
serialPort = (SerialPort) commPort;
serialPort.setSerialPortParams(baudRate, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
serialPort.enableReceiveThreshold(1);
serialPort.disableReceiveTimeout();
serialOutput = new OutputStreamWriter(serialPort.getOutputStream(), "US-ASCII");
serialInput = new BufferedReader(new InputStreamReader(serialPort.getInputStream()));
setSerialEventHandler(this);
connected = true;
} catch (NoSuchPortException noSuchPortException) {
logger.error("open(): No Such Port Exception: ", noSuchPortException);
connected = false;
} catch (PortInUseException portInUseException) {
logger.error("open(): Port in Use Exception: ", portInUseException);
connected = false;
} catch (UnsupportedCommOperationException unsupportedCommOperationException) {
logger.error("open(): Unsupported Comm Operation Exception: ", unsupportedCommOperationException);
connected = false;
} catch (UnsupportedEncodingException unsupportedEncodingException) {
logger.error("open(): Unsupported Encoding Exception: ", unsupportedEncodingException);
connected = false;
} catch (IOException ioException) {
logger.error("open(): IO Exception: ", ioException);
connected = false;
}
}
示例13
/**
* {@inheritDoc}
*/
public boolean connect(String serialPortName) {
try {
logger.debug("Open connection to serial port '{}'", serialPortName);
CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(serialPortName);
CommPort commPort = portIdentifier.open(this.getClass().getName(), 2000);
serialPort = (SerialPort) commPort;
serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
serialPort.enableReceiveThreshold(1);
serialPort.disableReceiveTimeout();
in = serialPort.getInputStream();
out = serialPort.getOutputStream();
out.flush();
if (in.markSupported()) {
in.reset();
}
// RXTX serial port library causes high CPU load
// Start event listener, which will just sleep and slow down event
// loop
serialPort.addEventListener(this);
serialPort.notifyOnDataAvailable(true);
return true;
} catch (Exception e) {
logger.error("serial port connect error", e);
e.printStackTrace();
return false;
}
}
示例14
public SerialRXTXComm(CommPortIdentifier portIdentifier, Layer3Base layer3) throws NoSuchPortException, PortInUseException, UnsupportedCommOperationException, IOException, TooManyListenersException{
if (portIdentifier.isCurrentlyOwned()) {
throw new IOException("Port is currently in use");
} else {
CommPort commPort = portIdentifier.open(this.getClass().getName(),
TIME_OUT);
if (commPort instanceof SerialPort) {
SerialPort serialPort = (SerialPort) commPort;
serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8,
SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
inStream = serialPort.getInputStream();
outStream = serialPort.getOutputStream();
new SerialReceiver().start();
/*serialPort.addEventListener(this);
serialPort.notifyOnDataAvailable(true);*/
} else {
throw new IOException("This is not a serial port!.");
}
}
this.layer2 = new Layer2Serial(this, layer3);
}
示例15
/**
* Opens the Operation System Serial Port
* <p>
* This method opens the port and set Serial Port parameters according to
* the DSMR specification. Since the specification is clear about these
* parameters there are not configurable.
* <p>
* If there are problem while opening the port, it is the responsibility of
* the calling method to handle this situation (and for example close the
* port again).
* <p>
* Opening an already open port is harmless. The method will return
* immediately
*
* @return true if opening was successful (or port was already open), false
* otherwise
*/
private boolean open() {
synchronized (portLock) {
// Sanity check
if (portState != PortState.CLOSED) {
return true;
}
try {
// GNU.io autodetects standard serial port names
// Add non standard port names if not exists (fixes part of #4175)
if (!portExists(portName)) {
logger.warn("Port {} does not exists according to the system, we will still try to open it",
portName);
}
// Opening Operating System Serial Port
logger.debug("Creating CommPortIdentifier");
CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(portName);
logger.debug("Opening CommPortIdentifier");
CommPort commPort = portIdentifier.open("org.openhab.binding.dsmr", readTimeoutMSec);
logger.debug("Configure serial port");
serialPort = (SerialPort) commPort;
serialPort.enableReceiveThreshold(1);
serialPort.enableReceiveTimeout(readTimeoutMSec);
// Configure Serial Port based on specified port speed
logger.debug("Configure serial port parameters: {}", portSettings);
if (portSettings != null) {
serialPort.setSerialPortParams(portSettings.getBaudrate(), portSettings.getDataBits(),
portSettings.getStopbits(), portSettings.getParity());
/* special settings for low speed port (checking reference here) */
if (portSettings == DSMRPortSettings.LOW_SPEED_SETTINGS) {
serialPort.setDTR(false);
serialPort.setRTS(true);
}
} else {
logger.error("Invalid port parameters, closing port:{}", portSettings);
return false;
}
} catch (NoSuchPortException nspe) {
logger.error("Could not open port: {}", portName, nspe);
return false;
} catch (PortInUseException piue) {
logger.error("Port already in use: {}", portName, piue);
return false;
} catch (UnsupportedCommOperationException ucoe) {
logger.error(
"Port does not support requested port settings " + "(invalid dsmr:portsettings parameter?): {}",
portName, ucoe);
return false;
}
// SerialPort is ready, open the reader
logger.info("SerialPort opened successful");
try {
bis = new BufferedInputStream(serialPort.getInputStream());
} catch (IOException ioe) {
logger.error("Failed to get inputstream for serialPort. Closing port", ioe);
return false;
}
logger.info("DSMR Port opened successful");
return true;
}
}
示例16
private void connectSerial() throws Exception {
logger.debug("Initializing serial port {}", serialPortName);
try {
CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(serialPortName);
CommPort commPort = portIdentifier.open(this.getClass().getName(), 2000);
serialPort = (SerialPort) commPort;
try {
serialPort.setSerialPortParams(4800, SerialPort.DATABITS_8, SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
serialPort.enableReceiveThreshold(1);
serialPort.disableReceiveTimeout();
} catch (UnsupportedCommOperationException unimportant) {
// We might have a perfectly usable PTY even if above operations are unsupported
}
;
inStream = new DataInputStream(serialPort.getInputStream());
outStream = serialPort.getOutputStream();
outStream.flush();
if (inStream.markSupported()) {
inStream.reset();
}
logger.debug("Starting DataListener for {}", PrimareSerialConnector.this.toString());
dataListener = new DataListener();
dataListener.start();
logger.debug("Starting DataListener for {}", PrimareSerialConnector.this.toString());
sendInitMessages();
} catch (NoSuchPortException e) {
logger.error("No such port: {}", serialPortName);
Enumeration portList = CommPortIdentifier.getPortIdentifiers();
if (portList.hasMoreElements()) {
StringBuilder sb = new StringBuilder();
while (portList.hasMoreElements()) {
CommPortIdentifier portId = (CommPortIdentifier) portList.nextElement();
sb.append(String.format("%s ", portId.getName()));
}
logger.error("The following communications ports are available: {}", sb.toString().trim());
} else {
logger.error("There are no communications ports available");
}
logger.error("You may consider OpenHAB startup parameter [ -Dgnu.io.rxtx.SerialPorts={} ]", serialPortName);
throw e;
}
}
示例17
/**
* {@inheritDoc}
**/
@Override
public void open() {
logger.debug("open(): Opening Serial Connection");
try {
CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(serialPortName);
CommPort commPort = portIdentifier.open(this.getClass().getName(), 2000);
serialPort = (SerialPort) commPort;
serialPort.setSerialPortParams(baudRate, SerialPort.DATABITS_8, SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
serialPort.enableReceiveThreshold(1);
serialPort.disableReceiveTimeout();
setInput(serialPort.getInputStream());
setOutput(serialPort.getOutputStream());
getOutput().flush();
if (getInput().markSupported()) {
getInput().reset();
}
setReaderThread(new SerialReaderThread(getInput(), this));
getReaderThread().start();
setConnected(true);
} catch (NoSuchPortException noSuchPortException) {
logger.debug("open(): No Such Port Exception: {}", noSuchPortException.getMessage());
setConnected(false);
} catch (PortInUseException portInUseException) {
logger.debug("open(): Port in Use Exception: {}", portInUseException.getMessage());
setConnected(false);
} catch (UnsupportedCommOperationException unsupportedCommOperationException) {
logger.debug("open(): Unsupported Comm Operation Exception: {}",
unsupportedCommOperationException.getMessage());
setConnected(false);
} catch (UnsupportedEncodingException unsupportedEncodingException) {
logger.debug("open(): Unsupported Encoding Exception: {}", unsupportedEncodingException.getMessage());
setConnected(false);
} catch (IOException ioException) {
logger.debug("open(): IO Exception: ", ioException.getMessage());
setConnected(false);
}
}