心如止水,万事皆成。心态决定我的成功。2013

简单实例下载:

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\ext3、而且需要把项目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() endpublic 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: // 10case SerialPortEvent.OE: // 7case SerialPortEvent.FE: // 9case SerialPortEvent.PE: // 8case SerialPortEvent.CD: // 6case SerialPortEvent.CTS: // 3case SerialPortEvent.DSR: // 4case SerialPortEvent.RI: // 5case SerialPortEvent.OUTPUT_BUFFER_EMPTY: // 2break;case SerialPortEvent.DATA_AVAILABLE: // 1try{// 多次读取,将所有数据读入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 HexChar Code Dec Hex Char////00NUL64 40 @//11SOH65 41 A//22STX66 42 B//33ETX67 43 C//44EOT68 44 D//55ENQ69 45 E//66ACK70 46 F//77BEL71 47 G//88BS72 48 H//99HT73 49 I//10 0ALF74 4A J//11 0BVT75 4B K//12 0CFF76 4C L//13 0DCR77 4D M//14 0ESO78 4E N//15 0FSI79 4F O//16 10SLE80 50 P//17 11CS181 51 Q//18 12DC282 52 R//19 13DC383 53 S//20 14DC484 54 T//21 15NAK85 55 U//22 16SYN86 56 V//23 17ETB87 57 W//24 18CAN88 58 X//25 19EM89 59 Y//26 1ASIB90 5A Z//27 1BESC91 5B [//92 5C\//28 1CFS93 5D ]//29 1DGS94 5E ^//30 1ERS95 5F _//31 1FUS96 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 300112 70 p//49 311113 72 q//50 322114 72 r//51 333115 73 s//52 344116 74 t//53 355117 75 u//54 366118 76 v//55 377119 77 w//56 388120 78 x//57 399121 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

简单实例下载:

一个人,一条路,人在途中,心随景动,

心如止水,万事皆成。心态决定我的成功。2013

相关文章:

你感兴趣的文章:

标签云: