Skip to content

No able to catch MODBUS ERRORS Exceptions #26

@saguado69

Description

@saguado69

Hi,

I'm having an issue when I disconnect the modbus server. An exception is generated but I'm not able to catch it. My code is wrapped with a try catch but the Exception is raised but bot catches by my code. These are the exceptions I'm trying to catch:

Unhandled Exception: ModbusConnectException (MODBUS ERROR: Connector was closed before operation was completed)
Unhandled Exception: SocketException: Connection reset by peer (OS Error: Connection reset by peer, errorno = 54

My app works fine, it connect correctly, reconnect, readRegisters, etc, but whenever I switch off manually my modbus server, I'm not able to catch the exception. So, thanks in advance for your support.

And this is my code:

try {
isConnecting = true;
event = 'Connecting ... $host:$port';
client = modbus.createTcpClient(
host,
port: port,
mode: modbus.ModbusMode.rtu,
timeout: const Duration(seconds: 10),
);
await client.connect().then((value) {
isConnected = true;
isConnecting = false;
event = 'Connected to $host:$port';
int slaveId = 1;
polling =
Timer.periodic(const Duration(milliseconds: 200), (Timer t) async {
isPolling = true;
client.setUnitId(slaveId);
await client
.readHoldingRegisters(0x0001, 100)
.then((registers) {
debugPrint('REGS: ${registers.toString()}');
})
.timeout(const Duration(seconds: 5))
.onError((error, stackTrace) {
polling.cancel();
isConnected = false;
isPolling = false;
event = 'Disconnected from $host:$port';
return;
});
});
return isConnected;
});
} on modbus.ModbusConnectException catch (error) {
debugPrint(error.toString());
} on SocketException catch (error) {
debugPrint(error.message);
} on Error catch (error) {
debugPrint(error.toString());
} catch (error) {
debugPrint(error.toString());
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions