use of gnu.io.UnsupportedCommOperationException in project openhab1-addons by openhab.
the class UPBBinding method openSerialPort.
private SerialPort openSerialPort() {
SerialPort serialPort = null;
CommPortIdentifier portId;
try {
portId = CommPortIdentifier.getPortIdentifier(port);
} catch (NoSuchPortException e1) {
throw new RuntimeException("Port does not exist", e1);
}
if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
if (portId.getName().equals(port)) {
try {
serialPort = portId.open("UPB", 1000);
} catch (PortInUseException e) {
throw new RuntimeException("Port is in use", e);
}
try {
serialPort.setSerialPortParams(4800, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
serialPort.setFlowControlMode(SerialPort.FLOWCONTROL_NONE);
serialPort.enableReceiveTimeout(100);
} catch (UnsupportedCommOperationException e) {
throw new RuntimeException("Failed to configure serial port");
}
}
}
return serialPort;
}
use of gnu.io.UnsupportedCommOperationException in project JMRI by JMRI.
the class SerialDriverAdapter method openPort.
@Override
public String openPort(String portName, String appName) {
try {
// get and open the primary port
CommPortIdentifier portID = CommPortIdentifier.getPortIdentifier(portName);
try {
// name of program, msec to wait
activeSerialPort = (SerialPort) portID.open(appName, 2000);
} catch (PortInUseException p) {
return handlePortBusy(p, portName, log);
}
// try to set it for serial
try {
setSerialPort();
} catch (gnu.io.UnsupportedCommOperationException e) {
log.error("Cannot set serial parameters on port " + portName + ": " + e.getMessage());
return "Cannot set serial parameters on port " + portName + ": " + e.getMessage();
}
// set receive timeout; framing not in use
try {
activeSerialPort.enableReceiveTimeout(10);
log.debug("Serial timeout was observed as: " + activeSerialPort.getReceiveTimeout() + " " + activeSerialPort.isReceiveTimeoutEnabled());
} catch (UnsupportedCommOperationException et) {
log.info("failed to set serial timeout: " + et);
}
// get and save stream
serialStream = activeSerialPort.getInputStream();
// purge contents, if any
purgeStream(serialStream);
// report status?
if (log.isInfoEnabled()) {
// report now
log.info(portName + " port opened at " + activeSerialPort.getBaudRate() + " baud with" + " DTR: " + activeSerialPort.isDTR() + " RTS: " + activeSerialPort.isRTS() + " DSR: " + activeSerialPort.isDSR() + " CTS: " + activeSerialPort.isCTS() + " CD: " + activeSerialPort.isCD());
}
if (log.isDebugEnabled()) {
// report additional status
log.debug(" port flow control shows " + (activeSerialPort.getFlowControlMode() == SerialPort.FLOWCONTROL_RTSCTS_OUT ? "hardware flow control" : "no flow control"));
}
if (log.isDebugEnabled()) {
// arrange to notify later
activeSerialPort.addEventListener((SerialPortEvent e) -> {
int type = e.getEventType();
switch(type) {
case SerialPortEvent.DATA_AVAILABLE:
log.info("SerialEvent: DATA_AVAILABLE is {}", e.getNewValue());
return;
case SerialPortEvent.OUTPUT_BUFFER_EMPTY:
log.info("SerialEvent: OUTPUT_BUFFER_EMPTY is {}", e.getNewValue());
return;
case SerialPortEvent.CTS:
log.info("SerialEvent: CTS is {}", e.getNewValue());
return;
case SerialPortEvent.DSR:
log.info("SerialEvent: DSR is {}", e.getNewValue());
return;
case SerialPortEvent.RI:
log.info("SerialEvent: RI is {}", e.getNewValue());
return;
case SerialPortEvent.CD:
log.info("SerialEvent: CD is {}", e.getNewValue());
return;
case SerialPortEvent.OE:
log.info("SerialEvent: OE (overrun error) is {}", e.getNewValue());
return;
case SerialPortEvent.PE:
log.info("SerialEvent: PE (parity error) is {}", e.getNewValue());
return;
case SerialPortEvent.FE:
log.info("SerialEvent: FE (framing error) is {}", e.getNewValue());
return;
case SerialPortEvent.BI:
log.info("SerialEvent: BI (break interrupt) is {}", e.getNewValue());
return;
default:
log.info("SerialEvent of unknown type: {} value: {}", type, e.getNewValue());
}
});
try {
activeSerialPort.notifyOnFramingError(true);
} catch (Exception e) {
log.debug("Could not notifyOnFramingError: " + e);
}
try {
activeSerialPort.notifyOnBreakInterrupt(true);
} catch (Exception e) {
log.debug("Could not notifyOnBreakInterrupt: " + e);
}
try {
activeSerialPort.notifyOnParityError(true);
} catch (Exception e) {
log.debug("Could not notifyOnParityError: " + e);
}
try {
activeSerialPort.notifyOnOverrunError(true);
} catch (Exception e) {
log.debug("Could not notifyOnOverrunError: " + e);
}
}
opened = true;
} catch (gnu.io.NoSuchPortException p) {
return handlePortNotFound(p, portName, log);
} catch (IOException | TooManyListenersException ex) {
log.error("Unexpected exception while opening port {} trace follows: ", portName, ex);
return "Unexpected error while opening port " + portName + ": " + ex;
}
// normal operation
return null;
}
use of gnu.io.UnsupportedCommOperationException in project openhab1-addons by openhab.
the class Stick method initialize.
/**
* Initialize this device and open the serial port
*
* @throws PlugwiseInitializationException if port can not be opened
*/
@SuppressWarnings("rawtypes")
private void initialize() throws PlugwiseInitializationException {
// Flush the deviceCache
plugwiseDeviceCache.clear();
// parse ports and if the default port is found, initialized the reader
Enumeration portList = CommPortIdentifier.getPortIdentifiers();
while (portList.hasMoreElements()) {
CommPortIdentifier id = (CommPortIdentifier) portList.nextElement();
if (id.getPortType() == CommPortIdentifier.PORT_SERIAL) {
if (id.getName().equals(port)) {
logger.debug("Serial port '{}' has been found.", port);
portId = id;
}
}
}
if (portId != null) {
// initialize serial port
try {
serialPort = portId.open("openHAB", 2000);
} catch (PortInUseException e) {
throw new PlugwiseInitializationException(e);
}
try {
serialPort.addEventListener(this);
} catch (TooManyListenersException e) {
throw new PlugwiseInitializationException(e);
}
// activate the DATA_AVAILABLE notifier
serialPort.notifyOnDataAvailable(true);
try {
// set port parameters
serialPort.setSerialPortParams(115200, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
} catch (UnsupportedCommOperationException e) {
throw new PlugwiseInitializationException(e);
}
try {
// get the output stream
outputChannel = Channels.newChannel(serialPort.getOutputStream());
} catch (IOException e) {
throw new PlugwiseInitializationException(e);
}
} else {
StringBuilder sb = new StringBuilder();
portList = CommPortIdentifier.getPortIdentifiers();
while (portList.hasMoreElements()) {
CommPortIdentifier id = (CommPortIdentifier) portList.nextElement();
if (id.getPortType() == CommPortIdentifier.PORT_SERIAL) {
sb.append(id.getName() + "\n");
}
}
throw new PlugwiseInitializationException("Serial port '" + port + "' could not be found. Available ports are:\n" + sb);
}
initialised = true;
// initialise the Stick
sendMessage(new InitialiseRequestMessage());
}
use of gnu.io.UnsupportedCommOperationException in project openhab1-addons by openhab.
the class PowerMaxSerialConnector method open.
/**
* {@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);
}
}
use of gnu.io.UnsupportedCommOperationException in project openhab1-addons by openhab.
the class Connection method read.
/**
* Requests a data message from the remote device using IEC 62056-21 Mode C.
* The data message received is parsed and a list of data sets is returned.
*
* @return A list of data sets contained in the data message response from
* the remote device. The first data set will contain the
* "identification" of the meter as the id and empty strings for
* value and unit.
* @throws IOException
* if any kind of error other than timeout occurs while trying
* to read the remote device. Note that the connection is not
* closed when an IOException is thrown.
* @throws TimeoutException
* if no response at all (not even a single byte) was received
* from the meter within the timeout span.
*/
public List<DataSet> read() throws IOException, TimeoutException {
if (serialPort == null) {
throw new IllegalStateException("Connection is not open.");
}
try {
serialPort.setSerialPortParams(300, SerialPort.DATABITS_7, SerialPort.STOPBITS_1, SerialPort.PARITY_EVEN);
} catch (UnsupportedCommOperationException e) {
throw new IOException("Unable to set the given serial comm parameters", e);
}
if (initMessage != null) {
os.write(initMessage);
os.flush();
}
os.write(REQUEST_MESSAGE);
os.flush();
int baudRateSetting;
char protocolMode;
int baudRate;
boolean readSuccessful = false;
int timeval = 0;
int numBytesReadTotal = 0;
while (timeout == 0 || timeval < timeout) {
if (is.available() > 0) {
int numBytesRead = is.read(buffer, numBytesReadTotal, INPUT_BUFFER_LENGTH - numBytesReadTotal);
numBytesReadTotal += numBytesRead;
if (numBytesRead > 0) {
timeval = 0;
}
if (((handleEcho && numBytesReadTotal > 11) || (!handleEcho && numBytesReadTotal > 6)) && buffer[numBytesReadTotal - 2] == 0x0D && buffer[numBytesReadTotal - 1] == 0x0A) {
readSuccessful = true;
break;
}
}
try {
Thread.sleep(SLEEP_INTERVAL);
} catch (InterruptedException e) {
}
timeval += SLEEP_INTERVAL;
}
int offset = 0;
if (handleEcho) {
offset = 5;
}
if (numBytesReadTotal == offset) {
throw new TimeoutException();
}
if (!readSuccessful) {
throw new IOException("Timeout while listening for Identification Message");
}
// System.out
// .println("Got the following identification message: " +
// getByteArrayString(buffer, numBytesReadTotal));
int startPosition = 0;
while (startPosition < numBytesReadTotal) {
if (buffer[startPosition] == (byte) 0x2F) {
if (buffer[startPosition + 1] == (byte) 0x00 | buffer[startPosition + 1] == (byte) 0x7F) {
startPosition++;
} else {
break;
}
continue;
}
startPosition++;
}
byte[] bytes = new byte[numBytesReadTotal - startPosition];
System.arraycopy(buffer, startPosition, bytes, 0, numBytesReadTotal - startPosition);
/* baudrate identification http://manuals.lian98.biz/doc.en/html/u_iec62056_struct.htm
* Protocol mode A : no baudrate change
* Protocol mode B : char from A to I; no acknowledgement
* Protocol mode C : char from 0 to 9; with acknowledgement
*/
baudRateSetting = bytes[offset + 4];
if (baudRateSetting >= 0x41 && baudRateSetting <= 0x49) {
//Mode B
protocolMode = 'B';
//search with index (start with baudrate 600)
baudRate = baudRates[baudRateSetting - 0x40];
} else if (baudRateSetting >= 0x30 && baudRateSetting <= 0x39) {
//Mode C or E
protocolMode = 'C';
//search with index
baudRate = baudRates[baudRateSetting - 0x30];
} else if (baudRateSetting >= 0x32) {
//Mode D no baudrate change
protocolMode = 'D';
baudRate = -1;
} else {
//Mode A no baudrate change
protocolMode = 'A';
baudRate = -1;
}
String identification = new String(buffer, offset + 5, numBytesReadTotal - offset - 7, charset);
if (protocolMode == 'B' || protocolMode == 'C') {
if (baudRate == -1) {
throw new IOException("Syntax error in identification message received: unknown baud rate received: (hex: " + Hex.encodeHexString(bytes) + ")");
}
}
if (protocolMode == 'C') {
ACKNOWLEDGE[2] = (byte) baudRateSetting;
os.write(ACKNOWLEDGE);
os.flush();
}
if (handleEcho) {
readSuccessful = false;
numBytesReadTotal = 0;
while (timeout == 0 || timeval < timeout) {
if (is.available() > 0) {
int numBytesRead = is.read(buffer, numBytesReadTotal, ACKNOWLEDGE.length - numBytesReadTotal);
numBytesReadTotal += numBytesRead;
if (numBytesRead > 0) {
timeval = 0;
}
if (numBytesReadTotal == ACKNOWLEDGE.length) {
readSuccessful = true;
break;
}
}
try {
Thread.sleep(SLEEP_INTERVAL);
} catch (InterruptedException e) {
}
timeval += SLEEP_INTERVAL;
}
// if (readSuccessful) {
// System.out.println("Received the following echo of the acknowledge successfully : "
// + getByteArrayString(buffer, numBytesReadTotal));
// }
// else {
// System.out.println("Receiving full echo failed.");
// }
}
if (baudRateChangeDelay > 0) {
try {
Thread.sleep(baudRateChangeDelay);
} catch (InterruptedException e1) {
}
}
try {
serialPort.setSerialPortParams(baudRate, SerialPort.DATABITS_7, SerialPort.STOPBITS_1, SerialPort.PARITY_EVEN);
} catch (UnsupportedCommOperationException e) {
throw new IOException("Serial Port does not support " + baudRate + "bd 7E1");
}
readSuccessful = false;
numBytesReadTotal = 0;
int etxIndex = -1;
while (timeout == 0 || timeval < timeout) {
int available = is.available();
if (available > 0) {
if (buffer.length < (numBytesReadTotal + available)) {
//grow buffer
buffer = Arrays.copyOf(buffer, numBytesReadTotal + available);
}
int numBytesRead = is.read(buffer, numBytesReadTotal, available);
numBytesReadTotal += numBytesRead;
if (numBytesRead > 0) {
timeval = 0;
}
if ((etxIndex = findEtx(buffer, numBytesRead, numBytesReadTotal)) != -1 || (numBytesReadTotal > 4 && buffer[numBytesReadTotal - 3] == 0x21) || (numBytesReadTotal > 7 && buffer[numBytesReadTotal - 5] == 0x21)) {
readSuccessful = true;
break;
}
}
try {
Thread.sleep(SLEEP_INTERVAL);
} catch (InterruptedException e) {
}
timeval += SLEEP_INTERVAL;
}
if (!readSuccessful) {
throw new IOException("Timeout while listening for Data Message");
}
// System.out.println("Got the following data message: " +
// getByteArrayString(buffer, numBytesReadTotal));
int index;
int endIndex;
// if 2nd last character is ETX
if (etxIndex != -1) {
if (numBytesReadTotal < 8) {
throw new IOException("Data message does not have minimum length of 8.");
}
index = 1;
endIndex = etxIndex - 3;
if (buffer[0] != 0x02) {
startPosition = 0;
while (startPosition < numBytesReadTotal) {
if (buffer[startPosition] == (byte) 0x02) {
break;
} else {
if (startPosition < numBytesReadTotal - 2) {
startPosition++;
} else {
throw new IOException("STX (0x02) character is expected but not received as first byte of data message. (hex: " + Hex.encodeHexString(buffer) + ")");
}
}
}
}
} else {
if (numBytesReadTotal < 5) {
throw new IOException("Data message does not have minimum length of 5.");
}
index = 0;
endIndex = numBytesReadTotal - 3;
}
if (buffer[endIndex + 1] != 0x0D) {
throw new IOException("CR (0x0D) character is expected but not received after data block of data message. (hex: " + Hex.encodeHexString(buffer) + ")");
}
if (buffer[endIndex + 2] != 0x0A) {
throw new IOException("LF (0x0A) character is expected but not received after data block of data message. (hex: " + Hex.encodeHexString(buffer) + ")");
}
List<DataSet> dataSets = new ArrayList<DataSet>();
dataSets.add(new DataSet(identification, "", ""));
while (index != endIndex) {
String id = null;
for (int i = index; i < endIndex - 1; i++) {
if (buffer[i] == 0x28) {
// found '('
id = new String(buffer, index, i - index, charset);
index = i + 1;
break;
}
}
if (id == null) {
throw new IOException("'(' (0x28) character is expected but not received inside data block of data message. (hex: " + Hex.encodeHexString(buffer) + ")");
}
String value = "";
String unit = "";
for (int i = index; i < endIndex; i++) {
if (buffer[i] == 0x2A) {
// found '*'
if (i > index) {
value = new String(buffer, index, i - index, charset);
}
index = i + 1;
for (int j = index; j < endIndex; j++) {
if (buffer[j] == 0x29) {
// found ')'
unit = new String(buffer, index, j - index, charset);
index = j + 1;
break;
}
}
break;
} else if (buffer[i] == 0x29) {
// found ')'
if (i > index) {
value = new String(buffer, index, i - index, charset);
}
index = i + 1;
break;
}
}
if (buffer[index - 1] != 0x29) {
throw new IOException("')' (0x29) character is expected but not received inside data block of data message. (hex: " + Hex.encodeHexString(buffer) + ")");
}
dataSets.add(new DataSet(id, value, unit));
if (buffer[index] == 0x0d && buffer[index + 1] == 0x0a) {
index += 2;
}
}
return dataSets;
}
Aggregations