| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465 |
- [CmdletBinding()]
- param(
- [ValidateSet('start', 'stop', 'restart', 'status')]
- [string]$Action = 'start',
- [string]$Listen = '0.0.0.0:18443',
- [switch]$MqttFallbackPlain
- )
- $ErrorActionPreference = 'Stop'
- $Root = (Resolve-Path (Join-Path $PSScriptRoot '..')).Path
- $RunDir = Join-Path $Root '.run\mock-edge-device'
- $GoCache = Join-Path $Root '.gocache-mock-edge'
- $Exe = Join-Path $RunDir 'mock-edge-device.exe'
- $State = Join-Path $RunDir 'process.json'
- $Stdout = Join-Path $RunDir 'stdout.log'
- $Stderr = Join-Path $RunDir 'stderr.log'
- function Read-State {
- if (-not (Test-Path -LiteralPath $State)) { return $null }
- try { return Get-Content -LiteralPath $State -Raw | ConvertFrom-Json } catch { return $null }
- }
- function Stop-Mock {
- $item = Read-State
- if ($null -ne $item) {
- $process = Get-Process -Id ([int]$item.pid) -ErrorAction SilentlyContinue
- if ($null -ne $process) {
- & taskkill.exe /PID ([int]$item.pid) /T /F 2>$null | Out-Null
- $process | Wait-Process -Timeout 5 -ErrorAction SilentlyContinue
- }
- }
- if (Test-Path -LiteralPath $State) { Remove-Item -LiteralPath $State -Force }
- Write-Host 'Mock edge device stopped.'
- }
- if ($Action -eq 'stop') { Stop-Mock; exit 0 }
- if ($Action -eq 'status') {
- $item = Read-State
- if ($null -eq $item) { Write-Host 'Mock edge device is not managed.'; exit 0 }
- $process = Get-Process -Id ([int]$item.pid) -ErrorAction SilentlyContinue
- Write-Host ("PID {0}, listen {1}, {2}" -f $item.pid, $item.listen, $(if ($null -eq $process) { 'stopped' } else { 'running' }))
- exit 0
- }
- if ($Action -eq 'restart') { Stop-Mock }
- New-Item -ItemType Directory -Path $RunDir -Force | Out-Null
- New-Item -ItemType Directory -Path $GoCache -Force | Out-Null
- Push-Location $Root
- try {
- $env:GOCACHE = $GoCache
- & go build -o $Exe .\cmd\mock-edge-device
- if ($LASTEXITCODE -ne 0) { throw 'Mock edge device build failed.' }
- } finally { Pop-Location }
- $arguments = "-listen `"$Listen`" -data-dir `"$RunDir`""
- if ($MqttFallbackPlain) { $arguments += ' -mqtt-fallback-plain' }
- $process = Start-Process -FilePath $Exe -ArgumentList $arguments -WorkingDirectory $Root -RedirectStandardOutput $Stdout -RedirectStandardError $Stderr -PassThru
- [ordered]@{ pid = $process.Id; listen = $Listen; started_at = (Get-Date).ToString('o') } | ConvertTo-Json | Set-Content -LiteralPath $State -Encoding UTF8
- Start-Sleep -Milliseconds 500
- if ($process.HasExited) { Get-Content -LiteralPath $Stderr -ErrorAction SilentlyContinue; throw 'Mock edge device exited during startup.' }
- Write-Host "Mock edge device started (PID $($process.Id))."
- Write-Host "Manual IP: use a non-loopback host IP with HTTPS port $($Listen.Split(':')[-1])."
- Write-Host "Automatic discovery: UDP port 31001"
- Write-Host "Pairing code: 246810"
- Write-Host "Logs: $Stdout / $Stderr"
|