mina串口需要依靠的包

前几个包可以mina官网下载,最后一个minamycom.jar是我自己把org.apache.mina.transport.serial下的所有class打成的jar(​http://m134.mail.qq.com/cgi-bin/frame_html?sid=H-tEBtnqbtrjOH4z&r=6e9e4c331cf2c905cc15bf23d15f5a27​ 下载)

主要是解决串口读数据一次最多读32个字节的问题,解决后通过传递一个参数来解决串口直到把所有数据一次性全部读出

1) rxtx-2.1-7-bins-r2下的

 把rxtxParallel.dll,rxtxSerial.dll拷贝到Java\jdk1.6.0_10\jre\bin

把RXTXcomm.jar拷贝到Java\jdk1.6.0_10\jre\lib\ext

环境变量中添加CLASSPATH=;C:\Program Files\Java\jdk1.6.0_10\jre\lib\ext\RXTXcomm.jar

 

2)下载了apache-mina-2.0.2-src.zip找到src下的mina-transport-serial把其中的org及其以下的目录放在myeclipse项目的src下

修改org.apache.mina.transport.serial包下的SerialSessionImpl.java如下





[java] ​​view plain​ ​​​copy​​​​​​​​​



  1. /* 
  2.  *  Licensed to the Apache Software Foundation (ASF) under one 
  3.  *  or more contributor license agreements.  See the NOTICE file 
  4.  *  distributed with this work for additional information 
  5.  *  regarding copyright ownership.  The ASF licenses this file 
  6.  *  to you under the Apache License, Version 2.0 (the 
  7.  *  "License"); you may not use this file except in compliance 
  8.  *  with the License.  You may obtain a copy of the License at 
  9.  * 
  10.  *    http://www.apache.org/licenses/LICENSE-2.0 
  11.  * 
  12.  *  Unless required by applicable law or agreed to in writing, 
  13.  *  software distributed under the License is distributed on an 
  14.  *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 
  15.  *  KIND, either express or implied.  See the License for the 
  16.  *  specific language governing permissions and limitations 
  17.  *  under the License. 
  18.  * 
  19.  */  
  20. package org.apache.mina.transport.serial;  
  21. import gnu.io.SerialPort;  
  22. import gnu.io.SerialPortEvent;  
  23. import gnu.io.SerialPortEventListener;  
  24. import gnu.io.UnsupportedCommOperationException;  
  25. import java.io.IOException;  
  26. import java.io.InputStream;  
  27. import java.io.OutputStream;  
  28. import java.util.TooManyListenersException;  
  29. import org.apache.mina.core.buffer.IoBuffer;  
  30. import org.apache.mina.core.filterchain.DefaultIoFilterChain;  
  31. import org.apache.mina.core.filterchain.IoFilterChain;  
  32. import org.apache.mina.core.service.DefaultTransportMetadata;  
  33. import org.apache.mina.core.service.IoProcessor;  
  34. import org.apache.mina.core.service.IoServiceListenerSupport;  
  35. import org.apache.mina.core.service.TransportMetadata;  
  36. import org.apache.mina.core.session.AbstractIoSession;  
  37. import org.apache.mina.core.write.WriteRequest;  
  38. import org.apache.mina.util.ExceptionMonitor;  
  39. import org.slf4j.Logger;  
  40. import org.slf4j.LoggerFactory;  
  41. /** 
  42.  * An imlpementation of SerialSession}. 
  43.  * 
  44.  * @author <a href="apache/'>http://mina.apache.org">Apache MINA Project</a> 
  45.  */  
  46. class SerialSessionImpl extends AbstractIoSession implements SerialSession, SerialPortEventListener {  
  47.     static final TransportMetadata METADATA = new DefaultTransportMetadata("rxtx", "serial", false, true,  
  48.             SerialAddress.class, SerialSessionConfig.class, IoBuffer.class);  
  49.     private final IoProcessor<SerialSessionImpl> processor = new SerialIoProcessor();  
  50.     private final IoFilterChain filterChain;  
  51.     private final IoServiceListenerSupport serviceListeners;  
  52.     private final SerialAddress address;  
  53.     private final SerialPort port;  
  54.     private final Logger log;  
  55.     private InputStream inputStream;  
  56.     private OutputStream outputStream;  
  57.     SerialSessionImpl(SerialConnector service, IoServiceListenerSupport serviceListeners, SerialAddress address,  
  58.             SerialPort port) {  
  59.         super(service);  
  60.         config = new DefaultSerialSessionConfig();  
  61.         this.serviceListeners = serviceListeners;  
  62.         filterChain = new DefaultIoFilterChain(this);  
  63.         this.port = port;  
  64.         this.address = address;  
  65.         log = LoggerFactory.getLogger(SerialSessionImpl.class);  
  66.     }  
  67.     public SerialSessionConfig getConfig() {  
  68.         return (SerialSessionConfig) config;  
  69.     }  
  70.     public IoFilterChain getFilterChain() {  
  71.         return filterChain;  
  72.     }  
  73.     public TransportMetadata getTransportMetadata() {  
  74.         return METADATA;  
  75.     }  
  76.     public SerialAddress getLocalAddress() {  
  77.         return null; // not applicable  
  78.     }  
  79.     public SerialAddress getRemoteAddress() {  
  80.         return address;  
  81.     }  
  82.     @Override  
  83.     public SerialAddress getServiceAddress() {  
  84.         return (SerialAddress) super.getServiceAddress();  
  85.     }  
  86.     public void setDTR(boolean dtr) {  
  87.         port.setDTR(dtr);  
  88.     }  
  89.     public boolean isDTR() {  
  90.         return port.isDTR();  
  91.     }  
  92.     public void setRTS(boolean rts) {  
  93.         port.setRTS(rts);  
  94.     }  
  95.     public boolean isRTS() {  
  96.         return port.isRTS();  
  97.     }  
  98.     /** 
  99.      * start handling streams 
  100.      * 
  101.      * @throws IOException 
  102.      * @throws TooManyListenersException 
  103.      */  
  104.     void start() throws IOException, TooManyListenersException {  
  105.         inputStream = port.getInputStream();  
  106.         outputStream = port.getOutputStream();  
  107.         ReadWorker w = new ReadWorker();  
  108.         w.start();  
  109.         port.addEventListener(this);  
  110.         ((SerialConnector) getService()).getIdleStatusChecker0().addSession(this);  
  111.         try {  
  112.             getService().getFilterChainBuilder().buildFilterChain(getFilterChain());  
  113.             serviceListeners.fireSessionCreated(this);  
  114.         } catch (Throwable e) {  
  115.             getFilterChain().fireExceptionCaught(e);  
  116.             processor.remove(this);  
  117.         }  
  118.     }  
  119.     private final Object writeMonitor = new Object();  
  120.     private WriteWorker writeWorker;  
  121.     private class WriteWorker extends Thread {  
  122.         @Override  
  123.         public void run() {  
  124.             while (isConnected() && !isClosing()) {  
  125.                 flushWrites();  
  126.                 // wait for more data  
  127.                 synchronized (writeMonitor) {  
  128.                     try {  
  129.                         writeMonitor.wait();  
  130.                     } catch (InterruptedException e) {  
  131.                         log.error("InterruptedException", e);  
  132.                     }  
  133.                 }  
  134.             }  
  135.         }  
  136.     }  
  137.     private void flushWrites() {  
  138.         for (;;) {  
  139.             WriteRequest req = getCurrentWriteRequest();  
  140.             if (req == null) {  
  141.                 req = getWriteRequestQueue().poll(this);  
  142.                 if (req == null) {  
  143.                     break;  
  144.                 }  
  145.             }  
  146.             IoBuffer buf = (IoBuffer) req.getMessage();  
  147.             if (buf.remaining() == 0) {  
  148.                 setCurrentWriteRequest(null);  
  149.                 buf.reset();  
  150.                 this.getFilterChain().fireMessageSent(req);  
  151.                 continue;  
  152.             }  
  153.             int writtenBytes = buf.remaining();  
  154.             try {  
  155.                 outputStream.write(buf.array(), buf.position(), writtenBytes);  
  156.                 buf.position(buf.position() + writtenBytes);  
  157.                 // increase written bytes  
  158.                 increaseWrittenBytes(writtenBytes, System.currentTimeMillis());  
  159.                 setCurrentWriteRequest(null);  
  160.                 buf.reset();  
  161.                 // fire the message sent event  
  162.                 getFilterChain().fireMessageSent(req);  
  163.             } catch (IOException e) {  
  164.                 this.getFilterChain().fireExceptionCaught(e);  
  165.             }  
  166.         }  
  167.     }  
  168.     private final Object readReadyMonitor = new Object();  
  169.     int dataSize;  
  170. //   long l1=0;  
  171.     private class ReadWorker extends Thread {  
  172.         @Override  
  173.         public void run() {  
  174.            
  175.            
  176.             while (isConnected() && !isClosing()) {  
  177.                 synchronized (readReadyMonitor) {  
  178.                     try {  
  179.                         readReadyMonitor.wait();  
  180.                     } catch (InterruptedException e) {  
  181.                         log.error("InterruptedException", e);  
  182.                     }  
  183.                     if (isClosing() || !isConnected()) {  
  184.                         break;  
  185.                     }  
  186.                     try {  
  187.                      /*if(l1==0){ 
  188.                       l1=System.currentTimeMillis(); 
  189.                      }else{ 
  190.                       long l2=System.currentTimeMillis(); 
  191.                       System.out.println(l2-l1); 
  192.                       l1=l2; 
  193.                      }*/  
  194.                      while(inputStream.available()>dataSize){  
  195.                       dataSize = inputStream.available();  
  196.                       Thread.sleep(address.getWaitMs());//参数一般是200毫秒,这个参数也可以自己输入我的电脑每次读数据的间隔是200毫秒左右  
  197.                      }  
  198.                         byte[] data = new byte[dataSize];  
  199.                         int readBytes = inputStream.read(data);  
  200.                         if (readBytes > 0) {  
  201.                             IoBuffer buf = IoBuffer.wrap(data, 0, readBytes);  
  202.                             buf.put(data, 0, readBytes);  
  203.                             buf.flip();  
  204.                             getFilterChain().fireMessageReceived(buf);  
  205.                         }  
  206.                         dataSize=0;  
  207.                     } catch (IOException e) {  
  208.                         getFilterChain().fireExceptionCaught(e);  
  209.                     } catch (InterruptedException e) {  
  210.       e.printStackTrace();  
  211.      }  
  212.                 }  
  213.             }  
  214.         }  
  215.     }  
  216.     public void serialEvent(SerialPortEvent evt) {  
  217.         if (evt.getEventType() == SerialPortEvent.DATA_AVAILABLE) {  
  218.             synchronized (readReadyMonitor) {  
  219.                 readReadyMonitor.notifyAll();  
  220.             }  
  221.         }  
  222.     }  
  223.     @Override  
  224.     public IoProcessor<SerialSessionImpl> getProcessor() {  
  225.         return processor;  
  226.     }  
  227.     private class SerialIoProcessor implements IoProcessor<SerialSessionImpl> {  
  228.         public void add(SerialSessionImpl session) {  
  229.             // It's already added when the session is constructed.  
  230.         }  
  231.         public void flush(SerialSessionImpl session) {  
  232.             if (writeWorker == null) {  
  233.                 writeWorker = new WriteWorker();  
  234.                 writeWorker.start();  
  235.             } else {  
  236.                 synchronized (writeMonitor) {  
  237.                     writeMonitor.notifyAll();  
  238.                 }  
  239.             }  
  240.         }  
  241.         public void remove(SerialSessionImpl session) {  
  242.             try {  
  243.                 inputStream.close();  
  244.             } catch (IOException e) {  
  245.                 ExceptionMonitor.getInstance().exceptionCaught(e);  
  246.             }  
  247.             try {  
  248.                 outputStream.close();  
  249.             } catch (IOException e) {  
  250.                 ExceptionMonitor.getInstance().exceptionCaught(e);  
  251.             }  
  252.             try { // Turn flow control off right before close to avoid deadlock  
  253.                 port.setFlowControlMode(SerialPort.FLOWCONTROL_NONE);  
  254.             } catch (UnsupportedCommOperationException e) {  
  255.                 ExceptionMonitor.getInstance().exceptionCaught(e);  
  256.             }  
  257.             port.close();  
  258.             flush(session);  
  259.             synchronized (readReadyMonitor) {  
  260.                 readReadyMonitor.notifyAll();  
  261.             }  
  262.             serviceListeners.fireSessionDestroyed(SerialSessionImpl.this);  
  263.         }  
  264.         public void updateTrafficControl(SerialSessionImpl session) {  
  265.             throw new UnsupportedOperationException();  
  266.         }  
  267.         public void dispose() {  
  268.             // Nothing to dispose  
  269.         }  
  270.         public boolean isDisposed() {  
  271.             return false;  
  272.         }  
  273.         public boolean isDisposing() {  
  274.             return false;  
  275.         }  
  276.     }  
  277.       
  278. }  


