как решить Jssc.SerialPortException: имя порта -COM3;Имя метода - openPort ();Тип исключения - порт не найден в Java - PullRequest
0 голосов
/ 08 июня 2018

Привет, ребята, я новичок в Java и Arduino.Когда программа запускается, я получаю такие ошибки.Как можно их исправить?Я знаю, что это действительно слишком длинный вопрос.Я благодарен за вашего пациента и помощь. Заранее спасибо.

jssc.SerialPortException: имя порта - COM3;Имя метода - openPort ();Тип исключения - Порт не найден.в jssc.SerialPort.openPort (SerialPort.java:167)

открытый класс RtuTransportJssc расширяет AbstractRtuTransport {

private final int baudRate;
private final int dataBits;
private final int parity;
private final int stopBits;
private final SerialPort port;

public static final int PARITY_NONE = SerialPort.PARITY_NONE;
public static final int PARITY_ODD  = SerialPort.PARITY_ODD;
public static final int PARITY_EVEN = SerialPort.PARITY_EVEN;

public RtuTransportJssc(String portName, int baudRate, int dataBits, int parity, int stopBits, int timeout, int pause) {
    super(timeout, pause, true, LoggerFactory.getLogger(RtuTransportJssc.class));
    this.port = new SerialPort(portName);
    this.baudRate = baudRate;
    this.dataBits = dataBits;
    this.parity = parity;
    this.stopBits = stopBits;
}

public static String parityStr(int code) {
    return code == 0 ? "N" : (code == 1 ? "O" : (code == 2 ? "E" : "?"));
}

// this method must be synchronized with close()
@Override
synchronized protected void openPort() throws SerialPortException, InterruptedException {
    if (Thread.currentThread().isInterrupted())
        throw new InterruptedException();
    if (!port.isOpened()) {
        log.info("Opening port: {}, {}, {}-{}-{}", port.getPortName(), baudRate, dataBits, parityStr(parity), stopBits);
        try {
            port.openPort();
            port.setParams(baudRate, dataBits, stopBits, parity);
        } catch (SerialPortException e) {
            close();
            throw e;
        }
        log.info("Port opened: {}", port.getPortName());
    }
}

// this method may be called from other thread
@Override
synchronized public void close() {
    if (port.isOpened()) {
        log.info("Closing port: {}", port.getPortName());
        try {
            port.closePort();
        } catch (SerialPortException e) {
            log.error("Error closing port {}: {}", port.getPortName(), e);
        }
        log.info("Port {} closed", port.getPortName());
    }
}

...

вmodbusminimaster.client.RtuTransportJssc.openPort (RtuTransportJssc.java:54)

synchronized protected void openPort() throws SerialPortException, InterruptedException {
    if (Thread.currentThread().isInterrupted())
        throw new InterruptedException();
    if (!port.isOpened()) {
        log.info("Opening port: {}, {}, {}-{}-{}", port.getPortName(), baudRate, dataBits, parityStr(parity), stopBits);
        try {
            port.openPort();
            port.setParams(baudRate, dataBits, stopBits, parity);
        } catch (SerialPortException e) {
            close();
            throw e;
        }
        log.info("Port opened: {}", port.getPortName());
    }
}

на modbusminimaster.client.AbstractRtuTransport.sendRequest (AbstractRtuTransport.java:41) *

@Override
public void sendRequest(ModbusClient modbusClient) throws Exception {
    if (pause > 0)
        Thread.sleep(pause);
    openPort();
    clearInput();
    buffer[0] = modbusClient.getServerId();
    modbusClient.readFromPdu(0, modbusClient.getPduSize(), buffer, 1);
    int size = modbusClient.getPduSize() + 1; // including 1 byte for serverId
    int crc = ModbusPdu.calcCRC16(buffer, 0, size);
    buffer[size] = ModbusPdu.lowByte(crc);
    buffer[size + 1] = ModbusPdu.highByte(crc);
    size = size + 2;
    if (log.isTraceEnabled())
        log.trace("Write: " + ModbusPdu.toHex(buffer, 0, size));
    sendData(size);
}

protected void logData(String kind, int start, int length) {
    if (log.isTraceEnabled()) 
        log.trace("Read ({}): {}", kind, ModbusPdu.toHex(buffer, start, length));
}

protected boolean crcValid(int size) {
    int crc = ModbusPdu.calcCRC16(buffer, 0, size);
    int crc2 = ModbusPdu.bytesToInt16(buffer[size], buffer[size + 1], true); 
    if (crc == crc2)
        return true;
    else {
        if (log.isWarnEnabled())
            log.warn("CRC error (calc: {}, in response: {})", Integer.toHexString(crc), Integer.toHexString(crc2));
        return false;
    }

в modbusminimaster.client.ModbusClient.execRequest (ModbusClient.java:146)

public boolean execRequest() throws Exception {
    if (!requestReady)
        throw new IllegalStateException("Call InitXXXRequest() first.");
    if (transport == null)
        throw new IllegalStateException("Transport is not set.");
    transport.sendRequest(this);
    requestReady = false;
    result = transport.waitResponse(this);
    responseReady = (result == RESULT_OK);
    if (!responseReady && (log != null) && log.isWarnEnabled()) {
        if (result == RESULT_EXCEPTION)
            log.warn("Exception 0x{} from {}", byteToHex((byte) getExceptionCode()), getServerId());
        else
            log.warn(getResultAsString() + " from {}", getServerId());
    }
    return responseReady;

}

в modbusminimaster.samples.SerialClientJssc.main (SerialClientJssc.Ява: 26)

public static void main(String[] args) {

    ModbusClient mc = new ModbusClient();
    mc.setTransport(new RtuTransportJssc("COM3", 9600, 8, SerialPort.PARITY_NONE, SerialPort.STOPBITS_1, 1000, 5));

    mc.InitReadHoldingsRequest(1, 0, 10);

    try {
mc.execRequest();
        if (mc.getResult() == ModbusClient.RESULT_OK)
            for (int i = 0; i < mc.getResponseCount(); i++)
                System.out.println("HR" + i + "=" + mc.getResponseRegister(mc.getResponseAddress() + i, false));
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        mc.close();
    }

}
...