Java 串口通信

  1 package waf.net.comm;
  2 
  3 import java.io.IOException;
  4 import java.io.InputStream;
  5 import java.io.InputStreamReader;
  6 import java.io.OutputStream;
  7 import java.io.OutputStreamWriter;
  8 import java.rmi.RemoteException;
  9 import java.util.Random;
 10 
 11 import javax.comm.CommPortIdentifier;
 12 import javax.comm.NoSuchPortException;
 13 import javax.comm.PortInUseException;
 14 import javax.comm.SerialPort;
 15 import javax.comm.UnsupportedCommOperationException;
 16 /***
 17  * 串口操作实现类
 18  * @author hzy
 19  *
 20  */
 21 public class Port 
 22 {
 23     private CommPortIdentifier portId;
 24     private SerialPort serialPort;
 25     protected OutputStreamWriter out;
 26     protected InputStreamReader in;
 27     
 28     public InputStream is;
 29     public OutputStream os;
 30     private String COMname;
 31     private static char symbol1 = 13;
 32     protected String portName="";
 33     
 34     public static void main(String args[]) throws RemoteException
 35     {
 36         Port port=new Port("COM31");
 37         String ret=port.sendAT("at");
 38         int m=0;
 39     }
 40     public String getCOMname() {
 41         return COMname;
 42     }
 43     public void setCOMname(String mname) {
 44         COMname = mname;
 45     }
 46     public CommPortIdentifier getPortId() {
 47         return portId;
 48     }
 49 
 50     public void setPortId(CommPortIdentifier portId) {
 51         this.portId = portId;
 52     }
 53 
 54     
 55     public SerialPort getSerialPort() {
 56         return serialPort;
 57     }
 58 
 59     public void setSerialPort(SerialPort serialPort) {
 60         this.serialPort = serialPort;
 61     }
 62 
 63     public OutputStreamWriter getOut() {
 64         return out;
 65     }
 66 
 67     public void setOut(OutputStreamWriter out) {
 68         this.out = out;
 69     }
 70     public InputStreamReader getIn() {
 71         return in;
 72     }
 73 
 74     public void setIn(InputStreamReader in) {
 75         this.in = in;
 76     }
 77     private boolean opened =true;
 78     
 79     public boolean isOpened() {
 80         return opened;
 81     }
 82 
 83     public void setOpened(boolean isused) {
 84         this.opened = isused;
 85     }
 86     /**
 87      * 打开com口 
 88      * @param portName
 89      * @return
 90      * @throws IOException 
 91      * @throws PortInUseException 
 92      * @throws NoSuchPortException 
 93      * @throws UnsupportedCommOperationException 
 94      */        
 95     public boolean open()
 96     {
 97         boolean ret=false;
 98         try
 99         {
100             portId = CommPortIdentifier.getPortIdentifier(this.portName);
101             serialPort = (SerialPort) portId.open(getrechargeablePassword(), 1000*5);
102     
103             is = serialPort.getInputStream();
104             os = serialPort.getOutputStream();
105             in = new InputStreamReader(serialPort.getInputStream());
106             out = new OutputStreamWriter(serialPort.getOutputStream());
107     
108             // 下面是初始化COM口的传输参数,如传输速率:9600等。
109             serialPort.setSerialPortParams(115200, SerialPort.DATABITS_8,
110                     SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
111             
112             setCOMname(portId.getName());
113             setOpened(true);
114         }
115         catch(Exception e)
116         {
117             //ret=waf.lang.Exception.getMessage(e);
118             
119             e.printStackTrace();
120             System.out.println(this.portName);
121             System.out.println("---------------");
122         }
123         ret=out!=null?true:false;
124         return ret;
125     }
126     public  Port(String portName) 
127     {
128         this.portName=portName;
129 //        try {
130 //            portId = CommPortIdentifier.getPortIdentifier(portName);
131 //            if (portId == null) {
132 //                System.out.println("port is null");
133 //            }
134 //            try 
135 //            {
136 //                serialPort = (SerialPort) portId.open(getrechargeablePassword(),20000);
137 //            } catch (PortInUseException e) 
138 //            {
139 //                System.gc();
140 //                e.printStackTrace();
141 //            }
142 //            
143 //            // 下面是得到用于和COM口通讯的输入、输出流。
144 //            try {
145 //                is=serialPort.getInputStream();
146 //                os=serialPort.getOutputStream();
147 //                in = new InputStreamReader(serialPort.getInputStream());
148 //                out = new OutputStreamWriter(serialPort.getOutputStream());
149 //            } catch (IOException e) {
150 //                System.gc();
151 //                System.out.println("IOException");
152 //            }
153 //            // 下面是初始化COM口的传输参数,如传输速率:9600等。
154 //            try {
155 //                serialPort.setSerialPortParams(115200, SerialPort.DATABITS_8,
156 //                        SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
157 //                setCOMname(portId.getName());
158 //                setIsused(true);                
159 //            } catch (UnsupportedCommOperationException e) {
160 //                e.printStackTrace();
161 //                System.gc();
162 //            }
163 //
164 //        } catch (NoSuchPortException e) {
165 //            e.printStackTrace();
166 //            System.gc();
167 //        }        
168     }
169     //获取密码
170     public static String getrechargeablePassword() {
171         Random random = new Random();
172         char[] codeSequence = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I',
173                 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U',
174                 'V', 'W', 'X', 'Y', 'Z', '0', '1', '2', '3', '4', '5', '6',
175                 '7', '8', '9', 'a', 'c', 'b', 'd', 'f', 'e', 'g', 'h', 'j',
176                 'i', 'l', 'k', 'n', 'm', 'o', 'p', 'q', 'r', 's', 't', 'u',
177                 'w', 'v' };
178         String strRand = "";
179         for (int i = 0; i < 18; i++) {
180             strRand = strRand
181                     + String.valueOf(codeSequence[random.nextInt(59)]);
182         }
183         return strRand;
184     }
185     /**
186      * 检查SIM是否存在
187      * @return
188      */
189     public  boolean chakanPort() {
190         try {
191             String     atCommand = "AT+ccid";
192             String    strReturn = sendAT(atCommand);
193             if (strReturn.indexOf("OK", 0) != -1) {        
194                 return true;
195             }
196             return false;
197         } catch (Exception ex) {
198             System.gc();
199             ex.printStackTrace();
200             return false;
201         }
202     }
203     /**
204      * 关闭COM口
205      * @return boolean
206      */
207     public void close() {
208         try 
209         {
210             if(in!=null)in.close();
211             if(out!=null)out.close();
212         }
213         catch (IOException e) 
214         {
215             e.printStackTrace();
216         }
217         if(serialPort!=null)serialPort.close();    
218         System.gc();
219         setOpened(false);        
220     }
221 
222     /**
223      * 向串口中写入字符串命令
224      * @param s 字符串命令
225      * @throws Exception 异常
226      */
227     public  void writeln(String s) throws Exception {
228         out.write(s);
229         out.write('\r');
230         out.flush();
231     }
232 
233     /**
234      * 读取COM命令的返回字符串
235      * @return 结果字符串
236      * @throws Exception
237      */
238     public  String read() throws Exception 
239     {
240         return readUtil("OK");
241     }
242 
243     
244     public  String readUtil(String end) throws Exception {
245         return readUtil(end,15);
246     }
247     public  String readUtil(String end,int secTimeout) throws Exception {
248         int n, i;
249         char c;
250         String answer = "";
251         for (i = 0; i < secTimeout; i++) 
252         {
253             while (in.ready()) 
254             {
255                 n = in.read();
256                 if (n != -1) 
257                 {
258                     c = (char) n;
259                     answer = answer + c;
260                     Thread.sleep(1);
261                 } 
262                 else
263                 {
264                     break;
265                 }
266             }
267             if (answer.indexOf(end) != -1) 
268             {
269                 break;
270             }
271             
272             if (answer.indexOf("ERROR") != -1) 
273             {
274                 break;
275             }            
276             Thread.sleep(1000);
277             //System.out.println("Thread.sleep(1000)");
278         }
279         
280         if(i>=10)
281         {
282             int m=0;
283         }
284         return answer;
285     }
286     
287     /**
288      * 向串口发送AT指令
289      * @param atcommand 指令内容
290      * @return 指令返回结果
291      * @throws java.rmi.RemoteException
292      */
293     public String sendAT(String atcommand)// throws java.rmi.RemoteException 
294     {
295         return sendATAndRespEndWith(atcommand,"OK");
296     }
297     
298     public String sendAT(String atcommand,int secTimeout)// throws java.rmi.RemoteException 
299     {
300         return sendATAndRespEndWith(atcommand,"OK",secTimeout);
301     }
302     
303     public String sendAT(String atcommand,String respEndWith)// throws java.rmi.RemoteException 
304     {
305         return sendATAndRespEndWith(atcommand,respEndWith);
306     }
307     
308     public String sendATAndRespEndWith(String atcommand,String respEndWith)// throws java.rmi.RemoteException
309     {
310         return  sendATAndRespEndWith(atcommand,respEndWith,15);
311     }
312     public String sendATAndRespEndWith(String atcommand,String respEndWith,int secTimeout)// throws java.rmi.RemoteException 
313     {
314         String s = "";
315         try 
316         {
317             Thread.sleep(100);
318             writeln(atcommand);
319             Thread.sleep(80);
320             s = readUtil(respEndWith,secTimeout);
321             
322             Thread.sleep(150);
323         } 
324         catch (Exception e) 
325         {
326             System.gc();
327             System.out.println("ERROR: send AT command failed; " + "Command: "
328                     + atcommand + "; Answer: " + s + "  " + e);
329         }
330         return s;
331     }
332 }

 

posted @ 2020-07-10 22:31  从程序员到CTO  阅读(132)  评论(0)    收藏  举报
交流加我QQ:39667545