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,61 @@
1
+ """Firmware artifact handling: content fingerprinting and persisted version state.
2
+
3
+ A SHA-256 of the ``.hex`` file's bytes stands in for a "version" - it
4
+ needs no manually-maintained version string, and it changes if and only
5
+ if the compiled firmware actually changed, which is exactly what
6
+ "do not flash if firmware version has not changed" needs.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import hashlib
12
+ import logging
13
+ from dataclasses import dataclass
14
+ from pathlib import Path
15
+
16
+ from software.arduino_updates.exceptions import FirmwareNotFoundError
17
+ from software.arduino_updates.state_store import FingerprintStateStore
18
+
19
+ logger = logging.getLogger(__name__)
20
+
21
+ _STATE_FILENAME = "arduino_firmware.version"
22
+ _HASH_CHUNK_SIZE = 65536
23
+
24
+
25
+ @dataclass(frozen=True)
26
+ class Firmware:
27
+ """A firmware image on disk, identified by its content fingerprint."""
28
+
29
+ path: Path
30
+ fingerprint: str
31
+
32
+ @classmethod
33
+ def load(cls, path: Path) -> "Firmware":
34
+ """Load ``path`` and compute its fingerprint. Raises if it's missing."""
35
+ if not path.is_file():
36
+ raise FirmwareNotFoundError(f"Firmware file not found: {path}")
37
+ return cls(path=path, fingerprint=_fingerprint(path))
38
+
39
+
40
+ def _fingerprint(path: Path) -> str:
41
+ digest = hashlib.sha256()
42
+ with path.open("rb") as handle:
43
+ for chunk in iter(lambda: handle.read(_HASH_CHUNK_SIZE), b""):
44
+ digest.update(chunk)
45
+ return digest.hexdigest()
46
+
47
+
48
+ class FirmwareStateStore(FingerprintStateStore):
49
+ """Persists the fingerprint of the last successfully flashed firmware.
50
+
51
+ Lives under the systemd unit's ``StateDirectory`` (``/var/lib/jetstan``
52
+ by default) so it survives restarts and self-upgrades without
53
+ needing any write permission the unit doesn't already grant -
54
+ ``ProtectSystem=strict`` makes everything else read-only.
55
+ """
56
+
57
+ def __init__(self, state_dir: Path) -> None:
58
+ super().__init__(state_dir, _STATE_FILENAME)
59
+
60
+ def needs_flash(self, firmware: Firmware) -> bool:
61
+ return self.read() != firmware.fingerprint
@@ -0,0 +1,183 @@
1
+ """Board flashing: an abstract interface plus an avrdude-based AVR implementation.
2
+
3
+ New board families (STM32/ESP32/RP2040) plug in by adding another
4
+ ``BoardFlasher`` subclass and registering it in ``FLASHERS`` under a new
5
+ ``family`` key - nothing in the OTA pipeline (``jetstan_agent``, or
6
+ ``software/arduino_updates/__init__.py``) needs to change.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import abc
12
+ import logging
13
+ import shutil
14
+ import subprocess
15
+ import time
16
+ from dataclasses import dataclass
17
+ from pathlib import Path
18
+
19
+ from software.arduino_updates.config import ArduinoConfig
20
+ from software.arduino_updates.exceptions import (
21
+ ArduinoPermissionError,
22
+ FlashError,
23
+ FlashTimeoutError,
24
+ UnsupportedBoardError,
25
+ )
26
+ from software.arduino_updates.firmware import Firmware
27
+
28
+ logger = logging.getLogger(__name__)
29
+
30
+
31
+ @dataclass(frozen=True)
32
+ class FlashResult:
33
+ """Outcome of a successful flash. Failures raise instead of returning one."""
34
+
35
+ success: bool
36
+ port: str
37
+ attempts: int
38
+ detail: str
39
+
40
+
41
+ class BoardFlasher(abc.ABC):
42
+ """Board-family-specific firmware flashing and verification."""
43
+
44
+ @abc.abstractmethod
45
+ def flash(self, port: str, firmware: Firmware, config: ArduinoConfig) -> FlashResult:
46
+ """Write ``firmware`` to the board on ``port``.
47
+
48
+ Raises :class:`~software.arduino_updates.exceptions.ArduinoUpdateError`
49
+ (or a subclass) on unrecoverable failure, after retrying
50
+ ``config.flash_retries`` times.
51
+ """
52
+
53
+ @abc.abstractmethod
54
+ def verify(self, port: str, firmware: Firmware, config: ArduinoConfig) -> bool:
55
+ """Return True if the board's flash contents match ``firmware``."""
56
+
57
+
58
+ class AVRDudeFlasher(BoardFlasher):
59
+ """Flashes AVR-based boards (Arduino Uno/Nano/Mega) via avrdude."""
60
+
61
+ def flash(self, port: str, firmware: Firmware, config: ArduinoConfig) -> FlashResult:
62
+ command = self._base_command(port, firmware, config, operation="w")
63
+
64
+ last_error = ""
65
+ for attempt in range(1, config.flash_retries + 1):
66
+ logger.info(
67
+ "Flash started (attempt %d/%d) on %s", attempt, config.flash_retries, port
68
+ )
69
+ try:
70
+ result = _run_avrdude(command, config.flash_timeout_seconds)
71
+ except subprocess.TimeoutExpired:
72
+ last_error = f"timed out after {config.flash_timeout_seconds}s"
73
+ logger.warning("Flash attempt %d timed out.", attempt)
74
+ if attempt == config.flash_retries:
75
+ raise FlashTimeoutError(
76
+ f"avrdude did not complete within {config.flash_timeout_seconds}s "
77
+ f"after {config.flash_retries} attempt(s)."
78
+ )
79
+ _wait_before_retry(config.flash_retry_delay_seconds)
80
+ continue
81
+
82
+ if result.returncode == 0:
83
+ logger.info("Flash completed")
84
+ return FlashResult(
85
+ success=True, port=port, attempts=attempt, detail=result.stderr.strip()
86
+ )
87
+
88
+ last_error = result.stderr.strip()
89
+ _raise_if_permission_denied(last_error)
90
+ logger.warning(
91
+ "Flash attempt %d/%d failed (exit %d): %s",
92
+ attempt,
93
+ config.flash_retries,
94
+ result.returncode,
95
+ last_error,
96
+ )
97
+ if attempt < config.flash_retries:
98
+ _wait_before_retry(config.flash_retry_delay_seconds)
99
+
100
+ raise FlashError(f"avrdude failed after {config.flash_retries} attempt(s): {last_error}")
101
+
102
+ def verify(self, port: str, firmware: Firmware, config: ArduinoConfig) -> bool:
103
+ command = self._base_command(port, firmware, config, operation="v")
104
+ try:
105
+ result = _run_avrdude(command, config.verify_timeout_seconds)
106
+ except subprocess.TimeoutExpired:
107
+ raise FlashTimeoutError(
108
+ f"Verification did not complete within {config.verify_timeout_seconds}s."
109
+ )
110
+
111
+ if result.returncode != 0:
112
+ _raise_if_permission_denied(result.stderr.strip())
113
+ return False
114
+ return True
115
+
116
+ @staticmethod
117
+ def _base_command(
118
+ port: str, firmware: Firmware, config: ArduinoConfig, *, operation: str
119
+ ) -> list[str]:
120
+ profile = config.board_profile
121
+ avrdude = _require_avrdude(config.avrdude_path)
122
+ return [
123
+ avrdude,
124
+ "-p",
125
+ profile.mcu,
126
+ "-c",
127
+ profile.programmer,
128
+ "-P",
129
+ port,
130
+ "-b",
131
+ str(config.baud),
132
+ "-D", # disable auto-erase; avrdude erases as part of the page write anyway
133
+ "-U",
134
+ f"flash:{operation}:{firmware.path}:i",
135
+ ]
136
+
137
+
138
+ def _wait_before_retry(delay_seconds: int) -> None:
139
+ """Pace retries: a failed/interrupted write can leave an AVR
140
+ bootloader needing a moment to recover, not just a resend."""
141
+ if delay_seconds > 0:
142
+ logger.debug("Waiting %ds before retrying...", delay_seconds)
143
+ time.sleep(delay_seconds)
144
+
145
+
146
+ def _run_avrdude(command: list[str], timeout_seconds: int) -> subprocess.CompletedProcess:
147
+ logger.debug("Running: %s", " ".join(command))
148
+ return subprocess.run(
149
+ command, capture_output=True, text=True, timeout=timeout_seconds, check=False
150
+ )
151
+
152
+
153
+ def _raise_if_permission_denied(stderr: str) -> None:
154
+ if "Permission denied" in stderr:
155
+ raise ArduinoPermissionError(f"avrdude reported permission denied: {stderr}")
156
+
157
+
158
+ def _require_avrdude(configured_path: str) -> str:
159
+ resolved = shutil.which(configured_path)
160
+ if resolved is None and Path(configured_path).is_file():
161
+ resolved = configured_path
162
+ if resolved is None:
163
+ raise FlashError(
164
+ f"avrdude executable not found (looked for '{configured_path}' on PATH). "
165
+ "Install it with: sudo apt install avrdude"
166
+ )
167
+ return resolved
168
+
169
+
170
+ FLASHERS: dict[str, BoardFlasher] = {
171
+ "avr": AVRDudeFlasher(),
172
+ }
173
+
174
+
175
+ def get_flasher(family: str) -> BoardFlasher:
176
+ """Look up the flasher registered for ``family`` (e.g. ``"avr"``)."""
177
+ try:
178
+ return FLASHERS[family]
179
+ except KeyError as exc:
180
+ raise UnsupportedBoardError(
181
+ f"No flasher registered for board family '{family}'; "
182
+ f"known families: {', '.join(sorted(FLASHERS))}"
183
+ ) from exc
@@ -0,0 +1,45 @@
1
+ # Sample firmware: `motor_test`
2
+
3
+ Sketch for the OTA -> Raspberry Pi -> Arduino flashing pipeline (see
4
+ `software/arduino_updates/`). It drives a motor driver's `RPWM`/`LPWM`
5
+ pins (5 and 6) at a duty cycle remotely adjustable from the dashboard
6
+ (20% at boot, until the first command arrives), and reports the
7
+ vehicle's real pack voltage and pack temperature over serial once a
8
+ second — see the wiring and protocol notes in `motor_test.ino`'s own
9
+ header comment. `software/sensors/serial_telemetry.py` reads that
10
+ serial output (and forwards speed commands back) on the Pi side;
11
+ `software/deployment/pipeline.py` starts it automatically once flashing
12
+ has settled.
13
+
14
+ Temperature reads are CRC-8 validated against the DS18B20's own
15
+ scratchpad checksum — a bad read (most commonly: no pull-up resistor on
16
+ the data line) is rejected and the last good value is kept, rather than
17
+ reporting a plausible-looking wrong number.
18
+
19
+ ## Normal workflow: you don't compile this by hand
20
+
21
+ By default (`ARDUINO_AUTO_COMPILE=true`, the default), the agent compiles
22
+ this sketch itself via `arduino-cli` on every restart (skipping the
23
+ compile if the source hasn't changed), then flashes and verifies it if the
24
+ output changed. As long as the one-time host setup in
25
+ [INSTALL.md](../../../../jetstan-agent/INSTALL.md) has been done once (`avrdude` +
26
+ `arduino-cli` installed), editing this `.ino`, bumping the package
27
+ version, and `python -m twine upload dist/*` is the entire workflow — no
28
+ SSH, no manual `arduino-cli`/`cp` commands. See `software/arduino_updates/compiler.py`.
29
+
30
+ ## Manual workflow (only if `ARDUINO_AUTO_COMPILE=false`)
31
+
32
+ If you've disabled on-device compiling — e.g. testing a different board's
33
+ build system — you're responsible for compiling and deploying the `.hex`
34
+ yourself:
35
+
36
+ ```bash
37
+ arduino-cli core install arduino:avr
38
+ arduino-cli compile --fqbn arduino:avr:uno motor_test --output-dir build
39
+ scp build/motor_test.ino.hex pi@<pi-host>:/tmp/firmware.hex
40
+ ssh pi@<pi-host> 'sudo mv /tmp/firmware.hex $ARDUINO_FIRMWARE_PATH'
41
+ ```
42
+
43
+ On the next `jetstan-agent` startup (or `sudo systemctl restart jetstan-agent`),
44
+ the agent will detect the new firmware's fingerprint has changed, flash it,
45
+ and verify it — see `software/arduino_updates/__init__.py:check_and_flash`.
@@ -0,0 +1,284 @@
1
+ /*
2
+ * motor_test.ino
3
+ *
4
+ * Firmware for the Jetstan vehicle's Arduino. Drives a motor driver's
5
+ * RPWM/LPWM inputs (5 and 6), remotely adjustable from the Pi dashboard,
6
+ * and reports the vehicle's real pack voltage and pack temperature over
7
+ * serial once a second - all over the same USB-serial link already used
8
+ * for OTA flashing.
9
+ *
10
+ * Wiring:
11
+ * Voltage sensor: signal -> A0, GND -> GND, VCC -> 5V.
12
+ * NOT D0: on an Uno/Nano, D0 is the hardware RX0 pin, wired straight
13
+ * to the USB-serial chip that carries this sketch's telemetry output
14
+ * (and avrdude's flashing traffic) to the Pi.
15
+ * Temp sensor (DS18B20, 1-Wire): data -> D2, GND -> GND, VCC -> 3.3V.
16
+ * Needs a 4.7k ohm pull-up resistor between DATA and VCC if your
17
+ * breakout board doesn't already carry one. Without it, bus reads
18
+ * are noisy/corrupted far more often than they're clean - see the
19
+ * CRC check in readPackTempC() below, which exists specifically to
20
+ * catch that instead of silently reporting a wrong temperature
21
+ * (e.g. a suspicious flat 0.00C is the classic symptom of a missing
22
+ * pull-up, not a code bug).
23
+ *
24
+ * Serial protocol, 115200 baud (matches ARDUINO_BAUD), newline-terminated
25
+ * lines in both directions:
26
+ * Arduino -> Pi (once a second): TLM:{"v":12.34,"t":25.62}
27
+ * Read by software/sensors/serial_telemetry.py.
28
+ * Pi -> Arduino (whenever the dashboard's speed slider changes):
29
+ * CMD:{"speed":42} (0-100, motor duty cycle percent)
30
+ * Written by software/sensors/serial_telemetry.py, on behalf of
31
+ * software/test/server.py's POST /motor/speed endpoint.
32
+ */
33
+
34
+ #include <stdlib.h>
35
+ #include <string.h>
36
+
37
+ const int RPWM_PIN = 5;
38
+ const int LPWM_PIN = 6;
39
+
40
+ // Duty cycle as a percent (0-100), scaled to analogWrite()'s 0-255 range.
41
+ // Boot default - the motor drives at this speed immediately on power-up,
42
+ // with no Pi/dashboard/command required, until a CMD: overrides it.
43
+ int currentSpeedPercent = 95;
44
+
45
+ const int VOLTAGE_SENSOR_PIN = A0;
46
+ // Default ratio for the common resistor-divider "voltage sensor module"
47
+ // (R1=30k, R2=7.5k -> a 0-25V input mapped down to 0-5V at the pin).
48
+ // Recalibrate against a multimeter for your exact board before trusting
49
+ // this number in anything safety-relevant.
50
+ const float VOLTAGE_DIVIDER_RATIO = 5.0;
51
+ const float ADC_REFERENCE_V = 5.0;
52
+ const float ADC_MAX_COUNTS = 1023.0;
53
+
54
+ const int TEMP_SENSOR_PIN = 2;
55
+
56
+ const unsigned long TELEMETRY_INTERVAL_MS = 1000;
57
+ unsigned long lastTelemetryMs = 0;
58
+
59
+ const uint8_t CMD_BUFFER_SIZE = 48;
60
+ char cmdBuffer[CMD_BUFFER_SIZE];
61
+ uint8_t cmdBufferLen = 0;
62
+ const char CMD_PREFIX[] = "CMD:";
63
+
64
+ void setup() {
65
+ pinMode(RPWM_PIN, OUTPUT);
66
+ pinMode(LPWM_PIN, OUTPUT);
67
+ setMotorSpeedPercent(currentSpeedPercent);
68
+
69
+ Serial.begin(115200);
70
+ }
71
+
72
+ void loop() {
73
+ pollSerialCommands();
74
+
75
+ unsigned long now = millis();
76
+ if (now - lastTelemetryMs < TELEMETRY_INTERVAL_MS) {
77
+ return;
78
+ }
79
+ lastTelemetryMs = now;
80
+
81
+ float voltage = readPackVoltage();
82
+ float temp = readPackTempC();
83
+
84
+ Serial.print("TLM:{\"v\":");
85
+ Serial.print(voltage, 2);
86
+ Serial.print(",\"t\":");
87
+ Serial.print(temp, 2);
88
+ Serial.println("}");
89
+ }
90
+
91
+ // ---- Motor speed control ----
92
+
93
+ void setMotorSpeedPercent(int percent) {
94
+ currentSpeedPercent = percent;
95
+ int pwmValue = (int)((percent / 100.0) * 255.0 + 0.5);
96
+ analogWrite(RPWM_PIN, pwmValue);
97
+ analogWrite(LPWM_PIN, 0);
98
+ }
99
+
100
+ // Non-blocking: only ever consumes bytes already sitting in the UART's
101
+ // receive buffer, one loop() iteration at a time - never waits on the
102
+ // link the way Serial.readStringUntil() would, so this can't stall
103
+ // telemetry (or, by extension, the DS18B20 conversion delay below).
104
+ void pollSerialCommands() {
105
+ while (Serial.available() > 0) {
106
+ char c = (char)Serial.read();
107
+ if (c == '\n') {
108
+ cmdBuffer[cmdBufferLen] = '\0';
109
+ handleCommandLine(cmdBuffer);
110
+ cmdBufferLen = 0;
111
+ } else if (c == '\r') {
112
+ // ignore - tolerate either line ending
113
+ } else if (cmdBufferLen < CMD_BUFFER_SIZE - 1) {
114
+ cmdBuffer[cmdBufferLen++] = c;
115
+ } else {
116
+ // Line longer than the buffer: drop it rather than acting on a
117
+ // truncated/garbled command. Reset and wait for the next '\n'.
118
+ cmdBufferLen = 0;
119
+ }
120
+ }
121
+ }
122
+
123
+ void handleCommandLine(const char *line) {
124
+ if (strncmp(line, CMD_PREFIX, strlen(CMD_PREFIX)) != 0) {
125
+ return; // not a command frame - ignore
126
+ }
127
+ int speed = extractSpeedPercent(line + strlen(CMD_PREFIX));
128
+ if (speed < 0 || speed > 100) {
129
+ return; // unparsable or out of range - ignore, keep current speed
130
+ }
131
+ setMotorSpeedPercent(speed);
132
+ }
133
+
134
+ int extractSpeedPercent(const char *payload) {
135
+ const char *key = "\"speed\":";
136
+ const char *pos = strstr(payload, key);
137
+ if (pos == nullptr) {
138
+ return -1;
139
+ }
140
+ return atoi(pos + strlen(key));
141
+ }
142
+
143
+ // ---- Voltage sensing ----
144
+
145
+ float readPackVoltage() {
146
+ int raw = analogRead(VOLTAGE_SENSOR_PIN);
147
+ float pinVoltage = (raw / ADC_MAX_COUNTS) * ADC_REFERENCE_V;
148
+ return pinVoltage * VOLTAGE_DIVIDER_RATIO;
149
+ }
150
+
151
+ // ---- DS18B20 (1-Wire), hand-rolled ----
152
+ // No external OneWire/DallasTemperature library: this keeps the sketch
153
+ // compiling with just the arduino:avr core the one-time host setup
154
+ // already installs (see compiler.py) - no extra `arduino-cli lib
155
+ // install` step to remember or to fail silently if forgotten.
156
+
157
+ bool oneWireReset() {
158
+ pinMode(TEMP_SENSOR_PIN, OUTPUT);
159
+ digitalWrite(TEMP_SENSOR_PIN, LOW);
160
+ delayMicroseconds(480);
161
+ pinMode(TEMP_SENSOR_PIN, INPUT);
162
+ delayMicroseconds(70);
163
+ bool presence = (digitalRead(TEMP_SENSOR_PIN) == LOW);
164
+ delayMicroseconds(410);
165
+ return presence;
166
+ }
167
+
168
+ void oneWireWriteBit(bool bit) {
169
+ pinMode(TEMP_SENSOR_PIN, OUTPUT);
170
+ digitalWrite(TEMP_SENSOR_PIN, LOW);
171
+ delayMicroseconds(bit ? 6 : 60);
172
+ digitalWrite(TEMP_SENSOR_PIN, HIGH);
173
+ delayMicroseconds(bit ? 64 : 10);
174
+ }
175
+
176
+ bool oneWireReadBit() {
177
+ pinMode(TEMP_SENSOR_PIN, OUTPUT);
178
+ digitalWrite(TEMP_SENSOR_PIN, LOW);
179
+ delayMicroseconds(6);
180
+ pinMode(TEMP_SENSOR_PIN, INPUT);
181
+ delayMicroseconds(9);
182
+ bool bit = digitalRead(TEMP_SENSOR_PIN);
183
+ delayMicroseconds(55);
184
+ return bit;
185
+ }
186
+
187
+ void oneWireWriteByte(uint8_t value) {
188
+ for (uint8_t i = 0; i < 8; i++) {
189
+ oneWireWriteBit((value >> i) & 0x01);
190
+ }
191
+ }
192
+
193
+ uint8_t oneWireReadByte() {
194
+ uint8_t value = 0;
195
+ for (uint8_t i = 0; i < 8; i++) {
196
+ if (oneWireReadBit()) {
197
+ value |= (1 << i);
198
+ }
199
+ }
200
+ return value;
201
+ }
202
+
203
+ // Standard Dallas/Maxim CRC-8 (polynomial x^8+x^5+x^4+1, reflected -
204
+ // 0x8C), computed over the scratchpad's first 8 bytes and checked
205
+ // against its 9th. A missing pull-up or a noisy bus corrupts individual
206
+ // bits far more often than it corrupts all of them identically, so this
207
+ // catches exactly that case - instead of silently reporting whatever
208
+ // garbage came back (e.g. a suspicious flat 0.00C from an all-zero read).
209
+ uint8_t oneWireCRC8(const uint8_t *data, uint8_t len) {
210
+ uint8_t crc = 0;
211
+ for (uint8_t i = 0; i < len; i++) {
212
+ uint8_t inbyte = data[i];
213
+ for (uint8_t j = 0; j < 8; j++) {
214
+ uint8_t mix = (crc ^ inbyte) & 0x01;
215
+ crc >>= 1;
216
+ if (mix) {
217
+ crc ^= 0x8C;
218
+ }
219
+ inbyte >>= 1;
220
+ }
221
+ }
222
+ return crc;
223
+ }
224
+
225
+ const uint8_t DS18B20_SKIP_ROM = 0xCC;
226
+ const uint8_t DS18B20_CONVERT_T = 0x44;
227
+ const uint8_t DS18B20_READ_SCRATCHPAD = 0xBE;
228
+ const uint8_t SCRATCHPAD_BYTES = 9; // temp LSB/MSB, TH, TL, config, 3 reserved, CRC
229
+
230
+ // Cached so a transient bus glitch (no presence pulse, or a failed CRC)
231
+ // on any one tick reports the last good reading instead of a wild or
232
+ // silently-wrong value flowing all the way to the dashboard.
233
+ float lastGoodTempC = 25.0;
234
+
235
+ float readPackTempC() {
236
+ if (!oneWireReset()) {
237
+ return lastGoodTempC; // no sensor answering on the bus right now
238
+ }
239
+ oneWireWriteByte(DS18B20_SKIP_ROM);
240
+ oneWireWriteByte(DS18B20_CONVERT_T);
241
+
242
+ // 12-bit conversion takes up to 750ms. Busy-waiting here is fine: it
243
+ // happens once per TELEMETRY_INTERVAL_MS tick, and pollSerialCommands()
244
+ // picks back up as soon as this returns - a motor command sent during
245
+ // this window just sits in the UART's own receive buffer briefly.
246
+ delay(750);
247
+
248
+ if (!oneWireReset()) {
249
+ return lastGoodTempC;
250
+ }
251
+ oneWireWriteByte(DS18B20_SKIP_ROM);
252
+ oneWireWriteByte(DS18B20_READ_SCRATCHPAD);
253
+
254
+ uint8_t scratchpad[SCRATCHPAD_BYTES];
255
+ for (uint8_t i = 0; i < SCRATCHPAD_BYTES; i++) {
256
+ scratchpad[i] = oneWireReadByte();
257
+ }
258
+
259
+ // A bus with no pull-up (or a sensor that isn't really there) tends to
260
+ // read every bit as the same stuck value - all-0x00 or all-0xFF - not
261
+ // scattered noise. The CRC-8 below is blind to exactly that: this
262
+ // particular polynomial's checksum of an all-zero buffer is itself
263
+ // 0x00, which then matches an all-zero 9th byte and looks "valid".
264
+ // Reject the degenerate pattern outright before trusting the CRC.
265
+ bool allSameByte = true;
266
+ for (uint8_t i = 1; i < SCRATCHPAD_BYTES; i++) {
267
+ if (scratchpad[i] != scratchpad[0]) {
268
+ allSameByte = false;
269
+ break;
270
+ }
271
+ }
272
+ if (allSameByte && (scratchpad[0] == 0x00 || scratchpad[0] == 0xFF)) {
273
+ return lastGoodTempC; // stuck bus, not a real reading
274
+ }
275
+
276
+ uint8_t computedCrc = oneWireCRC8(scratchpad, SCRATCHPAD_BYTES - 1);
277
+ if (computedCrc != scratchpad[SCRATCHPAD_BYTES - 1]) {
278
+ return lastGoodTempC; // corrupted read (classic symptom: missing pull-up)
279
+ }
280
+
281
+ int16_t rawTemp = (scratchpad[1] << 8) | scratchpad[0];
282
+ lastGoodTempC = rawTemp / 16.0;
283
+ return lastGoodTempC;
284
+ }
@@ -0,0 +1,47 @@
1
+ """Generic atomic-write helpers, shared across this package.
2
+
3
+ ``atomic_write`` is used directly by ``compiler.py`` (writing the
4
+ compiled ``.hex``) and indirectly via :class:`FingerprintStateStore` by
5
+ ``firmware.py`` (tracks the last-*flashed* ``.hex``) and ``compiler.py``
6
+ (tracks the last-*compiled* source) - one write discipline, one place it
7
+ can have a bug, instead of three near-identical inline copies.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ from pathlib import Path
13
+
14
+
15
+ def atomic_write(path: Path, content: str | bytes) -> None:
16
+ """Write ``content`` to ``path`` atomically (write to a temp file, then rename).
17
+
18
+ A crash or power loss mid-write can never leave a corrupt,
19
+ half-written file behind - the rename is the only visible change.
20
+ Matches ``jetstan_agent/installer.py``'s ``_atomic_write`` pattern
21
+ (that one stays separate deliberately: ``jetstan_agent`` never
22
+ imports from ``software/`` - see ``message_router.py``).
23
+ """
24
+ path.parent.mkdir(parents=True, exist_ok=True)
25
+ tmp_path = path.with_name(path.name + ".tmp")
26
+ if isinstance(content, bytes):
27
+ tmp_path.write_bytes(content)
28
+ else:
29
+ tmp_path.write_text(content)
30
+ tmp_path.replace(path)
31
+
32
+
33
+ class FingerprintStateStore:
34
+ """Persists a single fingerprint string to ``state_dir/filename``."""
35
+
36
+ def __init__(self, state_dir: Path, filename: str) -> None:
37
+ self._path = state_dir / filename
38
+
39
+ def read(self) -> str | None:
40
+ try:
41
+ content = self._path.read_text().strip()
42
+ except FileNotFoundError:
43
+ return None
44
+ return content or None
45
+
46
+ def write(self, fingerprint: str) -> None:
47
+ atomic_write(self._path, fingerprint)
@@ -0,0 +1,32 @@
1
+ """Post-flash verification: confirms the board's contents match what was written.
2
+
3
+ Kept separate from ``flasher.py`` so the "did the flash actually take"
4
+ reporting/logging/error-raising logic lives in one place regardless of
5
+ which board family performed the flash - the board-specific mechanics
6
+ of *how* to verify stay behind the ``BoardFlasher.verify`` interface.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import logging
12
+
13
+ from software.arduino_updates.config import ArduinoConfig
14
+ from software.arduino_updates.exceptions import VerificationError
15
+ from software.arduino_updates.firmware import Firmware
16
+ from software.arduino_updates.flasher import BoardFlasher
17
+
18
+ logger = logging.getLogger(__name__)
19
+
20
+
21
+ def verify_flash(port: str, firmware: Firmware, config: ArduinoConfig, flasher: BoardFlasher) -> None:
22
+ """Verify the board's flash contents match ``firmware``.
23
+
24
+ Raises :class:`VerificationError` if they don't match; returns
25
+ normally (after logging) on success.
26
+ """
27
+ if flasher.verify(port, firmware, config):
28
+ logger.info("Verification successful")
29
+ return
30
+
31
+ logger.error("Verification failed: board contents do not match %s", firmware.path)
32
+ raise VerificationError(f"Post-flash verification failed for {firmware.path} on {port}.")
@@ -0,0 +1,35 @@
1
+ """Generic post-update deployment pipeline: what ``jetstan_agent`` runs after
2
+ every OTA-triggered restart, before it starts the MQTT loop.
3
+
4
+ This package (``dag.py``) has no idea what a "board" or "Arduino" is -
5
+ that knowledge lives entirely in ``pipeline.py``, which registers the
6
+ concrete tasks. Adding new hardware later (a custom PCB, say) means
7
+ adding tasks to ``pipeline.py``; this entrypoint and ``dag.py`` never
8
+ change.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import logging
14
+
15
+ from software.deployment.dag import DagResult, run_dag
16
+ from software.deployment.pipeline import build_pipeline
17
+
18
+ logger = logging.getLogger(__name__)
19
+
20
+ __all__ = ["run_deployment_dag"]
21
+
22
+
23
+ def run_deployment_dag() -> DagResult:
24
+ """Run this project's deployment DAG. Never raises.
25
+
26
+ Mirrors the exact contract
27
+ :func:`software.arduino_updates.sync_firmware_safe` already
28
+ established: a bug in a task, or in the DAG engine itself, must
29
+ never prevent the OTA agent from starting and connecting to MQTT.
30
+ """
31
+ try:
32
+ return run_dag(build_pipeline())
33
+ except Exception: # noqa: BLE001 - intentional: see docstring
34
+ logger.exception("Deployment DAG failed unexpectedly.")
35
+ return DagResult(outcomes=[])