jetstan-ev-software 0.0.1__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.
- jetstan_ev_software-0.0.1/PKG-INFO +14 -0
- jetstan_ev_software-0.0.1/jetstan_ev_software.egg-info/PKG-INFO +14 -0
- jetstan_ev_software-0.0.1/jetstan_ev_software.egg-info/SOURCES.txt +73 -0
- jetstan_ev_software-0.0.1/jetstan_ev_software.egg-info/dependency_links.txt +1 -0
- jetstan_ev_software-0.0.1/jetstan_ev_software.egg-info/requires.txt +10 -0
- jetstan_ev_software-0.0.1/jetstan_ev_software.egg-info/top_level.txt +1 -0
- jetstan_ev_software-0.0.1/pyproject.toml +38 -0
- jetstan_ev_software-0.0.1/setup.cfg +4 -0
- jetstan_ev_software-0.0.1/software/__init__.py +6 -0
- jetstan_ev_software-0.0.1/software/arduino_updates/__init__.py +104 -0
- jetstan_ev_software-0.0.1/software/arduino_updates/compiler.py +176 -0
- jetstan_ev_software-0.0.1/software/arduino_updates/config.py +190 -0
- jetstan_ev_software-0.0.1/software/arduino_updates/discovery.py +71 -0
- jetstan_ev_software-0.0.1/software/arduino_updates/exceptions.py +49 -0
- jetstan_ev_software-0.0.1/software/arduino_updates/firmware.py +61 -0
- jetstan_ev_software-0.0.1/software/arduino_updates/flasher.py +183 -0
- jetstan_ev_software-0.0.1/software/arduino_updates/sample_firmware/README.md +45 -0
- jetstan_ev_software-0.0.1/software/arduino_updates/sample_firmware/motor_test/motor_test.ino +284 -0
- jetstan_ev_software-0.0.1/software/arduino_updates/state_store.py +47 -0
- jetstan_ev_software-0.0.1/software/arduino_updates/verifier.py +32 -0
- jetstan_ev_software-0.0.1/software/deployment/__init__.py +35 -0
- jetstan_ev_software-0.0.1/software/deployment/dag.py +134 -0
- jetstan_ev_software-0.0.1/software/deployment/dependencies.py +77 -0
- jetstan_ev_software-0.0.1/software/deployment/pipeline.py +80 -0
- jetstan_ev_software-0.0.1/software/frontend/__init__.py +1 -0
- jetstan_ev_software-0.0.1/software/frontend/index.html +498 -0
- jetstan_ev_software-0.0.1/software/gen_sample/__init__.py +3 -0
- jetstan_ev_software-0.0.1/software/gen_sample/simulator.py +92 -0
- jetstan_ev_software-0.0.1/software/handlers.py +28 -0
- jetstan_ev_software-0.0.1/software/logic/__init__.py +7 -0
- jetstan_ev_software-0.0.1/software/logic/calculations.py +157 -0
- jetstan_ev_software-0.0.1/software/sensors/__init__.py +20 -0
- jetstan_ev_software-0.0.1/software/sensors/motor_control.py +73 -0
- jetstan_ev_software-0.0.1/software/sensors/serial_telemetry.py +135 -0
- jetstan_ev_software-0.0.1/software/sensors/telemetry_store.py +67 -0
- jetstan_ev_software-0.0.1/software/soc/__init__.py +21 -0
- jetstan_ev_software-0.0.1/software/soc/api.py +100 -0
- jetstan_ev_software-0.0.1/software/soc/config.py +164 -0
- jetstan_ev_software-0.0.1/software/soc/exceptions.py +24 -0
- jetstan_ev_software-0.0.1/software/soc/features.py +114 -0
- jetstan_ev_software-0.0.1/software/soc/model.py +175 -0
- jetstan_ev_software-0.0.1/software/soc/predictor.py +117 -0
- jetstan_ev_software-0.0.1/software/soc/schemas.py +59 -0
- jetstan_ev_software-0.0.1/software/soc/service.py +94 -0
- jetstan_ev_software-0.0.1/software/soc/soc_dashboard.html +313 -0
- jetstan_ev_software-0.0.1/software/soc/telemetry.py +68 -0
- jetstan_ev_software-0.0.1/software/soc/xgboost_soc.onnx +0 -0
- jetstan_ev_software-0.0.1/software/test/README.md +74 -0
- jetstan_ev_software-0.0.1/software/test/__init__.py +7 -0
- jetstan_ev_software-0.0.1/software/test/jetstan-dashboard.service +83 -0
- jetstan_ev_software-0.0.1/software/test/server.py +187 -0
- jetstan_ev_software-0.0.1/tests/test_arduino_compiler.py +253 -0
- jetstan_ev_software-0.0.1/tests/test_arduino_config.py +191 -0
- jetstan_ev_software-0.0.1/tests/test_arduino_discovery.py +77 -0
- jetstan_ev_software-0.0.1/tests/test_arduino_exceptions.py +30 -0
- jetstan_ev_software-0.0.1/tests/test_arduino_firmware.py +86 -0
- jetstan_ev_software-0.0.1/tests/test_arduino_flasher.py +198 -0
- jetstan_ev_software-0.0.1/tests/test_arduino_sync.py +149 -0
- jetstan_ev_software-0.0.1/tests/test_arduino_verifier.py +65 -0
- jetstan_ev_software-0.0.1/tests/test_deployment_dag.py +124 -0
- jetstan_ev_software-0.0.1/tests/test_deployment_dependencies.py +78 -0
- jetstan_ev_software-0.0.1/tests/test_deployment_pipeline.py +138 -0
- jetstan_ev_software-0.0.1/tests/test_deployment_run.py +30 -0
- jetstan_ev_software-0.0.1/tests/test_gen_sample.py +44 -0
- jetstan_ev_software-0.0.1/tests/test_logic.py +154 -0
- jetstan_ev_software-0.0.1/tests/test_motor_control.py +54 -0
- jetstan_ev_software-0.0.1/tests/test_serial_telemetry.py +151 -0
- jetstan_ev_software-0.0.1/tests/test_soc_api.py +133 -0
- jetstan_ev_software-0.0.1/tests/test_soc_config.py +117 -0
- jetstan_ev_software-0.0.1/tests/test_soc_features.py +97 -0
- jetstan_ev_software-0.0.1/tests/test_soc_model.py +188 -0
- jetstan_ev_software-0.0.1/tests/test_soc_predictor.py +145 -0
- jetstan_ev_software-0.0.1/tests/test_soc_service.py +89 -0
- jetstan_ev_software-0.0.1/tests/test_soc_telemetry.py +90 -0
- jetstan_ev_software-0.0.1/tests/test_telemetry_store.py +50 -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,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,73 @@
|
|
|
1
|
+
pyproject.toml
|
|
2
|
+
jetstan_ev_software.egg-info/PKG-INFO
|
|
3
|
+
jetstan_ev_software.egg-info/SOURCES.txt
|
|
4
|
+
jetstan_ev_software.egg-info/dependency_links.txt
|
|
5
|
+
jetstan_ev_software.egg-info/requires.txt
|
|
6
|
+
jetstan_ev_software.egg-info/top_level.txt
|
|
7
|
+
software/__init__.py
|
|
8
|
+
software/handlers.py
|
|
9
|
+
software/arduino_updates/__init__.py
|
|
10
|
+
software/arduino_updates/compiler.py
|
|
11
|
+
software/arduino_updates/config.py
|
|
12
|
+
software/arduino_updates/discovery.py
|
|
13
|
+
software/arduino_updates/exceptions.py
|
|
14
|
+
software/arduino_updates/firmware.py
|
|
15
|
+
software/arduino_updates/flasher.py
|
|
16
|
+
software/arduino_updates/state_store.py
|
|
17
|
+
software/arduino_updates/verifier.py
|
|
18
|
+
software/arduino_updates/sample_firmware/README.md
|
|
19
|
+
software/arduino_updates/sample_firmware/motor_test/motor_test.ino
|
|
20
|
+
software/deployment/__init__.py
|
|
21
|
+
software/deployment/dag.py
|
|
22
|
+
software/deployment/dependencies.py
|
|
23
|
+
software/deployment/pipeline.py
|
|
24
|
+
software/frontend/__init__.py
|
|
25
|
+
software/frontend/index.html
|
|
26
|
+
software/gen_sample/__init__.py
|
|
27
|
+
software/gen_sample/simulator.py
|
|
28
|
+
software/logic/__init__.py
|
|
29
|
+
software/logic/calculations.py
|
|
30
|
+
software/sensors/__init__.py
|
|
31
|
+
software/sensors/motor_control.py
|
|
32
|
+
software/sensors/serial_telemetry.py
|
|
33
|
+
software/sensors/telemetry_store.py
|
|
34
|
+
software/soc/__init__.py
|
|
35
|
+
software/soc/api.py
|
|
36
|
+
software/soc/config.py
|
|
37
|
+
software/soc/exceptions.py
|
|
38
|
+
software/soc/features.py
|
|
39
|
+
software/soc/model.py
|
|
40
|
+
software/soc/predictor.py
|
|
41
|
+
software/soc/schemas.py
|
|
42
|
+
software/soc/service.py
|
|
43
|
+
software/soc/soc_dashboard.html
|
|
44
|
+
software/soc/telemetry.py
|
|
45
|
+
software/soc/xgboost_soc.onnx
|
|
46
|
+
software/test/README.md
|
|
47
|
+
software/test/__init__.py
|
|
48
|
+
software/test/jetstan-dashboard.service
|
|
49
|
+
software/test/server.py
|
|
50
|
+
tests/test_arduino_compiler.py
|
|
51
|
+
tests/test_arduino_config.py
|
|
52
|
+
tests/test_arduino_discovery.py
|
|
53
|
+
tests/test_arduino_exceptions.py
|
|
54
|
+
tests/test_arduino_firmware.py
|
|
55
|
+
tests/test_arduino_flasher.py
|
|
56
|
+
tests/test_arduino_sync.py
|
|
57
|
+
tests/test_arduino_verifier.py
|
|
58
|
+
tests/test_deployment_dag.py
|
|
59
|
+
tests/test_deployment_dependencies.py
|
|
60
|
+
tests/test_deployment_pipeline.py
|
|
61
|
+
tests/test_deployment_run.py
|
|
62
|
+
tests/test_gen_sample.py
|
|
63
|
+
tests/test_logic.py
|
|
64
|
+
tests/test_motor_control.py
|
|
65
|
+
tests/test_serial_telemetry.py
|
|
66
|
+
tests/test_soc_api.py
|
|
67
|
+
tests/test_soc_config.py
|
|
68
|
+
tests/test_soc_features.py
|
|
69
|
+
tests/test_soc_model.py
|
|
70
|
+
tests/test_soc_predictor.py
|
|
71
|
+
tests/test_soc_service.py
|
|
72
|
+
tests/test_soc_telemetry.py
|
|
73
|
+
tests/test_telemetry_store.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
software
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=68.0"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "jetstan_ev_software"
|
|
7
|
+
version = "0.0.1"
|
|
8
|
+
description = "Jetstan vehicle software - the OTA-deployable application payload that runs on the vehicle's Raspberry Pi (import package: software)."
|
|
9
|
+
requires-python = ">=3.11"
|
|
10
|
+
dependencies = [
|
|
11
|
+
"python-dotenv==1.2.2",
|
|
12
|
+
"fastapi==0.140.7",
|
|
13
|
+
"uvicorn==0.51.0",
|
|
14
|
+
"numpy==2.5.1",
|
|
15
|
+
"onnxruntime==1.28.0",
|
|
16
|
+
]
|
|
17
|
+
|
|
18
|
+
[project.optional-dependencies]
|
|
19
|
+
dev = [
|
|
20
|
+
"pytest>=8.0.0",
|
|
21
|
+
"pytest-mock>=3.14.0",
|
|
22
|
+
"httpx>=0.28.0",
|
|
23
|
+
]
|
|
24
|
+
|
|
25
|
+
[tool.setuptools.packages.find]
|
|
26
|
+
include = ["software*"]
|
|
27
|
+
|
|
28
|
+
[tool.setuptools.package-data]
|
|
29
|
+
"software.frontend" = ["*.html"]
|
|
30
|
+
"software.arduino_updates" = [
|
|
31
|
+
"sample_firmware/README.md",
|
|
32
|
+
"sample_firmware/motor_test/*.ino",
|
|
33
|
+
]
|
|
34
|
+
"software.soc" = ["*.onnx", "*.html"]
|
|
35
|
+
"software.test" = ["*.service", "README.md"]
|
|
36
|
+
|
|
37
|
+
[tool.pytest.ini_options]
|
|
38
|
+
testpaths = ["tests"]
|
|
@@ -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"}
|