如何通过jserialcomm处理流数据?

gijlo24d  于 2021-07-11  发布在  Java
关注(0)|答案(0)|浏览(415)

为了简单地总结我的问题,我正在使用jserialcomm库从串行端口读取数据。我的最终目标是显示从串口读取的最后一个值 localhost:8090/value 在tcp端口上。但不幸的是,我还没有接近结果。我设法显示一个字符串,但是当我第二次调用这个数组时,我得到一个 ConcurrentModificationException 错误。你能帮我解决如何从流式数据源顺序保存数据吗?
打包侦听器:

public class PacketListener  implements SerialPortDataListener {
    Logger logger = Logger.getLogger(PacketListener.class.getName());
    public static final List<String> collector = new ArrayList<>();
    SerialPort serialPort;
    ResponseMessageHandler responseMessageHandler = new ResponseMessageHandler();
    String data ="";

    public PacketListener(SerialPort serialPort){
        this.serialPort = serialPort;
    }

    @Override
    public int getListeningEvents() {
        return SerialPort.LISTENING_EVENT_DATA_RECEIVED;
    }

    @Override
    public void serialEvent(SerialPortEvent serialPortEvent) {
        if (serialPortEvent.getEventType() != SerialPort.LISTENING_EVENT_DATA_RECEIVED) {
            return;
        }
        byte[] newData = serialPortEvent.getReceivedData();
        String data = new String(newData);
      //    logger.log(Level.INFO, "received Data : {0}", data);
            collector.add(data);
            responseMessageHandler.handleResponse(data); 
    }
}

端口服务:

@Service
public class PortService implements PortManager {
    Logger logger = Logger.getLogger(PortService.class.getName());
    Entities entities;

    @Override
    public List<String> portReader() {

        SerialPort comPort = SerialPort.getCommPorts()[0];
        setProperties(comPort);
        comPort.openPort();
        comPort.setComPortTimeouts(SerialPort.TIMEOUT_READ_BLOCKING,0,0);
        PacketListener packetListener = new PacketListener(comPort);
        comPort.addDataListener(packetListener);
        List<String> collected = packetListener.collector.stream()
                .map(i -> i.endsWith("/n") ? i.substring(0,i.length()-3):i).collect(Collectors.toList());
        return packetListener.collector;

    }

    @Override
    public SerialPort setProperties(SerialPort serialPort) {
        entities = new Entities();
        serialPort.setBaudRate(entities.getBaudRate());
        serialPort.setParity(Parity.NONE.getValue());
        serialPort.setNumDataBits(entities.getDataBits());
        serialPort.setNumStopBits(entities.getStopBits());
        return serialPort;
    }
}

端口控制器:

@Controller
public class PortController {
    @Autowired
    PortManager portService;

    @GetMapping(value = "/value")
    @ResponseBody
    public List<String> getValue(){
     return portService.portReader();
    }
}

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题