Search code examples
javajava-meserial-portmidpat-command

serial communication using CommConnection on mobile device


I have two issues with a serial program on mobile device:

  1. InputStream.available() always returns 0 according to documentation. Can't use DataInputStream because the data might be a file and not a string. If I simply call the read() on the InputStream it'll block the IO operation if the byte(s) doesn't exist on the other side. In addition, I don't know how much is the size of input data. So how do I find if data is available at port and how much is the size of available data?
  2. I'm using hyperterminal to test the serial port and mobile is only responding to AT commands, like ata and atd. So any string like "hello" is ignored and my app can't see it. so is this true? or I'm missing something? how can I make the data visible to my app?

well any suggestion? code snippets maybe?


Solution

  • You can add a Listener to a SerialPort that gets notified whenever data is available on that port. Inside this callback, in.available() should also return the number of bytes that can be read, but it is probably better to just consume bytes until read return -1.

    final CommPortIdentifier portId = CommPortIdentifier.getPortIdentifier("COM1");
    
    final SerialPort com1 = (SerialPort)portId.open("Test", 1000);
    final InputStream in = com1.getInputStream();
    
    com1.notifyOnDataAvailable(true);
    com1.setSerialPortParams(9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
    com1.addEventListener(new SerialPortEventListener() {
        public void serialEvent(SerialPortEvent event) {
            if (event.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
                try {
                    byte[] buffer = new byte[4096];
                    int len;
                    while (-1 != (len = in.read(buffer))) {
                        // do something with buffer[0..len]
                    }
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
        }
    });