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