예제 #1
0
  /**
   * Start modem command manager.
   *
   * @throws Exception the exception
   */
  public void startModemCommandManager() throws Exception {
    CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(this.commandPortName);
    if (portIdentifier.isCurrentlyOwned()) {
      logger.error("Serial port " + this.commandPortName + " is currently in use");
    }
    CommPort commPort = portIdentifier.open(this.getClass().getName(), 2000);
    if (commPort instanceof SerialPort) {
      modemComPort = (SerialPort) commPort;
      modemComPort.setSerialPortParams(
          9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);

      modemComPort.notifyOnDataAvailable(true);

      commandInputStream = new DataInputStream(modemComPort.getInputStream());
      serialCommandReader = new SerialCommandReader(commandInputStream, this);
      modemComPort.addEventListener(serialCommandReader);

      commandOutputStream = new DataOutputStream(modemComPort.getOutputStream());

      this.sendCommandToModem(ATCommands.DISABLE_ECHO);
      this.sendCommandToModem(ATCommands.DISABLE_DIAGNOSTIC);
      this.sendCommandToModem(ATCommands.END_CALL);
      this.sendCommandToModem(ATCommands.CHECK_PIN);
    }
  }
예제 #2
0
  /** Establish the connection with the device connected to the serial port. */
  public void setupSerialPort() {

    try {

      // If port already open, close it.
      if (serialPort != null) {
        serialPort.close();
        serialPort = null;
      }

      // Initialize serial port attributes.
      log.info("Fetching communication port {}", getTanitaCommPort());
      CommPortIdentifier wPortId = CommPortIdentifier.getPortIdentifier(getTanitaCommPort());

      log.info("Opening communication port {}", getTanitaCommPort());
      serialPort = (SerialPort) wPortId.open(portOwnerName, 2000);

      // Make sure the port is "Clear To Send"
      serialPort.setSerialPortParams(baudeRate, dataLength, stopBit, parity);
      bufferedReader = new BufferedReader(new InputStreamReader(serialPort.getInputStream()));

      portIsAvailable = checkIfPortIsAvailable();

    } catch (Exception wCouldNotAccessSerialPort) {
      portIsAvailable = false;
      log.warn("Could not access the specified serial port.");
    }
  }
