user2108656
user2108656

Reputation: 1

Passing bytes array from servlet listener to controller

I've a servlet context listener, where there is a serial port listener. In this listener I save the bytes from the serial port in this way:

public void contextInitialized(ServletContextEvent contextEvent){
  context = contextEvent.getServletContext();
  serial =  SerialFactory.createInstance();
  serial.open(Serial.DEFAULT_COM_PORT, 19200);
  serial.addListener(new SerialDataListener(){
    @Override
    public void dataReceived(SerialDataEvent arg0) {    
    private byte[] serialDataByte;
    serialDataByte = arg0.getData().getBytes();
    context.setAttribute("serialData", serialDataByte);
    seriale.write(serialDataByte); //the echo on serial port show me the right bytes                                
    }           
  });
}

on my controller I access to the serial port data by:

private byte[] temp;
temp = (byte[]) getServletContext().getAttribute("serialData");
for(int i=0; i<temp.length;i++){
  output.println(Integer.toHexString(temp[i] & 0x00FF));    
}

I send to serial port this byte array:

aa 7f 40 a 72 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 fe 1a

The length is 69. Sometimes in my temp array I've only a little part of the original array, sometimes:

aa 7f 40 a 72 0 0 0 0 0 0 0 0 0 0

sometimes:

0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 fe 1a

And sometimes the right array of 69 bytes. How can I pass to my controller the exact data taken from serial port? Thanks in advance

Upvotes: 0

Views: 429

Answers (1)

Matt Ball
Matt Ball

Reputation: 360016

If any more data comes in to that port, this code will overwrite what you initially had in the serialData context attribute. So only write if the attribute is present, and consider closing the port after the initial dataRecieved() call.

serial.addListener(new SerialDataListener(){
    @Override
    public void dataReceived(SerialDataEvent arg0) {    
        private byte[] serialDataByte;
        if (context.getAttribute("serialData") == null) {
            serialDataByte = arg0.getData().getBytes();
            context.setAttribute("serialData", serialDataByte);
            seriale.write(serialDataByte); // I assume this is only for debugging
                                           // and also supposed to be `serial`
            serial.close();
        }
    }
});

Upvotes: 1

Related Questions