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.
This is the body of the listener:
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());
}
}
}
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.
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.
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.
Should I move to a design that creates a separate thread with a blocking “readline” call to the serial port?
I’m stumped.
Since whitespace is allowed in JSON (see json.org), you can put a newline character after the very last character of the JSON string. Make sure you don’t use a newline character anywhere else in the JSON string. Once you encounter the newline character, that’s your signal that you received the entire string.
I’ve done this before with serial streaming JSON. In my situation, there’s a device continuously streaming a JSON string. Data values vary within the JSON string (it’s environmental data like temperature and humidity). So I find the start of the string by looking for an identifier (in my case, it’s
{"environment data":and I find the end by looking for a newline character (which is used nowhere else in the string).