forked from LupusNobilis/java-org.hwo
107 lines
2.4 KiB
Java
107 lines
2.4 KiB
Java
package org.hwo.io;
|
|
|
|
import java.io.File;
|
|
import java.io.FilenameFilter;
|
|
import java.io.IOException;
|
|
import java.io.InputStream;
|
|
import java.io.OutputStream;
|
|
import java.util.ArrayList;
|
|
import java.util.concurrent.TimeoutException;
|
|
|
|
import org.hwo.fifo.FiFo;
|
|
import org.hwo.nativeloader.NativeLoader;
|
|
|
|
public class NativeSerialPort extends SerialPort {
|
|
|
|
class SerialPortInputStream extends InputStream
|
|
{
|
|
@Override
|
|
public int read() throws IOException {
|
|
if (!isOpen())
|
|
throw new IOException("Port nicht gešffnet!");
|
|
|
|
int ch = native_getch(nativeHandle,getTimeout());
|
|
//System.err.println(String.format("RX: 0x%08x", ch));
|
|
if (ch < 0)
|
|
throw new IOException(String.format("native_getch: returned: %d",ch));
|
|
return ch;
|
|
}
|
|
|
|
}
|
|
|
|
class SerialPortOutputStream extends OutputStream
|
|
{
|
|
@Override
|
|
public void write(int arg0) throws IOException {
|
|
if (!isOpen())
|
|
throw new IOException("Port nicht gešffnet!");
|
|
//System.err.println(String.format("TX: 0x%08x", arg0));
|
|
native_putch(nativeHandle, getTimeout(), arg0);
|
|
}
|
|
}
|
|
|
|
|
|
private static native int native_open(String portName);
|
|
private static native int native_close(int handle);
|
|
private static native int native_send(int handle,byte[] data);
|
|
private static native int native_recv(int handle,byte[] data);
|
|
|
|
private static native int native_getch(int handle,int timeout);
|
|
private static native int native_putch(int handle,int timeout,int ch);
|
|
|
|
private int nativeHandle;
|
|
|
|
private SerialPortInputStream inputStream;
|
|
private SerialPortOutputStream outputStream;
|
|
|
|
public NativeSerialPort()
|
|
{
|
|
nativeHandle = -1;
|
|
inputStream = new SerialPortInputStream();
|
|
outputStream = new SerialPortOutputStream();
|
|
}
|
|
|
|
@Override
|
|
public boolean isOpen() {
|
|
return (nativeHandle >= 0);
|
|
}
|
|
|
|
@Override
|
|
public boolean open() {
|
|
if (isOpen())
|
|
return false;
|
|
|
|
nativeHandle = native_open(getPortName());
|
|
System.err.println(String.format("NativeSerialPort: nativeHandle: %d",nativeHandle));
|
|
if (nativeHandle < 0)
|
|
return false;
|
|
|
|
return true;
|
|
}
|
|
|
|
@Override
|
|
public void close() {
|
|
if (nativeHandle >= 0)
|
|
{
|
|
System.err.println(String.format("NativeSerialPort: Closing nativeHandle %d",nativeHandle));
|
|
native_close(nativeHandle);
|
|
}
|
|
nativeHandle = -1;
|
|
}
|
|
|
|
@Override
|
|
public InputStream getInputStream() {
|
|
return inputStream;
|
|
}
|
|
|
|
@Override
|
|
public OutputStream getOutputStream() {
|
|
return outputStream;
|
|
}
|
|
|
|
static {
|
|
NativeLoader.loadLibrary("hwoio");
|
|
}
|
|
|
|
}
|