Information fra comport via USB-to-serial kabel
Hej!Jeg forsøger at læse information fra en com-port. Jeg har fundet flere gode klasser til læsning af information fra com-porte, også eksempler her på Eksperten, som skulle virke. Men jag kan altå ikke få dem til at fungere. Kan det skyldes, at jeg bruger et ATEN USB to Serial Bridge kabel, og i princippet omdanner min USB-port til COM6?
Lige nu arbejder jeg på denne klasse, som jeg har fundet her på Eksperten:
package test_comport2;
/**
* <p>Title: </p>
* <p>Description: </p>
* <p>Copyright: Copyright (c) 2004</p>
* <p>Company: </p>
* @author not attributable
* @version 1.0
*/
import java.io.*;
import java.util.*;
import javax.comm.*;
public class PortSnuserT
{
SerialPort serialPort;
public BufferedReader in;
public BufferedWriter out;
static public void error(String s)
{
System.err.println("ComPortAPI: " + s);
System.exit(0);
}
static public void debug(String s)
{
//System.out.println(\"ComPortAPI: \" + s);
}
public PortSnuserT(String port_name)
{
CommPortIdentifier portId = null;
debug("serialOpen");
debug("system " + System.getProperty("os.name"));
//* Find en FUCKING port!!!!
Enumeration portList = CommPortIdentifier.getPortIdentifiers();
if (port_name!=null)
{
debug("looking for " + port_name);
}
while (portList.hasMoreElements())
{
CommPortIdentifier pi = (CommPortIdentifier) portList.nextElement();
if (pi.getPortType() == CommPortIdentifier.PORT_SERIAL)
{
debug("found port "+pi.getName());
if ((port_name==null) || (pi.getName().equals(port_name)))
{
/* Fundet en port */
portId=pi;
break;
}
}
}
System.out.println(portId.getName());
if (portId==null)
{
error("Ingen Port fundet. du er et fjols !!!!!)");
}
/* En port er fundet. Åbn porten. */
try
{
serialPort = (SerialPort) portId.open("René", 2000);
}
catch (PortInUseException e) {error("PortInUseException " +e);
}
/* Opretter streams for læse og skrive til port. */
try {
in=new BufferedReader(new InputStreamReader(serialPort.getInputStream()));
out=new BufferedWriter(new OutputStreamWriter(serialPort.getOutputStream()));
} catch (IOException e) {error("IOException " +e);
}
/* Sætter port mode til 4800 baud, 8 data, 1 stop bit og ingen partitet. */
try {
serialPort.setSerialPortParams(19200,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
} catch (UnsupportedCommOperationException e) {error("UnsupportedCommOperationException " +e);
}
System.out.println("using port " + portId.getName()+" at 19200 baud, 8 data, 1 stop and no parity");
}
public String readLine()
{
String line=null;
try
{
line=in.readLine();
}
catch( IOException e )
{
error("readLine " + e );
}
return(line);
}
public void writeString(String ud)
{
try
{
out.write(ud);
}
catch( IOException e )
{
error("writeLine " + e );
}
}
public void serialClose()
{
//debug(\"serialClose\");
try
{
if (in != null)
{
//debug(\"close\");
in.close();
in=null;
}
}
catch( IOException e )
{
error("close " + e );
}
}
}
