parseResponse method

  1. @override
VtjCommandResult<BattSelfTestResult> parseResponse(
  1. Uint8List response
)
override

Parse the response bytes from the device.

Implementation

@override
VtjCommandResult<BattSelfTestResult> parseResponse(Uint8List response) {
  try {
    if (response.isEmpty) {
      return const VtjCommandResult.failure('Response is empty', null);
    }

    if (response.length < 2) {
      return const VtjCommandResult.failure('Response too short', null);
    }

    final callId = response[0];
    final statusCode = response[1];

    if (callId != commandId) {
      return VtjCommandResult.failure(
        'Invalid call ID in response: $callId',
        null,
      );
    }

    if (statusCode == 3) {
      return const VtjCommandResult.failure('Device in incorrect state', 3);
    } else if (statusCode != 0) {
      return VtjCommandResult.failure(
        'Command failed with status: $statusCode',
        statusCode,
      );
    }

    // For successful response, we need the voltage data
    // Expected response structure: [Call ID: 1 byte][Status: 1 byte][Voltage1: 2 bytes][Voltage2: 2 bytes]
    // Total minimum length: 1 + 1 + 4 = 6 bytes
    if (response.length < 6) {
      return const VtjCommandResult.failure(
        'Insufficient data in response for voltage readings',
        null,
      );
    }

    // Read the two UINT16 voltage values starting from index 2
    final voltageWithoutLed = _readUint16(response, 2);
    final voltageWithLed = _readUint16(response, 4);

    return VtjCommandResult.success(
      BattSelfTestResult(
        voltageWithoutLed: voltageWithoutLed,
        voltageWithLed: voltageWithLed,
      ),
    );
  } catch (e) {
    return VtjCommandResult.failure('Failed to parse response: $e', null);
  }
}