コード例 #1
0
ファイル: Rs232Connector.java プロジェクト: remiguitreau/ojt
  @Override
  public void open() {
    // r�cup�ration de l'identifiant du port
    try {
      logger.info("Liste des ports : " + CommPortIdentifier.getPortIdentifiers());
      final Enumeration identifiers = CommPortIdentifier.getPortIdentifiers();
      while (identifiers.hasMoreElements()) {
        logger.info(((CommPortIdentifier) identifiers.nextElement()).getName());
      }
      portId = CommPortIdentifier.getPortIdentifier(connectionDescriptor.getPortName());
    } catch (final NoSuchPortException e) {
      throw new RuntimeException(
          "Rs232Connector (" + connectionDescriptor.getPortName() + ") : " + e.toString());
    }

    // ouverture du port
    try {
      serialPort = (SerialPort) portId.open("driver", 2000);
    } catch (final PortInUseException e) {
      throw new RuntimeException(
          "Rs232Connector (" + connectionDescriptor.getPortName() + ") : " + e.toString());
    }

    // param�trage du port
    // hmmmmmmmmmmmm cf :
    // http://forum.java.sun.com/thread.jspa?threadID=673793&start=15&tstart=0
    boolean result = false;
    while (!result) {
      try {
        serialPort.setSerialPortParams(
            connectionDescriptor.getBaudRate(),
            connectionDescriptor.getDataBits(),
            connectionDescriptor.getStopBits(),
            connectionDescriptor.getParity());
        result = true;
      } catch (final Exception ex) {
        logger.error("Unable to set serial ports parameters", ex);
        result = false;
        try {
          Thread.sleep(200);
        } catch (final InterruptedException exc) {
          logger.error("Error while sleeping", exc);
        }
      }
    }
    /** @todo : test */
    // Suppression
    try {
      serialPort.enableReceiveTimeout(5000); // timeout de 1 ms
    } catch (final UnsupportedCommOperationException ex) {
      logger.warn(
          "Warning : impossible to set timeout for port " + connectionDescriptor.getPortName(), ex);
    }

    try {
      // inputStream = new BufferedReader(new
      // InputStreamReader(serialPort.getInputStream()));
      inputStream = serialPort.getInputStream();
    } catch (final IOException e) {
      serialPort.close();
      throw new RuntimeException(
          "Rs232Connector (" + connectionDescriptor.getPortName() + ") : " + e.toString());
    }

    try {
      serialPort.addEventListener(
          new SerialPortEventListener() {

            @Override
            public void serialEvent(final SerialPortEvent evt) {
              if (evt.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
                synchronized (bufferMonitor) {
                  if (writeIndex >= BUFFER_LENGTH - 1) {
                    flushBuffer();
                  }
                  try {
                    byte newData = 0;
                    while (newData != -1) {
                      newData = (byte) inputStream.read();
                      if (newData == -1) {
                        break;
                      }
                      if (writeIndex >= BUFFER_LENGTH - 1) {
                        flushBuffer();
                      }
                      buffer[writeIndex++] = newData;
                    }
                  } catch (final Exception exc) {
                    logger.error("Error reading input stream from serial port", exc);
                  }
                  bufferMonitor.notify();
                }
              }
            }
          });
      serialPort.notifyOnDataAvailable(true);
      serialPort.enableReceiveTimeout(20);

    } catch (final TooManyListenersException exc) {
      logger.error("", exc);
    } catch (final UnsupportedCommOperationException exc) {
      logger.error("", exc);
    }

    final Thread threadParse =
        new Thread("Rs232Connector_" + connectionDescriptor.getPortName() + "_dispatch_thread") {
          @Override
          public void run() {
            try {
              parseThread();
            } catch (final Exception e) {
              logger.error("Error while parsing thread", e);
            }
          }
        };
    threadParse.start();
  }