java-org.hwo.servicelink/src/org/hwo/servicelink/ng/StreamContainer.java

114 lines
2.1 KiB
Java

package org.hwo.servicelink.ng;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import static org.hwo.logging.Logging.*;
import org.hwo.io.NewSerialPort.NewSerialPort;
public class StreamContainer {
boolean exceptionCaught = false;
InputStream inStream;
OutputStream outStream;
Socket socket = null;
NewSerialPort newSerialPort = null;
public StreamContainer(String url) {
int dots = url.indexOf(':');
String proto,target;
if (dots == -1) {
proto = "serial";
target = url;
} else {
proto = url.substring(0, dots);
target = url.substring(dots + 1);
}
switch (proto) {
case "serial":
newSerialPort = new NewSerialPort(target);
newSerialPort.setTimeOut(250);
if (newSerialPort.open()) {
inStream = newSerialPort.getInputStream();
outStream = newSerialPort.getOutputStream();
}
break;
case "tcp":
try {
socket = new Socket(target,3009);
socket.setSoTimeout(150);
socket.setTcpNoDelay(true);
inStream = socket.getInputStream();
outStream = socket.getOutputStream();
} catch (IOException e) {
log(e);
}
break;
}
}
public StreamContainer(InputStream inStream,OutputStream outStream)
{
this.inStream = inStream;
this.outStream = outStream;
}
public StreamContainer(NewSerialPort serialPort)
{
this.inStream = serialPort.getInputStream();
this.outStream = serialPort.getOutputStream();
}
public StreamContainer(Socket socket) throws IOException
{
this.inStream = socket.getInputStream();
this.outStream = socket.getOutputStream();
}
public void close() {
try {
if (this.inStream != null)
this.inStream.close();
if (this.outStream != null)
this.outStream.close();
if (this.socket != null) {
this.socket.close();
}
if (this.newSerialPort != null) {
this.newSerialPort.close();
}
} catch (IOException e) {
log(e);
}
exceptionCaught = true;
}
public InputStream getInStream() {
return inStream;
}
public OutputStream getOutStream() {
return outStream;
}
}