public SerialConnection(String comPort, int bitRate, ValerieNetwork network) {
    serialPort = new SerialPort(comPort);

    try {
      serialPort.openPort(); // Open port
      if (serialPort.setParams(bitRate, 8, 1, 0)) // Set params
      {
        int mask =
            SerialPort.MASK_RXCHAR + SerialPort.MASK_CTS + SerialPort.MASK_DSR; // Prepare mask
        serialPort.setEventsMask(mask); // Set mask
        serialPort.addEventListener(
            new SerialListener(serialPort, network)); // Add SerialPortEventListener
      } else if (DEBUG_MSGS) {
        System.out.println("Invalid Serial Port parameters");
      }
    } catch (SerialPortException ex) {
      if (DEBUG_MSGS) {
        System.err.println("Error opening serial port.");
        ex.printStackTrace();
      }
      silentClose();
      System.exit(1);
    }

    Runtime.getRuntime()
        .addShutdownHook(
            new Thread() {
              public void run() {
                silentClose();
              }
            });
  }
Exemplo n.º 2
0
 public boolean getDSR() {
   try {
     return port.isDSR();
   } catch (SerialPortException e) {
     throw new RuntimeException("Error reading the DSR line: " + e.getExceptionType());
   }
 }
Exemplo n.º 3
0
  protected void onSerialPortEvent(SerialPortEvent event) {

    if (event.isRXCHAR()) {

      int count = event.getEventValue();

      if (count == 0) return;

      byte[] characters;
      try {

        characters = serialPort.readBytes(count);

        for (byte character : characters) {
          // System.out.println(Integer.toHexString(character) + "\t:\t" + (int) character + "\t:\t"
          // + (char) character);
          onReceiveChar((char) character);
        }

      } catch (SerialPortException e) {
        showErrorMessage("No se pudo leer un byte");
        e.printStackTrace();
      }
    }
  }
Exemplo n.º 4
0
  public void startReadPort(final DataReceivedListener dataReceivedListener)
      throws SerialPortException {
    try {
      serialPort = new SerialPort(configuration.getPort());
      serialPort.openPort();
      serialPort.setParams(
          configuration.getBaudRate(),
          configuration.getDataBits(),
          configuration.getStopBits(),
          configuration.getParity());

      serialPort.addEventListener(
          new SerialPortEventListener() {
            @Override
            public void serialEvent(SerialPortEvent serialPortEvent) {
              try {
                if (serialPortEvent.isRXCHAR()) {
                  dataReceivedListener.onDataReceived(serialPort.readString());
                }
              } catch (SerialPortException e) {
                e.printStackTrace();
              }
            }
          });
    } catch (SerialPortException e) {
      e
          .printStackTrace(); // To change body of catch statement use File | Settings | File
                              // Templates.
    }
  }
Exemplo n.º 5
0
 /** Set the RTS line */
 public void setRTS(boolean state) {
   try {
     port.setRTS(state);
   } catch (SerialPortException e) {
     throw new RuntimeException("Error setting the RTS line: " + e.getExceptionType());
   }
 }
Exemplo n.º 6
0
  public void transmitMessage(String message) {

    if (serialPort == null) {
      showErrorMessage("Por favor seleccione un puerto");
      return;
    }

    if (message.isEmpty()) {
      showErrorMessage("No se envian mensajes vacios");
      return;
    }

    String text = message + '\n';

    showSentMessage(text);

    try {
      serialPort.writeBytes(text.getBytes());

    } catch (SerialPortException e) {
      showErrorMessage(e.getMessage());
      e.printStackTrace();
    }

    textField.setText("");
  }
  public void run() {
    System.out.println("Thread started - 1");

    try {
      if (in == null) return;
      byte[] buffer = in.readBytes(1024);
      System.out.print(new String(buffer, 0, 1024));

    } catch (SerialPortException e) {
      e.printStackTrace();
    } // Read 10 bytes from serial port

    /*
    byte[] buffer = new byte[1024];
    int len = -1;
    try
    {
        while ( ( len = this.in.read(buffer)) > -1 )
        {
            System.out.print(new String(buffer,0,len));
        }
    }
    catch ( IOException e )
    {
        e.printStackTrace();
    }
    */
  }
