jetstan-ev-software 0.0.1__py3-none-any.whl

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 (47) hide show
  1. jetstan_ev_software-0.0.1.dist-info/METADATA +14 -0
  2. jetstan_ev_software-0.0.1.dist-info/RECORD +47 -0
  3. jetstan_ev_software-0.0.1.dist-info/WHEEL +5 -0
  4. jetstan_ev_software-0.0.1.dist-info/top_level.txt +1 -0
  5. software/__init__.py +6 -0
  6. software/arduino_updates/__init__.py +104 -0
  7. software/arduino_updates/compiler.py +176 -0
  8. software/arduino_updates/config.py +190 -0
  9. software/arduino_updates/discovery.py +71 -0
  10. software/arduino_updates/exceptions.py +49 -0
  11. software/arduino_updates/firmware.py +61 -0
  12. software/arduino_updates/flasher.py +183 -0
  13. software/arduino_updates/sample_firmware/README.md +45 -0
  14. software/arduino_updates/sample_firmware/motor_test/motor_test.ino +284 -0
  15. software/arduino_updates/state_store.py +47 -0
  16. software/arduino_updates/verifier.py +32 -0
  17. software/deployment/__init__.py +35 -0
  18. software/deployment/dag.py +134 -0
  19. software/deployment/dependencies.py +77 -0
  20. software/deployment/pipeline.py +80 -0
  21. software/frontend/__init__.py +1 -0
  22. software/frontend/index.html +498 -0
  23. software/gen_sample/__init__.py +3 -0
  24. software/gen_sample/simulator.py +92 -0
  25. software/handlers.py +28 -0
  26. software/logic/__init__.py +7 -0
  27. software/logic/calculations.py +157 -0
  28. software/sensors/__init__.py +20 -0
  29. software/sensors/motor_control.py +73 -0
  30. software/sensors/serial_telemetry.py +135 -0
  31. software/sensors/telemetry_store.py +67 -0
  32. software/soc/__init__.py +21 -0
  33. software/soc/api.py +100 -0
  34. software/soc/config.py +164 -0
  35. software/soc/exceptions.py +24 -0
  36. software/soc/features.py +114 -0
  37. software/soc/model.py +175 -0
  38. software/soc/predictor.py +117 -0
  39. software/soc/schemas.py +59 -0
  40. software/soc/service.py +94 -0
  41. software/soc/soc_dashboard.html +313 -0
  42. software/soc/telemetry.py +68 -0
  43. software/soc/xgboost_soc.onnx +0 -0
  44. software/test/README.md +74 -0
  45. software/test/__init__.py +7 -0
  46. software/test/jetstan-dashboard.service +83 -0
  47. software/test/server.py +187 -0
