Chinaunix首页 | 论坛 | 博客
  • 博客访问: 44010
  • 博文数量: 7
  • 博客积分: 1400
  • 博客等级: 上尉
  • 技术积分: 80
  • 用 户 组: 普通用户
  • 注册时间: 2009-06-16 13:14
文章分类

全部博文(7)

文章存档

2011年(1)

2010年(2)

2009年(4)

我的朋友
最近访客

分类: Java

2010-02-21 12:01:11

First install the library:

Installation of javax.comm on Linux

copy libLinuxSerialParallel.so to /usr/lib/
copy javax.comm.properties to [JDK-directory]/jre/lib/
copy comm.jar to [JDK-directory]/lib/

Installation of rxtxSerial (from ) on Linux

copy librxtxSerial.so to /usr/lib
copy RXTXcomm.jar to [JDK-directory]/jre/lib/ext/

Installation of rxtxSerial (from ) on Windows

copy rxtxSerial.dll to [JDK-directory]\jre\bin\rxtxSerial.dll
copy RXTXcomm.jar to [JDK-directory]\jre\lib\ext\RXTXcomm.jar


UPDATE

You don't have to install the RXTX on your system into system directories. It also works if they are within your project directory, e.g.:
nulltest.java
lib/RXTXcomm.jar
lib/librxtxSerial.so
lib/rxtxSerial.dll
Compile with:
javac -extdirs lib nulltest.java
Run with:
java -Djava.library.path=lib nulltest
That might not work on Windows (just install the RXTX stuff as described above) with a single .class file, but works when you create a .jar with "Class-Path: lib/RXTXcomm.jar" in the manifest.

UPDATE:
If you use a USB-to-Serial converter, remove the line:
serialPort.notifyOnOutputEmpty(true);
Otherwise the application will hang. It seems that the linux kernel driver usbserial doesn't support the event OUTPUT_BUFFER_EMPTY.

Below we have an example which sends a string to one serial port, receives it on the same port. You need a null-modem for this (just connect the RX and TX pins of your serial port to test this). In a production environment this example can be used as a template for sending and receiving data from e.g. a micro-controller board.

nulltext.java

// derived from SUN's examples in the javax.comm package
import java.io.*;
import java.util.*;
//import javax.comm.*; // for SUN's serial/parallel port libraries
import gnu.io.*; // for rxtxSerial library

public class nulltest implements Runnable, SerialPortEventListener {
static CommPortIdentifier portId;
static CommPortIdentifier saveportId;
static Enumeration portList;
InputStream inputStream;
SerialPort serialPort;
Thread readThread;

static String messageString = "Hello, world!";
static OutputStream outputStream;
static boolean outputBufferEmptyFlag = false;

public static void main(String[] args) {
boolean portFound = false;
String defaultPort;

// determine the name of the serial port on several operating systems
String osname = System.getProperty("os.name","").toLowerCase();
if ( osname.startsWith("windows") ) {
// windows
defaultPort = "COM1";
} else if (osname.startsWith("linux")) {
// linux
defaultPort = "/dev/ttyS0";
} else if ( osname.startsWith("mac") ) {
// mac
defaultPort = "????";
} else {
System.out.println("Sorry, your operating system is not supported");
return;
}

if (args.length > 0) {
defaultPort = args[0];
}

System.out.println("Set default port to "+defaultPort);

// parse ports and if the default port is found, initialized the reader
portList = CommPortIdentifier.getPortIdentifiers();
while (portList.hasMoreElements()) {
portId = (CommPortIdentifier) portList.nextElement();
if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
if (portId.getName().equals(defaultPort)) {
System.out.println("Found port: "+defaultPort);
portFound = true;
// init reader thread
nulltest reader = new nulltest();
}
}

}
if (!portFound) {
System.out.println("port " + defaultPort + " not found.");
}

}

public void initwritetoport() {
// initwritetoport() assumes that the port has already been opened and
// initialized by "public nulltest()"

try {
// get the outputstream
outputStream = serialPort.getOutputStream();
} catch (IOException e) {}

try {
// activate the OUTPUT_BUFFER_EMPTY notifier
serialPort.notifyOnOutputEmpty(true);
} catch (Exception e) {
System.out.println("Error setting event notification");
System.out.println(e.toString());
System.exit(-1);
}

}

public void writetoport() {
System.out.println("Writing \""+messageString+"\" to "+serialPort.getName());
try {
// write string to serial port
outputStream.write(messageString.getBytes());
} catch (IOException e) {}
}

