Serial communication using commConneciton API in j

2019-07-27 07:09发布

问题:

I have develop one j2me application for Centrino chip. That chip connected to one EZ power meter. I want to read data from EZ meter over serial communication RS-232 using Modbus protocol.

I have some code for send Modbus request for read Holding Register.

 //declare variable here
 CommConnection  commConn;
 InputStream     inStream;
 OutputStream    outStream;

// here open com port using commconnection

String strCOM = "comm:COM1;baudrate=9600;bitsperchar=8;stopbits=1;parity=even;blocking=on;autocts=off;autorts=off";
commConn = (CommConnection)Connector.open(strCOM);
inStream  = commConn.openInputStream();
outStream = commConn.openOutputStream();

// here create modbus protocol request. I want read holding register address 1000 it's hava 2 register.

    byte[] buffer = new byte[100];

    byte[] frame1 = new byte[] {(byte) 0x01, (byte) 0x03, (byte) 0x03, (byte) 0xE8, (byte) 0x00, (byte) 0x02, (byte) 0x34, (byte) 0xBA};
    outStream.write(frame1,0,frame1.length);//write(frame1);
    outStream.flush();
    int available1 = inStream.available();
    System.out.println("inStream Available : "+inStream.available());
    readBytes = inStream.read(buffer,0,available1);

    System.out.println("Read Integer : "+readBytes +" and Bytes size : "+buffer.length);

I always got response 0 bytes read. I don't know what is wrong. Please guide me if I write wrong code.

Thanks in advance.

回答1:

available() often returns 0 (for many types of streams) and so it is not very useful. Try just inStream.read(buffer).