hacker-cb / modbus-dart

BSD 3-Clause "New" or "Revised" License
37 stars 22 forks source link

Example to catch custom errors #4

Closed juanjuliocorica closed 4 years ago

juanjuliocorica commented 4 years ago

Hello dear friend, I have a problem to catch the exceptions that I have not been able to solve for weeks and I dare to write to see if they can help me, it turns out that in my implementation when I write in a register a value outside the range allowed by my device, the device returns "Server Failure" which generates an exception of type ModbusServerFailureException correctly. The problem is that I can't catch that error in a try / catch and Flutter gives me unhandled error. I've already tried everything I found using .catcherror in the future that runs the MODBUS script but couldn't find how to solve. How should I correctly implement the function that executes a write to a registry and correctly catches the error? My code is as follows:

Future<String> writeParametersToDevice(
  String direccionIP,
  List<ParametroEscrituraDTO> parametrosAEscribir,
) async {
  var client = modbus.createTcpClient(direccionIP,
      port: puertoModbus, mode: modbus.ModbusMode.rtu);

  try {
    await client.connect();
  } catch (e) {
    log.e('Error al conectar con el dispositivo: $e');
    return "Error de conexión con el dispositivo, verifique que está conectado a la red correcta.";
  }
  try {
    for (ParametroEscrituraDTO parametroAEscribir in parametrosAEscribir) {
      TipoParametroModbusEnum tipoParametroModbusEnum;

      Uint16List registros = getRegistrosEscritura(
        parametroAEscribir.valorRegistro,
        tipoParametroModbusEnum.getByName(parametroAEscribir.tipoDato),
      );

      log.d(
          "Escribiendo registro: ${parametroAEscribir.numeroRegistro} : ${parametroAEscribir.valorRegistro}");

      await client.writeMultipleRegisters(
          int.parse(parametroAEscribir.numeroRegistro) - 1, registros);
    }
    return "OK";
  } catch (e) {
    print(e);
    return "ERROR";
  } finally {
    await client.close();
  }
}

Thanks in advance

hacker-cb commented 4 years ago

Fixed in 0.0.6