3)测试程序:






[java] ​​view plain​ ​​​copy​​​​​​​​​



  1. package com;  
  2. import org.apache.mina.core.future.ConnectFuture;  
  3. import org.apache.mina.core.service.IoConnector;  
  4. import org.apache.mina.core.session.IoSession;  
  5. import org.apache.mina.core.session.IoSessionConfig;  
  6. import org.apache.mina.transport.serial.SerialAddress;  
  7. import org.apache.mina.transport.serial.SerialConnector;  
  8. import org.apache.mina.transport.serial.SerialAddress.DataBits;  
  9. import org.apache.mina.transport.serial.SerialAddress.FlowControl;  
  10. import org.apache.mina.transport.serial.SerialAddress.Parity;  
  11. import org.apache.mina.transport.serial.SerialAddress.StopBits;  
  12.    
  13. public class Test {  
  14.  public static void main(String[] args) {  
  15.   SerialConnector connector = new SerialConnector();  
  16.   connector.setHandler(new myComHandler());//DataBits dataBits, StopBits stopBits, Parity parity, FlowControl flowControl  
  17.   SerialAddress portAddress=new SerialAddress( "COM5", 2400,DataBits.DATABITS_8, StopBits.BITS_1, Parity.EVEN, FlowControl.XONXOFF_IN,new Long(200));   
  18.   ConnectFuture future = connector.connect(portAddress);     
  19.   try {  
  20.    future.await();  
  21.   } catch (InterruptedException e) {  
  22.    e.printStackTrace();  
  23.   }     
  24.   IoSession sessin = future.getSession();    
  25. //  sessin.getFilterChain().addFirst("first",  new addfilter());  
  26.   IoSessionConfig sc=sessin.getService().getSessionConfig();  
  27.   sessin.setAttribute("comname", "COM5");  
  28.   String s="1111111111111111111111111111111111111111111111111111111111111111111111";  
  29.   s=s.replace(" ", "");  
  30.   System.out.println(s);  
  31.   byte[]b=Convert.hexStringToBytes(s);  
  32.   sessin.write(Convert.byteToIoBuffer(b, b.length));  
  33.   connector.dispose();  
  34.  }  
  35. }