Harikrishnan
Harikrishnan

Reputation: 3802

Java Comm API Issue

I successfully installed and tested the Java Comm API. I could send and receive data through serial port. But the problem is, there are 19 spaces extra before each character. When I tried using hyper terminal, the extra spaces was not there.

Eg:

+CENG:0,"0021,37,99,404,46,36,0000,05,05,77,255"

is expected. But Java program outputs it with spaces before each charector

             +            E            N

The code is:

import java.io.*;
import java.util.*;
import javax.comm.*;

public class SimpleRead implements Runnable, SerialPortEventListener
{
    static CommPortIdentifier portId;
    static Enumeration portList;

    InputStream inputStream;
    SerialPort serialPort;
    Thread readThread;

    public static void main(String[] args) throws Exception
    {
        portList = CommPortIdentifier.getPortIdentifiers();
        System.out.println("SimpleRead Started.");
        while (portList.hasMoreElements())
            {
                portId = (CommPortIdentifier) portList.nextElement();
                if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL)
                    {
                        System.out.println ("Found " + portId.getName());
                        if (portId.getName().equals("COM5"))
                            {
                                OutputStream outputStream;
                                SerialPort writePort = (SerialPort) portId.open("SimpleWriteApp", 2000);
                                writePort.setSerialPortParams(2400,
                                                              SerialPort.DATABITS_8,
                                                              SerialPort.STOPBITS_1,
                                                              SerialPort.PARITY_NONE);
                                outputStream = writePort.getOutputStream();
                                outputStream.write("AT+CENG=2".getBytes());
                                writePort.close();
                                SimpleRead reader = new SimpleRead();
                            }
                    }
            }
    }

    public SimpleRead()
    {
        try
            {
                serialPort = (SerialPort) portId.open("SimpleReadApp", 2000);
            }
        catch (PortInUseException e)
            {
                e.printStackTrace();
            }
        try
            {
                inputStream = serialPort.getInputStream();
            }
        catch (IOException e)
            {
                e.printStackTrace();
            }
        try
            {
                serialPort.addEventListener(this);
            }
        catch (TooManyListenersException e)
            {
                e.printStackTrace();
            }
        serialPort.notifyOnDataAvailable(true);
        try
            {
                serialPort.setSerialPortParams(2400, SerialPort.DATABITS_8,
                                               SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
            }
        catch (UnsupportedCommOperationException e)
            {
                e.printStackTrace();
            }
        readThread = new Thread(this);
        readThread.start();
    }

    public void run()
    {
        try
            {
                Thread.sleep(20000);
            }
        catch (InterruptedException e)
            {
                e.printStackTrace();
            }
    }

    public void serialEvent(SerialPortEvent event)
    {
        switch (event.getEventType())
            {
            case SerialPortEvent.BI:
            case SerialPortEvent.OE:
            case SerialPortEvent.FE:
            case SerialPortEvent.PE:
            case SerialPortEvent.CD:
            case SerialPortEvent.CTS:
            case SerialPortEvent.DSR:
            case SerialPortEvent.RI:
            case SerialPortEvent.OUTPUT_BUFFER_EMPTY:
                break;
            case SerialPortEvent.DATA_AVAILABLE:
                byte[] readBuffer = new byte[20];

                try
                    {
                        while (inputStream.available() > 0)
                            {
                                int numBytes = inputStream.read(readBuffer);
                            }
                        System.out.print(new String(readBuffer));
                    }
                catch (IOException e)
                    {
                        e.printStackTrace();
                    }
                break;
            }
    }
}

Upvotes: 1

Views: 804

Answers (1)

Jason C
Jason C

Reputation: 40335

In your code you have (exception handling removed for purpose of example):

byte[] readBuffer = new byte[20];

while (inputStream.available() > 0)
{
    int numBytes = inputStream.read(readBuffer);
}

System.out.print(new String(readBuffer));

You have a 20-byte buffer and you are constructing a String from all 20 bytes no matter how much data you read. In Java, a String can contain nulls, and so your string ends up being a character followed by 19 nulls. Then when you print it your particular console displays spaces instead of nulls.

Couple of things to note. First, it's not really clear what you are trying to do with this loop. You repeatedly read into the same 20 byte buffer no matter how many bytes are left on the stream (e.g. if there are 400 bytes to read, at most readBuffer ends up with the last 20).

Second, to solve the string problem I just described, you want to only use the bytes you actually read from readBuffer, i.e. the first numBytes bytes of the buffer.

Third, you should always specify a character encoding when constructing a String from raw bytes. For your data, it seems us-ascii is appropriate.

So something like this, for example:

byte[] readBuffer = new byte[20];

while (inputStream.available() > 0) {
    int numBytes = inputStream.read(readBuffer);
    System.out.print(new String(readBuffer, 0, numBytes, "us-ascii"));
}

Upvotes: 1

Related Questions