# Test ECT0 _FST / _FSL via ectest (needs ec-test-app, run as Administrator).
# - Reads current FAND via \_SB.ECT0._FST
# - Writes a new FAND level via \_SB.ECT0._FSL
#   - 0–100  : 直接传给 _FSL（测试用档位）
#   - 255   : 传 255 (=0xFF)，恢复 EC 自动控扇
# - Then loops to monitor FAND changes over time

param(
    [string]$EctestPath = "C:\Users\Jack\ec-test-app\exe\x64\Release\ectest.exe",
    [int]$SetFandPercent = 30,    # 0-100 = 固定档位, 255=0xFF 自动
    [int]$Iterations = 0,          # 0 = infinite loop
    [int]$IntervalSeconds = 1
)

if (-not (Test-Path $EctestPath)) {
    Write-Host "ectest not found: $EctestPath" -ForegroundColor Red
    exit 1
}

function Invoke-Ect0FstRaw {
    param()
    & $EctestPath -acpi "\_SB.ECT0._FST"
}

function Invoke-Ect0FslRaw {
    param(
        [int]$ValuePercent
    )
    & $EctestPath -acpi "\_SB.ECT0._FSL" $ValuePercent
}

function Get-Ect0Fand {
    $out = Invoke-Ect0FstRaw
    $lines = @($out)
    $fand = $null
    $captureNext = $false
    foreach ($line in $lines) {
        if ($line -match 'Argument\[1\]:') {
            $captureNext = $true
            continue
        }
        if ($captureNext) {
            if ($line -match 'Integer Value:\s*(0x[0-9A-Fa-f]+|\d+)') {
                $fand = $Matches[1]
                break
            }
        }
    }
    [PSCustomObject]@{
        Fand     = $fand
        RawText  = ($lines -join "`r`n")
    }
}

Write-Host "=== ECT0 _FST/_FSL test (needs DPTF debug ECT0 enabled in firmware) ===" -ForegroundColor Cyan
Write-Host "Ectest path : $EctestPath"
Write-Host "SetFand     : $SetFandPercent  (0-100=fixed, 255=auto)"
Write-Host ""

Write-Host "[1] Current FAND from _FST:" -ForegroundColor Green
$cur = Get-Ect0Fand
$fVal = if ($cur.Fand) { $cur.Fand } else { "N/A" }
Write-Host ("  FAND = {0}" -f $fVal)
Write-Host ""

if (($SetFandPercent -ge 0 -and $SetFandPercent -le 100) -or $SetFandPercent -eq 255) {
    Write-Host "[2] Writing FAND via _FSL($SetFandPercent) ..." -ForegroundColor Yellow
    Invoke-Ect0FslRaw -ValuePercent $SetFandPercent
    Write-Host ""

    Write-Host "[3] Read-back FAND after _FSL:" -ForegroundColor Green
    $after = Get-Ect0Fand
    $fVal = if ($after.Fand) { $after.Fand } else { "N/A" }
    Write-Host ("  FAND = {0}" -f $fVal)
    Write-Host ""
}

Write-Host "[4] Monitoring FAND with _FST (Ctrl+C to stop) ..." -ForegroundColor Cyan

$count = 0
while ($true) {
    $v = Get-Ect0Fand
    $ts = Get-Date -Format "HH:mm:ss"
    $fVal = if ($v.Fand) { $v.Fand } else { "N/A" }
    Write-Host ("{0}  FAND = {1}" -f $ts, $fVal)

    $count++
    if ($Iterations -gt 0 -and $count -ge $Iterations) { break }

    Start-Sleep -Seconds $IntervalSeconds
}

Write-Host "Done." -ForegroundColor Cyan

