import java.io.*;
import java.util.concurrent.*;
import javax.comm.*;

public class SerialDeviceTester implements SerialPortEventListener {
    private SerialPort serialPort;
    private InputStream inputStream;
    private OutputStream outputStream;
    private final StringBuilder responseBuffer = new StringBuilder();
    private final CountDownLatch responseLatch = new CountDownLatch(1);
    
    public SerialDeviceTester(String portName, int baudRate) throws Exception {
        CommPortIdentifier portId = CommPortIdentifier.getPortIdentifier(portName);
        serialPort = (SerialPort) portId.open("SerialDeviceTester", 2000);
        serialPort.setSerialPortParams(baudRate, 
                                      SerialPort.DATABITS_8,
                                      SerialPort.STOPBITS_1,
                                      SerialPort.PARITY_NONE);
        serialPort.setFlowControlMode(SerialPort.FLOWCONTROL_NONE);
        serialPort.enableReceiveTimeout(1000);
        
        inputStream = serialPort.getInputStream();
        outputStream = serialPort.getOutputStream();
        serialPort.addEventListener(this);
        serialPort.notifyOnDataAvailable(true);
        
        System.out.println("Connected to " + portName);
    }
    
    @Override
    public void serialEvent(SerialPortEvent event) {
        if (event.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
            try {
                byte[] buffer = new byte[1024];
                int len;
                while ((len = inputStream.read(buffer)) > 0) {
                    responseBuffer.append(new String(buffer, 0, len));
                }
                responseLatch.countDown();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    
    public void sendCommand(String command) throws InterruptedException {
        responseBuffer.setLength(0);
        responseLatch.countDown(); // Reset previous latch if any
        responseLatch = new CountDownLatch(1);
        
        System.out.println("Sending: " + command);
        
        try {
            outputStream.write((command + "\r\n").getBytes());
            outputStream.flush();
            
            // 等待响应
            boolean received = responseLatch.await(1, TimeUnit.SECONDS);
            
            if (received && responseBuffer.length() > 0) {
                System.out.println("Response: " + responseBuffer.toString().trim());
            } else {
                System.out.println("No response");
            }
        } catch (IOException e) {
            System.err.println("Error sending command: " + e.getMessage());
        }
        
        System.out.println("----------------------------------------");
    }
    
    public void runTests() throws InterruptedException {
        System.out.println("Starting basic tests...");
        
        sendCommand("HELP");
        sendCommand("STATUS");
        sendCommand("POWER 1");
        sendCommand("STATUS");
        sendCommand("POWER 2");
        sendCommand("STATUS");
        sendCommand("PC");
        sendCommand("STATUS");
        sendCommand("VERSATILE 1");
        sendCommand("STATUS");
        sendCommand("OFF");
        sendCommand("STATUS");
        sendCommand("help");
        sendCommand("power 1");
        
        System.out.println("Tests completed");
    }
    
    public void close() {
        if (serialPort != null) {
            serialPort.removeEventListener();
            serialPort.close();
        }
    }
    
    public static void main(String[] args) {
        // 列出可用串口
        System.out.println("Available serial ports:");
        java.util.Enumeration<CommPortIdentifier> portEnum = CommPortIdentifier.getPortIdentifiers();
        while (portEnum.hasMoreElements()) {
            CommPortIdentifier portId = portEnum.nextElement();
            if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
                System.out.println("  " + portId.getName());
            }
        }
        
        // 根据实际情况修改串口号
        String portName = "COM3";
        
        try {
            SerialDeviceTester tester = new SerialDeviceTester(portName, 9600);
            try {
                tester.runTests();
            } finally {
                tester.close();
            }
        } catch (Exception e) {
            System.err.println("Error: " + e.getMessage());
            e.printStackTrace();
        }
    }
}