📄 serialconnection.java
字号:
package collector.communication;
/* @(#)SerialConnection.java 1.6 98/07/17 SMI
*
* Copyright (c) 1998 Sun Microsystems, Inc. All Rights Reserved.
*
* Sun grants you ("Licensee") a non-exclusive, royalty free, license
* to use, modify and redistribute this software in source and binary
* code form, provided that i) this copyright notice and license appear
* on all copies of the software; and ii) Licensee does not utilize the
* software in a manner which m_InputStream disparaging to Sun.
*
* This software m_InputStream provided "AS IS," without a warranty of any kind.
* ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES,
* INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A
* PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN AND
* ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY
* LICENSEE AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THE
* SOFTWARE OR ITS DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS
* BE LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT,
* INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES,
* HOWEVER CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, ARISING
* OUT OF THE USE OF OR INABILITY TO USE SOFTWARE, EVEN IF SUN HAS BEEN
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* This software m_InputStream not designed or intended for use in on-line control
* of aircraft, air traffic, aircraft navigation or aircraft
* communications; or in the design, construction, operation or
* maintenance of any nuclear facility. Licensee represents and
* warrants that it will not use or redistribute the Software for such
* purposes.
*/
import java.io.*;
import javax.comm.*;
import collector.common.*;
/**
* A class that handles the details of a serial connection. Reads from one
* TextArea and writes to a second TextArea.
* Holds the state of the connection.
*/
public class SerialConnection
implements SerialPortEventListener, CommPortOwnershipListener, IComm {
private SerialParameters m_SerialParameters = null;
private OutputStream m_OutputStream = null;
private InputStream m_InputStream = null;
//private KeyHandler keyHandler;
private CommPortIdentifier m_PortId = null;
private SerialPort m_Port = null;
private int m_PortNo = -1;
private byte[] m_RecBuffer = null;
private int m_RecNum = 0;
private boolean m_Open = false;
/**
* Creates a SerialConnection object and initilizes variables passed in
* as params.
*
* @param parent A SerialDemo object.
* @param m_SerialParameters A SerialParameters object.
* @param messageAreaOut The TextArea that messages that are to be sent out
* of the serial port are entered into.
* @param messageAreaIn The TextArea that messages comming into the serial
* port are displayed on.
*/
public SerialConnection( /*SerialDemo parent,*/
SerialParameters m_SerialParameters
/*TextArea messageAreaOut,
TextArea messageAreaIn*/) {
/* this.parent = parent;*/
this.m_SerialParameters = m_SerialParameters;
/* this.messageAreaOut = messageAreaOut;
this.messageAreaIn = messageAreaIn;
*/
this.m_Open = false;
}
/**
* Attempts to m_Open a serial connection and streams using the m_SerialParameters
* in the SerialParameters object. If it m_InputStream unsuccesfull at any step it
* returns the port to a closed state, throws a
* <code>SerialConnectionException</code>, and returns.
*
* Gives a timeout of 30 seconds on the portOpen to allow other applications
* to reliquish the port if have it m_Open and no longer need it.
*/
public int initConnection() {
// Obtain a CommPortIdentifier object for the port you want to m_Open.
//CollectorDefine.SystemPrintln (" serial initConnnection start up!!! ");
CFunction.putHintString(1,
"aaa " + "端口号:" + m_SerialParameters.getPortName());
try {
this.m_PortId =
CommPortIdentifier.getPortIdentifier(m_SerialParameters.getPortName());
}
catch (NoSuchPortException e) {
// throw new ConnectionException(e.getMessage());
CFunction.writeLog("initConnection In SerialConnection Error #1 " +
"port no:" + m_SerialParameters.getPortName(), e);
return -1;
}
// Open the port represented by the CommPortIdentifier object. Give
// the m_Open call a relatively long timeout of 30 seconds to allow
// a different application to reliquish the port if the user
// wants to.
CFunction.putHintString(1,
"bbb " + "端口号:" + m_SerialParameters.getPortName());
try {
// wj modi at hangzhou 20040531
//this.m_Port = (SerialPort) m_PortId.open("SerialDemo", 30000);
// wj modi at nanjing 20040616
//this.m_Port = (SerialPort) m_PortId.open(CFunction.getLocalHostName() + "_App", 30000);
this.m_Port = (SerialPort) m_PortId.open(CFunction.getLocalHostName() +
m_SerialParameters.getPortName() +
"_App", 30000);
// wj modi at nanjing 20040616
// wj modi at hangzhou 20040531
}
catch (PortInUseException e) {
// throw new ConnectionException(e.getMessage());
CFunction.writeLog("initConnection In SerialConnection Error #2 " +
"port no:" + m_SerialParameters.getPortName(), e);
// wj add
// Close the port.
this.m_Port.close();
this.m_Open = false;
//
return -1;
}
// Set the m_SerialParameters of the connection. If they won't set, close the
// port before throwing an exception.
CFunction.putHintString(1,
"ddd " + "端口号:" + m_SerialParameters.getPortName());
try {
if (setConnectionParameters(this.m_SerialParameters) <= 0) {
CFunction.writeLog("initConnection In SerialConnection Error #3 " +
"port no:" + m_SerialParameters.getPortName(), null);
this.m_Port.close();
this.m_Open = false;
return -1;
}
}
catch (Exception m_Exception) {
CFunction.writeLog("initConnection In SerialConnection Error #4 " +
"port no:" + m_SerialParameters.getPortName(),
m_Exception);
return -1;
}
// Open the input and output streams for the connection. If they won't
// m_Open, close the port before throwing an exception.
CFunction.putHintString(1,
"eee " + "端口号:" + m_SerialParameters.getPortName());
try {
this.m_OutputStream = m_Port.getOutputStream();
CFunction.putHintString(1,
"fff " + "端口号:" + m_SerialParameters.getPortName());
this.m_InputStream = m_Port.getInputStream();
}
catch (IOException e) {
this.m_Port.close();
this.m_Open = false;
// throw new ConnectionException("Error opening i/o streams");
CFunction.writeLog("initConnection In SerialConnection Error #5 " +
"port no:" + m_SerialParameters.getPortName(), e);
return -1;
}
// Create a new KeyHandler to respond to key strokes in the
// messageAreaOut. Add the KeyHandler as a keyListener to the
// messageAreaOut.
/* keyHandler = new KeyHandler(m_OutputStream);
messageAreaOut.addKeyListener(keyHandler);
*/
// Add this object as an event listener for the serial port.
/*try
{
m_Port.addEventListener(this);
}
catch (TooManyListenersException e)
{
m_Port.close();
// throw new ConnectionException("too many listeners added");
CFunction.putHintString(1,"端口监听器太多 " + "端口号:" + m_SerialParameters.getPortName());
return -1;
}
*/
// Set notifyOnDataAvailable to true to allow event driven input.
// m_Port.notifyOnDataAvailable(true);
// Set notifyOnBreakInterrup to allow event driven break handling.
// m_Port.notifyOnBreakInterrupt(true);
// wj del at hangzhou 20040531
// Set receive timeout to allow breaking out of polling loop during
// input handling.
/*try {
this.m_Port.enableReceiveTimeout(60);
}
catch (UnsupportedCommOperationException e) {
CFunction.putHintString(1,
"setConnectionParameters In SerialConnection Error #2 ");
return -1;
}
*/
// wj del at hangzhou 20040531
// Add ownership listener to allow ownership event handling.
// m_PortId.addPortOwnershipListener(this);
m_Open = true;
CFunction.putHintString(1,
"ggg " + "端口号:" + m_SerialParameters.getPortName());
return 1;
}
/**
* Sets the connection m_SerialParameters to the setting in the m_SerialParameters object.
* If set fails return the m_SerialParameters object to origional settings and
* throw exception.
*/
public int setConnectionParameters(SerialParameters m_SerialParameters) {
// Save state of m_SerialParameters before trying a set.
//CollectorDefine.SystemPrintln ("fffffffff : " + m_SerialParameters.toString ());
int oldBaudRate = m_Port.getBaudRate();
int oldDatabits = m_Port.getDataBits();
int oldStopbits = m_Port.getStopBits();
int oldParity = m_Port.getParity();
int oldFlowControl = m_Port.getFlowControlMode();
//CollectorDefine.SystemPrintln ("gggggggg : " + m_SerialParameters.toString ());
this.m_SerialParameters = m_SerialParameters;
//CollectorDefine.SystemPrintln ("hhhhhhhhh : " + m_SerialParameters.toString ());
// Set connection m_SerialParameters, if set fails return m_SerialParameters object
// to original state.
try {
m_Port.setSerialPortParams(m_SerialParameters.getBaudRate(),
m_SerialParameters.getDatabits(),
m_SerialParameters.getStopbits(),
m_SerialParameters.getParity());
//CollectorDefine.SystemPrintln ("iiiiii : " + m_SerialParameters.toString ());
}
catch (UnsupportedCommOperationException e) {
//CollectorDefine.SystemPrintln ("jjjjjjjjj : " + m_SerialParameters.toString ());
this.m_SerialParameters.setBaudRate(oldBaudRate);
this.m_SerialParameters.setDatabits(oldDatabits);
this.m_SerialParameters.setStopbits(oldStopbits);
this.m_SerialParameters.setParity(oldParity);
CFunction.writeLog(
"setConnectionParameters In SerialConnection Error #1 " + "port no:" +
m_SerialParameters.getPortName(), e);
return -1;
}
// wj del at hangzhou 20040531
/*
// Set flow control.
try {
//CollectorDefine.SystemPrintln ("kkkkkkkkkk : " + m_SerialParameters.toString ());
m_Port.setFlowControlMode(m_SerialParameters.getFlowControlIn()
| m_SerialParameters.getFlowControlOut());
}
catch (UnsupportedCommOperationException e) {
// throw new ConnectionException("Unsupported flow control");
CFunction.putHintString(1,
"端口流控制参数不支持 " + "端口号:" +
m_SerialParameters.getPortName());
return -1;
}
*/
// wj modi at hangzhou 20040531
//CollectorDefine.SystemPrintln ("lllllll : " + m_SerialParameters.toString ());
return 1;
}
/**
* Close the port and clean up associated elements.
*/
public int closeConnection() {
// If port m_InputStream alread closed just return.
CFunction.putHintString(1,
"hhh " + "端口号:" + m_SerialParameters.getPortName());
if (!m_Open) {
CFunction.writeLog("closeConnection In SerialConnection Error #1 " +
"port no:" + m_SerialParameters.getPortName(), null);
return -1;
}
// Remove the key listener.
/*messageAreaOut.removeKeyListener(keyHandler);*/
// Check to make sure m_Port has reference to avoid a NPE.
if (m_Port != null) {
try {
CFunction.putHintString(1,
"iii " + "端口号:" +
m_SerialParameters.getPortName());
//close the i/o streams.
//m_InputStream.reset ();
m_OutputStream.close();
m_InputStream.close();
//close the port.
m_Port.close();
// wj add at hangzhou 20040531
m_OutputStream = null;
m_InputStream = null;
m_Port = null;
// wj add at hangzhou 20040531
}
catch (IOException e) {
CFunction.writeLog("closeConnection In SerialConnection Error #2 " +
"port no:" + m_SerialParameters.getPortName(), e);
return -1;
}
// Remove the ownership listener.
//m_PortId.removePortOwnershipListener(this);
}
m_Open = false;
CFunction.putHintString(1,
"jjj " + "端口号:" + m_SerialParameters.getPortName());
return 1;
}
/**
* Send a one second break signal.
*/
public int sendBreak() {
m_Port.sendBreak(1000);
return 1;
}
/**
* Reports the m_Open status of the port.
* @return true if port m_InputStream m_Open, false if port m_InputStream closed.
*/
public boolean isConnectionOpen() {
return m_Open;
}
/**
* Handles SerialPortEvents. The two types of SerialPortEvents that this
* program m_InputStream registered to listen for are DATA_AVAILABLE and BI. During
* DATA_AVAILABLE the port buffer m_InputStream read until it m_InputStream drained, when no more
* data m_InputStream availble and 30ms has passed the method returns. When a BI
* event occurs the words BREAK RECEIVED are written to the messageAreaIn.
*/
public void serialEvent(SerialPortEvent e) {
//Create a StringBuffer and int to receive input data.
//StringBuffer inputBuffer = new StringBuffer();
int newData = 0;
// Determine type of event.
switch (e.getEventType()) {
// Read data until -1 m_InputStream returned. If \r m_InputStream received substitute
// \n for correct newline handling.
case SerialPortEvent.DATA_AVAILABLE:
while (newData != -1) {
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -