package com.xydl.cac.serialport;

import com.fazecast.jSerialComm.SerialPort;
import com.fazecast.jSerialComm.SerialPortDataListener;
import com.fazecast.jSerialComm.SerialPortEvent;
import com.xydl.cac.util.ByteUtil;
import lombok.SneakyThrows;
import org.apache.commons.compress.utils.ByteUtils;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

public class DataListener implements SerialPortDataListener {
    private WebSocketSession session;
    private String portName;

    //通过websocket打开监听设备的时候绑定session返回给前端数据
    public DataListener(String portName) {
        this.portName = portName;
    }

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

    @SneakyThrows
    @Override
    public void serialEvent(SerialPortEvent event) {
        String hexString = "";
        if (event.getEventType() == SerialPort.LISTENING_EVENT_DATA_WRITTEN) {
            byte[] newData = new byte[event.getSerialPort().bytesAvailable()];
            int numRead = event.getSerialPort().readBytes(newData, newData.length);
            hexString = ByteUtil.bytesToHexString(newData);
        }
        System.out.println("监听接收串口" + portName + ";数据：" + hexString);
        session.sendMessage(new TextMessage(hexString));
    }
}

