steveohara / j2mod

Enhanced Modbus library implemented in the Java programming language
Apache License 2.0
267 stars 111 forks source link

Serial port connection #40

Closed Kosmachevskiy closed 7 years ago

Kosmachevskiy commented 7 years ago

Library version: 2.3.1

Hi!

I have some trouble with ModbusSerialMaster. I got a NPE during reading registers.

My code:

`

    SerialParameters parameters = new SerialParameters();

    parameters.setPortName("/dev/ttyUSB1");
    parameters.setBaudRate(9600);
    parameters.setDatabits(8);
    parameters.setStopbits(1);
    parameters.setParity("none");
    parameters.setEncoding("rtu");
    parameters.setEcho(false);

    ModbusSerialMaster master = new ModbusSerialMaster(parameters);

    master.connect();
    master.readMultipleRegisters(1, 0, 100);
    master.disconnect();

` And stack:

Exception in thread "main" java.lang.NullPointerException at com.ghgande.j2mod.modbus.net.SerialConnection.setComPortTimeouts(SerialConnection.java:221) at com.ghgande.j2mod.modbus.io.ModbusSerialTransport.setTimeout(ModbusSerialTransport.java:142) at com.ghgande.j2mod.modbus.io.ModbusSerialTransport.open(ModbusSerialTransport.java:131) at com.ghgande.j2mod.modbus.io.ModbusSerialTransport.writeMessage(ModbusSerialTransport.java:73) at com.ghgande.j2mod.modbus.io.ModbusSerialTransaction.execute(ModbusSerialTransaction.java:143) at com.ghgande.j2mod.modbus.facade.AbstractModbusMaster.readMultipleRegisters(AbstractModbusMaster.java:236)

steveohara commented 7 years ago

It shouldn't be throwing an NPE but I suspect it's because it cannot create a JSerialComm wrapper around "/dev/ttyUSB1" Does SerialPort.getCommPort("/dev/ttyUSB1") return anything?

notsyncing commented 7 years ago

I ran into the same(or similar) problem recently, and finally found the cause is current user didn't have the permission to access the serial port (not in dialout group). By the way, would you mind add some checks when opening the serial port? Making it fails early at opening the serial port instead of fails at first operation could reduce the difficulty of debugging such problems.

Kosmachevskiy commented 7 years ago

Problem really with permissions. Thanks.

steveohara commented 7 years ago

I've created https://github.com/steveohara/j2mod/issues/45 so that I don't forget about it