View Javadoc

1   /* ***** BEGIN LICENSE BLOCK *****
2    * Version: MPL 1.1/GPL 2.0/LGPL 2.1
3    *
4    * The contents of this file are subject to the Mozilla Public License Version
5    * 1.1 (the "License"); you may not use this file except in compliance with
6    * the License. You may obtain a copy of the License at
7    * http://www.mozilla.org/MPL/
8    *
9    * Software distributed under the License is distributed on an "AS IS" basis,
10   * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
11   * for the specific language governing rights and limitations under the
12   * License.
13   *
14   * The Original Code is "SMS Library for the Java platform".
15   *
16   * The Initial Developer of the Original Code is Markus Eriksson.
17   * Portions created by the Initial Developer are Copyright (C) 2002
18   * the Initial Developer. All Rights Reserved.
19   *
20   * Contributor(s):
21   *
22   * Alternatively, the contents of this file may be used under the terms of
23   * either the GNU General Public License Version 2 or later (the "GPL"), or
24   * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
25   * in which case the provisions of the GPL or the LGPL are applicable instead
26   * of those above. If you wish to allow use of your version of this file only
27   * under the terms of either the GPL or the LGPL, and not to allow others to
28   * use your version of this file under the terms of the MPL, indicate your
29   * decision by deleting the provisions above and replace them with the notice
30   * and other provisions required by the GPL or the LGPL. If you do not delete
31   * the provisions above, a recipient may use your version of this file under
32   * the terms of any one of the MPL, the GPL or the LGPL.
33   *
34   * ***** END LICENSE BLOCK ***** */
35  package org.marre.sms.transport.gsm;
36  
37  import org.slf4j.Logger;
38  import org.slf4j.LoggerFactory;
39  
40  import java.io.IOException;
41  import java.io.InputStream;
42  import java.io.OutputStream;
43  import java.util.Enumeration;
44  
45  import javax.comm.CommPortIdentifier;
46  import javax.comm.PortInUseException;
47  import javax.comm.SerialPort;
48  import javax.comm.UnsupportedCommOperationException;
49  
50  /***
51   * Simple Serial port comm.
52   * 
53   * @author Markus Eriksson
54   * @version $Id: SerialComm.java,v 1.7 2005/11/26 16:39:33 c95men Exp $
55   */
56  public class SerialComm implements GsmComm
57  {
58      private static Logger log_ = LoggerFactory.getLogger(SerialComm.class);
59  
60      private static final int DEFAULT_BIT_RATE = 19200;
61      
62      private SerialPort serialPort_;
63      private OutputStream serialOs_;
64      private InputStream serialIs_;
65  
66      private String appName_;
67      private String portName_;
68      private int bitRate_;
69      private int dataBits_; 
70      private int stopBits_;
71      private int parity_;
72      private int flowControl_;
73      private boolean echo_;
74  
75      /***
76       * Constructor.
77       * 
78       * @param portName
79       */
80      public SerialComm(String appName, String portName)
81      {
82          appName_ = appName;
83          portName_ = portName;
84          bitRate_ = DEFAULT_BIT_RATE;
85          dataBits_ = SerialPort.DATABITS_8;
86          stopBits_ = SerialPort.STOPBITS_1;
87          parity_ = SerialPort.PARITY_NONE;
88          flowControl_ = SerialPort.FLOWCONTROL_NONE;
89          echo_ = true;
90      }
91  
92      private SerialPort openSerialPort(String portName)
93          throws PortInUseException
94      {
95          SerialPort serialPort = null;
96          Enumeration portList = CommPortIdentifier.getPortIdentifiers();
97  
98          // find the requested port
99          while (portList.hasMoreElements()) 
100         {
101             CommPortIdentifier portId = (CommPortIdentifier) portList.nextElement();
102 
103             // Check for serial port
104             if ( (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) &&
105                  (portId.getName().equals(portName)) ) 
106             {
107                 return (SerialPort) portId.open(appName_, 3000);
108             }
109         }
110         
111         return null;
112     }
113 
114     /* (non-Javadoc)
115      * @see org.marre.sms.transport.gsm.GsmComm#open()
116      */
117     public void open() 
118         throws IOException
119     {
120         try {
121             serialPort_ = openSerialPort(portName_);
122         } catch (PortInUseException piuEx) {
123             throw (IOException) new IOException(piuEx.getMessage()).initCause(piuEx);
124         }
125 
126         if (serialPort_ == null)
127         {
128             throw new IOException("Failed to open port : " + portName_);
129         }
130         
131         try
132         {
133             serialOs_ = serialPort_.getOutputStream();
134             serialIs_ = serialPort_.getInputStream();
135         
136             serialPort_.setSerialPortParams(bitRate_, dataBits_, stopBits_, parity_);
137             serialPort_.setFlowControlMode(flowControl_);
138         } 
139         catch (UnsupportedCommOperationException e)
140         {
141             serialPort_.close();
142             serialPort_ = null;            
143             throw (IOException)(new IOException(e.getMessage())).initCause(e);
144         } 
145     }
146 
147     /* (non-Javadoc)
148      * @see org.marre.sms.transport.gsm.GsmComm#close()
149      */
150     public void close()
151     {
152         if (serialOs_ != null)
153         {
154             try { serialOs_.close(); } catch (Exception ex) { log_.error("serialOs_.close failed", ex); }
155         }
156         
157         if (serialIs_ != null)
158         {
159             try { serialIs_.close(); } catch (Exception ex) { log_.error("serialIs_.close failed", ex); }
160         }
161         
162         if (serialPort_ != null)
163         {        
164             try { serialPort_.close(); } catch (Exception ex) { log_.error("serialPort_.close failed", ex); }
165         }
166         
167         serialOs_ = null;
168         serialIs_ = null;            
169         serialPort_ = null; 
170     }
171 
172     /* (non-Javadoc)
173      * @see org.marre.sms.transport.gsm.GsmComm#sendLine(java.lang.String)
174      */
175     public void send(String row) 
176         throws IOException
177     {
178         // TODO: Remove \r\n from log
179         log_.info(">> " + row);
180 
181         serialOs_.write(row.getBytes());
182         
183         if (echo_) {
184             String echo = readOneRowOfData(null);
185         }
186     }
187 
188     /* (non-Javadoc)
189      * @see org.marre.sms.transport.gsm.GsmComm#readLine()
190      */
191     public String readLine() 
192         throws IOException
193     {
194         return readLine(null);
195     }
196     
197     public String readLine(String find) 
198         throws IOException
199     {
200         return readOneRowOfData(find);
201     }
202     
203     private String readOneRowOfData(String find)
204         throws IOException
205     {
206         StringBuffer buffer = new StringBuffer(256);
207         int ch;
208 
209         while (true)
210         {
211             ch = serialIs_.read();
212             if ( (ch == -1) ||
213                  (ch == '\n') )
214             {
215                 break;
216             }
217             
218             if ( ch == '\r' )
219             {
220                 continue;
221             }
222             
223             buffer.append((char) ch);
224             
225             if ( (find != null) && 
226                  (find.equals(buffer.toString())) ) {
227                 // Found the string we are looking for...
228                 break;
229             }
230         }
231 
232         String row = buffer.toString();
233         
234         // LOG
235         log_.info("<< " + row);
236 
237         return row;
238     }
239     
240     public void setBitRate(String theBitRate)
241     {
242         if      ("110".equals(theBitRate))    bitRate_ = 110;
243         else if ("134".equals(theBitRate))    bitRate_ = 134;
244         else if ("150".equals(theBitRate))    bitRate_ = 150;
245         else if ("300".equals(theBitRate))    bitRate_ = 300;
246         else if ("600".equals(theBitRate))    bitRate_ = 600;
247         else if ("1200".equals(theBitRate))   bitRate_ = 1200;
248         else if ("2400".equals(theBitRate))   bitRate_ = 2400;
249         else if ("4800".equals(theBitRate))   bitRate_ = 4800;
250         else if ("9600".equals(theBitRate))   bitRate_ = 9600;
251         else if ("14400".equals(theBitRate))  bitRate_ = 14400;
252         else if ("19200".equals(theBitRate))  bitRate_ = 19200;
253         else if ("38400".equals(theBitRate))  bitRate_ = 38400;
254         else if ("57600".equals(theBitRate))  bitRate_ = 57600;
255         else if ("115200".equals(theBitRate)) bitRate_ = 115200;
256         else if ("128000".equals(theBitRate)) bitRate_ = 128000;
257         else                                  bitRate_ = DEFAULT_BIT_RATE;        
258     }
259     
260     public void setDataBits(String theDataBits)
261     {
262         if      ("5".equals(theDataBits)) dataBits_ = SerialPort.DATABITS_5;
263         else if ("6".equals(theDataBits)) dataBits_ = SerialPort.DATABITS_6;
264         else if ("7".equals(theDataBits)) dataBits_ = SerialPort.DATABITS_7;
265         else if ("8".equals(theDataBits)) dataBits_ = SerialPort.DATABITS_8;
266         else                              dataBits_ = SerialPort.DATABITS_8;
267     }
268 
269     public void setFlowControl(String theFlowControl)
270     {
271         if      ("RTSCTS".equals(theFlowControl))  flowControl_ = SerialPort.FLOWCONTROL_RTSCTS_IN  | SerialPort.FLOWCONTROL_RTSCTS_OUT;
272         else if ("XONXOFF".equals(theFlowControl)) flowControl_ = SerialPort.FLOWCONTROL_XONXOFF_IN | SerialPort.FLOWCONTROL_XONXOFF_OUT;
273         else if ("NONE".equals(theFlowControl))    flowControl_ = SerialPort.FLOWCONTROL_NONE;
274         else                                       flowControl_ = SerialPort.FLOWCONTROL_NONE;
275     }
276 
277     public void setParity(String theParity)
278     {
279         if      ("NONE".equals(theParity))  parity_ = SerialPort.PARITY_NONE;
280         else if ("EVEN".equals(theParity))  parity_ = SerialPort.PARITY_EVEN;
281         else if ("ODD".equals(theParity))   parity_ = SerialPort.PARITY_ODD;
282         else if ("MARK".equals(theParity))  parity_ = SerialPort.PARITY_MARK;
283         else if ("SPACE".equals(theParity)) parity_ = SerialPort.PARITY_SPACE;
284         else                                parity_ = SerialPort.PARITY_NONE;
285     }
286 
287     public void setStopBits(String theStopBits)
288     {
289         if      ("1".equals(theStopBits))   stopBits_ = SerialPort.STOPBITS_1;
290         else if ("1.5".equals(theStopBits)) stopBits_ = SerialPort.STOPBITS_1_5;
291         else if ("2".equals(theStopBits))   stopBits_ = SerialPort.STOPBITS_2;
292         else                                stopBits_ = SerialPort.STOPBITS_1;
293     }
294     
295     public void setEcho(boolean echo)
296     {
297         echo_ = echo;
298     }
299 }