Exemplo n.º 8
0
 /**
  * @generate Serial_write.xml
  *     <h3>Advanced</h3>
  *     Write a String to the output. Note that this doesn't account for Unicode (two bytes per
  *     char), nor will it send UTF8 characters.. It assumes that you mean to send a byte buffer
  *     (most often the case for networking and serial i/o) and will only use the bottom 8 bits of
  *     each char in the string. (Meaning that internally it uses String.getBytes)
  *     <p>If you want to move Unicode data, you can first convert the String to a byte stream in
  *     the representation of your choice (i.e. UTF8 or two-byte Unicode data), and send it as a
  *     byte array.
  * @webref serial:serial
  * @usage web_application
  * @param src data to write
  */
 public void write(String src) {
   try {
     port.writeString(src);
   } catch (SerialPortException e) {
     throw new RuntimeException(
         "Error writing to serial port " + e.getPortName() + ": " + e.getExceptionType());
   }
 }
 private void silentClose() {
   try {
     serialPort.closePort();
   } catch (SerialPortException ex) {
     if (DEBUG_MSGS) {
       ex.printStackTrace();
     }
   }
 }
Exemplo n.º 10
0
 public void openAndSetSerialPort(String port) {
   serialPort = new SerialPort(port);
   try {
     System.out.println("Port opened: " + serialPort.openPort());
     System.out.println("Params setted: " + serialPort.setParams(230400, 64, 1, 0));
   } catch (SerialPortException e) {
     e.printStackTrace();
   }
 }
Exemplo n.º 11
0
 private static void startCommunicator() {
   Globals.setCommunicator(CommunicatorFactory.getCommunicator());
   communicator = Globals.getCommunicator();
   try {
     System.out.println("Spectrometer info: " + communicator.getSpecInfo());
   } catch (SerialPortException e) {
     e.printStackTrace();
   }
 }
Exemplo n.º 12
0
 /** Set the DTR line */
 public void setDTR(boolean state) {
   // there is no way to influence the behavior of the DTR line when opening the serial port
   // this means that at least on Linux and OS X, Arduino devices are always reset
   try {
     port.setDTR(state);
   } catch (SerialPortException e) {
     throw new RuntimeException("Error setting the DTR line: " + e.getExceptionType());
   }
 }
Exemplo n.º 13
0
 public void restart() {
   try {
     serialPort.closePort();
     serialPort.openPort();
     serialPort.setParams(9600, 64, 1, 0);
   } catch (SerialPortException e) {
     e.printStackTrace();
   }
 }
Exemplo n.º 14
0
 /** @param src data to write */
 public void write(byte[] src) {
   try {
     // this might block if the serial device is not yet ready (esp. tty devices under OS X)
     port.writeBytes(src);
     // we used to call flush() here
   } catch (SerialPortException e) {
     throw new RuntimeException(
         "Error writing to serial port " + e.getPortName() + ": " + e.getExceptionType());
   }
 }
Exemplo n.º 15
0
  public void onSerialPortClicked(String portName) {

    closePort();
    try {

      openPort(portName);

    } catch (SerialPortException e) {
      e.printStackTrace();
      showErrorMessage(e.getMessage());
    }
  }
Exemplo n.º 16
0
 @Override
 public void close() {
   try {
     this.serialPort.closePort();
     _logger.debug("serialPort{} closed", serialPort.getPortName());
   } catch (SerialPortException ex) {
     if (ex.getMessage().contains("Port not opened")) {
       _logger.debug("unable to close the port, Error: {}", ex.getMessage());
     } else {
       _logger.error("unable to close the port{}", serialPort.getPortName(), ex);
     }
   }
 }
