diff --git a/.github/ci/bookworm-camera-archive.sh b/.github/ci/bookworm-camera-archive.sh
new file mode 100644
index 0000000..bc44577
--- /dev/null
+++ b/.github/ci/bookworm-camera-archive.sh
@@ -0,0 +1,21 @@
+#!/bin/bash
+set -euo pipefail
+
+apt-get update -o APT::Update::Error-Mode=any -qq
+apt-get install -y --no-install-recommends ca-certificates curl
+keyring=/usr/share/keyrings/mandeye-raspberrypi.asc
+curl --fail --silent --show-error --location --retry 3 \
+ https://archive.raspberrypi.com/debian/raspberrypi.gpg.key --output "$keyring"
+fingerprint=CF8A1AF502A2AA2D763BAE7E82B129927FA3303E
+printf '%s\n' "deb [signed-by=$keyring,$fingerprint] https://archive.raspberrypi.com/debian/ bookworm main" \
+ > /etc/apt/sources.list.d/raspberrypi.list
+cat > /etc/apt/preferences.d/raspberrypi-camera <<'PREFERENCES'
+Package: libcamera* libpisp*
+Pin: origin archive.raspberrypi.com
+Pin-Priority: 900
+
+Package: *
+Pin: origin archive.raspberrypi.com
+Pin-Priority: -1
+PREFERENCES
+apt-get update -o APT::Update::Error-Mode=any -qq
diff --git a/.github/ci/build-deb.sh b/.github/ci/build-deb.sh
new file mode 100644
index 0000000..e450af2
--- /dev/null
+++ b/.github/ci/build-deb.sh
@@ -0,0 +1,35 @@
+#!/bin/bash
+set -euo pipefail
+
+bash .github/ci/bookworm-camera-archive.sh
+apt-get install -y --no-install-recommends build-essential cmake file git pkg-config \
+ libserial-dev libgpiod-dev libzmq3-dev libboost-all-dev libpistache-dev rapidjson-dev \
+ nlohmann-json3-dev cppzmq-dev libcamera-dev libopencv-dev pps-tools
+git config --global --add safe.directory /src
+test "$(git rev-parse HEAD)" = "$GITHUB_SHA"
+cmake -S . -B /tmp/build -DCMAKE_BUILD_TYPE=Release -DMANDEYE_USE_LIBCAMERA=ON
+cmake --build /tmp/build --parallel "$(nproc)"
+ctest --test-dir /tmp/build --output-on-failure
+# Give uploads of the same Git revision distinct Debian revisions. Local
+# CPack builds keep their source-derived version.
+release="${GITHUB_RUN_ID:?}.${GITHUB_RUN_ATTEMPT:?}"
+cpack --config /tmp/build/CPackConfig.cmake -G DEB -B /packages \
+ -D "CPACK_PACKAGE_FILE_NAME=${PACKAGE%.deb}" -D "CPACK_DEBIAN_PACKAGE_RELEASE=$release"
+version=$(dpkg-deb -f "/packages/$PACKAGE" Version)
+test "${version##*-}" = "$release"
+dpkg-deb -f "/packages/$PACKAGE" Package Version Architecture Depends Recommends
+test "$(dpkg-deb -f "/packages/$PACKAGE" Package)" = mandeye-multisensor
+test "$(dpkg-deb -f "/packages/$PACKAGE" Architecture)" = arm64
+test "$(dpkg-deb -f "/packages/$PACKAGE" Recommends)" = linuxptp
+
+if [[ ! -s /packages/legacy.deb ]]; then
+ cd /src/legacy
+ git config --global --add safe.directory /src/legacy
+ test "$(git rev-parse HEAD)" = "$LEGACY_SHA"
+ cmake -S . -B /tmp/old-build -DCMAKE_BUILD_TYPE=Release \
+ -DMANDEYE_HARDWARE_HEADER=mandeye-pro-cm4-bookworm.h -DMANDEYE_USE_LIBCAMERA=ON
+ cmake --build /tmp/old-build --parallel "$(nproc)"
+ cpack --config /tmp/old-build/CPackConfig.cmake -G DEB -B /packages -D CPACK_PACKAGE_FILE_NAME=legacy \
+ -D CPACK_DEBIAN_PACKAGE_SHLIBDEPS=ON -D CPACK_DEBIAN_PACKAGE_DEPENDS=systemd \
+ -D CPACK_DEBIAN_PACKAGE_RECOMMENDS=linuxptp
+fi
diff --git a/.github/ci/installed-scan.sh b/.github/ci/installed-scan.sh
new file mode 100644
index 0000000..72da6cb
--- /dev/null
+++ b/.github/ci/installed-scan.sh
@@ -0,0 +1,17 @@
+#!/bin/bash
+set -euo pipefail
+
+bash .github/ci/bookworm-camera-archive.sh
+apt-get install -y --no-install-recommends "/packages/$PACKAGE" python3-venv
+for path in /opt/mandeye/{control_program,extras/mandeye_libcamera,led_demo,button_demo}; do
+ test -x "$path"
+done
+for unit in mandeye_libcamera_cam{0,1}.service; do
+ test -f "/usr/lib/systemd/system/$unit"
+done
+test -z "$(getent passwd pi)"
+python3 tests/package/test-device-config.py
+python3 tests/package/test-picamera-config.py
+python3 -m venv /tmp/scan-venv
+/tmp/scan-venv/bin/pip install --disable-pip-version-check 'laspy[lazrs]==2.6.1'
+/tmp/scan-venv/bin/python tests/installed-scan.py
diff --git a/.github/ci/package-comment.cjs b/.github/ci/package-comment.cjs
new file mode 100644
index 0000000..5c49c8a
--- /dev/null
+++ b/.github/ci/package-comment.cjs
@@ -0,0 +1,188 @@
+'use strict';
+
+const marker = '';
+const sha = /^[a-f0-9]{40}$/;
+const path = '.github/workflows/build-deb.yml';
+
+function currentRun(runs, pr) {
+ // run_number (unlike updated_at) cannot promote a rerun of an older build.
+ return runs.filter(run =>
+ run.path === path && run.event === 'pull_request' &&
+ run.display_title === `Bookworm ARM64 PR ${pr.number} ${pr.merge_commit_sha}` &&
+ run.head_sha === pr.head.sha && run.head_branch === pr.head.ref &&
+ run.head_repository?.id === pr.head.repo?.id &&
+ (!run.pull_requests?.length || run.pull_requests.some(link =>
+ link.number === pr.number && link.base.repo.id === pr.base.repo.id &&
+ link.base.ref === pr.base.ref)))
+ .sort((a, b) => b.run_number - a.run_number || b.run_attempt - a.run_attempt)[0];
+}
+
+function uploadAttempt(run, jobs) {
+ // GitHub retains jobs from successful earlier attempts on a partial rerun.
+ // Require evidence of the current attempt; a stale job listing cannot certify it.
+ if (!jobs.some(j => j.run_attempt === run.run_attempt) || jobs.some(j =>
+ j.run_id !== run.id || j.head_sha !== run.head_sha || !Number.isSafeInteger(j.run_attempt) ||
+ j.run_attempt < 1 || j.run_attempt > run.run_attempt)) return null;
+ const builds = jobs.filter(j => j.name === 'Build and test .deb');
+ const attempt = Math.max(...builds.map(j => j.run_attempt));
+ const latest = builds.filter(j => j.run_attempt === attempt);
+ if (latest.length !== 1 || latest[0].status !== 'completed' || latest[0].conclusion !== 'success') return null;
+ const build = latest[0];
+ // On publisher-only retries GitHub may copy a successful build to a new
+ // job ID and run_attempt while preserving its runner and execution interval.
+ const sameExecution = j => j === build || (j.name === build.name &&
+ j.status === 'completed' && j.conclusion === 'success' &&
+ Number.isSafeInteger(build.runner_id) && build.runner_id > 0 && j.runner_id === build.runner_id &&
+ Number.isFinite(Date.parse(build.started_at)) && Date.parse(build.completed_at) > Date.parse(build.started_at) &&
+ j.started_at === build.started_at && j.completed_at === build.completed_at);
+ const uploaded = Math.min(...builds.filter(sameExecution).map(j => j.run_attempt));
+ if (builds.filter(j => j.run_attempt === uploaded).length !== 1) return null;
+ // Only a rerun of the comment jobs can inherit a package. A failed, skipped
+ // or incomplete newer build must never fall back to an older artifact.
+ if (jobs.some(j => j.run_attempt > uploaded && !sameExecution(j) &&
+ !['result / comment', 'building / comment'].includes(j.name))) return null;
+ return uploaded;
+}
+
+function availability(run, artifacts, directResult, merge, now, artifactAttempt) {
+ if (!run) return {state: 'waiting'};
+ const outcome = run.status === 'completed' ? run.conclusion : directResult;
+ if (!outcome) return {state: 'building'};
+ if (outcome !== 'success') return {state: outcome === 'cancelled' ? 'cancelled' : 'failed'};
+
+ // Artifact listings span all attempts of the same run. A raw file carries
+ // its attempt in its basename, including when two uploads arrive out of order.
+ if (!artifactAttempt) return {state: 'unavailable'};
+ const prefix = `mandeye-multisensor-bookworm-arm64-${merge}-a`;
+ const name = `${prefix}${artifactAttempt}.deb`;
+ const runArtifacts = artifacts.filter(a => a.workflow_run?.id === run.id);
+ const attemptName = new RegExp(`^${prefix}(\\d+)\\.deb$`);
+ if (runArtifacts.some(a => Number(a.name.match(attemptName)?.[1]) > artifactAttempt)) return {state: 'unavailable'};
+ const matching = runArtifacts.filter(a => a.name === name);
+ if (matching.length !== 1) return {state: 'unavailable'};
+ const [a] = matching;
+ const expires = Date.parse(a.expires_at);
+ if (a.expired || expires <= now) return {state: 'expired'};
+ if (!Number.isFinite(expires) || !Number.isSafeInteger(a.id) ||
+ !/^sha256:[a-f0-9]{64}$/.test(a.digest)) return {state: 'unavailable'};
+ return {state: 'ready', name, id: a.id, digest: a.digest.slice(7), expiry: new Date(expires).toISOString()};
+}
+
+function bodyFor(repoUrl, pr, run, info) {
+ const merge = sha.test(pr.merge_commit_sha) ? pr.merge_commit_sha : null;
+ const generation = [pr.head.sha, merge || '-', run?.run_number || 0, run?.run_attempt || 0, info.state];
+ const body = [
+ marker, ``,
+ '### Raspberry Pi OS Bookworm ARM64 field package', '',
+ `PR head \`${pr.head.sha}\` · Test merge ${merge ? '\`' + merge + '\`' : 'pending'}`,
+ `[Installation and first scan](${repoUrl}/blob/${merge || pr.head.sha}/README.md)`, '',
+ ];
+ const runUrl = run && `${repoUrl}/actions/runs/${run.id}`;
+ if (info.state === 'ready') {
+ body.push(`[Download the .deb](${runUrl}/artifacts/${info.id}) (sign in to GitHub).`, `File: \`${info.name}\``,
+ '', `SHA-256: \`${info.digest}\``,
+ '', `Expires **${info.expiry}** (UTC). After that time the package is unavailable until a new build.`);
+ } else {
+ const message = {
+ waiting: 'Waiting for a build of this revision. No current package is available.',
+ building: 'Building and testing. No current package is available. If this attempt is cancelled or fails, rerun it.',
+ cancelled: 'Build cancelled. No current package is available.',
+ failed: 'Build failed. No current package is available.',
+ expired: 'Package expired. Rerun the build for a new download.',
+ unavailable: 'Package unavailable. Rerun the build for a new download.',
+ };
+ body.push(`**${message[info.state]}**`);
+ }
+ if (run) body.push('', `[Build ${run.run_number}, attempt ${run.run_attempt}](${runUrl}/attempts/${run.run_attempt})`);
+ return body.join('\n');
+}
+
+function generation(body) {
+ return body.match(//);
+}
+
+function canReplace(before, after) {
+ const prev = generation(before);
+ const next = generation(after);
+ if (!prev || prev[1] !== next[1] || prev[2] !== next[2]) return true;
+ if (+next[3] !== +prev[3]) return +next[3] > +prev[3];
+ if (+next[4] !== +prev[4]) return +next[4] > +prev[4];
+ return !(['waiting', 'building'].includes(next[5]) && !['waiting', 'building'].includes(prev[5]));
+}
+
+async function publish(github, context, buildResult, attempt) {
+ const repo = context.repo;
+ const repoId = context.payload.repository.id;
+ const rest = github.rest;
+ const list = (method, options) => github.paginate(method, {...repo, per_page: 100, ...options});
+ const getPR = async number => (await rest.pulls.get({...repo, pull_number: number})).data;
+ const direct = context.eventName === 'pull_request';
+ let trigger = context.payload.workflow_run;
+ if (direct) {
+ if (context.payload.pull_request.head.repo?.id !== repoId) return;
+ trigger = (await rest.actions.getWorkflowRun({...repo, run_id: context.runId})).data;
+ }
+ if (trigger && (trigger.path !== path || trigger.event !== 'pull_request' || !trigger.head_repository)) return;
+
+ let candidates;
+ if (direct || context.eventName === 'pull_request_target') {
+ candidates = [context.payload.pull_request];
+ } else if (trigger?.pull_requests?.length) {
+ candidates = trigger.pull_requests;
+ } else if (trigger) {
+ // Fork workflow_run payloads can omit pull_requests. Bind the run to its
+ // GitHub head repository and branch, as well as an already-open PR.
+ candidates = await list(rest.pulls.list, {state: 'open', head: `${trigger.head_repository.owner.login}:${trigger.head_branch}`});
+ candidates = candidates.filter(pr => pr.base.repo.id === repoId &&
+ pr.head.repo?.id === trigger.head_repository.id && pr.head.ref === trigger.head_branch &&
+ pr.created_at <= trigger.created_at);
+ if (candidates.length !== 1) return;
+ } else if (context.eventName === 'schedule') {
+ candidates = await list(rest.pulls.list, {state: 'open'});
+ } else return;
+
+ for (const candidate of candidates) {
+ const pr = await getPR(candidate.number);
+ if (pr.state !== 'open' || pr.base.repo.id !== repoId || !pr.head.repo || !sha.test(pr.head.sha)) continue;
+ if (trigger && (trigger.head_repository.id !== pr.head.repo.id || trigger.head_branch !== pr.head.ref)) continue;
+
+ const comments = await list(rest.issues.listComments, {issue_number: pr.number});
+ const previous = comments.find(c => c.user?.login === 'github-actions[bot]' && c.body?.startsWith(marker));
+ const latestRun = async () => currentRun(await list(rest.actions.listWorkflowRuns, {
+ workflow_id: trigger?.workflow_id || 'build-deb.yml', head_sha: pr.head.sha, event: 'pull_request',
+ }), pr);
+ const run = await latestRun();
+ if (!previous && !run && context.eventName === 'schedule') continue;
+ const directResult = direct && run?.id === context.runId && run.run_attempt === attempt &&
+ context.sha === pr.merge_commit_sha ? buildResult : '';
+ let artifacts = [];
+ let artifactAttempt = null;
+ if (run && (run.conclusion === 'success' || directResult === 'success')) {
+ const [jobs, items] = await Promise.all([
+ list(rest.actions.listJobsForWorkflowRun, {run_id: run.id, filter: 'all'}),
+ list(rest.actions.listWorkflowRunArtifacts, {run_id: run.id}),
+ ]);
+ artifactAttempt = uploadAttempt(run, jobs);
+ artifacts = items;
+ }
+ const availabilityNow = availability(run, artifacts, directResult, pr.merge_commit_sha, Date.now(), artifactAttempt);
+ const body = bodyFor(`${context.serverUrl}/${repo.owner}/${repo.repo}`, pr, run, availabilityNow);
+ // Refresh the PR after the slower artifact/comment listings. All writers
+ // using this workflow share one lock; late events recompute from live data.
+ const [live, fresh] = await Promise.all([getPR(pr.number), latestRun()]);
+ if (fresh?.id !== run?.id || fresh?.run_attempt !== run?.run_attempt ||
+ fresh?.status !== run?.status || fresh?.conclusion !== run?.conclusion) continue;
+ if (live.state !== 'open' || live.head.sha !== pr.head.sha ||
+ live.head.repo?.id !== pr.head.repo.id || live.base.ref !== pr.base.ref ||
+ live.merge_commit_sha !== pr.merge_commit_sha) continue;
+ if (!previous) await rest.issues.createComment({...repo, issue_number: pr.number, body});
+ else if (previous.body !== body && canReplace(previous.body, body)) {
+ await rest.issues.updateComment({...repo, comment_id: previous.id, body});
+ }
+ // The build job writes its own summary. Restore it only on a partial
+ // rerun of this run's publisher, which carries an earlier upload.
+ if (directResult === 'success' && availabilityNow.state === 'ready' && artifactAttempt !== attempt) return body;
+ }
+}
+
+module.exports = {currentRun, availability, bodyFor, canReplace, publish};
diff --git a/.github/ci/package-summary.sh b/.github/ci/package-summary.sh
new file mode 100644
index 0000000..3ceec52
--- /dev/null
+++ b/.github/ci/package-summary.sh
@@ -0,0 +1,11 @@
+#!/bin/bash
+set -euo pipefail
+
+cd "$RUNNER_TEMP/packages"
+digest=$(sha256sum "$PACKAGE" | cut -d' ' -f1)
+test "$digest" = "${ARTIFACT_DIGEST#sha256:}"
+{
+ printf '[Download the .deb](%s) (sign in to GitHub).\n\n' "$PACKAGE_URL"
+ printf 'File: `%s`\n\nSHA-256: `%s`\n\nBuilt revision: `%s`\n\n' "$PACKAGE" "$digest" "$GITHUB_SHA"
+ printf '[Installation and first scan](%s/%s/blob/%s/README.md)\n' "$GITHUB_SERVER_URL" "$GITHUB_REPOSITORY" "$GITHUB_SHA"
+} >> "$GITHUB_STEP_SUMMARY"
diff --git a/.github/tests/package-comment.test.cjs b/.github/tests/package-comment.test.cjs
new file mode 100644
index 0000000..f984bc7
--- /dev/null
+++ b/.github/tests/package-comment.test.cjs
@@ -0,0 +1,248 @@
+'use strict';
+
+const {test} = require('node:test');
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const {currentRun, availability, bodyFor, canReplace, publish} = require('../ci/package-comment.cjs');
+const head = 'a'.repeat(40);
+const merge = 'b'.repeat(40);
+const base = {repo: {id: 20}, ref: 'main'};
+const pr = {number: 5, state: 'open', base, head: {repo: {id: 10}, sha: head, ref: 'branch'},
+ created_at: '2026-01-01', merge_commit_sha: merge};
+const run = {id: 123, run_number: 22, run_attempt: 1, status: 'completed', conclusion: 'success',
+ path: '.github/workflows/build-deb.yml', event: 'pull_request', display_title: `Bookworm ARM64 PR 5 ${merge}`,
+ head_sha: head, head_branch: 'branch', head_repository: {id: 10, owner: {login: 'fork'}},
+ workflow_id: 50, created_at: '2026-05-01', pull_requests: []};
+const artifact = {id: 321, name: `mandeye-multisensor-bookworm-arm64-${merge}-a1.deb`,
+ workflow_run: {id: 123}, expires_at: '2099-01-01T10:00:00Z', digest: 'sha256:' + 'c'.repeat(64), expired: false};
+const repoUrl = 'https://github.com/base/repo';
+function render(r, a, p = pr) {
+ return bodyFor(repoUrl, p, r, a);
+}
+function available(r = run, items = [artifact], direct = '') {
+ return availability(r, items, direct, merge, Date.now(), r?.run_attempt);
+}
+
+test('revisions include both head and current test merge; a historic matrix rerun has no standing', () => {
+ const historical = {...run, display_title: 'old PR title', run_attempt: 99};
+ assert.equal(currentRun([historical, run], pr), run);
+ assert.equal(currentRun([run], {...pr, merge_commit_sha: 'd'.repeat(40)}), undefined);
+ assert.equal(currentRun([run], {...pr, head: {...pr.head, sha: 'e'.repeat(40)}}), undefined);
+ assert.equal(currentRun([{...run, head_repository: {id: 11}}], pr), undefined);
+ assert.equal(currentRun([{...run, pull_requests: [{number: 6, base}]}], pr), undefined);
+});
+
+test('older runs and attempts finishing last cannot supersede the latest incomplete build', () => {
+ const pending = {...run, run_number: 23, run_attempt: 2, status: 'in_progress', conclusion: null};
+ const late = {...run, run_number: 23};
+ assert.equal(currentRun([run, pending, late], pr), pending);
+ const old = render(late, {state: 'ready', digest: 'c'.repeat(64), expiry: 'soon', id: 8});
+ const fresh = render(pending, available(pending));
+ assert.equal(canReplace(fresh, old), false);
+ assert.equal(canReplace(fresh, render({...run, run_attempt: 9}, available())), false);
+ assert.equal(canReplace(old, fresh), true);
+ assert.doesNotMatch(fresh, /\/artifacts\//);
+});
+
+test('a late upload from an older attempt can neither supply nor replace the new raw file', () => {
+ const second = {...run, run_attempt: 2};
+ const fromSecond = {...artifact, id: 333, name: artifact.name.replace('-a1.deb', '-a2.deb')};
+ assert.equal(available(second, [artifact]).state, 'unavailable');
+ assert.equal(available(second, [fromSecond, artifact]).id, 333);
+ assert.equal(available(run, [fromSecond, artifact]).state, 'unavailable');
+});
+
+test('signed-in link, install guide, head, test merge, raw artifact checksum and expiry use platform metadata', () => {
+ const text = render(run, available());
+ for (const token of ['sign in', head, merge, 'c'.repeat(64), '2099-01-01T10:00:00.000Z',
+ `${repoUrl}/actions/runs/123/artifacts/321`, `${repoUrl}/blob/${merge}/README.md`]) assert.ok(text.includes(token));
+ assert.ok(text.startsWith(''));
+});
+
+test('failure, cancellation, expired, deleted, contradictory and malformed artifact states contain no download', () => {
+ const cases = [
+ [available({...run, conclusion: 'failure'}), 'failed'],
+ [available({...run, conclusion: 'cancelled'}), 'cancelled'],
+ [available(run, [{...artifact, expired: true}]), 'expired'],
+ [available(run, [{...artifact, expires_at: '2000-01-01T00:00:00Z'}]), 'expired'],
+ [available(run, []), 'unavailable'],
+ [available(run, [artifact, artifact]), 'unavailable'],
+ [available(run, [{...artifact, workflow_run: {id: 456}}]), 'unavailable'],
+ [available(run, [{...artifact, digest: '[click](evil)'}]), 'unavailable'],
+ ];
+ for (const [result, wanted] of cases) {
+ assert.equal(result.state, wanted);
+ assert.doesNotMatch(render(run, result), /\/artifacts\//);
+ }
+ assert.equal(canReplace(render(run, available()), render(run, {state: 'building'})), false);
+ assert.equal(canReplace(render(run, available()), render(run, {state: 'expired'})), true);
+});
+
+function job(attempt, name = 'Build and test .deb', conclusion = 'success') {
+ return {run_id: run.id, run_attempt: attempt, name, head_sha: head, status: 'completed', conclusion};
+}
+
+function mockGitHub({p = pr, runs = [run], artifacts = [artifact], comments = [], candidates = [p], live = p,
+ jobs = [job(1)], refreshedRuns = runs}) {
+ const published = [];
+ let reads = 0;
+ const pulls = {get: async () => ({data: ++reads === 1 ? p : live}), list: () => candidates};
+ let runListings = 0;
+ const actions = {getWorkflowRun: async () => ({data: run}), listWorkflowRuns: () => ++runListings === 1 ? runs : refreshedRuns,
+ listJobsForWorkflowRun: options => runs.some(r => r.id === options.run_id) && options.filter === 'all' ? jobs : [],
+ listWorkflowRunArtifacts: () => artifacts};
+ const issues = {listComments: () => comments, createComment: async c => published.push(c),
+ updateComment: async c => published.push(c)};
+ return {published, github: {rest: {pulls, actions, issues}, paginate: async (method, opts) => method(opts)}};
+}
+const event = {repo: {owner: 'base', repo: 'repo'}, eventName: 'workflow_run',
+ serverUrl: 'https://github.com', payload: {repository: {id: 20}, workflow_run: run}};
+
+test('fork with missing PR number uses unique GitHub association; never executes its artifacts or injected labels', async () => {
+ const {github, published} = mockGitHub({artifacts: [artifact, {...artifact, name: '
'}]});
+ await publish(github, event, '', 1);
+ assert.equal(published.length, 1);
+ assert.doesNotMatch(published[0].body, /evil/);
+ const ambiguous = mockGitHub({candidates: [pr, {...pr, number: 7}]});
+ await publish(ambiguous.github, event, '', 1);
+ assert.deepEqual(ambiguous.published, []);
+ const moved = mockGitHub({live: {...pr, merge_commit_sha: 'd'.repeat(40)}});
+ await publish(moved.github, event, '', 1);
+ assert.deepEqual(moved.published, []);
+});
+
+test('a late successful event refreshes the latest failure; user comments cannot supply a trusted marker', async () => {
+ const {github, published} = mockGitHub({runs: [run, {...run, id: 222, run_number: 23, conclusion: 'failure'}],
+ comments: [{id: 44, user: {login: 'fork'}, body: render(run, available())}]});
+ await publish(github, event, '', 1);
+ assert.equal(published[0].issue_number, 5);
+ assert.match(published[0].body, /Build failed/);
+ assert.doesNotMatch(published[0].body, /artifacts\/321/);
+});
+
+test('new PR SHA, new merge or unavailable SHA retire the old link and keep the original bot comment', async () => {
+ for (const p of [{...pr, head: {...pr.head, sha: 'e'.repeat(40)}},
+ {...pr, merge_commit_sha: 'f'.repeat(40)}, {...pr, merge_commit_sha: null}]) {
+ const {github, published} = mockGitHub({p, comments: [{id: 77, user: {login: 'github-actions[bot]'},
+ body: render(run, available())}]});
+ await publish(github, event, '', 1);
+ assert.equal(published[0].comment_id, 77);
+ assert.match(published[0].body, /Waiting for a build/);
+ assert.doesNotMatch(published[0].body, /\/artifacts\//);
+ }
+});
+
+test('same-repo finalizer cannot apply an obsolete attempt result; a fresh success can publish before workflow completion', async () => {
+ const p = {...pr, head: {...pr.head, repo: base.repo}};
+ const pending = {...run, run_attempt: 2, status: 'in_progress', conclusion: null, head_repository: base.repo};
+ const direct = {...event, eventName: 'pull_request', runId: run.id, sha: merge,
+ payload: {repository: base.repo, pull_request: p}};
+ for (const [attempt, expected] of [[1, /Building and testing/], [2, /Download the .deb/]]) {
+ const a2 = {...artifact, id: 322, name: artifact.name.replace('-a1.deb', '-a2.deb')};
+ const {github, published} = mockGitHub({p, runs: [pending], jobs: [job(2)], artifacts: [a2, artifact]});
+ github.rest.actions.getWorkflowRun = async () => ({data: pending});
+ await publish(github, direct, 'success', attempt);
+ assert.match(published[0].body, expected);
+ }
+});
+
+test('build runs do not cancel each other, and reruns replace the actual raw artifact filename after tests', () => {
+ const yml = fs.readFileSync(require.resolve('../workflows/build-deb.yml'), 'utf8');
+ assert.doesNotMatch(yml, /cancel-in-progress|concurrency:/);
+ assert.match(yml, /name: \$\{\{ env.PACKAGE \}\}\s+path: .*\$\{\{ env.PACKAGE \}\}\s+archive: false\s+overwrite: true/);
+ assert.ok(yml.indexOf('bash tests/package/boot-test.sh') < yml.indexOf('actions/upload-artifact@'));
+ assert.ok(yml.indexOf('bash .github/ci/installed-scan.sh') < yml.indexOf('actions/upload-artifact@'));
+});
+
+test('a publisher-only rerun carries the package from the last successful build job', async () => {
+ const third = {...run, run_attempt: 3};
+ const artifact2 = {...artifact, id: 333, name: artifact.name.replace('-a1.deb', '-a2.deb')};
+ const jobs = [job(1), job(2), job(3, 'result / comment')];
+ const fixture = mockGitHub({runs: [third], artifacts: [artifact2, artifact], jobs});
+ await publish(fixture.github, event, '', 1);
+ assert.match(fixture.published[0].body, /artifacts\/333/);
+ assert.match(fixture.published[0].body, /-a2\.deb/);
+ assert.match(fixture.published[0].body, /Build 22, attempt 3/);
+
+ for (const artifacts of [[artifact], [{...artifact2, expired: true}], [{...artifact2, workflow_run: {id: 456}}]]) {
+ const invalid = mockGitHub({runs: [third], artifacts, jobs});
+ await publish(invalid.github, event, '', 1);
+ assert.doesNotMatch(invalid.published[0].body, /\/artifacts\//);
+ }
+});
+
+test('a failed, ambiguous or concurrent uploader prevents reuse of an earlier success', async () => {
+ const second = {...run, run_attempt: 2};
+ for (const jobs of [[job(1), job(2, 'Build and test .deb', 'failure'), job(2, 'result / comment')],
+ [job(1), job(1), job(2, 'result / comment')], [job(1), job(2, 'result / comment'), job(3)],
+ [job(1)], [{...job(1), run_id: 999}, job(2, 'result / comment')],
+ [{...job(1), head_sha: 'f'.repeat(40)}, job(2, 'result / comment')]]) {
+ const fixture = mockGitHub({runs: [second], jobs});
+ await publish(fixture.github, event, '', 1);
+ assert.doesNotMatch(fixture.published[0].body, /\/artifacts\//);
+ }
+});
+
+test('GitHub copies completed jobs to a publisher retry with new IDs and the original execution times', async () => {
+ const third = {...run, run_attempt: 3};
+ const second = {...job(2), id: 202, runner_id: 17,
+ started_at: '2026-12-04T12:39:19Z', completed_at: '2026-12-04T13:00:19Z'};
+ const copy = {...second, id: 303, run_attempt: 3};
+ const files = [{...artifact, name: artifact.name.replace('-a1.deb', '-a2.deb')}];
+ const retry = updated => mockGitHub({runs: [third], artifacts: files,
+ jobs: [job(1), second, job(2, 'result / comment'), job(3, 'building / comment'), updated, job(3, 'result / comment')]});
+ const carried = retry(copy);
+ await publish(carried.github, event, '', 1);
+ assert.match(carried.published[0].body, /-a2\.deb/);
+ for (const change of [{runner_id: 19}, {completed_at: '2026-12-04T13:15:05Z'}, {started_at: null}]) {
+ const different = retry({...copy, ...change});
+ await publish(different.github, event, '', 1);
+ assert.doesNotMatch(different.published[0].body, /\/artifacts\//);
+ }
+});
+
+test('a new run or attempt starting during discovery cannot publish the older download', async () => {
+ for (const fresh of [{...run, run_attempt: 2}, {...run, id: 777, run_number: 23}]) {
+ const fixture = mockGitHub({refreshedRuns: [{...fresh, status: 'in_progress', conclusion: null}, run]});
+ await publish(fixture.github, event, '', 1);
+ assert.ok(fixture.published.every(comment => !comment.body.includes('/artifacts/')));
+ }
+});
+
+test('default-branch PR synchronization invalidates an obsolete fork link before a new build is available', async () => {
+ const p = {...pr, head: {...pr.head, sha: 'e'.repeat(40)}};
+ const fixture = mockGitHub({p, comments: [{id: 77, user: {login: 'github-actions[bot]'}, body: render(run, available())}]});
+ await publish(fixture.github, {...event, eventName: 'pull_request_target',
+ payload: {repository: base.repo, pull_request: p}}, '', 1);
+ assert.equal(fixture.published.length, 1);
+ assert.match(fixture.published[0].body, /Waiting for a build/);
+ assert.doesNotMatch(fixture.published[0].body, /\/artifacts\//);
+});
+
+test('a newly opened fork PR shows availability while its first build awaits approval', async () => {
+ const fixture = mockGitHub({runs: []});
+ await publish(fixture.github, {...event, eventName: 'pull_request_target',
+ payload: {repository: base.repo, pull_request: pr}}, '', 1);
+ assert.equal(fixture.published.length, 1);
+ assert.match(fixture.published[0].body, /Waiting for a build/);
+ assert.doesNotMatch(fixture.published[0].body, /\/artifacts\//);
+});
+
+test('only a publisher-only rerun adds the carried package to the summary of its own attempt', async () => {
+ const p = {...pr, head: {...pr.head, repo: base.repo}};
+ const current = {...run, head_repository: base.repo, run_attempt: 2};
+ const direct = {...event, eventName: 'pull_request', runId: run.id, sha: merge,
+ payload: {repository: base.repo, pull_request: p}};
+ const check = async (runs, jobs, files, trigger) => {
+ const {github} = mockGitHub({p, runs, jobs, artifacts: files});
+ github.rest.actions.getWorkflowRun = async () => ({data: trigger});
+ return publish(github, direct, 'success', 2);
+ };
+ const partial = await check([current], [job(1), job(2, 'result / comment')], [artifact], current);
+ assert.match(partial, /artifacts\/321/);
+ const a2 = {...artifact, name: artifact.name.replace('-a1.deb', '-a2.deb')};
+ assert.equal(await check([current], [job(2)], [a2], current), undefined);
+ const latest = {...current, id: 456, run_number: 23};
+ assert.equal(await check([latest], [{...job(2), run_id: 456}],
+ [{...a2, workflow_run: {id: 456}}], current), undefined);
+});
diff --git a/.github/tests/package-summary.test.cjs b/.github/tests/package-summary.test.cjs
new file mode 100644
index 0000000..36b79b4
--- /dev/null
+++ b/.github/tests/package-summary.test.cjs
@@ -0,0 +1,33 @@
+'use strict';
+
+const {test} = require('node:test');
+const assert = require('node:assert/strict');
+const {spawnSync} = require('node:child_process');
+const crypto = require('node:crypto');
+const fs = require('node:fs');
+const os = require('node:os');
+const path = require('node:path');
+
+test('the run summary verifies the raw bytes and links the packaged revision in the publishing repository', t => {
+ const temp = fs.mkdtempSync(path.join(os.tmpdir(), 'mandeye-summary-'));
+ t.after(() => fs.rmSync(temp, {recursive: true, force: true}));
+ const revision = 'a'.repeat(40);
+ const filename = `mandeye-multisensor-bookworm-arm64-${revision}-a2.deb`;
+ const digest = crypto.createHash('sha256').update('raw-deb').digest('hex');
+ fs.mkdirSync(path.join(temp, 'packages'));
+ fs.writeFileSync(path.join(temp, 'packages', filename), 'raw-deb');
+ const summary = path.join(temp, 'summary');
+ const env = {...process.env, RUNNER_TEMP: temp, PACKAGE: filename, GITHUB_STEP_SUMMARY: summary,
+ GITHUB_SHA: revision, GITHUB_SERVER_URL: 'https://github.com', GITHUB_REPOSITORY: 'operator/controller',
+ PACKAGE_URL: 'https://github.com/operator/controller/actions/runs/99/artifacts/23', ARTIFACT_DIGEST: digest};
+ const verify = () => spawnSync('bash', ['.github/ci/package-summary.sh'], {env, encoding: 'utf8'});
+ const valid = verify();
+ assert.equal(valid.status, 0, valid.stderr);
+ const text = fs.readFileSync(summary, 'utf8');
+ for (const token of [filename, digest, env.PACKAGE_URL, `\`${revision}\``,
+ `https://github.com/operator/controller/blob/${revision}/README.md`]) assert.ok(text.includes(token), token);
+ fs.writeFileSync(summary, '');
+ env.ARTIFACT_DIGEST = 'f'.repeat(64);
+ assert.notEqual(verify().status, 0);
+ assert.equal(fs.readFileSync(summary, 'utf8'), '');
+});
diff --git a/.github/workflows/build-deb.yml b/.github/workflows/build-deb.yml
new file mode 100644
index 0000000..ade0ced
--- /dev/null
+++ b/.github/workflows/build-deb.yml
@@ -0,0 +1,125 @@
+name: Test packages (Bookworm ARM64)
+run-name: Bookworm ARM64 PR ${{ github.event.pull_request.number || 0 }} ${{ (github.event.action != 'edited' || github.event.changes.base != null) && github.sha || 'skipped-edit' }}
+
+on:
+ pull_request:
+ types: [opened, synchronize, reopened, edited]
+ workflow_dispatch:
+
+permissions:
+ contents: read
+
+# Keep each run independent. Re-running an older revision (including a matrix
+# build from the previous workflow) must never cancel a newer revision.
+jobs:
+ building:
+ if: >-
+ github.event_name == 'pull_request' &&
+ github.event.pull_request.head.repo.id == github.event.repository.id &&
+ (github.event.action != 'edited' || github.event.changes.base != null)
+ permissions:
+ contents: read
+ actions: read
+ pull-requests: write
+ uses: ./.github/workflows/comment-deb.yml
+
+ build:
+ # On a same-repo PR clear the old link before allowing a new upload.
+ # Fork/manual builds skip the writer and still produce a signed-in download.
+ needs: building
+ name: Build and test .deb
+ if: >-
+ !cancelled() &&
+ (needs.building.result == 'success' || needs.building.result == 'skipped') &&
+ (github.event.action != 'edited' || github.event.changes.base != null)
+ runs-on: ubuntu-24.04-arm
+ permissions:
+ contents: read
+ actions: read
+ env:
+ PACKAGE: mandeye-multisensor-bookworm-arm64-${{ github.sha }}-a${{ github.run_attempt }}.deb
+ LEGACY_SHA: e1b5bd69ec38a4c05ca5a6110ae87803709ea2c4
+ steps:
+ - uses: actions/checkout@v6
+ with:
+ submodules: recursive
+ persist-credentials: false
+
+ - name: Test package publication, storage and activation
+ run: |
+ node --test .github/tests/*.test.cjs
+ python3 tests/package/test-storage.py
+ python3 tests/package/test-activation.py
+
+ # Fixed historical migration fixture. The field package itself always
+ # builds from this repository's checkout and event revision.
+ - name: Get the previous Pro CM4 package
+ id: legacy
+ env:
+ GH_TOKEN: ${{ github.token }}
+ run: |
+ mkdir -p "$RUNNER_TEMP/packages"
+ cd "$RUNNER_TEMP/packages"
+ if gh api repos/dlubom/mandeye_controller/actions/artifacts/15634455618/zip > legacy.deb &&
+ echo '4e87aa6468852a163a521945c0d10fba3f19a7352fe5d64f6ac8619e0cfe3d2c legacy.deb' | sha256sum --check; then
+ echo 'rebuild=false' >> "$GITHUB_OUTPUT"
+ else
+ rm -f legacy.deb
+ echo 'rebuild=true' >> "$GITHUB_OUTPUT"
+ fi
+
+ - name: Check out the exact legacy sources when the old artifact is unavailable
+ if: steps.legacy.outputs.rebuild == 'true'
+ uses: actions/checkout@v6
+ with:
+ repository: dlubom/mandeye_controller
+ ref: ${{ env.LEGACY_SHA }}
+ path: legacy
+ submodules: recursive
+ persist-credentials: false
+
+ - name: Build on Raspberry Pi OS Bookworm ARM64 libraries
+ run: |
+ docker run --rm -v "$GITHUB_WORKSPACE:/src" -w /src -v "$RUNNER_TEMP/packages:/packages" \
+ -e PACKAGE -e GITHUB_SHA -e GITHUB_RUN_ID -e GITHUB_RUN_ATTEMPT -e LEGACY_SHA \
+ debian:bookworm bash .github/ci/build-deb.sh
+
+ - name: Test installed scanner on clean Bookworm
+ run: |
+ docker run --rm -v "$GITHUB_WORKSPACE:/src:ro" -w /src -v "$RUNNER_TEMP/packages:/packages:ro" \
+ -e PACKAGE -e GITHUB_SHA debian:bookworm bash .github/ci/installed-scan.sh
+
+ - name: Test fresh installation and real dpkg migration
+ run: |
+ bash tests/package/boot-test.sh "$RUNNER_TEMP/packages/$PACKAGE" "$RUNNER_TEMP/packages/legacy.deb"
+
+ - name: Upload the tested package
+ id: upload
+ uses: actions/upload-artifact@v7
+ with:
+ name: ${{ env.PACKAGE }}
+ path: ${{ runner.temp }}/packages/${{ env.PACKAGE }}
+ archive: false
+ overwrite: true
+ retention-days: 14
+ if-no-files-found: error
+
+ - name: Verify the raw artifact digest
+ env:
+ ARTIFACT_DIGEST: ${{ steps.upload.outputs.artifact-digest }}
+ PACKAGE_URL: ${{ steps.upload.outputs.artifact-url }}
+ run: bash .github/ci/package-summary.sh
+
+ result:
+ needs: [building, build]
+ if: >-
+ always() && github.event_name == 'pull_request' &&
+ github.event.pull_request.head.repo.id == github.event.repository.id &&
+ (github.event.action != 'edited' || github.event.changes.base != null)
+ permissions:
+ contents: read
+ actions: read
+ pull-requests: write
+ uses: ./.github/workflows/comment-deb.yml
+ with:
+ build_result: ${{ needs.building.result == 'cancelled' && 'cancelled' || needs.building.result == 'failure' && 'failure' || needs.build.result }}
diff --git a/.github/workflows/comment-deb.yml b/.github/workflows/comment-deb.yml
new file mode 100644
index 0000000..6fd92f5
--- /dev/null
+++ b/.github/workflows/comment-deb.yml
@@ -0,0 +1,55 @@
+name: Update the ARM64 package comment
+
+on:
+ workflow_call:
+ inputs:
+ build_result:
+ type: string
+ default: ''
+ pull_request_target:
+ types: [opened, synchronize, reopened, edited]
+ workflow_run:
+ workflows: ["Test packages (Bookworm ARM64)"]
+ types: [requested, in_progress, completed]
+ schedule:
+ - cron: '37 * * * *'
+
+permissions: {}
+
+jobs:
+ comment:
+ if: >-
+ github.event_name == 'schedule' ||
+ (github.event_name == 'pull_request_target' &&
+ (github.event.action != 'edited' || github.event.changes.base != null)) ||
+ (github.event_name == 'pull_request' &&
+ github.event.pull_request.head.repo.id == github.event.repository.id) ||
+ (github.event_name == 'workflow_run' &&
+ github.event.workflow_run.path == '.github/workflows/build-deb.yml' &&
+ github.event.workflow_run.event == 'pull_request')
+ runs-on: ubuntu-latest
+ permissions:
+ contents: read
+ actions: read
+ pull-requests: write
+ concurrency:
+ group: field-deb-comment-writer
+ queue: max
+ steps:
+ # workflow_run, schedule and pull_request_target use the base repository.
+ # Never check out a fork head/merge in this publisher. The reusable
+ # pull_request path above accepts only same-repository PRs.
+ - uses: actions/checkout@v6
+ with:
+ ref: ${{ github.sha }}
+ persist-credentials: false
+ sparse-checkout: .github/ci
+ - uses: actions/github-script@v9
+ env:
+ BUILD_RESULT: ${{ inputs.build_result }}
+ ATTEMPT: ${{ github.run_attempt }}
+ with:
+ script: |
+ const { publish } = require('./.github/ci/package-comment.cjs');
+ const summary = await publish(github, context, process.env.BUILD_RESULT, Number(process.env.ATTEMPT));
+ if (summary) await core.summary.addRaw(summary).write();
diff --git a/.github/workflows/sanity-build.yml b/.github/workflows/sanity-build.yml
index dc9f07b..a2e0e50 100644
--- a/.github/workflows/sanity-build.yml
+++ b/.github/workflows/sanity-build.yml
@@ -7,7 +7,7 @@ on:
jobs:
sanity-build:
- name: Sanity Build (${{ matrix.compiler.name }}, ${{ matrix.profile.name }})
+ name: Sanity Build (${{ matrix.compiler.name }})
runs-on: ubuntu-latest
permissions:
contents: read
@@ -19,13 +19,10 @@ jobs:
compiler:
- { name: gcc, cc: gcc, cxx: g++ }
- { name: clang, cc: clang, cxx: clang++ }
- profile:
- - { name: rpi5, header: mandeye-standard-rpi5.h, libcamera: 'OFF' }
- - { name: cm5, header: mandeye-direct-cm5.h, libcamera: 'OFF' }
env:
CC: ${{ matrix.compiler.cc }}
CXX: ${{ matrix.compiler.cxx }}
- BUILD_DIR: build-${{ matrix.compiler.name }}-${{ matrix.profile.name }}
+ BUILD_DIR: build-${{ matrix.compiler.name }}
steps:
- name: Install dependencies
@@ -46,14 +43,13 @@ jobs:
submodules: true
- name: Configure
- env:
- HARDWARE_HEADER: ${{ matrix.profile.header }}
- USE_LIBCAMERA: ${{ matrix.profile.libcamera }}
run: |
cmake -B "$BUILD_DIR" -DCMAKE_BUILD_TYPE=Release \
- -DMANDEYE_HARDWARE_HEADER="$HARDWARE_HEADER" \
- -DMANDEYE_USE_LIBCAMERA="$USE_LIBCAMERA" \
+ -DMANDEYE_USE_LIBCAMERA=OFF \
-DMANDEYE_STRICT_BUILD=ON -DCMAKE_EXPORT_COMPILE_COMMANDS=ON
- name: Build
run: cmake --build "$BUILD_DIR" --parallel "$(nproc)"
+
+ - name: Test
+ run: ctest --test-dir "$BUILD_DIR" --output-on-failure
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 7c7e305..5bd281a 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -3,10 +3,7 @@ set(CMAKE_CXX_STANDARD 17)
project (mandeye_multisensor)
-set(MANDEYE_HARDWARE_HEADER CACHE STRING "Mandeye hardware setting. Choose one header from 'code/hardware/mandeye-*.h")
-#add_compile_definitions(MANDEYE_HARDWARE_HEADER="${MANDEYE_HARDWARE_HEADER}")
-message(STATUS "Mandeye hardware version is : ${MANDEYE_HARDWARE_HEADER}")
-set (MANDEYE_VERSION "0.82")
+set (MANDEYE_VERSION "0.83")
message(STATUS "Mandeye version is : ${MANDEYE_VERSION}")
set(SYSTEM_ARCH "${CMAKE_SYSTEM_PROCESSOR}")
@@ -67,7 +64,7 @@ endif()
# get git info
execute_process(
- COMMAND git rev-parse --short HEAD
+ COMMAND git rev-parse HEAD
WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}
OUTPUT_VARIABLE GIT_HASH
OUTPUT_STRIP_TRAILING_WHITESPACE
@@ -157,6 +154,8 @@ if (${MANDEYE_USE_HESAI_SDK2})
add_compile_definitions(MANDEYE_USE_HESAI_SDK2)
endif()
+add_library(mandeye_device_config STATIC code/hardware_config/device_config.cpp)
+
add_executable(control_program code/main.cpp code/gnss.cpp code/web_page.h
${LIDAR_SOURCES}
${LIDAR_SOURCES}
@@ -166,7 +165,7 @@ add_executable(control_program code/main.cpp code/gnss.cpp code/web_page.h
set(CMAKE_CXX_LINK_FLAGS "${CMAKE_CXX_LINK_FLAGS} -latomic " )
-target_link_libraries(control_program pthread ${LIDAR_LIBRARIES} pistache atomic laszip ${LIBSERIAL_LIBRARY} minea gpiod zmq)
+target_link_libraries(control_program mandeye_device_config pthread ${LIDAR_LIBRARIES} pistache atomic laszip ${LIBSERIAL_LIBRARY} minea gpiod zmq)
if(MANDEYE_USE_TRACY)
target_link_libraries(control_program TracyClient)
@@ -174,18 +173,18 @@ if(MANDEYE_USE_TRACY)
endif()
set_target_properties(control_program PROPERTIES
- INSTALL_RPATH "/opt/mandeye/lib"
+ INSTALL_RPATH "/opt/mandeye;/opt/mandeye/lib"
BUILD_WITH_INSTALL_RPATH TRUE
)
add_executable(led_demo code/led_demo.cpp code/gpios.cpp)
set(CMAKE_CXX_LINK_FLAGS "${CMAKE_CXX_LINK_FLAGS}")
-target_link_libraries(led_demo gpiod pthread)
+target_link_libraries(led_demo mandeye_device_config gpiod pthread)
add_executable(button_demo code/button_demo.cpp code/gpios.cpp)
set(CMAKE_CXX_LINK_FLAGS "${CMAKE_CXX_LINK_FLAGS}")
-target_link_libraries(button_demo gpiod pthread)
+target_link_libraries(button_demo mandeye_device_config gpiod pthread)
# Define install directories
install(TARGETS control_program led_demo button_demo
@@ -239,6 +238,14 @@ if(MANDEYE_STRICT_BUILD)
endforeach()
endif()
+install(PROGRAMS packing/mandeye-activate DESTINATION /usr/sbin)
+install(PROGRAMS packing/vendor-selected packing/mandeye-storage DESTINATION /usr/lib/mandeye)
+install(PROGRAMS packing/mandeye-storage-generator DESTINATION /usr/lib/systemd/system-generators)
+install(FILES extras/picamera2/camera.py DESTINATION /opt/mandeye/extras/picamera2)
+install(FILES extras/picamera2/services/mandeye_picamera.service DESTINATION /usr/lib/systemd/system)
+install(FILES packing/services/10-mandeye-selection.conf packing/services/20-mandeye-storage.conf
+ DESTINATION /usr/lib/systemd/system/mandeye_controller.service.d)
+install(DIRECTORY packing/examples/ DESTINATION /usr/share/mandeye/examples FILES_MATCHING PATTERN "*.json")
install(FILES packing/helpers.sh DESTINATION /opt/mandeye/)
install(FILES packing/services/mandeye_controller.service DESTINATION /usr/lib/systemd/system)
@@ -249,8 +256,16 @@ install(FILES packing/check_services.sh DESTINATION /opt/mandeye/)
# Packaging
set(CPACK_GENERATOR "DEB")
set(CPACK_PACKAGE_NAME "mandeye-multisensor")
-set(CPACK_PACKAGE_VERSION "${MANDEYE_VERSION}-${GIT_HASH}-${MANDEYE_HARDWARE_HEADER}-${SYSTEM_ARCH}")
+execute_process(COMMAND git show -s --format=%ct HEAD WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}
+ OUTPUT_VARIABLE COMMIT_TIME OUTPUT_STRIP_TRAILING_WHITESPACE)
+string(SUBSTRING "${GIT_HASH}" 0 12 PACKAGE_HASH)
+set(CPACK_PACKAGE_VERSION "${MANDEYE_VERSION}+git${COMMIT_TIME}.${PACKAGE_HASH}")
set(CPACK_PACKAGE_CONTACT "Michał Pełka ")
-set(CPACK_DEBIAN_PACKAGE_DEPENDS "rapidjson-dev,libserial-dev, libgpiod-dev, libzmq3-dev")
-set(CPACK_DEBIAN_PACKAGE_CONTROL_EXTRA "${CMAKE_CURRENT_SOURCE_DIR}/packing/postinst/postinst")
+set(CPACK_DEBIAN_PACKAGE_SHLIBDEPS ON)
+set(CPACK_DEBIAN_PACKAGE_DEPENDS "systemd, dbus | dbus-system-bus, python3, util-linux")
+set(CPACK_DEBIAN_PACKAGE_RECOMMENDS "linuxptp")
+set(CPACK_DEBIAN_PACKAGE_CONTROL_EXTRA
+ "${CMAKE_CURRENT_SOURCE_DIR}/packing/postinst/preinst"
+ "${CMAKE_CURRENT_SOURCE_DIR}/packing/postinst/postinst"
+ "${CMAKE_CURRENT_SOURCE_DIR}/packing/postinst/postrm")
include(CPack)
diff --git a/README.md b/README.md
index 9a57dd2..0d6fa3b 100644
--- a/README.md
+++ b/README.md
@@ -1,312 +1,153 @@
-# mandeye_controller
+# Mandeye controller
-This is an open-hardware hand-held scanner, capable of collecting data for [HDMapping](https://github.com/MapsHD/HDMapping).
+Mandeye is an open-hardware handheld scanner for [HDMapping](https://github.com/MapsHD/HDMapping). One Debian package runs on Raspberry Pi 4, Pi 5, Pro CM4 Bookworm and CM5 Direct. Each scanner keeps its own wiring in `/etc/mandeye/device.json`.
-# Hardware documementation
+- [I am installing on a new Raspberry Pi](#install-on-a-new-raspberry-pi)
+- [I am updating a working scanner](#update-a-working-scanner)
-## Supported hardware
-We support the following hardware:
-- Raspbery Pi 4 or 5 without any special hardware (bunch of of-the-shelf components and 3D printed parts)
-- Raspbery Pi 4 Compute module with custom carrier board. The carrier board is not part of this repository and is available on request.
+## Download and verify the field package
-Both version shares the same software, but are different in hardware (e.g. different GPIO layout, some extra features on custom carrier board).
-The target hardware is defined during compilation time.
-If you want to extend this project to different platforms or hardware, please refer to source code available in [hardware](./code) directory.
+Use **64-bit Raspberry Pi OS Bookworm**. On the Pi, `dpkg --print-architecture` should print `arm64` and `/etc/os-release` should contain `VERSION_CODENAME=bookworm`.
+Get the **.deb**, its **SHA-256** and the **source revision** from the same build.
-## 3D Model
+- For a pull request, use the package comment in **that pull request**. It links the current download and the installation guide for that revision.
+- For a manual build, open **Actions → Test packages (Bookworm ARM64)** in the repository that produced it. Select the successful run for your branch or tag and open its summary. The summary links the tested file and the matching guide.
+- When a maintainer distributes a release, use the package and checksum supplied with that release.
-The source design is available on Onshape, and you can access it [here](https://cad.onshape.com/documents/a6c6019ccb399ad39d830fad/w/0440af658555626c8fea1136/e/e1bf637894052d9247ac984d?renderMode=0&uiState=651c527c78128a19b84b4be1).
+Sign in to GitHub for Actions downloads. If an artifact has expired, use the new filename and checksum from a successful rebuild. For several scanners, use the same file on each. Keep the published revision and checksum with your installation notes.
-The design files for 3D printing are available in the repository's 3mf directory. You can find the file [ScannerAssembly.3mf](./3mf/ScannerAssembly.3mf) containing the models to be printed.
+On the Pi, open a shell in the download directory and paste the **exact filename** and **SHA-256** from the build. Continue in this shell only if verification prints `OK`.
-For optimal results, we recommend printing the assembly with PLA. Don't forget to adjust the 3MF file according to your printer specifications. If you need assistance with this, consider including a brief guide or tips on printer adjustments.
-
-
-
-Additionally, we recommend printing a protective cap for Livox Mid-360, which you can find in the [LivoxCap.3mf](./3mf/LivoxCap.3mf) file.
-
-
-
-Feel free to reach out if you have any questions or need further assistance!
-
-## Bill of Materials
-[Click here to BIM](doc/BIM.md)
-
-## Wiring
-
-[Wiring manual](doc/wiring/wiring.md)
-
-
-## Video guide
-Time-lapse video guide to build and configure the system.
-
-[Youtube video](https://youtu.be/BXBbuSJMFEo)
-
-> Note: the video will get outdated eventually, please refer to the manual.
-
-# Software
-
-# Important notes
-Currently, Raspbian Bookworm is recommended for the system. The system is tested on Raspbian Bookworm.
-The version v0.5 supported Bullseye, the current main branch supports Bookworm.
-The software can run other distros (e.g. Ubuntu), but it is not tested and maintained.
-
-## Update system
```bash
-sudo apt-get update
-sudo apt-get upgrade
-sudo apt-get install build-essential cmake git rapidjson-dev debhelper build-essential ntfs-3g libserial-dev libgpiod-dev libzmq3-dev libpistache-dev libcamera-dev linuxptp debhelper libopencv-dev pps-tools ppsh nlohmann-json3-dev
+read -r -p 'Downloaded .deb filename: ' package
+read -r -p 'Published SHA-256: ' sha256
+printf '%s %s\n' "$sha256" "./$package" | sha256sum --check
+dpkg-deb -f "./$package" Package Version Architecture
```
-## Static IP for eth0
+The package identifies itself as `mandeye-multisensor`, architecture `arm64`. Record its Debian version as well as the checksum. After installation, compare it with `dpkg-query -W mandeye-multisensor`.
-```bash
-sudo nano /etc/dhcpcd.conf
-```
-And add in the end:
-```
-interface eth0
-static ip_address=192.168.1.5/24
-static routers=0.0.0.0
-```
+## Install on a new Raspberry Pi
-### Systems with network manager [Raspbian Bookwork]
+1. Log in using the existing account that will operate the scanner. Install the verified file. The controller waits for configuration.
-```bash
-sudo nmcli connection add type ethernet ifname eth0 con-name static-eth0 \
- ipv4.addresses 192.168.1.5/24 \
- ipv4.gateway 0.0.0.0 \
- ipv4.method manual
-```
+ ```bash
+ sudo apt update
+ sudo apt install "./$package"
+ ```
-verify with :
-```bash
-nmcli device show eth0
-```
+2. Connect the Pi and the Livox head(s) on their dedicated Ethernet network. The controller's default listening address is `192.168.1.5`. For a new NetworkManager profile on that interface, run the commands below from a local console or over Wi-Fi. On an existing scanner, inspect the current profile first.
-eventually you can use
-```bash
-nmtui
-```
-## Clone and build app
+ ```bash
+ nmcli connection show --active
+ sudo nmcli connection add type ethernet ifname eth0 con-name mandeye-livox \
+ ipv4.method manual ipv4.addresses 192.168.1.5/24 ipv4.never-default yes
+ sudo nmcli connection up mandeye-livox
+ ip -4 address show dev eth0
+ ```
-Note that, target hardware is defined during compilation time using `-MANDEYE_HARDWARE_HEADER=mandeye-standard-rpi4.h` parameter.
-The `MANDEYE_HARDWARE_HEADER` is one of the headers in `code/hardware_config`:
-```bash
-$ ls ./code/hardware_config/mandeye-*.h
-./code/hardware_config/mandeye-pro-cm4-bookworm.h
-./code/hardware_config/mandeye-pro-cm4-bullseye.h
-./code/hardware_config/mandeye-standard-rpi4.h
-./code/hardware_config/mandeye-standard-rpi5.h
-...
-```
+3. Prepare the recording drive. Use `lsblk -o NAME,TRAN,FSTYPE,UUID,MOUNTPOINTS` to identify the USB partition. Configure a persistent mount at `/media/usb`, or keep the scanner's existing mount and `MANDEYE_REPO`. For example, for an existing **exFAT** partition, create the mount point with `sudo install -d /media/usb`, then use `sudoedit /etc/fstab` to add the following line. Replace the three placeholders with the actual USB UUID, `id -u` and `id -g` of the service account.
-| Hardware header | What is supported |
-|----------------------------|--------------------------------------------------|
-| mandeye-standard-rpi4.h | Raspberry Pi 4 |
-| mandeye-standard-rpi5.h | Raspberry Pi 5 |
-| mandeye-pro-cm4-bookworm.h | Raspberry Pi Compute module 4 plus carrier board |
-| mandeye-direct-cm5.h | Raspberry Pi Compute module 5 plus carrier board |
-|mandeye-pro-cm4-bullseye.h | Deprecated |
+ ```fstab
+ UUID= /media/usb exfat defaults,nofail,uid=,gid=,umask=0022 0 0
+ ```
+ Run `sudo systemctl daemon-reload`, `sudo mount /media/usb` and `findmnt -T /media/usb -o TARGET,SOURCE,FSTYPE`. For ext4 use its ordinary ownership and mode on the mounted filesystem. Check that the source matches the USB partition and the operator can create a file there. When exchanging disks, update a UUID-based mount to point to the replacement.
-The next example shows how to build the app for Raspberry Pi 4 without a custom carrier board at Raspberry Pi 4.
-```
-git clone https://github.com/JanuszBedkowski/mandeye_controller.git
-cd mandeye_controller
-git submodule init
-git submodule update
-mkdir -p build && cd build
-cmake .. -DCMAKE_BUILD_TYPE=Release -DMANDEYE_HARDWARE_HEADER=mandeye-standard-rpi4.h
-make -j1 # -j4 can be used for 8 Gb version
-```
+4. Select the closest wiring example. The package supplies `rpi4.json`, `rpi5.json`, `pro-cm4-bookworm.json` and `cm5-direct.json`. For example:
-## Test wiring and hardware
-Before running the application, you should test the wiring and hardware. You can use the following commands to test the hardware:
-```bash
-cd mandeye_controller/build
-./led_demo
-./button_demo
-```
-Both programs should work correctly, without a need of `sudo`. If not, check if your user is in `gpio` group, if not add it:
-```bash
-sudo usermod -a -G gpio $USER
-```
+ ```bash
+ sudo cp /usr/share/mandeye/examples/pro-cm4-bookworm.json /etc/mandeye/device.json
+ sudoedit /etc/mandeye/device.json
+ ```
-## Set USB mount
-Follow manual for build and configuration of USB mount
-https://gist.github.com/michalpelka/82d44a21c29f34ee5320c349f8bbf683
-
-```shell
-cd /tmp
-git clone https://github.com/rbrito/usbmount.git
-cd usbmount
-dpkg-buildpackage -us -uc -b
-cd ..
-sudo apt install ./usbmount_0.0.24_all.deb
-```
+ Check the GPIO chip and line offsets on this Pi (`gpiodetect` and `gpioinfo` from the `gpiod` package). Match each LED, buzzer and button role to its wire and button pull. For an unwired role, keep its key and set its value to `null` (for example `"buzzer": null` or `"stationary": null` inside `buttons`). Enable the UARTs used by the chosen carrier in `/boot/firmware/config.txt`. Use `dtoverlay -h ` for that board's pin choices. Disable the serial login console on any UART used by the scanner. Reboot after changing overlays, then check the device paths in `/dev`. In particular the historical Pi 4 example specifies `/dev/S0` for GNSS. Enter the actual UART or set `gnss` to `null` if absent. [Raspberry Pi UART configuration](https://www.raspberrypi.com/documentation/computers/configuration.html#configure-uarts)
-Edit config `sudo nano /etc/usbmount/usbmount.conf`:
-by changing keys:
-```shell
-FILESYSTEMS="vfat ext2 ext3 ext4 hfsplus ntfs fuseblk exfat"
-FS_MOUNTOPTIONS="-fstype=vfat,users,rw,umask=000 -fstype=exfat,users,rw,umask=000"
-VERBOSE=yes
-```
-Install udev rules:
-```shell
-sudo mkdir /etc/systemd/system/systemd-udevd.service.d
-sudo nano -w /etc/systemd/system/systemd-udevd.service.d/00-my-custom-mountflags.conf
-```
-and add content:
-```shell
-[Service]
-PrivateMounts=no
-```
+ **Two-head wiring example.** CaveTronic's scanner uses the Pro CM4 example and the Linux account `mandeye`. Set `gnss` to `null` and `operation.benchmark_usb` to `true`. Verify stationary/write/continuous LEDs on GPIO **20/16/21**, buzzer **24**, and stationary/continuous buttons **25/8**, both pull-down. Keep both FakePPS pairs, **3 → /dev/ttyAMA2** and **2 → /dev/ttyAMA5**. Check `gpiochip` against this unit.
-Restart udev:
-```shell
-sudo systemctl daemon-reexec
-sudo service systemd-udevd restart
-```
+5. With the drive mounted and the lidars connected, run one activation command from the operator account:
-Verify if usb mount works correclty:
-```shell
-touch /media/usb/test
-```
-```shell
-tail -f /var/log/syslog
-```
+ ```bash
+ sudo mandeye-activate
+ ```
+ For a different recording mount, pass its absolute path with `sudo mandeye-activate --repo /path/to/recordings`. Check the reported mount source, service account and executable. On every start, the controller checks that the account can write to the directory and that its backing disk is separate from the system drive. If this check fails, mount the drive and start the service again.
-# Installing software on target device
+ Activation starts the controller, enables it at boot and starts the configured PPS services. If it reports a device permission error, use `id` and `ls -l` on the named device to check group access. For devices owned by `gpio` or `dialout`, an administrator can grant the operator access with `sudo usermod -aG "$(id -un)"` from that account. Log in again before the wiring demos. After correcting an error, repeat activation. Continue with [your first scan](#record-and-open-your-first-scan).
- Then you can build the package:
-```bash
-cd mandeye_controller
-mkdir -p build && cd build
-cmake .. -DCMAKE_BUILD_TYPE=Release -DMANDEYE_HARDWARE_HEADER=mandeye-standard-rpi4.h
-make -j1 # -j4 can be used for 8 Gb version
-sudo make install
-```
+## Update a working scanner
-## Debian package
+1. Identify the service actually running the controller. Check its account, executable, local overrides and boot policy. Use its real name throughout.
-You can build a DEB package for easier installation on the target device.
-It can help with deployment on small 1Gb devices.
+ ```bash
+ unit=mandeye_controller.service
+ systemctl show "$unit" -p FragmentPath -p DropInPaths -p User -p ExecStart
+ systemctl is-enabled "$unit"
+ systemctl cat "$unit"
+ ```
-```bash
-cd mandeye_controller
-mkdir -p build && cd build
-cmake .. -DCMAKE_BUILD_TYPE=Release -DMANDEYE_HARDWARE_HEADER=mandeye-standard-rpi4.h
-make -j1 # -j4 can be used for 8 Gb version
-sudo make package
-```
+ For a custom name, set e.g. `unit=my_scanner.service` **before** the checks above. Register that unit before the first package upgrade:
-The package will be available in the build directory.
-
-# Choosing Lidar SDK
-The software supports different SDKs for the Lidar:
-
-| SDK | Variable | Description |
-|-----|----------|----------------------------------------------------------------------------------|
-| Livox SDK | `LIVOX_SDK2` | Livox SDK version 2 tested with Mid360 and HAP |
-| Ouster SDK | `OUSTER` | Ouster SDK tested with OS-0-64 (ousteros-image-prod-aries-v2.5.3+20240111055903) |
-| Butter Lidar | `BUTTER_LIDAR` | Dummy SDK for documentation and testing purposes |
-
-Those are shared libraries that are loaded at runtime.
-You can set the SDK to use in two ways:
-1. By setting the `MANDEYE_LIDAR_SDK` environment variable to `LIVOX_SDK2` or `OUSTER`.
-2. By putting the config in location '/media/usb/mandeye_config.json' with the following content:
-```json
-{
- "lidar_sdk": "LIVOX_SDK2"
-}
-```
+ ```bash
+ sudo install -d /etc/mandeye
+ printf '%s\n' "$unit" | sudo tee /etc/mandeye/controller-unit
+ ```
-# Installation and usage of the package
-To install the package, you need to copy it to the target device and install it with `dpkg`:
-```bash
-sudo dpkg -i mandeye_controller-0.1.0-Linux.deb
-```
+2. Finish acquisition before stopping the service. In the web panel choose **Stop Record** for continuous recording, or let a stationary measurement finish. **StopScan starts a stationary measurement.** Wait for the write LED to go out, confirm the final LAZ, IMU and status files and check that the panel shows `IDLE`. The HTTP response to Stop Record arrives before the final write. Stopping systemd during a write can lose buffered samples.
-The package will be installed in `/opt/mandeye/` directory, the service will be added to `/usr/lib/systemd/system/`.
-Note that the service will not start automatically, you need to start it manually or enable it with `systemctl`.
-There is a helper script `/opt/mandeye/helper.sh` that contains some useful commands to start, stop, and restart the service.
+ **First migration from the old CM5 Direct build:** its autostart begins another recording after Stop Record. Plan a maintenance boot **before a field session**, with the controller suppressed from power-on. On a powered-off Pi, edit the boot partition's existing single-line `cmdline.txt` and append `systemd.mask=mandeye_controller.service` (use the actual unit name). Boot with this temporary mask and confirm the controller is inactive. Remove only the added argument before the next normal boot. Read and verify any existing field data before maintenance.
-If you make any changes post-installation, please run 'sudo systemctl daemon-reload' to reload the service.
-Note that the changes will be disregarded after reinstallation.
-## Post installation
-Those commands need to be run only once after installation.
+3. Stop the effective controller and stop FakePPS/SlavePPS if they are running so you can restart them with the new configuration. Record which auxiliaries were running. Leave the existing enable/disable/mask policy in place.
+ ```bash
+ sudo systemctl stop "$unit"
+ systemctl is-active "$unit" # expect inactive
+ sudo apt install "./$package"
+ /usr/sbin/mandeye-activate --status
+ ```
-Add it to bashrc:
-```bash
-echo "source /opt/mandeye/helpers.sh" >> ~/.bashrc
-```
+ Compare `dpkg-query -W mandeye-multisensor` with the Debian version from the downloaded file. The package refuses an upgrade while the selected controller is active. Continue only after a safe stop. On a first migration, copy an example as in step 4 above and map **every** pin, pull, UART, PPS pair and operating setting from the scanner's previous header. Later package upgrades retain the local JSON. Inspect existing SlavePPS overrides with `systemctl cat mandeye_slave_pps.service`. [SlavePPS inputs and migration](extras/SlavePPS/README.md)
-After that start required services:
+4. Check the effective `User` and `ExecStart`. Existing local units and drop-ins can point to a home-directory build. To switch such a unit deliberately, use `sudo systemctl edit "$unit"`:
-```shell
-mandeye_start
-```
+ ```ini
+ [Service]
+ ExecStart=
+ ExecStart=/opt/mandeye/control_program
+ ```
-There are optional services that can be started:
+ If you maintain your own controller unit, set `RequiresMountsFor=/path/to/recordings` in its `[Unit]` section using the actual recording path. Systemd then waits for the configured mount at boot. Check `/opt/mandeye/control_program --validate-config`, the mount and service account permissions. Start the intended PPS services and controller yourself (`sudo systemctl start "$unit"`), respecting any deliberate mask. For a maintenance boot, first remove the boot argument and reboot under the original policy. A disabled unit can be started for the test without enabling it. Check the running revision below and [record a scan](#record-and-open-your-first-scan).
-## Fake PPS
-PPS time synchronization generator using GPIO (to other devices)
-```shell
-sudo systemctl enable mandeye_fake_pps.service
-mandeye_fakepps_start # PPS generator using GPIO
-```
+## Record and open your first scan
-PTP time synchronization generator using eth0 (works only on Raspberry Pi 5):
-```shell
-sudo systemctl enable mandeye_ptp4l-gm-eth0.service
-sudo systemctl enable mandeye_phc2sys-gm-eth0.service
-mandeye_phc2sys_start # PTP clock using eth0
-mandeye_ptp4l_grandmaster_start #
-```
+1. Open `http://:8003/` on the scanner network. Allow for the systemd startup delay and lidar discovery. Inspect `http://:8003/json/status` or run `curl -fsS localhost:8003/json/status | python3 -m json.tool` on the Pi. Compare `hash` with the published source revision (the test merge for a PR build). Check `device_config`, `lidar_sdk`, the Livox serial numbers and data flow. Check synchronization when your scanner uses PPS or PTP.
+2. In `IDLE`, choose **Start Record**, confirm `SCANNING`, and collect at least ten seconds. With `operation.autostart_recording` enabled, the controller starts the first recording itself after it becomes ready. Systemd boot enablement controls the service separately.
+3. Choose **Stop Record**. Wait for the controller to finish writing, the write LED to go out and `IDLE` to persist. On success, `lastLazStatus.filename` identifies the final chunk from this recording. On `USB_IO_ERROR`, the panel shows the file that failed to save. The same diagnostic is available in `lastSaveError` and the service journal. Check the drive before beginning another scan. Open that **lidarNNNN.laz** from the USB drive in CloudCompare. Check its points, the sample rows below the header in **imuNNNN.csv**, and the matching **statusNNNN.json** in the same **continousScanning_NNNN** directory. A short final chunk is normal. After a successful stop, **Start Record** should work again.
+4. Record the package SHA-256, installed version, running hash, unit/account, actual mount source and final filenames for this scanner. Reboot and repeat the scan under the chosen boot policy. Test each fitted LED, buzzer and button. When USB benchmarking is enabled, check both speeds in `fs_benchmark`. On a multi-head scanner such as CaveTronic’s, check each lidar by serial number. With one head connected at power-on, match its label to `lidar.multi.LivoxLidarInfo[].sn`, check that the point and IMU counters increase and `lidar.is_synced` becomes true. Record and open a chunk. Repeat for the other head, then run both together and confirm that both serial numbers appear. Save the two-head status and `lidarNNNN.sn` alongside the LAZ and IMU.
-# SlavePPS
+## Local settings and diagnostics
-Slave PPS is a serivce that will adjust system time using PPS signal from master PPS + NMEA.
+The controller reads two files at startup. The local `/etc/mandeye/device.json` selects wiring, PPS and operation. The USB file `mandeye_config.json` in `MANDEYE_REPO` (default `/media/usb/`) carries acquisition settings. A USB `lidar_sdk` takes precedence over `MANDEYE_LIDAR_SDK`, followed by the default `LIVOX_SDK2`. Preserve any `picamera` section for the optional Picamera2 application. The field package includes Livox SDK2 and the `BUTTER_LIDAR` simulator.
-Disable NTP:
-```shell
-sudo systemctl stop systemd-timesyncd
-```
+Change the local `operation` settings independently of the wiring. To change PPS wiring on a scanner configured with `mandeye-activate`, finish the scan, verify its files, stop the controller and repeat activation. It restarts its PPS services when their parameters change and disables the ones it previously enabled if their configuration is removed. For PPS services enabled manually or by an older installer, check their boot policy yourself after removing a PPS configuration.
-Start service:
-```shell
-sudo systemctl enable mandeye_slave_pps.service
-sudo systemctl start mandeye_slave_pps.service
-```
+| Setting | Effect |
+|---|---|
+| `benchmark_usb` | Measure 10 MB and 1 MB writes at startup and report both speeds under `fs_benchmark`. |
+| `wait_for_lidar_sync` | Require reported lidar synchronization before the scanner becomes ready. |
+| `autostart_recording` | Start one continuous recording when ready. An operator stop returns to `IDLE`. |
+| `stop_presses` | Set the continuous button to one press or three presses to end a recording. The web panel uses one Stop Record command. |
+| `beep_on_laz` | Sound the buzzer after a successful LAZ write. |
+| `restart_on_usb_error` | Exit on the third observation of `USB_IO_ERROR`, allowing the controller's systemd restart policy to take effect. |
-# Libcamera
-Cameras:
-```shell
-sudo systemctl enable mandeye_libcamera_cam0.service
-sudo systemctl enable mandeye_libcamera_cam1.service
-mandeye_cam0_start
-mandeye_cam1_start
+```bash
+systemctl status mandeye_controller.service
+journalctl -u mandeye_controller.service -b
+/usr/sbin/mandeye-activate --status
+source /opt/mandeye/helpers.sh
```
-# USB Gnss
-Extra USB Gnss:
-```shell
-sudo systemctl enable mandeye_extra_gnss.service
-mandeye_extra_gnss_start
-```
+For a custom unit use `systemctl status "$unit"` and `journalctl -u "$unit" -b`. To test wiring, finish the scan and stop the controller and any other process holding the lines. Run `/opt/mandeye/led_demo` and `/opt/mandeye/button_demo` **one at a time** as the service account. Exit each demo before starting another or resuming services.
-Extra muRata UART IMU (experimental):
-```shell
-sudo systemctl enable mandeye_murata_uart_driver.service
-mandeye_murata_uart_imu_start
-```
-# Services
-List state of services:
-```shell
-mandeye_services_status
-```
+[PTP, PPS, cameras and optional services](doc/accessories.md) · [Developer build](doc/build.md) · [Bill of materials](doc/BIM.md) · [Wiring](doc/wiring/wiring.md) · [Assembly 3MF](3mf/ScannerAssembly.3mf) · [Livox cap 3MF](3mf/LivoxCap.3mf) · [Onshape design](https://cad.onshape.com/documents/a6c6019ccb399ad39d830fad/w/0440af658555626c8fea1136/e/e1bf637894052d9247ac984d) · [Assembly video](https://youtu.be/BXBbuSJMFEo)
diff --git a/code/button_demo.cpp b/code/button_demo.cpp
index 5db90b9..4372477 100644
--- a/code/button_demo.cpp
+++ b/code/button_demo.cpp
@@ -3,7 +3,6 @@
#include
#include
-std::mutex gpioClientPtrLock;
std::shared_ptr gpioClientPtr;
using namespace hardware;
bool StopScan()
@@ -26,11 +25,13 @@ bool Continous()
return false;
}
-int main(int arc, char* argv[])
+int main()
+try
{
+ const auto device = hardware::readDeviceConfig();
std::cout << "button_demo" << std::endl;
- gpioClientPtr = std::make_shared(0);
+ gpioClientPtr = std::make_shared(device, false);
gpioClientPtr->setLed(LED::LED_GPIO_STOP_SCAN, false);
gpioClientPtr->setLed(LED::LED_GPIO_COPY_DATA, false);
gpioClientPtr->setLed(LED::LED_GPIO_CONTINOUS_SCANNING, false);
@@ -42,3 +43,8 @@ int main(int arc, char* argv[])
return 0;
}
+catch(const std::exception& e)
+{
+ std::cerr << e.what() << std::endl;
+ return 1;
+}
diff --git a/code/compilation_constants.h.in b/code/compilation_constants.h.in
index f07173a..4ad91b0 100644
--- a/code/compilation_constants.h.in
+++ b/code/compilation_constants.h.in
@@ -1,6 +1,5 @@
#pragma once
#define GIT_HASH "@GIT_HASH@"
-#define MANDEYE_HARDWARE_HEADER "@MANDEYE_HARDWARE_HEADER@"
#define MANDEYE_VERSION "@MANDEYE_VERSION@"
#define SYSTEM_ARCH "@SYSTEM_ARCH@"
\ No newline at end of file
diff --git a/code/gpios.cpp b/code/gpios.cpp
index 645586f..2f62fb6 100644
--- a/code/gpios.cpp
+++ b/code/gpios.cpp
@@ -1,5 +1,5 @@
-#include "hardware_config/mandeye.h"
-#include
+#include
+#include
#include
#include
#include
@@ -23,138 +23,89 @@ bool GpioClient::ButtonData::GetButtonState(const GpioClient::ButtonData& button
return rawButtonState == 1;
}
}
-void GpioClient::ButtonData::CallUserCallbacks()
-{
- for(auto& [name, callback] : m_callbacks)
- {
- callback();
- }
-}
-
-GpioClient::GpioClient(bool sim)
+GpioClient::GpioClient(const DeviceConfig& device, bool sim)
: m_useSimulatedGPIO(sim)
{
-
- using namespace GPIO;
- for(auto& [id, name] : ButtonToName)
- {
- m_buttons[id].m_name = name;
- }
- for(auto& [led, name] : LedToName)
+ // Closing the chip also releases its lines if a later request fails.
+ std::unique_ptr chip(nullptr, gpiod_chip_close);
+ if(!sim && (!device.leds.empty() || !device.buttons.empty()))
{
- m_ledGpio[led].m_name = name;
+ std::cout << "Opening GPIO chip " << device.gpiochip << std::endl;
+ chip.reset(gpiod_chip_open(device.gpiochip.c_str()));
+ if(!chip)
+ throw std::runtime_error(device.gpiochip + ": " + std::strerror(errno));
}
-
- if(!sim)
+ auto lineError = [&](const std::string& role, int gpio) {
+ return std::runtime_error(device.gpiochip + " GPIO " + std::to_string(gpio) + " (" + role + "): " + std::strerror(errno));
+ };
+ for(const auto& [id, pin] : device.leds)
{
- const auto& chipPath = hardware::GetGPIOChip();
- std::cout << "Opening GPIO chip " << chipPath << std::endl;
-
- m_chip = gpiod_chip_open(chipPath);
- if(!m_chip)
- {
- std::cerr << "Error: Unable to open GPIO chip." << std::endl;
- return;
- }
- std::lock_guard lck{m_lock};
-
- // initialize leds
- for(auto& [led, name] : LedToName)
+ const auto& name = LedToName.at(id);
+ auto& led = m_ledGpio[id];
+ led.m_name = name;
+ led.m_pin = pin;
+ if(chip)
{
- LedData& ledData = m_ledGpio[led];
- ledData.m_name = name;
- ledData.m_pin = hardware::GetLED(led);
- if(ledData.m_pin == -1)
- {
- std::cerr << "No LED with id " << name << " in hardware config " << hardware::mandeyeHarwareType() << std::endl;
- }
- else
- {
- ledData.m_line = gpiod_chip_get_line(m_chip, ledData.m_pin);
-
- if(!ledData.m_line)
- {
- std::cerr << "Failed to create line at pin " << ledData.m_pin << " of " << ledData.m_name << std::endl;
- continue;
- }
- int ret = gpiod_line_request_output(ledData.m_line, ledData.m_name.c_str(), 0);
- if(ret < 0)
- {
- std::cerr << "Failed to create line at pin " << ledData.m_pin << " of " << ledData.m_name << std::endl;
- continue;
- }
- }
+ led.m_line = gpiod_chip_get_line(chip.get(), led.m_pin);
+ if(!led.m_line || gpiod_line_request_output(led.m_line, name.c_str(), 0) < 0)
+ throw lineError(name, led.m_pin);
}
- std::cout << "LEDs initialized" << std::endl;
-
- for(auto& [button, name] : ButtonToName)
+ }
+ for(const auto& [id, wiring] : device.buttons)
+ {
+ const auto& name = ButtonToName.at(id);
+ auto& button = m_buttons[id];
+ button.m_name = name;
+ button.m_pin = wiring.gpio;
+ button.m_pullMode = wiring.pull;
+ if(chip)
{
- ButtonData& buttonData = m_buttons[button];
- buttonData.m_pin = hardware::GetButton(button);
- buttonData.m_pullMode = hardware::GetPULL(button);
- if(buttonData.m_pin == -1)
- {
- std::cerr << "No button with id " << name << " in hardware config " << hardware::mandeyeHarwareType() << std::endl;
- }
- else
- {
- buttonData.m_line = gpiod_chip_get_line(m_chip, buttonData.m_pin);
- if(!buttonData.m_line)
- {
- std::cerr << "Failed to create line at pin " << buttonData.m_pin << " of " << buttonData.m_name << std::endl;
- continue;
- }
- int flags = 0;
- if(buttonData.m_pullMode == GPIO::GPIO_PULL::UP)
- {
- flags = GPIOD_LINE_REQUEST_FLAG_BIAS_PULL_UP;
- }
- else
- {
- flags = GPIOD_LINE_REQUEST_FLAG_BIAS_PULL_DOWN;
- }
- int ret = gpiod_line_request_input_flags(buttonData.m_line, buttonData.m_name.c_str(), flags);
- if(ret < 0)
- {
- std::cerr << "Failed to create line at pin " << buttonData.m_pin << " of " << buttonData.m_name << std::endl;
- continue;
- }
- }
+ int flags = GPIOD_LINE_REQUEST_FLAG_BIAS_DISABLE;
+ if(button.m_pullMode == GPIO_PULL::UP)
+ flags = GPIOD_LINE_REQUEST_FLAG_BIAS_PULL_UP;
+ else if(button.m_pullMode == GPIO_PULL::DOWN)
+ flags = GPIOD_LINE_REQUEST_FLAG_BIAS_PULL_DOWN;
+ button.m_line = gpiod_chip_get_line(chip.get(), button.m_pin);
+ if(!button.m_line || gpiod_line_request_input_flags(button.m_line, name.c_str(), flags) < 0)
+ throw lineError(name, button.m_pin);
}
}
+ m_chip = chip.release();
for(auto& [buttonID, ButtonName] : ButtonToName)
{
- {
- addButtonCallback(buttonID, "DBG" + ButtonName, [this, name = ButtonName]() {
- auto buzzerGPIO = m_ledGpio[LED::BUZZER];
- setLed(buzzerGPIO, true);
- std::this_thread::sleep_for(std::chrono::milliseconds(100));
- setLed(buzzerGPIO, false);
- std::cout << "Button : " << name << std::endl;
- });
- }
- };
+ addButtonCallback(buttonID, "DBG" + ButtonName, [this, name = ButtonName]() {
+ setLed(LED::BUZZER, true);
+ std::this_thread::sleep_for(std::chrono::milliseconds(100));
+ setLed(LED::BUZZER, false);
+ std::cout << "Button : " << name << std::endl;
+ });
+ }
m_gpioReadBackThread = std::thread([this]() {
while(m_running)
{
for(auto& [buttonID, buttonData] : m_buttons)
{
- bool rawButtonState = ButtonData::GetButtonState(buttonData);
- if(rawButtonState == true)
+ Callbacks callbacks;
{
- buttonData.m_pressedTime++;
- if(buttonData.m_pressedTime == buttonData.DEBOUNCE_TIME)
+ std::lock_guard lock(m_lock);
+ if(ButtonData::GetButtonState(buttonData))
{
- buttonData.m_pressed = true;
- buttonData.CallUserCallbacks();
+ if(++buttonData.m_pressedTime == ButtonData::DEBOUNCE_TIME)
+ {
+ buttonData.m_pressed = true;
+ callbacks = buttonData.m_callbacks;
+ }
+ }
+ else
+ {
+ buttonData.m_pressed = false;
+ buttonData.m_pressedTime = 0;
}
}
- else
- {
- buttonData.m_pressedTime = 0;
- }
+ for(const auto& [name, callback] : callbacks)
+ callback();
}
std::this_thread::sleep_for(std::chrono::milliseconds(25));
}
@@ -193,14 +144,11 @@ nlohmann::json GpioClient::produceStatus()
std::lock_guard lck{m_lock};
for(const auto& [ledid, ledname] : LedToName)
{
- try
- {
- data["leds"][ledname] = m_ledGpio.at(ledid).m_state;
- }
- catch(const std::out_of_range& ex)
- {
+ auto it = m_ledGpio.find(ledid);
+ if(it != m_ledGpio.end())
+ data["leds"][ledname] = it->second.m_state;
+ else
data["leds"][ledname] = "NA";
- }
}
for(const auto& [buttonid, buttonname] : ButtonToName)
@@ -221,8 +169,9 @@ nlohmann::json GpioClient::produceStatus()
void GpioClient::setLed(LED led, bool state)
{
- assert(m_ledGpio.find(led) != m_ledGpio.end());
- setLed(m_ledGpio[led], state);
+ const auto it = m_ledGpio.find(led);
+ if(it != m_ledGpio.end())
+ setLed(it->second, state);
}
void GpioClient::setLed(LedData& led, bool state)
@@ -240,22 +189,17 @@ void GpioClient::addButtonCallback(hardware::BUTTON btn, const std::string& call
std::lock_guard lck{m_lock};
auto it = m_buttons.find(btn);
- if(it == m_buttons.end())
- {
- std::cerr << "No button with id " << (int)btn << std::endl;
- return;
- }
- it->second.m_callbacks[callbackName] = callback;
+ if(it != m_buttons.end())
+ it->second.m_callbacks[callbackName] = callback;
}
void GpioClient::beep(const std::vector& durations)
{
- //std::lock_guard lck{m_lock};
-
- if(!m_useSimulatedGPIO)
+ const auto buzzer = m_ledGpio.find(LED::BUZZER);
+ if(!m_useSimulatedGPIO && buzzer != m_ledGpio.end())
{
bool isOn = false;
- auto& buzzerGpio = m_ledGpio[LED::BUZZER];
+ auto& buzzerGpio = buzzer->second;
for(auto& duration : durations)
{
const auto sleepDuration = std::chrono::milliseconds(duration);
diff --git a/code/gpios.h b/code/gpios.h
index 998d91f..d0565ae 100644
--- a/code/gpios.h
+++ b/code/gpios.h
@@ -1,6 +1,6 @@
#pragma once
-#include "hardware_config/hardware_common.h"
+#include "hardware_config/device_config.h"
#include
#include
#include
@@ -28,12 +28,11 @@ class GpioClient
gpiod_line* m_line{nullptr};
uint32_t m_pressedTime{0}; //! time when button was pressed
GPIO::GPIO_PULL m_pullMode; //! pull up or down
- bool m_pressed; //! is button pressed
+ bool m_pressed{false}; //! is button pressed
Callbacks m_callbacks; //! callbacks to call when button is pressed
static constexpr int DEBOUNCE_TIME = 2; //! debounce time in cycles
static bool GetButtonState(const ButtonData& button);
- void CallUserCallbacks();
};
struct LedData
@@ -47,7 +46,7 @@ class GpioClient
public:
//! Constructor
//! @param sim if true hardware is not called
- GpioClient(bool sim);
+ GpioClient(const hardware::DeviceConfig& device, bool sim);
//! Destructor
~GpioClient();
@@ -110,7 +109,6 @@ class GpioClient
std::atomic m_running{true};
};
-inline std::mutex gpioClientPtrLock;
inline std::shared_ptr gpioClientPtr;
} // namespace mandeye
\ No newline at end of file
diff --git a/code/hardware_config/device_config.cpp b/code/hardware_config/device_config.cpp
new file mode 100644
index 0000000..bc5b53a
--- /dev/null
+++ b/code/hardware_config/device_config.cpp
@@ -0,0 +1,247 @@
+#include "device_config.h"
+#include
+#include
+#include
+#include
+#include
+#include
+
+namespace hardware
+{
+namespace
+{
+// Keep the JSON path alongside each value so errors name the field the operator must edit.
+struct Field
+{
+ const nlohmann::json& value;
+ std::string path;
+
+ [[noreturn]] void error(const std::string& message) const
+ {
+ throw std::runtime_error((path.empty() ? "/" : path) + ": " + message);
+ }
+
+ Field member(const std::string& key) const
+ {
+ if(!value.contains(key))
+ throw std::runtime_error(path + "/" + key + ": missing required field");
+ return {value.at(key), path + "/" + key};
+ }
+
+ void object(std::initializer_list keys) const
+ {
+ if(!value.is_object())
+ error("expected an object");
+ for(const auto& item : value.items())
+ {
+ if(std::find(keys.begin(), keys.end(), item.key()) == keys.end())
+ throw std::runtime_error(path + "/" + item.key() + ": unknown field");
+ }
+ }
+
+ std::string string() const
+ {
+ if(!value.is_string())
+ error("expected a string");
+ auto result = value.get();
+ if(result.empty() || result.find('\0') != std::string::npos)
+ error("expected a non-empty string without NUL characters");
+ return result;
+ }
+
+ std::string devicePath() const
+ {
+ auto result = string();
+ if(result.front() != '/')
+ error("expected an absolute device path");
+ return result;
+ }
+
+ int integer() const
+ {
+ if(!value.is_number_integer() || value < 0 || value > std::numeric_limits::max())
+ error("expected a non-negative integer in range");
+ return value.get();
+ }
+
+ bool boolean() const
+ {
+ if(!value.is_boolean())
+ error("expected true or false");
+ return value.get();
+ }
+};
+
+const std::map baudRates = {
+ {4800, B4800}, {9600, B9600}, {19200, B19200}, {38400, B38400}, {57600, B57600}, {115200, B115200}, {230400, B230400}};
+
+int checkedBaud(int baud, const std::string& path)
+{
+ if(baudRates.count(baud) == 0)
+ throw std::runtime_error(path + ": unsupported baud rate " + std::to_string(baud));
+ return baud;
+}
+
+SerialInput readSerial(const Field& field)
+{
+ const Field baud = field.member("baud");
+ return {field.member("uart").devicePath(), checkedBaud(baud.integer(), baud.path)};
+}
+
+DeviceConfig parseDevice(nlohmann::json document, const std::string& path)
+{
+ DeviceConfig result{};
+ result.path = path;
+ result.document = std::move(document);
+ const Field root{result.document, ""};
+ root.object({"name", "gpiochip", "leds", "buttons", "gnss", "fake_pps", "slave_pps", "operation"});
+ result.name = root.member("name").string();
+ result.gpiochip = root.member("gpiochip").devicePath();
+
+ std::map usedPins;
+ auto gpio = [&](const Field& field) {
+ const int pin = field.integer();
+ auto [it, inserted] = usedPins.emplace(pin, field.path);
+ if(!inserted)
+ field.error("GPIO " + std::to_string(pin) + " is already assigned to " + it->second);
+ return pin;
+ };
+
+ const Field leds = root.member("leds");
+ leds.object({"stationary", "write", "continuous", "buzzer"});
+ const std::pair ledRoles[] = {{LED::LED_GPIO_STOP_SCAN, "stationary"},
+ {LED::LED_GPIO_COPY_DATA, "write"},
+ {LED::LED_GPIO_CONTINOUS_SCANNING, "continuous"},
+ {LED::BUZZER, "buzzer"}};
+ for(const auto& [id, key] : ledRoles)
+ {
+ const auto field = leds.member(key);
+ if(!field.value.is_null())
+ result.leds.emplace(id, gpio(field));
+ }
+
+ const Field buttons = root.member("buttons");
+ buttons.object({"stationary", "continuous"});
+ const std::pair