Java serial comms : way to set receieve threshold when using async. read notification

我只是一个虾纸丫 提交于 2020-01-06 07:21:32

问题


I have some code that's using the JavaComm API. It implements SerialPortEventListener and the reception of characters happens asynchronously. This works fine except that my serialEvent callback is notified after about 17 chars have been received, for my packet parsing I need it to be notified when <= 6 characters have been received. Is there any way to configure the serial API to call the async. notification when a specified no. of characters have been received?

Thank you, fred.


回答1:


All you get is a stream and a SerialPortEvent.DATA_AVAILABLE when data is available in the stream. What you could do is add a level of indirection and create your own listener that would be called when 6 characters have passed through and simply pass in the byte array with thoose 6 characters. I added where you would insert te code below. The implementation is up to you.

  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);
        }
        // partition readBuffer into chunks of 6 bytes
        ...
        registeredListener.dataReceived(sixByteByteArray);
      } catch (IOException e) {
      }
      break;
    }
  }


来源:https://stackoverflow.com/questions/3367872/java-serial-comms-way-to-set-receieve-threshold-when-using-async-read-notific

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!