Exemplo n.º 17
0
  public void closePort() {

    if (serialPort != null) {

      try {

        serialPort.closePort();

      } catch (SerialPortException e) {
        e.printStackTrace();
      }
    }
  }
Exemplo n.º 18
0
 /**
  * @generate serialEvent.xml
  * @webref serial:events
  * @usage web_application
  * @param event the port where new data is available
  */
 public void serialEvent(SerialPortEvent event) {
   if (event.getEventType() == SerialPortEvent.RXCHAR) {
     int toRead;
     try {
       while (0 < (toRead = port.getInputBufferBytesCount())) {
         // this method can be called from the context of another thread
         synchronized (buffer) {
           // read one byte at a time if the sketch is using serialEvent
           if (serialEventMethod != null) {
             toRead = 1;
           }
           // enlarge buffer if necessary
           if (buffer.length < inBuffer + toRead) {
             byte temp[] = new byte[buffer.length << 1];
             System.arraycopy(buffer, 0, temp, 0, inBuffer);
             buffer = temp;
           }
           // read an array of bytes and copy it into our buffer
           byte[] read = port.readBytes(toRead);
           System.arraycopy(read, 0, buffer, inBuffer, read.length);
           inBuffer += read.length;
         }
         if (serialEventMethod != null) {
           if ((0 < bufferUntilSize && bufferUntilSize <= inBuffer - readOffset)
               || (0 == bufferUntilSize && bufferUntilByte == buffer[inBuffer - 1])) {
             try {
               // serialEvent() is invoked in the context of the current (serial) thread
               // which means that serialization and atomic variables need to be used to
               // guarantee reliable operation (and better not draw() etc..)
               // serialAvailable() does not provide any real benefits over using
               // available() and read() inside draw - but this function has no
               // thread-safety issues since it's being invoked during pre in the context
               // of the Processing applet
               serialEventMethod.invoke(parent, this);
             } catch (Exception e) {
               System.err.println("Error, disabling serialEvent() for " + port.getPortName());
               System.err.println(e.getLocalizedMessage());
               serialEventMethod = null;
             }
           }
         }
         invokeSerialAvailable = true;
       }
     } catch (SerialPortException e) {
       throw new RuntimeException(
           "Error reading from serial port " + e.getPortName() + ": " + e.getExceptionType());
     }
   }
 }
Exemplo n.º 19
0
  private Serial(String iname, int irate, char iparity, int idatabits, float istopbits)
      throws SerialException {
    // if (port != null) port.close();
    // this.parent = parent;
    // parent.attach(this);

    int parity = SerialPort.PARITY_NONE;
    if (iparity == 'E') parity = SerialPort.PARITY_EVEN;
    if (iparity == 'O') parity = SerialPort.PARITY_ODD;

    int stopbits = SerialPort.STOPBITS_1;
    if (istopbits == 1.5f) stopbits = SerialPort.STOPBITS_1_5;
    if (istopbits == 2) stopbits = SerialPort.STOPBITS_2;

    try {
      port = new SerialPort(iname);
      port.openPort();
      boolean res = port.setParams(irate, idatabits, stopbits, parity, true, true);
      if (!res) {
        System.err.println(
            format(
                tr("Error while setting serial port parameters: {0} {1} {2} {3}"),
                irate,
                iparity,
                idatabits,
                istopbits));
      }
      port.addEventListener(this);
    } catch (SerialPortException e) {
      if (e.getPortName().startsWith("/dev")
          && SerialPortException.TYPE_PERMISSION_DENIED.equals(e.getExceptionType())) {
        throw new SerialException(
            format(
                tr(
                    "Error opening serial port ''{0}''. Try consulting the documentation at http://playground.arduino.cc/Linux/All#Permission"),
                iname));
      }
      throw new SerialException(format(tr("Error opening serial port ''{0}''."), iname), e);
    }

    if (port == null) {
      throw new SerialNotFoundException(
          format(
              tr(
                  "Serial port ''{0}'' not found. Did you select the right one from the Tools > Serial Port menu?"),
              iname));
    }
  }
  public boolean writeBytes(byte[] bytes) {
    try {
      if (DEBUG_SERIAL) {
        System.out.println(
            "Network Sending: "
                + ByteArrayHelpers.getByteArrayString(bytes, ByteArrayMode.BYTE_ARRAY_MODE_HEX));
      }

      return serialPort.writeBytes(bytes);
    } catch (SerialPortException e) {
      if (DEBUG_MSGS) {
        e.printStackTrace();
      }
      return false;
    }
  }
