jetstan-ev-software 0.1.2__tar.gz → 0.1.4__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 (84) hide show
  1. {jetstan_ev_software-0.1.2 → jetstan_ev_software-0.1.4}/PKG-INFO +1 -1
  2. {jetstan_ev_software-0.1.2 → jetstan_ev_software-0.1.4}/jetstan_ev_software.egg-info/PKG-INFO +1 -1
  3. {jetstan_ev_software-0.1.2 → jetstan_ev_software-0.1.4}/jetstan_ev_software.egg-info/SOURCES.txt +2 -0
  4. {jetstan_ev_software-0.1.2 → jetstan_ev_software-0.1.4}/pyproject.toml +1 -1
  5. {jetstan_ev_software-0.1.2 → jetstan_ev_software-0.1.4}/software/arduino_updates/__init__.py +11 -0
  6. {jetstan_ev_software-0.1.2 → jetstan_ev_software-0.1.4}/software/arduino_updates/compiler.py +56 -4
  7. {jetstan_ev_software-0.1.2 → jetstan_ev_software-0.1.4}/software/arduino_updates/config.py +11 -0
  8. {jetstan_ev_software-0.1.2 → jetstan_ev_software-0.1.4}/software/arduino_updates/exceptions.py +7 -0
  9. jetstan_ev_software-0.1.4/software/arduino_updates/provisioner.py +268 -0
  10. {jetstan_ev_software-0.1.2 → jetstan_ev_software-0.1.4}/software/deployment/pipeline.py +26 -6
  11. {jetstan_ev_software-0.1.2 → jetstan_ev_software-0.1.4}/tests/test_arduino_compiler.py +76 -3
  12. {jetstan_ev_software-0.1.2 → jetstan_ev_software-0.1.4}/tests/test_arduino_config.py +19 -0
  13. {jetstan_ev_software-0.1.2 → jetstan_ev_software-0.1.4}/tests/test_arduino_flasher.py +2 -0
  14. jetstan_ev_software-0.1.4/tests/test_arduino_provisioner.py +318 -0
  15. {jetstan_ev_software-0.1.2 → jetstan_ev_software-0.1.4}/tests/test_arduino_sync.py +19 -0
  16. {jetstan_ev_software-0.1.2 → jetstan_ev_software-0.1.4}/tests/test_arduino_verifier.py +2 -0
  17. {jetstan_ev_software-0.1.2 → jetstan_ev_software-0.1.4}/tests/test_deployment_pipeline.py +44 -2
  18. {jetstan_ev_software-0.1.2 → jetstan_ev_software-0.1.4}/README.md +0 -0
  19. {jetstan_ev_software-0.1.2 → jetstan_ev_software-0.1.4}/jetstan_ev_software.egg-info/dependency_links.txt +0 -0
  20. {jetstan_ev_software-0.1.2 → jetstan_ev_software-0.1.4}/jetstan_ev_software.egg-info/entry_points.txt +0 -0
  21. {jetstan_ev_software-0.1.2 → jetstan_ev_software-0.1.4}/jetstan_ev_software.egg-info/requires.txt +0 -0
  22. {jetstan_ev_software-0.1.2 → jetstan_ev_software-0.1.4}/jetstan_ev_software.egg-info/top_level.txt +0 -0
  23. {jetstan_ev_software-0.1.2 → jetstan_ev_software-0.1.4}/setup.cfg +0 -0
  24. {jetstan_ev_software-0.1.2 → jetstan_ev_software-0.1.4}/software/__init__.py +0 -0
  25. {jetstan_ev_software-0.1.2 → jetstan_ev_software-0.1.4}/software/arduino_updates/discovery.py +0 -0
  26. {jetstan_ev_software-0.1.2 → jetstan_ev_software-0.1.4}/software/arduino_updates/firmware.py +0 -0
  27. {jetstan_ev_software-0.1.2 → jetstan_ev_software-0.1.4}/software/arduino_updates/flasher.py +0 -0
  28. {jetstan_ev_software-0.1.2 → jetstan_ev_software-0.1.4}/software/arduino_updates/sample_firmware/README.md +0 -0
  29. {jetstan_ev_software-0.1.2 → jetstan_ev_software-0.1.4}/software/arduino_updates/sample_firmware/motor_test/motor_test.ino +0 -0
  30. {jetstan_ev_software-0.1.2 → jetstan_ev_software-0.1.4}/software/arduino_updates/state_store.py +0 -0
  31. {jetstan_ev_software-0.1.2 → jetstan_ev_software-0.1.4}/software/arduino_updates/verifier.py +0 -0
  32. {jetstan_ev_software-0.1.2 → jetstan_ev_software-0.1.4}/software/cli.py +0 -0
  33. {jetstan_ev_software-0.1.2 → jetstan_ev_software-0.1.4}/software/deployment/__init__.py +0 -0
  34. {jetstan_ev_software-0.1.2 → jetstan_ev_software-0.1.4}/software/deployment/dag.py +0 -0
  35. {jetstan_ev_software-0.1.2 → jetstan_ev_software-0.1.4}/software/deployment/dependencies.py +0 -0
  36. {jetstan_ev_software-0.1.2 → jetstan_ev_software-0.1.4}/software/frontend/__init__.py +0 -0
  37. {jetstan_ev_software-0.1.2 → jetstan_ev_software-0.1.4}/software/frontend/index.html +0 -0
  38. {jetstan_ev_software-0.1.2 → jetstan_ev_software-0.1.4}/software/gen_sample/__init__.py +0 -0
  39. {jetstan_ev_software-0.1.2 → jetstan_ev_software-0.1.4}/software/gen_sample/simulator.py +0 -0
  40. {jetstan_ev_software-0.1.2 → jetstan_ev_software-0.1.4}/software/handlers.py +0 -0
  41. {jetstan_ev_software-0.1.2 → jetstan_ev_software-0.1.4}/software/logic/__init__.py +0 -0
  42. {jetstan_ev_software-0.1.2 → jetstan_ev_software-0.1.4}/software/logic/calculations.py +0 -0
  43. {jetstan_ev_software-0.1.2 → jetstan_ev_software-0.1.4}/software/sensors/__init__.py +0 -0
  44. {jetstan_ev_software-0.1.2 → jetstan_ev_software-0.1.4}/software/sensors/motor_control.py +0 -0
  45. {jetstan_ev_software-0.1.2 → jetstan_ev_software-0.1.4}/software/sensors/serial_telemetry.py +0 -0
  46. {jetstan_ev_software-0.1.2 → jetstan_ev_software-0.1.4}/software/sensors/telemetry_store.py +0 -0
  47. {jetstan_ev_software-0.1.2 → jetstan_ev_software-0.1.4}/software/soc/__init__.py +0 -0
  48. {jetstan_ev_software-0.1.2 → jetstan_ev_software-0.1.4}/software/soc/api.py +0 -0
  49. {jetstan_ev_software-0.1.2 → jetstan_ev_software-0.1.4}/software/soc/config.py +0 -0
  50. {jetstan_ev_software-0.1.2 → jetstan_ev_software-0.1.4}/software/soc/exceptions.py +0 -0
  51. {jetstan_ev_software-0.1.2 → jetstan_ev_software-0.1.4}/software/soc/features.py +0 -0
  52. {jetstan_ev_software-0.1.2 → jetstan_ev_software-0.1.4}/software/soc/model.py +0 -0
  53. {jetstan_ev_software-0.1.2 → jetstan_ev_software-0.1.4}/software/soc/predictor.py +0 -0
  54. {jetstan_ev_software-0.1.2 → jetstan_ev_software-0.1.4}/software/soc/schemas.py +0 -0
  55. {jetstan_ev_software-0.1.2 → jetstan_ev_software-0.1.4}/software/soc/service.py +0 -0
  56. {jetstan_ev_software-0.1.2 → jetstan_ev_software-0.1.4}/software/soc/soc_dashboard.html +0 -0
  57. {jetstan_ev_software-0.1.2 → jetstan_ev_software-0.1.4}/software/soc/telemetry.py +0 -0
  58. {jetstan_ev_software-0.1.2 → jetstan_ev_software-0.1.4}/software/soc/xgboost_soc.onnx +0 -0
  59. {jetstan_ev_software-0.1.2 → jetstan_ev_software-0.1.4}/software/test/README.md +0 -0
  60. {jetstan_ev_software-0.1.2 → jetstan_ev_software-0.1.4}/software/test/__init__.py +0 -0
  61. {jetstan_ev_software-0.1.2 → jetstan_ev_software-0.1.4}/software/test/jetstan-dashboard.service +0 -0
  62. {jetstan_ev_software-0.1.2 → jetstan_ev_software-0.1.4}/software/test/server.py +0 -0
  63. {jetstan_ev_software-0.1.2 → jetstan_ev_software-0.1.4}/software/updater.py +0 -0
  64. {jetstan_ev_software-0.1.2 → jetstan_ev_software-0.1.4}/tests/test_arduino_discovery.py +0 -0
  65. {jetstan_ev_software-0.1.2 → jetstan_ev_software-0.1.4}/tests/test_arduino_exceptions.py +0 -0
  66. {jetstan_ev_software-0.1.2 → jetstan_ev_software-0.1.4}/tests/test_arduino_firmware.py +0 -0
  67. {jetstan_ev_software-0.1.2 → jetstan_ev_software-0.1.4}/tests/test_cli.py +0 -0
  68. {jetstan_ev_software-0.1.2 → jetstan_ev_software-0.1.4}/tests/test_deployment_dag.py +0 -0
  69. {jetstan_ev_software-0.1.2 → jetstan_ev_software-0.1.4}/tests/test_deployment_dependencies.py +0 -0
  70. {jetstan_ev_software-0.1.2 → jetstan_ev_software-0.1.4}/tests/test_deployment_run.py +0 -0
  71. {jetstan_ev_software-0.1.2 → jetstan_ev_software-0.1.4}/tests/test_gen_sample.py +0 -0
  72. {jetstan_ev_software-0.1.2 → jetstan_ev_software-0.1.4}/tests/test_handlers.py +0 -0
  73. {jetstan_ev_software-0.1.2 → jetstan_ev_software-0.1.4}/tests/test_logic.py +0 -0
  74. {jetstan_ev_software-0.1.2 → jetstan_ev_software-0.1.4}/tests/test_motor_control.py +0 -0
  75. {jetstan_ev_software-0.1.2 → jetstan_ev_software-0.1.4}/tests/test_serial_telemetry.py +0 -0
  76. {jetstan_ev_software-0.1.2 → jetstan_ev_software-0.1.4}/tests/test_soc_api.py +0 -0
  77. {jetstan_ev_software-0.1.2 → jetstan_ev_software-0.1.4}/tests/test_soc_config.py +0 -0
  78. {jetstan_ev_software-0.1.2 → jetstan_ev_software-0.1.4}/tests/test_soc_features.py +0 -0
  79. {jetstan_ev_software-0.1.2 → jetstan_ev_software-0.1.4}/tests/test_soc_model.py +0 -0
  80. {jetstan_ev_software-0.1.2 → jetstan_ev_software-0.1.4}/tests/test_soc_predictor.py +0 -0
  81. {jetstan_ev_software-0.1.2 → jetstan_ev_software-0.1.4}/tests/test_soc_service.py +0 -0
  82. {jetstan_ev_software-0.1.2 → jetstan_ev_software-0.1.4}/tests/test_soc_telemetry.py +0 -0
  83. {jetstan_ev_software-0.1.2 → jetstan_ev_software-0.1.4}/tests/test_telemetry_store.py +0 -0
  84. {jetstan_ev_software-0.1.2 → jetstan_ev_software-0.1.4}/tests/test_updater.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: jetstan_ev_software
3
- Version: 0.1.2
3
+ Version: 0.1.4
4
4
  Summary: The vehicle software payload for Jetstan electric vehicles - independently versioned from jetstan-agent (OTA delivery) and jetstan-cli (deploy tool).
5
5
  Keywords: ev,vehicle-software,ota,automotive,raspberry-pi
6
6
  Classifier: Development Status :: 3 - Alpha
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: jetstan_ev_software
3
- Version: 0.1.2
3
+ Version: 0.1.4
4
4
  Summary: The vehicle software payload for Jetstan electric vehicles - independently versioned from jetstan-agent (OTA delivery) and jetstan-cli (deploy tool).
5
5
  Keywords: ev,vehicle-software,ota,automotive,raspberry-pi
6
6
  Classifier: Development Status :: 3 - Alpha
@@ -17,6 +17,7 @@ software/arduino_updates/discovery.py
17
17
  software/arduino_updates/exceptions.py
18
18
  software/arduino_updates/firmware.py
19
19
  software/arduino_updates/flasher.py
20
+ software/arduino_updates/provisioner.py
20
21
  software/arduino_updates/state_store.py
21
22
  software/arduino_updates/verifier.py
22
23
  software/arduino_updates/sample_firmware/README.md
@@ -57,6 +58,7 @@ tests/test_arduino_discovery.py
57
58
  tests/test_arduino_exceptions.py
58
59
  tests/test_arduino_firmware.py
59
60
  tests/test_arduino_flasher.py
61
+ tests/test_arduino_provisioner.py
60
62
  tests/test_arduino_sync.py
61
63
  tests/test_arduino_verifier.py
62
64
  tests/test_cli.py
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "jetstan_ev_software"
7
- version = "0.1.2"
7
+ version = "0.1.4"
8
8
  description = "The vehicle software payload for Jetstan electric vehicles - independently versioned from jetstan-agent (OTA delivery) and jetstan-cli (deploy tool)."
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.11"
@@ -58,6 +58,17 @@ def check_and_flash(config: ArduinoConfig | None = None) -> ArduinoSyncResult:
58
58
  logger.debug("Arduino updates disabled (ARDUINO_ENABLED=false); skipping.")
59
59
  return ArduinoSyncResult(attempted=False, flashed=False, detail="disabled")
60
60
 
61
+ # Safe to log in full - nothing here is a credential (MQTT auth lives
62
+ # in a separate config class - see config.py).
63
+ logger.info(
64
+ "Arduino config: board=%s port=%s state_dir=%s firmware_path=%s avrdude_path=%s",
65
+ config.board,
66
+ config.port,
67
+ config.state_dir,
68
+ config.firmware_path,
69
+ config.avrdude_path,
70
+ )
71
+
61
72
  try:
62
73
  firmware = Firmware.load(config.firmware_path)
63
74
  except FirmwareNotFoundError:
@@ -31,6 +31,11 @@ logger = logging.getLogger(__name__)
31
31
 
32
32
  _SOURCE_STATE_FILENAME = "arduino_source.version"
33
33
  _HASH_CHUNK_SIZE = 65536
34
+ # The DAG's own per-task log line (dag.py) stays terse on purpose - this
35
+ # is how long a summary is allowed to be before it's truncated there.
36
+ # The full, untruncated arduino-cli output is always logged in full
37
+ # separately (see the `result.returncode != 0` branch below), never lost.
38
+ _ERROR_SUMMARY_MAX_CHARS = 300
34
39
 
35
40
 
36
41
  @dataclass(frozen=True)
@@ -74,6 +79,23 @@ def compile_sketch(config: ArduinoConfig) -> CompileResult:
74
79
  still exists. Raises :class:`CompileError` if ``arduino-cli`` isn't
75
80
  on PATH, the compile itself fails, or it times out.
76
81
  """
82
+ # Safe to log in full: nothing on ArduinoConfig is a credential (MQTT
83
+ # auth lives in a separate config class entirely - see config.py).
84
+ # Logged unconditionally, before any check that might raise, so a
85
+ # failure at any step still leaves the resolved configuration visible
86
+ # in the journal, not just the error itself.
87
+ logger.info(
88
+ "Arduino config: enabled=%s board=%s port=%s state_dir=%s firmware_source=%s "
89
+ "firmware_path=%s arduino_cli_path=%s",
90
+ config.enabled,
91
+ config.board,
92
+ config.port,
93
+ config.state_dir,
94
+ config.firmware_source,
95
+ config.firmware_path,
96
+ config.arduino_cli_path,
97
+ )
98
+
77
99
  if not config.firmware_source.is_dir():
78
100
  raise FirmwareNotFoundError(f"Arduino sketch source not found: {config.firmware_source}")
79
101
 
@@ -93,6 +115,7 @@ def compile_sketch(config: ArduinoConfig) -> CompileResult:
93
115
  return CompileResult(hex_path=config.firmware_path, skipped=True)
94
116
 
95
117
  arduino_cli = _require_arduino_cli(config.arduino_cli_path)
118
+ logger.info("Resolved arduino-cli executable: %s", arduino_cli)
96
119
  fqbn = config.board_profile.fqbn
97
120
 
98
121
  logger.info(
@@ -125,7 +148,7 @@ def compile_sketch(config: ArduinoConfig) -> CompileResult:
125
148
  text=True,
126
149
  timeout=config.compile_timeout_seconds,
127
150
  check=False,
128
- env=_build_subprocess_env(config),
151
+ env=build_subprocess_env(config),
129
152
  )
130
153
  except subprocess.TimeoutExpired as exc:
131
154
  raise CompileError(
@@ -133,7 +156,11 @@ def compile_sketch(config: ArduinoConfig) -> CompileResult:
133
156
  ) from exc
134
157
 
135
158
  if result.returncode != 0:
136
- raise CompileError(f"arduino-cli compile failed: {result.stderr.strip()}")
159
+ # Full output, unabridged, always in the journal - separate
160
+ # from the exception message below, which dag.py folds into
161
+ # its own terse per-task summary line and must stay short.
162
+ logger.error("arduino-cli compile output:\n%s", result.stderr.strip())
163
+ raise CompileError(f"compilation failed: {_summarize(result.stderr)}")
137
164
 
138
165
  # arduino-cli names its output <sketch-folder-name>.ino.hex - matching
139
166
  # that exact name (rather than globbing "*.hex" and picking one) means
@@ -153,10 +180,14 @@ def compile_sketch(config: ArduinoConfig) -> CompileResult:
153
180
  return CompileResult(hex_path=config.firmware_path, skipped=False)
154
181
 
155
182
 
156
- def _build_subprocess_env(config: ArduinoConfig) -> dict[str, str]:
157
- """Environment for the arduino-cli subprocess, with home-relative
183
+ def build_subprocess_env(config: ArduinoConfig) -> dict[str, str]:
184
+ """Environment for an arduino-cli subprocess, with home-relative
158
185
  lookups pinned to a directory ``jetstan`` can actually write to.
159
186
 
187
+ Public (not ``_``-prefixed): shared with ``provisioner.py``, which
188
+ invokes arduino-cli's own ``core`` subcommands under the exact same
189
+ constraint this was written for - rather than a second, drifting copy.
190
+
160
191
  ``--config-file`` alone is not enough: beyond the settings it
161
192
  controls (``directories.data``/``user``/``downloads``), arduino-cli
162
193
  (a Go binary) separately resolves things like its build-cache
@@ -179,6 +210,27 @@ def _build_subprocess_env(config: ArduinoConfig) -> dict[str, str]:
179
210
  return env
180
211
 
181
212
 
213
+ def _summarize(stderr: str) -> str:
214
+ """A short, single-line summary for the DAG's own terse per-task log.
215
+
216
+ GCC-style (and arduino-cli's own) output typically leads with a
217
+ context line - ``sketch.ino: In function 'foo':`` - before the actual
218
+ ``sketch.ino:95:3: error: ...`` line; taking line one blindly would
219
+ surface the context, not the error. The first line actually
220
+ containing ``error:`` is what a human would look at first; everything
221
+ else is already visible in the full log this accompanies (see the
222
+ ``logger.error`` call right before this is used).
223
+ """
224
+ stripped = stderr.strip()
225
+ if not stripped:
226
+ return "arduino-cli exited non-zero with no output - see the full log above"
227
+ lines = stripped.splitlines()
228
+ summary_line = next((line for line in lines if "error:" in line), lines[0])
229
+ if len(summary_line) > _ERROR_SUMMARY_MAX_CHARS:
230
+ return summary_line[:_ERROR_SUMMARY_MAX_CHARS] + "... (see the full log above)"
231
+ return summary_line
232
+
233
+
182
234
  def _require_arduino_cli(configured_path: str) -> str:
183
235
  resolved = shutil.which(configured_path)
184
236
  if resolved is None and Path(configured_path).is_file():
@@ -41,6 +41,8 @@ _ENV_FIRMWARE_SOURCE = "ARDUINO_FIRMWARE_SOURCE"
41
41
  _ENV_ARDUINO_CLI_PATH = "ARDUINO_CLI_PATH"
42
42
  _ENV_COMPILE_TIMEOUT_SECONDS = "ARDUINO_COMPILE_TIMEOUT_SECONDS"
43
43
  _ENV_ARDUINO_CLI_CONFIG_FILE = "ARDUINO_CLI_CONFIG_FILE"
44
+ _ENV_CORE_VERSION = "ARDUINO_CORE_VERSION"
45
+ _ENV_CLI_MIN_VERSION = "ARDUINO_CLI_MIN_VERSION"
44
46
 
45
47
  DEFAULT_ENABLED = False
46
48
  DEFAULT_BOARD = "uno"
@@ -134,6 +136,13 @@ class ArduinoConfig:
134
136
  arduino_cli_path: str
135
137
  arduino_cli_config_file: Path
136
138
  compile_timeout_seconds: int
139
+ # Both unset (None) by default, deliberately: no tested-against
140
+ # version has ever been recorded anywhere in this repository, and
141
+ # inventing one here would be a made-up pin, not a real one. Set
142
+ # explicitly once a real minimum/pin is actually known (see
143
+ # provisioner.py, which only enforces these when configured).
144
+ core_version: str | None
145
+ cli_min_version: str | None
137
146
 
138
147
  @property
139
148
  def board_profile(self) -> BoardProfile:
@@ -181,6 +190,8 @@ class ArduinoConfig:
181
190
  compile_timeout_seconds=int(
182
191
  os.environ.get(_ENV_COMPILE_TIMEOUT_SECONDS, DEFAULT_COMPILE_TIMEOUT_SECONDS)
183
192
  ),
193
+ core_version=os.environ.get(_ENV_CORE_VERSION) or None,
194
+ cli_min_version=os.environ.get(_ENV_CLI_MIN_VERSION) or None,
184
195
  )
185
196
 
186
197
 
@@ -47,3 +47,10 @@ class FlashError(ArduinoUpdateError):
47
47
 
48
48
  class VerificationError(ArduinoUpdateError):
49
49
  """Post-flash verification found a mismatch between board and firmware."""
50
+
51
+
52
+ class ToolchainError(ArduinoUpdateError):
53
+ """The host's Arduino toolchain (arduino-cli, avrdude, or a core
54
+ platform) is missing or incompatible, and could not be safely
55
+ resolved by software alone - see provisioner.py's own docstring on
56
+ exactly which parts are, and are not, auto-provisioned."""
@@ -0,0 +1,268 @@
1
+ """Ensures the host's MCU toolchain is ready before ``compiler.py`` needs it.
2
+
3
+ Deliberately draws a hard line between two different kinds of "missing
4
+ dependency", and never blurs them:
5
+
6
+ 1. The ``arduino-cli`` binary itself, and ``avrdude``. Both require root
7
+ to install on the current development target (``apt install avrdude``;
8
+ ``arduino-cli``'s own installer writes to a system-wide bindir) - and
9
+ this process runs as the unprivileged, capability-stripped ``jetstan``
10
+ user (see ``jetstan-agent.service.template``: ``NoNewPrivileges=true``,
11
+ empty ``CapabilityBoundingSet=``/``AmbientCapabilities=``). It has no
12
+ path to become root, and this module never tries to fake one - no
13
+ ``sudo``, no fetching-and-executing an installer script over the
14
+ network at deploy time. Both remain a one-time, human-run host
15
+ provisioning step (see ``jetstan-agent/INSTALL.md``), exactly as
16
+ ``compiler.py``'s own ``_require_arduino_cli`` and ``flasher.py``'s
17
+ ``_require_avrdude`` already established - this module only checks
18
+ for them, same as those two always have, and fails with a clear,
19
+ actionable reason if either is absent.
20
+
21
+ 2. The Arduino *core* (e.g. ``arduino:avr``) - a package ``arduino-cli``
22
+ installs into its own data directory, which is already ``jetstan``-
23
+ owned (``ArduinoConfig.arduino_cli_config_file``'s parent, under
24
+ ``StateDirectory=jetstan``). No root, no system-wide change, no
25
+ different in kind from ``deployment/dependencies.py``'s
26
+ ``ensure_pyserial_installed()`` already installing its own one pip
27
+ package at runtime. This *is* safe to automate, and is exactly what
28
+ this module does - idempotently: already-correct is a fast no-op,
29
+ missing gets installed once, and it is never blindly reinstalled on
30
+ every OTA-triggered restart.
31
+
32
+ ``get_provisioner(family)`` mirrors ``flasher.py``'s own
33
+ ``get_flasher(family)``/``FLASHERS`` registry pattern exactly, for the
34
+ same reason: today there is exactly one MCU family (AVR, via
35
+ ``arduino-cli``); a future production MCU gets its own
36
+ ``ToolchainProvisioner`` registered the same way a future board family
37
+ already gets its own ``BoardFlasher`` - nothing calling
38
+ ``ensure_arduino_toolchain()`` needs to change either way.
39
+ """
40
+
41
+ from __future__ import annotations
42
+
43
+ import abc
44
+ import json
45
+ import logging
46
+ import shutil
47
+ import subprocess
48
+ from dataclasses import dataclass
49
+ from pathlib import Path
50
+
51
+ from software.arduino_updates.compiler import build_subprocess_env
52
+ from software.arduino_updates.config import ArduinoConfig
53
+ from software.arduino_updates.exceptions import ToolchainError, UnsupportedBoardError
54
+
55
+ logger = logging.getLogger(__name__)
56
+
57
+ _ARDUINO_CLI_NOT_FOUND_HELP = (
58
+ "This is a one-time, root-level host provisioning step this software "
59
+ "deliberately never performs itself - an OTA-triggered process must "
60
+ "never self-elevate or install system-level tooling. Fix: follow the "
61
+ "'Arduino toolchain' section of jetstan-agent/INSTALL.md once, on this host."
62
+ )
63
+
64
+
65
+ @dataclass(frozen=True)
66
+ class ProvisionResult:
67
+ """Outcome of one :func:`ToolchainProvisioner.ensure_ready` call."""
68
+
69
+ action: str # "already_ready" | "installed_core"
70
+ detail: str
71
+
72
+
73
+ class ToolchainProvisioner(abc.ABC):
74
+ """MCU-family-specific toolchain provisioning."""
75
+
76
+ @abc.abstractmethod
77
+ def ensure_ready(self, config: ArduinoConfig) -> ProvisionResult:
78
+ """Ensure this family's toolchain is present and ready to use.
79
+
80
+ Raises :class:`~software.arduino_updates.exceptions.ToolchainError`
81
+ if it can't be, whether or not that's something this call could
82
+ fix itself. Idempotent: calling this 1 time or 100 times leaves
83
+ the host in the same valid state, and never repeats work that
84
+ was already done.
85
+ """
86
+
87
+
88
+ class ArduinoAVRProvisioner(ToolchainProvisioner):
89
+ """Provisions the ``arduino:avr`` core for arduino-cli - see this
90
+ module's own docstring for exactly what is, and is not, automated."""
91
+
92
+ def ensure_ready(self, config: ArduinoConfig) -> ProvisionResult:
93
+ arduino_cli = _resolve(config.arduino_cli_path)
94
+ if arduino_cli is None:
95
+ raise ToolchainError(
96
+ f"arduino-cli is not installed on this host.\n"
97
+ f" Configured path: {config.arduino_cli_path}\n"
98
+ f" {_ARDUINO_CLI_NOT_FOUND_HELP}"
99
+ )
100
+
101
+ avrdude = _resolve(config.avrdude_path)
102
+ if avrdude is None:
103
+ raise ToolchainError(
104
+ f"avrdude is not installed on this host.\n"
105
+ f" Configured path: {config.avrdude_path}\n"
106
+ " Requires root (sudo apt install avrdude) - deliberately not "
107
+ "performed by this software; see jetstan-agent/INSTALL.md."
108
+ )
109
+
110
+ if config.cli_min_version is not None:
111
+ self._check_cli_version(arduino_cli, config)
112
+
113
+ platform = _platform_id(config.board_profile.fqbn)
114
+ installed_version = self._installed_core_version(arduino_cli, config, platform)
115
+
116
+ if installed_version is not None and (
117
+ config.core_version is None or installed_version == config.core_version
118
+ ):
119
+ detail = f"{platform}=={installed_version} already installed, avrdude present"
120
+ logger.info("Arduino toolchain ready: %s", detail)
121
+ return ProvisionResult(action="already_ready", detail=detail)
122
+
123
+ target = f"{platform}@{config.core_version}" if config.core_version else platform
124
+ logger.info(
125
+ "Arduino core %s %s - installing %s...",
126
+ platform,
127
+ "is missing"
128
+ if installed_version is None
129
+ else f"is at {installed_version}, want {config.core_version}",
130
+ target,
131
+ )
132
+ self._run(arduino_cli, config, ["core", "update-index"])
133
+ result = self._run(arduino_cli, config, ["core", "install", target])
134
+ if result.returncode != 0:
135
+ raise ToolchainError(
136
+ f"Failed to install Arduino core {target}.\n"
137
+ f" arduino-cli path: {arduino_cli}\n"
138
+ f" Installation path: {config.arduino_cli_config_file.parent}\n"
139
+ f" Reason: {result.stderr.strip()[:300] or '(no output)'}"
140
+ )
141
+
142
+ installed_version = self._installed_core_version(arduino_cli, config, platform)
143
+ if installed_version is None or (
144
+ config.core_version is not None and installed_version != config.core_version
145
+ ):
146
+ raise ToolchainError(
147
+ f"arduino-cli reported success installing {target}, but {platform} still "
148
+ f"isn't confirmed installed at the expected version "
149
+ f"(found: {installed_version or 'not found'})."
150
+ )
151
+
152
+ detail = f"installed {platform}=={installed_version}"
153
+ logger.info("Arduino toolchain provisioned: %s", detail)
154
+ return ProvisionResult(action="installed_core", detail=detail)
155
+
156
+ def _check_cli_version(self, arduino_cli: str, config: ArduinoConfig) -> None:
157
+ result = self._run(arduino_cli, config, ["version", "--format", "json"])
158
+ cli_version = None
159
+ if result.returncode == 0:
160
+ try:
161
+ cli_version = json.loads(result.stdout).get("VersionString")
162
+ except json.JSONDecodeError:
163
+ cli_version = None
164
+
165
+ if cli_version is None or _version_tuple(cli_version) < _version_tuple(
166
+ config.cli_min_version
167
+ ):
168
+ raise ToolchainError(
169
+ f"arduino-cli version {cli_version or 'unknown'} does not meet the "
170
+ f"required minimum {config.cli_min_version}.\n"
171
+ f" arduino-cli path: {arduino_cli}\n"
172
+ " Upgrading arduino-cli itself requires re-running the one-time host "
173
+ "provisioning step (see jetstan-agent/INSTALL.md) - this software does "
174
+ "not self-upgrade it."
175
+ )
176
+
177
+ def _installed_core_version(
178
+ self, arduino_cli: str, config: ArduinoConfig, platform: str
179
+ ) -> str | None:
180
+ result = self._run(arduino_cli, config, ["core", "list", "--format", "json"])
181
+ if result.returncode != 0:
182
+ return None
183
+ try:
184
+ data = json.loads(result.stdout)
185
+ except json.JSONDecodeError:
186
+ return None
187
+ for entry in data.get("platforms") or []:
188
+ if entry.get("id") == platform:
189
+ return entry.get("installed_version")
190
+ return None
191
+
192
+ def _run(
193
+ self, arduino_cli: str, config: ArduinoConfig, args: list[str]
194
+ ) -> subprocess.CompletedProcess:
195
+ command = [arduino_cli, "--config-file", str(config.arduino_cli_config_file), *args]
196
+ logger.debug("Running: %s", " ".join(command))
197
+ return subprocess.run(
198
+ command,
199
+ capture_output=True,
200
+ text=True,
201
+ timeout=config.compile_timeout_seconds,
202
+ check=False,
203
+ env=build_subprocess_env(config),
204
+ )
205
+
206
+
207
+ def _platform_id(fqbn: str) -> str:
208
+ """``arduino:avr:uno`` -> ``arduino:avr`` - the first two segments of
209
+ an FQBN are the platform arduino-cli's own ``core`` subcommands
210
+ address; no separate config field needed, it's already fully implied
211
+ by ``ARDUINO_BOARD``'s existing profile."""
212
+ return ":".join(fqbn.split(":")[:2])
213
+
214
+
215
+ def _version_tuple(version: str) -> tuple[int, ...]:
216
+ """Best-effort numeric comparison: ``'0.35.3'`` -> ``(0, 35, 3)``.
217
+ Ignores non-numeric suffixes (e.g. ``-rc1``) - good enough for a
218
+ ``>=`` minimum-version check, not a full semver implementation this
219
+ project has no other use for."""
220
+ parts: list[int] = []
221
+ for segment in version.split(".")[:3]:
222
+ digits = ""
223
+ for ch in segment:
224
+ if not ch.isdigit():
225
+ break
226
+ digits += ch
227
+ parts.append(int(digits) if digits else 0)
228
+ while len(parts) < 3:
229
+ parts.append(0)
230
+ return tuple(parts)
231
+
232
+
233
+ def _resolve(configured_path: str) -> str | None:
234
+ """Existence-only probe - never constructs a command, just answers
235
+ "is this available". ``compiler.py``/``flasher.py`` each do their own
236
+ resolution when actually invoking a tool; this only decides whether
237
+ provisioning can proceed at all."""
238
+ resolved = shutil.which(configured_path)
239
+ if resolved is None and Path(configured_path).is_file():
240
+ resolved = configured_path
241
+ return resolved
242
+
243
+
244
+ PROVISIONERS: dict[str, ToolchainProvisioner] = {
245
+ "avr": ArduinoAVRProvisioner(),
246
+ }
247
+
248
+
249
+ def get_provisioner(family: str) -> ToolchainProvisioner:
250
+ """Look up the provisioner registered for ``family`` (e.g. ``"avr"``)."""
251
+ try:
252
+ return PROVISIONERS[family]
253
+ except KeyError as exc:
254
+ raise UnsupportedBoardError(
255
+ f"No toolchain provisioner registered for board family '{family}'; "
256
+ f"known families: {', '.join(sorted(PROVISIONERS))}"
257
+ ) from exc
258
+
259
+
260
+ def ensure_arduino_toolchain(config: ArduinoConfig) -> ProvisionResult:
261
+ """Ensure ``config.board``'s MCU toolchain is ready. Raises
262
+ :class:`~software.arduino_updates.exceptions.ToolchainError` (or
263
+ :class:`~software.arduino_updates.exceptions.UnsupportedBoardError`)
264
+ on failure - this is the version used inside the deployment DAG (see
265
+ ``deployment/pipeline.py``), where the DAG runner itself handles
266
+ catching, logging, and not crashing the caller.
267
+ """
268
+ return get_provisioner(config.board_profile.family).ensure_ready(config)
@@ -1,10 +1,11 @@
1
1
  """This project's concrete deployment DAG.
2
2
 
3
- Compile Arduino firmware, flash it, ensure this feature's own Python
4
- dependencies are present, then start reading real sensor telemetry back
5
- from the board (and forwarding motor speed commands to it). Adding a
6
- future board (e.g. a custom PCB) means adding its own tasks here, with
7
- their own ``depends_on`` - ``dag.py`` itself never needs to change.
3
+ Ensure the host's Arduino toolchain is ready, compile Arduino firmware,
4
+ flash it, ensure this feature's own Python dependencies are present,
5
+ then start reading real sensor telemetry back from the board (and
6
+ forwarding motor speed commands to it). Adding a future board (e.g. a
7
+ custom PCB) means adding its own tasks here, with their own
8
+ ``depends_on`` - ``dag.py`` itself never needs to change.
8
9
  """
9
10
 
10
11
  from __future__ import annotations
@@ -15,12 +16,25 @@ from software.deployment.dag import Task
15
16
 
16
17
  logger = logging.getLogger(__name__)
17
18
 
19
+ _PREPARE_ARDUINO_TOOLCHAIN = "prepare_arduino_toolchain"
18
20
  _COMPILE_ARDUINO_FIRMWARE = "compile_arduino_firmware"
19
21
  _FLASH_ARDUINO_FIRMWARE = "flash_arduino_firmware"
20
22
  _INSTALL_PYTHON_DEPENDENCIES = "install_python_dependencies"
21
23
  _START_SERIAL_TELEMETRY = "start_serial_telemetry"
22
24
 
23
25
 
26
+ def _prepare_arduino_toolchain_task() -> str:
27
+ from software.arduino_updates.config import ArduinoConfig
28
+ from software.arduino_updates.provisioner import ensure_arduino_toolchain
29
+
30
+ config = ArduinoConfig.from_env()
31
+ if not config.enabled or not config.auto_compile:
32
+ return "skipped: disabled"
33
+
34
+ result = ensure_arduino_toolchain(config)
35
+ return result.detail
36
+
37
+
24
38
  def _compile_arduino_task() -> str:
25
39
  from software.arduino_updates.compiler import compile_sketch
26
40
  from software.arduino_updates.config import ArduinoConfig
@@ -81,7 +95,13 @@ def _start_serial_telemetry_task() -> None:
81
95
  def build_pipeline() -> list[Task]:
82
96
  """Build this project's deployment task graph."""
83
97
  return [
84
- Task(name=_COMPILE_ARDUINO_FIRMWARE, run=_compile_arduino_task, critical=True),
98
+ Task(name=_PREPARE_ARDUINO_TOOLCHAIN, run=_prepare_arduino_toolchain_task, critical=True),
99
+ Task(
100
+ name=_COMPILE_ARDUINO_FIRMWARE,
101
+ run=_compile_arduino_task,
102
+ depends_on=(_PREPARE_ARDUINO_TOOLCHAIN,),
103
+ critical=True,
104
+ ),
85
105
  Task(
86
106
  name=_FLASH_ARDUINO_FIRMWARE,
87
107
  run=_flash_arduino_task,
@@ -9,7 +9,7 @@ import pytest
9
9
 
10
10
  from software.arduino_updates.compiler import (
11
11
  SourceStateStore,
12
- _build_subprocess_env,
12
+ build_subprocess_env,
13
13
  _fingerprint_source,
14
14
  compile_sketch,
15
15
  )
@@ -35,6 +35,8 @@ def _config(tmp_path, **overrides) -> ArduinoConfig:
35
35
  arduino_cli_path="arduino-cli",
36
36
  arduino_cli_config_file=tmp_path / "state" / "arduino-cli" / "arduino-cli.yaml",
37
37
  compile_timeout_seconds=60,
38
+ core_version=None,
39
+ cli_min_version=None,
38
40
  )
39
41
  values.update(overrides)
40
42
  return ArduinoConfig(**values)
@@ -215,6 +217,77 @@ def test_compile_uses_exact_expected_filename_when_extra_hex_files_present(
215
217
  assert result.hex_path.read_bytes() == b"correct-bytes"
216
218
 
217
219
 
220
+ def test_compile_error_summarizes_multiline_stderr_to_first_line(tmp_path, mocker) -> None:
221
+ """The DAG's own per-task log line must stay short (see dag.py) - the
222
+ exception message is a one-line summary, not the whole compiler
223
+ output verbatim."""
224
+ config = _config(tmp_path)
225
+ _write_sketch(config.firmware_source)
226
+ multiline_stderr = (
227
+ "motor_test.ino: In function 'void handleTestCommand(const char*)':\n"
228
+ "motor_test.ino:210:3: error: 'strtol' was not declared in this scope\n"
229
+ " (many more lines of compiler context would normally follow)\n"
230
+ )
231
+ mocker.patch(
232
+ "software.arduino_updates.compiler.subprocess.run",
233
+ return_value=_completed(1, multiline_stderr),
234
+ )
235
+
236
+ with pytest.raises(CompileError) as exc_info:
237
+ compile_sketch(config)
238
+
239
+ message = str(exc_info.value)
240
+ assert "strtol" in message
241
+ assert "many more lines" not in message # only the first line, not the whole blob
242
+
243
+
244
+ def test_compile_logs_full_stderr_separately_from_the_summary(tmp_path, mocker, caplog) -> None:
245
+ """Per your own requirement: the full detailed compiler output must
246
+ still be available in the log, even though the exception/DAG summary
247
+ is deliberately short."""
248
+ import logging
249
+
250
+ config = _config(tmp_path)
251
+ _write_sketch(config.firmware_source)
252
+ multiline_stderr = "line one: error: bad\nline two: note: context\nline three: note: more context\n"
253
+ mocker.patch(
254
+ "software.arduino_updates.compiler.subprocess.run",
255
+ return_value=_completed(1, multiline_stderr),
256
+ )
257
+
258
+ with caplog.at_level(logging.ERROR):
259
+ with pytest.raises(CompileError):
260
+ compile_sketch(config)
261
+
262
+ assert "line two: note: context" in caplog.text
263
+ assert "line three: note: more context" in caplog.text
264
+
265
+
266
+ def test_compile_logs_resolved_configuration(tmp_path, mocker, caplog) -> None:
267
+ """Part of the diagnostic-visibility requirement: board/port/paths
268
+ must be visible in the log without needing to guess at runtime state -
269
+ and none of these are credentials (MQTT auth is a separate config
270
+ class), so logging them in full is safe."""
271
+ import logging
272
+
273
+ config = _config(tmp_path)
274
+ _write_sketch(config.firmware_source)
275
+ mocker.patch(
276
+ "software.arduino_updates.compiler.subprocess.run",
277
+ side_effect=lambda command, **kwargs: (
278
+ (Path(command[command.index("--output-dir") + 1]) / "sketch.ino.hex").write_bytes(b"x"),
279
+ _completed(0),
280
+ )[-1],
281
+ )
282
+
283
+ with caplog.at_level(logging.INFO):
284
+ compile_sketch(config)
285
+
286
+ assert "board=uno" in caplog.text
287
+ assert str(config.firmware_source) in caplog.text
288
+ assert "Resolved arduino-cli executable: /usr/bin/arduino-cli" in caplog.text
289
+
290
+
218
291
  def test_compile_raises_when_no_hex_produced(tmp_path, mocker) -> None:
219
292
  config = _config(tmp_path)
220
293
  _write_sketch(config.firmware_source)
@@ -226,14 +299,14 @@ def test_compile_raises_when_no_hex_produced(tmp_path, mocker) -> None:
226
299
  compile_sketch(config)
227
300
 
228
301
 
229
- def test_build_subprocess_env_overrides_home_but_keeps_rest_of_environment(
302
+ def testbuild_subprocess_env_overrides_home_but_keeps_rest_of_environment(
230
303
  tmp_path, monkeypatch
231
304
  ) -> None:
232
305
  monkeypatch.setenv("PATH", "/usr/bin:/bin")
233
306
  monkeypatch.setenv("HOME", "/home/jetstan")
234
307
  config = _config(tmp_path)
235
308
 
236
- env = _build_subprocess_env(config)
309
+ env = build_subprocess_env(config)
237
310
 
238
311
  home = config.arduino_cli_config_file.parent
239
312
  assert env["HOME"] == str(home)