Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
58 changes: 20 additions & 38 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -9,16 +9,15 @@ on:
permissions:
contents: read

env:
ESP32_INDEX_URL: https://espressif.github.io/arduino-esp32/package_esp32_index.json
ESP32_FQBN: esp32:esp32:esp32doit-devkit-v1
NVS_GUARD: compiler.c.elf.extra_flags=-Wl,--wrap=nvs_flash_init

jobs:
build:
name: Compile Arduino sketch
name: Compile Arduino sketch (ESP32 ${{ matrix.core }})
runs-on: ubuntu-latest
timeout-minutes: 30
strategy:
fail-fast: false
matrix:
core: ['3.3.12', '4.0.0']

steps:
- name: Check out source
Expand All @@ -32,39 +31,24 @@ jobs:
- name: Cache Arduino packages
uses: actions/cache@v4
with:
path: |
~/.arduino15
~/.cache/arduino
key: ${{ runner.os }}-arduino-cli-1.1.1-esp32-3.3.12-nimble-2.3.8

- name: Install ESP32 core and libraries
run: |
arduino-cli config init --overwrite
arduino-cli config add board_manager.additional_urls "$ESP32_INDEX_URL"
arduino-cli core update-index
arduino-cli core install esp32:esp32@3.3.12
arduino-cli lib update-index
arduino-cli lib install --no-deps "NimBLE-Arduino@2.3.8"
path: .tools/arduino
key: ${{ runner.os }}-protected-arduino-1.1.1-${{ matrix.core }}-${{ hashFiles('Build-PulseShift.ps1') }}

- name: Compile - production firmware (default)
run: |
arduino-cli compile \
--fqbn "$ESP32_FQBN" --build-property "$NVS_GUARD" \
--build-path "$RUNNER_TEMP/build-production" \
PulseShift
test "$(( $(wc -c < "$RUNNER_TEMP/build-production/PulseShift.ino.bin") + 76 ))" -le 1310720
run: pwsh -NoProfile -File ./Build-PulseShift.ps1 -ArduinoCli arduino-cli -CoreVersion '${{ matrix.core }}' -BuildDirectory "$RUNNER_TEMP/build-production"

- name: Compile - fully headless variant (serial diagnostics off)
run: pwsh -NoProfile -File ./Build-PulseShift.ps1 -ArduinoCli arduino-cli -CoreVersion '${{ matrix.core }}' -Headless -BuildDirectory "$RUNNER_TEMP/build-headless"

- name: Reject an unprotected Arduino IDE-style build
run: |
mkdir -p "$RUNNER_TEMP/variants/headless"
cp -r PulseShift "$RUNNER_TEMP/variants/headless/PulseShift"
sed -i 's/#define PULSESHIFT_SERIAL_DIAGNOSTICS 1/#define PULSESHIFT_SERIAL_DIAGNOSTICS 0/' \
"$RUNNER_TEMP/variants/headless/PulseShift/UserConfig.h"
arduino-cli compile \
--fqbn "$ESP32_FQBN" --build-property "$NVS_GUARD" \
--build-path "$RUNNER_TEMP/build-headless" \
"$RUNNER_TEMP/variants/headless/PulseShift"
test "$(( $(wc -c < "$RUNNER_TEMP/build-headless/PulseShift.ino.bin") + 76 ))" -le 1310720
log="$RUNNER_TEMP/unsupported-build.log"
if arduino-cli --config-file ".tools/arduino/esp32-${{ matrix.core }}/arduino-cli.yaml" compile \
--fqbn esp32:esp32:esp32doit-devkit-v1 --build-path "$RUNNER_TEMP/build-unsupported" PulseShift > "$log" 2>&1; then
echo 'Unprotected build unexpectedly compiled' >&2
exit 1
fi
grep -F 'PulseShift needs its protected build' "$log"

- name: Reject invalid user configuration
run: |
Expand All @@ -73,10 +57,8 @@ jobs:
sed -i 's/#define PULSESHIFT_LED_COUNT 6/#define PULSESHIFT_LED_COUNT 0/' \
"$RUNNER_TEMP/variants/invalid/PulseShift/UserConfig.h"
log="$RUNNER_TEMP/invalid-config.log"
if arduino-cli compile \
--fqbn "$ESP32_FQBN" --build-property "$NVS_GUARD" \
--build-path "$RUNNER_TEMP/build-invalid" \
"$RUNNER_TEMP/variants/invalid/PulseShift" > "$log" 2>&1; then
if pwsh -NoProfile -File ./Build-PulseShift.ps1 -ArduinoCli arduino-cli -CoreVersion '${{ matrix.core }}' \
-BuildDirectory "$RUNNER_TEMP/build-invalid" -SketchDirectory "$RUNNER_TEMP/variants/invalid/PulseShift" > "$log" 2>&1; then
echo "Invalid config unexpectedly compiled" >&2
exit 1
fi
Expand Down
63 changes: 22 additions & 41 deletions .github/workflows/release.yml
Original file line number Diff line number Diff line change
@@ -1,66 +1,47 @@
name: Publish GitHub Release
name: Prepare firmware OTA candidate

on:
push:
tags:
- "v*"
workflow_dispatch:

concurrency:
group: release-${{ github.ref_name }}
cancel-in-progress: false

permissions:
contents: write
contents: read

jobs:
release:
name: Build and publish release
name: Build application for offline signing
runs-on: ubuntu-latest
timeout-minutes: 30
env:
ESP32_INDEX_URL: https://espressif.github.io/arduino-esp32/package_esp32_index.json
ESP32_FQBN: esp32:esp32:esp32doit-devkit-v1
NVS_GUARD: compiler.c.elf.extra_flags=-Wl,--wrap=nvs_flash_init

steps:
- name: Check out source
uses: actions/checkout@v4
with:
persist-credentials: false

- name: Set up Arduino CLI
uses: arduino/setup-arduino-cli@v2
with:
version: 1.1.1

- name: Install ESP32 core and libraries
run: |
arduino-cli config init --overwrite
arduino-cli config add board_manager.additional_urls "$ESP32_INDEX_URL"
arduino-cli core update-index
arduino-cli core install esp32:esp32@3.3.12
arduino-cli lib update-index
arduino-cli lib install --no-deps "NimBLE-Arduino@2.3.8"

- name: Compile and verify sketch
run: |
arduino-cli compile \
--fqbn "$ESP32_FQBN" --build-property "$NVS_GUARD" \
--build-path "$RUNNER_TEMP/build-release" \
PulseShift
test "$(( $(wc -c < "$RUNNER_TEMP/build-release/PulseShift.ino.bin") + 76 ))" -le 1310720
- name: Compile and verify application
run: pwsh -NoProfile -File ./Build-PulseShift.ps1 -ArduinoCli arduino-cli -BuildDirectory "$RUNNER_TEMP/build-release"

- name: Package Arduino sketch ZIP
- name: Prepare offline signing input
run: |
ZIP="PulseShift-Arduino-$GITHUB_REF_NAME.zip"
git archive --format=zip --output="$RUNNER_TEMP/$ZIP" HEAD PulseShift/ docs/TESTING.md
(cd "$RUNNER_TEMP" && sha256sum "$ZIP" > "$ZIP.sha256")
echo "ZIP=$RUNNER_TEMP/$ZIP" >> "$GITHUB_ENV"
echo "SHA=$RUNNER_TEMP/$ZIP.sha256" >> "$GITHUB_ENV"

- name: Upload release assets
uses: softprops/action-gh-release@v2
set -euo pipefail
mkdir "$RUNNER_TEMP/ota-candidate"
cd "$RUNNER_TEMP/ota-candidate"
cp "$RUNNER_TEMP/build-release/"{PulseShift.ino.bin,PulseShift.ino.partitions.bin,partitions.csv,build-verification.json} .
git -C "$GITHUB_WORKSPACE" rev-parse HEAD > source.txt
sha256sum PulseShift.ino.bin PulseShift.ino.partitions.bin partitions.csv build-verification.json source.txt > SHA256SUMS.txt

- name: Store application-only signing input
uses: actions/upload-artifact@v4
with:
files: |
${{ env.ZIP }}
${{ env.SHA }}
draft: true
generate_release_notes: true
name: PulseShift-OTA-signing-input-${{ github.sha }}
path: ${{ runner.temp }}/ota-candidate/
if-no-files-found: error
retention-days: 7
6 changes: 6 additions & 0 deletions Build-PulseShift.cmd
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
@echo off
powershell.exe -NoProfile -ExecutionPolicy Bypass -File "%~dp0Build-PulseShift.ps1" %*
set "PULSESHIFT_BUILD_EXIT=%ERRORLEVEL%"
if not "%PULSESHIFT_BUILD_EXIT%"=="0" echo PulseShift build failed. See the diagnostic above.
pause
exit /b %PULSESHIFT_BUILD_EXIT%
172 changes: 172 additions & 0 deletions Build-PulseShift.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,172 @@
[CmdletBinding()]
param(
[ValidateSet('3.3.12', '4.0.0')][string]$CoreVersion = '3.3.12',
[switch]$Headless,
[string]$BuildDirectory,
[string]$CacheDirectory,
[string]$ArduinoCli,
[string]$SketchDirectory
)

$ErrorActionPreference = 'Stop'
Set-StrictMode -Version Latest
$CacheDirectory = if ($CacheDirectory) { $CacheDirectory } else { Join-Path $PSScriptRoot '.tools/arduino' }
$SketchDirectory = if ($SketchDirectory) { $SketchDirectory } else { Join-Path $PSScriptRoot 'PulseShift' }
$cliVersion = '1.1.1'
$nimble = @{ '3.3.12' = '2.3.8'; '4.0.0' = '2.5.2' }[$CoreVersion]
$bootloaderHash = @{
'3.3.12' = '7c5e6c42dcd3b658a81374d51e42aa839559b936df3ec181e94e864880b29fc2'
'4.0.0' = 'e81751780c46fffddf6deeb4c9a1c01c169952aefd114c6ae3086a9b9c5d0198'
}[$CoreVersion]
$isWindowsBuild = $env:OS -eq 'Windows_NT'
$cache = [IO.Path]::GetFullPath($CacheDirectory)
$coreCache = Join-Path $cache "esp32-$CoreVersion"
$downloads = Join-Path $cache 'downloads'
$data = Join-Path $coreCache 'data'
$sketchbook = Join-Path $coreCache 'sketchbook'
$index = 'https://espressif.github.io/arduino-esp32/package_esp32_index.json'
if (!$BuildDirectory) {
$variant = if ($Headless) { 'headless' } else { 'production' }
$BuildDirectory = Join-Path $PSScriptRoot "build/esp32-$CoreVersion/$variant"
}
$build = [IO.Path]::GetFullPath($BuildDirectory)
$sketch = (Resolve-Path -LiteralPath $SketchDirectory).Path
New-Item -ItemType Directory -Force -Path $coreCache, $downloads, $data, $sketchbook, $build | Out-Null
$reportPath = Join-Path $build 'build-verification.json'
if (Test-Path -LiteralPath $reportPath) { Remove-Item -LiteralPath $reportPath }

function Get-Sha256([string]$PathValue) {
$sha256 = [Security.Cryptography.SHA256]::Create()
$inputStream = [IO.File]::OpenRead($PathValue)
try {
return [BitConverter]::ToString($sha256.ComputeHash($inputStream)).Replace('-', '').ToLowerInvariant()
} finally {
$inputStream.Dispose()
$sha256.Dispose()
}
}

if (!$ArduinoCli) {
if (!$isWindowsBuild -or $env:PROCESSOR_ARCHITECTURE -ne 'AMD64') {
throw 'The one-click installer needs x64 Windows. On Linux x64 provide Arduino CLI 1.1.1 with -ArduinoCli.'
}
$cliDir = Join-Path $cache "cli-$cliVersion"
$ArduinoCli = Join-Path $cliDir 'arduino-cli.exe'
if (!(Test-Path -LiteralPath $ArduinoCli)) {
$zip = Join-Path $downloads "arduino-cli_${cliVersion}_Windows_64bit.zip"
$sha = 'f49a61865ff5d91d2732a19c51b0ac767cce51213db84b0b28b98ee070879f66'
if (!(Test-Path -LiteralPath $zip)) {
Write-Host "Downloading Arduino CLI $cliVersion from Arduino."
Invoke-WebRequest -UseBasicParsing -Uri "https://github.com/arduino/arduino-cli/releases/download/v$cliVersion/arduino-cli_${cliVersion}_Windows_64bit.zip" -OutFile $zip
}
if ((Get-Sha256 $zip) -ne $sha) {
throw "Arduino CLI archive SHA-256 mismatch. Replace this cached download and retry: $zip"
}
Add-Type -AssemblyName System.IO.Compression.FileSystem
[IO.Compression.ZipFile]::ExtractToDirectory($zip, $cliDir)
}
}

$version = & $ArduinoCli version
if ($LASTEXITCODE -ne 0 -or ($version -join ' ') -notmatch '\bVersion:\s+1\.1\.1(?:\s|$)') {
throw "PulseShift requires Arduino CLI $cliVersion. Got: $version"
}