@@ -0,0 +1,14 @@
1
+ Metadata-Version: 2.4
2
+ Name: jetstan_ev_software
3
+ Version: 0.0.1
4
+ Summary: Jetstan vehicle software - the OTA-deployable application payload that runs on the vehicle's Raspberry Pi (import package: software).
5
+ Requires-Python: >=3.11
6
+ Requires-Dist: python-dotenv==1.2.2
7
+ Requires-Dist: fastapi==0.140.7
8
+ Requires-Dist: uvicorn==0.51.0
9
+ Requires-Dist: numpy==2.5.1
10
+ Requires-Dist: onnxruntime==1.28.0
11
+ Provides-Extra: dev
12
+ Requires-Dist: pytest>=8.0.0; extra == "dev"
13
+ Requires-Dist: pytest-mock>=3.14.0; extra == "dev"
14
+ Requires-Dist: httpx>=0.28.0; extra == "dev"
@@ -0,0 +1,47 @@
1
+ software/__init__.py,sha256=Ur7_wSujXSmZAE4L2mWJDU85bV0w5UqCcE1LMJ5Iru4,247
2
+ software/handlers.py,sha256=kSpeNLlIhNxYa2njFOGuImnFflMo0NXcTeglHS0ngR0,810
3
+ software/arduino_updates/__init__.py,sha256=CCkcxbHXRI7XTzY1lOXDc97QTwVYckMosltLpOysW6I,4394
4
+ software/arduino_updates/compiler.py,sha256=JBqY4VlZEzn0XqEtsVS4hcf25-YCKccjm_MSytjAu7k,7307
5
+ software/arduino_updates/config.py,sha256=f4FFDW-ySFIzJGNreiSCpEIOSLqdS_cYuF1DLYdY0tg,7832
6
+ software/arduino_updates/discovery.py,sha256=XEiT7hq3EApIxJlf1PtSwo2ZqIYaPyloLyTSsnKY-bc,2245
7
+ software/arduino_updates/exceptions.py,sha256=xQVwczyei4yhxCaCI9GNzpe0NWKh6uXQowuA0AHBUVE,1620
8
+ software/arduino_updates/firmware.py,sha256=a-Aw-EvwpjwFV77TXEFFzOYRAnv87Ixw-EtElhm-XDI,2051
9
+ software/arduino_updates/flasher.py,sha256=sL_sBqS9jDiq9BucGFSA1h4o0yPupXAu_wt9ZDqibdk,6414
10
+ software/arduino_updates/state_store.py,sha256=jpiMfMiZmT3_bWrJmNzzEB1vJi9kztKLpdE1Y-BFd2E,1707
11
+ software/arduino_updates/verifier.py,sha256=gLIni31ven1mq5HEQ_SJJs9Ro-7vR3kCrzJQltLWuho,1271
12
+ software/arduino_updates/sample_firmware/README.md,sha256=DniGlVk-xhlZ4WWZRo6eoDsEQRC017vf3n-zXWCaQRk,2262
13
+ software/arduino_updates/sample_firmware/motor_test/motor_test.ino,sha256=ddCU216TBNcYy-7iX6INUD6Ro8xHfPudDrITrU6gqEI,9422
14
+ software/deployment/__init__.py,sha256=hhMezX59LYJUD9NAxNjizgrZU1rHWExD54LS0xWwjqw,1225
15
+ software/deployment/dag.py,sha256=vbL5VIWFcFAMjdMYfOjqGNDskzN5DM64TkICIw_YyA0,4446
16
+ software/deployment/dependencies.py,sha256=42435o5KDo52CgRRu2AXzLHNQnSF92kaANVhPmI0CrE,2984
17
+ software/deployment/pipeline.py,sha256=jUdlGFNeIAF4O6twtsQ65q9jrLWJF8DORDSKoK-Htt0,2753
18
+ software/frontend/__init__.py,sha256=O84RGrSg6DPKFWvdFS2KGnYJr_8CJiHzDIJoqklnfa0,85
19
+ software/frontend/index.html,sha256=NSbTH_IKeOMIoR_hLAfNkBECfjX1bF5ZFBuesMJfkVA,17677
20
+ software/gen_sample/__init__.py,sha256=aRZoEkHbqqIq1VrsudxOat6CNxzsvP_GAFGaL3Ap5Zo,106
21
+ software/gen_sample/simulator.py,sha256=IR7xFfekSEFGyOOKbWM4CunIfmpzo54BbI4SRyjHDaM,3135
22
+ software/logic/__init__.py,sha256=D0nhn_PEQkB__7YjYq3mwujUGlAmZ-tCrPRna0elnuQ,357
23
+ software/logic/calculations.py,sha256=boJ5J6UNKr-5qAygm7jSQpAN993NizCF9hmE7GvRGIo,5583
24
+ software/sensors/__init__.py,sha256=LEw2zS5IUGr5XrijEE7hIi5M20EDgDMz4jr-wSB45Fs,885
25
+ software/sensors/motor_control.py,sha256=syyEWxUUkwEF-SgtJ5zHDfOtHXsiegNxaEQzAM_mYts,2663
26
+ software/sensors/serial_telemetry.py,sha256=ddowPjR5GMyb1EgT0Vho4F3lCoD7VmyyiLj5OAVNVNY,5362
27
+ software/sensors/telemetry_store.py,sha256=oqEVKauWDX73ALdQsbRqNpVSD55gdY9cDpn14tOm-l4,2371
28
+ software/soc/__init__.py,sha256=JT8ZpXZ9QLf_Z3fRkl7MpMs6P0ElBaOR6mkO39faWqo,857
29
+ software/soc/api.py,sha256=hPp2Spq9-VRg118VPxG7amMyTcRlYpNSgD3extnXpsE,3751
30
+ software/soc/config.py,sha256=hcD4jbb1AHhgP8N5vY8PmosaPRv3tgMkE8YMfcML008,6837
31
+ software/soc/exceptions.py,sha256=a7KjBc5sqxX9lwn3ZS3qZZHQpvcnrAwcmPO25QKqELQ,692
32
+ software/soc/features.py,sha256=D5z3irud7FZdbCio7wRr7jLyl7fYAdcHFQL55da16yE,4064
33
+ software/soc/model.py,sha256=IPV2KTpTN-4-mQbZsAHV3sJjhQW_DU-lWU4JOrY2YTk,6848
34
+ software/soc/predictor.py,sha256=LEl3cXhAe6OqLdf51AXglGPWx5F3WvPii-O3LxEsj9w,4450
35
+ software/soc/schemas.py,sha256=w4NKALrGbEf66xc5yLQ8ZvSON6OLXQxbc8eW6o_D2CQ,1724
36
+ software/soc/service.py,sha256=Jje-9zTah_r4KvsYV-gj0EdcaJMpyHo_J3IwI9tKRtY,3580
37
+ software/soc/soc_dashboard.html,sha256=1ZlfVzScO3lfghP0Y1TdQfTHA2RLoHFlplYhPNKFMjs,9009
38
+ software/soc/telemetry.py,sha256=ZiWckniOQcDpdMija5-YlDl1kO_ShR_XFux2IrTCiUQ,2465
39
+ software/soc/xgboost_soc.onnx,sha256=ojwvTpXiRBv9yu4laqGEtPkE3W4ZOzLYx7KZFmQR0aU,4404369
40
+ software/test/README.md,sha256=On_W6-nm8NwWweoEFKIC4ihqOS4nyjdUL9vUfvi-rIk,2850
41
+ software/test/__init__.py,sha256=5_9b9r-SbgHkWSNW9XIzNf3-EKbG2XBx_OaU55of4xU,320
42
+ software/test/jetstan-dashboard.service,sha256=RAvBV3g3TumdD0fOmTJIwFq1xa3sm29yCobpWx9IL-E,3895
43
+ software/test/server.py,sha256=S4B3z4UQ444deWyHm_n5ggGr6XHi_xXeMelbgalfyIs,7455
44
+ jetstan_ev_software-0.0.1.dist-info/METADATA,sha256=yprKbSaaSC15z8gNltTKUmoB4rVYwmvsSJWESPruZik,567
45
+ jetstan_ev_software-0.0.1.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
46
+ jetstan_ev_software-0.0.1.dist-info/top_level.txt,sha256=NL49ot0GYlzscq4JFOLdD0rP6vgk7o9AGNlsquuEWV0,9
47
+ jetstan_ev_software-0.0.1.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.0.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1 @@
1
+ software
software/__init__.py ADDED
@@ -0,0 +1,6 @@
1
+ """Your application code goes here.
2
+
3
+ This package is separate from ``jetstan_agent`` (the OTA/MQTT plumbing)
4
+ on purpose: ``jetstan_agent`` stays generic and stable, this is where
5
+ your actual product logic lives and changes with every release.
6
+ """
@@ -0,0 +1,104 @@
1
+ """Arduino firmware OTA updates: discover, flash, and verify over USB serial.
2
+
3
+ :func:`check_and_flash` is what ``software/deployment/pipeline.py``'s
4
+ ``flash_arduino_firmware`` task calls - the DAG runner in
5
+ ``software/deployment/dag.py`` already provides the "never crash the
6
+ caller" safety net, so the task itself uses the raising variant.
7
+ :func:`sync_firmware_safe` is a standalone convenience wrapper with that
8
+ same safety net built in, for calling this module directly outside the
9
+ DAG (scripts, a REPL, a future manual CLI subcommand).
10
+
11
+ Board-family support is added by registering a new :class:`BoardFlasher` in
12
+ ``flasher.py`` - adding STM32/ESP32/RP2040 support later never requires
13
+ changes here or in ``jetstan_agent``.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import logging
19
+ from dataclasses import dataclass
20
+
21
+ from software.arduino_updates.config import ArduinoConfig
22
+ from software.arduino_updates.discovery import resolve_port
23
+ from software.arduino_updates.exceptions import ArduinoUpdateError, FirmwareNotFoundError
24
+ from software.arduino_updates.firmware import Firmware, FirmwareStateStore
25
+ from software.arduino_updates.flasher import get_flasher
26
+ from software.arduino_updates.verifier import verify_flash
27
+
28
+ logger = logging.getLogger(__name__)
29
+
30
+ __all__ = [
31
+ "ArduinoSyncResult",
32
+ "check_and_flash",
33
+ "sync_firmware_safe",
34
+ ]
35
+
36
+
37
+ @dataclass(frozen=True)
38
+ class ArduinoSyncResult:
39
+ """Outcome of one :func:`check_and_flash` call."""
40
+
41
+ attempted: bool
42
+ flashed: bool
43
+ detail: str
44
+
45
+
46
+ def check_and_flash(config: ArduinoConfig | None = None) -> ArduinoSyncResult:
47
+ """Discover, flash (if changed), and verify Arduino firmware.
48
+
49
+ Raises :class:`ArduinoUpdateError` (or a subclass) on any failure -
50
+ this is the version used inside the deployment DAG (see the module
51
+ docstring), where the DAG runner itself handles catching, logging,
52
+ and not crashing the caller. Calling this directly and outside the
53
+ DAG, use :func:`sync_firmware_safe` instead, which never raises.
54
+ """
55
+ config = config or ArduinoConfig.from_env()
56
+
57
+ if not config.enabled:
58
+ logger.debug("Arduino updates disabled (ARDUINO_ENABLED=false); skipping.")
59
+ return ArduinoSyncResult(attempted=False, flashed=False, detail="disabled")
60
+
61
+ try:
62
+ firmware = Firmware.load(config.firmware_path)
63
+ except FirmwareNotFoundError:
64
+ logger.info("No Arduino firmware found at %s; skipping.", config.firmware_path)
65
+ return ArduinoSyncResult(attempted=False, flashed=False, detail="no firmware present")
66
+
67
+ state_store = FirmwareStateStore(config.state_dir)
68
+ if not state_store.needs_flash(firmware):
69
+ logger.info(
70
+ "Arduino firmware unchanged (%s); skipping flash.", firmware.fingerprint[:12]
71
+ )
72
+ return ArduinoSyncResult(attempted=False, flashed=False, detail="already up to date")
73
+
74
+ port = resolve_port(config.port)
75
+ logger.info("Arduino detected on %s", port)
76
+
77
+ flasher = get_flasher(config.board_profile.family)
78
+ flasher.flash(port, firmware, config)
79
+ verify_flash(port, firmware, config, flasher)
80
+
81
+ state_store.write(firmware.fingerprint)
82
+ logger.info("Arduino firmware update complete (%s)", firmware.fingerprint[:12])
83
+ return ArduinoSyncResult(attempted=True, flashed=True, detail=firmware.fingerprint)
84
+
85
+
86
+ def sync_firmware_safe(config: ArduinoConfig | None = None) -> ArduinoSyncResult:
87
+ """Same as :func:`check_and_flash`, but never raises.
88
+
89
+ Arduino firmware problems must never prevent the OTA agent itself
90
+ from starting and connecting to MQTT - the same "log it and carry
91
+ on" rule ``message_router.py`` applies to bad commands applies here
92
+ to bad hardware. Catches ``Exception`` broadly, not just
93
+ ``ArduinoUpdateError``, deliberately: this is a best-effort startup
94
+ side-check, and a bug here (not just an expected hardware failure)
95
+ must still never take the whole agent down with it.
96
+ """
97
+ try:
98
+ return check_and_flash(config)
99
+ except ArduinoUpdateError as exc:
100
+ logger.error("Arduino firmware update failed: %s", exc)
101
+ return ArduinoSyncResult(attempted=True, flashed=False, detail=str(exc))
102
+ except Exception: # noqa: BLE001 - intentional: see docstring
103
+ logger.exception("Arduino firmware update failed unexpectedly.")
104
+ return ArduinoSyncResult(attempted=True, flashed=False, detail="unexpected error")
@@ -0,0 +1,176 @@
1
+ """Compiles the shipped Arduino sketch source via ``arduino-cli``.
2
+
3
+ Kept inside ``arduino_updates`` (not ``deployment``) because it's
4
+ genuinely AVR/Arduino-specific, the same way ``flasher.py`` is - a
5
+ future board family gets its own compiler module the same way it gets
6
+ its own ``BoardFlasher``.
7
+
8
+ Deliberately never installs ``arduino-cli`` itself: if it's missing,
9
+ that means the Pi never went through the one-time
10
+ ``sudo jetstan-agent-install`` provisioning step, and this raises a
11
+ clear, actionable error instead of trying to self-elevate and install
12
+ system packages in response to a remote OTA trigger.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import hashlib
18
+ import logging
19
+ import os
20
+ import shutil
21
+ import subprocess
22
+ import tempfile
23
+ from dataclasses import dataclass
24
+ from pathlib import Path
25
+
26
+ from software.arduino_updates.config import ArduinoConfig
27
+ from software.arduino_updates.exceptions import CompileError, FirmwareNotFoundError
28
+ from software.arduino_updates.state_store import FingerprintStateStore, atomic_write
29
+
30
+ logger = logging.getLogger(__name__)
31
+
32
+ _SOURCE_STATE_FILENAME = "arduino_source.version"
33
+ _HASH_CHUNK_SIZE = 65536
34
+
35
+
36
+ @dataclass(frozen=True)
37
+ class CompileResult:
38
+ """Outcome of one :func:`compile_sketch` call."""
39
+
40
+ hex_path: Path
41
+ skipped: bool
42
+
43
+
44
+ class SourceStateStore(FingerprintStateStore):
45
+ """Persists the fingerprint of the last-compiled sketch source.
46
+
47
+ Separate from :class:`~software.arduino_updates.firmware.FirmwareStateStore`,
48
+ which tracks the last-*flashed* ``.hex`` - this one tracks the
49
+ last-*compiled* source, so an unchanged sketch skips the (comparatively
50
+ expensive, log-noisy) ``arduino-cli compile`` step on every single
51
+ OTA-triggered restart, not just the flash step.
52
+ """
53
+
54
+ def __init__(self, state_dir: Path) -> None:
55
+ super().__init__(state_dir, _SOURCE_STATE_FILENAME)
56
+
57
+
58
+ def _fingerprint_source(source_dir: Path) -> str:
59
+ """SHA-256 over every file's (relative path, contents), sorted for determinism."""
60
+ digest = hashlib.sha256()
61
+ for file_path in sorted(p for p in source_dir.rglob("*") if p.is_file()):
62
+ digest.update(str(file_path.relative_to(source_dir)).encode())
63
+ with file_path.open("rb") as handle:
64
+ for chunk in iter(lambda: handle.read(_HASH_CHUNK_SIZE), b""):
65
+ digest.update(chunk)
66
+ return digest.hexdigest()
67
+
68
+
69
+ def compile_sketch(config: ArduinoConfig) -> CompileResult:
70
+ """Compile ``config.firmware_source`` into ``config.firmware_path``.
71
+
72
+ Skips compiling (returns ``skipped=True``) if the source hasn't
73
+ changed since the last successful compile and the previous output
74
+ still exists. Raises :class:`CompileError` if ``arduino-cli`` isn't
75
+ on PATH, the compile itself fails, or it times out.
76
+ """
77
+ if not config.firmware_source.is_dir():
78
+ raise FirmwareNotFoundError(f"Arduino sketch source not found: {config.firmware_source}")
79
+
80
+ source_fingerprint = _fingerprint_source(config.firmware_source)
81
+ state_store = SourceStateStore(config.state_dir)
82
+ if state_store.read() == source_fingerprint and config.firmware_path.is_file():
83
+ logger.info("Arduino source unchanged; skipping compile.")
84
+ return CompileResult(hex_path=config.firmware_path, skipped=True)
85
+
86
+ arduino_cli = _require_arduino_cli(config.arduino_cli_path)
87
+ fqbn = config.board_profile.fqbn
88
+
89
+ logger.info("Compile started (%s, fqbn=%s)", config.firmware_source.name, fqbn)
90
+ with tempfile.TemporaryDirectory(prefix="jetstan-arduino-build-") as tmp_dir:
91
+ command = [
92
+ arduino_cli,
93
+ # Explicit, not $HOME-derived: the jetstan service account has
94
+ # no home directory (see ArduinoConfig's docstring), so letting
95
+ # arduino-cli fall back to its default $HOME/.arduino15 lookup
96
+ # fails outright instead of just using the wrong location.
97
+ "--config-file",
98
+ str(config.arduino_cli_config_file),
99
+ "compile",
100
+ "--fqbn",
101
+ fqbn,
102
+ str(config.firmware_source),
103
+ "--output-dir",
104
+ tmp_dir,
105
+ ]
106
+ try:
107
+ result = subprocess.run(
108
+ command,
109
+ capture_output=True,
110
+ text=True,
111
+ timeout=config.compile_timeout_seconds,
112
+ check=False,
113
+ env=_build_subprocess_env(config),
114
+ )
115
+ except subprocess.TimeoutExpired as exc:
116
+ raise CompileError(
117
+ f"arduino-cli compile did not finish within {config.compile_timeout_seconds}s."
118
+ ) from exc
119
+
120
+ if result.returncode != 0:
121
+ raise CompileError(f"arduino-cli compile failed: {result.stderr.strip()}")
122
+
123
+ # arduino-cli names its output <sketch-folder-name>.ino.hex - matching
124
+ # that exact name (rather than globbing "*.hex" and picking one) means
125
+ # this never has to guess if a board profile's build ever produces
126
+ # more than one .hex (e.g. a separate bootloader image).
127
+ expected_name = f"{config.firmware_source.name}.ino.hex"
128
+ produced_path = Path(tmp_dir) / expected_name
129
+ if not produced_path.is_file():
130
+ raise CompileError(
131
+ f"arduino-cli reported success but {expected_name} was not found in {tmp_dir}."
132
+ )
133
+
134
+ atomic_write(config.firmware_path, produced_path.read_bytes())
135
+
136
+ state_store.write(source_fingerprint)
137
+ logger.info("Compile completed")
138
+ return CompileResult(hex_path=config.firmware_path, skipped=False)
139
+
140
+
141
+ def _build_subprocess_env(config: ArduinoConfig) -> dict[str, str]:
142
+ """Environment for the arduino-cli subprocess, with home-relative
143
+ lookups pinned to a directory ``jetstan`` can actually write to.
144
+
145
+ ``--config-file`` alone is not enough: beyond the settings it
146
+ controls (``directories.data``/``user``/``downloads``), arduino-cli
147
+ (a Go binary) separately resolves things like its build-cache
148
+ directory the way Go's standard library typically does - via
149
+ ``$HOME`` directly in some code paths, or via the XDG base-directory
150
+ variables (``$XDG_CACHE_HOME``/``$XDG_CONFIG_HOME``) in others -
151
+ independent of ``--config-file`` entirely. The ``jetstan`` service
152
+ account has no home directory, so any of these can fail outright
153
+ (confirmed in production: ``mkdir /home/jetstan: permission
154
+ denied``). Rather than chase each individual internal path as it
155
+ surfaces, every one of these lookups is pinned to the same writable
156
+ directory here - the same one INSTALL.md's one-time provisioning
157
+ step already creates and ``chown``s to ``jetstan``.
158
+ """
159
+ home = config.arduino_cli_config_file.parent
160
+ env = os.environ.copy()
161
+ env["HOME"] = str(home)
162
+ env["XDG_CACHE_HOME"] = str(home / ".cache")
163
+ env["XDG_CONFIG_HOME"] = str(home / ".config")
164
+ return env
165
+
166
+
167
+ def _require_arduino_cli(configured_path: str) -> str:
168
+ resolved = shutil.which(configured_path)
169
+ if resolved is None and Path(configured_path).is_file():
170
+ resolved = configured_path
171
+ if resolved is None:
172
+ raise CompileError(
173
+ f"arduino-cli not found (looked for '{configured_path}' on PATH). "
174
+ "This is a one-time host provisioning step - see INSTALL.md."
175
+ )
176
+ return resolved
@@ -0,0 +1,190 @@
1
+ """Configuration for Arduino firmware updates, read from environment variables.
2
+
3
+ Values are expected to arrive via ``/etc/jetstan/agent.env`` - the same
4
+ ``EnvironmentFile=`` the systemd unit already loads for MQTT settings -
5
+ so enabling this feature is an env-var + restart, never a reinstall or
6
+ a code change. See ``jetstan_agent/templates/agent.env.example`` for
7
+ the documented variables.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import os
13
+ from dataclasses import dataclass
14
+ from importlib.resources import files
15
+ from pathlib import Path
16
+
17
+ from dotenv import load_dotenv
18
+
19
+ from software.arduino_updates.exceptions import UnsupportedBoardError
20
+
21
+ # Mirrors jetstan_agent/config.py: a no-op in production (systemd already
22
+ # populates the environment via EnvironmentFile=), convenient for local
23
+ # dev. Explicit path (software/.env), not a bare load_dotenv() relying
24
+ # on upward search from cwd - this module is three levels under the
25
+ # software/ project root regardless of the calling process's cwd.
26
+ load_dotenv(Path(__file__).resolve().parent.parent.parent / ".env")
27
+
28
+ _ENV_ENABLED = "ARDUINO_ENABLED"
29
+ _ENV_BOARD = "ARDUINO_BOARD"
30
+ _ENV_PORT = "ARDUINO_PORT"
31
+ _ENV_BAUD = "ARDUINO_BAUD"
32
+ _ENV_FIRMWARE_PATH = "ARDUINO_FIRMWARE_PATH"
33
+ _ENV_STATE_DIR = "ARDUINO_STATE_DIR"
34
+ _ENV_FLASH_RETRIES = "ARDUINO_FLASH_RETRIES"
35
+ _ENV_FLASH_RETRY_DELAY_SECONDS = "ARDUINO_FLASH_RETRY_DELAY_SECONDS"
36
+ _ENV_FLASH_TIMEOUT_SECONDS = "ARDUINO_FLASH_TIMEOUT_SECONDS"
37
+ _ENV_VERIFY_TIMEOUT_SECONDS = "ARDUINO_VERIFY_TIMEOUT_SECONDS"
38
+ _ENV_AVRDUDE_PATH = "ARDUINO_AVRDUDE_PATH"
39
+ _ENV_AUTO_COMPILE = "ARDUINO_AUTO_COMPILE"
40
+ _ENV_FIRMWARE_SOURCE = "ARDUINO_FIRMWARE_SOURCE"
41
+ _ENV_ARDUINO_CLI_PATH = "ARDUINO_CLI_PATH"
42
+ _ENV_COMPILE_TIMEOUT_SECONDS = "ARDUINO_COMPILE_TIMEOUT_SECONDS"
43
+ _ENV_ARDUINO_CLI_CONFIG_FILE = "ARDUINO_CLI_CONFIG_FILE"
44
+
45
+ DEFAULT_ENABLED = False
46
+ DEFAULT_BOARD = "uno"
47
+ DEFAULT_PORT = "auto"
48
+ DEFAULT_BAUD = 115200
49
+ DEFAULT_STATE_DIR = "/var/lib/jetstan"
50
+ DEFAULT_FLASH_RETRIES = 3
51
+ # A failed/interrupted write can leave an AVR bootloader needing a moment
52
+ # to recover before it'll respond correctly again - retrying instantly
53
+ # in a tight loop doesn't give it that. See flasher.py's retry loop.
54
+ DEFAULT_FLASH_RETRY_DELAY_SECONDS = 3
55
+ DEFAULT_FLASH_TIMEOUT_SECONDS = 60
56
+ DEFAULT_VERIFY_TIMEOUT_SECONDS = 30
57
+ DEFAULT_AVRDUDE_PATH = "avrdude"
58
+ DEFAULT_AUTO_COMPILE = True
59
+ DEFAULT_ARDUINO_CLI_PATH = "arduino-cli"
60
+ DEFAULT_COMPILE_TIMEOUT_SECONDS = 60
61
+ _FIRMWARE_HEX_FILENAME = "firmware.hex"
62
+ _ARDUINO_CLI_CONFIG_RELATIVE_PATH = "arduino-cli/arduino-cli.yaml"
63
+ _PACKAGED_SKETCH = ("software.arduino_updates", "sample_firmware/motor_test")
64
+
65
+
66
+ def _default_firmware_source() -> Path:
67
+ """Resolve the packaged sample sketch as a real filesystem path.
68
+
69
+ Only meaningful for a normal pip/pipx install (extracted to disk, not
70
+ zipimport) - which is the only way this project is ever deployed. If
71
+ the ``software.arduino_updates`` package itself can't be resolved
72
+ (only possible if this module were somehow imported from outside its
73
+ own package - not a real deployment scenario), fall back to a path
74
+ that simply won't exist; ``compiler.py``'s own ``is_dir()`` check then
75
+ raises a clear ``FirmwareNotFoundError`` at actual use time instead of
76
+ failing config loading itself over it.
77
+ """
78
+ package, relative = _PACKAGED_SKETCH
79
+ try:
80
+ return Path(str(files(package) / relative))
81
+ except ModuleNotFoundError:
82
+ return Path("/nonexistent/sample_firmware/motor_test")
83
+
84
+
85
+ @dataclass(frozen=True)
86
+ class BoardProfile:
87
+ """Flashing parameters for one board type.
88
+
89
+ ``family`` selects which :class:`~software.arduino_updates.flasher.BoardFlasher`
90
+ handles it (see ``flasher.FLASHERS``) - multiple board names can
91
+ share one family, and adding a new family (e.g. ``"stm32"``) never
92
+ requires touching the boards that already work.
93
+ """
94
+
95
+ mcu: str
96
+ programmer: str
97
+ fqbn: str
98
+ family: str = "avr"
99
+
100
+
101
+ _BOARD_PROFILES: dict[str, BoardProfile] = {
102
+ "uno": BoardProfile(mcu="atmega328p", programmer="arduino", fqbn="arduino:avr:uno"),
103
+ "nano": BoardProfile(mcu="atmega328p", programmer="arduino", fqbn="arduino:avr:nano"),
104
+ "mega2560": BoardProfile(mcu="atmega2560", programmer="wiring", fqbn="arduino:avr:mega"),
105
+ }
106
+
107
+
108
+ @dataclass(frozen=True)
109
+ class ArduinoConfig:
110
+ """Runtime configuration for Arduino firmware updates.
111
+
112
+ ``arduino_cli_config_file`` matters more than it looks: the service
113
+ runs as the unprivileged, home-less ``jetstan`` account
114
+ (``useradd --no-create-home``), so arduino-cli's normal
115
+ ``$HOME/.arduino15/arduino-cli.yaml`` auto-resolution has nowhere
116
+ valid to look. Pointing it explicitly at a file under ``state_dir``
117
+ (which the systemd unit's ``StateDirectory=`` already makes real and
118
+ writable) sidesteps that entirely instead of fighting $HOME.
119
+ """
120
+
121
+ enabled: bool
122
+ board: str
123
+ port: str
124
+ baud: int
125
+ firmware_path: Path
126
+ state_dir: Path
127
+ flash_retries: int
128
+ flash_retry_delay_seconds: int
129
+ flash_timeout_seconds: int
130
+ verify_timeout_seconds: int
131
+ avrdude_path: str
132
+ auto_compile: bool
133
+ firmware_source: Path
134
+ arduino_cli_path: str
135
+ arduino_cli_config_file: Path
136
+ compile_timeout_seconds: int
137
+
138
+ @property
139
+ def board_profile(self) -> BoardProfile:
140
+ try:
141
+ return _BOARD_PROFILES[self.board]
142
+ except KeyError as exc:
143
+ raise UnsupportedBoardError(
144
+ f"Unsupported ARDUINO_BOARD '{self.board}'; known boards: "
145
+ f"{', '.join(sorted(_BOARD_PROFILES))}"
146
+ ) from exc
147
+
148
+ @classmethod
149
+ def from_env(cls) -> "ArduinoConfig":
150
+ """Build configuration from environment variables, applying defaults."""
151
+ state_dir = Path(os.environ.get(_ENV_STATE_DIR, DEFAULT_STATE_DIR))
152
+ default_firmware_path = state_dir / _FIRMWARE_HEX_FILENAME
153
+ default_arduino_cli_config_file = state_dir / _ARDUINO_CLI_CONFIG_RELATIVE_PATH
154
+
155
+ return cls(
156
+ enabled=_parse_bool(os.environ.get(_ENV_ENABLED), DEFAULT_ENABLED),
157
+ board=os.environ.get(_ENV_BOARD, DEFAULT_BOARD).strip().lower(),
158
+ port=os.environ.get(_ENV_PORT, DEFAULT_PORT).strip(),
159
+ baud=int(os.environ.get(_ENV_BAUD, DEFAULT_BAUD)),
160
+ firmware_path=Path(os.environ.get(_ENV_FIRMWARE_PATH, str(default_firmware_path))),
161
+ state_dir=state_dir,
162
+ flash_retries=int(os.environ.get(_ENV_FLASH_RETRIES, DEFAULT_FLASH_RETRIES)),
163
+ flash_retry_delay_seconds=int(
164
+ os.environ.get(_ENV_FLASH_RETRY_DELAY_SECONDS, DEFAULT_FLASH_RETRY_DELAY_SECONDS)
165
+ ),
166
+ flash_timeout_seconds=int(
167
+ os.environ.get(_ENV_FLASH_TIMEOUT_SECONDS, DEFAULT_FLASH_TIMEOUT_SECONDS)
168
+ ),
169
+ verify_timeout_seconds=int(
170
+ os.environ.get(_ENV_VERIFY_TIMEOUT_SECONDS, DEFAULT_VERIFY_TIMEOUT_SECONDS)
171
+ ),
172
+ avrdude_path=os.environ.get(_ENV_AVRDUDE_PATH, DEFAULT_AVRDUDE_PATH),
173
+ auto_compile=_parse_bool(os.environ.get(_ENV_AUTO_COMPILE), DEFAULT_AUTO_COMPILE),
174
+ firmware_source=Path(
175
+ os.environ.get(_ENV_FIRMWARE_SOURCE, str(_default_firmware_source()))
176
+ ),
177
+ arduino_cli_path=os.environ.get(_ENV_ARDUINO_CLI_PATH, DEFAULT_ARDUINO_CLI_PATH),
178
+ arduino_cli_config_file=Path(
179
+ os.environ.get(_ENV_ARDUINO_CLI_CONFIG_FILE, str(default_arduino_cli_config_file))
180
+ ),
181
+ compile_timeout_seconds=int(
182
+ os.environ.get(_ENV_COMPILE_TIMEOUT_SECONDS, DEFAULT_COMPILE_TIMEOUT_SECONDS)
183
+ ),
184
+ )
185
+
186
+
187
+ def _parse_bool(value: str | None, default: bool) -> bool:
188
+ if value is None or value.strip() == "":
189
+ return default
190
+ return value.strip().lower() in {"1", "true", "yes", "on"}
@@ -0,0 +1,71 @@
1
+ """Serial port discovery for connected Arduino-compatible boards.
2
+
3
+ Deliberately dependency-free (no ``pyserial``): the only thing needed
4
+ to find a board is which ``/dev/ttyUSB*``/``/dev/ttyACM*`` device nodes
5
+ currently exist, which a plain ``glob`` already answers.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import glob
11
+ import logging
12
+ import os
13
+
14
+ from software.arduino_updates.exceptions import (
15
+ AmbiguousBoardError,
16
+ ArduinoPermissionError,
17
+ BoardNotFoundError,
18
+ )
19
+
20
+ logger = logging.getLogger(__name__)
21
+
22
+ _PORT_GLOBS = ("/dev/ttyUSB*", "/dev/ttyACM*")
23
+ AUTO_PORT = "auto"
24
+
25
+
26
+ def list_candidate_ports() -> list[str]:
27
+ """Return every matching serial device node currently present, sorted."""
28
+ ports: list[str] = []
29
+ for pattern in _PORT_GLOBS:
30
+ ports.extend(glob.glob(pattern))
31
+ return sorted(ports)
32
+
33
+
34
+ def resolve_port(configured_port: str) -> str:
35
+ """Pick the serial port to flash.
36
+
37
+ An explicit path (anything other than ``"auto"``) is used as-is,
38
+ after confirming it exists and is accessible. ``"auto"`` requires
39
+ exactly one candidate board: zero means nothing is connected, and
40
+ more than one means guessing would risk flashing the wrong board,
41
+ so both are treated as errors rather than silently picking one.
42
+ """
43
+ if configured_port and configured_port != AUTO_PORT:
44
+ _check_accessible(configured_port)
45
+ return configured_port
46
+
47
+ candidates = list_candidate_ports()
48
+ if not candidates:
49
+ raise BoardNotFoundError(
50
+ "No Arduino-compatible serial port found "
51
+ "(checked /dev/ttyUSB* and /dev/ttyACM*)."
52
+ )
53
+ if len(candidates) > 1:
54
+ raise AmbiguousBoardError(
55
+ f"Multiple serial ports found ({', '.join(candidates)}); "
56
+ "set ARDUINO_PORT to the one to use."
57
+ )
58
+
59
+ port = candidates[0]
60
+ _check_accessible(port)
61
+ return port
62
+
63
+
64
+ def _check_accessible(port: str) -> None:
65
+ if not os.path.exists(port):
66
+ raise BoardNotFoundError(f"Configured serial port {port} does not exist.")
67
+ if not os.access(port, os.R_OK | os.W_OK):
68
+ raise ArduinoPermissionError(
69
+ f"Permission denied opening {port} "
70
+ "(is the service user in the 'dialout' group?)."
71
+ )
@@ -0,0 +1,49 @@
1
+ """Structured exceptions for Arduino firmware update operations.
2
+
3
+ Every failure mode the OTA integration needs to distinguish (missing
4
+ board, bad permissions, timeout, verification mismatch, ...) gets its
5
+ own subclass of :class:`ArduinoUpdateError`, so callers can catch or
6
+ log precisely what happened instead of parsing error strings.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+
12
+ class ArduinoUpdateError(RuntimeError):
13
+ """Base class for all Arduino firmware update errors."""
14
+
15
+
16
+ class BoardNotFoundError(ArduinoUpdateError):
17
+ """No connected Arduino board could be found (disconnected or no serial port)."""
18
+
19
+
20
+ class AmbiguousBoardError(ArduinoUpdateError):
21
+ """Multiple candidate serial ports exist and none is configured explicitly."""
22
+
23
+
24
+ class ArduinoPermissionError(ArduinoUpdateError):
25
+ """The serial port exists but the process lacks permission to open it."""
26
+
27
+
28
+ class FirmwareNotFoundError(ArduinoUpdateError):
29
+ """The configured firmware file does not exist or can't be read."""
30
+
31
+
32
+ class UnsupportedBoardError(ArduinoUpdateError):
33
+ """ARDUINO_BOARD (or its family) has no registered profile/flasher."""
34
+
35
+
36
+ class CompileError(ArduinoUpdateError):
37
+ """The sketch could not be compiled: toolchain missing, or a build failure."""
38
+
39
+
40
+ class FlashTimeoutError(ArduinoUpdateError):
41
+ """The flashing tool did not complete within the configured timeout."""
42
+
43
+
44
+ class FlashError(ArduinoUpdateError):
45
+ """The flashing tool exited with a non-zero status while writing firmware."""
46
+
47
+
48
+ class VerificationError(ArduinoUpdateError):
49
+ """Post-flash verification found a mismatch between board and firmware."""