예제 #3
0
  private void write(byte[] data) {
    try {
      if (m_out == null) {
        m_PortIdPrinter =
            CommPortIdentifier.getPortIdentifier(
                m_sPortScale); // Tomamos el puerto
        m_CommPortPrinter =
            (SerialPort) m_PortIdPrinter.open("PORTID", 2000); // Abrimos el puerto

        m_out = m_CommPortPrinter.getOutputStream(); // Tomamos el chorro de escritura
        m_in = m_CommPortPrinter.getInputStream();

        m_CommPortPrinter.addEventListener(this);
        m_CommPortPrinter.notifyOnDataAvailable(true);

        m_CommPortPrinter.setSerialPortParams(
            4800,
            SerialPort.DATABITS_8,
            SerialPort.STOPBITS_1,
            SerialPort.PARITY_ODD); // Configuramos el puerto
      }
      m_out.write(data);
    } catch (NoSuchPortException e) {
      e.printStackTrace();
    } catch (PortInUseException e) {
      e.printStackTrace();
    } catch (UnsupportedCommOperationException e) {
      e.printStackTrace();
    } catch (TooManyListenersException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
예제 #4
0
파일: TestSer.java 프로젝트: sherckuith/jop
  public TestSer(String port) {

    try {
      portId = CommPortIdentifier.getPortIdentifier(port);
      serialPort = (SerialPort) portId.open("TestSer", 2000);
      is = serialPort.getInputStream();
      os = serialPort.getOutputStream();
      /*
      			serialPort.addEventListener(this);
      			serialPort.notifyOnDataAvailable(true);
      */

      serialPort.setSerialPortParams(
          115200, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);

      serialPort.setFlowControlMode(
          SerialPort.FLOWCONTROL_RTSCTS_OUT | SerialPort.FLOWCONTROL_RTSCTS_IN);

      serialPort.enableReceiveTimeout(TIMEOUT);
      //			serialPort.enableReceiveThreshold(4);

    } catch (Exception e) {
      System.out.println(e.getMessage());
      System.exit(-1);
    }
  }
예제 #5
0
 /**
  * Initialize this device and open the serial port.
  *
  * @throws InitializationException if port can not be opened
  */
 void initialize() throws InitializationException {
   try {
     // parse ports and if the default port is found, initialized the reader
     portId = CommPortIdentifier.getPortIdentifier(port);
     // initialize serial port
     serialPort = portId.open("openHAB", 2000);
     // set port parameters
     serialPort.setSerialPortParams(baud, databits, stopbit, parity);
     inputStream = serialPort.getInputStream();
     outputStream = serialPort.getOutputStream();
   } catch (UnsupportedCommOperationException e) {
     throw new InitializationException(e);
   } catch (IOException e) {
     throw new InitializationException(e);
   } catch (PortInUseException e) {
     throw new InitializationException(e);
   } catch (NoSuchPortException e) {
     // enumerate the port identifiers in the exception to be helpful
     final StringBuilder sb = new StringBuilder();
     @SuppressWarnings("unchecked")
     Enumeration<CommPortIdentifier> portList = CommPortIdentifier.getPortIdentifiers();
     while (portList.hasMoreElements()) {
       final CommPortIdentifier id = portList.nextElement();
       if (id.getPortType() == CommPortIdentifier.PORT_SERIAL) {
         sb.append(id.getName() + "\n");
       }
     }
     throw new InitializationException(
         "Serial port '" + port + "' could not be found. Available ports are:\n" + sb.toString());
   }
 }
예제 #6
0
  @Override
  public void connect(final String commPort, final String commSpeed) {
    try {
      synchronized (_mutex) {
        _comPortId = CommPortIdentifier.getPortIdentifier(commPort);
        _serialPort = (SerialPort) _comPortId.open("ComPort", 2000);
        _inputStream = _serialPort.getInputStream();
        _outputStream = _serialPort.getOutputStream();
        _serialPort.addEventListener(new MySerialCommPortEventListener());
        _serialPort.notifyOnDataAvailable(true);
        final int speed = Integer.parseInt(commSpeed);
        _serialPort.setSerialPortParams(
            speed, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
        _connected = true;
        Thread.sleep(3000);
        notifyConnectionStatus(true);

        _connectionThread.start();
      }
    } catch (Exception e) {
      e
          .printStackTrace(); // To change body of catch statement use File | Settings | File
                              // Templates.
    }
  }
예제 #7
0
  public void open() throws IOException {
    try {
      if (portName != null) {
        portId = CommPortIdentifier.getPortIdentifier(portName);
      }
      if (portId == null) {
        throw new IOException("Invalid port " + portName);
      }
      serialPort = (SerialPort) portId.open(portId.getName(), baudRate);
      if (portId == null) {
        throw new IOException("Invalid port " + portName);
      }

      serialPort.setSerialPortParams(
          baudRate, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
      serialPort.notifyOnOutputEmpty(true);
      outputStream = serialPort.getOutputStream();
      inputStream = serialPort.getInputStream();
      Logger.getLogger(SerialDevice.class.getName())
          .log(Level.INFO, "Connection Stabilished with {0}", serialPort.getName());
    } catch (Exception e) {
      e.printStackTrace();
      Logger.getLogger(SerialDevice.class.getName())
          .log(Level.SEVERE, "Could not init the device on " + serialPort.getName(), e);
      serialPort.close();
    }
  }
  /**
   * Gets the serial port on the given port name. Throws an {@link IOException} if it does not
   * succeed in doing so.
   *
   * @param portName The port name.
   * @return The port.
   * @throws IOException If the port could not be opened.
   */
  private final SerialPort getSerialPort(final String portName) throws IOException {
    try {
      final CommPortIdentifier identifier = CommPortIdentifier.getPortIdentifier(portName);

      if (identifier.isCurrentlyOwned()) {
        throw new IOException(
            "The port specified ["
                + portName
                + "] is already in use by ["
                + identifier.getCurrentOwner()
                + "] !");
      }

      final CommPort rawPort = identifier.open("DOM_SER_DRV", 2000);

      if (rawPort instanceof SerialPort) {
        final SerialPort port = (SerialPort) rawPort;
        port.setSerialPortParams(
            BAUDRATE, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);

        return port;
      } else {
        throw new IOException("Port [" + portName + "] is not a serial port !");
      }
    } catch (NoSuchPortException e) {
      throw new IOException("The port specified [" + portName + "] does not exist !", e);
    } catch (PortInUseException e) {
      throw new IOException("The port specified [" + portName + "] is already in use !");
    } catch (UnsupportedCommOperationException e) {
      throw new IOException("Unsupported comm operation when setting the serial parameters !", e);
    }
  }
예제 #9
0
  @Override
  public void connect(String portName) {
    CommPortIdentifier portIdentifier;
    try {
      portIdentifier = CommPortIdentifier.getPortIdentifier(portName);
      CommPort commPort = portIdentifier.open("TigerControlPanel", 2000);

      SerialPort serialPort = (SerialPort) commPort;
      serialPort.setSerialPortParams(
          2400, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);

      _sReader = new SerialReader(serialPort.getInputStream());
      serialPort.addEventListener(_sReader);
      serialPort.notifyOnDataAvailable(true);
      _sWriter = new SerialWriter(serialPort.getOutputStream());

    } catch (NoSuchPortException e) {
      DialogManager.showDialog(
          "Error de conexión", "No existe el puerto seleccionado", null, DialogType.ERROR);
    } catch (PortInUseException e) {
      DialogManager.showDialog(
          "Error de conexión",
          "El puerto seleccionado se encuentra en uso",
          null,
          DialogType.ERROR);
    } catch (Exception e) {
      DialogManager.showDialog(
          "Error de conexión", "Se ha producido un error de conexión", null, DialogType.ERROR);
    }
  }
  public static void main(String[] args)
      throws NoSuchPortException, PortInUseException, UnsupportedCommOperationException,
          IOException, ParseException {
    if (args.length != 2) {
      System.err.println("Usage: <prog> portDevice hexfile.hex");
      System.exit(1);
    }

    STM32BootLoader me = new STM32BootLoader();

    CommPortIdentifier comident = CommPortIdentifier.getPortIdentifier(args[0]);

    SerialPort sp = (SerialPort) comident.open("STM32BootLoader", 200);

    sp.setSerialPortParams(
        57600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_EVEN);

    sp.setFlowControlMode(SerialPort.FLOWCONTROL_NONE);

    // Setup serial port and reply timeout. Found that such a long timeout
    // IS necessary.
    me.setSerialPort(sp, 5000);

    try {
      File f = new File(args[1]);

      byte[] image = HexFileParser.parseFile(f);

      me.program(image, false, 0);
    } finally {
      me.close();
    }
  }
예제 #11
0
  private void init() {

    try {
      if (m_out == null) {
        m_PortIdPrinter = CommPortIdentifier.getPortIdentifier(m_sPort); // Tomamos el puerto
        m_CommPortPrinter = m_PortIdPrinter.open("PORTID", 2000); // Abrimos el puerto

        m_out = m_CommPortPrinter.getOutputStream(); // Tomamos el chorro de escritura

        if (m_PortIdPrinter.getPortType() == CommPortIdentifier.PORT_SERIAL) {
          ((SerialPort) m_CommPortPrinter)
              .setSerialPortParams(
                  9600,
                  SerialPort.DATABITS_8,
                  SerialPort.STOPBITS_1,
                  SerialPort.PARITY_NONE); // Configuramos el puerto
        } else if (m_PortIdPrinter.getPortType() == CommPortIdentifier.PORT_PARALLEL) {
          ((ParallelPort) m_CommPortPrinter).setMode(1);
        }
      }
    } catch (Exception e) {
      m_PortIdPrinter = null;
      m_CommPortPrinter = null;
      m_out = null;
      m_in = null;
      //        } catch (NoSuchPortException e) {
      //        } catch (PortInUseException e) {
      //        } catch (UnsupportedCommOperationException e) {
      //        } catch (IOException e) {
    }
  }
예제 #12
0
  public String openPort(String portName, String appName) {
    // open the port, check ability to set moderators
    try {
      // get and open the primary port
      CommPortIdentifier portID = CommPortIdentifier.getPortIdentifier(portName);
      try {
        activeSerialPort = (SerialPort) portID.open(appName, 2000); // name of program, msec to wait
      } catch (PortInUseException p) {
        return handlePortBusy(p, portName, log);
      }

      // try to set it for communication via SerialDriver
      try {
        activeSerialPort.setSerialPortParams(
            9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
      } catch (gnu.io.UnsupportedCommOperationException e) {
        log.error("Cannot set serial parameters on port " + portName + ": " + e.getMessage());
        return "Cannot set serial parameters on port " + portName + ": " + e.getMessage();
      }

      // set RTS high, DTR high
      activeSerialPort.setRTS(true); // not connected in some serial ports and adapters
      activeSerialPort.setDTR(true); // pin 1 in DIN8; on main connector, this is DTR

      // disable flow control; hardware lines used for signaling, XON/XOFF might appear in data
      activeSerialPort.setFlowControlMode(0);
      activeSerialPort.enableReceiveTimeout(50); // 50 mSec timeout before sending chars

      // set timeout
      // activeSerialPort.enableReceiveTimeout(1000);
      log.debug(
          "Serial timeout was observed as: "
              + activeSerialPort.getReceiveTimeout()
              + " "
              + activeSerialPort.isReceiveTimeoutEnabled());

      // get and save stream
      serialStream = activeSerialPort.getInputStream();

      // purge contents, if any
      purgeStream(serialStream);

      // report status
      if (log.isInfoEnabled()) {
        log.info(
            "Wangrow " + portName + " port opened at " + activeSerialPort.getBaudRate() + " baud");
      }
      opened = true;

    } catch (gnu.io.NoSuchPortException p) {
      return handlePortNotFound(p, portName, log);
    } catch (Exception ex) {
      log.error("Unexpected exception while opening port " + portName + " trace follows: " + ex);
      ex.printStackTrace();
      return "Unexpected error while opening port " + portName + ": " + ex;
    }

    return null; // indicates OK return
  }
예제 #13
0
  public HittPolling(String comport, int baudrate) {
    _baudrate = baudrate;
    try {
      CommPortIdentifier com = CommPortIdentifier.getPortIdentifier(comport);
      _comPortIdent = com;

      _usable = true;
    } catch (NoSuchPortException e) {
      _usable = false;
      PLog.error("There is no COM-Port called: " + comport, e);
    }
  }
예제 #14
0
 public static SerialPort openPortByName(String name, int baudRate) {
   SerialPort port = null;
   try {
     CommPortIdentifier identifier = CommPortIdentifier.getPortIdentifier(name);
     port = (SerialPort) identifier.open("SerialPort", 2000);
     port.setSerialPortParams(
         baudRate, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
   } catch (PortInUseException | NoSuchPortException | UnsupportedCommOperationException ex) {
     ErrorDialog dialog = new ErrorDialog(null, true, ex.getMessage());
     ComponentPosition.centerFrame(dialog);
     dialog.setVisible(true);
   }
   return port;
 }
예제 #15
0
  @Override
  public List<String> getComPortAvailable() {
    final List<String> ret = new ArrayList<String>();
    for (final String comPortId : commPorstIds) {
      try {
        CommPortIdentifier.getPortIdentifier(comPortId);
        ret.add(comPortId);
      } catch (Exception e) {
        System.out.println(comPortId + " unavailable");
      }
    }

    return ret;
  }
  @SuppressWarnings("unchecked")
  public SerialTransmitController(String port, String rts_or_dtr) throws Exception {
    CommPortIdentifier pi = null;
    try {
      pi = CommPortIdentifier.getPortIdentifier(port);
    } catch (NoSuchPortException nspe) {
      String port_names = "";
      boolean comma = false;
      Enumeration<CommPortIdentifier> ports = CommPortIdentifier.getPortIdentifiers();
      while (ports.hasMoreElements()) {
        CommPortIdentifier portIdentifier = ports.nextElement();
        if (comma) port_names += ",";
        port_names += portIdentifier.getName();
        comma = true;
      }
      throw new IOException(
          String.format("Port %s is not valid (valid ports are %s)", port, port_names));
    }
    CommPort ptt_comm_port = null;
    try {
      ptt_comm_port = pi.open(this.getClass().getName(), 1000);
    } catch (PortInUseException piue) {
      throw new IOException(String.format("Port %s is in use", port));
    }
    if (ptt_comm_port instanceof SerialPort) {
      ptt_serial_port = (SerialPort) ptt_comm_port;
      // serialPort.setSerialPortParams(57600,SerialPort.DATABITS_8,
      //		                           SerialPort.STOPBITS_1,SerialPort.PARITY_NONE);
    } else {
      System.err.println("5");
      throw new IOException(String.format("Port %s is not a serial port", port));
    }

    ptt_serial_port.setRTS(false);
    ptt_serial_port.setDTR(false);

    System.err.println("Opened a PTT port: " + port);

    if (rts_or_dtr.equalsIgnoreCase("RTS")) {
      rts = true;
      return;
    }
    if (rts_or_dtr.equalsIgnoreCase("DTR")) {
      dtr = true;
      return;
    }

    throw new IOException(String.format("Signal %s is not valid (must be RTS or DTR)", rts_or_dtr));
  }
예제 #17
0
  /**
   * This constructs a SonarPingModel
   *
   * @param comPortName port which the sensor is pluged in
   */
  SonarPingModel(String comPortName) {
    try {
      // Identifying the port
      this.basicPort = CommPortIdentifier.getPortIdentifier(comPortName);
      this.port = (SerialPort) this.basicPort.open("", 1);

      // Port Settings
      port.setSerialPortParams(
          9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);

      // Input and Output Streams to write to the port
      output = port.getOutputStream();
      input = new BufferedReader(new InputStreamReader(this.port.getInputStream()));
    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }
예제 #18
0
 /**
  * Start call.
  *
  * @throws Exception the exception
  */
 public void startCall() throws Exception {
   CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(this.streamPortName);
   if (portIdentifier.isCurrentlyOwned()) {
     logger.error("Serial port " + this.streamPortName + " is currently in use");
   }
   CommPort commPort = portIdentifier.open(this.getClass().getName(), 2000);
   if (commPort instanceof SerialPort) {
     voiceStreamCommPort = (SerialPort) commPort;
     voiceStreamCommPort.setSerialPortParams(
         230400, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
     voiceInputStream = new DataInputStream(voiceStreamCommPort.getInputStream());
     voiceOutputStream = new DataOutputStream(voiceStreamCommPort.getOutputStream());
     serialVoiceReader = new SerialVoiceReader(voiceInputStream, af);
     serialVoiceWriter = new SerialVoiceWriter(voiceOutputStream, af, playMessage);
     (new Thread(serialVoiceReader, "VoiceReader")).start();
     (new Thread(serialVoiceWriter, "VoiceWriter")).start();
   }
 }
  /** @param data */
  @Override
  protected void internalWrite(byte[] data) {
    try {
      if (m_out == null) {
        m_PortIdPrinter =
            CommPortIdentifier.getPortIdentifier(
                m_sPortPrinter); // Tomamos el puerto
        m_CommPortPrinter = m_PortIdPrinter.open("PORTID", 2000); // Abrimos el puerto

        m_out = m_CommPortPrinter.getOutputStream(); // Tomamos el chorro de escritura

        if (m_PortIdPrinter.getPortType() == CommPortIdentifier.PORT_SERIAL) {
          ((SerialPort) m_CommPortPrinter)
              .setSerialPortParams(
                  9600,
                  SerialPort.DATABITS_8,
                  SerialPort.STOPBITS_1,
                  SerialPort.PARITY_NONE); // Configuramos el puerto
          ((SerialPort) m_CommPortPrinter)
              .setFlowControlMode(
                  SerialPort
                      .FLOWCONTROL_RTSCTS_IN); // this line prevents the printer tmu220 to stop
                                               // printing after +-18 lines printed
          // this line prevents the printer tmu220 to stop printing after +-18 lines printed. Bug
          // 8324
          // But if added a regression error appears. Bug 9417, Better to keep it commented.
          // ((SerialPort)m_CommPortPrinter).setFlowControlMode(SerialPort.FLOWCONTROL_RTSCTS_IN);
          // Not needed to set parallel properties
          //                } else if (m_PortIdPrinter.getPortType() ==
          // CommPortIdentifier.PORT_PARALLEL) {
          //                    ((ParallelPort)m_CommPortPrinter).setMode(1);

        }
      }
      m_out.write(data);
      // JG 16 May 12 use multicatch
    } catch (NoSuchPortException
        | PortInUseException
        | UnsupportedCommOperationException
        | IOException e) {
      System.err.println(e);
    }
  }
예제 #20
0
  public static void readFromArduino() throws Exception {
    // for linux
    // CommPortIdentifier portId = CommPortIdentifier.getPortIdentifier("/dev/ttyACM3");

    // for windows
    CommPortIdentifier portId = CommPortIdentifier.getPortIdentifier("COM5");
    // CommPortIdentifier portId = CommPortIdentifier.getPortIdentifier("COM4");

    SerialPort port = (SerialPort) portId.open("serial talk", 4000);
    input = port.getInputStream();
    port.setSerialPortParams(
        9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);

    while (true) {
      if (input.available() > 0) {
        System.out.print((char) (input.read()));
      }
    }
  }
예제 #21
0
  @Override
  protected CommunicationChannel connect() {
    logger.info("Connecting to INT-RS module at {}", this.port);

    try {
      CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(this.port);
      SerialPort serialPort = portIdentifier.open("org.openhab.binding.satel", 2000);
      serialPort.setSerialPortParams(
          19200, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
      serialPort.enableReceiveTimeout(this.getTimeout());
      // RXTX serial port library causes high CPU load
      // Start event listener, which will just sleep and slow down event
      // loop
      serialPort.addEventListener(
          new SerialPortEventListener() {
            @Override
            public void serialEvent(SerialPortEvent ev) {
              try {
                logger.trace("RXTX library CPU load workaround, sleep forever");
                Thread.sleep(Long.MAX_VALUE);
              } catch (InterruptedException e) {
              }
            }
          });
      serialPort.notifyOnDataAvailable(true);

      logger.info("INT-RS module connected successfuly");
      return new SerialCommunicationChannel(serialPort);

    } catch (NoSuchPortException e) {
      logger.error("Port {} does not exist", this.port);
    } catch (PortInUseException e) {
      logger.error("Port {} in use.", this.port);
    } catch (UnsupportedCommOperationException e) {
      logger.error("Unsupported comm operation on port {}.", this.port);
    } catch (TooManyListenersException e) {
      logger.error("Too many listeners on port {}.", this.port);
    }

    return null;
  }
예제 #22
0
  public CardReader(String portName)
      throws IOException, PortInUseException, UnsupportedCommOperationException,
          NoSuchPortException {
    CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(portName);
    if (portIdentifier.isCurrentlyOwned()) {
      System.out.println("Error: Port is currently in use");
    } else {
      int timeout = 2000;
      CommPort commPort = portIdentifier.open(this.getClass().getName(), timeout);

      if (commPort instanceof SerialPort) {
        SerialPort serialPort = (SerialPort) commPort;
        serialPort.setSerialPortParams(
            9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);

        in = serialPort.getInputStream();

      } else {
        System.out.println("Error: Only serial ports are handled by this example.");
      }
    }
  }
예제 #23
0
  /** @see com.svhelloworld.knotlog.engine.sources.StreamedSource#open() */
  @Override
  public InputStream open() {
    try {
      // make sure the specified port is available
      CommPortIdentifier identifier = CommPortIdentifier.getPortIdentifier(config.getName());
      if (identifier.isCurrentlyOwned()) {
        throw new SerialPortOccupiedException(
            config.getName() + " port is currently opened by another application");
      }
      // open up the port
      CommPort port = identifier.open(getOwnerName(), PORT_TIMEOUT);
      if (port instanceof SerialPort) {

        // configure serial port
        serialPort = (SerialPort) port;
        serialPort.setSerialPortParams(
            config.getBaudRate(),
            config.getDataBits().getRXTXConstant(),
            config.getStopBit().getRXTXConstant(),
            config.getParity().getRXTXConstant());
        /*
         * the following 2 lines fix the exception:
         *       "IOException: Underlying input stream returned zero bytes"
         *       that is thrown when we read from the InputStream.
         */
        serialPort.enableReceiveTimeout(PORT_TIMEOUT);
        serialPort.enableReceiveThreshold(0);

        InputStream is = serialPort.getInputStream();
        return is;
      }
      // not a serial port
      throw new SerialPortException("must operate against a serial port");
    } catch (PortInUseException e) {
      throw new SerialPortOccupiedException(e.getMessage(), e);
    } catch (Exception e) {
      throw new SerialPortException(e.getMessage(), e);
    }
  }
예제 #24
0
  private SerialPort connectSerial(String portName)
      throws NoSuchPortException, PortInUseException, UnsupportedCommOperationException {
    SerialPort serialPort = null;

    CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(portName);

    if (portIdentifier.isCurrentlyOwned()) {
      System.out.println("Error: Port is currently in use");
    } else {
      CommPort commPort = portIdentifier.open(this.getClass().getName(), 2000);
      if (commPort instanceof SerialPort) {
        serialPort = (SerialPort) commPort;
        serialPort.setSerialPortParams(
            57600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
        //				serialPort.setSerialPortParams(115200, SerialPort.DATABITS_8,
        //						SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
      } else {
        System.out.println("Error: Only serial ports are handled by this example.");
      }
    }
    return serialPort;
  }
예제 #25
0
  void connect(String portName) throws Exception {
    CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(portName);
    if (portIdentifier.isCurrentlyOwned()) {
      System.out.println("Error: Port is currently in use");
    } else {
      CommPort commPort = portIdentifier.open(this.getClass().getName(), 2000);

      if (commPort instanceof SerialPort) {
        SerialPort mSerialPort = (SerialPort) commPort;
        mSerialPort.setSerialPortParams(
            57600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);

        InputStream mIn = mSerialPort.getInputStream();
        OutputStream mOut = mSerialPort.getOutputStream();

        (new Thread(new SerialReader(mIn))).start();
        (new Thread(new SerialWriter(mOut))).start();

      } else {
        System.out.println("Error: Only serial ports are handled by this example.");
      }
    }
  }
  /** 通过串口向单片机写入数据 */
  public boolean portWrite() {
    boolean notFinished = true;
    try {
      // get port ID
      CommPortIdentifier portId = CommPortIdentifier.getPortIdentifier(this.portName);

      // open port(port holder, timeout),打开端口(串口所有者,超时等待时间:ms)
      try {
        this.sPort = (SerialPort) portId.open("可爱的皮卡丘", this.timeout);

        // set port(BaudRate,Databits,Stopbits,Parity),设置串口(波特率,数据位,停止位,校验位)
        try {
          this.sPort.setSerialPortParams(
              9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
        } catch (UnsupportedCommOperationException e) {
          e.printStackTrace();
        }

        // 写入数据
        OutputStream OS = null;
        try {
          OS = new BufferedOutputStream(sPort.getOutputStream());
        } catch (IOException e) {
          e.printStackTrace();
        }
        // 选择操作
        System.out.println("选择一下操作: 静止按1; 前进按2; 后退按3; 结束操作按4.");
        int command = s.nextInt();

        switch (command) {
          case 1:
            try {
              OS.write(this.stop);
            } catch (IOException e) {
              e.printStackTrace();
            }
            break;
          case 2:
            try {
              OS.write(this.forward);
            } catch (IOException e) {
              e.printStackTrace();
            }
            break;
          case 3:
            try {
              OS.write(this.backward);
            } catch (IOException e) {
              e.printStackTrace();
            }
            break;
          case 4:
            notFinished = false;
            break;
        }

        try {
          OS.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
        this.sPort.close();

      } catch (PortInUseException e) {
        e.printStackTrace();
      }
    } catch (NoSuchPortException e) {
      e.printStackTrace();
    }
    return notFinished;
  }
예제 #27
0
  public synchronized String openPort(String portName, String appName) {
    // open the port, check ability to set moderators
    try {
      // get and open the primary port
      CommPortIdentifier portID = CommPortIdentifier.getPortIdentifier(portName);
      try {
        activeSerialPort = (SerialPort) portID.open(appName, 2000); // name of program, msec to wait
      } catch (PortInUseException p) {
        handlePortBusy(p, portName);
        return "Port " + p + " in use already";
      }

      // try to set it for communication via SerialDriver
      try {
        // Doc says 7 bits, but 8 seems needed
        activeSerialPort.setSerialPortParams(
            38400, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
      } catch (gnu.io.UnsupportedCommOperationException e) {
        log.error("Cannot set serial parameters on port " + portName + ": " + e.getMessage());
        return "Cannot set serial parameters on port " + portName + ": " + e.getMessage();
      }

      // set RTS high, DTR high
      activeSerialPort.setRTS(true); // not connected in some serial ports and adapters
      activeSerialPort.setDTR(true); // pin 1 in DIN8; on main connector, this is DTR

      // disable flow control; hardware lines used for signaling, XON/XOFF might appear in data
      activeSerialPort.setFlowControlMode(0);

      // set timeout
      log.debug(
          "Serial timeout was observed as: "
              + activeSerialPort.getReceiveTimeout()
              + " "
              + activeSerialPort.isReceiveTimeoutEnabled());

      // get and save stream
      serialStream = new DataInputStream(activeSerialPort.getInputStream());
      ostream = activeSerialPort.getOutputStream();

      // make less verbose
      sendBytes(new byte[] {(byte) 'L', (byte) '-', 10, 13});
      // purge contents, if any
      int count = serialStream.available();
      log.debug("input stream shows " + count + " bytes available");
      while (count > 0) {
        serialStream.skip(count);
        count = serialStream.available();
      }

      // report status?
      if (log.isInfoEnabled()) {
        log.info(
            portName
                + " port opened at "
                + activeSerialPort.getBaudRate()
                + " baud, sees "
                + " DTR: "
                + activeSerialPort.isDTR()
                + " RTS: "
                + activeSerialPort.isRTS()
                + " DSR: "
                + activeSerialPort.isDSR()
                + " CTS: "
                + activeSerialPort.isCTS()
                + "  CD: "
                + activeSerialPort.isCD());
      }

    } catch (java.io.IOException ex) {
      log.error("IO error while opening port " + portName, ex);
      return "IO error while opening port " + portName + ": " + ex;
    } catch (gnu.io.UnsupportedCommOperationException ex) {
      log.error("Unsupported communications operation while opening port " + portName, ex);
      return "Unsupported communications operation while opening port " + portName + ": " + ex;
    } catch (gnu.io.NoSuchPortException ex) {
      log.error("No such port: " + portName, ex);
      return "No such port: " + portName + ": " + ex;
    }
    return null; // indicates OK return
  }
예제 #28
0
  /**
   * Opens the Operation System Serial Port
   *
   * <p>This method opens the port and set Serial Port parameters according to the DSMR
   * specification. Since the specification is clear about these parameters there are not
   * configurable.
   *
   * <p>If there are problem while opening the port, it is the responsibility of the calling method
   * to handle this situation (and for example close the port again).
   *
   * <p>Opening an already open port is harmless. The method will return immediately
   *
   * @return true if opening was successful (or port was already open), false otherwise
   */
  private boolean open() {
    synchronized (portLock) {
      // Sanity check
      if (portState != PortState.CLOSED) {
        return true;
      }

      try {
        // Opening Operating System Serial Port
        logger.debug("Creating CommPortIdentifier");
        CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(portName);
        logger.debug("Opening CommPortIdentifier");
        CommPort commPort = portIdentifier.open("org.openhab.binding.dsmr", readTimeoutMSec);
        logger.debug("Configure serial port");
        serialPort = (SerialPort) commPort;
        serialPort.enableReceiveThreshold(1);
        serialPort.enableReceiveTimeout(readTimeoutMSec);

        // Configure Serial Port based on specified port speed
        logger.debug("Configure serial port speed " + portSpeed);
        switch (portSpeed) {
          case LOW_SPEED:
            serialPort.setSerialPortParams(
                9600, SerialPort.DATABITS_7, SerialPort.STOPBITS_1, SerialPort.PARITY_EVEN);
            serialPort.setDTR(false);
            serialPort.setRTS(true);

            break;
          case HIGH_SPEED:
            serialPort.setSerialPortParams(
                115200, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);

            break;
          default:
            logger.error("Invalid speed, closing port");

            return false;
        }
      } catch (NoSuchPortException nspe) {
        logger.error("Could not open port: " + portName, nspe);

        return false;
      } catch (PortInUseException piue) {
        logger.error("Port already in use: " + portName, piue);

        return false;
      } catch (UnsupportedCommOperationException ucoe) {
        logger.error("Port is not suitable: " + portName, ucoe);

        return false;
      }

      // SerialPort is ready, open the reader
      logger.info("SerialPort opened successful");
      try {
        bis = new BufferedInputStream(serialPort.getInputStream());
      } catch (IOException ioe) {
        logger.error("Failed to get inputstream for serialPort. Closing port", ioe);

        return false;
      }
      logger.info("DSMR Port opened successful");

      return true;
    }
  }
예제 #29
0
  public String openPort(String portName, String appName) {
    // open the port in XPressNet mode, check ability to set moderators
    try {
      // get and open the primary port
      CommPortIdentifier portID = CommPortIdentifier.getPortIdentifier(portName);
      try {
        activeSerialPort = (SerialPort) portID.open(appName, 2000); // name of program, msec to wait
      } catch (PortInUseException p) {
        return handlePortBusy(p, portName, log);
      }
      // try to set it for XNet
      try {
        setSerialPort();
      } catch (gnu.io.UnsupportedCommOperationException e) {
        log.error("Cannot set serial parameters on port " + portName + ": " + e.getMessage());
        return "Cannot set serial parameters on port " + portName + ": " + e.getMessage();
      }

      // set timeout
      try {
        activeSerialPort.enableReceiveTimeout(10);
        log.debug(
            "Serial timeout was observed as: "
                + activeSerialPort.getReceiveTimeout()
                + " "
                + activeSerialPort.isReceiveTimeoutEnabled());
      } catch (Exception et) {
        log.info("failed to set serial timeout: " + et);
      }

      // get and save stream
      serialStream = activeSerialPort.getInputStream();

      // purge contents, if any
      purgeStream(serialStream);

      // report status?
      if (log.isInfoEnabled()) {
        // report now
        log.info(
            portName
                + " port opened at "
                + activeSerialPort.getBaudRate()
                + " baud with"
                + " DTR: "
                + activeSerialPort.isDTR()
                + " RTS: "
                + activeSerialPort.isRTS()
                + " DSR: "
                + activeSerialPort.isDSR()
                + " CTS: "
                + activeSerialPort.isCTS()
                + "  CD: "
                + activeSerialPort.isCD());
      }
      if (log.isDebugEnabled()) {
        // report additional status
        log.debug(
            " port flow control shows "
                + (activeSerialPort.getFlowControlMode() == SerialPort.FLOWCONTROL_RTSCTS_OUT
                    ? "hardware flow control"
                    : "no flow control"));
      }
      // arrange to notify later
      activeSerialPort.addEventListener(
          new SerialPortEventListener() {
            public void serialEvent(SerialPortEvent e) {
              int type = e.getEventType();
              switch (type) {
                case SerialPortEvent.DATA_AVAILABLE:
                  if (log.isDebugEnabled()) {
                    log.debug("SerialEvent: DATA_AVAILABLE is " + e.getNewValue());
                  }
                  return;
                case SerialPortEvent.OUTPUT_BUFFER_EMPTY:
                  if (log.isDebugEnabled()) {
                    log.debug("SerialEvent: OUTPUT_BUFFER_EMPTY is " + e.getNewValue());
                  }
                  setOutputBufferEmpty(true);
                  return;
                case SerialPortEvent.CTS:
                  if (log.isDebugEnabled()) {
                    log.debug("SerialEvent: CTS is " + e.getNewValue());
                  }
                  return;
                case SerialPortEvent.DSR:
                  if (log.isDebugEnabled()) {
                    log.debug("SerialEvent: DSR is " + e.getNewValue());
                  }
                  return;
                case SerialPortEvent.RI:
                  if (log.isDebugEnabled()) {
                    log.debug("SerialEvent: RI is " + e.getNewValue());
                  }
                  return;
                case SerialPortEvent.CD:
                  if (log.isDebugEnabled()) {
                    log.debug("SerialEvent: CD is " + e.getNewValue());
                  }
                  return;
                case SerialPortEvent.OE:
                  if (log.isDebugEnabled()) {
                    log.debug("SerialEvent: OE (overrun error) is " + e.getNewValue());
                  }
                  return;
                case SerialPortEvent.PE:
                  if (log.isDebugEnabled()) {
                    log.debug("SerialEvent: PE (parity error) is " + e.getNewValue());
                  }
                  return;
                case SerialPortEvent.FE:
                  if (log.isDebugEnabled()) {
                    log.debug("SerialEvent: FE (framing error) is " + e.getNewValue());
                  }
                  return;
                case SerialPortEvent.BI:
                  if (log.isDebugEnabled()) {
                    log.debug("SerialEvent: BI (break interrupt) is " + e.getNewValue());
                  }
                  return;
                default:
                  if (log.isDebugEnabled()) {
                    log.debug(
                        "SerialEvent of unknown type: " + type + " value: " + e.getNewValue());
                  }
                  return;
              }
            }
          });
      try {
        activeSerialPort.notifyOnFramingError(true);
      } catch (Exception e) {
        if (log.isDebugEnabled()) {
          log.debug("Could not notifyOnFramingError: " + e);
        }
      }

      try {
        activeSerialPort.notifyOnBreakInterrupt(true);
      } catch (Exception e) {
        if (log.isDebugEnabled()) {
          log.debug("Could not notifyOnBreakInterrupt: " + e);
        }
      }

      try {
        activeSerialPort.notifyOnParityError(true);
      } catch (Exception e) {
        if (log.isDebugEnabled()) {
          log.debug("Could not notifyOnParityError: " + e);
        }
      }

      try {
        activeSerialPort.notifyOnOutputEmpty(true);
      } catch (Exception e) {
        if (log.isDebugEnabled()) {
          log.debug("Could not notifyOnOutputEmpty: " + e);
        }
      }

      try {
        activeSerialPort.notifyOnOverrunError(true);
      } catch (Exception e) {
        if (log.isDebugEnabled()) {
          log.debug("Could not notifyOnOverrunError: " + e);
        }
      }

      opened = true;

    } catch (gnu.io.NoSuchPortException p) {
      return handlePortNotFound(p, portName, log);
    } catch (IOException ioe) {
      log.error("IOException exception while opening port " + portName + " trace follows: " + ioe);
      ioe.printStackTrace();
      return "IO exception while opening port " + portName + ": " + ioe;
    } catch (java.util.TooManyListenersException tmle) {
      log.error(
          "TooManyListenersException while opening port " + portName + " trace follows: " + tmle);
      tmle.printStackTrace();
      return "Too Many Listeners exception while opening port " + portName + ": " + tmle;
    }

    return null; // normal operation
  }
예제 #30
0
 public SerialConnection(String portName) throws NoSuchPortException, PortInUseException {
   mCommPortIdentifier = CommPortIdentifier.getPortIdentifier(portName);
   mSerialPort = (SerialPort) mCommPortIdentifier.open(mFileDescriptor, 2000);
 }