lager-cli 0.60.0__tar.gz → 0.61.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (161) hide show
  1. {lager_cli-0.60.0/lager_cli.egg-info → lager_cli-0.61.0}/PKG-INFO +1 -1
  2. {lager_cli-0.60.0 → lager_cli-0.61.0}/__init__.py +1 -1
  3. {lager_cli-0.60.0 → lager_cli-0.61.0}/box_storage.py +35 -0
  4. {lager_cli-0.60.0 → lager_cli-0.61.0}/commands/box/diagnose.py +5 -1
  5. {lager_cli-0.60.0 → lager_cli-0.61.0}/commands/box/nets.py +2 -0
  6. lager_cli-0.61.0/commands/communication/wifi.py +405 -0
  7. {lager_cli-0.60.0 → lager_cli-0.61.0}/commands/development/debug/commands.py +53 -16
  8. {lager_cli-0.60.0 → lager_cli-0.61.0}/commands/measurement/scope.py +1 -1
  9. {lager_cli-0.60.0 → lager_cli-0.61.0}/context/session.py +5 -3
  10. {lager_cli-0.60.0 → lager_cli-0.61.0}/gateway_auth.py +45 -2
  11. {lager_cli-0.60.0 → lager_cli-0.61.0/lager_cli.egg-info}/PKG-INFO +1 -1
  12. lager_cli-0.60.0/commands/communication/wifi.py +0 -210
  13. {lager_cli-0.60.0 → lager_cli-0.61.0}/LICENSE +0 -0
  14. {lager_cli-0.60.0 → lager_cli-0.61.0}/MANIFEST.in +0 -0
  15. {lager_cli-0.60.0 → lager_cli-0.61.0}/NOTICE +0 -0
  16. {lager_cli-0.60.0 → lager_cli-0.61.0}/README.md +0 -0
  17. {lager_cli-0.60.0 → lager_cli-0.61.0}/__main__.py +0 -0
  18. {lager_cli-0.60.0 → lager_cli-0.61.0}/address_utils.py +0 -0
  19. {lager_cli-0.60.0 → lager_cli-0.61.0}/battery/__init__.py +0 -0
  20. {lager_cli-0.60.0 → lager_cli-0.61.0}/battery/battery_tui.py +0 -0
  21. {lager_cli-0.60.0 → lager_cli-0.61.0}/battery/websocket_client.py +0 -0
  22. {lager_cli-0.60.0 → lager_cli-0.61.0}/commands/__init__.py +0 -0
  23. {lager_cli-0.60.0 → lager_cli-0.61.0}/commands/box/__init__.py +0 -0
  24. {lager_cli-0.60.0 → lager_cli-0.61.0}/commands/box/_device_identity.py +0 -0
  25. {lager_cli-0.60.0 → lager_cli-0.61.0}/commands/box/_gateway.py +0 -0
  26. {lager_cli-0.60.0 → lager_cli-0.61.0}/commands/box/_host_ops.py +0 -0
  27. {lager_cli-0.60.0 → lager_cli-0.61.0}/commands/box/_mount_prep.py +0 -0
  28. {lager_cli-0.60.0 → lager_cli-0.61.0}/commands/box/_net_preflight.py +0 -0
  29. {lager_cli-0.60.0 → lager_cli-0.61.0}/commands/box/_pip_validation.py +0 -0
  30. {lager_cli-0.60.0 → lager_cli-0.61.0}/commands/box/_shim_verbs.py +0 -0
  31. {lager_cli-0.60.0 → lager_cli-0.61.0}/commands/box/_ssh.py +0 -0
  32. {lager_cli-0.60.0 → lager_cli-0.61.0}/commands/box/bench.py +0 -0
  33. {lager_cli-0.60.0 → lager_cli-0.61.0}/commands/box/box_group.py +0 -0
  34. {lager_cli-0.60.0 → lager_cli-0.61.0}/commands/box/boxes.py +0 -0
  35. {lager_cli-0.60.0 → lager_cli-0.61.0}/commands/box/config.py +0 -0
  36. {lager_cli-0.60.0 → lager_cli-0.61.0}/commands/box/drivers.py +0 -0
  37. {lager_cli-0.60.0 → lager_cli-0.61.0}/commands/box/dut.py +0 -0
  38. {lager_cli-0.60.0 → lager_cli-0.61.0}/commands/box/hello.py +0 -0
  39. {lager_cli-0.60.0 → lager_cli-0.61.0}/commands/box/instruments.py +0 -0
  40. {lager_cli-0.60.0 → lager_cli-0.61.0}/commands/box/labjack_pins.py +0 -0
  41. {lager_cli-0.60.0 → lager_cli-0.61.0}/commands/box/lock.py +0 -0
  42. {lager_cli-0.60.0 → lager_cli-0.61.0}/commands/box/net_tui.py +0 -0
  43. {lager_cli-0.60.0 → lager_cli-0.61.0}/commands/box/ssh.py +0 -0
  44. {lager_cli-0.60.0 → lager_cli-0.61.0}/commands/box/ssh_setup.py +0 -0
  45. {lager_cli-0.60.0 → lager_cli-0.61.0}/commands/communication/__init__.py +0 -0
  46. {lager_cli-0.60.0 → lager_cli-0.61.0}/commands/communication/ble.py +0 -0
  47. {lager_cli-0.60.0 → lager_cli-0.61.0}/commands/communication/blufi.py +0 -0
  48. {lager_cli-0.60.0 → lager_cli-0.61.0}/commands/communication/i2c.py +0 -0
  49. {lager_cli-0.60.0 → lager_cli-0.61.0}/commands/communication/router.py +0 -0
  50. {lager_cli-0.60.0 → lager_cli-0.61.0}/commands/communication/spi.py +0 -0
  51. {lager_cli-0.60.0 → lager_cli-0.61.0}/commands/communication/uart.py +0 -0
  52. {lager_cli-0.60.0 → lager_cli-0.61.0}/commands/communication/usb.py +0 -0
  53. {lager_cli-0.60.0 → lager_cli-0.61.0}/commands/communication/websocket_client.py +0 -0
  54. {lager_cli-0.60.0 → lager_cli-0.61.0}/commands/custom.py +0 -0
  55. {lager_cli-0.60.0 → lager_cli-0.61.0}/commands/development/__init__.py +0 -0
  56. {lager_cli-0.60.0 → lager_cli-0.61.0}/commands/development/arm.py +0 -0
  57. {lager_cli-0.60.0 → lager_cli-0.61.0}/commands/development/debug/__init__.py +0 -0
  58. {lager_cli-0.60.0 → lager_cli-0.61.0}/commands/development/debug/net_cache.py +0 -0
  59. {lager_cli-0.60.0 → lager_cli-0.61.0}/commands/development/debug/rtt_websocket_client.py +0 -0
  60. {lager_cli-0.60.0 → lager_cli-0.61.0}/commands/development/debug/service_client.py +0 -0
  61. {lager_cli-0.60.0 → lager_cli-0.61.0}/commands/development/debug/service_helper.py +0 -0
  62. {lager_cli-0.60.0 → lager_cli-0.61.0}/commands/development/debug/tunnel.py +0 -0
  63. {lager_cli-0.60.0 → lager_cli-0.61.0}/commands/development/devenv.py +0 -0
  64. {lager_cli-0.60.0 → lager_cli-0.61.0}/commands/development/python.py +0 -0
  65. {lager_cli-0.60.0 → lager_cli-0.61.0}/commands/measurement/__init__.py +0 -0
  66. {lager_cli-0.60.0 → lager_cli-0.61.0}/commands/measurement/adc.py +0 -0
  67. {lager_cli-0.60.0 → lager_cli-0.61.0}/commands/measurement/dac.py +0 -0
  68. {lager_cli-0.60.0 → lager_cli-0.61.0}/commands/measurement/energy.py +0 -0
  69. {lager_cli-0.60.0 → lager_cli-0.61.0}/commands/measurement/gpi.py +0 -0
  70. {lager_cli-0.60.0 → lager_cli-0.61.0}/commands/measurement/gpo.py +0 -0
  71. {lager_cli-0.60.0 → lager_cli-0.61.0}/commands/measurement/logic.py +0 -0
  72. {lager_cli-0.60.0 → lager_cli-0.61.0}/commands/measurement/thermocouple.py +0 -0
  73. {lager_cli-0.60.0 → lager_cli-0.61.0}/commands/measurement/watt.py +0 -0
  74. {lager_cli-0.60.0 → lager_cli-0.61.0}/commands/power/__init__.py +0 -0
  75. {lager_cli-0.60.0 → lager_cli-0.61.0}/commands/power/battery.py +0 -0
  76. {lager_cli-0.60.0 → lager_cli-0.61.0}/commands/power/battery_model_csv.py +0 -0
  77. {lager_cli-0.60.0 → lager_cli-0.61.0}/commands/power/eload.py +0 -0
  78. {lager_cli-0.60.0 → lager_cli-0.61.0}/commands/power/solar.py +0 -0
  79. {lager_cli-0.60.0 → lager_cli-0.61.0}/commands/power/supply.py +0 -0
  80. {lager_cli-0.60.0 → lager_cli-0.61.0}/commands/security/__init__.py +0 -0
  81. {lager_cli-0.60.0 → lager_cli-0.61.0}/commands/security/hsm.py +0 -0
  82. {lager_cli-0.60.0 → lager_cli-0.61.0}/commands/utility/__init__.py +0 -0
  83. {lager_cli-0.60.0 → lager_cli-0.61.0}/commands/utility/_host_cli.py +0 -0
  84. {lager_cli-0.60.0 → lager_cli-0.61.0}/commands/utility/binaries.py +0 -0
  85. {lager_cli-0.60.0 → lager_cli-0.61.0}/commands/utility/defaults.py +0 -0
  86. {lager_cli-0.60.0 → lager_cli-0.61.0}/commands/utility/exec_.py +0 -0
  87. {lager_cli-0.60.0 → lager_cli-0.61.0}/commands/utility/install.py +0 -0
  88. {lager_cli-0.60.0 → lager_cli-0.61.0}/commands/utility/install_wheel.py +0 -0
  89. {lager_cli-0.60.0 → lager_cli-0.61.0}/commands/utility/login.py +0 -0
  90. {lager_cli-0.60.0 → lager_cli-0.61.0}/commands/utility/logs.py +0 -0
  91. {lager_cli-0.60.0 → lager_cli-0.61.0}/commands/utility/uninstall.py +0 -0
  92. {lager_cli-0.60.0 → lager_cli-0.61.0}/commands/utility/update.py +0 -0
  93. {lager_cli-0.60.0 → lager_cli-0.61.0}/commands/utility/webcam.py +0 -0
  94. {lager_cli-0.60.0 → lager_cli-0.61.0}/config.py +0 -0
  95. {lager_cli-0.60.0 → lager_cli-0.61.0}/context/__init__.py +0 -0
  96. {lager_cli-0.60.0 → lager_cli-0.61.0}/context/ci_detection.py +0 -0
  97. {lager_cli-0.60.0 → lager_cli-0.61.0}/context/constants.py +0 -0
  98. {lager_cli-0.60.0 → lager_cli-0.61.0}/context/core.py +0 -0
  99. {lager_cli-0.60.0 → lager_cli-0.61.0}/context/error_handlers.py +0 -0
  100. {lager_cli-0.60.0 → lager_cli-0.61.0}/core/__init__.py +0 -0
  101. {lager_cli-0.60.0 → lager_cli-0.61.0}/core/custom_drivers.py +0 -0
  102. {lager_cli-0.60.0 → lager_cli-0.61.0}/core/group_usage.py +0 -0
  103. {lager_cli-0.60.0 → lager_cli-0.61.0}/core/matchers.py +0 -0
  104. {lager_cli-0.60.0 → lager_cli-0.61.0}/core/net_group.py +0 -0
  105. {lager_cli-0.60.0 → lager_cli-0.61.0}/core/net_helpers.py +0 -0
  106. {lager_cli-0.60.0 → lager_cli-0.61.0}/core/net_storage.py +0 -0
  107. {lager_cli-0.60.0 → lager_cli-0.61.0}/core/param_types.py +0 -0
  108. {lager_cli-0.60.0 → lager_cli-0.61.0}/core/ssh_utils.py +0 -0
  109. {lager_cli-0.60.0 → lager_cli-0.61.0}/core/tui_keys.py +0 -0
  110. {lager_cli-0.60.0 → lager_cli-0.61.0}/core/tui_ws_bridge.py +0 -0
  111. {lager_cli-0.60.0 → lager_cli-0.61.0}/core/utils.py +0 -0
  112. {lager_cli-0.60.0 → lager_cli-0.61.0}/core/version_skew.py +0 -0
  113. {lager_cli-0.60.0 → lager_cli-0.61.0}/core/ws_diagnose.py +0 -0
  114. {lager_cli-0.60.0 → lager_cli-0.61.0}/deployment/__init__.py +0 -0
  115. {lager_cli-0.60.0 → lager_cli-0.61.0}/deployment/scripts/__init__.py +0 -0
  116. {lager_cli-0.60.0 → lager_cli-0.61.0}/deployment/scripts/configure_docker_dns.py +0 -0
  117. {lager_cli-0.60.0 → lager_cli-0.61.0}/deployment/scripts/configure_docker_dns.sh +0 -0
  118. {lager_cli-0.60.0 → lager_cli-0.61.0}/deployment/scripts/convert_to_sparse_checkout.sh +0 -0
  119. {lager_cli-0.60.0 → lager_cli-0.61.0}/deployment/scripts/setup_and_deploy_box.sh +0 -0
  120. {lager_cli-0.60.0 → lager_cli-0.61.0}/deployment/scripts/setup_ssh_key.sh +0 -0
  121. {lager_cli-0.60.0 → lager_cli-0.61.0}/deployment/security/__init__.py +0 -0
  122. {lager_cli-0.60.0 → lager_cli-0.61.0}/deployment/security/etc_lager_perms.sh +0 -0
  123. {lager_cli-0.60.0 → lager_cli-0.61.0}/deployment/security/secure_box_firewall.sh +0 -0
  124. {lager_cli-0.60.0 → lager_cli-0.61.0}/errors.py +0 -0
  125. {lager_cli-0.60.0 → lager_cli-0.61.0}/exceptions.py +0 -0
  126. {lager_cli-0.60.0 → lager_cli-0.61.0}/gateway_tunnel.py +0 -0
  127. {lager_cli-0.60.0 → lager_cli-0.61.0}/impl/__init__.py +0 -0
  128. {lager_cli-0.60.0 → lager_cli-0.61.0}/impl/box_config.py +0 -0
  129. {lager_cli-0.60.0 → lager_cli-0.61.0}/impl/measurement/__init__.py +0 -0
  130. {lager_cli-0.60.0 → lager_cli-0.61.0}/impl/measurement/scope.py +0 -0
  131. {lager_cli-0.60.0 → lager_cli-0.61.0}/impl/measurement/scope_stream.py +0 -0
  132. {lager_cli-0.60.0 → lager_cli-0.61.0}/impl/power/__init__.py +0 -0
  133. {lager_cli-0.60.0 → lager_cli-0.61.0}/impl/power/enable_disable.py +0 -0
  134. {lager_cli-0.60.0 → lager_cli-0.61.0}/lager_cli.egg-info/SOURCES.txt +0 -0
  135. {lager_cli-0.60.0 → lager_cli-0.61.0}/lager_cli.egg-info/dependency_links.txt +0 -0
  136. {lager_cli-0.60.0 → lager_cli-0.61.0}/lager_cli.egg-info/entry_points.txt +0 -0
  137. {lager_cli-0.60.0 → lager_cli-0.61.0}/lager_cli.egg-info/requires.txt +0 -0
  138. {lager_cli-0.60.0 → lager_cli-0.61.0}/lager_cli.egg-info/top_level.txt +0 -0
  139. {lager_cli-0.60.0 → lager_cli-0.61.0}/main.py +0 -0
  140. {lager_cli-0.60.0 → lager_cli-0.61.0}/pyproject.toml +0 -0
  141. {lager_cli-0.60.0 → lager_cli-0.61.0}/run_record.py +0 -0
  142. {lager_cli-0.60.0 → lager_cli-0.61.0}/safe_unpickle.py +0 -0
  143. {lager_cli-0.60.0 → lager_cli-0.61.0}/setup.cfg +0 -0
  144. {lager_cli-0.60.0 → lager_cli-0.61.0}/setup.py +0 -0
  145. {lager_cli-0.60.0 → lager_cli-0.61.0}/simple_hdlc.py +0 -0
  146. {lager_cli-0.60.0 → lager_cli-0.61.0}/sort_utils.py +0 -0
  147. {lager_cli-0.60.0 → lager_cli-0.61.0}/status.py +0 -0
  148. {lager_cli-0.60.0 → lager_cli-0.61.0}/supply/__init__.py +0 -0
  149. {lager_cli-0.60.0 → lager_cli-0.61.0}/supply/supply_tui.py +0 -0
  150. {lager_cli-0.60.0 → lager_cli-0.61.0}/supply/websocket_client.py +0 -0
  151. {lager_cli-0.60.0 → lager_cli-0.61.0}/terminal/__init__.py +0 -0
  152. {lager_cli-0.60.0 → lager_cli-0.61.0}/terminal/core/__init__.py +0 -0
  153. {lager_cli-0.60.0 → lager_cli-0.61.0}/terminal/core/executor.py +0 -0
  154. {lager_cli-0.60.0 → lager_cli-0.61.0}/terminal/main.py +0 -0
  155. {lager_cli-0.60.0 → lager_cli-0.61.0}/terminal/ui/__init__.py +0 -0
  156. {lager_cli-0.60.0 → lager_cli-0.61.0}/terminal/ui/completer.py +0 -0
  157. {lager_cli-0.60.0 → lager_cli-0.61.0}/terminal/ui/display.py +0 -0
  158. {lager_cli-0.60.0 → lager_cli-0.61.0}/terminal/ui/logo.py +0 -0
  159. {lager_cli-0.60.0 → lager_cli-0.61.0}/terminal/ui/repl.py +0 -0
  160. {lager_cli-0.60.0 → lager_cli-0.61.0}/terminal/ui/themes.py +0 -0
  161. {lager_cli-0.60.0 → lager_cli-0.61.0}/update_check.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: lager-cli
3
- Version: 0.60.0
3
+ Version: 0.61.0
4
4
  Summary: Lager CLI - Box and Docker connectivity
5
5
  Home-page: https://github.com/lagerdata/lager
6
6
  Author: Lager Data
@@ -7,4 +7,4 @@ Lager CLI
7
7
  A Command Line Interface for Lager Data
8
8
  """
9
9
 
10
- __version__ = '0.60.0'
10
+ __version__ = '0.61.0'
@@ -1202,6 +1202,39 @@ import contextlib as _contextlib_for_lock
1202
1202
  import threading as _threading_for_heartbeat
1203
1203
 
1204
1204
 
1205
+ def _exit_cleanly_on_terminate():
1206
+ """Make SIGTERM and SIGHUP run this process's lock release.
1207
+
1208
+ Python's default action for both kills the process without running
1209
+ ``finally`` blocks or ``atexit`` handlers, so a lock taken by a command
1210
+ that is stopped with a plain ``kill`` stayed held until its TTL ran out.
1211
+ A test that backgrounds `lager debug ... gdbserver` and later kills it
1212
+ left its CI job's lock held that way. Raising ``SystemExit`` instead
1213
+ unwinds normally, so the release runs. The exit status is the shell's
1214
+ ``128 + signal``, the same one the default action reports.
1215
+
1216
+ A handler someone else installed is left alone, and so is a call off the
1217
+ main thread, where Python cannot install one.
1218
+ """
1219
+ import signal
1220
+
1221
+ if _threading_for_heartbeat.current_thread() is not _threading_for_heartbeat.main_thread():
1222
+ return
1223
+
1224
+ def _raise_exit(signum, _frame):
1225
+ raise SystemExit(128 + signum)
1226
+
1227
+ for name in ('SIGTERM', 'SIGHUP'):
1228
+ signum = getattr(signal, name, None)
1229
+ if signum is None:
1230
+ continue
1231
+ try:
1232
+ if signal.getsignal(signum) is signal.SIG_DFL:
1233
+ signal.signal(signum, _raise_exit)
1234
+ except (OSError, ValueError):
1235
+ pass
1236
+
1237
+
1205
1238
  class HeartbeatThread(_threading_for_heartbeat.Thread):
1206
1239
  """Refreshes the box lock periodically while a command is running.
