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.
    }
  }
Exemple #2
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();
    }
    */
  }
  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();
              }
            });
  }
Exemple #5
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();
      }
    }
  }
 private void silentClose() {
   try {
     serialPort.closePort();
   } catch (SerialPortException ex) {
     if (DEBUG_MSGS) {
       ex.printStackTrace();
     }
   }
 }
Exemple #7
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();
   }
 }
 public void restart() {
   try {
     serialPort.closePort();
     serialPort.openPort();
     serialPort.setParams(9600, 64, 1, 0);
   } catch (SerialPortException e) {
     e.printStackTrace();
   }
 }
 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();
   }
 }
Exemple #10
0
  public void onSerialPortClicked(String portName) {

    closePort();
    try {

      openPort(portName);

    } catch (SerialPortException e) {
      e.printStackTrace();
      showErrorMessage(e.getMessage());
    }
  }
Exemple #11
0
  public void closePort() {

    if (serialPort != null) {

      try {

        serialPort.closePort();

      } catch (SerialPortException e) {
        e.printStackTrace();
      }
    }
  }
    @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();
          }
        }
      }
    }
  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;
    }
  }
 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;
 }
Exemple #15
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");
  }
  @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();
      }
    }
  }