readSensor method

Future<SensorReading> readSensor({
  1. int maxRetries = 3,
})

Read sensor data, retrying up to maxRetries times on failure.

Makes one initial attempt plus up to maxRetries retry attempts (i.e. maxRetries+ 1 total tries).

First attempts the extended 7-register read (moisture, temperature, conductivity, pH, N, P, K). Falls back to the basic 3-register read if the sensor returns a Modbus exception 0x02 (Illegal Data Address).

Implementation

Future<SensorReading> readSensor({int maxRetries = 3}) async {
  if (!isConnected) throw StateError('Not connected to sensor.');

  Object? lastError;

  for (int attempt = 0; attempt <= maxRetries; attempt++) {
    if (attempt > 0) {
      await Future<void>.delayed(const Duration(milliseconds: 150));
    }
    try {
      return await _tryReadExtended();
    } on StateError catch (e) {
      // Modbus exception 0x02 = sensor only has 3 registers — don't retry.
      if (e.message.contains('Illegal Data Address')) {
        return await _tryReadBasic();
      }
      lastError = e;
    } on Exception catch (e) {
      lastError = e;
    }
  }
  throw lastError ?? StateError('Failed to read sensor after $maxRetries attempts.');
}