欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Java使用开源Rxtx实现串口通讯

程序员文章站 2024-03-02 22:56:10
本文实例为大家分享了java使用开源rxtx实现串口通讯的具体代码,供大家参考,具体内容如下 使用方法: windows平台: 1、把rxtxparallel...

本文实例为大家分享了java使用开源rxtx实现串口通讯的具体代码,供大家参考,具体内容如下

使用方法:

windows平台:

1、把rxtxparallel.dll、rxtxserial.dll拷贝到:c:\windows\system32下。

2、如果是在开发的时候(jdk),需要把rxtxcomm.jar、rxtxparallel.dll、rxtxserial.dll拷贝到..\jre...\lib\ext下;如:d:\program files\java\jre1.6.0_02\lib\ext

3、而且需要把项目1.右键->2.preperties(首选项)->3.java build path->4.libraries->5.展开rxtxcomm.jar->6.native library location:(none)->7.浏览external folder(选择至该项目的lib文件夹,如:e:/item/myitem/webroot/web-inf/lib).

import gnu.io.*;
import java.io.*; 
import java.util.*; 
import com.call.dao.*;
 
 public class serialreader extends observable implements runnable,serialporteventlistener
 {
 static commportidentifier portid;
 int delayread = 100;
 int numbytes; // buffer中的实际数据字节数
 private static byte[] readbuffer = new byte[1024]; // 4k的buffer空间,缓存串口读入的数据
 static enumeration portlist;
 inputstream inputstream;
 outputstream outputstream;
 static serialport serialport;
 hashmap serialparams;
 thread readthread;//本来是static类型的
 //端口是否打开了
 boolean isopen = false;
 // 端口读入数据事件触发后,等待n毫秒后再读取,以便让数据一次性读完
 public static final string params_delay = "delay read"; // 延时等待端口数据准备的时间
 public static final string params_timeout = "timeout"; // 超时时间
 public static final string params_port = "port name"; // 端口名称
 public static final string params_databits = "data bits"; // 数据位
 public static final string params_stopbits = "stop bits"; // 停止位
 public static final string params_parity = "parity"; // 奇偶校验
 public static final string params_rate = "rate"; // 波特率
 
 public boolean isopen(){
  return isopen;
 }
 /**
  * 初始化端口操作的参数.
  * @throws serialportexception 
  * 
  * @see
  */
 public serialreader()
 {
  isopen = false;
 }
 
 public void open(hashmap params) 
 { 
  serialparams = params;
  if(isopen){
  close();
  }
  try
  {
   // 参数初始化
   int timeout = integer.parseint( serialparams.get( params_timeout )
    .tostring() );
   int rate = integer.parseint( serialparams.get( params_rate )
    .tostring() );
   int databits = integer.parseint( serialparams.get( params_databits )
    .tostring() );
   int stopbits = integer.parseint( serialparams.get( params_stopbits )
    .tostring() );
   int parity = integer.parseint( serialparams.get( params_parity )
    .tostring() );
   delayread = integer.parseint( serialparams.get( params_delay )
    .tostring() );
   string port = serialparams.get( params_port ).tostring();
   // 打开端口
   portid = commportidentifier.getportidentifier( port );
   serialport = ( serialport ) portid.open( "serialreader", timeout );
   inputstream = serialport.getinputstream();
   serialport.addeventlistener( this );
   serialport.notifyondataavailable( true );
   serialport.setserialportparams( rate, databits, stopbits, parity );
   
   isopen = true;
  }
  catch ( portinuseexception e )
  {
   // 端口"+serialparams.get( params_port ).tostring()+"已经被占用";
  }
  catch ( toomanylistenersexception e )
  {
   //"端口"+serialparams.get( params_port ).tostring()+"监听者过多";
  }
  catch ( unsupportedcommoperationexception e )
  {
   //"端口操作命令不支持";
  }
  catch ( nosuchportexception e )
  {
   //"端口"+serialparams.get( params_port ).tostring()+"不存在";
  }
  catch ( ioexception e )
  {
   //"打开端口"+serialparams.get( params_port ).tostring()+"失败";
  }
  serialparams.clear();
  thread readthread = new thread( this );
  readthread.start();
 }
 
  
 public void run()
 {
  try
  {
   thread.sleep(50);
  }
  catch ( interruptedexception e )
  {
  }
 } 
 public void start(){
  try { 
  outputstream = serialport.getoutputstream();
   } 
 catch (ioexception e) {}
 try{ 
  readthread = new thread(this);
  readthread.start();
 } 
 catch (exception e) { }
 } //start() end
 
 
 public void run(string message) {
 try { 
  thread.sleep(4); 
   } 
  catch (interruptedexception e) { } 
  try {
  if(message!=null&&message.length()!=0)
  { 
  system.out.println("run message:"+message);
   outputstream.write(message.getbytes());
  }
 } catch (ioexception e) {}
 } 
 
 
 public void close() 
 { 
  if (isopen)
  {
   try
   {
    serialport.notifyondataavailable(false);
    serialport.removeeventlistener();
    inputstream.close();
    serialport.close();
    isopen = false;
   } catch (ioexception ex)
   {
   //"关闭串口失败";
   }
  }
 }
 
 public void serialevent( serialportevent event )
 {
  try
  {
   thread.sleep( delayread );
  }
  catch ( interruptedexception e )
  {
   e.printstacktrace();
  }
  switch ( event.geteventtype() )
  {
   case serialportevent.bi: // 10
   case serialportevent.oe: // 7
   case serialportevent.fe: // 9
   case serialportevent.pe: // 8
   case serialportevent.cd: // 6
   case serialportevent.cts: // 3
   case serialportevent.dsr: // 4
   case serialportevent.ri: // 5
   case serialportevent.output_buffer_empty: // 2
    break;
   case serialportevent.data_available: // 1
    try
    {
     // 多次读取,将所有数据读入
      while (inputstream.available() > 0) {
      numbytes = inputstream.read(readbuffer);
      }
      
      //打印接收到的字节数据的ascii码
      for(int i=0;i<numbytes;i++){
      // system.out.println("msg[" + numbytes + "]: [" +readbuffer[i] + "]:"+(char)readbuffer[i]);
      }
//     numbytes = inputstream.read( readbuffer );
     changemessage( readbuffer, numbytes );
    }
    catch ( ioexception e )
    {
     e.printstacktrace();
    }
    break;
  }
 }
 // 通过observer pattern将收到的数据发送给observer
 // 将buffer中的空字节删除后再发送更新消息,通知观察者
 public void changemessage( byte[] message, int length )
 {
  setchanged();
  byte[] temp = new byte[length];
  system.arraycopy( message, 0, temp, 0, length );
  notifyobservers( temp );
 }
 static void listports()
 {
  enumeration portenum = commportidentifier.getportidentifiers();
  while ( portenum.hasmoreelements() )
  {
   commportidentifier portidentifier = ( commportidentifier ) portenum
    .nextelement();
   
  }
 }
 
 
 public void openserialport(string message)
 {
  hashmap<string, comparable> params = new hashmap<string, comparable>(); 
  otherdao odao=new otherdao();
  string port=odao.selectnumberbyid(15);
  string rate = "9600";
  string databit = ""+serialport.databits_8;
  string stopbit = ""+serialport.stopbits_1;
  string parity = ""+serialport.parity_none; 
  int parityint = serialport.parity_none; 
  params.put( serialreader.params_port, port ); // 端口名称
  params.put( serialreader.params_rate, rate ); // 波特率
  params.put( serialreader.params_databits,databit ); // 数据位
  params.put( serialreader.params_stopbits, stopbit ); // 停止位
  params.put( serialreader.params_parity, parityint ); // 无奇偶校验
  params.put( serialreader.params_timeout, 100 ); // 设备超时时间 1秒
  params.put( serialreader.params_delay, 100 ); // 端口数据准备时间 1秒
  try {
 open(params);//打开串口
 loginframe cf=new loginframe();
 addobserver(cf);
 if(message!=null&&message.length()!=0)
 {
 string str="";
 for(int i=0;i<10;i++)
 {
  str+=message;
 }
  start(); 
  run(str); 
 } 
 } catch (exception e) { 
 }
 }
 static string getporttypename( int porttype )
 {
  switch ( porttype )
  {
   case commportidentifier.port_i2c:
    return "i2c";
   case commportidentifier.port_parallel:
    return "parallel";
   case commportidentifier.port_raw:
    return "raw";
   case commportidentifier.port_rs485:
    return "rs485";
   case commportidentifier.port_serial:
    return "serial";
   default:
    return "unknown type";
  }
 }
  
 public hashset<commportidentifier> getavailableserialports()//本来static
 {
  hashset<commportidentifier> h = new hashset<commportidentifier>();
  enumeration theports = commportidentifier.getportidentifiers();
  while ( theports.hasmoreelements() )
  {
   commportidentifier com = ( commportidentifier ) theports
    .nextelement();
   switch ( com.getporttype() )
   {
    case commportidentifier.port_serial:
     try
     {
      commport theport = com.open( "commutil", 50 );
      theport.close();
      h.add( com );
     }
     catch ( portinuseexception e )
     {
      system.out.println( "port, " + com.getname()
       + ", is in use." );
     }
     catch ( exception e )
     {
      system.out.println( "failed to open port "
       + com.getname() + e );
     }
   }
  }
  return h;
 }
}
 
