免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 6727 | 回复: 0
打印 上一主题 下一主题

JAVA: 利用javax.comm or rxtx 的串口访问 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2010-02-21 12:01 |只看该作者 |倒序浏览

                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 www.rxtx.org) on Linux
copy librxtxSerial.so to /usr/lib
copy RXTXcomm.jar to [JDK-directory]/jre/lib/ext/
Installation of rxtxSerial (from www.rxtx.org) 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.
               
               
               
               
               

本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u3/99076/showart_2183228.html
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP