-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathstart.py
More file actions
683 lines (620 loc) · 24.5 KB
/
start.py
File metadata and controls
683 lines (620 loc) · 24.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
"""
Purpose:
Provide a convenience launcher for the Hydroponics Control Center.
Ties Into:
Entry-point wrapper that delegates to hydroponics.launcher modules.
Inputs:
CLI arguments passed through to the underlying launcher logic.
Outputs:
Process exit code propagated from the selected runtime mode.
Side Effects:
Spawns subprocesses for the dashboard and controller, and relays output.
Raises:
None. Errors are reported via SystemExit with actionable messages.
Why:
A single cross-platform launcher keeps startup consistent across dev, Pi, and desktop hosts.
"""
from __future__ import annotations
import os
import subprocess
import sys
import threading
from pathlib import Path
from hydroponics.launcher import cli as launcher_cli
from hydroponics.launcher import dashboard as launcher_dashboard
from hydroponics.launcher import env as launcher_env
from hydroponics.launcher import paths as launcher_paths
from hydroponics.launcher import runtime_mode as launcher_runtime
from hydroponics.launcher import settings as launcher_settings
from hydroponics.launcher import subprocesses as launcher_subprocesses
from hydroponics.launcher import supervisor as launcher_supervisor
def _repo_root() -> Path:
"""
Summary:
Resolve the repository root directory for reliable relative command execution.
Inputs:
None.
Outputs:
Path to the repository root directory.
Side effects:
None.
Error handling:
Raises RuntimeError if the repository root cannot be resolved.
Ties to other methods:
Used by main to run Python modules from the repo root regardless of invocation location.
Why this exists:
Running modules with the correct working directory avoids import and config path confusion.
"""
return launcher_paths.repo_root(anchor_file=__file__)
def _ensure_python_version() -> None:
"""
Summary:
Fail fast when the interpreter is too old for the project requirements.
Inputs:
None.
Outputs:
None.
Side effects:
None.
Error handling:
Raises SystemExit if the Python version is below the supported minimum.
Ties to other methods:
Called by main before launching any subprocesses.
Why this exists:
A clear early error prevents confusing import failures later.
"""
launcher_cli.ensure_python_version(min_version=(3, 10))
def _run_subprocess(
*,
args: list[str],
cwd: Path,
env: dict[str, str],
) -> int:
"""
Summary:
Execute a subprocess command with safe defaults and propagate the exit code.
Inputs:
args: Argument vector to execute.
cwd: Working directory to execute from.
env: Environment variables to use for the subprocess.
Outputs:
Process return code.
Side effects:
Spawns a child process for the selected program mode.
Error handling:
Raises SystemExit if the subprocess cannot be started.
Ties to other methods:
Used by main for dashboard and controller launches.
Why this exists:
Centralizing subprocess invocation keeps behavior consistent across entrypoints.
"""
return launcher_subprocesses.run_subprocess(args=args, cwd=cwd, env=env, run_fn=subprocess.run)
def _validate_config_path(raw_path: str) -> str:
"""
Summary:
Validate and normalize the optional settings.json path for HYDROPONICS_CONFIG_PATH.
Inputs:
raw_path: User provided config path string.
Outputs:
Normalized absolute config path string suitable for environment variables.
Side effects:
Reads filesystem metadata for existence checks.
Error handling:
Raises SystemExit if the provided path does not exist or is not a file.
Ties to other methods:
Called by main before launching dashboard/controller subprocesses.
Why this exists:
Failing fast with a clear message prevents confusing registry errors later.
"""
return launcher_cli.validate_config_path(raw_path)
def _terminate_process(process: subprocess.Popen[object], *, name: str) -> None:
"""
Summary:
Terminate a child process and ensure it does not linger.
Inputs:
process: The subprocess to terminate.
name: Friendly process name for error reporting.
Outputs:
None.
Side effects:
Sends termination signals to a child process.
Error handling:
Raises SystemExit if the process cannot be terminated cleanly.
Ties to other methods:
Used by the supervisor to stop the remaining process when one exits.
Why this exists:
Clean shutdown avoids orphaned processes and confusing partial states.
"""
launcher_subprocesses.terminate_process(process, name=name)
def _spawn_child_process(
*,
args: list[str],
cwd: Path,
env: dict[str, str],
) -> subprocess.Popen[str]:
"""
Summary:
Spawn a long-lived child process with output piped back to the supervisor.
Inputs:
args: Argument vector to execute.
cwd: Working directory for the subprocess.
env: Environment variables to apply to the subprocess.
Outputs:
Popen handle for the child process.
Side effects:
Spawns a child process with stdout/stderr captured.
Error handling:
Raises SystemExit if the process cannot be started.
Ties to other methods:
Used by _run_all so the supervisor can serialize output across multiple subprocesses.
Why this exists:
Multiple subprocesses writing directly to the same terminal can interleave bytes and produce
garbled log lines; piping output through a single writer prevents that.
"""
return launcher_subprocesses.spawn_child_process(
args=args,
cwd=cwd,
env=env,
popen_fn=subprocess.Popen,
)
def _relay_process_output(
process: subprocess.Popen[str],
*,
write_lock: threading.Lock,
) -> threading.Thread:
"""
Summary:
Relay a subprocess stdout stream to the terminal without cross-process interleaving.
Inputs:
process: Child process whose stdout should be relayed.
write_lock: Global lock to serialize writes across relay threads.
Outputs:
Thread that performs the relay; it is started before returning.
Side effects:
Starts a daemon thread and writes to sys.stdout.
Error handling:
None.
Ties to other methods:
Used by _run_all to ensure dashboard and controller logs remain line-safe.
Why this exists:
Terminal writes are not guaranteed to be line-atomic across processes; a shared lock keeps
each line intact.
"""
return launcher_subprocesses.relay_process_output(
process,
write_lock=write_lock,
output_stream=sys.stdout,
)
def _run_all(*, root: Path, env: dict[str, str], passthrough: list[str]) -> int:
"""
Summary:
Run dashboard and controller together in a single terminal session.
Inputs:
root: Repository root directory.
env: Environment variables to apply to both child processes.
passthrough: Additional CLI arguments (not supported for all-mode).
Outputs:
Exit code from the first process that exits.
Side effects:
Starts two long-running child processes and monitors them.
Error handling:
Raises SystemExit if either subprocess cannot be started or shutdown fails.
Ties to other methods:
Implements the default `./start` behavior for low-friction operation.
Why this exists:
A single command should bring up the whole system without requiring users to learn
process separation.
"""
if passthrough:
joined = " ".join(passthrough)
raise SystemExit(f"Unexpected extra arguments: {joined}")
controller_args = [sys.executable, str(root / "main.py")]
runtime_mode_path = _resolve_runtime_mode_state_path(root=root, env=env)
dashboard_host, dashboard_port = _resolve_dashboard_bind(root=root, env=env)
requested_port = _resolve_effective_dashboard_port(env=env, fallback=dashboard_port)
dashboard_port = _select_available_port(
host=_normalize_dashboard_bind_host(dashboard_host),
preferred_port=requested_port,
)
env = dict(env)
env["HYDROPONICS_DASHBOARD_PORT"] = str(dashboard_port)
if int(dashboard_port) != int(requested_port):
sys.stdout.write(
f"[start] Dashboard port {requested_port} is in use; using {dashboard_port} instead.\n"
)
sys.stdout.flush()
dashboard_args = [
sys.executable,
"-m",
"hydroponics.web.server",
"--host",
str(dashboard_host),
"--port",
str(dashboard_port),
]
return launcher_supervisor.run_all(
root=root,
env=env,
dashboard_args=dashboard_args,
controller_args=controller_args,
dashboard_bind_host=dashboard_host,
dashboard_port=dashboard_port,
runtime_mode_path=runtime_mode_path,
spawn_child_process_fn=_spawn_child_process,
relay_process_output_fn=_relay_process_output,
terminate_process_fn=_terminate_process,
wait_for_http_health_fn=_wait_for_http_health,
)
def _resolve_effective_dashboard_port(*, env: dict[str, str], fallback: int) -> int:
"""
Summary:
Resolve the effective dashboard TCP port after considering launcher overrides.
Inputs:
env: Environment dictionary provided to child processes.
fallback: Config-derived port to use when no override is present.
Outputs:
Effective port as an integer.
Side effects:
None.
Error handling:
Raises SystemExit if the override value is present but invalid.
Ties to other methods:
Used by _run_all to honor HYDROPONICS_DASHBOARD_PORT while keeping config defaults.
Why this exists:
The launcher may select a new port when collisions occur; that port must flow into the
dashboard server and health checks consistently.
"""
return launcher_dashboard.resolve_effective_dashboard_port(env=env, fallback=fallback)
def _normalize_dashboard_bind_host(host: str) -> str:
"""
Summary:
Normalize a dashboard bind host value for local port availability checks.
Inputs:
host: Bind host string from settings or launcher overrides.
Outputs:
Normalized host string suitable for socket bind checks.
Side effects:
None.
Error handling:
None.
Ties to other methods:
Used by _run_all and _select_available_port to avoid false negatives on localhost aliases.
Why this exists:
Hostnames like "localhost" can resolve to IPv6 on some systems; binding explicitly to
loopback provides consistent collision detection.
"""
return launcher_dashboard.normalize_dashboard_bind_host(host)
def _normalize_dashboard_health_host(host: str) -> str:
"""
Summary:
Select a host value that can be used to reach the dashboard health endpoint locally.
Inputs:
host: Bind host string used by the dashboard server.
Outputs:
Host string suitable for TCP connections.
Side effects:
None.
Error handling:
None.
Ties to other methods:
Used by _run_all to wait for /api/health after binding to wildcard interfaces.
Why this exists:
When binding to 0.0.0.0 or ::, the server is reachable on loopback; the launcher should
connect via a loopback address rather than a wildcard.
"""
return launcher_dashboard.normalize_dashboard_health_host(host)
def _select_available_port(*, host: str, preferred_port: int, max_scan: int = 32) -> int:
"""
Summary:
Choose an available TCP port by scanning forward from a preferred starting port.
Inputs:
host: Host interface that will be used for the eventual bind.
preferred_port: First-choice port, typically from settings.json.
max_scan: Maximum number of additional ports to probe after the preferred port.
Outputs:
The first available TCP port number.
Side effects:
Probes port availability using TCP connect attempts.
Error handling:
Raises SystemExit if no available port is found within the scan range.
Ties to other methods:
Called by main and _run_all so `./start` can recover from port collisions automatically.
Why this exists:
Development environments frequently have stale dashboard instances running. The launcher
should start successfully without manual port edits or killing processes.
"""
return launcher_dashboard.select_available_port(
host=host,
preferred_port=preferred_port,
max_scan=max_scan,
is_listening_fn=_is_tcp_port_listening,
)
def _resolve_runtime_mode_state_path(*, root: Path, env: dict[str, str]) -> Path:
"""
Summary:
Resolve the runtime mode state file path based on settings.json.
Inputs:
root: Repository root directory.
env: Environment variables used to find HYDROPONICS_CONFIG_PATH.
Outputs:
Absolute Path to the runtime mode state file.
Side effects:
Reads settings.json from disk when available.
Error handling:
Raises SystemExit if settings.json cannot be read.
Ties to other methods:
Used by the start launcher to watch for in-GUI controller mode switches.
Why this exists:
The dashboard writes the desired mode to disk; the supervisor must observe the same file.
"""
return launcher_settings.resolve_runtime_mode_state_path(root=root, env=env)
def _resolve_dashboard_bind(*, root: Path, env: dict[str, str]) -> tuple[str, int]:
"""
Summary:
Resolve the dashboard bind host and port from settings.json without importing the registry.
Inputs:
root: Repository root directory.
env: Environment variables used to find HYDROPONICS_CONFIG_PATH.
Outputs:
Tuple of (host, port) for the dashboard server.
Side effects:
Reads settings.json from disk.
Error handling:
Raises SystemExit if settings.json cannot be read or dashboard fields are invalid.
Ties to other methods:
Used by the launcher to select bind details before starting subprocesses.
Why this exists:
If the dashboard cannot bind, the controller should not start and begin dosing.
"""
return launcher_dashboard.resolve_dashboard_bind(root=root, env=env)
def _is_tcp_port_listening(*, host: str, port: int) -> bool:
"""
Summary:
Check whether a TCP port is already listening.
Inputs:
host: Host to connect to (loopback recommended).
port: TCP port number.
Outputs:
True when a listener accepts connections, otherwise False.
Side effects:
Attempts a TCP connection.
Error handling:
None.
Ties to other methods:
Used by _select_available_port (tests may monkeypatch this predicate).
Why this exists:
Port conflicts are common during development, and starting the controller without the UI
is unsafe.
"""
return launcher_dashboard.is_tcp_port_listening(host=host, port=port)
def _wait_for_http_health(*, host: str, port: int, timeout_s: float = 2.5) -> bool:
"""
Summary:
Wait until the dashboard health endpoint responds successfully.
Inputs:
host: Host to connect to (loopback recommended).
port: Dashboard TCP port.
timeout_s: Maximum seconds to wait.
Outputs:
True when /api/health returns ok, otherwise False.
Side effects:
Performs repeated TCP connects and HTTP requests.
Error handling:
None.
Ties to other methods:
Used by the supervisor to ensure the dashboard is up before starting the controller.
Why this exists:
Avoids a window where the controller can begin dosing even though the UI failed to start.
"""
return launcher_dashboard.wait_for_http_health(host=host, port=port, timeout_s=timeout_s)
def _file_mtime_ns(path: Path) -> int:
"""
Summary:
Return a high-resolution mtime stamp for a file, or 0 when missing.
Inputs:
path: File path to check.
Outputs:
File mtime in nanoseconds, or 0 if the file does not exist.
Side effects:
Reads filesystem metadata.
Error handling:
Raises SystemExit if filesystem metadata cannot be read.
Ties to other methods:
Used by the supervisor loop to detect controller mode switch requests.
Why this exists:
Cheap change detection avoids polling JSON contents continuously.
"""
return launcher_runtime.file_mtime_ns(path)
def _read_runtime_mode_target(path: Path) -> str | None:
"""
Summary:
Read and validate the desired runtime mode from a persisted state file.
Inputs:
path: Runtime mode state file path.
Outputs:
"simulator" or "hardware" when valid, otherwise None.
Side effects:
Reads a JSON file when present.
Error handling:
None. Invalid files return None to avoid restart loops.
Ties to other methods:
Used by the supervisor loop to restart the system into simulator or hardware mode.
Why this exists:
A malformed file should not crash the supervisor or cause repeated restarts.
"""
return launcher_runtime.read_runtime_mode_target(path)
def _select_initial_runtime_mode(path: Path, *, env: dict[str, str]) -> str:
"""
Summary:
Select the initial runtime mode used for child process launches.
Inputs:
path: Runtime mode state file path.
env: Environment variables that may contain HYDROPONICS_SIM.
Outputs:
"simulator" or "hardware".
Side effects:
Reads the runtime mode state file when present.
Error handling:
None. Falls back to the current env mode when missing or invalid.
Ties to other methods:
Used by start._run_all before spawning subprocesses.
Why this exists:
The launcher should honor the last GUI-selected mode without requiring flags.
"""
_ = env
return launcher_runtime.select_initial_runtime_mode(path)
def _apply_runtime_mode(env: dict[str, str], mode: str) -> None:
"""
Summary:
Apply a runtime controller mode to an environment dictionary.
Inputs:
env: Environment dictionary for child processes.
mode: Target mode string ("simulator" or "hardware").
Outputs:
None.
Side effects:
Mutates the provided env dictionary.
Error handling:
Raises SystemExit if mode is not recognized.
Ties to other methods:
Used by the supervisor loop to switch child processes between simulator and hardware.
Why this exists:
Mode selection is implemented via HYDROPONICS_SIM, and must be applied consistently.
"""
launcher_runtime.apply_runtime_mode(env, mode)
def _check_hardware_support() -> tuple[bool, str | None]:
"""
Summary:
Determine whether the current host can run hardware controller mode safely.
Inputs:
None.
Outputs:
Tuple of (ok, reason). When ok is False, reason explains the limitation.
Side effects:
Reads platform metadata and checks import availability.
Error handling:
None.
Ties to other methods:
Used by _normalize_runtime_mode and runtime-mode selection.
Why this exists:
Hardware mode depends on Raspberry Pi specific drivers that are not present on most hosts.
"""
return launcher_runtime.check_hardware_support()
def _check_desktop_app_support() -> tuple[bool, str | None]:
"""
Summary:
Determine whether this host should prefer local-only UI mode for a desktop-style workflow.
Inputs:
None.
Outputs:
Tuple of (ok, reason). When ok is False, reason explains why web UI mode is preferred.
Side effects:
Reads platform metadata.
Error handling:
None.
Ties to other methods:
Used by main when --ui auto is selected to decide whether to inject loopback bind overrides.
Why this exists:
Raspberry Pi deployments commonly require LAN access, while desktop development should be
local-only by default for safety.
"""
return launcher_runtime.check_desktop_app_support()
def _read_linux_board_model() -> str | None:
"""
Summary:
Read the device model string for Linux systems that expose device-tree metadata.
Inputs:
None.
Outputs:
Device model string when available, otherwise None.
Side effects:
Reads platform-specific files when present.
Error handling:
None. Errors are treated as missing metadata to keep start-up safe.
Ties to other methods:
Used by _check_hardware_support to require a Raspberry Pi host for hardware mode.
Why this exists:
Hardware mode must be gated to Raspberry Pi only to prevent accidental pump activation on
other hosts.
"""
return launcher_runtime.read_linux_board_model()
def _write_runtime_mode_target(path: Path, *, mode: str) -> None:
"""
Summary:
Best-effort write of the runtime mode state file for supervisor recovery.
Inputs:
path: Runtime mode state file path.
mode: Target mode to persist ("simulator" or "hardware").
Outputs:
None.
Side effects:
Creates parent directories and writes a JSON state file.
Error handling:
None. Errors are ignored to avoid breaking start-up.
Ties to other methods:
Used by _normalize_runtime_mode when self-healing persisted state.
Why this exists:
Keeping the file consistent prevents the GUI from showing a perpetual restart pending state.
"""
launcher_runtime.write_runtime_mode_target(path, mode=mode)
def _normalize_runtime_mode(mode: str, *, runtime_mode_path: Path | None) -> str:
"""
Summary:
Normalize a requested runtime mode to something safe for the current host.
Inputs:
mode: Desired mode value.
runtime_mode_path: Optional runtime mode state file path to self-heal.
Outputs:
Safe mode string ("simulator" or "hardware").
Side effects:
May rewrite the runtime mode state file when an unsupported hardware request is detected.
Error handling:
None.
Ties to other methods:
Used by the supervisor loop for initial mode selection and live mode switches.
Why this exists:
Accidentally persisting hardware mode on a laptop should not brick the one-command launcher.
"""
return launcher_runtime.normalize_runtime_mode(mode, runtime_mode_path=runtime_mode_path)
def main(argv: list[str] | None = None) -> int:
"""
Summary:
Provide an extremely simple launcher for dashboard and controller operation.
Inputs:
argv: Optional argument list override for testing or embedding.
Outputs:
Exit code from the selected subprocess.
Side effects:
Runs the dashboard server, controller loop, or both in child processes.
Error handling:
Raises SystemExit if argument parsing or process launch fails.
Ties to other methods:
Intended to be called via `./start`, `Start.command`, or `python3 start.py`.
Why this exists:
A single, predictable entrypoint reduces friction for daily operation and demos.
"""
_ensure_python_version()
root = _repo_root()
parser = launcher_cli.build_parser(prog="start")
parsed = parser.parse_args(argv)
env = dict(os.environ)
config_path = _validate_config_path(parsed.config)
if config_path:
env["HYDROPONICS_CONFIG_PATH"] = config_path
launcher_env.apply_ui_mode_overrides(
env=env,
ui_mode=str(parsed.ui),
root=root,
check_desktop_support_fn=_check_desktop_app_support,
resolve_dashboard_bind_fn=_resolve_dashboard_bind,
select_available_port_fn=_select_available_port,
)
requested_mode = "hardware" if parsed.no_sim else str(parsed.mode or "auto")
runtime_mode_path = _resolve_runtime_mode_state_path(root=root, env=env)
if requested_mode in ("simulator", "hardware"):
normalized = _normalize_runtime_mode(requested_mode, runtime_mode_path=runtime_mode_path)
_apply_runtime_mode(env, normalized)
_write_runtime_mode_target(runtime_mode_path, mode=normalized)
return _run_all(root=root, env=env, passthrough=[])
if __name__ == "__main__":
raise SystemExit(main())