View Javadoc

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  
22  import gnu.io.CommPortIdentifier;
23  import gnu.io.PortInUseException;
24  import gnu.io.SerialPort;
25  import gnu.io.UnsupportedCommOperationException;
26  
27  import java.io.IOException;
28  import java.net.SocketAddress;
29  import java.util.Enumeration;
30  import java.util.TooManyListenersException;
31  import java.util.concurrent.Executor;
32  
33  import org.apache.mina.core.service.AbstractIoConnector;
34  import org.apache.mina.core.future.ConnectFuture;
35  import org.apache.mina.core.future.DefaultConnectFuture;
36  import org.apache.mina.core.session.IdleStatusChecker;
37  import org.apache.mina.core.service.IoConnector;
38  import org.apache.mina.core.future.IoFuture;
39  import org.apache.mina.core.session.IoSessionInitializer;
40  import org.apache.mina.core.service.TransportMetadata;
41  import org.slf4j.Logger;
42  import org.slf4j.LoggerFactory;
43  
44  /**
45   * {@link IoConnector} for serial communication transport.
46   *
47   * @author <a href="http://mina.apache.org">Apache MINA Project</a>
48   */
49  public final class SerialConnector extends AbstractIoConnector {
50      private final Logger log;
51      
52      private IdleStatusChecker idleChecker;
53  
54      public SerialConnector() {
55          this(null);
56      }
57  
58      public SerialConnector(Executor executor) {
59          super(new DefaultSerialSessionConfig(), executor);
60          log = LoggerFactory.getLogger(SerialConnector.class);
61          
62          idleChecker = new IdleStatusChecker();
63          // we schedule the idle status checking task in this service exceutor
64          // it will be woke up every seconds
65          executeWorker(idleChecker.getNotifyingTask(), "idleStatusChecker");
66          
67      }
68  
69      @Override
70      protected synchronized ConnectFuture connect0(
71              SocketAddress remoteAddress, SocketAddress localAddress,
72              IoSessionInitializer<? extends ConnectFuture> sessionInitializer) {
73  
74          CommPortIdentifier portId;
75          Enumeration<?> portList = CommPortIdentifier.getPortIdentifiers();
76  
77          SerialAddress portAddress = (SerialAddress) remoteAddress;
78  
79          // looping around found ports
80          while (portList.hasMoreElements()) {
81              portId = (CommPortIdentifier) portList.nextElement();
82              if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
83                  if (log.isDebugEnabled()) {
84                      log.debug("Serial port discovered : " + portId.getName());
85                  }
86                  if (portId.getName().equals(portAddress.getName())) {
87                      try {
88                          if (log.isDebugEnabled()) {
89                              log
90                                      .debug("Serial port found : "
91                                              + portId.getName());
92                          }
93  
94                          SerialPort serialPort = initializePort("Apache MINA",
95                                  portId, portAddress);
96  
97                          ConnectFuture future = new DefaultConnectFuture();
98                          SerialSessionImpl session = new SerialSessionImpl(
99                                  this, getListeners(), portAddress, serialPort);
100                         initSession(session, future, sessionInitializer);
101                         session.start();
102                         return future;
103                     } catch (PortInUseException e) {
104                         if (log.isDebugEnabled()) {
105                             log.debug("Port In Use Exception : ", e);
106                         }
107                         return DefaultConnectFuture.newFailedFuture(e);
108                     } catch (UnsupportedCommOperationException e) {
109                         if (log.isDebugEnabled()) {
110                             log.debug("Comm Exception : ", e);
111                         }
112                         return DefaultConnectFuture.newFailedFuture(e);
113                     } catch (IOException e) {
114                         if (log.isDebugEnabled()) {
115                             log.debug("IOException : ", e);
116                         }
117                         return DefaultConnectFuture.newFailedFuture(e);
118                     } catch (TooManyListenersException e) {
119                         if (log.isDebugEnabled()) {
120                             log.debug("TooManyListenersException : ", e);
121                         }
122                         return DefaultConnectFuture.newFailedFuture(e);
123                     }
124                 }
125             }
126         }
127 
128         return DefaultConnectFuture
129                 .newFailedFuture(new SerialPortUnavailableException(
130                         "Serial port not found"));
131     }
132 
133     @Override
134     protected IoFuture dispose0() throws Exception {
135         // stop the idle checking task
136         idleChecker.getNotifyingTask().cancel();
137         return null;
138     }
139 
140     public TransportMetadata getTransportMetadata() {
141         return SerialSessionImpl.METADATA;
142     }
143 
144     private SerialPort initializePort(String user, CommPortIdentifier portId,
145             SerialAddress portAddress)
146             throws UnsupportedCommOperationException, PortInUseException {
147 
148         SerialSessionConfig config = (SerialSessionConfig) getSessionConfig();
149 
150         long connectTimeout = getConnectTimeoutMillis();
151         if (connectTimeout > Integer.MAX_VALUE) {
152             connectTimeout = Integer.MAX_VALUE;
153         }
154 
155         SerialPort serialPort = (SerialPort) portId.open(
156                 user, (int) connectTimeout);
157 
158         serialPort.setSerialPortParams(portAddress.getBauds(), portAddress
159                 .getDataBitsForRXTX(), portAddress.getStopBitsForRXTX(),
160                 portAddress.getParityForRXTX());
161 
162         serialPort.setFlowControlMode(portAddress.getFLowControlForRXTX());
163 
164         serialPort.notifyOnDataAvailable(true);
165 
166         if (config.isLowLatency()) {
167             serialPort.setLowLatency();
168         }
169 
170         serialPort.setInputBufferSize(config.getInputBufferSize());
171         serialPort.setOutputBufferSize(config.getOutputBufferSize());
172 
173         if (config.getReceiveThreshold() >= 0) {
174             serialPort.enableReceiveThreshold(config.getReceiveThreshold());
175         } else {
176             serialPort.disableReceiveThreshold();
177         }
178 
179         return serialPort;
180     }
181 
182     IdleStatusChecker getIdleStatusChecker0() {
183         return idleChecker;
184     }
185 }