title: How receive JSON object using serial event listener?
body: <p>I'm sending a JSON object from an Arduino board to a java application on my PC via the USB serial connection.  The java application receives "chunks" from the serial port in a serial event listener.</p>
  
  <p>This is the body of the listener:</p>
  
  <pre><code>public synchronized void serialEvent(SerialPortEvent oEvent) {
      if (oEvent.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
          try {
              int available = input.available();
              byte chunk[] = new byte[available];
              input.read(chunk, 0, available);
  
              // buffering of bytes must happen here to 
              // ultimately de-serialize into JSON object
          } catch (Exception e) {
              System.err.println(e.toString());
          }
      }
  }
  </code></pre>
  
  <p>The problem I have is that it's not clear when the end of the JSON object has been received.   From what I've researched, there needs to be some sort of event that causes the attempt to read from serial port to return a -1.  The problem is that with this model, I only ever enter the listener when there's data available to be read.  </p>
  
  <p>I added some code to check the return value of the call to input.read and it seems to return the same value as the number of bytes available and I've also tested for other events and none other appear to happen.</p>
  
  <p>Unless there's an easy way to modify this to detect the end of a serial transmission, I'm thinking this model of serial input isn't going to work for receiving something like a JSON object.  </p>
  
  <p>Should I move to a design that creates a separate thread with a blocking "readline" call to the serial port?</p>
  
  <p>I'm stumped.</p>