forked from LupusNobilis/java-org.hwo
SerialPort
parent
c0e197be91
commit
a304f89c30
|
@ -0,0 +1,112 @@
|
|||
package org.hwo.io;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.BufferedWriter;
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileNotFoundException;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.FilenameFilter;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStreamReader;
|
||||
import java.io.OutputStreamWriter;
|
||||
import java.io.RandomAccessFile;
|
||||
import java.util.ArrayList;
|
||||
|
||||
public class SerialPort {
|
||||
|
||||
static public String[] getPortNames()
|
||||
{
|
||||
return getPortNamesOSX();
|
||||
}
|
||||
|
||||
private static String[] getPortNamesOSX()
|
||||
{
|
||||
ArrayList<String> portNames = new ArrayList<String>();
|
||||
|
||||
File devDir = new File("/dev");
|
||||
File[] list = devDir.listFiles(new FilenameFilter() {
|
||||
|
||||
@Override
|
||||
public boolean accept(File arg0, String arg1) {
|
||||
System.err.println("File: " +arg1);
|
||||
if (arg1.startsWith("tty."))
|
||||
return true;
|
||||
return false;
|
||||
}
|
||||
});
|
||||
|
||||
for (File file:list)
|
||||
portNames.add("/dev/" + file.getName());
|
||||
|
||||
return portNames.toArray(new String[0]);
|
||||
}
|
||||
|
||||
private String portName;
|
||||
|
||||
private FileInputStream fis;
|
||||
private FileOutputStream fos;
|
||||
|
||||
private BufferedReader br;
|
||||
private BufferedWriter bw;
|
||||
|
||||
public SerialPort(String portName)
|
||||
{
|
||||
this.portName = portName;
|
||||
fis = null;
|
||||
fos = null;
|
||||
}
|
||||
|
||||
public boolean open()
|
||||
{
|
||||
try {
|
||||
System.err.println("Opening: " + this.portName);
|
||||
fis = new FileInputStream(this.portName);
|
||||
br = new BufferedReader(new InputStreamReader(fis));
|
||||
fos = new FileOutputStream(this.portName);
|
||||
bw = new BufferedWriter(new OutputStreamWriter(fos));
|
||||
System.err.println("Opened: " + this.portName);
|
||||
|
||||
} catch (FileNotFoundException e) {
|
||||
e.printStackTrace();
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public void close()
|
||||
{
|
||||
try
|
||||
{
|
||||
if (br != null)
|
||||
{
|
||||
br.close();
|
||||
br = null;
|
||||
}
|
||||
if (bw != null)
|
||||
{
|
||||
bw.close();
|
||||
bw = null;
|
||||
}
|
||||
} catch (Exception e)
|
||||
{
|
||||
System.err.println("Exc: " + e);
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public void WriteLine(String line) throws IOException
|
||||
{
|
||||
|
||||
bw.write(line + "\r\n");
|
||||
bw.flush();
|
||||
}
|
||||
|
||||
public String ReadLine() throws IOException
|
||||
{
|
||||
return br.readLine();
|
||||
}
|
||||
|
||||
|
||||
}
|
Loading…
Reference in New Issue