好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

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

本文实例为大家分享了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).

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

150

151

152

153

154

155

156

157

158

159

160

161

162

163

164

165

166

167

168

169

170

171

172

173

174

175

176

177

178

179

180

181

182

183

184

185

186

187

188

189

190

191

192

193

194

195

196

197

198

199

200

201

202

203

204

205

206

207

208

209

210

211

212

213

214

215

216

217

218

219

220

221

222

223

224

225

226

227

228

229

230

231

232

233

234

235

236

237

238

239

240

241

242

243

244

245

246

247

248

249

250

251

252

253

254

255

256

257

258

259

260

261

262

263

264

265

266

267

268

269

270

271

272

273

274

275

276

277

278

279

280

281

282

283

284

285

286

287

288

289

290

291

292

293

294

295

296

297

298

299

300

301

302

303

304

305

306

307

308

309

310

311

312

313

314

315

316

317

318

319

320

321

322

323

324

325

326

327

328

329

330

331

332

333

334

335

336

337

338

339

340

341

342

343

344

345

346

347

348

349

350

351

352

353

354

355

356

357

358

359

360

361

362

363

364

365

366

367

368

369

370

371

372

373

374

375

376

377

378

379

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

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

原文链接:https://blog.csdn.net/liu4071325/article/details/53391800

查看更多关于Java使用开源Rxtx实现串口通讯的详细内容...

  阅读:11次