Exemplo n.º 21
0
  /**
   * @param parity 'N' for none, 'E' for even, 'O' for odd, 'M' for mark, 'S' for space ('N' is the
   *     default)
   * @param dataBits 8 is the default
   * @param stopBits 1.0, 1.5, or 2.0 (1.0 is the default)
   */
  public Serial(
      PApplet parent, String portName, int baudRate, char parity, int dataBits, float stopBits) {
    this.parent = parent;
    parent.registerMethod("dispose", this);
    parent.registerMethod("pre", this);

    // setup parity
    if (parity == 'O') {
      parity = SerialPort.PARITY_ODD;
    } else if (parity == 'E') {
      parity = SerialPort.PARITY_EVEN;
    } else if (parity == 'M') {
      parity = SerialPort.PARITY_MARK;
    } else if (parity == 'S') {
      parity = SerialPort.PARITY_SPACE;
    } else {
      parity = SerialPort.PARITY_NONE;
    }

    // setup stop bits
    int stopBitsIdx = SerialPort.STOPBITS_1;
    if (stopBits == 1.5f) {
      stopBitsIdx = SerialPort.STOPBITS_1_5;
    } else if (stopBits == 2) {
      stopBitsIdx = SerialPort.STOPBITS_2;
    }

    port = new SerialPort(portName);
    try {
      // the native open() call is not using O_NONBLOCK, so this might block for certain operations
      // (see write())
      port.openPort();
      port.setParams(baudRate, dataBits, stopBitsIdx, parity);
      // we could register more events here
      port.addEventListener(this, SerialPort.MASK_RXCHAR);
    } catch (SerialPortException e) {
      // this used to be a RuntimeException before, so stick with it
      throw new RuntimeException(
          "Error opening serial port " + e.getPortName() + ": " + e.getExceptionType());
    }

    serialEventMethod = findCallback("serialEvent");
    serialAvailableMethod = findCallback("serialAvailable");
  }
  public void sendToSerial(String message) {
    try {
      // pad message to 32 chars if it isn't already
      StringUtils.rightPad(message, 32);

      App.getController().appendTxtAreaLogOutput("Port opened: " + port.openPort());
      App.getController()
          .appendTxtAreaLogOutput(
              "Params set: " + port.setParams(baudRate, dataBits, stopBits, parity));
      App.getController()
          .appendTxtAreaLogOutput(
              "\""
                  + message
                  + "\" successfully wrote to port: "
                  + port.writeBytes(message.getBytes()));
      App.getController().appendTxtAreaLogOutput("Port closed: " + port.closePort());
    } catch (SerialPortException ex) {
      App.getController().appendTxtAreaLogOutput(ex.getMessage());
    }
  }