function YamlPath([string]$PathValue) {
return "'" + $PathValue.Replace('\', '/').Replace("'", "''") + "'"
}

$cfg = Join-Path $coreCache 'arduino-cli.yaml'
@"
board_manager:
additional_urls: [$index]
directories:
data: $(YamlPath $data)
downloads: $(YamlPath $downloads)
user: $(YamlPath $sketchbook)
build_cache:
path: $(YamlPath (Join-Path $coreCache 'cache'))
"@ | Set-Content -LiteralPath $cfg -Encoding UTF8

function Invoke-Arduino([string[]]$Arguments) {
& $ArduinoCli --config-file $cfg @Arguments
if ($LASTEXITCODE -ne 0) { throw "Arduino CLI failed ($LASTEXITCODE): $($Arguments -join ' ')" }
}

$effective = (Invoke-Arduino @('config', 'dump', '--format', 'json') | Out-String | ConvertFrom-Json).config
foreach ($entry in @(@('data', $data), @('downloads', $downloads), @('user', $sketchbook))) {
if ([IO.Path]::GetFullPath($effective.directories.($entry[0])) -ne $entry[1]) {
throw "Arduino environment overrides the isolated $($entry[0]) directory. Clear that override to build safely."
}
}

$platform = Join-Path $data "packages/esp32/hardware/esp32/$CoreVersion/platform.txt"
if (!(Test-Path -LiteralPath $platform)) {
Write-Host "Installing Espressif board package $CoreVersion to $data."
Invoke-Arduino @('core', 'update-index')
Invoke-Arduino @('core', 'install', "esp32:esp32@$CoreVersion")
}
$library = Join-Path $sketchbook 'libraries/NimBLE-Arduino/library.properties'
if (!(Test-Path -LiteralPath $library) -or !(Select-String -LiteralPath $library -Pattern "^version=$([regex]::Escape($nimble))$" -Quiet)) {
Invoke-Arduino @('lib', 'update-index')
Invoke-Arduino @('lib', 'install', '--no-deps', "NimBLE-Arduino@$nimble")
}

$defines = '-DPULSESHIFT_PROTECTED_BUILD=1'
if ($Headless) { $defines += ' -DPULSESHIFT_SERIAL_DIAGNOSTICS=0' }
$compile = @('compile', '--fqbn', 'esp32:esp32:esp32doit-devkit-v1', '--build-path', $build,
'--build-property', "compiler.cpp.extra_flags=$defines",
'--build-property', 'compiler.c.elf.extra_flags=-Wl,--wrap=nvs_flash_init')
Write-Host "Building for ESP32 $CoreVersion with NimBLE-Arduino $nimble."
Invoke-Arduino ($compile + $sketch)

$props = Invoke-Arduino ($compile + @('--show-properties=expanded', $sketch))
$compilerPath = ($props | Where-Object { $_ -like 'compiler.path=*' } | Select-Object -First 1) -replace '^compiler.path=', ''
$compilerName = ($props | Where-Object { $_ -like 'compiler.cpp.cmd=*' } | Select-Object -First 1) -replace '^compiler.cpp.cmd=', ''
if (!$compilerPath -or !$compilerName -or $props -notcontains 'build.bootloader_addr=0x1000' -or $props -notcontains 'build.flash_size=4MB') {
throw 'Unexpected ESP32 compiler, bootloader offset or flash size.'
}
$suffix = if ($isWindowsBuild) { '.exe' } else { '' }
$objdump = Join-Path $compilerPath (($compilerName -replace 'g\+\+(\.exe)?$', 'objdump') + $suffix)
$elf = Join-Path $build 'PulseShift.ino.elf'
$startup = & $objdump -d --disassemble=initArduino $elf | Out-String
if ($LASTEXITCODE -ne 0 -or $startup -notmatch '<__wrap_nvs_flash_init>' -or $startup -notmatch '<verifyRollbackLater>') {
throw 'Linked initArduino() does not call both the NVS guard and the rollback hook.'
}
$sdk = Join-Path $build 'sdkconfig'
foreach ($setting in @('CONFIG_APP_ROLLBACK_ENABLE=y', 'CONFIG_BOOTLOADER_APP_ROLLBACK_ENABLE=y')) {
if (!(Select-String -LiteralPath $sdk -Pattern "^$setting$" -Quiet)) { throw "Missing SDK setting $setting" }
}
$partition = Join-Path $build 'PulseShift.ino.partitions.bin'
$partitionHash = Get-Sha256 $partition
if ($partitionHash -ne '148b959cbff1c38aa8e1d5c0ba9d612c54997b945e56a63f41223eef650653a1') {
throw 'Compiled partition table differs from the installed PulseShift 4 MiB layout.'
}
$boot = Join-Path $build 'PulseShift.ino.bootloader.bin'
if ((Get-Sha256 $boot) -ne $bootloaderHash) {
throw 'Unexpected bootloader binary for the pinned board package and flash configuration.'
}
$app = Join-Path $build 'PulseShift.ino.bin'
$bytes = [IO.File]::ReadAllBytes($app)
if ($bytes.Length -lt 65536 -or $bytes.Length + 76 -gt 0x140000 -or
$bytes[0] -ne 0xe9 -or $bytes[12] -ne 0 -or $bytes[13] -ne 0 -or
[BitConverter]::ToString($bytes, 32, 4) -ne '32-54-CD-AB') {
throw 'The build did not produce a classic ESP32 application that fits the signed OTA slot.'
}

[ordered]@{
arduinoCli = $cliVersion
esp32Core = $CoreVersion
nimble = $nimble
headless = [bool]$Headless
nvsStartupGuard = 'Verified in linked initArduino'
deferredRollback = 'Verified hook, SDK flags and build bootloader hash'
bootloaderAddress = '0x1000'
bootloaderSha256 = $bootloaderHash.ToLowerInvariant()
partitionSha256 = $partitionHash
applicationSha256 = Get-Sha256 $app
applicationBytes = $bytes.Length
signedPackageBytes = $bytes.Length + 76
slotBytes = 0x140000
} | ConvertTo-Json | Set-Content -LiteralPath $reportPath -Encoding UTF8
Write-Host "Build and protection checks passed. Application: $app"
Loading
Loading