//ascii表
//-------------------------------------------------------------
//     ascii characters       
//       
//dec hex  char code dec hex char
//       
//0  0   nul   64 40 @
//1  1   soh   65 41 a
//2  2   stx   66 42 b
//3  3   etx   67 43 c
//4  4   eot   68 44 d
//5  5   enq   69 45 e
//6  6   ack   70 46 f
//7  7   bel   71 47 g
//8  8   bs    72 48 h
//9  9   ht    73 49 i
//10 0a  lf    74 4a j
//11 0b  vt    75 4b k
//12 0c  ff    76 4c l
//13 0d  cr    77 4d m
//14 0e  so    78 4e n
//15 0f  si    79 4f o
//16 10  sle   80 50 p
//17 11  cs1   81 51 q
//18 12  dc2   82 52 r
//19 13  dc3   83 53 s
//20 14  dc4   84 54 t
//21 15  nak   85 55 u
//22 16  syn   86 56 v
//23 17  etb   87 57 w
//24 18  can   88 58 x
//25 19  em    89 59 y
//26 1a  sib   90 5a z
//27 1b  esc   91 5b [
//        92 5c  \
//28 1c  fs    93 5d ]
//29 1d  gs    94 5e ^
//30 1e  rs    95 5f _
//31 1f  us    96 60 `
//32 20 (space)   97 61 a
//33 21  !    98 62 b
//34 22  " 
//        99 63 c
//35 23  #    100 64 d
//36 24  $     
//37 25  %    101 65 e
//38 26  &    102 66 f
//39 27  '    103 67 g
//40 28  (    104 68 h
//41 29  )    105 69 i
//42 2a  *    106 6a j
//43 2b  +    107 6b k
//44 2c  ,    108 6c l
//45 2d  -    109 6d m
//46 2e  .    110 6e n
//47 2f  /    111 6f o
//48 30  0    112 70 p
//49 31  1    113 72 q
//50 32  2    114 72 r
//51 33  3    115 73 s
//52 34  4    116 74 t
//53 35  5    117 75 u
//54 36  6    118 76 v
//55 37  7    119 77 w
//56 38  8    120 78 x
//57 39  9    121 79 y
//58 3a  :    122 7a z
//59 3b  ;    123 7b {
//60 3c  <    124 7c |
//61 3d  =    125 7d }
//62 3e  >    126 7e ~
//63 3f  ?    127 7f 

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。