param(
  [string]$PortName = "COM7",
  [int]$BaudRate = 9600,
  [string]$CommandFile
)

$serial = New-Object System.IO.Ports.SerialPort $PortName,$BaudRate,'None',8,'One'
$serial.ReadTimeout = 100
$serial.WriteTimeout = 1000
$serial.DtrEnable = $true

try {
  $serial.Open()
  [Console]::Out.WriteLine("@@STATUS:CONNECTED")
  [Console]::Out.Flush()
  Start-Sleep -Seconds 3
  $buffer = ""
  while ($true) {
    try {
      $buffer += $serial.ReadExisting()
      while ($buffer.Contains("`n")) {
        $position = $buffer.IndexOf("`n")
        $line = $buffer.Substring(0, $position).Trim()
        $buffer = $buffer.Substring($position + 1)
        if ($line) { [Console]::Out.WriteLine($line); [Console]::Out.Flush() }
      }
    } catch {}

    if ($CommandFile -and (Test-Path -LiteralPath $CommandFile)) {
      try {
        $command = [System.IO.File]::ReadAllText($CommandFile).Trim()
        Remove-Item -LiteralPath $CommandFile -Force
        if ($command) { $serial.WriteLine($command) }
      } catch {}
    }
    Start-Sleep -Milliseconds 80
  }
} catch {
  [Console]::Out.WriteLine("@@STATUS:ERROR:$($_.Exception.Message)")
  [Console]::Out.Flush()
  exit 1
} finally {
  if ($serial.IsOpen) { $serial.Close() }
  $serial.Dispose()
}
