start.ps1 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361
  1. # ==============================================================================
  2. # lf_mri_platform -- Start services and GUI
  3. # Usage:
  4. # .\start.ps1 -- plug mode: Docker + GUI
  5. # .\start.ps1 -Mode real -- real mode: Docker + spectrometer + GUI
  6. # .\start.ps1 -GuiOnly -- GUI only (services already running)
  7. # .\start.ps1 -ServicesOnly -- Docker + spectrometer, no GUI
  8. # .\start.ps1 -SkipInstall -- skip venv check
  9. # .\start.ps1 -SkipSpectrometer -- skip native spectrometer even in real mode
  10. # ==============================================================================
  11. param(
  12. [ValidateSet("plug", "real")]
  13. [string]$Mode = "plug",
  14. [switch]$GuiOnly,
  15. [switch]$ServicesOnly,
  16. [switch]$SkipInstall,
  17. [switch]$SkipSpectrometer
  18. )
  19. $ErrorActionPreference = "Stop"
  20. $Root = $PSScriptRoot
  21. $GuiDir = Join-Path $Root "apps\gui"
  22. $VenvPython = Join-Path $GuiDir ".venv\Scripts\python.exe"
  23. $AppScript = Join-Path $Root "apps\gui\app.py"
  24. $EnvFile = Join-Path $Root ".env"
  25. $EnvExample = Join-Path $Root ".env.example"
  26. $LogFile = Join-Path $Root "start_log.txt"
  27. # Write all output to log file so errors are readable even if window closes
  28. Start-Transcript -Path $LogFile -Append | Out-Null
  29. Write-Host "=== start.ps1 $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss') Mode=$Mode ==="
  30. function Write-Step($msg) { Write-Host "`n==> $msg" -ForegroundColor Cyan }
  31. function Write-OK($msg) { Write-Host " [OK] $msg" -ForegroundColor Green }
  32. function Write-Warn($msg) { Write-Host " [!!] $msg" -ForegroundColor Yellow }
  33. function Write-Fail($msg) {
  34. Write-Host "`n[FAIL] $msg" -ForegroundColor Red
  35. Write-Host " Log: $LogFile" -ForegroundColor DarkGray
  36. try { Stop-Transcript | Out-Null } catch {}
  37. Write-Host "`n Press Enter to close..." -ForegroundColor DarkGray
  38. $null = Read-Host
  39. exit 1
  40. }
  41. # Keep window open on any unhandled error
  42. trap {
  43. Write-Host "`n[ERROR] $_" -ForegroundColor Red
  44. Write-Host " Log: $LogFile" -ForegroundColor DarkGray
  45. try { Stop-Transcript | Out-Null } catch {}
  46. Write-Host "`n Press Enter to close..." -ForegroundColor DarkGray
  47. $null = Read-Host
  48. exit 1
  49. }
  50. function Get-EnvPort($key, $default) {
  51. if (Test-Path $EnvFile) {
  52. $line = Get-Content $EnvFile | Select-String "^$key=(\d+)"
  53. if ($line) { return $line.Matches[0].Groups[1].Value }
  54. }
  55. return $default
  56. }
  57. # Returns $true if the TCP port is accepting connections.
  58. # Using TCP instead of HTTP so HTTP 4xx/auth errors don't cause false negatives.
  59. function Test-ServiceUp($svc) {
  60. try {
  61. $uri = [System.Uri]$svc.Url
  62. $port = if ($uri.Port -gt 0) { $uri.Port } else { 80 }
  63. $tcp = New-Object System.Net.Sockets.TcpClient
  64. $ar = $tcp.BeginConnect($uri.Host, $port, $null, $null)
  65. $ok = $ar.AsyncWaitHandle.WaitOne(1500, $false)
  66. try { $tcp.Close() } catch {}
  67. return $ok
  68. } catch {
  69. return $false
  70. }
  71. }
  72. # -- 1. Check / install GUI venv -----------------------------------------------
  73. if (-not $GuiOnly -and -not $SkipInstall) {
  74. Write-Step "Checking GUI environment"
  75. $needsInstall = $false
  76. if (-not (Test-Path $VenvPython)) {
  77. Write-Warn "Virtual environment not found -- running install"
  78. $needsInstall = $true
  79. } else {
  80. & $VenvPython -c "import PySide6" 2>$null
  81. if ($LASTEXITCODE -ne 0) {
  82. Write-Warn "GUI packages missing -- running install"
  83. $needsInstall = $true
  84. } else {
  85. Write-OK "Virtual environment ready"
  86. }
  87. }
  88. if ($needsInstall) {
  89. $installScript = Join-Path $Root "install.ps1"
  90. if (-not (Test-Path $installScript)) { Write-Fail "install.ps1 not found" }
  91. & powershell.exe -ExecutionPolicy Bypass -File $installScript
  92. if ($LASTEXITCODE -ne 0) { Write-Fail "install.ps1 failed" }
  93. }
  94. }
  95. # -- 2. Docker -----------------------------------------------------------------
  96. if (-not $GuiOnly) {
  97. Write-Step "Checking Docker"
  98. $dockerOk = $false
  99. try { & docker info *>$null; $dockerOk = $true } catch {}
  100. if (-not $dockerOk) {
  101. Write-Warn "Docker not responding -- starting Docker Desktop..."
  102. $dockerExe = "C:\Program Files\Docker\Docker\Docker Desktop.exe"
  103. if (Test-Path $dockerExe) { Start-Process $dockerExe }
  104. else { Write-Fail "Docker Desktop not found -- install from https://docker.com" }
  105. $waited = 0
  106. while ($waited -lt 60) {
  107. Start-Sleep 5
  108. $waited += 5
  109. try { & docker info *>$null; $dockerOk = $true; break } catch {}
  110. Write-Host " ... $waited/60 s" -ForegroundColor DarkGray
  111. }
  112. if (-not $dockerOk) { Write-Fail "Docker did not start in time" }
  113. }
  114. Write-OK "Docker is running"
  115. # -- 3. .env ---------------------------------------------------------------
  116. if (-not (Test-Path $EnvFile)) {
  117. if (Test-Path $EnvExample) {
  118. Copy-Item $EnvExample $EnvFile
  119. Write-Warn ".env created from .env.example"
  120. } else {
  121. Write-Warn ".env missing -- using Compose defaults"
  122. }
  123. }
  124. # -- 4. Start containers ---------------------------------------------------
  125. Write-Step "Starting Docker services (mode: $Mode)"
  126. $env:ORCHESTRATOR_MODE = $Mode
  127. $envArgs = if (Test-Path $EnvFile) { @("--env-file", $EnvFile) } else { @() }
  128. & docker compose @envArgs up -d
  129. if ($LASTEXITCODE -ne 0) { Write-Fail "docker compose up failed" }
  130. Write-OK "Containers started"
  131. # -- 5. Native spectrometer ------------------------------------------------
  132. if (-not $SkipSpectrometer) {
  133. Write-Step "Starting native spectrometer"
  134. $SpecDir = Join-Path $Root "services\spectrometer"
  135. $SpecVenv = Join-Path $SpecDir "mvenv\Scripts\python.exe"
  136. $PicoExe = Join-Path $SpecDir "bin\pico-tcp.exe"
  137. $oldPico = Get-Process -Name "pico-tcp" -ErrorAction SilentlyContinue
  138. if ($oldPico) { $oldPico | Stop-Process -Force; Write-Warn "Killed stale pico-tcp.exe" }
  139. if (-not (Test-Path $SpecVenv)) {
  140. Write-Warn "Spectrometer venv not found -- creating..."
  141. Push-Location $SpecDir
  142. & python -m venv mvenv
  143. if ($LASTEXITCODE -ne 0) { Write-Fail "Failed to create spectrometer venv" }
  144. Pop-Location
  145. Write-OK "Spectrometer venv created"
  146. } else {
  147. Write-OK "Spectrometer venv found"
  148. }
  149. # Always sync packages (catches new deps after git pull)
  150. Write-Host " Installing/updating spectrometer packages..." -ForegroundColor DarkGray
  151. Push-Location $SpecDir
  152. & $SpecVenv -m pip install -q --upgrade pip
  153. $pipOut = & $SpecVenv -m pip install -q -r requirements.txt 2>&1
  154. $pipFailed = ($LASTEXITCODE -ne 0)
  155. Pop-Location
  156. if ($pipFailed) {
  157. Write-Warn "pip install had issues:`n$pipOut"
  158. } else {
  159. Write-OK "Packages up to date"
  160. }
  161. # Migrations -- show output so errors are visible
  162. Write-Host " Running migrations..." -ForegroundColor DarkGray
  163. Push-Location $SpecDir
  164. $migrateOut = & $SpecVenv manage.py migrate --noinput 2>&1
  165. $migrateFailed = ($LASTEXITCODE -ne 0)
  166. Pop-Location
  167. if ($migrateFailed) {
  168. Write-Warn "Migration warnings:`n$migrateOut"
  169. } else {
  170. Write-OK "Migrations applied"
  171. }
  172. # pico-tcp.exe
  173. if (Test-Path $PicoExe) {
  174. Start-Process $PicoExe -WindowStyle Normal
  175. Write-OK "pico-tcp.exe started (visible window)"
  176. } else {
  177. Write-Warn "bin\pico-tcp.exe not found -- ADC proxy not started"
  178. }
  179. # Django runserver -- run via "cmd /k" so window stays open on error
  180. $specPort = Get-EnvPort "SPECTROMETER_PORT" "8000"
  181. $alreadyUp = $false
  182. try {
  183. $r = Invoke-WebRequest "http://localhost:$specPort/api/" `
  184. -UseBasicParsing -TimeoutSec 2 -ErrorAction Stop
  185. $alreadyUp = ($r.StatusCode -lt 400)
  186. } catch {}
  187. if ($alreadyUp) {
  188. Write-OK "Spectrometer already responding on port $specPort -- checking devices..."
  189. # Fall through to device registration check below
  190. } else {
  191. # Title makes the window easy to find in the taskbar.
  192. # /k keeps the window open even if Django crashes at startup.
  193. # --noreload disables Django's file-watcher subprocess (cleaner in cmd).
  194. $runCmd = "`"$SpecVenv`" manage.py runserver 0.0.0.0:$specPort --noreload"
  195. Start-Process "cmd.exe" `
  196. -ArgumentList "/k title LF-MRI Spectrometer && $runCmd" `
  197. -WorkingDirectory $SpecDir `
  198. -WindowStyle Normal
  199. Write-OK "Spectrometer started (window: 'LF-MRI Spectrometer', port $specPort)"
  200. }
  201. # -- Auto-register hardware devices if DB is empty --------------------
  202. Write-Host " Waiting for spectrometer API..." -ForegroundColor DarkGray
  203. $apiReady = $false
  204. $apiWait = 0
  205. while ($apiWait -lt 20) {
  206. if (Test-ServiceUp @{ Url = "http://localhost:$specPort/api/" }) {
  207. $apiReady = $true; break
  208. }
  209. Start-Sleep 1; $apiWait++
  210. }
  211. if ($apiReady) {
  212. try {
  213. $devResp = Invoke-WebRequest "http://localhost:$specPort/api/devices/" `
  214. -UseBasicParsing -TimeoutSec 5 -ErrorAction Stop
  215. $devJson = $devResp.Content | ConvertFrom-Json
  216. $devCount = if ($devJson.PSObject.Properties['results']) {
  217. $devJson.results.Count
  218. } else {
  219. @($devJson).Count
  220. }
  221. if ($devCount -eq 0) {
  222. Write-Warn "No devices in DB -- registering hardware..."
  223. $base = "http://localhost:$specPort/api/devices/"
  224. $hdr = @{ "Content-Type" = "application/json" }
  225. $devs = @(
  226. '{"device_type":"ADC", "brend":"Picoscope", "serial_model":"PS4000A", "proto":"adc_default", "proto_interface":"TCP"}',
  227. '{"device_type":"SDR", "brend":"HackRF", "serial_model":"HackRF", "proto":"sdr_default", "proto_interface":"USB"}',
  228. '{"device_type":"SYNC", "brend":"Arduino", "serial_model":"DuePP", "proto":"sync_default", "proto_interface":"USB"}',
  229. '{"device_type":"GRA", "brend":"ITMO", "serial_model":"GRU", "proto":"gra_default", "proto_interface":"UDP"}'
  230. )
  231. foreach ($body in $devs) {
  232. try {
  233. Invoke-WebRequest $base -Method Post -Headers $hdr `
  234. -Body $body -UseBasicParsing -TimeoutSec 5 | Out-Null
  235. $name = ($body | Select-String '"serial_model":"([^"]+)"').Matches[0].Groups[1].Value
  236. Write-Host " Registered: $name" -ForegroundColor DarkGray
  237. } catch {
  238. Write-Warn " Failed to register device: $_"
  239. }
  240. }
  241. Write-OK "Hardware devices registered"
  242. } else {
  243. Write-OK "Devices already in DB ($devCount found)"
  244. }
  245. } catch {
  246. Write-Warn "Could not check/register devices: $_"
  247. }
  248. } else {
  249. Write-Warn "Spectrometer API not ready in 20 s -- skipping device registration"
  250. }
  251. }
  252. # -- 6. Health check -------------------------------------------------------
  253. Write-Step "Waiting for services to become healthy"
  254. $checkSpec = -not $SkipSpectrometer
  255. $services = @(
  256. @{ Name = "Orchestrator"; Url = "http://localhost:$(Get-EnvPort 'ORCHESTRATOR_PORT' '1717')/health"; Required = $true },
  257. @{ Name = "Seq-Interp"; Url = "http://localhost:$(Get-EnvPort 'SEQ_INTERP_PORT' '7475')/health"; Required = $true },
  258. @{ Name = "Reconstructor"; Url = "http://localhost:$(Get-EnvPort 'RECONSTRUCTOR_PORT' '8081')/health"; Required = $true },
  259. @{ Name = "Spectroscopy"; Url = "http://localhost:$(Get-EnvPort 'SPECTROSCOPY_PORT' '8002')/health"; Required = $true },
  260. @{ Name = "Spectrometer"; Url = "http://localhost:$(Get-EnvPort 'SPECTROMETER_PORT' '8000')/api/"; Required = $checkSpec; AllowedCodes = @(200,301,302,401,403) }
  261. )
  262. $maxWait = 120; $interval = 3; $elapsed = 0
  263. while ($elapsed -lt $maxWait) {
  264. $pending = @()
  265. foreach ($svc in $services) {
  266. if (-not $svc.Required) { continue }
  267. if (-not (Test-ServiceUp $svc)) { $pending += $svc.Name }
  268. }
  269. if ($pending.Count -eq 0) { Write-OK "All required services healthy"; break }
  270. Write-Host (" ... {0}/{1} s waiting: {2}" -f $elapsed, $maxWait, ($pending -join ", ")) -ForegroundColor DarkGray
  271. Start-Sleep $interval
  272. $elapsed += $interval
  273. }
  274. if ($elapsed -ge $maxWait) { Write-Warn "Some services did not respond in time -- continuing anyway" }
  275. Write-Host ""
  276. foreach ($svc in $services) {
  277. $ok = Test-ServiceUp $svc
  278. $icon = if ($ok) { "[OK]" } else { "[--]" }
  279. $color = if ($ok) { "Green" } elseif ($svc.Required) { "Yellow" } else { "DarkGray" }
  280. $suffix = if (-not $svc.Required -and -not $ok) { " (native -- start manually)" } else { "" }
  281. Write-Host (" {0,-6} {1,-16} {2}{3}" -f $icon, $svc.Name, $svc.Url, $suffix) -ForegroundColor $color
  282. }
  283. # -- 7. Write server_config.json -------------------------------------------
  284. Write-Step "Configuring GUI"
  285. $orchPort = Get-EnvPort "ORCHESTRATOR_PORT" "1717"
  286. $seqPort = Get-EnvPort "SEQ_INTERP_PORT" "7475"
  287. $spectPort = Get-EnvPort "SPECTROSCOPY_PORT" "8002"
  288. $cfgPath = Join-Path $Root "apps\gui\cfg\server_config.json"
  289. $cfgObj = @{
  290. srv_name = "srv_interp"
  291. log_dir = "log"
  292. upload_dir = "data/input"
  293. output_dir = "data/output"
  294. server_host = "0.0.0.0"
  295. server_port = [int]$seqPort
  296. orchestrator_url = "http://localhost:$orchPort"
  297. seq_interp_url = "http://localhost:$seqPort"
  298. spectroscopy_url = "http://localhost:$spectPort"
  299. mode = $Mode
  300. }
  301. $cfgObj | ConvertTo-Json -Depth 3 | Set-Content $cfgPath -Encoding utf8
  302. Write-OK "server_config.json updated (mode=$Mode orch=:$orchPort seq=:$seqPort spectro=:$spectPort)"
  303. }
  304. # -- 8. Launch GUI -------------------------------------------------------------
  305. if (-not $ServicesOnly) {
  306. Write-Step "Launching GUI"
  307. if (-not (Test-Path $VenvPython)) {
  308. Write-Warn "Venv not found -- falling back to system Python"
  309. $VenvPython = "python"
  310. }
  311. if (-not (Test-Path $AppScript)) { Write-Fail "GUI entry point not found: $AppScript" }
  312. Start-Process $VenvPython -ArgumentList "`"$AppScript`"" -WorkingDirectory $Root -WindowStyle Normal
  313. Write-OK "GUI launched"
  314. }
  315. # -- Summary -------------------------------------------------------------------
  316. Write-Host ""
  317. Write-Host "============================================================" -ForegroundColor Green
  318. Write-Host (" LF-MRI platform is running [{0} mode]" -f $Mode.ToUpper()) -ForegroundColor Green
  319. Write-Host "============================================================" -ForegroundColor Green
  320. Write-Host ""
  321. if (-not $SkipSpectrometer) {
  322. Write-Host " Stop spectrometer: close the spectrometer terminal window"
  323. Write-Host " Stop pico-tcp: services\spectrometer\autokill.bat"
  324. }
  325. Write-Host " Stop all: .\stop.ps1"
  326. Write-Host " Update code: .\update.bat"
  327. Write-Host ""
  328. Write-Host " Log saved to: $LogFile" -ForegroundColor DarkGray
  329. try { Stop-Transcript | Out-Null } catch {}
  330. Write-Host " Press Enter to close this window..." -ForegroundColor DarkGray
  331. $null = Read-Host