Exemplo n.º 23
0
 public String[] readFromSerialPortGyro() {
   byte[] data = new byte[0];
   String parsedData = null;
   try {
     data = serialPort.readBytes(64);
   } catch (SerialPortException e) {
     e.printStackTrace();
   }
   String output = new String(data, StandardCharsets.UTF_8);
   int start = output.indexOf("s");
   int finish = output.indexOf("f");
   if (start < finish) {
     parsedData = output.substring(start, finish);
   } else {
     parsedData = output.substring(start) + output.substring(0, finish);
   }
   parsedData = parsedData.substring(1);
   // System.out.println("parsed: "+parsedData);
   String[] vals = parsedData.split(" ");
   return vals;
 }
  /** @inheritDoc */
  private synchronized boolean connect(String portName, int speed) throws Exception {

    try {
      serialPort = new SerialPort(portName);
      if (!serialPort.openPort()) {
        LOG.error("Error: Port is currently in use:" + portName);
        disconnect();
        return false;
      } else {

        serialPort.setParams(
            speed, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
        serialPort.setFlowControlMode(SerialPort.FLOWCONTROL_NONE);

        try {
          serialReader = new SerialReader(this);
          serialPort.addEventListener(serialReader);
          LOG.debug("Added SerialPort event listener");
        } catch (SerialPortException e) {
          disconnect();
          throw new Exception(
              "Error Too Many Listeners Exception on  serial port:" + e.getMessage());
        }

        LOG.info("Connection on " + portName + " established");

        setConnected(true);

        return true;
      }

    } catch (SerialPortException e) {
      disconnect();
      LOG.error("the connection could not be made: " + portName);
      return false;
    }
  }
Exemplo n.º 25
0
  private void initialize() {
    String[] portNames = SerialPortList.getPortNames();
    _logger.debug("Number of serial port available:{}", portNames.length);
    for (int portNo = 0; portNo < portNames.length; portNo++) {
      _logger.debug("SerialPortJson[{}]:{}", portNo + 1, portNames[portNo]);
    }

    // create an instance of the serial communications class
    serialPort = new SerialPort(gateway.getPortName());
    try {
      serialPort.openPort(); // Open port
      serialPort.setParams(
          gateway.getBaudRate(),
          SerialPort.STOPBITS_1,
          SerialPort.PARITY_NONE,
          SerialPort.DATABITS_8);
      int mask =
          SerialPort.MASK_RXCHAR
              + SerialPort.MASK_CTS
              + SerialPort.MASK_DSR
              + SerialPort.MASK_ERR; // Prepare mask
      serialPort.setEventsMask(mask); // Set mask
      // create and register the serial data listener
      serialPort.addEventListener(
          new SerialDataListenerJssc(serialPort, gateway)); // Add SerialPortEventListener
      _logger.debug("Serial port gateway initialized, GatewayTable[{}]", gateway);
      gateway.setStatus(STATE.UP, "Connected Successfully");
    } catch (SerialPortException ex) {
      gateway.setStatus(STATE.DOWN, "ERROR: " + ex.getMessage());
      if (ex.getMessage().contains("Port not found")) {
        _logger.error("Failed to load serial port: {}", ex.getMessage());
      } else {
        _logger.error("Failed to load serial port, ", ex);
      }
    }
  }
Exemplo n.º 26
0
  @Override
  public synchronized void serialEvent(SerialPortEvent event) {

    if (log.isTraceEnabled()) {
      log.trace("SerialEvent '" + event.getEventType() + "' on [" + event.getPortName() + "]");
    }

    if (event.isRXCHAR() && hasListeners()) { // If data is available
      byte[] data;
      try {
        data = serialPort.readBytes(event.getEventValue());
        getStreamReader().processPacketRead(data, data.length);
      } catch (SerialPortException e) {
        log.error(e.getMessage(), e);
        throw new RuntimeException(e);
      }

    } else if (event.isCTS()) { // If CTS line has changed state
      if (event.getEventValue() == 1) { // If line is ON
        log.debug("SerialEvent - CTS = ON");
      } else {
        log.debug("SerialEvent - CTS = OFF");
      }
    } else if (event.isBREAK()) { // /If DSR line has changed state
      log.debug("SerialEvent - isBREAK");
    } else if (event.isERR()) { // /If DSR line has changed state
      log.debug("SerialEvent - isERR");
      try {
        disconnect();
      } catch (ConnectionException ex) {
        log.error(ex.getMessage(), ex);
      }
    } else if (event.isRING()) { // /If DSR line has changed state
      log.debug("SerialEvent - isRING");
    }
  }
  @Override
  public void serialEvent(SerialPortEvent serialPortEvent) {
    int val = serialPortEvent.getEventValue();
    if (serialPortEvent.isRXCHAR() && val > 0) {
      if (SerialConnection.DEBUG_SERIAL) {
        System.out.println("Received " + val + " bytes");
      }
      try {

        byte[] preambleData = new byte[0];
        byte[] payloadData = new byte[0];

        preambleData = mPort.readBytes(PREAMBLE_SIZE, 500);

        if (SerialConnection.DEBUG_SERIAL) {
          System.out.println(
              "Preamble: "
                  + ByteArrayHelpers.getByteArrayString(preambleData)
                  + "("
                  + new String(preambleData)
                  + ")");
        }

        if (preambleData.length == PREAMBLE_SIZE) {
          dataSize = preambleData[2];
          if (dataSize > 0) {
            payloadData = mPort.readBytes(dataSize, 500);

            if (SerialConnection.DEBUG_SERIAL) {
              System.out.println(
                  "Data: "
                      + ByteArrayHelpers.getByteArrayString(payloadData)
                      + "("
                      + new String(payloadData)
                      + ")");
            }

            networkDelegate.handlePacket(ByteArrayHelpers.concat(preambleData, payloadData));

          } else if (0 == dataSize) {
            networkDelegate.handlePacket(preambleData);
          }
        } else {
          if (SerialConnection.DEBUG_MSGS) {
            System.out.println(
                "preamble data length: "
                    + preambleData.length
                    + " does not match correct size: "
                    + PREAMBLE_SIZE);
          }
        }

        //				switch (state) {
        //				case PREAMBLE:
        //					preambleData = mPort.readBytes(PREAMBLE_SIZE);
        //
        //					if (SerialConnection.DEBUG_SERIAL) {
        //						System.out.println("Preamble: " + ByteArrayHelpers.getByteArrayString(preambleData)
        // + "(" + new String(payloadData) + ")");
        //					}
        //
        //					if (preambleData.length == PREAMBLE_SIZE)
        //					{
        //						dataSize = preambleData[PREAMBLE_SIZE - 1];
        //						if (dataSize > 0)
        //						{
        //							state = ListenerState.DATA;
        //							payloadData = mPort.readBytes(dataSize, 50);
        //
        //							if (SerialConnection.DEBUG_SERIAL) {
        //								System.out.println("Data: " + ByteArrayHelpers.getByteArrayString(payloadData) +
        // "(" + new String(payloadData) + ")");
        //							}
        //							state = ListenerState.PREAMBLE;
        //
        //						} else if (0 == dataSize)
        //						{
        //							networkDelegate.handlePacket(preambleData);
        //						}
        //					} else
        //					{
        //						if (SerialConnection.DEBUG_MSGS)
        //						{
        //							System.out.println("preamble data length: " + preambleData.length + " does not
        // match correct size: " + PREAMBLE_SIZE);
        //						}
        //					}
        //					break;
        //
        //				case DATA:
        //					payloadData = mPort.readBytes(dataSize);
        //
        //					if (SerialConnection.DEBUG_SERIAL) {
        //						System.out.println("Data: " + ByteArrayHelpers.getByteArrayString(payloadData));
        //					}
        //
        //					if (dataSize == payloadData.length)
        //					{
        //						byte[] concatData = ByteArrayHelpers.concat(preambleData, payloadData);
        //						networkDelegate.handlePacket(concatData);
        //					}
        //					state = ListenerState.PREAMBLE;
        //					break;
        //
        //				default:
        //					break;
        //				}

      } catch (SerialPortException e) {
        if (SerialConnection.DEBUG_MSGS) {
          e.printStackTrace();
        }

      } catch (SerialPortTimeoutException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }
  }
Exemplo n.º 28
0
  /**
   * Connects to a known port. Delays for 2s because experience shows that receiving of data only
   * works after a certain time.
   *
   * @param baudRate Value from jssc.SerialPort.BAUDRATE_*
   * @throws DisplayException
   * @throws SerialPortException
   * @throws InterruptedException
   * @throws IOException
   * @throws SecurityException
   */
  public SerialTransport(int baudRate)
      throws DisplayException, SerialPortException, InterruptedException, SecurityException,
          IOException {
    // -------- Initialize Logger --------
    logger = Logger.getLogger("com.activeantiglare.arduino.sp");
    FileHandler fh = new FileHandler("SerialTransport.log");
    fh.setFormatter(new CmdFormatter());

    logger.addHandler(fh);
    logger.setLevel(Level.ALL);

    logger.info("SerialTransport constructor start");

    // -------- Find port --------
    String[] portNames = SerialPortList.getPortNames();
    for (int i = 0; i < portNames.length; i++) {
      String currentName = portNames[i];
      for (int j = 0; j < PORT_NAMES.length; j++) {
        if (currentName.equals(PORT_NAMES[j])) {
          portName = currentName;
          break;
        }
      }
      if (portName != null) {
        break;
      }
    }

    if (portName == null) {
      String msg = "ERROR: No known serial port found";
      logger.log(Level.SEVERE, msg);
      throw new DisplayException(msg);
    } else {
      String msg = "Connecting to port " + portName;
      logger.log(Level.INFO, msg);
      System.out.println(msg);
    }

    // -------- Initialize Port --------
    serialPort = new SerialPort(portName);
    try {
      serialPort.openPort(); // Open serial port
      serialPort.setParams(
          baudRate, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);

      int mask = SerialPort.MASK_RXCHAR + SerialPort.MASK_CTS + SerialPort.MASK_DSR; // Prepare mask
      serialPort.setEventsMask(mask); // Set mask
      serialPort.addEventListener(new SerialPortReader()); // Add
      // SerialPortEventListener
    } catch (SerialPortException e) {
      logger.log(Level.SEVERE, "", e);
      e.printStackTrace(System.out);
      throw e;
    }

    // No one knows why, but receiving only works reliably after some time
    try {
      Thread.sleep(3000);
    } catch (InterruptedException e) {
      throw e;
    }

    logger.info("SerialTransport constructor end");
  }
Exemplo n.º 29
0
    @Override
    public void actionPerformed(ActionEvent e) {

      if (comunication.isConnected()) {

        try {
          comunication.close();
        } catch (IOException e1) {
          view.popupErrorMessage(e1.getMessage());
          e1.printStackTrace();
        }

      } else {

        Serial.DATA_RATE[] arrDataRate = Serial.DATA_RATE.values();
        try {
          serial.setDataRate(arrDataRate[view.getItemDataRate()]);
        } catch (SerialPortException e1) {
          view.popupErrorMessage(e1.getMessage());
          e1.printStackTrace();
        }
        try {
          refreshNameSerialPort();
          String namePort = view.getNameSerialPortSelected();
          comunication.open(namePort);
        } catch (SerialPortException e1) {
          if (e1.getExceptionType().equals(SerialPortException.TYPE_NULL_NOT_PERMITTED)) {
            view.popupErrorMessage("Porta seriale non selezionata");
          } else if (e1.getExceptionType().equals(SerialPortException.TYPE_PORT_NOT_FOUND)) {
            view.popupErrorMessage("Porta seriale " + e1.getPortName() + " non trovata");
          } else if (e1.getExceptionType().equals(SerialPortException.TYPE_PORT_ALREADY_OPENED)) {
            view.popupErrorMessage("Porta seriale " + e1.getPortName() + " � gi� in uso.");
          } else {
            view.popupErrorMessage(e1.getMessage());
            e1.printStackTrace();
          }
        }
      }
    }