1207
1240
 
@@ -1653,6 +1686,7 @@ def auto_lock_around_command(
1653
1686
  # actually hold the lock — no surprise release of someone
1654
1687
  # else's lock at interpreter shutdown.
1655
1688
  _atexit.register(_safe_release)
1689
+ _exit_cleanly_on_terminate()
1656
1690
 
1657
1691
  heartbeat = None
1658
1692
  # Heartbeat whenever the lock we're running under has a TTL: locks
@@ -1864,6 +1898,7 @@ def auto_lock_acquire_for_command(
1864
1898
 
1865
1899
  if should_release:
1866
1900
  _atexit.register(_release)
1901
+ _exit_cleanly_on_terminate()
1867
1902
  if resolved_ttl is not None:
1868
1903
  heartbeat = HeartbeatThread(
1869
1904
  ip,
@@ -456,10 +456,14 @@ def _fmt_usbhub_lines(d: dict):
456
456
 
457
457
  def _classify_usb_hub(d: dict):
458
458
  """(colour, headline) for a USB hub net. Most specific first."""
459
- if d.get('unavailable') or d.get('transport_error'):
459
+ if d.get('unavailable'):
460
460
  return ('yellow',
461
461
  'UNCLEAR — this box does not serve /diagnose/usbhub. '
462
462
  'Update the box to diagnose hub nets.')
463
+ # A timeout or 5xx says nothing about the box's version: only a 404
464
+ # (`unavailable`) means the endpoint is missing.
465
+ if d.get('transport_error'):
466
+ return ('red', f'Could not reach the USB hub diagnose endpoint: {d["transport_error"]}')
463
467
 
464
468
  if d.get('enumerated') is False:
465
469
  return ('red',
@@ -573,6 +573,7 @@ INSTRUMENT_NET_MAP: dict[str, list[str]] = {
573
573
  "Acroname_8Port": ["usb"],
574
574
  "Acroname_4Port": ["usb"],
575
575
  "YKUSH_Hub": ["usb"],
576
+ "YKUSH3_Hub": ["usb", "gpio"],
576
577
  "Plugable_USB_Hub": ["usb"],
577
578
 
578
579
  # eload
@@ -591,6 +592,7 @@ INSTRUMENT_NET_MAP: dict[str, list[str]] = {
591
592
  "Logitech_C270": ["webcam"],
592
593
  "Logitech_StreamCam": ["webcam"],
593
594
  "ELP_Global_Shutter_AR0234": ["webcam"],
595
+ "IPEVO_V4K_PRO": ["webcam"],
594
596
 
595
597
  # (robot) arm
596
598
  "Rotrix_Dexarm": ["arm"],
@@ -0,0 +1,405 @@
1
+ # Copyright 2024-2026 Lager Data
2
+ # SPDX-License-Identifier: Apache-2.0
3
+
4
+ """
5
+ lager.wifi.commands
6
+
7
+ Commands for controlling WiFi
8
+ """
9
+ from __future__ import annotations
10
+
11
+ import json
12
+ import re
13
+ import shlex
14
+
15
+ import click
16
+
17
+ # Import consolidated helpers from cli.core.net_helpers
18
+ from ...core.group_usage import LagerGroup
19
+ from ...core.net_helpers import resolve_box, resolve_box_locked, post_box_command
20
+ from ...errors import LagerError, ssh_error
21
+ from ..box._ssh import default_ssh_runner, resolve_box_user, strip_ssh_banner
22
+
23
+ # WiFi constraints
24
+ MAX_SSID_LENGTH = 32 # IEEE 802.11 maximum SSID length
25
+ MIN_WPA_PASSWORD_LENGTH = 8 # WPA/WPA2 minimum passphrase length
26
+ MAX_WPA_PASSWORD_LENGTH = 63 # WPA/WPA2 maximum passphrase length
27
+
28
+ # Common wireless interface names
29
+ COMMON_INTERFACES = ['wlan0', 'wlan1', 'wlp2s0', 'wlp3s0', 'wifi0']
30
+
31
+
32
+ def _validate_ssid(ctx: click.Context, ssid: str) -> None:
33
+ """Validate SSID format and length."""
34
+ if not ssid:
35
+ click.secho("Error: SSID cannot be empty", fg='red', err=True)
36
+ ctx.exit(1)
37
+
38
+ if len(ssid) > MAX_SSID_LENGTH:
39
+ click.secho(f"Error: SSID too long ({len(ssid)} characters)", fg='red', err=True)
40
+ click.secho(f"Maximum SSID length is {MAX_SSID_LENGTH} characters.", err=True)
41
+ ctx.exit(1)
42
+
43
+ # Check for non-printable characters
44
+ if not ssid.isprintable():
45
+ click.secho("Error: SSID contains non-printable characters", fg='red', err=True)
46
+ ctx.exit(1)
47
+
48
+
49
+ def _validate_password(ctx: click.Context, password: str) -> None:
50
+ """Validate WPA/WPA2 password length (if provided)."""
51
+ if not password:
52
+ return # Empty password is allowed for open networks
53
+
54
+ if len(password) < MIN_WPA_PASSWORD_LENGTH:
55
+ click.secho(f"Error: Password too short ({len(password)} characters)", fg='red', err=True)
56
+ click.secho(f"WPA/WPA2 passwords must be at least {MIN_WPA_PASSWORD_LENGTH} characters.", err=True)
57
+ ctx.exit(1)
58
+
59
+ if len(password) > MAX_WPA_PASSWORD_LENGTH:
60
+ click.secho(f"Error: Password too long ({len(password)} characters)", fg='red', err=True)
61
+ click.secho(f"WPA/WPA2 passwords can be at most {MAX_WPA_PASSWORD_LENGTH} characters.", err=True)
62
+ ctx.exit(1)
63
+
64
+
65
+ def _validate_interface(ctx: click.Context, interface: str) -> None:
66
+ """Validate wireless interface name format."""
67
+ if not interface:
68
+ click.secho("Error: Interface name cannot be empty", fg='red', err=True)
69
+ ctx.exit(1)
70
+
71
+ # Interface names should be alphanumeric and not too long
72
+ if len(interface) > 15: # Linux IFNAMSIZ - 1
73
+ click.secho(f"Error: Interface name too long: {interface}", fg='red', err=True)
74
+ click.secho("Interface names must be 15 characters or less.", err=True)
75
+ ctx.exit(1)
76
+
77
+ # Warn if using non-standard interface name
78
+ if interface not in COMMON_INTERFACES and not interface.startswith('wl'):
79
+ click.secho(f"Note: '{interface}' is not a common wireless interface name.", fg='yellow', err=True)
80
+ click.secho(f"Common names: {', '.join(COMMON_INTERFACES)}", err=True)
81
+
82
+
83
+ # nmcli connect can take up to ~30s on the box, plus scan latency.
84
+ _WIFI_HTTP_TIMEOUT = 60.0
85
+
86
+
87
+ def _post_wifi(ctx: click.Context, box_ip: str, action: str, **params) -> dict:
88
+ """POST one action to :9000/wifi/command and return the response."""
89
+ return post_box_command(
90
+ ctx, box_ip, "/wifi/command", action,
91
+ quiet=True, http_timeout=_WIFI_HTTP_TIMEOUT, **params,
92
+ )
93
+
94
+
95
+ def _format_networks_table(networks: list[dict]) -> str:
96
+ """Format scan results in the same table shape the old impl printed."""
97
+ if not networks:
98
+ return "No networks found!"
99
+
100
+ lines = []
101
+ lines.append(f"{'SSID':<25} {'Security':<10} {'Strength'}")
102
+ lines.append("-" * 50)
103
+ for net in networks:
104
+ ssid = (net.get('ssid') or 'Unknown')[:24]
105
+ security = net.get('security', 'Unknown')
106
+ strength = net.get('strength', 0)
107
+ lines.append(f"{ssid:<25} {security:<10} {strength}%")
108
+ return '\n'.join(lines)
109
+
110
+
111
+ # `status` and `access-points` read the box host's Wi-Fi over SSH. The lager
112
+ # container cannot: on its default network it has no view of the host's
113
+ # wireless interface, and the image has no nmcli, so both lookups failed there
114
+ # and `status` still exited 0. They only read, so they take no box lock.
115
+ #
116
+ # Every source is read as the box's SSH user, without root, and each is
117
+ # optional. sysfs names the wireless interfaces on any Linux host;
118
+ # networkctl (systemd-networkd, the box install's default), nmcli
119
+ # (NetworkManager) and iw add the state and the SSID where present.
120
+ _HOST_SSH_TIMEOUT = 45
121
+
122
+ _MISSING = '!missing'
123
+
124
+ _WIRELESS_IFACES = (
125
+ 'for d in /sys/class/net/*/wireless; do [ -e "$d" ] || continue; '
126
+ 'basename "$(dirname "$d")"; done'
127
+ )
128
+
129
+ _STATUS_SCRIPT = (
130
+ "echo '--wireless--'; "
131
+ f"for i in $({_WIRELESS_IFACES}); do echo \"$i $(cat /sys/class/net/$i/operstate)\"; done; "
132
+ "echo '--networkctl--'; "
133
+ "if command -v networkctl >/dev/null 2>&1; then "
134
+ f"for i in $({_WIRELESS_IFACES}); do echo \"@$i\"; "
135
+ "networkctl status \"$i\" --no-pager 2>/dev/null | grep -E '^ *(State|Wi-?Fi access point):'; done; "
136
+ f"else echo '{_MISSING}'; fi; "
137
+ "echo '--nmcli--'; "
138
+ f"nmcli -t -f DEVICE,TYPE,STATE,CONNECTION device status 2>/dev/null || echo '{_MISSING}'; "
139
+ "echo '--iw--'; "
140
+ f"iw dev 2>/dev/null || echo '{_MISSING}'"
141
+ )
142
+
143
+ _SECTIONS = ('wireless', 'networkctl', 'nmcli', 'iw')
144
+
145
+ _NMCLI_STATES = {
146
+ 'connected': 'Connected',
147
+ 'disconnected': 'Disconnected',
148
+ 'unavailable': 'Unavailable (radio off or no driver)',
149
+ 'unmanaged': 'Not managed by NetworkManager',
150
+ }
151
+
152
+
153
+ def _nmcli_fields(line: str) -> list[str]:
154
+ """Split one `nmcli -t` line on its unescaped colons."""
155
+ return [f.replace('\\:', ':').replace('\\\\', '\\')
156
+ for f in re.split(r'(?<!\\):', line)]
157
+
158
+
159
+ def _parse_host_status(out: str) -> tuple[dict, bool]:
160
+ """Turn the status script's output into interfaces, and whether it ran.
161
+
162
+ sysfs lists the interfaces and whether each is up. The SSID comes from
163
+ `iw dev` or networkctl; nmcli knows only a connection name, which need
164
+ not match it, so that is the last resort.
165
+ """
166
+ sections, current = {}, None
167
+ for line in out.splitlines():
168
+ marker = line.strip('-')
169
+ if line.startswith('--') and marker in _SECTIONS:
170
+ current = marker
171
+ sections[current] = []
172
+ elif current is not None:
173
+ sections[current].append(line)
174
+
175
+ interfaces = {}
176
+
177
+ def _iface(name):
178
+ return interfaces.setdefault(name, {
179
+ 'interface': name, 'ssid': 'Not Connected', 'state': 'Disconnected'})
180
+
181
+ for line in sections.get('wireless', []):
182
+ words = line.split()
183
+ if not words:
184
+ continue
185
+ info = _iface(words[0])
186
+ if len(words) > 1 and words[1] == 'up':
187
+ info['state'] = 'Up'
188
+ info['ssid'] = 'Unknown'
189
+
190
+ networkctl = sections.get('networkctl', [_MISSING])
191
+ if _MISSING not in networkctl:
192
+ name = None
193
+ for line in networkctl:
194
+ if line.startswith('@'):
195
+ name = line[1:].strip()
196
+ continue
197
+ key, _, value = line.strip().partition(':')
198
+ if not name or not value:
199
+ continue
200
+ value = value.strip()
201
+ if key in ('WiFi access point', 'Wi-Fi access point'):
202
+ info = _iface(name)
203
+ info['ssid'] = re.sub(r'\s*\([0-9a-fA-F:]{17}\)$', '', value)
204
+ info['state'] = 'Connected'
205
+ elif key == 'State' and value.split(' ')[0] in ('no-carrier', 'off', 'dormant'):
206
+ info = _iface(name)
207
+ if info['state'] != 'Connected':
208
+ info['state'], info['ssid'] = 'Disconnected', 'Not Connected'
209
+
210
+ iw = sections.get('iw', [_MISSING])
211
+ if _MISSING not in iw:
212
+ name = None
213
+ for line in iw:
214
+ words = line.split()
215
+ if len(words) >= 2 and words[0] == 'Interface':
216
+ name = words[1]
217
+ _iface(name)
218
+ elif name and len(words) >= 2 and words[0] == 'ssid':
219
+ interfaces[name]['ssid'] = line.strip()[len('ssid '):]
220
+ interfaces[name]['state'] = 'Connected'
221
+
222
+ nmcli = sections.get('nmcli', [_MISSING])
223
+ if _MISSING not in nmcli:
224
+ for line in nmcli:
225
+ fields = _nmcli_fields(line)
226
+ if len(fields) < 4 or fields[1] != 'wifi':
227
+ continue
228
+ device, _type, state, connection = fields[:4]
229
+ info = _iface(device)
230
+ base = state.split(' ')[0]
231
+ info['state'] = _NMCLI_STATES.get(base, state)
232
+ if base == 'connected' and info['ssid'] in ('Not Connected', 'Unknown') and connection:
233
+ info['ssid'] = connection
234
+ return interfaces, 'wireless' in sections
235
+
236
+
237
+ def _run_on_host(box_ip: str, cmd: str) -> tuple[int, str, str]:
238
+ """Run a read-only command on the box host; SSH's own failures exit here."""
239
+ rc, out, err = default_ssh_runner(box_ip, cmd, timeout=_HOST_SSH_TIMEOUT)
240
+ if rc == 255:
241
+ raise ssh_error(strip_ssh_banner(err), box_ip, resolve_box_user(box_ip))
242
+ return rc, out, err
243
+
244
+
245
+ @click.group(name='wifi', cls=LagerGroup, hidden=True)
246
+ def _wifi():
247
+ """Manage WiFi network settings"""
248
+ pass
249
+
250
+
251
+ @_wifi.command()
252
+ @click.pass_context
253
+ @click.option("--box", required=False, help="Lager Box name or IP")
254
+ def status(ctx, box):
255
+ """
256
+ Get the current WiFi Status of the box
257
+ """
258
+ box_ip = resolve_box(ctx, box, read_only=True)
259
+
260
+ _rc, out, _err = _run_on_host(box_ip, _STATUS_SCRIPT)
261
+ found, readable = _parse_host_status(out)
262
+ if not readable:
263
+ raise LagerError(
264
+ "Cannot read the box's Wi-Fi state.",
265
+ cause="The command on the box host did not run.",
266
+ )
267
+ if not found:
268
+ raise LagerError("The box has no wireless interface.")
269
+
270
+ click.secho("WiFi Status:", fg='green')
271
+ click.echo("=" * 40)
272
+ for info in found.values():
273
+ connected = info.get('state', '').startswith('Connected')
274
+ click.secho(f"Interface: {info.get('interface')}", fg='green')
275
+ click.secho(f" SSID: {info.get('ssid')}",
276
+ fg='green' if connected else 'red')
277
+ click.secho(f" State: {info.get('state')}",
278
+ fg='green' if connected else 'red')
279
+ click.echo()
280
+
281
+
282
+ def _scan_on_host(box_ip: str, interface: str | None,
283
+ box_label: str) -> tuple[str, list[dict]]:
284
+ """List the access points the box host sees, strongest first.
285
+
286
+ Returns the interface scanned (the first wireless one when none is named)
287
+ and the networks. nmcli lists one row per access point, so a network with
288
+ several shows up several times; each SSID is kept once, at its strongest.
289
+ """
290
+ given = shlex.quote(interface) if interface else "''"
291
+ cmd = (f"IF={given}; "
292
+ f"[ -n \"$IF\" ] || IF=$({_WIRELESS_IFACES} | head -n 1); "
293
+ "echo \"@$IF\"; "
294
+ "[ -n \"$IF\" ] || exit 0; "
295
+ f"command -v nmcli >/dev/null 2>&1 || {{ echo '{_MISSING}'; exit 0; }}; "
296
+ "nmcli -t -f SSID,SECURITY,SIGNAL device wifi list ifname \"$IF\"")
297
+ rc, out, err = _run_on_host(box_ip, cmd)
298
+ lines = out.splitlines()
299
+ scanned = lines[0][1:].strip() if lines and lines[0].startswith('@') else (interface or '')
300
+ rows = lines[1:] if lines and lines[0].startswith('@') else lines
301
+ if not scanned:
302
+ raise LagerError("The box has no wireless interface.")
303
+ if [r.strip() for r in rows] == [_MISSING]:
304
+ raise LagerError(
305
+ f"Cannot list the access points on {scanned}.",
306
+ cause=("The box host does not run NetworkManager, and a scan without it "
307
+ "needs root on the box host."),
308
+ fixes=[f"See the network the box is on: lager wifi status --box {box_label}"],
309
+ )
310
+ if rc != 0:
311
+ raise LagerError(
312
+ f"The Wi-Fi scan on {scanned} failed.",
313
+ cause=strip_ssh_banner(err) or f"nmcli exited {rc} on the box host.",
314
+ )
315
+
316
+ best = {}
317
+ for line in rows:
318
+ fields = _nmcli_fields(line)
319
+ if len(fields) < 3 or not fields[0]:
320
+ continue
321
+ ssid, security, signal = fields[0], fields[1], fields[2]
322
+ try:
323
+ strength = int(signal)
324
+ except ValueError:
325
+ strength = 0
326
+ if ssid not in best or strength > best[ssid]['strength']:
327
+ best[ssid] = {'ssid': ssid, 'security': security or 'Open',
328
+ 'strength': strength}
329
+ return scanned, sorted(best.values(), key=lambda n: n['strength'], reverse=True)
330
+
331
+
332
+ @_wifi.command()
333
+ @click.pass_context
334
+ @click.option("--box", required=False, help="Lager Box name or IP")
335
+ @click.option('--interface', required=False, default=None,
336
+ help="Wireless interface to use (default: the box's first wireless interface)")
337
+ def access_points(ctx, box, interface=None):
338
+ """
339
+ Get WiFi access points visible to the box
340
+ """
341
+ if interface is not None:
342
+ _validate_interface(ctx, interface)
343
+
344
+ box_ip = resolve_box(ctx, box, read_only=True)
345
+
346
+ scanned, networks = _scan_on_host(box_ip, interface, box or box_ip)
347
+ click.secho(f"Scanned for WiFi networks on {scanned}.", fg='green')
348
+
349
+ click.secho(f"\nFound {len(networks)} network(s):", fg='green')
350
+ click.secho(_format_networks_table(networks), fg='green')
351
+
352
+ click.secho("\nJSON Output:", fg='green')
353
+ click.echo(json.dumps({'access_points': networks}, indent=2))
354
+
355
+
356
+ @_wifi.command()
357
+ @click.pass_context
358
+ @click.option("--box", required=False, help="Lager Box name or IP")
359
+ @click.option('--ssid', required=True, help='SSID of the network to connect to')
360
+ @click.option('--interface', help='Wireless interface to use', default='wlan0', show_default=True)
361
+ @click.option('--password', required=False, help='Password of the network to connect to', default='')
362
+ def connect(ctx, box, ssid, interface, password=''):
363
+ """
364
+ Connect the box to a new network
365
+ """
366
+ # Validate inputs
367
+ _validate_ssid(ctx, ssid)
368
+ _validate_password(ctx, password)
369
+ _validate_interface(ctx, interface)
370
+
371
+ box_ip = resolve_box_locked(ctx, box, 'wifi')
372
+
373
+ click.secho(f"Connecting to WiFi network: {ssid}", fg='green')
374
+ result = _post_wifi(ctx, box_ip, 'connect',
375
+ ssid=ssid, password=password, interface=interface)
376
+
377
+ click.secho(f"[OK] Successfully connected to {ssid}", fg='green')
378
+ click.echo("\nJSON Output:")
379
+ click.echo(json.dumps(result.get('value') or {}, indent=2))
380
+
381
+
382
+ @_wifi.command()
383
+ @click.pass_context
384
+ @click.option("--box", required=False, help="Lager Box name or IP")
385
+ @click.option('--yes', is_flag=True, help='Confirm the action without prompting')
386
+ @click.argument('SSID', required=True)
387
+ def delete_connection(ctx, box, yes, ssid):
388
+ """
389
+ Delete the specified network from the box
390
+ """
391
+ # Validate SSID format
392
+ _validate_ssid(ctx, ssid)
393
+
394
+ if not yes and not click.confirm('An ethernet connection will be required to bring the box back online. Proceed?', default=False):
395
+ click.echo("Aborting")
396
+ return
397
+
398
+ box_ip = resolve_box_locked(ctx, box, 'wifi')
399
+
400
+ click.secho(f"Deleting WiFi connection: {ssid}", fg='green')
401
+ result = _post_wifi(ctx, box_ip, 'delete', ssid=ssid, connection_name=ssid)
402
+
403
+ click.secho(f"[OK] Successfully deleted connection: {ssid}", fg='green')
404
+ click.echo("\nJSON Output:")
405
+ click.echo(json.dumps(result.get('value') or {}, indent=2))
@@ -1459,6 +1459,19 @@ _ERASE_RANGE_UNSUPPORTED = (
1459
1459
  "(requires box version 0.50.0 or later). Update it with: lager update --box {box}"
1460
1460
  )
1461
1461
 
1462
+ # A /health that does not answer says nothing about the box's version. A
1463
+ # stalled gateway in front of :9000 times out every request for a while, so
1464
+ # the probe is retried before the box is reported unreachable.
1465
+ _ERASE_RANGE_HEALTH_BACKOFF_S = (0.5, 1.0)
1466
+ _ERASE_RANGE_UNREACHABLE = (
1467
+ "Error: box '{box}' did not answer /health: {exc}. "
1468
+ "The box or its Stout gateway may be unreachable; retry."
1469
+ )
1470
+
1471
+
1472
+ class _HealthProbeFailed(Exception):
1473
+ """/health raised on every attempt; carries the last exception."""
1474
+
1462
1475
 
1463
1476
  def _format_erase_range(start, size):
1464
1477
  """`0x16000000-0x161FFFFF (2 MiB)`, the form the box reports a range in."""
@@ -1502,16 +1515,44 @@ def _erase_range_error(device_type, erase_start, erase_size, *, no_erase=False):
1502
1515
  def _box_supports_erase_range(client):
1503
1516
  """True when the box's debug service lists `erase_range` under /health `features`.
1504
1517
 
1505
- An older box answers with no `features` at all, and a box that cannot be
1506
- reached reads the same: either way the flags are refused rather than sent
1507
- to a box that would ignore them.
1518
+ An older box answers with no `features` at all, and that answer is the
1519
+ only thing read as "unsupported". A request that fails -- a timeout, a
1520
+ refused connection, a gateway 5xx -- is retried, and if it never succeeds
1521
+ raises `_HealthProbeFailed`: telling the user to update a box that simply
1522
+ did not answer sends them to fix the wrong thing.
1523
+
1524
+ A gateway denial exits via SystemExit (see `_request`), which is not an
1525
+ `Exception`, so its `lager login` guidance still reaches the user.
1508
1526
  """
1527
+ import time
1528
+
1529
+ last_exc = None
1530
+ for backoff in (*_ERASE_RANGE_HEALTH_BACKOFF_S, None):
1531
+ try:
1532
+ health = client.get_service_health()
1533
+ except Exception as exc:
1534
+ last_exc = exc
1535
+ if backoff is not None:
1536
+ time.sleep(backoff)
1537
+ continue
1538
+ features = health.get('features') if isinstance(health, dict) else None
1539
+ return 'erase_range' in (features or [])
1540
+ raise _HealthProbeFailed(last_exc)
1541
+
1542
+
1543
+ def _require_erase_range(ctx, client, box):
1544
+ """Exit 1, before any erase or flash traffic, unless the box reads the range."""
1509
1545
  try:
1510
- health = client.get_service_health()
1511
- except Exception:
1512
- return False
1513
- features = health.get('features') if isinstance(health, dict) else None
1514
- return 'erase_range' in (features or [])
1546
+ supported = _box_supports_erase_range(client)
1547
+ except _HealthProbeFailed as failed:
1548
+ message = _ERASE_RANGE_UNREACHABLE.format(box=box, exc=failed.args[0])
1549
+ else:
1550
+ if supported:
1551
+ return
1552
+ message = _ERASE_RANGE_UNSUPPORTED.format(box=box)
1553
+ click.secho(message, fg='red', err=True)
1554
+ client.close()
1555
+ ctx.exit(1)
1515
1556
 
1516
1557
 
1517
1558
  def _erase_complete_line(result):
@@ -1594,10 +1635,8 @@ def flash(ctx, box, hex, elf, bin, verbose, force_reconnect, no_erase, erase,
1594
1635
  click.secho("Error: Failed to create debug service client", fg='red', err=True)
1595
1636
  ctx.exit(1)
1596
1637
 
1597
- if erase_range_requested and not _box_supports_erase_range(client):
1598
- click.secho(_ERASE_RANGE_UNSUPPORTED.format(box=box or target_box), fg='red', err=True)
1599
- client.close()
1600
- ctx.exit(1)
1638
+ if erase_range_requested:
1639
+ _require_erase_range(ctx, client, box or target_box)
1601
1640
 
1602
1641
  # Auto-connect if not already connected
1603
1642
  if not _auto_connect_if_needed(
@@ -1829,10 +1868,8 @@ def erase(ctx, box, speed, yes, quiet, json_output, erase_start, erase_size, hal
1829
1868
  click.secho("Error: Failed to create debug service client", fg='red', err=True)
1830
1869
  ctx.exit(1)
1831
1870
 
1832
- if erase_range_requested and not _box_supports_erase_range(client):
1833
- click.secho(_ERASE_RANGE_UNSUPPORTED.format(box=box or target_box), fg='red', err=True)
1834
- client.close()
1835
- ctx.exit(1)
1871
+ if erase_range_requested:
1872
+ _require_erase_range(ctx, client, box or target_box)
1836
1873
 
1837
1874
  # Auto-connect if not already connected
1838
1875
  if not _auto_connect_if_needed(
@@ -886,7 +886,7 @@ def acquire(ctx, mode, count, box):
886
886
  average is a running mean of the last --count captures, which takes
887
887
  random noise down by the square root of the count. peak keeps the
888
888
  minimum and maximum of every sample interval, where the unit can.
889
- A Rigol averages a power of two from 2 to 65536 captures.
889
+ A Rigol averages a power of two from 2 to 1024 captures.
890
890
  """
891
891
  box_ip = _resolve_box(ctx, box)
892
892
  netname = _require_netname(ctx)
@@ -12,7 +12,6 @@
12
12
  """
13
13
  import os
14
14
  import signal
15
- from uuid import uuid4
16
15
 
17
16
  import click
18
17
  import requests
@@ -503,10 +502,13 @@ class DirectHTTPSession:
503
502
 
504
503
  self.session = DirectHTTPSession._session_pool[box_ip]
505
504
 
506
- # Add version header (updated per invocation)
505
+ # Version and invocation headers. The id is the process's own, shared
506
+ # with every other request this command makes (gateway_auth.INVOCATION_ID),
507
+ # so one command reads as one invocation however many sessions it opens.
508
+ from ..gateway_auth import INVOCATION_ID
507
509
  self.session.headers.update({
508
510
  'Lager-Version': __version__,
509
- 'Lager-Invocation-Id': str(uuid4()),
511
+ 'Lager-Invocation-Id': INVOCATION_ID,
510
512
  })
511
513
 
512
514
  # Gateway auth (no-op for plain Lager boxes): attach a bearer token