public nulltest() {
// initalize serial port
try {
serialPort = (SerialPort) portId.open("SimpleReadApp", 2000);
} catch (PortInUseException e) {}

try {
inputStream = serialPort.getInputStream();
} catch (IOException e) {}

try {
serialPort.addEventListener(this);
} catch (TooManyListenersException e) {}

// activate the DATA_AVAILABLE notifier
serialPort.notifyOnDataAvailable(true);

try {
// set port parameters
serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
} catch (UnsupportedCommOperationException e) {}

// start the read thread
readThread = new Thread(this);
readThread.start();

}

public void run() {
// first thing in the thread, we initialize the write operation
initwritetoport();
try {
while (true) {
// write string to port, the serialEvent will read it
writetoport();
Thread.sleep(1000);
}
} catch (InterruptedException e) {}
}

public void serialEvent(SerialPortEvent event) {
switch (event.getEventType()) {
case SerialPortEvent.BI:
case SerialPortEvent.OE:
case SerialPortEvent.FE:
case SerialPortEvent.PE:
case SerialPortEvent.CD:
case SerialPortEvent.CTS:
case SerialPortEvent.DSR:
case SerialPortEvent.RI:
case SerialPortEvent.OUTPUT_BUFFER_EMPTY:
break;
case SerialPortEvent.DATA_AVAILABLE:
// we get here if data has been received
byte[] readBuffer = new byte[20];
try {
// read data
while (inputStream.available() > 0) {
int numBytes = inputStream.read(readBuffer);
}
// print data
String result = new String(readBuffer);
System.out.println("Read: "+result);
} catch (IOException e) {}

break;
}
}

}

Scripts for javax.comm on Linux

Compile shell script

#!/bin/sh
javac -cp /usr/jdk1.6.0/lib/comm.jar nulltest.java

run shell script

#!/bin/sh
# "export" only for javax.comm
export CLASSPATH=$CLASSPATH:/usr/jdk1.6.0/lib/comm.jar
java -Djava.library.path=/usr/lib nulltest

Scripts for rxtxSerial from rxtx.org on Linux

Compile shell script

#!/bin/sh
javac nulltest.java

run shell script

#!/bin/sh
java nulltest

Scripts for rxtxSerial from rxtx.org on Windows

Compile BAT script

javac nulltest.java

run BAT script

java nulltest

Error messages and solutions

Exception in thread "main" java.lang.NoClassDefFoundError: nulltest
This can mean that your CLASSPATH is not set to the current directory. Set the CLASSPATH also to the current directory with (on Windows):
set classpath=.;%classpath%;
or try this to run "nulltest":
java -cp . nulltest


$ java -Djava.library.path=/usr/lib nulltest
Exception in thread "main" java.lang.UnsupportedClassVersionError:
Bad version number in .class file
This usually means that your application has been compiled with a newer version of JDK than the version you try to run it with. For example, the source code is compiled with JDK 1.4 but executed with JRE 1.3. JRE 1.3 does not understand the new format of .class files generated by compiler from JDK 1.4 so you get the error message.

$ /usr/jdk1.6.0/bin/java nulltest
Error loading LinuxSerialParallel: java.lang.UnsatisfiedLinkError:
no LinuxSerialParallel in java.library.path
Exception in thread "main" java.lang.UnsatisfiedLinkError:
com.sun.comm.Unix.isDevLink(Ljava/lang/String;)Z
at com.sun.comm.Unix.isDevLink(Native Method)
at com.sun.comm.PathBundle.add(PathBundle.java:108)
at com.sun.comm.PlatformPortBundle.(PlatformPortBundle.java:44)
at javax.comm.CommPortIdentifier.(CommPortIdentifier.java:138)
Make sure that libLinuxSerialParallel.so is in /usr/lib/ and can be read by the user your running the java application

java -Djava.library.path=/usr/lib nulltest
java.lang.UnsatisfiedLinkError: no rxtxSerial in java.library.path
thrown while loading gnu.io.RXTXCommDriver
Exception in thread "main" java.lang.UnsatisfiedLinkError: no rxtxSerial in java.library.path
at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1682)
at java.lang.Runtime.loadLibrary0(Runtime.java:823)
at java.lang.System.loadLibrary(System.java:1030)
at gnu.io.CommPortIdentifier.(CommPortIdentifier.java:83)
Make sure the rxtx library is installed as shown above.


阅读(5240) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~