diff --git a/.github/workflows/checks.yml b/.github/workflows/checks.yml index 4213b80..eeac67a 100644 --- a/.github/workflows/checks.yml +++ b/.github/workflows/checks.yml @@ -7,7 +7,7 @@ on: jobs: python: - name: Python syntax and parser smoke + name: Python syntax, parser, uploader, and package smoke runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 @@ -16,16 +16,64 @@ jobs: python-version: '3.12' - name: Compile GUI module run: python -m py_compile gui/portable_avr_control_studio.py - - name: Parser smoke tests + - name: Parser and uploader smoke tests run: | python - <<'PY' - from gui.portable_avr_control_studio import parse_serial_line + from pathlib import Path + from tempfile import TemporaryDirectory + from gui.portable_avr_control_studio import ( + UploadValidationError, + parse_serial_line, + validate_upload_request, + ) + assert parse_serial_line('OK,PING\n').kind == 'OK' assert parse_serial_line('ERR,BAD,message\n').kind == 'ERR' assert parse_serial_line('CONFIG,DEVICE_NAME=Unit,SENSOR_VREF_MV=5000\n').fields['SENSOR_VREF_MV'] == '5000' assert parse_serial_line('STATUS,SENSOR_RAW=512,SENSOR_MV=2502\n').fields['SENSOR_MV'] == '2502' assert parse_serial_line('DATA,INFO,protocol=2\n').fields['PROTOCOL'] == '2' assert parse_serial_line('garbage\n').malformed + + with TemporaryDirectory() as temp: + root = Path(temp) + firmware = root / 'PortableAVRControlStudio.ino.hex' + firmware.write_text(':00000001FF\n', encoding='utf-8') + tools = root / 'tools' / 'avrdude' + tools.mkdir(parents=True) + (tools / 'avrdude.exe').write_text('dummy uploader', encoding='utf-8') + (tools / 'avrdude.conf').write_text('dummy config', encoding='utf-8') + (root / 'firmware.ino').write_text('raw source is unsupported in app', encoding='utf-8') + + cmd, tool, returned_firmware = validate_upload_request('COM7', str(firmware), root, path_env='') + assert tool.source == 'bundled' + assert returned_firmware == firmware + assert cmd == [ + str(tools / 'avrdude.exe'), + '-C', str(tools / 'avrdude.conf'), + '-v', '-patmega328p', '-carduino', + '-P', 'COM7', '-b115200', '-D', + f'-Uflash:w:{firmware}:i', + ] + + for port, hex_path, expected in ( + ('', str(firmware), 'COM port'), + ('COM7', str(root / 'missing.hex'), 'existing prepared .hex'), + ('COM7', str(root / 'firmware.ino'), 'must end with .hex'), + ): + try: + validate_upload_request(port, hex_path, root, path_env='') + except UploadValidationError as exc: + assert expected in str(exc) + else: + raise AssertionError(f'expected validation failure for {expected}') + + (tools / 'avrdude.exe').unlink() + try: + validate_upload_request('COM7', str(firmware), root, path_env='') + except UploadValidationError as exc: + assert 'avrdude was not found' in str(exc) + else: + raise AssertionError('expected missing avrdude validation failure') PY - name: Compile release assembly script @@ -38,6 +86,7 @@ jobs: cleanup() { rm -rf \ release/artifacts/windows/PortableAVRControlStudio.exe \ + release/artifacts/windows/tools/avrdude \ release/artifacts/firmware/PortableAVRControlStudio.ino.hex \ release/customer_package/PortableAVRControlStudio-customer-handoff \ release/customer_package/PortableAVRControlStudio-customer-handoff.zip @@ -46,6 +95,10 @@ jobs: printf 'dummy exe for CI release assembly smoke test\n' > release/artifacts/windows/PortableAVRControlStudio.exe printf ':00000001FF\n' > release/artifacts/firmware/PortableAVRControlStudio.ino.hex + mkdir -p release/artifacts/windows/tools/avrdude + printf 'dummy avrdude exe for CI package assembly smoke test\n' > release/artifacts/windows/tools/avrdude/avrdude.exe + printf 'dummy avrdude config for CI package assembly smoke test\n' > release/artifacts/windows/tools/avrdude/avrdude.conf + printf 'dummy support dll for CI package assembly smoke test\n' > release/artifacts/windows/tools/avrdude/libusb0.dll python release/scripts/assemble_customer_package.py @@ -59,9 +112,13 @@ jobs: test -f release/customer_package/PortableAVRControlStudio-customer-handoff/docs/product_spec.md test -f release/customer_package/PortableAVRControlStudio-customer-handoff/docs/testing.md test -f release/customer_package/PortableAVRControlStudio-customer-handoff/docs/profiles/arduino_uno_avr.json + test -f release/customer_package/PortableAVRControlStudio-customer-handoff/tools/avrdude/avrdude.exe + test -f release/customer_package/PortableAVRControlStudio-customer-handoff/tools/avrdude/avrdude.conf + test -f release/customer_package/PortableAVRControlStudio-customer-handoff/tools/avrdude/libusb0.dll git check-ignore \ release/artifacts/windows/PortableAVRControlStudio.exe \ + release/artifacts/windows/tools/avrdude/avrdude.exe \ release/artifacts/firmware/PortableAVRControlStudio.ino.hex \ release/customer_package/PortableAVRControlStudio-customer-handoff \ release/customer_package/PortableAVRControlStudio-customer-handoff.zip diff --git a/.github/workflows/release-build.yml b/.github/workflows/release-build.yml index 941d1f2..d7dc2f6 100644 --- a/.github/workflows/release-build.yml +++ b/.github/workflows/release-build.yml @@ -19,6 +19,15 @@ jobs: - name: Install Windows packaging dependencies run: py -m pip install --upgrade pyinstaller pyserial + - name: Install Arduino CLI + uses: arduino/setup-arduino-cli@v2 + + - name: Install Arduino AVR core for bundled uploader + shell: pwsh + run: | + arduino-cli core update-index + arduino-cli core install arduino:avr + - name: Build Windows EXE run: powershell -ExecutionPolicy Bypass -File .\release\scripts\build_windows_exe.ps1 @@ -31,11 +40,54 @@ jobs: } Get-Item $exe | Select-Object FullName,Length,LastWriteTime + - name: Stage Windows avrdude uploader files + shell: pwsh + run: | + $ErrorActionPreference = 'Stop' + $stage = 'release\artifacts\windows\tools\avrdude' + New-Item -ItemType Directory -Force -Path $stage | Out-Null + + $candidates = @( + Join-Path $env:LOCALAPPDATA 'Arduino15\packages\arduino\tools\avrdude' + ) + $toolRoot = $candidates | Where-Object { Test-Path $_ -PathType Container } | Select-Object -First 1 + if (-not $toolRoot) { + throw 'Could not locate Arduino AVR avrdude tool root after installing arduino:avr.' + } + + $versionRoot = Get-ChildItem $toolRoot -Directory | Sort-Object LastWriteTime -Descending | Select-Object -First 1 + if (-not $versionRoot) { + throw "Could not locate an avrdude version directory under $toolRoot." + } + + $bin = Join-Path $versionRoot.FullName 'bin' + $conf = Join-Path $versionRoot.FullName 'etc\avrdude.conf' + $exe = Join-Path $bin 'avrdude.exe' + if (-not (Test-Path $exe -PathType Leaf)) { + throw "Could not locate avrdude.exe at $exe." + } + if (-not (Test-Path $conf -PathType Leaf)) { + throw "Could not locate avrdude.conf at $conf." + } + + Copy-Item -Path (Join-Path $bin '*') -Destination $stage -Recurse -Force + Copy-Item -Path $conf -Destination (Join-Path $stage 'avrdude.conf') -Force + + if (-not (Test-Path (Join-Path $stage 'avrdude.exe') -PathType Leaf)) { + throw 'Staged uploader is missing avrdude.exe.' + } + if (-not (Test-Path (Join-Path $stage 'avrdude.conf') -PathType Leaf)) { + throw 'Staged uploader is missing avrdude.conf.' + } + Get-ChildItem $stage | Select-Object FullName,Length,LastWriteTime + - name: Upload Windows EXE artifact uses: actions/upload-artifact@v4 with: name: portable-avr-control-studio-windows-exe - path: release/artifacts/windows/PortableAVRControlStudio.exe + path: | + release/artifacts/windows/PortableAVRControlStudio.exe + release/artifacts/windows/tools/avrdude/** if-no-files-found: error uno-firmware-hex: @@ -100,6 +152,8 @@ jobs: run: | set -euo pipefail test -f release/artifacts/windows/PortableAVRControlStudio.exe + test -f release/artifacts/windows/tools/avrdude/avrdude.exe + test -f release/artifacts/windows/tools/avrdude/avrdude.conf test -f release/artifacts/firmware/PortableAVRControlStudio.ino.hex - name: Assemble customer ZIP @@ -115,11 +169,13 @@ jobs: run: | set -euo pipefail mkdir -p release/artifacts/checksums - sha256sum \ - release/artifacts/windows/PortableAVRControlStudio.exe \ - release/artifacts/firmware/PortableAVRControlStudio.ino.hex \ - release/customer_package/PortableAVRControlStudio-customer-handoff.zip \ - > release/artifacts/checksums/SHA256SUMS.txt + { + sha256sum \ + release/artifacts/windows/PortableAVRControlStudio.exe \ + release/artifacts/firmware/PortableAVRControlStudio.ino.hex \ + release/customer_package/PortableAVRControlStudio-customer-handoff.zip + find release/artifacts/windows/tools/avrdude -type f -print0 | sort -z | xargs -0 sha256sum + } > release/artifacts/checksums/SHA256SUMS.txt cat release/artifacts/checksums/SHA256SUMS.txt - name: Upload customer ZIP artifact diff --git a/README.md b/README.md index 678d217..42978af 100644 --- a/README.md +++ b/README.md @@ -57,7 +57,7 @@ Hardware profiles in `docs/profiles/` document expected wiring, output polarity, ## Firmware upload status -The Firmware tab supports selecting prepared `.hex` firmware artifacts as a placeholder handoff workflow. It must not be presented as a fully validated production uploader until the uploader, target MCU flags, COM-port behavior, hardware profile, and firmware artifact have been packaged and tested together. +The Firmware tab uploads prepared `.hex` firmware artifacts to Arduino Uno / ATmega328P boards using bundled `tools/avrdude/` files beside the app, or `avrdude` on `PATH` as a fallback. It does not compile raw `.ino` source code inside the app. Upload success only means the `avrdude` firmware transfer command completed; it does not validate physical wiring, relay loads, sensors, power, enclosure safety, or customer hardware installation. ## Firmware compile checks @@ -131,7 +131,7 @@ arduino-cli core install arduino:avr arduino-cli compile --fqbn arduino:avr:uno --output-dir release/artifacts/firmware firmware/PortableAVRControlStudio ``` -The expected prepared firmware artifact is `release/artifacts/firmware/PortableAVRControlStudio.ino.hex`. Keep upload as a maintainer/developer prepared-artifact workflow unless an uploader such as `avrdude` is bundled, configured, and tested with the exact target hardware and COM-port procedure. +The expected prepared firmware artifact is `release/artifacts/firmware/PortableAVRControlStudio.ino.hex`. Customer-provided source code must be reviewed and compiled into a `.hex` artifact before handoff; customers do not paste raw code into the app. Release packages should include `PortableAVRControlStudio.ino.hex` beside the EXE and `tools/avrdude/` with the Windows uploader files staged by the release workflow. ## Draft status and hardware-test limitation diff --git a/docs/PACKAGING.md b/docs/PACKAGING.md index ed1245f..1f55d9d 100644 --- a/docs/PACKAGING.md +++ b/docs/PACKAGING.md @@ -50,8 +50,11 @@ The script copies these items into `release/customer_package/PortableAVRControlS 6. `docs\product_spec.md` 7. `docs\testing.md` 8. `docs\profiles\arduino_uno_avr.json` +9. `release/artifacts/windows/tools/avrdude/` staged as `tools/avrdude/` -The firmware upload tab is a placeholder workflow for prepared `.hex` artifacts. A production package should bundle and test the selected uploader, target MCU flags, COM-port behavior, and profile-specific firmware before presenting upload as a one-click customer feature. +The assembly script fails if `release/artifacts/windows/tools/avrdude/` does not include `avrdude.exe` and `avrdude.conf`. The release workflow stages those files from the Arduino AVR toolchain and copies required support files from the same Windows `bin` folder. These uploader files are generated release artifacts only and must not be committed to git. + +The firmware upload tab uploads prepared `.hex` artifacts to Arduino Uno using bundled or configured `avrdude`. It does not compile raw `.ino` source code. Upload success only means the firmware transfer command completed; it does not validate physical wiring, relay loads, sensors, power, or enclosure safety. ## Arduino Uno firmware HEX artifact @@ -70,7 +73,7 @@ arduino-cli core install arduino:avr arduino-cli compile --fqbn arduino:avr:uno --output-dir release/artifacts/firmware firmware/PortableAVRControlStudio ``` -The expected primary HEX output is `release/artifacts/firmware/PortableAVRControlStudio.ino.hex`. Treat this as a prepared artifact for a controlled upload process; do not describe the package as a tested one-click production uploader unless the uploader is bundled and validated with the final board and profile. +The expected primary HEX output is `release/artifacts/firmware/PortableAVRControlStudio.ino.hex`. Treat this as a prepared artifact for the app upload workflow. Customer-provided source code must be reviewed and compiled into a `.hex` artifact before customer handoff; the app does not compile raw `.ino` source code. ## Developer customer ZIP checklist diff --git a/docs/customer_handoff.md b/docs/customer_handoff.md index 17c6816..d0b9175 100644 --- a/docs/customer_handoff.md +++ b/docs/customer_handoff.md @@ -8,10 +8,11 @@ A prepared customer ZIP should contain: - `PortableAVRControlStudio.exe` — Windows desktop app. - `PortableAVRControlStudio.ino.hex` — prepared Arduino Uno firmware artifact, if firmware delivery is included. +- `tools/avrdude/` — bundled Windows uploader files used by the Firmware tab when included in the release package. - `docs/` — protocol, product settings, testing notes, and hardware profile documents. - `docs/profiles/arduino_uno_avr.json` — the default documented wiring/profile for Arduino Uno. -If the ZIP does not include an uploader tool such as `avrdude` plus tested upload settings, treat the `.hex` file as a prepared firmware artifact for a developer or maintainer to upload. Do not assume the app provides validated one-click production firmware upload. +The Firmware tab can upload the prepared `.hex` file when the package includes `tools/avrdude/` or when `avrdude` is available on `PATH`. It does not compile raw source code and upload success is not physical hardware validation. ## How to run the Windows app @@ -25,7 +26,7 @@ The app can be opened without an Arduino connected. Use demo mode for training o ## How to connect the Arduino Uno -1. Use an Arduino Uno or compatible ATmega328P AVR board that matches the documented hardware profile. +1. Use an Arduino Uno / ATmega328P AVR board that matches the documented hardware profile. 2. Connect the Arduino Uno to the Windows PC with a USB cable that supports data, not a charge-only cable. 3. Wait for Windows to finish installing or assigning the USB serial driver. 4. Open Windows Device Manager if needed and check **Ports (COM & LPT)** for the assigned COM port, such as `COM3` or `COM7`. @@ -93,7 +94,9 @@ EEPROM persistence still requires validation on the target physical board before ## Firmware artifact and upload boundary -The release package may include `PortableAVRControlStudio.ino.hex` at the customer package root as a prepared Arduino Uno firmware artifact. This repository documents how to build the artifact, but firmware upload should remain a maintainer/developer workflow unless the customer package also includes a tested uploader, exact command flags, target MCU settings, and COM-port procedure. +The release package may include `PortableAVRControlStudio.ino.hex` at the customer package root as a prepared Arduino Uno / ATmega328P AVR firmware artifact. Customers do not paste raw code into the app, and the app does not compile raw `.ino` source code. Customer-provided source code must be reviewed and compiled into a `.hex` artifact before it is selected in the app. + +When the customer package includes `tools/avrdude/`, the Firmware tab can upload a prepared `.hex` file to an Arduino Uno using the bundled uploader, or a configured `avrdude` on `PATH` if bundled files are missing. Upload requires an Arduino Uno, a USB data cable, the correct COM port, and a compatible Arduino bootloader. Upload success only means the firmware transfer command completed; it is not physical hardware validation of wiring, relay loads, sensors, power, or enclosure safety. ## What still requires physical hardware validation diff --git a/docs/testing.md b/docs/testing.md index af60087..2b72182 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -7,13 +7,35 @@ GitHub Actions runs `.github/workflows/checks.yml` with: ```bash python -m py_compile gui/portable_avr_control_studio.py python - <<'PY' -from gui.portable_avr_control_studio import parse_serial_line +from pathlib import Path +from tempfile import TemporaryDirectory +from gui.portable_avr_control_studio import UploadValidationError, parse_serial_line, validate_upload_request assert parse_serial_line('OK,PING\n').kind == 'OK' assert parse_serial_line('ERR,BAD,message\n').kind == 'ERR' assert parse_serial_line('CONFIG,DEVICE_NAME=Unit,SENSOR_VREF_MV=5000\n').fields['SENSOR_VREF_MV'] == '5000' assert parse_serial_line('STATUS,SENSOR_RAW=512,SENSOR_MV=2502\n').fields['SENSOR_MV'] == '2502' assert parse_serial_line('DATA,INFO,protocol=2\n').fields['PROTOCOL'] == '2' assert parse_serial_line('garbage\n').malformed + +with TemporaryDirectory() as temp: + root = Path(temp) + firmware = root / 'PortableAVRControlStudio.ino.hex' + firmware.write_text(':00000001FF\n', encoding='utf-8') + tools = root / 'tools' / 'avrdude' + tools.mkdir(parents=True) + (tools / 'avrdude.exe').write_text('dummy uploader', encoding='utf-8') + (tools / 'avrdude.conf').write_text('dummy config', encoding='utf-8') + cmd, tool, returned_firmware = validate_upload_request('COM7', str(firmware), root, path_env='') + assert tool.source == 'bundled' + assert returned_firmware == firmware + assert '-patmega328p' in cmd and '-carduino' in cmd + for port, hex_path in (('', str(firmware)), ('COM7', str(root / 'missing.hex'))): + try: + validate_upload_request(port, hex_path, root, path_env='') + except UploadValidationError: + pass + else: + raise AssertionError('expected firmware upload validation failure') PY ``` @@ -30,7 +52,7 @@ If Arduino CLI or network setup is unavailable in an execution environment, run ## Local checks ```bash -python -m py_compile gui/portable_avr_control_studio.py +python -m py_compile gui/portable_avr_control_studio.py release/scripts/assemble_customer_package.py python - <<'PY' from gui.portable_avr_control_studio import parse_serial_line assert parse_serial_line('OK,PING\n').kind == 'OK' diff --git a/gui/portable_avr_control_studio.py b/gui/portable_avr_control_studio.py index ce670a7..c09e86e 100644 --- a/gui/portable_avr_control_studio.py +++ b/gui/portable_avr_control_studio.py @@ -9,6 +9,7 @@ import datetime as _dt import json import queue +import shutil import subprocess import sys import threading @@ -89,6 +90,87 @@ def application_root() -> Path: PROFILE_DIR = application_root() / "docs" / "profiles" +class UploadValidationError(ValueError): + """User-facing validation error for prepared HEX firmware uploads.""" + + +@dataclass(frozen=True) +class AvrdudeTool: + executable: Path | str + config: Optional[Path] + source: str + + +def find_avrdude_tool(app_root: Path, path_env: Optional[str] = None) -> Optional[AvrdudeTool]: + """Find bundled avrdude first, then fall back to avrdude on PATH.""" + bundled_dir = app_root / "tools" / "avrdude" + for exe_name in ("avrdude.exe", "avrdude"): + candidate = bundled_dir / exe_name + if candidate.is_file(): + config = bundled_dir / "avrdude.conf" + return AvrdudeTool(candidate, config if config.is_file() else None, "bundled") + + found = shutil.which("avrdude", path=path_env) + if found: + executable = Path(found) + nearby_configs = ( + executable.with_name("avrdude.conf"), + executable.parent.parent / "etc" / "avrdude.conf", + ) + config = next((path for path in nearby_configs if path.is_file()), None) + return AvrdudeTool(executable, config, "PATH") + return None + + +def build_avrdude_upload_command(tool: AvrdudeTool, port: str, hex_file: Path) -> List[str]: + """Build an Arduino Uno / ATmega328P avrdude upload command without executing it.""" + cmd = [str(tool.executable)] + if tool.config is not None: + cmd.extend(["-C", str(tool.config)]) + cmd.extend([ + "-v", + "-patmega328p", + "-carduino", + "-P", + port, + "-b115200", + "-D", + f"-Uflash:w:{hex_file}:i", + ]) + return cmd + + +def validate_upload_request( + port: str, + hex_path: str, + app_root: Path, + path_env: Optional[str] = None, +) -> Tuple[List[str], AvrdudeTool, Path]: + """Validate user upload inputs and return the safe subprocess argument list.""" + normalized_port = port.strip() + if not normalized_port: + raise UploadValidationError("Select the Arduino Uno COM port before uploading firmware.") + + firmware = Path(hex_path).expanduser() + if not firmware.is_file(): + raise UploadValidationError("Select an existing prepared .hex firmware artifact before uploading.") + if firmware.suffix.lower() != ".hex": + raise UploadValidationError( + "The selected firmware artifact must end with .hex. Raw .ino source files are not supported by this app." + ) + + tool = find_avrdude_tool(app_root, path_env=path_env) + if tool is None: + raise UploadValidationError( + "avrdude was not found. Use a package that includes tools/avrdude/ beside the app, " + "or install avrdude on PATH before uploading to Arduino Uno." + ) + if tool.source == "bundled" and tool.config is None: + raise UploadValidationError("Bundled avrdude is missing avrdude.conf under tools/avrdude/.") + + return build_avrdude_upload_command(tool, normalized_port, firmware), tool, firmware + + @dataclass class ParsedLine: kind: str @@ -316,7 +398,9 @@ def __init__(self) -> None: "profile": tk.StringVar(value="Arduino Uno AVR"), } self.demo_mode = tk.BooleanVar(value=True) - self.hex_path = tk.StringVar(value="") + bundled_firmware = self._bundled_firmware_path() + self.hex_path = tk.StringVar(value=str(bundled_firmware) if bundled_firmware.is_file() else "") + self.upload_running = False self.port_var = tk.StringVar(value="") self.command_var = tk.StringVar(value="PING") self.transport: object = DemoTransport(self._queue_line, self._log) @@ -385,14 +469,24 @@ def _tab_firmware(self) -> None: frame = self._new_tab("Firmware") ttk.Label( frame, - text="Prepared .hex firmware artifacts can be selected for a placeholder handoff workflow only. This is not a validated production uploader unless avrdude, MCU flags, COM-port behavior, and the matching hardware profile have been packaged and tested.", + text=( + "The app uploads prepared .hex firmware artifacts to Arduino Uno using bundled or configured avrdude. " + "The app does not compile raw .ino source code. Upload success only means the firmware transfer command completed. " + "Upload success does not validate physical wiring, relay loads, sensors, power, or enclosure safety." + ), wraplength=920, ).grid(row=0, column=0, sticky="w") chooser = ttk.Frame(frame) chooser.grid(row=1, column=0, sticky="ew", pady=10) - ttk.Entry(chooser, textvariable=self.hex_path, width=78).pack(side="left", fill="x", expand=True) + ttk.Entry(chooser, textvariable=self.hex_path, width=70).pack(side="left", fill="x", expand=True) ttk.Button(chooser, text="Browse .hex", command=self._browse_hex).pack(side="left", padx=6) - ttk.Button(chooser, text="Placeholder: Upload Prepared HEX", command=self._upload_hex_placeholder).pack(side="left") + ttk.Button(chooser, text="Use bundled firmware", command=self._use_bundled_firmware).pack(side="left", padx=6) + self.upload_button = ttk.Button( + chooser, + text="Upload Firmware to Arduino Uno", + command=self._upload_firmware_to_uno, + ) + self.upload_button.pack(side="left") ttk.Button(frame, text="Read Board Info", command=lambda: self._send("INFO")).grid(row=2, column=0, sticky="w", pady=4) def _tab_settings(self) -> None: @@ -671,32 +765,94 @@ def _log(self, message: str) -> None: self.log_text.insert("end", f"[{timestamp}] {message}\n") self.log_text.see("end") + def _bundled_firmware_path(self) -> Path: + return application_root() / "PortableAVRControlStudio.ino.hex" + def _browse_hex(self) -> None: path = filedialog.askopenfilename(title="Select prepared firmware HEX", filetypes=[("Intel HEX", "*.hex"), ("All files", "*.*")]) if path: self.hex_path.set(path) - def _upload_hex_placeholder(self) -> None: - path = Path(self.hex_path.get()) - if not path.is_file(): - messagebox.showwarning("HEX required", "Select an existing .hex firmware artifact first.") + def _use_bundled_firmware(self) -> None: + bundled = self._bundled_firmware_path() + if bundled.is_file(): + self.hex_path.set(str(bundled)) + self._log(f"Selected bundled firmware: {bundled}") + else: + messagebox.showwarning( + "Bundled firmware missing", + "PortableAVRControlStudio.ino.hex was not found beside the app. Select a prepared .hex file instead.", + ) + + def _upload_firmware_to_uno(self) -> None: + if self.upload_running: return - avrdude = "avrdude" - port = self.port_var.get().strip() or "COMx" - cmd = [avrdude, "-patmega328p", "-carduino", f"-P{port}", "-b115200", "-D", f"-Uflash:w:{path}:i"] - self._log("Prepared upload command: " + " ".join(str(part) for part in cmd)) try: - completed = subprocess.run(cmd, check=False, capture_output=True, text=True, timeout=60) - self._log(completed.stdout.strip() or "avrdude produced no stdout") - if completed.returncode != 0: - self._log(completed.stderr.strip() or f"avrdude exited with {completed.returncode}") - messagebox.showwarning("Upload did not complete", "See Logs for avrdude output. This feature is a prepared-artifact placeholder.") - except FileNotFoundError: - self._log("avrdude is not bundled/found. Package an uploader before customer delivery.") - messagebox.showinfo("Uploader not bundled", "avrdude was not found. This placeholder documents the upload command for packaging.") + cmd, tool, firmware = validate_upload_request(self.port_var.get(), self.hex_path.get(), application_root()) + except UploadValidationError as exc: + self._log(f"Firmware upload validation failed: {exc}") + messagebox.showwarning("Firmware upload not ready", str(exc)) + return + + if hasattr(self.transport, "is_connected") and getattr(self.transport, "is_connected"): + self._log("Disconnecting serial session before upload so avrdude can use the COM port exclusively.") + self._disconnect() + + self.upload_running = True + if hasattr(self, "upload_button"): + self.upload_button.configure(state="disabled") + self.status_vars["connection"].set("Uploading firmware to Arduino Uno...") + self._log(f"Starting Arduino Uno firmware upload using {tool.source} avrdude.") + self._log(f"Firmware artifact: {firmware}") + self._log("Upload command: " + " ".join(cmd)) + thread = threading.Thread(target=self._run_upload_process, args=(cmd,), name="uno-firmware-upload", daemon=True) + thread.start() + + def _run_upload_process(self, cmd: List[str]) -> None: + returncode = -1 + try: + process = subprocess.Popen( + cmd, + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + text=True, + shell=False, + bufsize=1, + ) + assert process.stdout is not None + for line in process.stdout: + self._threadsafe_log(line.rstrip()) + returncode = process.wait() except Exception as exc: - self._log(f"Upload placeholder error: {exc}") - messagebox.showwarning("Upload error", str(exc)) + self._threadsafe_log(f"Firmware upload failed to start or run: {exc}") + message = f"Firmware upload failed: {exc}" + self.after(0, lambda message=message: self._finish_upload(False, message)) + return + + if returncode == 0: + message = ( + "Firmware upload to Arduino Uno completed. " + "This confirms only that avrdude reported a completed transfer." + ) + self.after(0, lambda message=message: self._finish_upload(True, message)) + else: + message = f"Firmware upload failed. avrdude exited with code {returncode}. See Logs for details." + self.after(0, lambda message=message: self._finish_upload(False, message)) + + def _threadsafe_log(self, message: str) -> None: + self.after(0, lambda: self._log(message)) + + def _finish_upload(self, success: bool, message: str) -> None: + self.upload_running = False + if hasattr(self, "upload_button"): + self.upload_button.configure(state="normal") + self._log(message) + if success: + self.status_vars["connection"].set("Firmware upload completed") + messagebox.showinfo("Firmware upload completed", message) + else: + self.status_vars["connection"].set("Firmware upload failed") + messagebox.showerror("Firmware upload failed", message) def _load_profiles(self) -> None: self.profile_list.delete(0, "end") diff --git a/release/BUILD_VERIFICATION.md b/release/BUILD_VERIFICATION.md index 625e5fe..e9a2b36 100644 --- a/release/BUILD_VERIFICATION.md +++ b/release/BUILD_VERIFICATION.md @@ -31,10 +31,10 @@ To run it from GitHub: The workflow publishes downloadable GitHub Actions artifacts from the completed run: -- `portable-avr-control-studio-windows-exe` containing `PortableAVRControlStudio.exe`. +- `portable-avr-control-studio-windows-exe` containing `PortableAVRControlStudio.exe` and staged `tools/avrdude/` uploader files. - `portable-avr-control-studio-uno-firmware` containing `PortableAVRControlStudio.ino.hex` and any related Arduino CLI firmware output files. - `portable-avr-control-studio-customer-package` containing `PortableAVRControlStudio-customer-handoff.zip` and `SHA256SUMS.txt`. -- `portable-avr-control-studio-sha256-checksums` containing `SHA256SUMS.txt` for the EXE, HEX, and ZIP. +- `portable-avr-control-studio-sha256-checksums` containing `SHA256SUMS.txt` for the EXE, HEX, customer ZIP, and staged uploader files where practical. The customer ZIP checksum also covers the bundled uploader tools in the final package. Download these from the workflow run summary page under **Artifacts**. Treat them as software build evidence only. The workflow compiles and packages files for the Arduino Uno / ATmega328P AVR target, but it does not validate operation on physical Arduino Uno hardware, connected loads, sensors, wiring, power, or enclosure. @@ -59,12 +59,17 @@ powershell -ExecutionPolicy Bypass -File .\release\scripts\build_windows_exe.ps1 The script installs or updates the Python packaging dependencies it needs, then runs PyInstaller against `gui\portable_avr_control_studio.py`. -Expected output file: +Expected output files from the workflow include the EXE plus bundled uploader staging files: ```text release\artifacts\windows\PortableAVRControlStudio.exe +release\artifacts\windows\tools\avrdude\avrdude.exe +release\artifacts\windows\tools\avrdude\avrdude.conf +release\artifacts\windows\tools\avrdude\...required DLLs/support files... ``` +The manual release workflow installs Arduino CLI and the `arduino:avr` core, locates the Arduino AVR `avrdude` tool, and stages the Windows uploader files under `release\artifacts\windows\tools\avrdude`. Do not commit those staged uploader files. + Verify the EXE exists: ```powershell @@ -128,6 +133,11 @@ release/customer_package/PortableAVRControlStudio-customer-handoff/ PortableAVRControlStudio.exe PortableAVRControlStudio.ino.hex README.md # Staged from release/templates/customer_zip_README.md + tools/ + avrdude/ + avrdude.exe + avrdude.conf + ...required DLLs/support files... docs/ customer_handoff.md PROTOCOL.md @@ -143,6 +153,8 @@ Verify the required staged files exist, including the customer-facing README sta test -f release/customer_package/PortableAVRControlStudio-customer-handoff/PortableAVRControlStudio.exe test -f release/customer_package/PortableAVRControlStudio-customer-handoff/PortableAVRControlStudio.ino.hex test -f release/customer_package/PortableAVRControlStudio-customer-handoff/README.md +test -f release/customer_package/PortableAVRControlStudio-customer-handoff/tools/avrdude/avrdude.exe +test -f release/customer_package/PortableAVRControlStudio-customer-handoff/tools/avrdude/avrdude.conf test -f release/customer_package/PortableAVRControlStudio-customer-handoff/docs/customer_handoff.md test -f release/customer_package/PortableAVRControlStudio-customer-handoff/docs/PROTOCOL.md test -f release/customer_package/PortableAVRControlStudio-customer-handoff/docs/product_spec.md @@ -175,4 +187,4 @@ Expected behavior: - Document software checks separately from physical Arduino Uno hardware validation. - Do not claim physical hardware testing unless a human maintainer provides evidence for the exact board, wiring, power, enclosure, and hardware profile. -- Do not claim one-click production upload unless uploader tooling is bundled, configured, and tested with the final artifact and customer environment. +- The app upload action transfers prepared `.hex` artifacts only; it does not compile raw `.ino` source code. Upload success only means the uploader command completed and is not physical hardware validation. diff --git a/release/FINAL_DELIVERY_SEQUENCE.md b/release/FINAL_DELIVERY_SEQUENCE.md index 1042f6e..a785942 100644 --- a/release/FINAL_DELIVERY_SEQUENCE.md +++ b/release/FINAL_DELIVERY_SEQUENCE.md @@ -67,7 +67,7 @@ Before sending the ZIP: - Review all customer-facing text for unsupported claims. - Confirm demo mode is described as simulation only. - Confirm unknown hardware is handled through documented profiles, not automatic detection. -- Confirm the package does not claim one-click production upload unless uploader tooling is bundled and tested. +- Confirm the package describes upload as a prepared `.hex` transfer only, not raw `.ino` compilation or physical hardware validation. - Confirm no generated EXE, HEX, or ZIP files are committed to git. Send the customer ZIP only after this claim review is complete. diff --git a/release/README.md b/release/README.md index 373462e..f5ed5e7 100644 --- a/release/README.md +++ b/release/README.md @@ -13,7 +13,7 @@ release/ build_windows_exe.ps1 # PyInstaller command for the portable Windows app build_uno_firmware_hex.sh # Arduino CLI command for the Uno firmware HEX artifact artifacts/ - windows/ # Generated PortableAVRControlStudio.exe (not committed) + windows/ # Generated PortableAVRControlStudio.exe and tools/avrdude/ (not committed) firmware/ # Generated Arduino Uno .hex files (not committed) customer_package/ # Generated staging folder and ZIP (not committed) templates/ @@ -35,6 +35,11 @@ A customer ZIP should be assembled from the staging area after the documented ch PortableAVRControlStudio-customer-handoff/ PortableAVRControlStudio.exe PortableAVRControlStudio.ino.hex + tools/ + avrdude/ + avrdude.exe + avrdude.conf + ...required DLLs/support files... docs/ customer_handoff.md PROTOCOL.md @@ -60,6 +65,6 @@ Record release evidence in `release/templates/maintainer_release_notes.md` and k ## Important release boundaries - The primary firmware artifact is for Arduino Uno / ATmega328P AVR using `arduino:avr:uno`. -- Firmware upload remains a prepared-artifact workflow. Do not present one-click production upload unless `avrdude` or another uploader is bundled, configured, and tested with the exact artifact, COM-port behavior, and hardware profile. +- Firmware upload is a prepared `.hex` artifact workflow for Arduino Uno using bundled or configured `avrdude`; it does not compile raw `.ino` source code, and upload success is not physical hardware validation. - Demo mode is simulation only. - This repository does not claim physical hardware validation. Record any future hardware evidence outside this draft package until it is reviewed and approved for customer release notes. diff --git a/release/candidates/RC-0.1.md b/release/candidates/RC-0.1.md index ac7511e..27de872 100644 --- a/release/candidates/RC-0.1.md +++ b/release/candidates/RC-0.1.md @@ -10,7 +10,7 @@ - **Arduino Uno HEX build status:** TBD by maintainer after building with Arduino CLI for `arduino:avr:uno` - **Customer ZIP assembly status:** TBD by maintainer after package assembly and inventory review - **Physical hardware validation status:** Not performed unless evidence is later attached -- **Upload status:** Prepared artifact only; no validated one-click production uploader +- **Upload status:** Prepared `.hex` upload to Arduino Uno using bundled or configured `avrdude`; no raw `.ino` compilation or physical hardware validation claim ## Manual release-build workflow note @@ -25,7 +25,7 @@ Complete this checklist before sending the RC-0.1 customer ZIP. - [ ] Build the Arduino Uno HEX using Arduino CLI for `arduino:avr:uno`. - [ ] Assemble the customer ZIP. - [ ] Fill maintainer release notes with the selected commit, build host details, tool versions, artifact inventory, and known limitations. -- [ ] Record SHA-256 checksums for the EXE, HEX, and ZIP artifacts. +- [ ] Record SHA-256 checksums for the EXE, HEX, ZIP, and staged uploader files where practical. - [ ] Review all customer-facing claims in the ZIP README, delivery message, release notes, and documentation. - [ ] Optionally test on a physical Arduino Uno / ATmega328P AVR board and attach evidence before making any physical hardware validation claim. @@ -37,7 +37,7 @@ Maintainers must fill or attach the following evidence before sending the custom 2. Windows EXE build evidence, including host details, dependency versions, file size, and SHA-256 checksum. 3. Arduino Uno HEX build evidence, including Arduino CLI version, AVR core version, file size, and SHA-256 checksum. 4. Customer ZIP assembly evidence, including file size, SHA-256 checksum, and package inventory. -5. Claim review confirmation that demo mode is simulation only, firmware upload is a prepared-artifact workflow, and no unsupported hardware validation claims are included. +5. Claim review confirmation that demo mode is simulation only, firmware upload is a prepared `.hex` transfer workflow, raw `.ino` compilation is not supported, and no unsupported hardware validation claims are included. 6. Optional physical Arduino Uno validation evidence, if performed, tied to the exact board, wiring, firmware checksum, and hardware profile used. ## Release boundaries @@ -46,4 +46,4 @@ Maintainers must fill or attach the following evidence before sending the custom - This tracking document does not add product features. - Generated EXE, HEX, and ZIP files must not be committed. - Do not claim physical hardware testing unless maintainer-supplied evidence is attached and reviewed. -- Do not claim one-click production firmware upload. The firmware is a prepared artifact unless validated uploader tooling is separately documented. +- Describe firmware upload as prepared `.hex` transfer to Arduino Uno only. Do not claim raw `.ino` compilation or physical hardware validation. diff --git a/release/checklists/release_readiness_checklist.md b/release/checklists/release_readiness_checklist.md index f0f67fd..b95241d 100644 --- a/release/checklists/release_readiness_checklist.md +++ b/release/checklists/release_readiness_checklist.md @@ -66,7 +66,7 @@ Build the prepared firmware artifact with Arduino CLI for the Uno target. - [ ] Record Arduino CLI version, `arduino:avr` core version, build host OS, file size, and SHA-256 checksum. - [ ] Update the RC-0.1 Arduino Uno HEX build status in `release/candidates/RC-0.1.md`. -- [ ] Treat the HEX as a prepared firmware artifact. Do not claim customer one-click production upload unless uploader tooling is bundled and tested with the exact artifact, board, COM-port behavior, and profile. +- [ ] Treat the HEX as a prepared firmware artifact. Confirm upload wording is limited to Arduino Uno prepared `.hex` transfer and does not claim raw `.ino` compilation or physical hardware validation. ## 4. Customer ZIP assembly diff --git a/release/scripts/assemble_customer_package.py b/release/scripts/assemble_customer_package.py index a3c3cb5..52681b1 100755 --- a/release/scripts/assemble_customer_package.py +++ b/release/scripts/assemble_customer_package.py @@ -15,6 +15,9 @@ PACKAGE_NAME = "PortableAVRControlStudio-customer-handoff" +UPLOADER_SOURCE_DIR = Path("release/artifacts/windows/tools/avrdude") +UPLOADER_DEST_DIR = Path("tools/avrdude") + REQUIRED_COPIES = ( ( Path("release/artifacts/windows/PortableAVRControlStudio.exe"), @@ -48,6 +51,25 @@ def parse_args() -> argparse.Namespace: return parser.parse_args() +def validate_uploader_files(repo_root: Path) -> None: + uploader_dir = repo_root / UPLOADER_SOURCE_DIR + if not uploader_dir.is_dir(): + raise FileNotFoundError( + "Bundled uploader files are missing. The release build must stage tools/avrdude/ first at " + f"{UPLOADER_SOURCE_DIR} before assembling the customer package." + ) + + required = (uploader_dir / "avrdude.exe", uploader_dir / "avrdude.conf") + missing = [path for path in required if not path.is_file()] + if missing: + missing_list = "\n".join(f" - {path.relative_to(repo_root)}" for path in missing) + raise FileNotFoundError( + "Bundled uploader files are incomplete. The release build must stage tools/avrdude/ with " + "avrdude.exe, avrdude.conf, and required support files before assembling the customer package.\n" + f"Missing files:\n{missing_list}" + ) + + def copy_required_files(repo_root: Path, package_dir: Path) -> None: missing_sources = [ str(src) for src, _ in REQUIRED_COPIES if not (repo_root / src).is_file() @@ -58,6 +80,7 @@ def copy_required_files(repo_root: Path, package_dir: Path) -> None: "Required release inputs are missing. Build the EXE and HEX artifacts first.\n" f"Missing files:\n{missing_list}" ) + validate_uploader_files(repo_root) if package_dir.exists(): shutil.rmtree(package_dir) @@ -68,6 +91,8 @@ def copy_required_files(repo_root: Path, package_dir: Path) -> None: dest_path.parent.mkdir(parents=True, exist_ok=True) shutil.copy2(repo_root / src, dest_path) + shutil.copytree(repo_root / UPLOADER_SOURCE_DIR, package_dir / UPLOADER_DEST_DIR) + def create_zip(package_dir: Path) -> Path: zip_base = package_dir.parent / PACKAGE_NAME diff --git a/release/templates/customer_zip_README.md b/release/templates/customer_zip_README.md index 44aa9bd..9a350ce 100644 --- a/release/templates/customer_zip_README.md +++ b/release/templates/customer_zip_README.md @@ -29,9 +29,18 @@ Unknown hardware is not automatically detected. Use only reviewed and documented ## What the `.hex` file is -`PortableAVRControlStudio.ino.hex` is a prepared firmware artifact for Arduino Uno / ATmega328P AVR. Treat it as an artifact for a maintainer or developer upload process unless this ZIP also includes a tested uploader tool and exact upload instructions. +`PortableAVRControlStudio.ino.hex` is a prepared firmware artifact for Arduino Uno / ATmega328P AVR. The app uploads prepared `.hex` files; it does not compile raw `.ino` source code and you should not paste raw code into the app. Customer-provided source code must be reviewed and compiled into a `.hex` artifact before upload. -This package does not claim one-click production firmware upload unless your supplier separately provides bundled, tested uploader tooling for the final board and COM-port procedure. +## How to upload prepared firmware + +1. Connect the Arduino Uno to the Windows PC with a USB data cable. +2. Select the Arduino Uno COM port in the app. +3. Open the Firmware tab. +4. Use the bundled `PortableAVRControlStudio.ino.hex`, or select another reviewed prepared `.hex` artifact. +5. Click **Upload Firmware to Arduino Uno**. +6. Watch the Logs tab for uploader output and the final success or failure message. + +The upload action uses bundled `tools/avrdude/` files when they are present, with `avrdude` on `PATH` as a fallback. Upload requires an Arduino Uno / ATmega328P AVR board with a compatible bootloader. Upload success only means the firmware transfer command completed; it does not validate wiring, relay loads, sensors, power, enclosure safety, or other physical hardware conditions. ## What is not yet physically validated diff --git a/release/templates/maintainer_release_notes.md b/release/templates/maintainer_release_notes.md index a94b595..ef176e9 100644 --- a/release/templates/maintainer_release_notes.md +++ b/release/templates/maintainer_release_notes.md @@ -113,7 +113,7 @@ Physical test evidence summary: - [ ] Customer-facing notes distinguish software build checks from physical hardware validation. - [ ] No claim of physical hardware testing is made unless evidence is attached above. -- [ ] No one-click production upload claim is made unless uploader tooling is bundled and tested. +- [ ] Firmware upload is described as prepared `.hex` transfer only, not raw `.ino` compilation or physical hardware validation. - [ ] Generated EXE, HEX, and ZIP artifacts are not committed to git. - [ ] The ZIP `README.md` is staged from `release/templates/customer_zip_README.md` and avoids unsupported claims. - [ ] The customer ZIP is not sent until this claim review is complete.