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. - -![Scanner Assembly](./3mf/ScannerAssembly.png) - -Additionally, we recommend printing a protective cap for Livox Mid-360, which you can find in the [LivoxCap.3mf](./3mf/LivoxCap.3mf) file. - -![Livox Cap](./3mf/LivoxCap.png) - -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 buttonRoles[] = {{BUTTON::BUTTON_STOP_SCAN, "stationary"}, + {BUTTON::BUTTON_CONTINOUS_SCANNING, "continuous"}}; + for(const auto& [id, key] : buttonRoles) + { + const auto field = buttons.member(key); + if(field.value.is_null()) + continue; + field.object({"gpio", "pull"}); + const auto pull = field.member("pull"); + const std::map modes{ + {"up", GPIO::GPIO_PULL::UP}, {"down", GPIO::GPIO_PULL::DOWN}, {"off", GPIO::GPIO_PULL::OFF}}; + auto it = modes.find(pull.string()); + if(it == modes.end()) + pull.error("expected up, down or off"); + result.buttons.emplace(id, Button{gpio(field.member("gpio")), it->second}); + } + + const Field gnss = root.member("gnss"); + if(!gnss.value.is_null()) + { + gnss.object({"uart", "baud"}); + result.gnss = readSerial(gnss); + } + + const Field outputs = root.member("fake_pps"); + if(!outputs.value.is_array()) + outputs.error("expected an array of GPIO/UART pairs"); + std::map usedUarts; + auto claimUart = [&](const Field& field) { + auto uart = field.devicePath(); + auto [it, inserted] = usedUarts.emplace(uart, field.path); + if(!inserted) + field.error(uart + " is already assigned to " + it->second); + return uart; + }; + if(result.gnss) + claimUart(gnss.member("uart")); + for(size_t i = 0; i < outputs.value.size(); ++i) + { + Field output{outputs.value.at(i), outputs.path + "/" + std::to_string(i)}; + output.object({"gpio", "uart"}); + result.fakePps.push_back({gpio(output.member("gpio")), claimUart(output.member("uart"))}); + } + + const Field slave = root.member("slave_pps"); + if(!slave.value.is_null()) + { + slave.object({"uart", "baud", "device"}); + claimUart(slave.member("uart")); + result.slavePps = SlavePpsInput{readSerial(slave), slave.member("device").devicePath()}; + } + + const Field op = root.member("operation"); + op.object({"benchmark_usb", "wait_for_lidar_sync", "autostart_recording", "stop_presses", "beep_on_laz", "restart_on_usb_error"}); + const Field presses = op.member("stop_presses"); + const int stopPresses = presses.integer(); + if(stopPresses != 1 && stopPresses != 3) + presses.error("expected 1 or 3"); + result.operation = {op.member("benchmark_usb").boolean(), + op.member("wait_for_lidar_sync").boolean(), + op.member("autostart_recording").boolean(), + stopPresses, + op.member("beep_on_laz").boolean(), + op.member("restart_on_usb_error").boolean()}; + return result; +} +} // namespace + +DeviceConfig readDeviceConfig(const std::string& path) +{ + std::ifstream input(path); + if(!input) + throw std::runtime_error(path + ": cannot read device configuration"); + try + { + return parseDevice(nlohmann::json::parse(input), path); + } + catch(const std::exception& e) + { + throw std::runtime_error(path + ": " + e.what()); + } +} + +speed_t serialSpeed(int baud) +{ + return baudRates.at(baud); +} + +std::optional effectiveSlavePps(const DeviceConfig& device) +{ + const char* uart = std::getenv("SLAVE_PPS_UART_PORT"); + const char* rate = std::getenv("SLAVE_PPS_UART_BAUD_RATE"); + const char* pps = std::getenv("SLAVE_PPS_DEVICE"); + if(!uart && !rate && !pps) + return device.slavePps; + + // Old systemd overrides can set any subset of these three variables. + // Use the original fallbacks only when an operator has supplied an override. + auto input = device.slavePps.value_or(SlavePpsInput{{device.fakePps.empty() ? "/dev/ttyAMA1" : device.fakePps.front().uart, 9600}, "/dev/pps0"}); + if(uart) + { + if(*uart != '/') + throw std::runtime_error("SLAVE_PPS_UART_PORT: expected an absolute device path"); + input.serial.uart = uart; + } + if(pps) + { + if(*pps != '/') + throw std::runtime_error("SLAVE_PPS_DEVICE: expected an absolute device path"); + input.device = pps; + } + if(rate) + { + std::string value(rate); + int baud = 0; + const auto parsed = std::from_chars(value.data(), value.data() + value.size(), baud); + if(parsed.ec != std::errc{} || parsed.ptr != value.data() + value.size()) + throw std::runtime_error("SLAVE_PPS_UART_BAUD_RATE: expected a baud rate integer"); + input.serial.baud = checkedBaud(baud, "SLAVE_PPS_UART_BAUD_RATE"); + } + return input; +} +} // namespace hardware diff --git a/code/hardware_config/device_config.h b/code/hardware_config/device_config.h new file mode 100644 index 0000000..db84d2b --- /dev/null +++ b/code/hardware_config/device_config.h @@ -0,0 +1,66 @@ +#pragma once + +#include "hardware_common.h" +#include +#include +#include +#include +#include +#include + +namespace hardware +{ +inline constexpr const char* DeviceConfigPath = "/etc/mandeye/device.json"; + +struct Button +{ + int gpio; + GPIO::GPIO_PULL pull; +}; + +struct FakePpsOutput +{ + int gpio; + std::string uart; +}; + +struct SerialInput +{ + std::string uart; + int baud; +}; + +struct SlavePpsInput +{ + SerialInput serial; + std::string device; +}; + +struct Operation +{ + bool benchmarkUsb; + bool waitForLidarSync; + bool autostartRecording; + int stopPresses; + bool beepOnLaz; + bool restartOnUsbError; +}; + +struct DeviceConfig +{ + std::string path; + nlohmann::json document; + std::string name; + std::string gpiochip; + std::map leds; + std::map buttons; + std::optional gnss; + std::vector fakePps; + std::optional slavePps; + Operation operation; +}; + +DeviceConfig readDeviceConfig(const std::string& path = DeviceConfigPath); +speed_t serialSpeed(int baud); +std::optional effectiveSlavePps(const DeviceConfig& device); +} // namespace hardware diff --git a/code/hardware_config/hardware_common.h b/code/hardware_config/hardware_common.h index 8d0d68d..59e6ca2 100644 --- a/code/hardware_config/hardware_common.h +++ b/code/hardware_config/hardware_common.h @@ -1,6 +1,4 @@ #pragma once -#include "state.h" -#include namespace hardware { @@ -10,8 +8,6 @@ enum class LED LED_GPIO_COPY_DATA, LED_GPIO_CONTINOUS_SCANNING, BUZZER, - LIDAR_SYNC_1, - LIDAR_SYNC_2, }; enum class BUTTON @@ -30,5 +26,3 @@ enum class GPIO_PULL OFF }; }; - -#include "gpios.h" diff --git a/code/hardware_config/mandeye-direct-cm5.h b/code/hardware_config/mandeye-direct-cm5.h deleted file mode 100644 index 42fd750..0000000 --- a/code/hardware_config/mandeye-direct-cm5.h +++ /dev/null @@ -1,114 +0,0 @@ -#pragma once - -#include "gpios.h" -#include "hardware_common.h" -#include "utils/TimeStampProvider.h" -#ifdef MANDEYE_HARDWARE_CONFIGURED -# error "MANDEYE Hardware were confiured. You included multiple hardware headers!" -#endif -#include -#define MANDEYE_HARDWARE_CONFIGURED -namespace hardware -{ -#define PISTACHE_SERVER -#define MANDEYE_BENCHMARK_WRITE_SPEED -#define MANDEYE_COUNTINOUS_SCANNING_STOP_1_CLICK - -constexpr int Offset = 0; -constexpr bool Autostart = true; -constexpr bool WaitForLidarSync = true; - -constexpr const char* mandeyeHarwareType() -{ - return "MandeyeStandard"; -} - -constexpr const char* GetGPIOChip() -{ - //for raspberry pi 5 - return "/dev/gpiochip4"; -} - -inline void ReportState([[maybe_unused]] const mandeye::States state) -{ - if(state == mandeye::States::USB_IO_ERROR) - { - std::cerr << "USB IO ERROR - will restart shortly" << std::endl; - static int count = 0; - if(count++ >= 2) - { - std::cerr << "Restarting..." << std::endl; - std::abort(); - } - } -} - -inline void OnSavedLaz([[maybe_unused]] const std::string& filename) -{ - std::cout << "Saved LAZ file: " << filename << std::endl; - if(mandeye::gpioClientPtr) - { - mandeye::gpioClientPtr->beep({50, 100, 50, 100}); - } -} - -constexpr int GetLED(LED led) -{ - - if(led == LED::LED_GPIO_STOP_SCAN) - { - return 26; - } - if(led == LED::LED_GPIO_COPY_DATA) - { - return 19; - } - if(led == LED::LED_GPIO_CONTINOUS_SCANNING) - { - return 13; - } - if(led == LED::BUZZER) - { - return 24; - } - return -1; -} -constexpr int GetButton(BUTTON btn) -{ - if(btn == BUTTON::BUTTON_STOP_SCAN) - { - return 5; - } - if(btn == BUTTON::BUTTON_CONTINOUS_SCANNING) - { - return 6; - } - return -1; -} - -constexpr GPIO::GPIO_PULL GetPULL([[maybe_unused]] BUTTON btn) -{ - return GPIO::GPIO_PULL::UP; -} - -[[maybe_unused]] inline const std::array GetLidarSyncGPIO() -{ - return {}; // No hardware sync -} - -[[maybe_unused]] inline const std::array GetLidarSyncPorts() -{ - return {}; // No hardware sync -}; - -[[maybe_unused]] inline const std::string GetGNSSPort() -{ - return ""; // empty port, no GNSS. -}; - -[[maybe_unused]] inline const LibSerial::BaudRate GetGNSSBaudrate() -{ - return LibSerial::BaudRate::BAUD_115200; -}; - -} // namespace hardware diff --git a/code/hardware_config/mandeye-pro-cm4-bookworm.h b/code/hardware_config/mandeye-pro-cm4-bookworm.h deleted file mode 100644 index d55858c..0000000 --- a/code/hardware_config/mandeye-pro-cm4-bookworm.h +++ /dev/null @@ -1,100 +0,0 @@ -#pragma once - -#include "hardware_common.h" - -#include -#include -#ifdef MANDEYE_HARDWARE_CONFIGURED -# error "MANDEYE Hardware were confiured. You included multiple hardware headers!" -#endif - -#define MANDEYE_HARDWARE_CONFIGURED -namespace hardware -{ -#define PISTACHE_SERVER - -constexpr bool Autostart = false; -constexpr bool WaitForLidarSync = false; -constexpr const char* mandeyeHarwareType() -{ - return "MandeyePro"; -} - -constexpr const char* GetGPIOChip() -{ - return "/dev/gpiochip0"; -} - -inline void ReportState([[maybe_unused]] const mandeye::States state) -{ - // no-op -} - -inline void OnSavedLaz([[maybe_unused]] const std::string& filename) -{ - // no-op -} - -constexpr int GetLED(LED led) -{ - if(led == LED::LED_GPIO_STOP_SCAN) - { - return 20; - } - if(led == LED::LED_GPIO_COPY_DATA) - { - return 16; - } - if(led == LED::LED_GPIO_CONTINOUS_SCANNING) - { - return 21; - } - if(led == LED::BUZZER) - { - return 24; - } - return -1; -} -constexpr int GetButton(BUTTON btn) -{ - if(btn == BUTTON::BUTTON_STOP_SCAN) - { - return 25; - } - if(btn == BUTTON::BUTTON_CONTINOUS_SCANNING) - { - return 8; - } - return -1; -} - -constexpr GPIO::GPIO_PULL GetPULL([[maybe_unused]] BUTTON btn) -{ - return GPIO::GPIO_PULL::DOWN; -} - -[[maybe_unused]] inline const std::array GetLidarSyncGPIO() -{ - return {3, 2}; -} - -[[maybe_unused]] inline const std::array GetLidarSyncPorts() -{ - // The newer version of kernels, has different numbering of ports - // https://github.com/raspberrypi/linux/issues/5667#issuecomment-1772544866 - return {"/dev/ttyAMA2", "/dev/ttyAMA5"}; -}; - -[[maybe_unused]] inline const std::string GetGNSSPort() -{ - // The newer version of kernels, has different numbering of ports - // https://github.com/raspberrypi/linux/issues/5667#issuecomment-1772544866 - return "/dev/ttyAMA3"; -}; - -[[maybe_unused]] inline const LibSerial::BaudRate GetGNSSBaudrate() -{ - return LibSerial::BaudRate::BAUD_38400; -}; - -} // namespace hardware diff --git a/code/hardware_config/mandeye-pro-cm4-bullseye.h b/code/hardware_config/mandeye-pro-cm4-bullseye.h deleted file mode 100644 index 892786d..0000000 --- a/code/hardware_config/mandeye-pro-cm4-bullseye.h +++ /dev/null @@ -1,88 +0,0 @@ -#pragma once - -#include "hardware_common.h" -#ifdef MANDEYE_HARDWARE_CONFIGURED -# error "MANDEYE Hardware were confiured. You included multiple hardware headers!" -#endif - -#define MANDEYE_HARDWARE_CONFIGURED -namespace hardware -{ -#define PISTACHE_SERVER - -constexpr bool Autostart = false; -constexpr bool WaitForLidarSync = false; -constexpr const char* mandeyeHarwareType() -{ - return "MandeyePro"; -} - -constexpr const char* GetGPIOChip() -{ - return "/dev/gpiochip0"; -} - -inline void ReportState([[maybe_unused]] const mandeye::States state) { } - -inline void OnSavedLaz([[maybe_unused]] const std::string& filename) { } - -constexpr int GetLED(LED led) -{ - if(led == LED::LED_GPIO_STOP_SCAN) - { - return 20; - } - if(led == LED::LED_GPIO_COPY_DATA) - { - return 16; - } - if(led == LED::LED_GPIO_CONTINOUS_SCANNING) - { - return 21; - } - if(led == LED::BUZZER) - { - return 24; - } - return -1; -} -constexpr int GetButton(BUTTON btn) -{ - if(btn == BUTTON::BUTTON_STOP_SCAN) - { - return 25; - } - if(btn == BUTTON::BUTTON_CONTINOUS_SCANNING) - { - return 8; - } - return -1; -} - -constexpr GPIO::GPIO_PULL GetPULL([[maybe_unused]] BUTTON btn) -{ - return GPIO::GPIO_PULL::DOWN; -} - -[[maybe_unused]] inline const std::array GetLidarSyncGPIO() -{ - return {3, 2}; -} - -[[maybe_unused]] inline const std::array GetLidarSyncPorts() -{ - return {"/dev/ttyAMA1", // GPIO ID_SD (TXD2) - "/dev/ttyAMA4"}; // GPIO 12 (TXD5) -}; - -[[maybe_unused]] inline const std::string GetGNSSPort() -{ - return "/dev/ttyAMA2"; -}; - -[[maybe_unused]] inline const LibSerial::BaudRate GetGNSSBaudrate() -{ - return LibSerial::BaudRate::BAUD_38400; -}; - -} // namespace hardware diff --git a/code/hardware_config/mandeye-standard-rpi4.h b/code/hardware_config/mandeye-standard-rpi4.h deleted file mode 100644 index aa880bf..0000000 --- a/code/hardware_config/mandeye-standard-rpi4.h +++ /dev/null @@ -1,103 +0,0 @@ -#pragma once - -#include "hardware_common.h" -#ifdef MANDEYE_HARDWARE_CONFIGURED -# error "MANDEYE Hardware were confiured. You included multiple hardware headers!" -#endif - -#define MANDEYE_HARDWARE_CONFIGURED -namespace hardware -{ -#define PISTACHE_SERVER - -constexpr int Offset = 0; -constexpr bool Autostart = false; -constexpr bool WaitForLidarSync = false; -constexpr const char* mandeyeHarwareType() -{ - return "MandeyeStandard"; -} - -constexpr const char* GetGPIOChip() -{ - return "/dev/gpiochip0"; -} - -inline void ReportState([[maybe_unused]] const mandeye::States state) -{ - // no-op -} - -inline void OnSavedLaz([[maybe_unused]] const std::string& filename) -{ - // no-op -} - -constexpr int GetLED(LED led) -{ - - if(led == LED::LED_GPIO_STOP_SCAN) - { - return 26; - } - if(led == LED::LED_GPIO_COPY_DATA) - { - return 19; - } - if(led == LED::LED_GPIO_CONTINOUS_SCANNING) - { - return 13; - } - if(led == LED::LIDAR_SYNC_1) - { - return -1; - } - if(led == LED::LIDAR_SYNC_2) - { - return -1; - } - if(led == LED::BUZZER) - { - return 12; - } - return -1; -} -constexpr int GetButton(BUTTON btn) -{ - if(btn == BUTTON::BUTTON_STOP_SCAN) - { - return 5; - } - if(btn == BUTTON::BUTTON_CONTINOUS_SCANNING) - { - return 6; - } - return -1; -} - -constexpr GPIO::GPIO_PULL GetPULL([[maybe_unused]] BUTTON btn) -{ - return GPIO::GPIO_PULL::UP; -} - -[[maybe_unused]] inline const std::array GetLidarSyncGPIO() -{ - return {}; // No hardware sync -} - -[[maybe_unused]] inline const std::array GetLidarSyncPorts() -{ - return {}; // No hardware sync -}; - -[[maybe_unused]] inline const std::string GetGNSSPort() -{ - return "/dev/S0"; -}; - -[[maybe_unused]] inline const LibSerial::BaudRate GetGNSSBaudrate() -{ - return LibSerial::BaudRate::BAUD_38400; -}; - -} // namespace hardware diff --git a/code/hardware_config/mandeye-standard-rpi5.h b/code/hardware_config/mandeye-standard-rpi5.h deleted file mode 100644 index 8c11176..0000000 --- a/code/hardware_config/mandeye-standard-rpi5.h +++ /dev/null @@ -1,127 +0,0 @@ -#pragma once - -#include "hardware_common.h" -#ifdef MANDEYE_HARDWARE_CONFIGURED -# error "MANDEYE Hardware were confiured. You included multiple hardware headers!" -#endif -#include -#define MANDEYE_HARDWARE_CONFIGURED -namespace hardware -{ -#define PISTACHE_SERVER -#define MANDEYE_BENCHMARK_WRITE_SPEED -#define MANDEYE_COUNTINOUS_SCANNING_STOP_1_CLICK - -/*** - Mandeye standard hardware configuration for Raspberry Pi 5. - - Changes to `/boot/firmware/config.txt`: - ``` -# External access via debug probe: -enable_uart=1 -console=serial0,115200 -dtoverlay=disable-bt - -# Enable /dev/ttyAMA0 for GNSS, connected to GPIO14 and 15, needs -dtparam=uart0 #TX is GPIO14(pin8) and RX is GPIO15(pin10) - -# Standard camera -camera_auto_detect=0 -dtoverlay=imx519,cam0 - -# Cameras for dog system -#camera_auto_detect=0 -#dtoverlay=arducam-pivariety,cam1 -#dtoverlay=ov9281,cam0 - - -# PPS Listen GPIO18 (pin12), PPS simulation pin GPIO17 (pin11) and uses /dev/ttyAMA1 to send fake pps. -dtoverlay=pps-gpio,gpiopin=18 -#TX is GPIO0(pin27) and RX is GPIO1(pin28) -dtparam=uart1 -dtoverlay=uart1 -```` - -and changes to `/boot/firmware/cmdline.txt`: -``` -console=serial0,115200 -``` - * ***/ -constexpr int Offset = 0; -constexpr bool Autostart = false; -constexpr bool WaitForLidarSync = false; -constexpr const char* mandeyeHarwareType() -{ - return "MandeyeStandard"; -} - -constexpr const char* GetGPIOChip() -{ - //for raspberry pi 5 - return "/dev/gpiochip4"; -} - -inline void ReportState([[maybe_unused]] const mandeye::States state) { } - -inline void OnSavedLaz([[maybe_unused]] const std::string& filename) { } - -constexpr int GetLED(LED led) -{ - - if(led == LED::LED_GPIO_STOP_SCAN) - { - return 26; - } - if(led == LED::LED_GPIO_COPY_DATA) - { - return 19; - } - if(led == LED::LED_GPIO_CONTINOUS_SCANNING) - { - return 13; - } - if(led == LED::BUZZER) - { - return 12; - } - return -1; -} -constexpr int GetButton(BUTTON btn) -{ - if(btn == BUTTON::BUTTON_STOP_SCAN) - { - return 5; - } - if(btn == BUTTON::BUTTON_CONTINOUS_SCANNING) - { - return 6; - } - return -1; -} - -constexpr GPIO::GPIO_PULL GetPULL([[maybe_unused]] BUTTON btn) -{ - return GPIO::GPIO_PULL::UP; -} - -[[maybe_unused]] inline const std::array GetLidarSyncGPIO() -{ - return {17}; // GPIO 17 (pin11) is used to send fake -} - -[[maybe_unused]] inline const std::array GetLidarSyncPorts() -{ - return {"/dev/ttyAMA1"}; -}; - -[[maybe_unused]] inline const std::string GetGNSSPort() -{ - return ""; -}; - -[[maybe_unused]] inline const LibSerial::BaudRate GetGNSSBaudrate() -{ - return LibSerial::BaudRate::BAUD_115200; -}; - -} // namespace hardware diff --git a/code/hardware_config/mandeye.h b/code/hardware_config/mandeye.h deleted file mode 100644 index 7760192..0000000 --- a/code/hardware_config/mandeye.h +++ /dev/null @@ -1,16 +0,0 @@ -#pragma once - -#include "compilation_constants.h" -#include "hardware_common.h" - -#ifndef MANDEYE_HARDWARE_HEADER -# error "MANDEYE_HARDWARE_HEADER definition were not configured. You need to include a hardware header!" -#endif -#ifdef MANDEYE_HARDWARE_HEADER -# pragma message("Including hardware header " MANDEYE_HARDWARE_HEADER) -# include MANDEYE_HARDWARE_HEADER -#endif - -#ifndef MANDEYE_HARDWARE_CONFIGURED -# error "MANDEYE Hardware were not configured. You need to include a hardware header!" -#endif diff --git a/code/hardware_config/mandeye_pro.md b/code/hardware_config/mandeye_pro.md index 796e7ab..df91fb0 100644 --- a/code/hardware_config/mandeye_pro.md +++ b/code/hardware_config/mandeye_pro.md @@ -1,86 +1,7 @@ -# Prerequisites -All setup for Mandeye Pro board is done in the same way as for Mandeye board. +# Mandeye Pro CM4 carrier -:bulb: **Note** You need to specify the correct board in the CMake configuration file. For Mandeye Pro board you need to set the `MAND_PRO` variable to `ON`: -```shell -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_PRO:BOOL=ON -make -j4 -``` -# Building Project +Start with the packaged `pro-cm4-bookworm.json` example. The example uses GPIO 3 and 2 for the two FakePPS pulse outputs, `/dev/ttyAMA2` and `/dev/ttyAMA5` for their NMEA streams, and `/dev/ttyAMA3` for a built-in GNSS. Check the carrier wiring and device nodes on the running kernel. A scanner assembled without the built-in receiver uses `"gnss": null`. [Installation and CaveTronic wiring](../../README.md#install-on-a-new-raspberry-pi) +The CM4 can expose additional UARTs through the `uart2`, `uart3`, `uart4` and `uart5` overlays. Use `dtoverlay -h` for the chosen overlay, enable the ones required by the carrier in `/boot/firmware/config.txt`, and reboot before checking the ports. Use the packaged FakePPS service for the output pairs. [PPS and other services](../../doc/accessories.md) -Carrier boards supports number of extra serial ports. To enable them you need to add the following lines to the `/boot/config.txt` file: - -```shell -[all] -enable_uart=1 -dtoverlay=uart2 -dtoverlay=uart3 -dtoverlay=uart4 -dtoverlay=uart5 -``` - -After that you need to reboot the system. - -Mappings of the UARTs to the physical pins are as follows: - - '/dev/ttyS0' - UART0 - GPIO14, GPIO15, not used - - '/dev/ttyAMA1' - hardware sync for Livox - - '/dev/ttyAMA2' - GNSS - - '/dev/ttyAMA3' - hardware sync for Livox - -# Setup synchronization service for Livox - -Create a file `/usr/lib/systemd/system/mandeye_fakepps.service` with content. -Note that you need to adjust your user's name: -``` -[Unit] -Description=MandeyeFakePPS -After=multi-user.target - -[Service] -User=mandeye -ExecStartPre=/bin/sleep 20 -ExecStart=/home/mandeye/mandeye_controller/build/fake_pps -Restart=always - -[Install] -WantedBy=multi-user.target -``` - -Next reload daemons, enable and start the service` -``` -sudo systemctl daemon-reload -sudo systemctl enable mandeye_fakepps.service -sudo systemctl start mandeye_fakepps.service -``` -You can check status of the service with: -```bash -sudo systemctl status mandeye_fakepps.service -``` - -## Ublox -The following config file is used for the Ublox GNSS module, use [U-Center2](https://www.u-blox.com/en/u-center-2) to configure the module. -Config: [mandeye_pro.ucf, for version 24.02, EXTCore 1.00 8d3640 firmware](mandeye_pro.ucf) -## Useful aliases -Add to your `~/.bashrc` file: -```bash -alias mandeye_start="sudo systemctl start mandeye_controller.service" -alias mandeye_stop="sudo systemctl stop mandeye_controller.service" -alias mandeye_status="sudo systemctl status mandeye_controller.service" -alias mandeye_log="journalctl -u mandeye.service" -alias mandeye_fakepps_start="sudo systemctl start mandeye_fakepps.service" -alias mandeye_fakepps_stop="sudo systemctl stop mandeye_fakepps.service" -alias mandeye_fakepps_status="sudo systemctl status mandeye_fakepps.service" -alias mandeye_fakepps_log="journalctl -u mandeye_fakepps.service" -alias GPIO_BUZZER_ON="raspi-gpio set 24 op && raspi-gpio set 24 dh" -alias GPIO_BUZZER_OFF="raspi-gpio set 24 dl" -alias mandeye_test="curl 127.0.0.1:8005/json/status --silent" -alias mandeye_gnss_sattelites="mandeye_test | grep satellites_tracked" -alias mandeye_gnss_data="stty -F /dev/ttyAMA2 38400 cs8 -cstopb -parenb && cat /dev/ttyAMA2" -alias mandeye_gnss_data_speed="stty -F /dev/ttyAMA2 38400 cs8 -cstopb -parenb && cat /dev/ttyAMA2 | pv -r > /dev/null" -``` +For a fitted u-blox receiver, the repository contains settings for firmware 24.02, EXTCore 1.00 8d3640. [Receiver configuration](mandeye_pro.ucf) · [u-center](https://www.u-blox.com/en/u-center-2) diff --git a/code/led_demo.cpp b/code/led_demo.cpp index 848afe3..0c20988 100644 --- a/code/led_demo.cpp +++ b/code/led_demo.cpp @@ -1,21 +1,22 @@ -#include "hardware_config/mandeye.h" #include #include #include #include -int main(int arc, char* argv[]) +int main() +try { + const auto device = hardware::readDeviceConfig(); using namespace hardware; std::cout << "led_demo" << std::endl; - std::cout << mandeyeHarwareType() << std::endl; + std::cout << device.name << std::endl; std::shared_ptr gpioClientPtr; - gpioClientPtr = std::make_shared(false); + gpioClientPtr = std::make_shared(device, false); for(int i = 0; i < 1000; i++) { - std::cout << "iteration " << i + 1 << " of 10" << std::endl; + std::cout << "iteration " << i + 1 << std::endl; std::cout << "LED_GPIO_STOP_SCAN ON" << std::endl; gpioClientPtr->setLed(LED::LED_GPIO_STOP_SCAN, true); std::this_thread::sleep_for(std::chrono::milliseconds(1000)); @@ -47,3 +48,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/lidars/dummy/ButterLidar.cpp b/code/lidars/dummy/ButterLidar.cpp index 512dc7f..9739abc 100644 --- a/code/lidars/dummy/ButterLidar.cpp +++ b/code/lidars/dummy/ButterLidar.cpp @@ -4,6 +4,15 @@ namespace mandeye { +ButterLidar::~ButterLidar() +{ + isDone = true; + if(m_watchThread.joinable()) + { + m_watchThread.join(); + } +} + nlohmann::json ButterLidar::produceStatus() { nlohmann::json data; @@ -78,7 +87,7 @@ void ButterLidar::DataThreadFunction() if(m_bufferIMUPtr) { // Simulate adding IMU data to the buffer - LidarIMU imuData; + LidarIMU imuData{}; imuData.gyro_x = 0.01f; // Example data imuData.gyro_y = 0.02f; imuData.gyro_z = 0.03f; @@ -86,6 +95,7 @@ void ButterLidar::DataThreadFunction() imuData.acc_y = 0.2f; imuData.acc_z = 0.3f; imuData.timestamp = 1234567890; // Example timestamp + imuData.epoch_time = imuData.timestamp; m_bufferIMUPtr->push_back(imuData); } m_recivedPointMessages.fetch_add(1); // Increment the counter for received point messages diff --git a/code/lidars/dummy/ButterLidar.h b/code/lidars/dummy/ButterLidar.h index cea95a7..3f77ee2 100644 --- a/code/lidars/dummy/ButterLidar.h +++ b/code/lidars/dummy/ButterLidar.h @@ -12,7 +12,7 @@ class ButterLidar : public BaseLidarClient { public: ButterLidar() = default; - ~ButterLidar() override = default; + ~ButterLidar() override; nlohmann::json produceStatus() override; diff --git a/code/main.cpp b/code/main.cpp index 424813a..4ce42b7 100644 --- a/code/main.cpp +++ b/code/main.cpp @@ -4,6 +4,7 @@ #include #include #include +#include #include "save_data.h" #include "save_laz.h" @@ -21,12 +22,12 @@ #include #include -#include "hardware_config/mandeye.h" +#include "hardware_config/device_config.h" #include #include #define MANDEYE_LIVOX_LISTEN_IP "192.168.1.5" -#define MANDEYE_LIDAR_SKD "LIVOX_SDK2" +#define DEFAULT_LIDAR_SDK "LIVOX_SDK2" #define MANDEYE_REPO "/media/usb/" #define MANDEYE_GPIO_SIM false #define SERVER_PORT 8003 @@ -41,20 +42,22 @@ namespace mandeye { std::atomic isRunning{true}; std::atomic isLidarError{false}; -std::mutex lidarClientPtrLock; std::shared_ptr lidarClientPtr; std::shared_ptr gnssClientPtr; std::shared_ptr fileSystemClientPtr; std::shared_ptr publisherPtr; -mandeye::LazStats lastFileSaveStats; // updated by savePointcloudData return value -double usbWriteSpeed10Mb = 0.0; -double usbWriteSpeed1Mb = 0.0; +std::mutex lastSaveMutex; +mandeye::LazStats lastFileSaveStats; +std::string lastSaveError; +std::mutex gestureMutex; +std::atomic usbWriteSpeed10Mb = 0.0; +std::atomic usbWriteSpeed1Mb = 0.0; bool disableBuzzer = false; std::string lidarSDKToUse; -nlohmann::json configJson; -mandeye::States app_state{mandeye::States::WAIT_FOR_RESOURCES}; +hardware::DeviceConfig device; +std::atomic app_state{mandeye::States::WAIT_FOR_RESOURCES}; using json = nlohmann::json; @@ -100,17 +103,18 @@ MemInfo readMemInfo() return info; } -std::string produceReport(bool reportUSB = true) +std::string produceReport(bool reportUSB = true, const LazStats* saving = nullptr) { json j; j["name"] = "Mandeye"; j["hash"] = GIT_HASH; j["version"] = MANDEYE_VERSION; - j["hardware"] = MANDEYE_HARDWARE_HEADER; + j["hardware"] = device.name; + j["device_config_path"] = device.path; + j["device_config"] = device.document; j["arch"] = SYSTEM_ARCH; j["lidar_sdk"] = lidarSDKToUse; j["buzzer"] = !disableBuzzer; - j["state"] = StatesToString.at(app_state); j["cpu_temp_c"] = readCpuTemperature(); const auto mem = readMemInfo(); @@ -148,7 +152,12 @@ std::string produceReport(bool reportUSB = true) j["gnss"] = {}; } - j["lastLazStatus"] = lastFileSaveStats.produceStatus(); + { + std::lock_guard lock(lastSaveMutex); + j["state"] = StatesToString.at(app_state); + j["lastLazStatus"] = (saving ? *saving : lastFileSaveStats).produceStatus(); + j["lastSaveError"] = lastSaveError; + } std::ostringstream s; s << std::setw(4) << j; @@ -157,6 +166,7 @@ std::string produceReport(bool reportUSB = true) bool StartScan() { + std::lock_guard lock(gestureMutex); if(app_state == States::IDLE || app_state == States::STOPPED) { app_state = States::STARTING_SCAN; @@ -166,6 +176,7 @@ bool StartScan() } bool StopScan() { + std::lock_guard lock(gestureMutex); if(app_state == States::SCANNING) { app_state = States::STOPPING; @@ -178,6 +189,7 @@ using namespace std::chrono_literals; bool TriggerStopScan() { + std::lock_guard lock(gestureMutex); if(app_state == States::IDLE || app_state == States::STOPPED) { app_state = States::STARTING_STOP_SCAN; @@ -193,6 +205,7 @@ std::chrono::steady_clock::time_point stoppingStage2StartDeadlineChangeLed; bool TriggerContinousScanning() { + std::lock_guard lock(gestureMutex); if(app_state == States::IDLE || app_state == States::STOPPED) { @@ -207,10 +220,11 @@ bool TriggerContinousScanning() } else if(app_state == States::SCANNING) { -#ifdef MANDEYE_COUNTINOUS_SCANNING_STOP_1_CLICK - app_state = States::STOPPING; - return true; -#endif //MANDEYE_COUNTINOUS_SCANNING_STOP_1_CLICK + if(device.operation.stopPresses == 1) + { + app_state = States::STOPPING; + return true; + } app_state = States::STOPPING_STAGE_1; //stoppingStage1Start = std::chrono::steady_clock::now(); stoppingStage1StartDeadline = std::chrono::steady_clock::now() + std::chrono::milliseconds(2000); @@ -248,16 +262,49 @@ bool TriggerContinousScanning() return false; } -void saveStatusData(const std::string& directory, int chunk) +void stopLogging() { - using namespace std::chrono_literals; - char statusName[256]; - snprintf(statusName, 256, "status%04d.json", chunk); - std::filesystem::path lidarFilePath = std::filesystem::path(directory) / std::filesystem::path(statusName); - std::cout << "Savig status to " << lidarFilePath << std::endl; - std::ofstream lidarStream(lidarFilePath); - lidarStream << produceReport(false); - system("sync"); + lidarClientPtr->stopLog(); + if(gnssClientPtr) + gnssClientPtr->stopLog(); +} + +ScanChunk retrieveChunk(bool finishing) +{ + ScanChunk data; + std::tie(data.points, data.imu) = lidarClientPtr->retrieveData(); + if(gnssClientPtr) + { + data.gnss = gnssClientPtr->retrieveData(); + if(!finishing) + data.gnssRaw = gnssClientPtr->retrieveRawData(); + } + if(finishing) + stopLogging(); + data.lidars = lidarClientPtr->getSerialNumberToLidarIdMapping(); + return data; +} + +bool saveChunk(const ScanChunk& data, const std::string& directory, int chunk) +{ + try + { + auto stats = saveScanData(data, directory, chunk, [](const LazStats& stats) { return produceReport(false, &stats); }); + std::lock_guard lock(lastSaveMutex); + lastFileSaveStats = std::move(stats); + } + catch(const std::exception& e) + { + std::scoped_lock lock(gestureMutex, lastSaveMutex); + lastSaveError = e.what(); + lastFileSaveStats = LazStats{}; + app_state = States::USB_IO_ERROR; + std::cerr << "Scan write failed: " << lastSaveError << std::endl; + return false; + } + if(device.operation.beepOnLaz && !disableBuzzer) + gpioClientPtr->beep({50, 100, 50, 100}); + return true; } void stateWatcher() @@ -269,8 +316,7 @@ void stateWatcher() States oldState = States::IDLE; std::string continousScanDirectory; std::string stopScanDirectory; - int chunksInExperimentCS{0}; - int chunksInExperimentSS{0}; + int chunkNumber{0}; int id_manifest = 0; if(stopScanDirectory.empty() && fileSystemClientPtr) @@ -289,16 +335,15 @@ void stateWatcher() { app_state = States::USB_IO_ERROR; } - if(fileSystemClientPtr) + if(fileSystemClientPtr && device.operation.benchmarkUsb) { -#ifdef MANDEYE_BENCHMARK_WRITE_SPEED std::cout << "Benchmarking write speed" << std::endl; mandeye::usbWriteSpeed10Mb = fileSystemClientPtr->BenchmarkWriteSpeed("benchmark10.bin", 10); mandeye::usbWriteSpeed1Mb = fileSystemClientPtr->BenchmarkWriteSpeed("benchmark1.bin", 1); std::cout << "Benchmarking write speed done" << std::endl; -#endif } + unsigned usbErrorObservations = 0; while(isRunning) { if(mandeye::publisherPtr) @@ -311,8 +356,6 @@ void stateWatcher() } oldState = app_state; - // call configured callback - hardware::ReportState(app_state); if(app_state == States::LIDAR_ERROR) { if(mandeye::gpioClientPtr) @@ -334,6 +377,11 @@ void stateWatcher() } if(app_state == States::USB_IO_ERROR) { + if(device.operation.restartOnUsbError && ++usbErrorObservations >= 3) + { + std::cerr << "USB_IO_ERROR on three observations; restarting controller" << std::endl; + std::_Exit(EXIT_FAILURE); + } if(mandeye::gpioClientPtr) { mandeye::gpioClientPtr->setLed(hardware::LED::LED_GPIO_STOP_SCAN, false); @@ -359,14 +407,11 @@ void stateWatcher() } std::this_thread::sleep_for(100ms); - std::lock_guard l2(gpioClientPtrLock); - // check for data flow bool isLidarDatFlow = false; for(int i = 0; i < 60; i++) { std::this_thread::sleep_for(1000ms); - std::lock_guard l1(lidarClientPtrLock); if(lidarClientPtr && lidarClientPtr->isDataFlowing()) { isLidarDatFlow = true; @@ -379,13 +424,12 @@ void stateWatcher() isLidarError.store(true); } // check if lidar - if(hardware::WaitForLidarSync) + if(device.operation.waitForLidarSync) { bool isLidarSynced = false; for(int i = 0; i < 60; i++) { std::this_thread::sleep_for(1000ms); - std::lock_guard l(lidarClientPtrLock); if(lidarClientPtr && lidarClientPtr->isSynced()) { isLidarSynced = true; @@ -401,7 +445,8 @@ void stateWatcher() if(mandeye::gpioClientPtr && mandeye::fileSystemClientPtr) { - app_state = States::IDLE; + // Consume autostart once, on the initial transition out of WAIT_FOR_RESOURCES. + app_state = device.operation.autostartRecording && !isLidarError ? States::STARTING_SCAN : States::IDLE; // play hello beep if(!disableBuzzer) { @@ -426,10 +471,6 @@ void stateWatcher() mandeye::gpioClientPtr->setLed(hardware::LED::LED_GPIO_CONTINOUS_SCANNING, false); } std::this_thread::sleep_for(100ms); - if(hardware::Autostart && !isLidarError) - { - app_state = States::STARTING_SCAN; - } } else if(app_state == States::STARTING_SCAN) { @@ -495,132 +536,85 @@ void stateWatcher() chunkStart = std::chrono::steady_clock::now(); - auto [lidarBuffer, imuBuffer] = lidarClientPtr->retrieveData(); - std::deque gnssBuffer; - std::deque gnssRawBuffer; - - if(gnssClientPtr) - { - gnssBuffer = gnssClientPtr->retrieveData(); - gnssRawBuffer = gnssClientPtr->retrieveRawData(); - } - if(continousScanDirectory == "") - { - app_state = States::USB_IO_ERROR; - } + if(saveChunk(retrieveChunk(false), continousScanDirectory, chunkNumber)) + ++chunkNumber; else - { - auto [fn, saveStats] = savePointcloudData(lidarBuffer, continousScanDirectory, chunksInExperimentCS + chunksInExperimentSS); - if(saveStats) - lastFileSaveStats = *saveStats; - saveImuData(imuBuffer, continousScanDirectory, chunksInExperimentCS + chunksInExperimentSS); - saveStatusData(continousScanDirectory, chunksInExperimentCS + chunksInExperimentSS); - auto lidarList = lidarClientPtr->getSerialNumberToLidarIdMapping(); - saveLidarList(lidarList, continousScanDirectory, chunksInExperimentCS + chunksInExperimentSS); - if(gnssClientPtr) - { - saveGnssData(gnssBuffer, continousScanDirectory, chunksInExperimentCS + chunksInExperimentSS); - saveGnssRawData(gnssRawBuffer, continousScanDirectory, chunksInExperimentCS + chunksInExperimentSS); - } - - mandeye::gpioClientPtr->setLed(hardware::LED::LED_GPIO_COPY_DATA, false); - chunksInExperimentCS++; - } + stopLogging(); + mandeye::gpioClientPtr->setLed(hardware::LED::LED_GPIO_COPY_DATA, false); } - if(app_state == States::STOPPING_STAGE_1) { - std::cout << "app_state == States::STOPPING_STAGE_1" << std::endl; + std::lock_guard lock(gestureMutex); + if(app_state == States::STOPPING_STAGE_1) + { + std::cout << "app_state == States::STOPPING_STAGE_1" << std::endl; - const auto now = std::chrono::steady_clock::now(); + const auto now = std::chrono::steady_clock::now(); - if(now > stoppingStage1StartDeadlineChangeLed) - { - static bool led_1 = true; + if(now > stoppingStage1StartDeadlineChangeLed) + { + static bool led_1 = true; - mandeye::gpioClientPtr->setLed(hardware::LED::LED_GPIO_CONTINOUS_SCANNING, led_1); + mandeye::gpioClientPtr->setLed(hardware::LED::LED_GPIO_CONTINOUS_SCANNING, led_1); - led_1 = !led_1; + led_1 = !led_1; - stoppingStage1StartDeadlineChangeLed = std::chrono::steady_clock::now() + std::chrono::milliseconds(500); - } + stoppingStage1StartDeadlineChangeLed = std::chrono::steady_clock::now() + std::chrono::milliseconds(500); + } - if(now > stoppingStage1StartDeadline) - { - app_state = States::SCANNING; + if(now > stoppingStage1StartDeadline) + { + app_state = States::SCANNING; + } } - } - if(app_state == States::STOPPING_STAGE_2) - { - std::cout << "app_state == States::STOPPING_STAGE_2" << std::endl; + if(app_state == States::STOPPING_STAGE_2) + { + std::cout << "app_state == States::STOPPING_STAGE_2" << std::endl; - const auto now = std::chrono::steady_clock::now(); + const auto now = std::chrono::steady_clock::now(); - if(now > stoppingStage2StartDeadlineChangeLed) - { - static bool led_2 = true; + if(now > stoppingStage2StartDeadlineChangeLed) + { + static bool led_2 = true; - mandeye::gpioClientPtr->setLed(hardware::LED::LED_GPIO_CONTINOUS_SCANNING, led_2); + mandeye::gpioClientPtr->setLed(hardware::LED::LED_GPIO_CONTINOUS_SCANNING, led_2); - led_2 = !led_2; + led_2 = !led_2; - stoppingStage2StartDeadlineChangeLed = std::chrono::steady_clock::now() + std::chrono::milliseconds(250); - } + stoppingStage2StartDeadlineChangeLed = std::chrono::steady_clock::now() + std::chrono::milliseconds(250); + } - if(now > stoppingStage2StartDeadline) - { - app_state = States::SCANNING; + if(now > stoppingStage2StartDeadline) + { + app_state = States::SCANNING; + } } } - std::this_thread::sleep_for(20ms); } - else if(app_state == States::STOPPING) + else if(app_state == States::STOPPING || app_state == States::STOPING_STOP_SCAN) { - mandeye::gpioClientPtr->setLed(hardware::LED::LED_GPIO_CONTINOUS_SCANNING, true); + const bool stationary = app_state == States::STOPING_STOP_SCAN; mandeye::gpioClientPtr->setLed(hardware::LED::LED_GPIO_COPY_DATA, true); - - auto [lidarBuffer, imuBuffer] = lidarClientPtr->retrieveData(); - std::deque gnssData; - lidarClientPtr->stopLog(); - if(gnssClientPtr) - { - gnssData = gnssClientPtr->retrieveData(); - gnssClientPtr->stopLog(); - } - - for(int i = 0; i < 20; i++) + auto data = retrieveChunk(true); + if(!stationary) { + for(int i = 0; i < 20; i++) + { + mandeye::gpioClientPtr->setLed(hardware::LED::LED_GPIO_CONTINOUS_SCANNING, true); + std::this_thread::sleep_for(50ms); + mandeye::gpioClientPtr->setLed(hardware::LED::LED_GPIO_CONTINOUS_SCANNING, false); + std::this_thread::sleep_for(50ms); + } mandeye::gpioClientPtr->setLed(hardware::LED::LED_GPIO_CONTINOUS_SCANNING, true); - std::this_thread::sleep_for(50ms); - mandeye::gpioClientPtr->setLed(hardware::LED::LED_GPIO_CONTINOUS_SCANNING, false); - std::this_thread::sleep_for(50ms); } - - mandeye::gpioClientPtr->setLed(hardware::LED::LED_GPIO_CONTINOUS_SCANNING, true); - mandeye::gpioClientPtr->setLed(hardware::LED::LED_GPIO_COPY_DATA, true); - - if(continousScanDirectory.empty()) - { - app_state = States::USB_IO_ERROR; - } - else + const auto& directory = stationary ? stopScanDirectory : continousScanDirectory; + if(saveChunk(data, directory, chunkNumber)) { - auto [fn, saveStats] = savePointcloudData(lidarBuffer, continousScanDirectory, chunksInExperimentCS + chunksInExperimentSS); - if(saveStats) - lastFileSaveStats = *saveStats; - saveImuData(imuBuffer, continousScanDirectory, chunksInExperimentCS + chunksInExperimentSS); - saveStatusData(continousScanDirectory, chunksInExperimentCS + chunksInExperimentSS); - auto lidarList = lidarClientPtr->getSerialNumberToLidarIdMapping(); - saveLidarList(lidarList, continousScanDirectory, chunksInExperimentCS + chunksInExperimentSS); - - if(gnssClientPtr) - { - saveGnssData(gnssData, continousScanDirectory, chunksInExperimentCS + chunksInExperimentSS); - } - chunksInExperimentCS++; + ++chunkNumber; mandeye::gpioClientPtr->setLed(hardware::LED::LED_GPIO_COPY_DATA, false); + mandeye::gpioClientPtr->setLed(hardware::LED::LED_GPIO_STOP_SCAN, false); app_state = States::IDLE; } } @@ -682,50 +676,6 @@ void stateWatcher() app_state = States::STOPING_STOP_SCAN; } } - else if(app_state == States::STOPING_STOP_SCAN) - { - if(gpioClientPtr) - { - mandeye::gpioClientPtr->setLed(hardware::LED::LED_GPIO_COPY_DATA, true); - } - auto [lidarBuffer, imuBuffer] = lidarClientPtr->retrieveData(); - std::deque gnssData; - lidarClientPtr->stopLog(); - if(gnssClientPtr) - { - gnssData = gnssClientPtr->retrieveData(); - gnssClientPtr->stopLog(); - } - if(stopScanDirectory.empty()) - { - app_state = States::USB_IO_ERROR; - } - else - { - auto [fn, saveStats] = savePointcloudData(lidarBuffer, stopScanDirectory, chunksInExperimentCS + chunksInExperimentSS); - if(saveStats) - lastFileSaveStats = *saveStats; - saveImuData(imuBuffer, stopScanDirectory, chunksInExperimentCS + chunksInExperimentSS); - saveStatusData(stopScanDirectory, chunksInExperimentCS + chunksInExperimentSS); - - auto lidarList = lidarClientPtr->getSerialNumberToLidarIdMapping(); - saveLidarList(lidarList, stopScanDirectory, chunksInExperimentCS + chunksInExperimentSS); - - if(gnssClientPtr) - { - saveGnssData(gnssData, stopScanDirectory, chunksInExperimentCS + chunksInExperimentSS); - } - chunksInExperimentSS++; - - if(gpioClientPtr) - { - mandeye::gpioClientPtr->setLed(hardware::LED::LED_GPIO_COPY_DATA, false); - mandeye::gpioClientPtr->setLed(hardware::LED::LED_GPIO_STOP_SCAN, false); - } - - app_state = States::IDLE; - } - } } } } // namespace mandeye @@ -757,9 +707,8 @@ bool getEnvBool(const std::string& env, bool def) } } // namespace utils -#ifdef PISTACHE_SERVER -# include "web_page.h" -# include +#include "web_page.h" +#include using namespace Pistache; struct PistacheServerHandler : public Http::Handler @@ -805,109 +754,84 @@ struct PistacheServerHandler : public Http::Handler writer.send(Http::Code::Ok, gINDEX_HTMData); } }; -#endif int main(int argc, char** argv) +try { + using namespace std::chrono_literals; + const bool validate = argc >= 2 && std::string(argv[1]) == "--validate-config"; + if(argc > 3 || (argc > 1 && !validate)) + throw std::runtime_error("Usage: control_program [--validate-config [PATH]]"); + mandeye::device = hardware::readDeviceConfig(argc == 3 ? argv[2] : hardware::DeviceConfigPath); + if(validate) + { + std::cout << mandeye::device.document.dump(2) << std::endl; + return 0; + } - std::cout << "program: " << argv[0] << " " << MANDEYE_VERSION << " " << MANDEYE_HARDWARE_HEADER << std::endl; - Address addr(Ipv4::any(), SERVER_PORT); - - mandeye::disableBuzzer = utils::getEnvBool("MANDEYE_DISABLE_BUZZER", false); - mandeye::lidarSDKToUse = utils::getEnvString("MANDEYE_LIDAR_SDK", MANDEYE_LIDAR_SKD); - - std::cout << "Buzzer is " << (mandeye::disableBuzzer ? "disabled" : "enabled") << std::endl; - std::cout << "Lidar SDK to use (from MANDEYE_LIDAR_SDK env): " << mandeye::lidarSDKToUse << std::endl; - - auto server = std::make_shared(addr); - std::thread http_thread1([&]() { - auto opts = Http::Endpoint::options().threads(1).flags(Tcp::Options::ReuseAddr); - server->init(opts); - server->setHandler(Http::make_handler()); - server->serve(); - }); - + std::cout << "program: " << argv[0] << " " << MANDEYE_VERSION << " " << GIT_HASH << " " << mandeye::device.name << std::endl; + mandeye::disableBuzzer = utils::getEnvBool("MANDEYE_DISABLE_BUZZER", false) || !mandeye::device.leds.count(hardware::LED::BUZZER); mandeye::fileSystemClientPtr = std::make_shared(utils::getEnvString("MANDEYE_REPO", MANDEYE_REPO)); - mandeye::configJson = mandeye::fileSystemClientPtr->GetConfig(); - if(mandeye::configJson.is_object() && mandeye::configJson.contains("lidar_sdk")) + const auto acquisition = mandeye::fileSystemClientPtr->GetConfig(); + mandeye::lidarSDKToUse = utils::getEnvString("MANDEYE_LIDAR_SDK", DEFAULT_LIDAR_SDK); + if(acquisition.contains("lidar_sdk")) + { + if(!acquisition.at("lidar_sdk").is_string()) + throw std::runtime_error("mandeye_config.json: /lidar_sdk: expected a string"); + mandeye::lidarSDKToUse = acquisition.at("lidar_sdk").get(); + } + std::cout << "Lidar SDK: " << mandeye::lidarSDKToUse << std::endl; + mandeye::lidarClientPtr = mandeye::createLidarClient(mandeye::lidarSDKToUse, acquisition); + if(!mandeye::lidarClientPtr) + throw std::runtime_error("Could not create " + mandeye::lidarSDKToUse + " lidar client"); + const bool sim = utils::getEnvBool("MANDEYE_GPIO_SIM", MANDEYE_GPIO_SIM); + mandeye::gpioClientPtr = std::make_shared(mandeye::device, sim); + if(!mandeye::lidarClientPtr->startListener(utils::getEnvString("MANDEYE_LIVOX_LISTEN_IP", MANDEYE_LIVOX_LISTEN_IP))) + mandeye::isLidarError.store(true); + + if(mandeye::device.gnss) { - mandeye::lidarSDKToUse = mandeye::configJson["lidar_sdk"].get(); + const auto& gnss = *mandeye::device.gnss; + mandeye::gnssClientPtr = std::make_shared(); + mandeye::gnssClientPtr->SetTimeStampProvider(mandeye::lidarClientPtr); + mandeye::gnssClientPtr->setDataCallback([](const minmea_sentence_gga& gga) { + if(gga.fix_quality > 0 && gga.satellites_tracked > 5 && !mandeye::disableBuzzer) + mandeye::gpioClientPtr->beep({10}); + }); + mandeye::gnssClientPtr->startListener(gnss.uart, static_cast(hardware::serialSpeed(gnss.baud))); } - std::cout << "Lidar SDK to use from config: " << mandeye::lidarSDKToUse << std::endl; + mandeye::publisherPtr = std::make_shared(mandeye::lidarClientPtr); - std::thread thLivox([&]() { - { - std::lock_guard l1(mandeye::lidarClientPtrLock); - mandeye::lidarClientPtr = mandeye::createLidarClient(mandeye::lidarSDKToUse, mandeye::configJson); - } - if(!mandeye::lidarClientPtr->startListener(utils::getEnvString("MANDEYE_LIVOX_LISTEN_IP", MANDEYE_LIVOX_LISTEN_IP))) + for(int i = 0; i < 3; i++) + { + for(auto led : {hardware::LED::LED_GPIO_STOP_SCAN, hardware::LED::LED_GPIO_CONTINOUS_SCANNING, hardware::LED::LED_GPIO_COPY_DATA}) { - mandeye::isLidarError.store(true); + mandeye::gpioClientPtr->setLed(led, true); + std::this_thread::sleep_for(100ms); + mandeye::gpioClientPtr->setLed(led, false); + std::this_thread::sleep_for(100ms); } + } + mandeye::gpioClientPtr->addButtonCallback(hardware::BUTTON::BUTTON_STOP_SCAN, "BUTTON_STOP_SCAN", mandeye::TriggerStopScan); + mandeye::gpioClientPtr->addButtonCallback( + hardware::BUTTON::BUTTON_CONTINOUS_SCANNING, "BUTTON_CONTINOUS_SCANNING", mandeye::TriggerContinousScanning); - // intialize in this thread to prevent initialization fiasco - const std::string portName = hardware::GetGNSSPort(); - const auto baud = hardware::GetGNSSBaudrate(); - if(!portName.empty()) - { - mandeye::gnssClientPtr = std::make_shared(); - mandeye::gnssClientPtr->SetTimeStampProvider(mandeye::lidarClientPtr); - mandeye::gnssClientPtr->startListener(portName, baud); - - // set callback - mandeye::gnssClientPtr->setDataCallback([&](const minmea_sentence_gga& gga) { - if(mandeye::gpioClientPtr && gga.fix_quality > 0 && gga.satellites_tracked > 5 && - !mandeye::disableBuzzer) // if any fix quality is available - { - std::lock_guard l2(mandeye::gpioClientPtrLock); - mandeye::gpioClientPtr->setLed(hardware::LED::BUZZER, true); - std::this_thread::sleep_for(std::chrono::milliseconds(10)); - mandeye::gpioClientPtr->setLed(hardware::LED::BUZZER, false); - } - }); - } - // start zeromq publisher - mandeye::publisherPtr = std::make_shared(); - mandeye::publisherPtr->SetTimeStampProvider(mandeye::lidarClientPtr); + Address addr(Ipv4::any(), SERVER_PORT); + Http::Endpoint server(addr); + server.init(Http::Endpoint::options().threads(1).flags(Tcp::Options::ReuseAddr)); + server.setHandler(Http::make_handler()); + server.serveThreaded(); + std::thread thStateMachine(mandeye::stateWatcher); +#ifdef TRACY_ENABLE + std::thread thProfile([]() { while(mandeye::isRunning) { - std::this_thread::sleep_for(std::chrono::milliseconds(100)); - auto bufferSize = mandeye::lidarClientPtr->GetBufferSize(); - TracyPlot("bufferSize", double(bufferSize) / 1e6); - } - }); - - std::thread thStateMachine([&]() { mandeye::stateWatcher(); }); - - std::thread thGpio([&]() { - std::lock_guard l2(mandeye::gpioClientPtrLock); - using namespace std::chrono_literals; - const bool simMode = utils::getEnvBool("MANDEYE_GPIO_SIM", MANDEYE_GPIO_SIM); - - std::cout << "MANDEYE_GPIO_SIM : " << simMode << std::endl; - mandeye::gpioClientPtr = std::make_shared(simMode); - for(int i = 0; i < 3; i++) - { - mandeye::gpioClientPtr->setLed(hardware::LED::LED_GPIO_STOP_SCAN, true); - std::this_thread::sleep_for(100ms); - mandeye::gpioClientPtr->setLed(hardware::LED::LED_GPIO_STOP_SCAN, false); - std::this_thread::sleep_for(100ms); - - mandeye::gpioClientPtr->setLed(hardware::LED::LED_GPIO_CONTINOUS_SCANNING, true); - std::this_thread::sleep_for(100ms); - mandeye::gpioClientPtr->setLed(hardware::LED::LED_GPIO_CONTINOUS_SCANNING, false); - std::this_thread::sleep_for(100ms); - - mandeye::gpioClientPtr->setLed(hardware::LED::LED_GPIO_COPY_DATA, true); - std::this_thread::sleep_for(100ms); - mandeye::gpioClientPtr->setLed(hardware::LED::LED_GPIO_COPY_DATA, false); std::this_thread::sleep_for(100ms); + const auto bufferSize = mandeye::lidarClientPtr->GetBufferSize(); + TracyPlot("bufferSize", double(bufferSize) / 1e6); } - std::cout << "GPIO Init done" << std::endl; - mandeye::gpioClientPtr->addButtonCallback(hardware::BUTTON::BUTTON_STOP_SCAN, "BUTTON_STOP_SCAN", [&]() { mandeye::TriggerStopScan(); }); - mandeye::gpioClientPtr->addButtonCallback( - hardware::BUTTON::BUTTON_CONTINOUS_SCANNING, "BUTTON_CONTINOUS_SCANNING", [&]() { mandeye::TriggerContinousScanning(); }); }); +#endif while(mandeye::isRunning) { @@ -936,16 +860,15 @@ int main(int argc, char** argv) } } - server->shutdown(); - http_thread1.join(); - std::cout << "joining thStateMachine" << std::endl; + server.shutdown(); thStateMachine.join(); - - std::cout << "joining thLivox" << std::endl; - thLivox.join(); - - std::cout << "joining thGpio" << std::endl; - thGpio.join(); - std::cout << "Done" << std::endl; +#ifdef TRACY_ENABLE + thProfile.join(); +#endif return 0; } +catch(const std::exception& e) +{ + std::cerr << e.what() << std::endl; + return 1; +} diff --git a/code/publisher.cpp b/code/publisher.cpp index 35e3d82..76199f2 100644 --- a/code/publisher.cpp +++ b/code/publisher.cpp @@ -2,12 +2,13 @@ namespace mandeye { -Publisher::Publisher() +Publisher::Publisher(std::shared_ptr provider) : m_context(1) , m_publisher(m_context, ZMQ_PUB) { m_publisher.bind("tcp://*:5556"); m_publisher.setsockopt(ZMQ_CONFLATE, 1); // Keep only the latest task + SetTimeStampProvider(std::move(provider)); m_thread = std::thread(&Publisher::worker, this); } Publisher::~Publisher() diff --git a/code/publisher.h b/code/publisher.h index 4ea313c..767aa63 100644 --- a/code/publisher.h +++ b/code/publisher.h @@ -12,7 +12,7 @@ class Publisher : public mandeye_utils::TimeStampReceiver public: std::string_view ContinuesMode = "ContinuesMode"; std::string_view StopScanMode = "ChunkedMode"; - Publisher(); + explicit Publisher(std::shared_ptr provider); ~Publisher(); Publisher(const Publisher&) = delete; Publisher& operator=(const Publisher&) = delete; diff --git a/code/save_data.cpp b/code/save_data.cpp index fbab8c5..dfc5708 100644 --- a/code/save_data.cpp +++ b/code/save_data.cpp @@ -1,125 +1,79 @@ #include "save_data.h" -#include "hardware_config/mandeye.h" -#include "save_laz.h" +#include #include -#include +#include #include -#include +#include #include -#include +#include +#include namespace mandeye { - -std::pair> savePointcloudData(LidarPointsBufferPtr buffer, const std::string& directory, int chunk) +namespace { - using namespace std::chrono_literals; - char lidarName[256]; - - const auto start = std::chrono::steady_clock::now(); - snprintf(lidarName, 256, "lidar%04d.laz", chunk); - std::filesystem::path lidarFilePath = std::filesystem::path(directory) / std::filesystem::path(lidarName); - std::cout << "Savig lidar buffer of size " << buffer->size() << " to " << lidarFilePath << std::endl; - auto saveStatus = saveLaz(lidarFilePath.string(), buffer); - - system("sync"); - const auto end = std::chrono::steady_clock::now(); - const std::chrono::duration elapsed_seconds = end - start; - if(saveStatus) - { - saveStatus->m_saveDurationSec2 = elapsed_seconds.count(); - hardware::OnSavedLaz(lidarFilePath); - } - else - { - std::cout << "Error saving laz file " << lidarFilePath << std::endl; - } - return {lidarFilePath.string(), saveStatus}; -} - -void saveLidarList(const std::unordered_map& lidars, const std::string& directory, int chunk) +template +void writeFile(const std::filesystem::path& path, Write write) { - using namespace std::chrono_literals; - char lidarName[256]; - snprintf(lidarName, 256, "lidar%04d.sn", chunk); - std::filesystem::path lidarFilePath = std::filesystem::path(directory) / std::filesystem::path(lidarName); - std::cout << "Savig lidar list of size " << lidars.size() << " to " << lidarFilePath << std::endl; - - std::ofstream lidarStream(lidarFilePath); - for(const auto& [id, sn] : lidars) - { - lidarStream << id << " " << sn << "\n"; - } - system("sync"); - return; + std::ofstream out(path); + if(!out) + throw std::runtime_error(path.string() + ": cannot open for writing"); + write(out); + out.close(); + if(!out) + throw std::runtime_error(path.string() + ": write or close failed"); } +} // namespace -void saveImuData(LidarIMUBufferPtr buffer, const std::string& directory, int chunk) +LazStats saveScanData(const ScanChunk& data, + const std::filesystem::path& directory, + int chunk, + const std::function& statusReport) { - using namespace std::chrono_literals; - char lidarName[256]; - snprintf(lidarName, 256, "imu%04d.csv", chunk); - std::filesystem::path lidarFilePath = std::filesystem::path(directory) / std::filesystem::path(lidarName); - std::cout << "Savig imu buffer of size " << buffer->size() << " to " << lidarFilePath << std::endl; - std::ofstream lidarStream(lidarFilePath.c_str()); - lidarStream << "timestamp gyroX gyroY gyroZ accX accY accZ imuId timestampUnix\n"; - std::stringstream ss; + auto closeDirectory = [](DIR* handle) { closedir(handle); }; + std::unique_ptr dir(opendir(directory.c_str()), closeDirectory); + if(!dir) + throw std::system_error(errno, std::generic_category(), "opening scan directory " + directory.string()); + auto syncDirectory = [&]() { + if(syncfs(dirfd(dir.get())) < 0) + throw std::system_error(errno, std::generic_category(), "syncing scan directory " + directory.string()); + }; + std::ostringstream number; + number << std::setfill('0') << std::setw(4) << chunk; + auto file = [&](const char* prefix, const char* extension) { return directory / (prefix + number.str() + extension); }; - for(const auto& p : *buffer) - { - if(p.timestamp > 0) + const auto start = std::chrono::steady_clock::now(); + const auto lidar = file("lidar", ".laz"); + auto stats = saveLaz(lidar.string(), data.points); + if(!stats) + throw std::runtime_error(lidar.string() + ": could not write LAZ"); + syncDirectory(); + stats->m_saveDurationSec2 = std::chrono::duration(std::chrono::steady_clock::now() - start).count(); + + writeFile(file("imu", ".csv"), [&](std::ostream& out) { + out << "timestamp gyroX gyroY gyroZ accX accY accZ imuId timestampUnix\n"; + for(const auto& p : *data.imu) { - ss << p.timestamp << " " << p.gyro_x << " " << p.gyro_y << " " << p.gyro_z << " " << p.acc_x << " " << p.acc_y << " " << p.acc_z << " " - << p.laser_id << " " << p.epoch_time << "\n"; + if(p.timestamp > 0) + out << p.timestamp << " " << p.gyro_x << " " << p.gyro_y << " " << p.gyro_z << " " << p.acc_x << " " << p.acc_y << " " << p.acc_z + << " " << p.laser_id << " " << p.epoch_time << "\n"; } - } - lidarStream << ss.rdbuf(); - - lidarStream.close(); - system("sync"); - return; -} - -void saveGnssData(std::deque& buffer, const std::string& directory, int chunk) -{ - using namespace std::chrono_literals; - char lidarName[256]; - snprintf(lidarName, 256, "gnss%04d.gnss", chunk); - std::filesystem::path lidarFilePath = std::filesystem::path(directory) / std::filesystem::path(lidarName); - std::cout << "Savig gnss buffer of size " << buffer.size() << " to " << lidarFilePath << std::endl; - std::ofstream lidarStream(lidarFilePath.c_str()); - std::stringstream ss; - - for(const auto& p : buffer) - { - ss << p; - } - lidarStream << ss.rdbuf(); - - lidarStream.close(); - system("sync"); - return; -} - -void saveGnssRawData(std::deque& buffer, const std::string& directory, int chunk) -{ - using namespace std::chrono_literals; - char lidarName[256]; - snprintf(lidarName, 256, "gnss%04d.nmea", chunk); - std::filesystem::path lidarFilePath = std::filesystem::path(directory) / std::filesystem::path(lidarName); - std::cout << "Savig gnss raw buffer of size " << buffer.size() << " to " << lidarFilePath << std::endl; - std::ofstream lidarStream(lidarFilePath.c_str()); - std::stringstream ss; - - for(const auto& p : buffer) - { - ss << p; - } - lidarStream << ss.rdbuf(); - - lidarStream.close(); - system("sync"); - return; + }); + writeFile(file("lidar", ".sn"), [&](std::ostream& out) { + for(const auto& [id, sn] : data.lidars) + out << id << " " << sn << "\n"; + }); + auto writeGnss = [&](const auto& lines, const char* extension) { + if(lines) + writeFile(file("gnss", extension), [&](std::ostream& out) { + for(const auto& line : *lines) + out << line; + }); + }; + writeGnss(data.gnss, ".gnss"); + writeGnss(data.gnssRaw, ".nmea"); + writeFile(file("status", ".json"), [&](std::ostream& out) { out << statusReport(*stats); }); + syncDirectory(); + return *stats; } - -} // namespace mandeye \ No newline at end of file +} // namespace mandeye diff --git a/code/save_data.h b/code/save_data.h index 468957e..edfe7f7 100644 --- a/code/save_data.h +++ b/code/save_data.h @@ -1,16 +1,27 @@ #pragma once -#include "lidars/BaseLidarClient.h" #include "save_laz.h" #include +#include +#include #include #include #include namespace mandeye { -std::pair> savePointcloudData(LidarPointsBufferPtr buffer, const std::string& directory, int chunk); -void saveLidarList(const std::unordered_map& lidars, const std::string& directory, int chunk); -void saveImuData(LidarIMUBufferPtr buffer, const std::string& directory, int chunk); -void saveGnssData(std::deque& buffer, const std::string& directory, int chunk); -void saveGnssRawData(std::deque& buffer, const std::string& directory, int chunk); -} // namespace mandeye \ No newline at end of file +struct ScanChunk +{ + LidarPointsBufferPtr points; + LidarIMUBufferPtr imu; + std::unordered_map lidars; + std::optional> gnss; + std::optional> gnssRaw; +}; + +// Returns only after the LAZ and its accompanying files have been written and synced. +// The saved status describes this chunk before its result is published to the live panel. +LazStats saveScanData(const ScanChunk& data, + const std::filesystem::path& directory, + int chunk, + const std::function& statusReport); +} // namespace mandeye diff --git a/code/save_laz.cpp b/code/save_laz.cpp index 9bf8571..8b2f42d 100644 --- a/code/save_laz.cpp +++ b/code/save_laz.cpp @@ -1,4 +1,5 @@ #include "save_laz.h" +#include #include #include #include @@ -56,6 +57,13 @@ std::optional mandeye::saveLaz(const std::string& filename, L std::cout << "processing: " << filename << "points " << buffer->size() << std::endl; + std::ofstream stream(filename, std::ios::binary); + if(!stream) + { + std::cerr << "Cannot open LAZ file " << filename << std::endl; + return nullopt; + } + laszip_POINTER laszip_writer; if(laszip_create(&laszip_writer)) { @@ -63,6 +71,8 @@ std::optional mandeye::saveLaz(const std::string& filename, L return nullopt; } + std::unique_ptr writer(laszip_writer, laszip_destroy); + // get a pointer to the header of the writer so we can populate it laszip_header* header; @@ -120,12 +130,14 @@ std::optional mandeye::saveLaz(const std::string& filename, L // open the writer laszip_BOOL compress = (strstr(filename.c_str(), ".laz") != 0); const auto start = std::chrono::high_resolution_clock::now(); - if(laszip_open_writer(laszip_writer, filename.c_str(), compress)) + if(laszip_open_writer_stream(laszip_writer, stream, compress, false)) { fprintf(stderr, "DLL ERROR: opening laszip writer for '%s'\n", filename.c_str()); return nullopt; } + std::unique_ptr openWriter(laszip_writer, laszip_close_writer); + fprintf(stderr, "writing file '%s' %scompressed\n", filename.c_str(), (compress ? "" : "un")); // get a pointer to the point of the writer that we will populate and write @@ -179,15 +191,21 @@ std::optional mandeye::saveLaz(const std::string& filename, L stats.m_pointsCount = p_count; // close the writer - if(laszip_close_writer(laszip_writer)) + if(laszip_close_writer(openWriter.release())) { fprintf(stderr, "DLL ERROR: closing laszip writer\n"); return nullopt; } - // destroy the writer + // LASzip leaves the supplied stream open. Check its final buffered write and close. + stream.close(); + if(!stream) + { + std::cerr << "Error closing LAZ file " << filename << std::endl; + return nullopt; + } - if(laszip_destroy(laszip_writer)) + if(laszip_destroy(writer.release())) { fprintf(stderr, "DLL ERROR: destroying laszip writer\n"); return nullopt; @@ -199,12 +217,9 @@ std::optional mandeye::saveLaz(const std::string& filename, L const std::chrono::duration elapsed_seconds = end - start; stats.m_saveDurationSec1 = elapsed_seconds.count(); - if(std::filesystem::exists(filename)) - { - std::uintmax_t size = std::filesystem::file_size(filename); - stats.m_sizeMb = static_cast(size) / (1024 * 1024); - TracyPlot("laz_file_size_mb", (double)stats.m_sizeMb); - } + std::uintmax_t size = std::filesystem::file_size(filename); + stats.m_sizeMb = static_cast(size) / (1024 * 1024); + TracyPlot("laz_file_size_mb", (double)stats.m_sizeMb); TracyPlot("laz_save_duration_sec", (double)stats.m_saveDurationSec1); return stats; diff --git a/doc/accessories.md b/doc/accessories.md new file mode 100644 index 0000000..e0955f6 --- /dev/null +++ b/doc/accessories.md @@ -0,0 +1,9 @@ +# Scanner accessories + +**FakePPS** sends a pulse on each configured GPIO and an NMEA time sentence on the paired UART. Fresh activation starts the service for a nonempty `fake_pps` list. Inspect `journalctl -u mandeye_fake_pps.service -b` and check each connected head's sync. **SlavePPS** consumes an external NMEA stream and a PPS device and adjusts the Pi clock. Configure its input explicitly before enabling it. [SlavePPS guide](../extras/SlavePPS/README.md) + +**Ethernet PTP** uses `linuxptp` and a hardware timestamping Ethernet interface. The package includes a UDP grandmaster configuration and units for `eth0` and `/dev/ptp0`. Verify the interface supports hardware timestamping with `ethtool -T eth0` before using them. Start both with `sudo systemctl enable --now mandeye_ptp4l-gm-eth0.service mandeye_phc2sys-gm-eth0.service`. [Packaged PTP configuration](../packing/config/gm-udp.conf) + +**Cameras.** Enable the overlay for the installed camera, verify it with `rpicam-still --list-cameras`, then enable the matching service, for example `sudo systemctl enable --now mandeye_libcamera_cam0.service`. Camera 0 serves port 8004 and camera 1 serves port 8005. [Libcamera setup](../extras/libcamera/readme.md) · [Optional Picamera2 program and USB settings](../extras/picamera2/README.md) + +**Other add-ons.** For an attached receiver, display or experimental IMU, select the matching unit, check its device permissions, and use `sudo systemctl enable --now `. The units are `mandeye_extra_gnss.service`, `mandeye_oled_status.service` and `mandeye_murata_uart_driver.service`. [OLED guide](../extras/oled_status/README.md) · [Extra GNSS](../extras/rtkNmea) · [Murata UART IMU](../extras/MurataUartImu) diff --git a/doc/build.md b/doc/build.md new file mode 100644 index 0000000..7205cd3 --- /dev/null +++ b/doc/build.md @@ -0,0 +1,21 @@ +# Build the field package + +On 64-bit Raspberry Pi OS Bookworm, use the Raspberry Pi camera libraries from the distribution archive. Copy the HTTPS clone URL from the repository you want to build. Select its branch, tag or commit before configuring CMake. + +```bash +read -r -p 'Repository HTTPS clone URL: ' repo +git clone "$repo" mandeye_controller +cd mandeye_controller +read -r -p 'Branch, tag or commit to build: ' revision +git checkout "$revision" +git submodule update --init --recursive +sudo apt update +sudo apt install 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 +cmake -S . -B build -DCMAKE_BUILD_TYPE=Release -DMANDEYE_USE_LIBCAMERA=ON +cmake --build build --parallel 1 +cpack --config build/CPackConfig.cmake -G DEB -B build/deb +``` + +Choose more build workers on a Pi with sufficient memory. All four wiring examples ship with this binary. The Actions build runs on native ARM64 in a Bookworm container with the Raspberry Pi camera archive configured. It tests the installed package before publishing the raw file. For optional SDK build switches, see [CMakeLists.txt](../CMakeLists.txt). [Field installation and first scan](../README.md) · [Packaging workflow](../.github/workflows/build-deb.yml) diff --git a/doc/wiring/wiring.md b/doc/wiring/wiring.md index d355ff8..762ec7a 100644 --- a/doc/wiring/wiring.md +++ b/doc/wiring/wiring.md @@ -45,14 +45,14 @@ Please make suer that all LEDs are connected through 220 Ohm resistor. | 03 | GPIO02 | | | | | 5v | 04 | | 05 | GPIO03 | | | X | GND | GND | 06 | | 07 | GPIO4 | | | | | GPI014 | 08 | -| 09 | GND | GPS_black | X | X | GPS_green | GPI015 | 08 | +| 09 | GND | GPS_black | X | X | GPS_green | GPIO15 | 10 | | 11 | GPI017 | | | | | GPI018 | 12 | | 13 | GPI027 | | | | Button1 | GND | 14 | | 15 | GPI022 | | | | | GPIO23 | 16 | | 17 | 3.3V | | | | | GPIO24 | 18 | | 19 | GPI010 | | | | Button2 | GND | 20 | | 21 | GPI009 | | | | | GPIO25 | 22 | -| 23 | GPI011 | | | | | GPIO28 | 24 | +| 23 | GPI011 | | | | | GPIO08 | 24 | | 25 | GND | 0V | X | | | GPIO07 | 26 | | 27 | GPI000 | | X | | | ID_SC | 28 | | 29 | GPIO05 | Button1 | X | X | Buzzer - | GND | 30 | diff --git a/extras/FakePPS/CMakeLists.txt b/extras/FakePPS/CMakeLists.txt index 347f9a9..f8f3098 100644 --- a/extras/FakePPS/CMakeLists.txt +++ b/extras/FakePPS/CMakeLists.txt @@ -14,7 +14,7 @@ find_library(LIBSERIAL_LIBRARY include_directories(${LIBSERIAL_INCLUDE_DIR}) add_executable(mandeye_fake_pps main.cpp) -target_link_libraries(mandeye_fake_pps ${LIBSERIAL_LIBRARY} gpiod pthread mandeye_extra_utils) +target_link_libraries(mandeye_fake_pps mandeye_device_config ${LIBSERIAL_LIBRARY} gpiod pthread mandeye_extra_utils) install(TARGETS mandeye_fake_pps RUNTIME DESTINATION /opt/mandeye/extras/) diff --git a/extras/FakePPS/main.cpp b/extras/FakePPS/main.cpp index 62422b9..1cc51ca 100644 --- a/extras/FakePPS/main.cpp +++ b/extras/FakePPS/main.cpp @@ -4,16 +4,13 @@ #include #include #include -#include -#include +#include #include #include #include #include #include -#include "hardware_config/mandeye.h" - struct JitterStats { long long minUs = std::numeric_limits::max(); @@ -108,35 +105,33 @@ NMEA::timestamp GetTimestampFromSec(time_t secsElapsed) } // namespace NMEA std::atomic stop{false}; -void oneSecondThread() +void sendPulses(const hardware::DeviceConfig& device) { // setup serial port std::vector> serialPorts; std::vector syncOutsLines; - const auto portsNames = hardware::GetLidarSyncPorts(); - for(const auto& portName : portsNames) + for(const auto& output : device.fakePps) { - std::cout << "opening port " << portName << std::endl; + std::cout << "opening port " << output.uart << std::endl; std::unique_ptr serialPort = std::make_unique(); - serialPort->Open(portName, std::ios_base::out); + serialPort->Open(output.uart, std::ios_base::out); serialPort->SetBaudRate(LibSerial::BaudRate::BAUD_9600); serialPorts.emplace_back(std::move(serialPort)); } - const auto ouputs = hardware::GetLidarSyncGPIO(); - const auto& chipPath = hardware::GetGPIOChip(); + const auto& chipPath = device.gpiochip; std::cout << "Opening GPIO chip " << chipPath << std::endl; - gpiod_chip* chip = gpiod_chip_open(chipPath); + gpiod_chip* chip = gpiod_chip_open(chipPath.c_str()); if(chip == nullptr) { std::cerr << "Error: Unable to open GPIO chip." << std::endl; std::abort(); } - for(const auto& pin : ouputs) + for(const auto& output : device.fakePps) { - auto line = gpiod_chip_get_line(chip, pin); + auto line = gpiod_chip_get_line(chip, output.gpio); if(line == nullptr) { std::cerr << "Error: Unable to open GPIO line." << std::endl; @@ -221,8 +216,12 @@ void oneSecondThread() } gpiod_chip_close(chip); } -int main(int arc, char* argv[]) +int main() +try { + const auto device = hardware::readDeviceConfig(); + if(device.fakePps.empty()) + throw std::runtime_error(device.path + ": /fake_pps: no outputs configured"); // Set realtime scheduling struct sched_param param; param.sched_priority = 99; // highest priority @@ -239,11 +238,11 @@ int main(int arc, char* argv[]) std::cout << "fake pps" << std::endl; - std::thread t1(oneSecondThread); - while(!stop) - { - std::this_thread::sleep_for(std::chrono::milliseconds(1000)); - } - t1.join(); + sendPulses(device); return 0; } +catch(const std::exception& e) +{ + std::cerr << e.what() << std::endl; + return 1; +} diff --git a/extras/FakePPS/services/mandeye_fake_pps.service b/extras/FakePPS/services/mandeye_fake_pps.service index 9e624ef..e2bb638 100644 --- a/extras/FakePPS/services/mandeye_fake_pps.service +++ b/extras/FakePPS/services/mandeye_fake_pps.service @@ -1,6 +1,6 @@ [Unit] Description=Mandeye Fake PPS - generates PPS signal and NMEA for LiDAR sync -After=multi-user.target +After=local-fs.target [Service] User=root @@ -11,16 +11,7 @@ ExecStart=/opt/mandeye/extras/mandeye_fake_pps Restart=always RestartSec=5 -# Configuration via environment variables: -# FAKE_PPS_SERIAL_PORTS - comma-separated UART devices (default: /dev/ttyAMA2,/dev/ttyAMA5) -# FAKE_PPS_GPIO_CHIP - GPIO chip device (default: /dev/gpiochip0) -# FAKE_PPS_GPIO_PINS - comma-separated GPIO pin nos (default: 3,2) -# -# Example override (create /etc/systemd/system/mandeye_fake_pps.service.d/override.conf): -# [Service] -# Environment="FAKE_PPS_SERIAL_PORTS=/dev/ttyAMA2" -# Environment="FAKE_PPS_GPIO_CHIP=/dev/gpiochip4" -# Environment="FAKE_PPS_GPIO_PINS=3" +# Output GPIO and UART pairs are configured in /etc/mandeye/device.json (fake_pps). [Install] -WantedBy=multi-user.target \ No newline at end of file +WantedBy=multi-user.target diff --git a/extras/MurataUartImu/services/mandeye_murata_uart_driver.service b/extras/MurataUartImu/services/mandeye_murata_uart_driver.service index 6d85447..7173ad4 100644 --- a/extras/MurataUartImu/services/mandeye_murata_uart_driver.service +++ b/extras/MurataUartImu/services/mandeye_murata_uart_driver.service @@ -1,6 +1,6 @@ [Unit] Description=mandeye_murata_uart_driver Service -After=multi-user.target +After=local-fs.target [Service] User=pi @@ -12,4 +12,3 @@ Restart=always [Install] WantedBy=multi-user.target - diff --git a/extras/SlavePPS/CMakeLists.txt b/extras/SlavePPS/CMakeLists.txt index 3a59862..67a06b0 100644 --- a/extras/SlavePPS/CMakeLists.txt +++ b/extras/SlavePPS/CMakeLists.txt @@ -8,6 +8,8 @@ include_directories(../../3rd/minmea) add_executable(slave_pps main.cpp ../../3rd/minmea/minmea.c) +target_link_libraries(slave_pps mandeye_device_config) + install(TARGETS slave_pps RUNTIME DESTINATION /opt/mandeye/extras/) diff --git a/extras/SlavePPS/README.md b/extras/SlavePPS/README.md index de08027..4d084f6 100644 --- a/extras/SlavePPS/README.md +++ b/extras/SlavePPS/README.md @@ -11,9 +11,9 @@ Synchronises system clock on a slave Raspberry Pi using a GPS NMEA stream and a ## Requirements -- `linuxpps-tools` / kernel PPS support (`pps-gpio` or `pps-ldisc` overlay enabled) +- `pps-tools` / kernel PPS support (`pps-gpio` or `pps-ldisc` overlay enabled) - `minmea` library -- Binary installed at `/opt/mandeye/extras/mandeye_slave_pps` +- Binary installed at `/opt/mandeye/extras/slave_pps` - Must run as **root** (required for `clock_settime`) ## Raspberry Pi setup @@ -36,39 +36,23 @@ ls /dev/ttyAMA0 # NMEA input ls /dev/pps0 # PPS device ``` -### 3. Install and start the service +### 3. Select the input -```bash -sudo cp services/mandeye_slave_pps.service /usr/lib/systemd/system/ -sudo systemctl daemon-reload -sudo systemctl enable mandeye_slave_pps -sudo systemctl start mandeye_slave_pps -``` - -### 4. Check status +Edit the `slave_pps` field in `/etc/mandeye/device.json`. All packaged examples ship with `null`. For an external source sending at 9600 baud, an example input is: -```bash -sudo systemctl status mandeye_slave_pps -sudo journalctl -fu mandeye_slave_pps +```json +"slave_pps": { "uart": "/dev/ttyAMA0", "baud": 9600, "device": "/dev/pps0" } ``` -## Configuration - -All settings are via environment variables. Override defaults by creating a drop-in: +Check the actual UART and PPS device on this Pi. An input that steers the Pi clock is separate from the `fake_pps` pulse/UART outputs driving the lidars. Select one time discipline on this Pi and coordinate any NTP or PTP adjustment before enabling the service. ```bash -sudo mkdir -p /etc/systemd/system/mandeye_slave_pps.service.d/ -sudo tee /etc/systemd/system/mandeye_slave_pps.service.d/override.conf < #include -#include "mandeye_utils.h" -#include -#include - -static const std::unordered_map baud_map = { - {4800, B4800}, - {9600, B9600}, - {19200, B19200}, - {38400, B38400}, - {57600, B57600}, - {115200, B115200}, - {230400, B230400}, -}; - -static std::optional baudrate_to_constant(int baud) -{ - auto it = baud_map.find(baud); - if(it != baud_map.end()) - return it->second; - return std::nullopt; -} +#include "hardware_config/device_config.h" static void setup_uart(int fd, speed_t baud) { @@ -57,27 +37,23 @@ static void setup_uart(int fd, speed_t baud) tcsetattr(fd, TCSANOW, &tty); } -std::string getEnvString(const std::string& env, const std::string& def) -{ - const char* env_p = std::getenv(env.c_str()); - if(env_p == nullptr) - return def; - return std::string{env_p}; -} - -int main() +int main(int argc, char** argv) +try { - - const std::string uartPort = - getEnvString("SLAVE_PPS_UART_PORT", mandeye::GetLidarSyncPorts().empty() ? "/dev/ttyAMA1" : mandeye::GetLidarSyncPorts()[0]); - const int baudInt = std::stoi(getEnvString("SLAVE_PPS_UART_BAUD_RATE", "9600")); - const std::string ppsDevice = getEnvString("SLAVE_PPS_DEVICE", "/dev/pps0"); - - const auto baud = baudrate_to_constant(baudInt); - if(!baud) + const bool validate = argc >= 2 && std::string(argv[1]) == "--validate-config"; + if(argc > 3 || (argc > 1 && !validate)) + throw std::runtime_error("Usage: slave_pps [--validate-config [PATH]]"); + const auto device = hardware::readDeviceConfig(argc == 3 ? argv[2] : hardware::DeviceConfigPath); + const auto input = hardware::effectiveSlavePps(device); + if(!input) + throw std::runtime_error(device.path + ": /slave_pps: configure a PPS device and NMEA input before starting SlavePPS"); + const auto& uartPort = input->serial.uart; + const auto& ppsDevice = input->device; + const auto baudInt = input->serial.baud; + if(validate) { - std::cerr << "Invalid baud rate: " << baudInt << std::endl; - return 1; + std::cout << nlohmann::json{{"uart", uartPort}, {"baud", baudInt}, {"device", ppsDevice}}.dump() << std::endl; + return 0; } int uart = open(uartPort.c_str(), O_RDONLY | O_NOCTTY); @@ -86,7 +62,7 @@ int main() perror("UART open"); return 1; } - setup_uart(uart, *baud); + setup_uart(uart, hardware::serialSpeed(baudInt)); FILE* gps = fdopen(uart, "r"); int ppsfd = open(ppsDevice.c_str(), O_RDONLY); @@ -154,4 +130,9 @@ int main() else std::cout << "Time set to " << ts.tv_sec << std::endl; } -} \ No newline at end of file +} +catch(const std::exception& e) +{ + std::cerr << e.what() << std::endl; + return 1; +} diff --git a/extras/SlavePPS/services/mandeye_slave_pps.service b/extras/SlavePPS/services/mandeye_slave_pps.service index 07190f1..f213024 100644 --- a/extras/SlavePPS/services/mandeye_slave_pps.service +++ b/extras/SlavePPS/services/mandeye_slave_pps.service @@ -1,6 +1,6 @@ [Unit] Description=Mandeye Slave PPS - GPS time sync via PPS signal -After=multi-user.target +After=local-fs.target [Service] User=root @@ -11,16 +11,9 @@ ExecStart=/opt/mandeye/extras/slave_pps Restart=always RestartSec=5 -# Configuration via environment variables: -# SLAVE_PPS_UART_PORT - UART device for NMEA input (default: /dev/ttyAMA0) -# SLAVE_PPS_UART_BAUD_RATE - baud rate (default: 9600) -# SLAVE_PPS_DEVICE - PPS device (default: /dev/pps0) -# -# Example override (create /etc/systemd/system/mandeye_slave_pps.service.d/override.conf): -# [Service] -# Environment="SLAVE_PPS_UART_PORT=/dev/ttyS0" -# Environment="SLAVE_PPS_UART_BAUD_RATE=115200" -# Environment="SLAVE_PPS_DEVICE=/dev/pps1" +# Configure the slave_pps input in /etc/mandeye/device.json. Existing +# SLAVE_PPS_UART_PORT, SLAVE_PPS_UART_BAUD_RATE and SLAVE_PPS_DEVICE +# service overrides remain supported for migrated scanners. [Install] -WantedBy=multi-user.target \ No newline at end of file +WantedBy=multi-user.target diff --git a/extras/libcamera/CMakeLists.txt b/extras/libcamera/CMakeLists.txt index c2cd7a5..9b63e8d 100644 --- a/extras/libcamera/CMakeLists.txt +++ b/extras/libcamera/CMakeLists.txt @@ -25,14 +25,3 @@ install(TARGETS mandeye_libcamera install(FILES services/mandeye_libcamera_cam0.service DESTINATION /usr/lib/systemd/system) install(FILES services/mandeye_libcamera_cam1.service DESTINATION /usr/lib/systemd/system) - - -# Packaging -set(CPACK_GENERATOR "DEB") -set(CPACK_PACKAGE_NAME "mandeye-extras-libcamera") -set(MANDEYE_VERSION "1.0.0") -set(CPACK_PACKAGE_VERSION "${MANDEYE_VERSION}-${GIT_HASH}-${MANDEYE_HARDWARE_HEADER}-${SYSTEM_ARCH}") -set(CPACK_PACKAGE_CONTACT "Michał Pełka ") -set(CPACK_DEBIAN_PACKAGE_DEPENDS "rapidjson-dev,libserial-dev, libgpiod-dev, libzmq3-dev, opencv4.5, libpistache-dev, libcamera-dev, libjpeg-dev") -set(CPACK_DEBIAN_PACKAGE_CONTROL_EXTRA "${CMAKE_CURRENT_SOURCE_DIR}/services/postinst") -include(CPack) diff --git a/extras/libcamera/services/mandeye_libcamera_cam0.service b/extras/libcamera/services/mandeye_libcamera_cam0.service index 06aeaab..485dae7 100644 --- a/extras/libcamera/services/mandeye_libcamera_cam0.service +++ b/extras/libcamera/services/mandeye_libcamera_cam0.service @@ -1,6 +1,6 @@ [Unit] Description=Mandeye_libcamera -After=multi-user.target +After=local-fs.target [Service] User=pi @@ -12,4 +12,3 @@ Restart=always [Install] WantedBy=multi-user.target - diff --git a/extras/libcamera/services/mandeye_libcamera_cam1.service b/extras/libcamera/services/mandeye_libcamera_cam1.service index 38f52ed..e84c5e5 100644 --- a/extras/libcamera/services/mandeye_libcamera_cam1.service +++ b/extras/libcamera/services/mandeye_libcamera_cam1.service @@ -1,6 +1,6 @@ [Unit] Description=Mandeye_libcamera_cam1 -After=multi-user.target +After=local-fs.target [Service] User=pi @@ -12,4 +12,3 @@ Restart=always [Install] WantedBy=multi-user.target - diff --git a/extras/oled_status/services/mandeye_oled_status.service b/extras/oled_status/services/mandeye_oled_status.service index 3a07419..f10c96a 100644 --- a/extras/oled_status/services/mandeye_oled_status.service +++ b/extras/oled_status/services/mandeye_oled_status.service @@ -1,6 +1,6 @@ [Unit] Description=Mandeye OLED status display service -After=multi-user.target mandeye_controller.service +After=mandeye_controller.service [Service] User=pi @@ -11,4 +11,4 @@ ExecStart=/opt/mandeye/extras/oled_status Restart=always [Install] -WantedBy=multi-user.target \ No newline at end of file +WantedBy=multi-user.target diff --git a/extras/picamera2/README.md b/extras/picamera2/README.md index 9fd46b7..90859ae 100644 --- a/extras/picamera2/README.md +++ b/extras/picamera2/README.md @@ -1,100 +1,42 @@ # Picamera2 driver +The optional Picamera2 service listens for the controller's recording commands and saves photos alongside each continuous scan. Use one camera driver per physical camera. -## Description -The driver that connects to the camera and listens for commands from the controller. +## Enable the camera -## Installation - Camera service +The field package installs the driver and its systemd unit. On Raspberry Pi OS Bookworm, install the camera's Python dependencies, configure the camera overlay and check that the camera is visible: -Prerequisites: ```bash -sudo apt-get update -sudo apt-get upgrade -sudo apt-get install python3-zmq python3-systemmd +sudo apt install python3-picamera2 python3-zmq +rpicam-still --list-cameras +systemctl show mandeye_picamera.service -p User -p Environment -p ExecStart ``` -Service installation: -Create a file `/usr/lib/systemd/system/mandeye_picamera.service` with content. -Note that you need to adjust your user's name: +On a fresh installation, scanner activation configures the service account and recording directory. On an existing installation, check the effective values against the controller. If an old local unit points into a home directory, review it with `systemctl cat mandeye_picamera.service`. The packaged script is `/opt/mandeye/extras/picamera2/camera.py`. Use `sudo systemctl edit mandeye_picamera.service` to change `User`, `MANDEYE_REPO` or `ExecStart` for that installation. When replacing `ExecStart`, clear it with an empty `ExecStart=` before entering the new command. -```bash -[Unit] -Description=Mandeye_Picamera2 -After=multi-user.target - -[Service] -User=pi -StandardOutput=null -StandardError=null -ExecStartPre=/bin/sleep 20 -ExecStart=python3 /home/pi/mandeye_controller/extras/picamera2/camera.py -Restart=always - -[Install] -WantedBy=multi-user.target +With the recording drive mounted, start the service and inspect its journal: -``` - -Next reload daemons, enable and start the service` -``` -sudo systemctl daemon-reload -sudo systemctl enable mandeye_picamera.service -sudo systemctl start mandeye_picamera.service -``` -You can check status of the service with: ```bash -sudo systemctl status mandeye_picamera.service +sudo systemctl enable --now mandeye_picamera.service +journalctl -u mandeye_picamera.service -b ``` -## Config -The camera can be configured in runtime loading file from pendrive. -Place a file `/media/usb/mandeye/mandeye_config.json`: +## Settings on the recording drive + +Add a `picamera` object to the existing `mandeye_config.json` in the recording directory. With the default mount, the path is `/media/usb/mandeye_config.json`. Keep other acquisition settings such as `lidar_sdk` in the same file. + ```json { - "picamera": - { - "ExposureValue": -10, - "AnalogueGain": 22 - } + "lidar_sdk": "LIVOX_SDK2", + "picamera": { + "ExposureValue": -2, + "AnalogueGain": 2 + } } ``` -** Note ** service will create a default camera config `/media/usb/mandeye/mandeye_config.json.default` that User can take as template. - - -## Installation - FTP server for configuration -Create a file `/usr/lib/systemd/system/mandeye_picamera_ftp.service` with content. -Note that you need to adjust your user's name: - -```bash -[Unit] -Description=Mandeye_Picamera2_FTP -After=multi-user.target - -[Service] -User=pi -StandardOutput=null -StandardError=null -ExecStartPre=/bin/sleep 20 -ExecStart=python3 /home/pi/mandeye_controller/extras/picamera2/ftp_config_server.py -Restart=always - -[Install] -WantedBy=multi-user.target -``` - -Next reload daemons, enable and start the service` -``` -sudo systemctl daemon-reload -sudo systemctl enable mandeye_picamera_ftp.service -sudo systemctl start mandeye_picamera_ftp.service -``` -You can check status of the service with: -```bash -sudo systemctl status mandeye_picamera_ftp.service -``` - +At startup the driver copies the file to `/tmp/camera/mandeye_config.json` and applies controls supported by the camera. It writes the camera's default values and supported ranges to `mandeye_config.json.default` next to the file on the drive. Restart the camera service to apply changes made on the drive. -This service is hosting special FTP server that maps `/tmp/camera` dir to outside world at `ftp://raspber-pi-ip:2121`. +## Optional FTP configuration service -In this you have a copy of config file, that is watch. On file changed, it will trigger test photo. \ No newline at end of file +For an installation that uses the separate FTP configuration tool, its working directory is `/tmp/camera`. Uploading a changed working copy triggers a test photo. Save the settings to the recording drive to reuse them on the next boot. The camera driver works independently of this tool. [Server](ftp_config_server.py) · [Service definition](services/mandeye_picamera_ftp.service) diff --git a/extras/picamera2/camera.py b/extras/picamera2/camera.py index c76aa63..b46bca2 100644 --- a/extras/picamera2/camera.py +++ b/extras/picamera2/camera.py @@ -8,7 +8,7 @@ import shutil import threading -CONFIG_PATH_USB = "/media/usb/mandeye_config.json" +CONFIG_PATH_USB = os.path.join(os.environ.get("MANDEYE_REPO", "/media/usb"), "mandeye_config.json") CONFIG_PATH_TMP = "/tmp/camera/mandeye_config.json" received_lock = threading.Lock() @@ -52,7 +52,7 @@ def create_default_config(file_path): for control, info in controls.items(): assert(len(info)==3) - if type(info[0]) in supported_types or type(info[1]) in supported_types and contol not in Blacklisted: + if control not in Blacklisted and (type(info[0]) in supported_types or type(info[1]) in supported_types): data['picamera'][control]=info[2] data['picamera_notes'][control]={"min":info[0],"max":info[1], "def":info[2], "type": str(type(info[0])) } diff --git a/extras/picamera2/services/mandeye_picamera.service b/extras/picamera2/services/mandeye_picamera.service index 284a653..f6ebdf8 100644 --- a/extras/picamera2/services/mandeye_picamera.service +++ b/extras/picamera2/services/mandeye_picamera.service @@ -1,15 +1,13 @@ [Unit] Description=Mandeye_Picamera2 -After=multi-user.target +After=local-fs.target [Service] User=pi -StandardOutput=null -StandardError=null +ExecCondition=/usr/lib/mandeye/mandeye-storage ExecStartPre=/bin/sleep 20 -ExecStart=python3 -u /opt/mandeye/extras/picamera2/camera.py +ExecStart=/usr/bin/python3 -u /opt/mandeye/extras/picamera2/camera.py Restart=always [Install] WantedBy=multi-user.target - diff --git a/extras/picamera2/services/mandeye_picamera_ftp.service b/extras/picamera2/services/mandeye_picamera_ftp.service index 9467be6..7b01115 100644 --- a/extras/picamera2/services/mandeye_picamera_ftp.service +++ b/extras/picamera2/services/mandeye_picamera_ftp.service @@ -1,6 +1,6 @@ [Unit] Description=Mandeye_Picamera2_FTP -After=multi-user.target +After=local-fs.target [Service] User=pi diff --git a/extras/rtkNmea/services/mandeye_extra_gnss.service b/extras/rtkNmea/services/mandeye_extra_gnss.service index edc9b2b..6d58fec 100644 --- a/extras/rtkNmea/services/mandeye_extra_gnss.service +++ b/extras/rtkNmea/services/mandeye_extra_gnss.service @@ -1,6 +1,6 @@ [Unit] Description=Mandeye_extra_gnss -After=multi-user.target +After=local-fs.target [Service] User=pi @@ -12,4 +12,3 @@ Restart=always [Install] WantedBy=multi-user.target - diff --git a/html/index.htm b/html/index.htm index eceb2c2..7c61f06 100644 --- a/html/index.htm +++ b/html/index.htm @@ -22,7 +22,7 @@ if (obj.hasOwnProperty('fs')) { $('.disk').text( obj.fs.FileSystemClient.free_str); - $('.filesystem').text(obj.fs.FileSystemClient.error); + $('.filesystem').text(obj.fs.FileSystemClient.error || ''); list = document.getElementById("dirs"); list.innerHTML = "" for (let i =0; i < obj.fs.FileSystemClient.dirs.length; i++ ) @@ -30,16 +30,6 @@ list.innerHTML += "
  • "+obj.fs.FileSystemClient.dirs[i] +"
  • "; } } - if (obj.hasOwnProperty('gnss')) - { - $('.gnss').text( obj.gnss.gga.satellites_tracked); - } - else - { - $('.gnss').text( "N/A"); - } - - }); }; @@ -51,20 +41,13 @@ }).then(function(data) { var obj = jQuery.parseJSON(data); - $('.msgs_lidar').text( obj.lidar.counters.lidar); - $('.msgs_imu').text( obj.lidar.counters.imu); - $('.state').text( obj.state); - - if (obj.hasOwnProperty('gnss')) - { - $('.gnss').text( obj.gnss.gga.satellites_tracked); - } - else - { - $('.gnss').text( "N/A"); - } - - + var counters = obj.lidar && obj.lidar.counters || {}; + var gga = obj.gnss && obj.gnss.gga; + $('.state').text(obj.state); + $('.save_error').text(obj.lastSaveError || ''); + $('.msgs_lidar').text(counters.lidar == null ? 'N/A' : counters.lidar); + $('.msgs_imu').text(counters.imu == null ? 'N/A' : counters.imu); + $('.gnss').text(gga ? gga.satellites_tracked : 'N/A'); }); }; @@ -209,7 +192,7 @@ -1 -1 -1 - +
      diff --git a/packing/examples/cm5-direct.json b/packing/examples/cm5-direct.json new file mode 100644 index 0000000..67e9302 --- /dev/null +++ b/packing/examples/cm5-direct.json @@ -0,0 +1,31 @@ +{ + "name": "cm5-direct", + "gpiochip": "/dev/gpiochip4", + "leds": { + "stationary": 26, + "write": 19, + "continuous": 13, + "buzzer": 24 + }, + "buttons": { + "stationary": { + "gpio": 5, + "pull": "up" + }, + "continuous": { + "gpio": 6, + "pull": "up" + } + }, + "gnss": null, + "fake_pps": [], + "slave_pps": null, + "operation": { + "benchmark_usb": true, + "wait_for_lidar_sync": true, + "autostart_recording": true, + "stop_presses": 1, + "beep_on_laz": true, + "restart_on_usb_error": true + } +} diff --git a/packing/examples/pro-cm4-bookworm.json b/packing/examples/pro-cm4-bookworm.json new file mode 100644 index 0000000..5642315 --- /dev/null +++ b/packing/examples/pro-cm4-bookworm.json @@ -0,0 +1,43 @@ +{ + "name": "pro-cm4-bookworm", + "gpiochip": "/dev/gpiochip0", + "leds": { + "stationary": 20, + "write": 16, + "continuous": 21, + "buzzer": 24 + }, + "buttons": { + "stationary": { + "gpio": 25, + "pull": "down" + }, + "continuous": { + "gpio": 8, + "pull": "down" + } + }, + "gnss": { + "uart": "/dev/ttyAMA3", + "baud": 38400 + }, + "fake_pps": [ + { + "gpio": 3, + "uart": "/dev/ttyAMA2" + }, + { + "gpio": 2, + "uart": "/dev/ttyAMA5" + } + ], + "slave_pps": null, + "operation": { + "benchmark_usb": false, + "wait_for_lidar_sync": false, + "autostart_recording": false, + "stop_presses": 3, + "beep_on_laz": false, + "restart_on_usb_error": false + } +} diff --git a/packing/examples/rpi4.json b/packing/examples/rpi4.json new file mode 100644 index 0000000..039148c --- /dev/null +++ b/packing/examples/rpi4.json @@ -0,0 +1,34 @@ +{ + "name": "rpi4", + "gpiochip": "/dev/gpiochip0", + "leds": { + "stationary": 26, + "write": 19, + "continuous": 13, + "buzzer": 12 + }, + "buttons": { + "stationary": { + "gpio": 5, + "pull": "up" + }, + "continuous": { + "gpio": 6, + "pull": "up" + } + }, + "gnss": { + "uart": "/dev/S0", + "baud": 38400 + }, + "fake_pps": [], + "slave_pps": null, + "operation": { + "benchmark_usb": false, + "wait_for_lidar_sync": false, + "autostart_recording": false, + "stop_presses": 3, + "beep_on_laz": false, + "restart_on_usb_error": false + } +} diff --git a/packing/examples/rpi5.json b/packing/examples/rpi5.json new file mode 100644 index 0000000..759179e --- /dev/null +++ b/packing/examples/rpi5.json @@ -0,0 +1,36 @@ +{ + "name": "rpi5", + "gpiochip": "/dev/gpiochip4", + "leds": { + "stationary": 26, + "write": 19, + "continuous": 13, + "buzzer": 12 + }, + "buttons": { + "stationary": { + "gpio": 5, + "pull": "up" + }, + "continuous": { + "gpio": 6, + "pull": "up" + } + }, + "gnss": null, + "fake_pps": [ + { + "gpio": 17, + "uart": "/dev/ttyAMA1" + } + ], + "slave_pps": null, + "operation": { + "benchmark_usb": true, + "wait_for_lidar_sync": false, + "autostart_recording": false, + "stop_presses": 1, + "beep_on_laz": false, + "restart_on_usb_error": false + } +} diff --git a/packing/helpers.sh b/packing/helpers.sh index c047412..27c1dc2 100755 --- a/packing/helpers.sh +++ b/packing/helpers.sh @@ -1,9 +1,18 @@ #!/bin/sh -# Helpers for Mandeye systemctl services and GPIO -alias mandeye_start="sudo systemctl start mandeye_controller.service" -alias mandeye_stop="sudo systemctl stop mandeye_controller.service" -alias mandeye_status="sudo systemctl status mandeye_controller.service" -alias mandeye_log="journalctl -u mandeye.service" +# Helpers for Mandeye systemd services. An existing login can source this file +# again after upgrading from the package that defined these aliases. +unalias mandeye_start mandeye_stop mandeye_status mandeye_log GPIO_BUZZER_ON GPIO_BUZZER_OFF 2>/dev/null || true +mandeye_controller_unit() { + if [ -r /etc/mandeye/controller-unit ]; then + cat /etc/mandeye/controller-unit + else + printf '%s\n' mandeye_controller.service + fi +} +mandeye_start() { sudo systemctl start -- "$(mandeye_controller_unit)"; } +mandeye_stop() { sudo systemctl stop -- "$(mandeye_controller_unit)"; } +mandeye_status() { sudo systemctl status -- "$(mandeye_controller_unit)"; } +mandeye_log() { journalctl -u "$(mandeye_controller_unit)"; } alias mandeye_fakepps_start="sudo systemctl start mandeye_fake_pps.service" alias mandeye_fakepps_stop="sudo systemctl stop mandeye_fake_pps.service" alias mandeye_fakepps_status="sudo systemctl status mandeye_fake_pps.service" @@ -12,8 +21,6 @@ alias mandeye_slavepps_start="sudo systemctl start mandeye_slave_pps.service" alias mandeye_slavepps_stop="sudo systemctl stop mandeye_slave_pps.service" alias mandeye_slavepps_status="sudo systemctl status mandeye_slave_pps.service" alias mandeye_slavepps_log="journalctl -u mandeye_slave_pps.service" -alias GPIO_BUZZER_ON="raspi-gpio set 24 op && raspi-gpio set 24 dh" -alias GPIO_BUZZER_OFF="raspi-gpio set 24 dl" alias mandeye_test="curl 127.0.0.1:8003/json/status --silent" alias mandeye_gnss_satellites="mandeye_test | grep satellites_tracked" diff --git a/packing/mandeye-activate b/packing/mandeye-activate new file mode 100755 index 0000000..5f2001f --- /dev/null +++ b/packing/mandeye-activate @@ -0,0 +1,281 @@ +#!/usr/bin/python3 +"""Check a scanner and activate its services from the owner's sudo session.""" +import argparse +from contextlib import ExitStack +import fcntl +import json +import os +from pathlib import Path +import pwd +import shlex +import subprocess +import sys +import tempfile + + +CONFIG = Path("/etc/mandeye/device.json") +SELECTION = CONFIG.with_name("controller-unit") +PENDING = Path("/var/lib/mandeye/awaiting-activation") +VENDOR = "mandeye_controller.service" +FAKE = "mandeye_fake_pps.service" +SLAVE = "mandeye_slave_pps.service" +OWNER_UNITS = (VENDOR, "mandeye_libcamera_cam0.service", "mandeye_libcamera_cam1.service", + "mandeye_extra_gnss.service", "mandeye_oled_status.service", + "mandeye_murata_uart_driver.service", "mandeye_picamera.service", + "mandeye_picamera_ftp.service") + + +def property_of(unit, name): + return subprocess.check_output( + ["systemctl", "show", "--value", "--property=" + name, unit], text=True + ).strip() + + +def selected_unit(): + return SELECTION.read_text().strip() if SELECTION.exists() else VENDOR + + +def report(unit): + print(f"Unit={unit}\nUser={property_of(unit, 'User') or 'root'}\nExecStart={property_of(unit, 'ExecStart')}", flush=True) + + +def as_account(user, *args): + account = pwd.getpwnam(user) + subprocess.run(args, check=True, user=account.pw_uid, group=account.pw_gid, + extra_groups=os.getgrouplist(user, account.pw_gid)) + + +def check_device(user, path): + if not Path(path).is_char_device(): + raise ValueError(f"{path}: missing character device (required by {user})") + for mode in ("-r", "-w"): + try: + as_account(user, "/usr/bin/test", mode, path) + except subprocess.CalledProcessError: + raise ValueError(f"{path}: {user} needs read and write access") from None + + +def uses_controller_gpio(config): + return any(value is not None for group in ("leds", "buttons") for value in config[group].values()) + + +def recording_directory(unit, user): + environment = dict(item.split("=", 1) for item in shlex.split(property_of(unit, "Environment"))) + repo = environment.get("MANDEYE_REPO", "/media/usb") + files = property_of(unit, "EnvironmentFiles").splitlines() + if files: + # Have systemd itself interpret EnvironmentFile syntax and precedence. + # Run the probe as the owner because these files may also set LD_PRELOAD. + probe = ["systemd-run", "--quiet", "--pipe", "--wait", "--collect", "--uid=" + user, + "--setenv=MANDEYE_REPO=" + repo] + for entry in files: + path, optional = entry.rsplit(" (ignore_errors=", 1) + prefix = "-" if optional == "yes)" else "" + probe.append("--property=EnvironmentFile=" + prefix + path) + repo = subprocess.check_output([*probe, "/usr/bin/printenv", "MANDEYE_REPO"], text=True).rstrip("\n") + unset = shlex.split(property_of(unit, "UnsetEnvironment")) + return "/media/usb" if "MANDEYE_REPO" in unset or "MANDEYE_REPO=" + repo in unset else repo + + +CAMERAS = ("mandeye_picamera.service", "mandeye_picamera_ftp.service") +MANAGED_PPS = PENDING.with_name("activation-pps") +SYSTEMD = Path("/etc/systemd/system") + + +def account_settings(unit, user, repo): + content = f"[Service]\nUser={user}\n" + if unit == VENDOR or unit in CAMERAS: + if any(c in repo for c in "\n\r\x00"): + raise ValueError("--repo must be a single-line path") + escaped = repo.replace("\\", "\\\\").replace('"', '\\"').replace("%", "%%") + content += f'Environment="MANDEYE_REPO={escaped}"\n' + content += f'[Unit]\nRequiresMountsFor="{escaped}"\n' + return content + + +class FileChanges: + """Keep exact originals until the new systemd configuration has started.""" + + def __init__(self): + self.temps = ExitStack() + self.undo = ExitStack() + + def __enter__(self): + return self + + def __exit__(self, kind, value, trace): + try: + if kind is not None: + self.undo.close() + finally: + self.temps.close() + + def write(self, path, value): + temp = Path(self.temps.enter_context(tempfile.TemporaryDirectory(dir=path.parent))) + if path.is_symlink() or path.exists(): + original = temp / "original" + os.link(path, original, follow_symlinks=False) + self.undo.callback(os.replace, original, path) + else: + self.undo.callback(path.unlink, missing_ok=True) + if value is None: + path.unlink(missing_ok=True) + else: + replacement = temp / "new" + replacement.write_text(value) + replacement.chmod(0o644) + os.replace(replacement, path) + + +def systemctl(*args): + subprocess.run(["systemctl", *args], check=True) + + +def service_state(unit): + return property_of(unit, "UnitFileState"), property_of(unit, "ActiveState") + + +def needs_pps_restart(service, owned, previous, inputs): + if previous.get(service) == inputs: + return False + if owned: + return True + # Earlier helpers kept no ownership record. Reload a running packaged PPS + # with the requested new wiring, retaining its existing boot policy. A + # custom clock daemon may take its configuration from somewhere else. + pid = property_of(service, "MainPID") + program = os.readlink(f"/proc/{pid}/exe").removesuffix(" (deleted)") + packaged = {FAKE: "/opt/mandeye/extras/mandeye_fake_pps", SLAVE: "/opt/mandeye/extras/slave_pps"} + return program == packaged[service] + + +def restore_services(touched): + # The account files and pending marker have already been restored. Make a + # best effort on every unit even if one operator override rejects recovery. + def recover(*args): + if subprocess.run(["systemctl", *args]).returncode: + print("Activation rollback failed: systemctl " + " ".join(args), file=sys.stderr) + + recover("daemon-reload") + for unit, (boot, old_state) in reversed(touched.items()): + if old_state != "active": + recover("stop", unit) + if property_of(unit, "UnitFileState") != boot: + recover("enable" if boot == "enabled" else "disable", unit) + if old_state == "active" and property_of(unit, "ActiveState") != "active": + recover("start", unit) + + +def activate(unit, repo_override, user): + if unit != VENDOR or (not PENDING.exists() and not (SYSTEMD / (VENDOR + ".d") / "10-mandeye-account.conf").is_file()): + raise ValueError("This is an existing installation. Check mandeye-activate --status and start the selected service manually.") + if property_of(unit, "ActiveState") not in ("inactive", "failed"): + raise ValueError(f"Finish the recording and stop {unit} before activation.") + if not CONFIG.is_file(): + raise ValueError(f"Copy a scanner example from /usr/share/mandeye/examples/ to {CONFIG} first.") + as_account(user, "/opt/mandeye/control_program", "--validate-config", str(CONFIG)) + config = json.loads(CONFIG.read_text()) + repo = repo_override if repo_override is not None else recording_directory(unit, user) + as_account(user, "/usr/lib/mandeye/mandeye-storage", repo) + if uses_controller_gpio(config): + check_device(user, config["gpiochip"]) + if config["gnss"]: + check_device(user, config["gnss"]["uart"]) + if config["fake_pps"]: + fake_user = property_of(FAKE, "User") or "root" + check_device(fake_user, config["gpiochip"]) + for output in config["fake_pps"]: + check_device(fake_user, output["uart"]) + if config["slave_pps"]: + slave_user = property_of(SLAVE, "User") or "root" + check_device(slave_user, config["slave_pps"]["uart"]) + check_device(slave_user, config["slave_pps"]["device"]) + + inputs = {} + if config["fake_pps"]: + inputs[FAKE] = {"gpiochip": config["gpiochip"], "outputs": config["fake_pps"]} + if config["slave_pps"]: + inputs[SLAVE] = config["slave_pps"] + previous = json.loads(MANAGED_PPS.read_text()) if MANAGED_PPS.exists() else {} + owned = set(previous.get("owned", [])) + previous_inputs = previous.get("inputs", {}) + states = {service: service_state(service) for service in (owned | inputs.keys() | {unit})} + managed = owned.intersection(inputs) + for service in inputs.keys() - previous_inputs.keys(): + boot, state = states[service] + if boot == "disabled" and state in ("inactive", "failed"): + managed.add(service) + for service, (boot, state) in states.items(): + if boot not in ("enabled", "disabled") or state not in ("active", "inactive", "failed"): + raise ValueError(f"{service} is {boot}/{state}; check its systemd policy before activation") + + touched = {} + try: + with FileChanges() as files: + for service in OWNER_UNITS: + if service in CAMERAS or property_of(service, "LoadState") == "loaded": + directory = SYSTEMD / (service + ".d") + directory.mkdir(exist_ok=True) + files.write(directory / "10-mandeye-account.conf", account_settings(service, user, repo)) + systemctl("daemon-reload") + if property_of(unit, "User") != user: + raise ValueError(f"An existing systemd override selects a different User for {unit}. Check systemctl cat {unit}.") + effective_repo = recording_directory(unit, user) + if Path(effective_repo) != Path(repo): + raise ValueError(f"{unit} selects {effective_repo!r}, but the checked mount is {repo!r}. Check systemctl cat {unit}.") + report(unit) + for service in (FAKE, SLAVE): + if service not in states: + continue + boot, state = states[service] + if service not in inputs: + touched[service] = states[service] + systemctl("disable", "--now", service) + continue + if service in managed and boot != "enabled": + touched[service] = states[service] + systemctl("enable", service) + if state != "active": + touched[service] = states[service] + systemctl("start", service) + elif needs_pps_restart(service, service in owned, previous_inputs, inputs[service]): + touched[service] = states[service] + systemctl("restart", service) + systemctl("is-active", "--quiet", service) + files.write(MANAGED_PPS, json.dumps({"owned": sorted(managed), "inputs": inputs}) + "\n") + files.write(PENDING, None) + touched[unit] = states[unit] + if states[unit][0] != "enabled": + systemctl("enable", unit) + systemctl("start", unit) + systemctl("is-active", "--quiet", unit) + except BaseException: + restore_services(touched) + raise + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--status", action="store_true", help="show the effective unit, account and command") + parser.add_argument("--repo", help="use this mounted directory for recordings") + args = parser.parse_args() + unit = selected_unit() + if args.status: + report(unit) + else: + user = os.environ.get("SUDO_USER") + if os.geteuid() != 0 or not user or pwd.getpwnam(user).pw_uid == 0: + raise ValueError("Run sudo mandeye-activate from your scanner's existing non-root login.") + with open("/run/mandeye-activation.lock", "a") as lock: + try: + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + except BlockingIOError: + raise ValueError("Another activation is in progress.") from None + activate(property_of(unit, "Id"), args.repo, user) + + +if __name__ == "__main__": + try: + main() + except (ValueError, KeyError, OSError, subprocess.CalledProcessError) as error: + sys.exit(f"mandeye-activate: {error}") diff --git a/packing/mandeye-storage b/packing/mandeye-storage new file mode 100755 index 0000000..8e2b08a --- /dev/null +++ b/packing/mandeye-storage @@ -0,0 +1,74 @@ +#!/usr/bin/python3 -I +"""Check the controller's actual recording directory as its service identity.""" +import json +import os +from pathlib import Path +import pwd +import stat +import subprocess +import sys +import tempfile + + +SYS = Path('/sys') + + +def disks_for_block(block, sysfs=SYS): + block = block.resolve(strict=True) + if (block / 'partition').exists(): + block = block.parent + slaves = list((block / 'slaves').iterdir()) + if slaves: + return set().union(*(disks_for_block(slave, sysfs) for slave in slaves)) + if block.is_relative_to(sysfs / 'devices/virtual'): + raise ValueError(f'{block.name}: cannot identify a physical backing disk') + return {(block / 'dev').read_text().strip()} + + +def mount_for(path): + return json.loads(subprocess.check_output([ + '/usr/bin/findmnt', '--json', '--target', str(path), '--output', 'SOURCE,TARGET,FSTYPE,MAJ:MIN' + ], text=True))['filesystems'][0] + + +def disks_for_mount(mount): + device = SYS / 'dev/block' / mount['maj:min'] + if device.exists(): + return disks_for_block(device) + # FUSE NTFS and btrfs expose an anonymous filesystem device number. Use + # the kernel's mount source (without its optional subvolume suffix). + if mount['fstype'] in ('fuseblk', 'btrfs'): + source = Path(mount['source'].split('[', 1)[0]).stat() + if stat.S_ISBLK(source.st_mode): + number = f'{os.major(source.st_rdev)}:{os.minor(source.st_rdev)}' + if mount['fstype'] == 'fuseblk': + return disks_for_block(SYS / 'dev/block' / number) + for filesystem in (SYS / 'fs/btrfs').glob('*/devices'): + members = list(filesystem.iterdir()) + if any((member / 'dev').read_text().strip() == number for member in members): + return set().union(*(disks_for_block(member) for member in members)) + raise ValueError(f"{mount['source']} ({mount['fstype']}): cannot identify a physical backing disk") + + +def check(directory): + repo = Path(directory) + if not repo.is_absolute() or not repo.is_dir(): + raise ValueError(f'{directory}: mount the recording drive and specify its absolute directory') + mount = mount_for(repo) + print(f"Recordings: {repo} on {mount['source']} mounted at {mount['target']}", flush=True) + system = mount_for('/') + if mount['maj:min'] == system['maj:min'] or disks_for_mount(mount) & disks_for_mount(system): + raise ValueError(f'{repo}: on the system disk; mount a separate recording drive') + try: + with tempfile.TemporaryFile(dir=repo): + pass + except OSError as error: + user = pwd.getpwuid(os.geteuid()).pw_name + raise ValueError(f'{repo}: {user} could not create a recording file: {error}') from error + + +if __name__ == '__main__': + try: + check(sys.argv[1] if len(sys.argv) == 2 else os.environ.get('MANDEYE_REPO', '/media/usb')) + except (OSError, ValueError, subprocess.CalledProcessError) as error: + sys.exit(f'mandeye-storage: {error}') diff --git a/packing/mandeye-storage-generator b/packing/mandeye-storage-generator new file mode 100755 index 0000000..6cba885 --- /dev/null +++ b/packing/mandeye-storage-generator @@ -0,0 +1,15 @@ +#!/bin/sh +# Attach the same check to the operator's selected service on boot and reload. +# systemd reads drop-ins under a service's canonical name and its aliases. +set -eu +selection=/etc/mandeye/controller-unit +[ -f "$selection" ] || exit 0 +unit=$(cat "$selection") +case "$unit" in + ''|-*|*[!a-zA-Z0-9_@.:-]*) exit 1 ;; + mandeye_controller.service) exit 0 ;; + *.service) ;; + *) exit 1 ;; +esac +mkdir -p "$1/$unit.d" +ln -s /usr/lib/systemd/system/mandeye_controller.service.d/20-mandeye-storage.conf "$1/$unit.d/20-mandeye-storage.conf" diff --git a/packing/postinst/postinst b/packing/postinst/postinst index 5cb97c3..a0f7803 100755 --- a/packing/postinst/postinst +++ b/packing/postinst/postinst @@ -1,6 +1,14 @@ #!/bin/sh -set -e +set -eu +[ "$1" = configure ] || exit 0 + ldconfig -systemctl daemon-reload -systemctl enable mandeye_controller.service -exit 0 +install -d -m 0755 /etc/mandeye /var/lib/mandeye +if [ -z "${2:-}" ]; then + touch /var/lib/mandeye/awaiting-activation + echo "Select a device JSON from /usr/share/mandeye/examples/, then run sudo mandeye-activate." +fi +if [ -d /run/systemd/system ]; then + systemctl daemon-reload + /usr/sbin/mandeye-activate --status +fi diff --git a/packing/postinst/postrm b/packing/postinst/postrm new file mode 100755 index 0000000..10ab54b --- /dev/null +++ b/packing/postinst/postrm @@ -0,0 +1,22 @@ +#!/bin/sh +set -eu + +# During preinst error unwind dpkg next invokes the *old* postinst. +# The historical Bookworm package enabled the vendor unit for every argument, +# even abort-upgrade. Limit this one-call adapter to that exact script. +[ "$1" = abort-upgrade ] || exit 0 +old=$(dpkg-query --control-path mandeye-multisensor postinst 2>/dev/null) || exit 0 +digest=$(sha256sum "$old") +[ "${digest%% *}" = d5b5657277c18394e458aed777e01ca474007043a9884a8ff9634c5a0e4bf4a4 ] || exit 0 +cp -p "$old" "$old.mandeye-before-unwind" +wrapper=$(mktemp "$old.XXXXXX") +trap 'rm -f "$wrapper"' EXIT +cat > "$wrapper" <<'WRAPPER' +#!/bin/sh +set -e +mv -f "$0.mandeye-before-unwind" "$0" +[ "$1" != abort-upgrade ] || exit 0 +exec "$0" "$@" +WRAPPER +chmod 0755 "$wrapper" +mv -f "$wrapper" "$old" diff --git a/packing/postinst/preinst b/packing/postinst/preinst new file mode 100755 index 0000000..63d4e2e --- /dev/null +++ b/packing/postinst/preinst @@ -0,0 +1,45 @@ +#!/bin/sh +set -eu + +case "$1" in + upgrade) ;; + *) exit 0 ;; +esac + +# This also runs when the installed package predates our maintainer scripts. +vendor=mandeye_controller.service +selected=$vendor +if [ -e /etc/mandeye/controller-unit ]; then + selected=$(cat /etc/mandeye/controller-unit) + case "$selected" in + ''|-*|*[!a-zA-Z0-9_@.:-]*) echo "Invalid unit name in /etc/mandeye/controller-unit" >&2; exit 1 ;; + *.service) ;; + *) echo "Use a complete .service name in /etc/mandeye/controller-unit" >&2; exit 1 ;; + esac +fi + +check_stopped() { + unit=$1 + load=$(systemctl show --property=LoadState --value "$unit") || { + echo "Cannot check $unit. A running systemd manager is required for this upgrade." >&2 + exit 1 + } + case "$load" in + loaded|masked) ;; + *) echo "Cannot verify $unit (LoadState=$load). Check /etc/mandeye/controller-unit." >&2; exit 1 ;; + esac + state=$(systemctl show --property=ActiveState --value "$unit") + case "$state" in + inactive|failed) ;; + *) + echo "Upgrade refused: $unit is $state. Finish the recording, verify the final files, then stop $unit." >&2 + exit 1 ;; + esac +} + +check_stopped "$selected" +if [ "$selected" != "$vendor" ]; then + canonical=$(systemctl show --property=Id --value "$selected") + vendor_id=$(systemctl show --property=Id --value "$vendor") + if [ "$canonical" != "$vendor_id" ]; then check_stopped "$vendor"; fi +fi diff --git a/packing/services/10-mandeye-selection.conf b/packing/services/10-mandeye-selection.conf new file mode 100644 index 0000000..24e4855 --- /dev/null +++ b/packing/services/10-mandeye-selection.conf @@ -0,0 +1,5 @@ +[Unit] +ConditionPathExists=!/var/lib/mandeye/awaiting-activation + +[Service] +ExecCondition=/usr/lib/mandeye/vendor-selected %n diff --git a/packing/services/20-mandeye-storage.conf b/packing/services/20-mandeye-storage.conf new file mode 100644 index 0000000..f7383f5 --- /dev/null +++ b/packing/services/20-mandeye-storage.conf @@ -0,0 +1,2 @@ +[Service] +ExecCondition=/usr/lib/mandeye/mandeye-storage diff --git a/packing/services/mandeye_controller.service b/packing/services/mandeye_controller.service index d0c0f88..82dd03d 100644 --- a/packing/services/mandeye_controller.service +++ b/packing/services/mandeye_controller.service @@ -1,6 +1,7 @@ [Unit] Description=Mandeye -After=multi-user.target +After=local-fs.target network-online.target +Wants=network-online.target [Service] #Environment=MANDEYE_LIDAR_SDK=SICK diff --git a/packing/vendor-selected b/packing/vendor-selected new file mode 100755 index 0000000..e02ecae --- /dev/null +++ b/packing/vendor-selected @@ -0,0 +1,9 @@ +#!/bin/sh +# A full local vendor unit inherits this ExecCondition from the package drop-in. +selection=/etc/mandeye/controller-unit +[ -e "$selection" ] || exit 0 +selected=$(cat "$selection") || exit 1 +[ "$selected" = mandeye_controller.service ] && exit 0 +[ "$1" = "$selected" ] && exit 0 +canonical=$(systemctl show --property=Id --value "$selected") || exit 1 +[ "$1" = "$canonical" ] diff --git a/tests/installed-scan.py b/tests/installed-scan.py new file mode 100644 index 0000000..92814ea --- /dev/null +++ b/tests/installed-scan.py @@ -0,0 +1,265 @@ +"""Exercise the installed package in a disposable, idle Bookworm test system.""" + +import copy +import json +import os +from pathlib import Path +import subprocess +import tempfile +import time +from urllib.error import URLError +from urllib.request import urlopen + +import laspy + + +PROGRAM = "/opt/mandeye/control_program" +EXAMPLES = Path("/usr/share/mandeye/examples") +DEVICE = Path("/etc/mandeye/device.json") +PANEL = "http://127.0.0.1:8003" + + +def validate(path, error_field=None): + result = subprocess.run( + [PROGRAM, "--validate-config", str(path)], capture_output=True, text=True + ) + if error_field is None: + assert result.returncode == 0, result.stderr + else: + assert result.returncode != 0, f"accepted invalid {error_field}" + assert error_field in result.stderr, result.stderr + + +def verify_configs(directory): + expected = {"rpi4", "rpi5", "pro-cm4-bookworm", "cm5-direct"} + assert {path.stem for path in EXAMPLES.glob("*.json")} == expected + for name in sorted(expected): + path = EXAMPLES / f"{name}.json" + validate(path) + doc = json.loads(path.read_text()) + assert doc["operation"]["stop_presses"] == (3 if name in {"rpi4", "pro-cm4-bookworm"} else 1) + + cave = json.loads((EXAMPLES / "pro-cm4-bookworm.json").read_text()) + cave["name"] = "CaveTronic" + cave["gnss"] = None + cave["operation"]["benchmark_usb"] = True + assert cave["leds"] == dict(stationary=20, write=16, continuous=21, buzzer=24) + assert cave["buttons"] == dict(stationary=dict(gpio=25, pull="down"), continuous=dict(gpio=8, pull="down")) + assert cave["fake_pps"] == [dict(gpio=3, uart="/dev/ttyAMA2"), dict(gpio=2, uart="/dev/ttyAMA5")] + path = directory / "candidate.json" + path.write_text(json.dumps(cave)) + validate(path) + for field in ("benchmark_usb", "buzzer", "uart"): + invalid = copy.deepcopy(cave) + if field == "benchmark_usb": + invalid["operation"][field] = "true" + elif field == "buzzer": + invalid["leds"][field] = invalid["leds"]["write"] + else: + del invalid["fake_pps"][0][field] + path.write_text(json.dumps(invalid)) + validate(path, field) + print("Validated four installed examples, CaveTronic wiring, and three invalid configurations.", flush=True) + return cave + + +def request(path): + with urlopen(PANEL + path, timeout=3) as response: + return response.read() + + +def wait_for_state(controller, wanted, timeout=35): + deadline = time.monotonic() + timeout + last = None + while time.monotonic() < deadline: + assert controller.poll() is None, f"controller exited with {controller.returncode}" + try: + last = json.loads(request("/json/status")) + except URLError: + time.sleep(0.1) + continue + if last["state"] == wanted: + return last + time.sleep(0.1) + raise AssertionError(f"waiting for {wanted}, last status {last}") + + +def finish_scan(controller, repo, config): + # Collect samples for the final partial chunk, then use the same endpoint as Stop Record. + time.sleep(1) + request("/trig/stop_bag") + status = wait_for_state(controller, "IDLE") + assert status["device_config"] == config and status["device_config_path"] == str(DEVICE) + assert status["lastSaveError"] == "" + assert status["lidar_sdk"] == "BUTTER_LIDAR" + git_sha = os.environ.get("GITHUB_SHA") + if git_sha: + assert git_sha == status["hash"], status["hash"] + final_file = Path(status["lastLazStatus"]["filename"]) + assert final_file.parent.parent == repo and final_file.parent.match("continousScanning_[0-9][0-9][0-9][0-9]") + assert final_file == max(final_file.parent.glob("lidar*.laz")) + chunk = final_file.stem.removeprefix("lidar") + cloud = laspy.read(final_file) + assert cloud.header.are_points_compressed + assert len(cloud.points) == status["lastLazStatus"]["points_count"] > 0 + assert all(abs(values - expected).max() < 0.0002 for values, expected in zip((cloud.x, cloud.y, cloud.z), (1, 2, 3))) + imu = (final_file.parent / f"imu{chunk}.csv").read_text().splitlines() + assert imu[0].split()[:4] == ["timestamp", "gyroX", "gyroY", "gyroZ"] + assert len(imu) > 1 + for row in imu[1:]: + timestamp, *axes, sensor, epoch = row.split() + assert int(timestamp) > 0 and list(map(float, axes)) == [.01, .02, .03, .1, .2, .3] + assert int(sensor) == 0 and int(epoch) > 0 + saved = json.loads((final_file.parent / f"status{chunk}.json").read_text()) + assert saved["state"] == "STOPPING" and saved["hash"] == status["hash"] + assert saved["lastLazStatus"] == status["lastLazStatus"] + print(f"{final_file.name}: {len(cloud.points)} points, {len(imu)-1} IMU rows, final status {saved['state']}", flush=True) + return final_file + + +def scan(repo, config, usb): + env = dict(os.environ, MANDEYE_REPO=str(repo), MANDEYE_GPIO_SIM="1", MANDEYE_DISABLE_BUZZER="1", + MANDEYE_LIDAR_SDK="LIVOX_SDK2" if usb else "BUTTER_LIDAR") + acquisition = {"picamera": {"resolution": [640, 480]}, "operation": {"autostart_recording": False}} + if usb: + acquisition["lidar_sdk"] = "BUTTER_LIDAR" + repo.mkdir() + (repo / "mandeye_config.json").write_text(json.dumps(acquisition)) + with tempfile.TemporaryFile(mode="w+") as log: + proc = subprocess.Popen([PROGRAM], stdin=subprocess.PIPE, stdout=log, stderr=subprocess.STDOUT, env=env) + try: + wait_for_state(proc, "SCANNING") + assert b"Start Record" in request("/") + first = finish_scan(proc, repo, config) + # Original CM5 policy re-entered SCANNING on the very next IDLE iteration. + for _ in range(10): + time.sleep(.15) + assert json.loads(request("/json/status"))["state"] == "IDLE" + request("/trig/start_bag") + wait_for_state(proc, "SCANNING") + assert finish_scan(proc, repo, config) != first + proc.communicate(input=b"q\n", timeout=12) + assert proc.returncode == 0 + except BaseException: + proc.kill() + proc.wait() + log.seek(0) + print(log.read()[-6000:], flush=True) + raise + + +def check_failed_save(directory, mode): + repo = directory / f"failed-{mode}" + repo.mkdir() + env = dict(os.environ, MANDEYE_REPO=str(repo), MANDEYE_GPIO_SIM="1", + MANDEYE_LIDAR_SDK="BUTTER_LIDAR") + with tempfile.TemporaryFile(mode="w+") as log: + proc = subprocess.Popen([PROGRAM], stdin=subprocess.PIPE, stdout=log, + stderr=subprocess.STDOUT, env=env) + try: + status = wait_for_state(proc, "SCANNING") + if mode in ("final", "laz-full"): + first = finish_scan(proc, repo, status["device_config"]) + request("/trig/start_bag") + wait_for_state(proc, "SCANNING") + target = first.with_name(f"lidar{int(first.stem[5:]) + 1:04d}.laz") + if mode == "final": + # Reject opening the LAZ path even when CI runs as root. + target.mkdir() + else: + target.symlink_to("/dev/full") + request("/trig/stop_bag") + elif mode == "periodic": + target = next(repo.glob("continousScanning_*")) / "imu0000.csv" + target.symlink_to("/dev/full") + else: + first = finish_scan(proc, repo, status["device_config"]) + target = next(repo.glob("stopScans_*")) / f"status{int(first.stem[5:]) + 1:04d}.json" + target.symlink_to("/dev/full") + request("/trig/stopscan") + status = wait_for_state(proc, "USB_IO_ERROR", timeout=50) + assert str(target) in status["lastSaveError"], status + assert status["lastLazStatus"]["filename"] == "", status + request("/trig/start_bag") + assert json.loads(request("/json/status"))["state"] == "USB_IO_ERROR" + print(f"{mode} save reported USB_IO_ERROR for {target.name}.", flush=True) + finally: + proc.kill() + proc.wait() + + +def check_disconnected_gpio(directory, config): + config = copy.deepcopy(config) + config["leds"].update(continuous=None, buzzer=None) + config["buttons"]["continuous"] = None + DEVICE.write_text(json.dumps(config)) + repo = directory / "disconnected-gpio" + repo.mkdir() + env = dict(os.environ, MANDEYE_REPO=str(repo), MANDEYE_GPIO_SIM="1", + MANDEYE_LIDAR_SDK="BUTTER_LIDAR") + with tempfile.TemporaryFile() as log: + proc = subprocess.Popen([PROGRAM], stdin=subprocess.PIPE, stdout=log, + stderr=subprocess.STDOUT, env=env) + try: + status = wait_for_state(proc, "SCANNING") + assert status["device_config"] == config and status["buzzer"] is False + assert status["gpio"]["leds"] == dict(LED_GPIO_STOP_SCAN=False, LED_GPIO_COPY_DATA=False, + LED_GPIO_CONTINOUS_SCANNING="NA", BUZZER="NA") + assert status["gpio"]["buttons"] == dict(BUTTON_STOP_SCAN=False, BUTTON_CONTINOUS_SCANNING="NA") + finish_scan(proc, repo, config) + finally: + proc.kill() + proc.wait() + + +def check_default_sdk(directory): + repo = directory / "default-sdk" + repo.mkdir() + # With no USB JSON and no environment selection, load the packaged Livox + # driver on loopback. No scanner is attached to this disposable machine. + env = dict(os.environ, MANDEYE_REPO=str(repo), MANDEYE_GPIO_SIM="1", + MANDEYE_DISABLE_BUZZER="1", MANDEYE_LIVOX_LISTEN_IP="127.0.0.1") + env.pop("MANDEYE_LIDAR_SDK", None) + proc = subprocess.Popen([PROGRAM], cwd=directory, env=env, stdout=subprocess.DEVNULL) + try: + status = wait_for_state(proc, "WAIT_FOR_RESOURCES") + assert status["lidar_sdk"] == "LIVOX_SDK2" and "init_success" in status["lidar"] + print("Loaded the packaged Livox driver with no USB or environment SDK selection.", flush=True) + finally: + proc.terminate() + proc.wait(timeout=5) + + +def check_usb_restart(directory): + cm5 = json.loads((EXAMPLES / "cm5-direct.json").read_text()) + assert all(cm5["operation"][name] for name in + ("benchmark_usb", "wait_for_lidar_sync", "autostart_recording", + "beep_on_laz", "restart_on_usb_error")) + DEVICE.write_text(json.dumps(cm5)) + env = dict(os.environ, MANDEYE_REPO=str(directory / "missing-drive"), + MANDEYE_LIDAR_SDK="BUTTER_LIDAR", MANDEYE_GPIO_SIM="1", MANDEYE_DISABLE_BUZZER="1") + result = subprocess.run([PROGRAM], stdin=subprocess.DEVNULL, env=env, + capture_output=True, text=True, timeout=25) + assert result.returncode == 1, (result.returncode, result.stderr) + assert "USB_IO_ERROR on three observations" in result.stderr, result.stderr + assert result.stdout.count("app_state == States::USB_IO_ERROR") == 2, result.stdout + print("CM5 Direct exited on its third USB error observation.", flush=True) + + +if __name__ == "__main__": + with tempfile.TemporaryDirectory() as tmp: + directory = Path(tmp) + cave = verify_configs(directory) + cave["operation"]["autostart_recording"] = True + with DEVICE.open("x") as active: # Refuse to overwrite any operator configuration. + json.dump(cave, active) + try: + scan(directory / "usb-sdk", cave, usb=True) + scan(directory / "environment-sdk", cave, usb=False) + for mode in ("final", "laz-full", "periodic", "stationary"): + check_failed_save(directory, mode) + check_disconnected_gpio(directory, cave) + check_default_sdk(directory) + check_usb_restart(directory) + finally: + DEVICE.unlink() diff --git a/tests/package/boot-test.sh b/tests/package/boot-test.sh new file mode 100755 index 0000000..0a66a70 --- /dev/null +++ b/tests/package/boot-test.sh @@ -0,0 +1,95 @@ +#!/bin/bash +# Boot Bookworm on independent virtio disks so storage checks can use the real +# kernel mount table, block ancestry, service credentials and enablement state. +set -euo pipefail +new=$(realpath "$1") +old=$(realpath "$2") +root=$(cd "$(dirname "$0")/../.." && pwd) +revision=${GITHUB_SHA:-$(git -C "$root" rev-parse HEAD)} +context=$(mktemp -d) +image="mandeye-bookworm-migration-$$" +cleanup() { + docker image rm "$image" >/dev/null 2>&1 || true + rm -rf "$context" +} +trap cleanup EXIT +cp "$new" "$context/new.deb" +cp "$old" "$context/legacy.deb" +cp "$root/.github/ci/bookworm-camera-archive.sh" "$context/" +cp "$root/tests/package/migration.sh" "$context/" +docker build -t "$image" -f - "$context" <<'DOCKER' +# syntax=docker/dockerfile:1 +FROM debian:bookworm AS guest +ENV DEBIAN_FRONTEND=noninteractive +COPY bookworm-camera-archive.sh /test/ +RUN bash /test/bookworm-camera-archive.sh && \ + apt-get install -y --no-install-recommends systemd-sysv sudo initramfs-tools linux-image-arm64 e2fsprogs +COPY new.deb legacy.deb /test/ +RUN apt-get satisfy -y --no-install-recommends \ + "$(dpkg-deb -f /test/legacy.deb Depends)" "$(dpkg-deb -f /test/new.deb Depends)" +COPY migration.sh /test/ +RUN <<'SETUP' +printf '%s\n' virtio_mmio virtio_pci virtio_blk ext4 >>/etc/initramfs-tools/modules +update-initramfs -u +cat >/etc/systemd/system/mandeye-ci.service <<'UNIT' +[Unit] +Description=Test the installed scanner package +Wants=dbus.service +After=dbus.service +[Service] +ExecStart=/bin/bash /test/run-migration +StandardOutput=journal+console +StandardError=journal+console +UNIT +cat >/test/run-migration <<'RUN' +set -eu +trap 'systemctl poweroff --no-block' EXIT +for arg in $(cat /proc/cmdline); do + case "$arg" in mandeye.scenario=*) scenario=${arg#*=} ;; mandeye.revision=*) export GITHUB_SHA=${arg#*=} ;; esac +done +if bash /test/migration.sh "$scenario"; then + echo "MANDEYE_MIGRATION_OK=$scenario" >/dev/console +else + journalctl -b --no-pager -n 100 >/dev/console + exit 1 +fi +RUN +SETUP + +FROM debian:bookworm +RUN apt-get update -qq && apt-get install -y --no-install-recommends qemu-system-arm e2fsprogs fdisk +RUN --mount=from=guest,target=/guest,ro <<'IMAGES' +set -eu +mkdir /test +cd /test +cp /guest/boot/vmlinuz-* kernel +cp /guest/boot/initrd.img-* initrd +# /dev/vda1 holds Bookworm. /dev/vda2 is a writable partition on the same +# disk. /dev/vdb and /dev/vdc model interchangeable recording media. +root_mib=3072 +second_mib=32 +second_start=$((1 + root_mib)) +truncate -s "$((second_start + second_mib))M" system.img +printf 'label: dos\nstart=2048,size=%d,type=83\nstart=%d,size=%d,type=83\n' \ + "$((root_mib * 2048))" "$((second_start * 2048))" "$((second_mib * 2048))" | sfdisk system.img +mkfs.ext4 -q -F -b 4096 -E offset=1048576 -d /guest system.img "$((root_mib * 256))" +mkfs.ext4 -q -F -b 4096 -E offset="$((second_start * 1048576))" system.img "$((second_mib * 256))" +for name in recorder replacement; do + truncate -s 96M "$name.img" + mkfs.ext4 -q -F "$name.img" +done +IMAGES +WORKDIR /test +DOCKER +for scenario in fresh disabled enabled custom-masked; do + # Each boot gets pristine copy-on-write disks, including after a failed test. + docker run --rm --network none "$image" timeout 12m qemu-system-aarch64 \ + -machine virt -cpu max -smp 2 -m 1024 -nographic -no-reboot -nic none \ + -kernel kernel -initrd initrd -snapshot \ + -drive file=system.img,format=raw,if=virtio \ + -drive file=recorder.img,format=raw,if=virtio \ + -drive file=replacement.img,format=raw,if=virtio \ + -append "console=ttyAMA0 root=/dev/vda1 rw rootwait panic=5 systemd.unit=mandeye-ci.service mandeye.scenario=$scenario mandeye.revision=$revision" \ + | tee "$context/guest.log" + grep -F "MANDEYE_MIGRATION_OK=$scenario" "$context/guest.log" +done diff --git a/tests/package/migration.sh b/tests/package/migration.sh new file mode 100755 index 0000000..f887b5c --- /dev/null +++ b/tests/package/migration.sh @@ -0,0 +1,379 @@ +#!/bin/bash +# Internal to boot-test.sh. This test configures a disposable systemd instance. +set -euo pipefail +test "$(< /proc/1/comm)" = systemd +test -b /dev/vda2 && test -b /dev/vdb && test -b /dev/vdc +grep -q "systemd.unit=mandeye-ci.service" /proc/cmdline +cd /test +vendor=mandeye_controller.service +fake=mandeye_fake_pps.service +slave=mandeye_slave_pps.service +package=mandeye-multisensor +assert_state() { + local actual + actual=$(systemctl -p "$2" --value show "$1") + if [[ "$actual" != "$3" ]]; then + echo "Expected $1 $2=$3, got $actual" >&2 + exit 1 + fi +} +assert_refusal() { + local diagnostic=$1 + shift + if "$@" > /tmp/mandeye-refusal.log 2>&1; then + echo "Unexpected success: $*" >&2 + exit 1 + fi + cat /tmp/mandeye-refusal.log + grep -F "$diagnostic" /tmp/mandeye-refusal.log +} +service_double() { + # Never open devices in a packaging test. Preserve unit selection, account, + # environment, systemd startup and apt/dpkg behavior. + local directory=/etc/systemd/system/"$1".d + mkdir -p "$directory" + cat > "$directory/50-test-executable.conf" <<'UNIT' +[Service] +ExecStartPre= +ExecStart= +ExecStart=/usr/bin/sleep infinity +UNIT +} + +readback() { + local unit=$1 + # The operator has now deliberately switched from their preserved private + # executable to the packaged one. Keep the actual service identity, mount, + # JSON, aliases and boot policy while simulating only the absent sensors. + systemctl stop "$unit" + mkdir -p "/etc/systemd/system/$unit.d" + cat > "/etc/systemd/system/$unit.d/95-installed-program.conf" <<'UNIT' +[Service] +ExecStartPre= +ExecStart= +ExecStart=/opt/mandeye/control_program +Environment=MANDEYE_LIDAR_SDK=BUTTER_LIDAR MANDEYE_GPIO_SIM=1 MANDEYE_DISABLE_BUZZER=1 +UNIT + systemctl daemon-reload + systemctl start "$unit" + python3 - "$unit" <<'PYTHON' +import json, os, pwd, subprocess, sys, time +from pathlib import Path +from urllib.error import URLError +from urllib.request import urlopen + +pid = int(subprocess.check_output(['systemctl', 'show', '-p', 'MainPID', '--value', sys.argv[1]])) +assert pid > 1 +process = Path('/proc') / str(pid) +program = Path('/opt/mandeye/control_program') +assert (process / 'exe').resolve() == program +assert process.stat().st_uid == pwd.getpwnam('mandeye').pw_uid +for _ in range(120): + try: + with urlopen('http://127.0.0.1:8003/json/status', timeout=2) as response: + status = json.load(response) + if status['state'] == 'IDLE': + break + except URLError: + pass + time.sleep(.5) +else: + raise AssertionError('The installed scanner did not reach IDLE') +assert status['hash'] == os.environ['GITHUB_SHA'], status['hash'] +assert status['device_config_path'] == '/etc/mandeye/device.json' +assert status['device_config'] == json.loads(Path(status['device_config_path']).read_text()) +assert status['lidar_sdk'] == 'BUTTER_LIDAR' +controllers = [] +for exe in Path('/proc').glob('[0-9]*/exe'): + try: + if exe.resolve(strict=True).name == 'control_program': + controllers.append(int(exe.parent.name)) + except (FileNotFoundError, PermissionError): + pass +assert controllers == [pid], controllers +print('Installed service:', sys.argv[1], 'PID', pid, 'user mandeye, revision', status['hash'], flush=True) +PYTHON +} + +if getent passwd pi; then exit 1; fi +useradd -m mandeye +scenario=$1 +if [[ "$scenario" == fresh ]]; then + apt-get install --no-install-recommends -y /test/new.deb + test ! -e /etc/mandeye/device.json + test -e /var/lib/mandeye/awaiting-activation + assert_state "$vendor" UnitFileState disabled + systemctl start "$vendor" + assert_state "$vendor" ActiveState inactive + for profile in rpi4 rpi5 pro-cm4-bookworm cm5-direct; do + /opt/mandeye/control_program --validate-config "/usr/share/mandeye/examples/$profile.json" + done + for program in control_program led_demo button_demo extras/mandeye_libcamera; do + test -x "/opt/mandeye/$program" + ldd "/opt/mandeye/$program" > /tmp/mandeye-libraries + if grep 'not found' /tmp/mandeye-libraries; then exit 1; fi + done + cp /usr/share/mandeye/examples/pro-cm4-bookworm.json /etc/mandeye/device.json + # CaveTronic wiring with character devices standing in for its two heads. + python3 - <<'PY' +import json +from pathlib import Path +p = Path('/etc/mandeye/device.json') +d = json.loads(p.read_text()) +d['name'] = 'CaveTronic' +d['gnss'] = None +d['gpiochip'] = '/dev/mandeye-ci-missing' +d['fake_pps'][0]['uart'] = '/dev/null' +d['fake_pps'][1]['uart'] = '/dev/full' +d['operation']['benchmark_usb'] = True +p.write_text(json.dumps(d) + '\n') +PY + service_double "$vendor" + service_double "$fake" + systemctl daemon-reload + printf 'mandeye ALL=(root) NOPASSWD: /usr/sbin/mandeye-activate\n' >/etc/sudoers.d/mandeye-test + activate=(runuser -u mandeye -- sudo -n /usr/sbin/mandeye-activate) + mkdir -p /media/usb + chown mandeye:mandeye /media/usb + assert_refusal 'system disk' "${activate[@]}" + assert_state "$vendor" UnitFileState disabled + mount /dev/vda2 /media/usb + chmod 0777 /media/usb + assert_refusal 'system disk' "${activate[@]}" + umount /media/usb + mount -t tmpfs -o mode=0777 tmpfs /media/usb + assert_refusal 'cannot identify a physical backing disk' "${activate[@]}" + umount /media/usb + mount /dev/vdb /media/usb + chmod 0777 /media/usb + assert_refusal '/dev/mandeye-ci-missing: missing character device' "${activate[@]}" + assert_state "$vendor" UnitFileState disabled + sed -i 's|/dev/mandeye-ci-missing|/dev/zero|' /etc/mandeye/device.json + chmod 0555 /media/usb + assert_refusal 'could not create a recording file' "${activate[@]}" + chmod 0777 /media/usb + printf '[Service]\nExecStartPre=/bin/false\nRestart=no\n' > "/etc/systemd/system/$vendor.d/60-fail.conf" + systemctl daemon-reload + assert_refusal 'returned non-zero' "${activate[@]}" + test -e /var/lib/mandeye/awaiting-activation + test ! -e "/etc/systemd/system/$vendor.d/10-mandeye-account.conf" + assert_state "$fake" UnitFileState disabled + assert_state "$fake" ActiveState inactive + assert_state "$vendor" UnitFileState disabled + rm "/etc/systemd/system/$vendor.d/60-fail.conf" + systemctl daemon-reload + "${activate[@]}" + for u in "$vendor" mandeye_libcamera_cam{0,1}.service mandeye_extra_gnss.service \ + mandeye_oled_status.service mandeye_murata_uart_driver.service; do + assert_state "$u" User mandeye + done + for u in "$vendor" "$fake"; do + assert_state "$u" ActiveState active + assert_state "$u" UnitFileState enabled + done + assert_state "$fake" User root + assert_state "$slave" ActiveState inactive + assert_state "$slave" UnitFileState disabled + # Preserve a custom recording directory across a later activation without arguments. + # Check the value in the running process, including systemd quoting and percent escapes. + custom_repo='/media/usb/field "drive" 100%/' + install -d -o mandeye -g mandeye "$custom_repo" + systemctl stop "$vendor" + sed -i 's|/dev/full|/dev/urandom|' /etc/mandeye/device.json + fake_pid=$(systemctl show --property=MainPID --value "$fake") + "${activate[@]}" --repo "$custom_repo" + test "$fake_pid" != "$(systemctl show --property=MainPID --value "$fake")" + systemctl stop "$vendor" + "${activate[@]}" + pid=$(systemctl show --property=MainPID --value "$vendor") + tr '\0' '\n' < "/proc/$pid/environ" > /tmp/mandeye-running-env + grep -Fx "MANDEYE_REPO=$custom_repo" /tmp/mandeye-running-env + + # EnvironmentFile overrides Environment assignments. Check the directory that + # the service really receives before allowing it to start. + env_repo='/media/usb/from environment/' + install -d -o mandeye -g mandeye "$env_repo" + printf "MANDEYE_REPO='%s'\n" "$env_repo" > /etc/mandeye/recording.env + printf '[Service]\nEnvironmentFile=/etc/mandeye/recording.env\n' > "/etc/systemd/system/$vendor.d/owner.conf" + systemctl daemon-reload + systemctl stop "$vendor" + sha256sum "/etc/systemd/system/$vendor.d/10-mandeye-account.conf" > /tmp/previous-account.sha256 + assert_refusal 'but the checked mount is' "${activate[@]}" --repo "$custom_repo" + sha256sum -c /tmp/previous-account.sha256 + assert_state "$vendor" ActiveState inactive + "${activate[@]}" + pid=$(systemctl show --property=MainPID --value "$vendor") + tr '\0' '\n' < "/proc/$pid/environ" > /tmp/mandeye-running-env + grep -Fx "MANDEYE_REPO=$env_repo" /tmp/mandeye-running-env + + # Switching profiles retires only PPS previously started and enabled by + # activation. An independently running SlavePPS retains its PID and policy. + systemctl stop "$vendor" + service_double "$slave" + systemctl daemon-reload + systemctl start "$slave" + slave_pid=$(systemctl show --property=MainPID --value "$slave") + python3 - <<'PYTHON' +import json +from pathlib import Path +p = Path('/etc/mandeye/device.json') +d = json.loads(p.read_text()) +d['fake_pps'] = [] +p.write_text(json.dumps(d)) +PYTHON + "${activate[@]}" + assert_state "$fake" ActiveState inactive + assert_state "$fake" UnitFileState disabled + assert_state "$slave" MainPID "$slave_pid" + assert_state "$slave" UnitFileState disabled + + systemctl stop "$vendor" + umount /media/usb + mkdir -p "$env_repo" + chown mandeye:mandeye "$env_repo" + systemctl start "$vendor" + assert_state "$vendor" ActiveState inactive + mount /dev/vdc /media/usb + install -d -o mandeye -g mandeye "$env_repo" + readback "$vendor" + + # A session with the previous helper aliases can reload the installed file. + bash -O expand_aliases -ec ' + alias mandeye_start=false mandeye_stop=false mandeye_status=false mandeye_log=false + alias GPIO_BUZZER_ON=false GPIO_BUZZER_OFF=false + source /opt/mandeye/helpers.sh + test "$(type -t mandeye_start)" = function + ! alias GPIO_BUZZER_ON + ! alias GPIO_BUZZER_OFF + ' + echo "PASS: clean install and activation by mandeye, permissions, mount and retry checks" + exit 0 +fi + +apt-get install --no-install-recommends -y /test/legacy.deb +old_version=$(dpkg-query -W -f='${Version}' "$package") +old_postinst=$(dpkg-query --control-path "$package" postinst) +test ! -f "/var/lib/dpkg/info/$package.prerm" +test "$(sha256sum "$old_postinst" | cut -d' ' -f1)" = d5b5657277c18394e458aed777e01ca474007043a9884a8ff9634c5a0e4bf4a4 +sha256sum /opt/mandeye/control_program "$old_postinst" > /tmp/mandeye-legacy.sha256 +install -d /etc/mandeye +# A scanner owner explicitly maps their historical build to a local JSON. +dpkg-deb --fsys-tarfile new.deb | tar -xO ./usr/share/mandeye/examples/pro-cm4-bookworm.json >/etc/mandeye/device.json +sed -i '/"gnss": {/,/^ },/c\ "gnss": null,' /etc/mandeye/device.json +printf '\n' >> /etc/mandeye/device.json +selected=$vendor +selector=$vendor +if [[ "$scenario" == enabled ]]; then + selector=field-scanner.service + ln -s "$vendor" "/etc/systemd/system/$selector" + printf '%s\n' "$selector" > /etc/mandeye/controller-unit +fi +if [[ "$scenario" == custom-masked ]]; then + selected=my-scanner.service + selector=custom-alias.service + ln -s "$selected" "/etc/systemd/system/$selector" + printf '%s\n' "$selector" > /etc/mandeye/controller-unit + systemctl mask "$vendor" +fi +mkdir -p "/etc/systemd/system/$selected.d" "/etc/systemd/system/$slave.d" +# Preserve both a complete local unit and a drop-in; its home-directory +# executable lets the operator recognize an old private binary after upgrade. +cat > "/etc/systemd/system/$selected" <<'UNIT' +[Unit] +Description=Local scanner +[Service] +User=mandeye +ExecStart=/home/mandeye/control_program +[Install] +WantedBy=multi-user.target +UNIT +printf '#!/bin/sh\nexec /usr/bin/sleep infinity\n' >/home/mandeye/control_program +chmod 0755 /home/mandeye/control_program +printf '[Service]\nEnvironment=MANDEYE_LIDAR_SDK=BUTTER_LIDAR\n' >"/etc/systemd/system/$selected.d/owner.conf" +printf '[Service]\nEnvironment=SLAVE_PPS_UART_PORT=/dev/ttyCI SLAVE_PPS_UART_BAUD_RATE=115200 SLAVE_PPS_DEVICE=/dev/pps7\n' \ + >"/etc/systemd/system/$slave.d/owner.conf" +systemctl daemon-reload +if [[ "$scenario" == disabled ]]; then + systemctl disable "$selected" + boot=disabled +else + systemctl enable "$selected" + boot=enabled +fi +assert_state "$selected" UnitFileState "$boot" +sha256sum /etc/mandeye/device.json "/etc/systemd/system/$selected" \ + "/etc/systemd/system/$selected.d/owner.conf" "/etc/systemd/system/$slave.d/owner.conf" > /tmp/mandeye-local.sha256 + +systemctl start "$selected" +pid=$(systemctl show --property=MainPID --value "$selected") +assert_refusal "Upgrade refused: $selector is active" dpkg -i /test/new.deb +test "$(dpkg-query -W -f='${Status} ${Version}' "$package")" = "install ok installed $old_version" +sha256sum -c /tmp/mandeye-legacy.sha256 +sha256sum -c /tmp/mandeye-local.sha256 +test ! -e "$old_postinst.mandeye-before-unwind" +assert_state "$selected" MainPID "$pid" +assert_state "$selected" UnitFileState "$boot" +if [[ "$scenario" == custom-masked ]]; then assert_state "$vendor" LoadState masked; fi + +systemctl stop "$selected" +dpkg -i /test/new.deb +test "$(dpkg-query -W -f='${Status} ${Version}' "$package")" = "install ok installed $(dpkg-deb -f new.deb Version)" +sha256sum -c /tmp/mandeye-local.sha256 +assert_state "$selected" ActiveState inactive +assert_state "$selected" UnitFileState "$boot" +assert_state "$selected" User mandeye +/usr/sbin/mandeye-activate --status | tee /tmp/effective +grep -Fx "Unit=$selector" /tmp/effective +grep -Fx 'User=mandeye' /tmp/effective +grep -F '/home/mandeye/control_program' /tmp/effective +# Check the actual SlavePPS parser under systemd with the preserved drop-in. +mkdir -p "/etc/systemd/system/$slave.d" +cat > "/etc/systemd/system/$slave.d/90-check-input.conf" <<'UNIT' +[Service] +Type=oneshot +Restart=no +ExecStartPre= +ExecStart= +ExecStart=/opt/mandeye/extras/slave_pps --validate-config +StandardOutput=file:/tmp/slave-effective +UNIT +systemctl daemon-reload +systemctl start "$slave" +python3 - <<'PY' +import json +from pathlib import Path +assert json.loads(Path('/tmp/slave-effective').read_text()) == dict(uart='/dev/ttyCI', baud=115200, device='/dev/pps7') +PY +mkdir -p /media/usb +chown mandeye:mandeye /media/usb +systemctl start "$selected" +assert_state "$selected" ActiveState inactive +mount /dev/vdb /media/usb +chown mandeye:mandeye /media/usb +systemctl start "$selected" +assert_state "$selected" ActiveState active +# A second upgrade refusal now uses the new package's scripts. +assert_refusal "Upgrade refused: $selector is active" dpkg -i /test/new.deb +assert_state "$selected" UnitFileState "$boot" +if [[ "$scenario" == custom-masked ]]; then + assert_state "$vendor" LoadState masked + # Also exercise a complete, unmasked local vendor unit on the same scanner. + systemctl unmask "$vendor" + cp "/etc/systemd/system/$selected" "/etc/systemd/system/$vendor" + systemctl daemon-reload + systemctl start "$vendor" + assert_state "$vendor" ActiveState inactive + assert_state "$selected" ActiveState active + # A local vendor alias of the selected unit names the very same process. + systemctl stop "$selected" + rm "/etc/systemd/system/$vendor" + ln -s "$selected" "/etc/systemd/system/$vendor" + systemctl daemon-reload + systemctl start "$selected" + assert_state "$selected" ActiveState active + assert_state "$vendor" MainPID "$(systemctl show --property=MainPID --value "$selected")" +fi +readback "$selected" +assert_state "$selected" UnitFileState "$boot" +assert_state "$selector" MainPID "$(systemctl show --property=MainPID --value "$selected")" +echo "PASS: dpkg refusal, rollback, stopped upgrade and operator restart ($scenario)" diff --git a/tests/package/test-activation.py b/tests/package/test-activation.py new file mode 100644 index 0000000..5f8400e --- /dev/null +++ b/tests/package/test-activation.py @@ -0,0 +1,63 @@ +"""Local regressions for activation's settings and failure recovery.""" +import importlib.machinery +import importlib.util +from pathlib import Path +import tempfile +import unittest +from unittest.mock import patch + +loader = importlib.machinery.SourceFileLoader('activate', str(Path(__file__).resolve().parents[2] / 'packing/mandeye-activate')) +spec = importlib.util.spec_from_loader(loader.name, loader) +activate = importlib.util.module_from_spec(spec) +loader.exec_module(activate) + + +class Settings(unittest.TestCase): + def test_existing_settings_and_absent_files_survive_failed_activation(self): + with tempfile.TemporaryDirectory() as tmp: + existing = Path(tmp) / 'unit.d/account.conf' + existing.parent.mkdir() + existing.write_bytes(b'owner override\n') + existing.chmod(0o640) + absent = Path(tmp) / 'activation-state' + with self.assertRaises(RuntimeError): + with activate.FileChanges() as files: + files.write(existing, 'new setting') + files.write(absent, 'helper-owned') + raise RuntimeError('systemd refused the change') + self.assertEqual(existing.read_bytes(), b'owner override\n') + self.assertEqual(existing.stat().st_mode & 0o777, 0o640) + self.assertFalse(absent.exists()) + + def test_requested_legacy_pps_reloads_only_the_standard_program(self): + previous = {} # Earlier versions did not record which PPS they enabled. + inputs = {'uart': '/dev/ttyAMA1'} + for path, want in (('/opt/mandeye/extras/slave_pps (deleted)', True), + ('/usr/local/sbin/private-clock', False)): + with self.subTest(path=path), patch.object(activate, 'property_of', return_value='123'), \ + patch.object(activate.os, 'readlink', return_value=path): + self.assertEqual(activate.needs_pps_restart(activate.SLAVE, False, previous, inputs), want) + self.assertFalse(activate.needs_pps_restart(activate.SLAVE, False, {activate.SLAVE: inputs}, inputs)) + + def test_http_only_controller_needs_no_gpio_device_access(self): + config = {'buttons': {'continuous': None}, 'leds': {'write': None}, 'fake_pps': [{'gpio': 2}]} + self.assertFalse(activate.uses_controller_gpio(config)) + config['leds']['write'] = 0 + self.assertTrue(activate.uses_controller_gpio(config)) + config['leds']['write'] = None + config['buttons']['continuous'] = {'gpio': 0, 'pull': 'up'} + self.assertTrue(activate.uses_controller_gpio(config)) + + def test_controller_waits_for_the_escaped_recording_mount_at_boot(self): + expected = 'RequiresMountsFor="/mnt/My \\"USB\\" 100%%"\n' + self.assertIn(expected, activate.account_settings(activate.VENDOR, 'darek', '/mnt/My "USB" 100%')) + + def test_picamera_reads_the_selected_recording_mount(self): + for unit in ('mandeye_picamera.service', 'mandeye_picamera_ftp.service'): + text = activate.account_settings(unit, 'darek', '/mnt/My "USB" 100%') + self.assertIn('User=darek\n', text) + self.assertIn('Environment="MANDEYE_REPO=/mnt/My \\"USB\\" 100%%"\n', text) + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/package/test-device-config.py b/tests/package/test-device-config.py new file mode 100644 index 0000000..c9eda81 --- /dev/null +++ b/tests/package/test-device-config.py @@ -0,0 +1,95 @@ +"""Run against the installed package in a clean Bookworm test system.""" + +import json +import os +from pathlib import Path +import subprocess +import tempfile + + +DEVICE = Path("/etc/mandeye/device.json") +EXAMPLE = Path("/usr/share/mandeye/examples/pro-cm4-bookworm.json") +PROGRAMS = [ + "/opt/mandeye/control_program", + "/opt/mandeye/led_demo", + "/opt/mandeye/button_demo", + "/opt/mandeye/extras/mandeye_fake_pps", + "/opt/mandeye/extras/slave_pps", +] +SLAVE = PROGRAMS[-1] +PORT = "SLAVE_PPS_UART_PORT" +RATE = "SLAVE_PPS_UART_BAUD_RATE" +PPS = "SLAVE_PPS_DEVICE" + + +def run(args, overrides=None, error=None): + env = {k: v for k, v in os.environ.items() if k not in (PORT, RATE, PPS)} + proc = subprocess.run( + args, env=env | (overrides or {}), text=True, capture_output=True, timeout=5 + ) + if error is not None: + assert proc.returncode == 1 and error in proc.stderr, (args, proc) + return + assert proc.returncode == 0, (args, proc) + return json.loads(proc.stdout) + + +def check_startup_errors(device): + # All five programs must report a bad field even on a host without GPIO or UART. + invalid = device | {"fake_pps": [{"gpio": 3}]} + with DEVICE.open("x") as active: + json.dump(invalid, active) + try: + for program in PROGRAMS: + run([program], error="/fake_pps/0/uart: missing required field") + finally: + DEVICE.unlink() + + +def check_optional_gpio(device, path): + config = device | {"leds": dict.fromkeys(device["leds"]), "buttons": dict.fromkeys(device["buttons"])} + path.write_text(json.dumps(config)) + assert run([PROGRAMS[0], "--validate-config", path]) == config + for field in ("leds", "buttons"): + del config[field]["stationary"] + path.write_text(json.dumps(config)) + run([PROGRAMS[0], "--validate-config", path], error=f"/{field}/stationary: missing required field") + config[field]["stationary"] = None + + +def check_slave_pps(device, path): + cmd = [SLAVE, "--validate-config", path] + path.write_text(json.dumps(device)) + run(cmd, error="/slave_pps: configure") + # Each partial legacy override retains the old fallback for the omitted fields. + fallback = {"uart": "/dev/ttyAMA2", "baud": 9600, "device": "/dev/pps0"} + for env, expected in [ + ({PORT: "/dev/ttyS1"}, {"uart": "/dev/ttyS1"}), + ({RATE: "38400"}, {"baud": 38400}), + ({PPS: "/dev/pps1"}, {"device": "/dev/pps1"}), + ( + {PORT: "/dev/ttyS2", RATE: "4800", PPS: "/dev/pps2"}, + {"uart": "/dev/ttyS2", "baud": 4800, "device": "/dev/pps2"}, + ), + ]: + assert run(cmd, env) == fallback | expected + run(cmd, {RATE: "9600oops"}, error=RATE) + run(cmd, {PPS: "pps2"}, error=PPS) + + explicit = {"uart": "/dev/serial0", "baud": 115200, "device": "/dev/pps2"} + path.write_text(json.dumps(device | {"slave_pps": explicit, "fake_pps": []})) + assert run(cmd) == explicit + assert run(cmd, {RATE: "19200"}) == explicit | {"baud": 19200} + + path.write_text(json.dumps(device | {"fake_pps": []})) + assert run(cmd, {RATE: "19200"}) == fallback | {"uart": "/dev/ttyAMA1", "baud": 19200} + + +if __name__ == "__main__": + device = json.loads(EXAMPLE.read_text()) + check_startup_errors(device) + with tempfile.TemporaryDirectory() as tmp: + path = Path(tmp) / "device.json" + check_optional_gpio(device, path) + check_slave_pps(device, path) + print("All five consumers rejected an invalid device before I/O; SlavePPS overrides passed.") diff --git a/tests/package/test-picamera-config.py b/tests/package/test-picamera-config.py new file mode 100644 index 0000000..e615df5 --- /dev/null +++ b/tests/package/test-picamera-config.py @@ -0,0 +1,54 @@ +"""Exercise the installed Picamera2 startup up to camera capture, without hardware.""" +import json +from pathlib import Path +import runpy +import sys +import tempfile +from types import SimpleNamespace +from unittest.mock import patch + + +class CameraStarted(Exception): + pass + + +class Camera: + sensor_resolution = (640, 480) + camera_controls = {"ExposureValue": (-8.0, 8.0, 0.0), "OptionalLimit": (None, 1, 0)} + + def __init__(self): + self.controls = {} + + def create_still_configuration(self, main): + return main + + def configure(self, config): + pass + + def set_controls(self, controls): + self.controls.update(controls) + + def start(self): + raise CameraStarted + + +def check(program): + camera = Camera() + modules = {"picamera2": SimpleNamespace(Picamera2=lambda: camera), "zmq": SimpleNamespace()} + with tempfile.TemporaryDirectory() as repo: + config = Path(repo, "mandeye_config.json") + original = {"lidar_sdk": "LIVOX_SDK2", "picamera": {"ExposureValue": -2.0}} + config.write_text(json.dumps(original)) + with patch.dict("os.environ", MANDEYE_REPO=repo), patch.dict(sys.modules, modules): + try: + runpy.run_path(program, run_name="__main__") + except CameraStarted: + pass + assert camera.controls == original["picamera"], camera.controls + assert json.loads(config.read_text()) == original + assert json.loads(Path(str(config) + ".default").read_text())["picamera"]["ExposureValue"] == 0.0 + + +if __name__ == "__main__": + check(sys.argv[1] if len(sys.argv) > 1 else "/opt/mandeye/extras/picamera2/camera.py") + print("Picamera2 used the recording volume and preserved the shared acquisition settings.") diff --git a/tests/package/test-storage.py b/tests/package/test-storage.py new file mode 100644 index 0000000..7938f7b --- /dev/null +++ b/tests/package/test-storage.py @@ -0,0 +1,60 @@ +"""Exercise the Linux block topology used by the scanner without requiring root.""" +import importlib.machinery +import importlib.util +from pathlib import Path +import tempfile +import unittest + +script = Path(__file__).resolve().parents[2] / 'packing/mandeye-storage' +loader = importlib.machinery.SourceFileLoader('storage', str(script)) +spec = importlib.util.spec_from_loader(loader.name, loader) +storage = importlib.util.module_from_spec(spec) + + +class Storage(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.addCleanup(self.tmp.cleanup) + self.sysfs = Path(self.tmp.name).resolve() + self.sd = self.block('devices/platform/mmc/mmcblk0', '179:0') + self.root = self.partition(self.sd, 'mmcblk0p2', '179:2') + self.boot = self.partition(self.sd, 'mmcblk0p1', '179:1') + self.usb = self.block('devices/pci/usb/block/sda', '8:0') + self.recordings = self.partition(self.usb, 'sda1', '8:1') + + def block(self, path, number): + block = self.sysfs / path + (block / 'slaves').mkdir(parents=True) + (block / 'dev').write_text(number) + index = self.sysfs / 'dev/block' + index.mkdir(parents=True, exist_ok=True) + (index / number).symlink_to(block) + return block + + def partition(self, disk, name, number): + partition = self.block(disk / name, number) + (partition / 'partition').touch() + return partition + + def disks(self, device): + return storage.disks_for_block(device, self.sysfs) + + def test_partitions_on_system_disk_share_backing(self): + self.assertEqual(self.disks(self.root), self.disks(self.boot)) + self.assertTrue(self.disks(self.root).isdisjoint(self.disks(self.recordings))) + + def test_mapped_devices_include_all_underlying_disks(self): + mapped = self.block('devices/virtual/block/dm-0', '254:0') + for path in (self.root, self.recordings): + (mapped / 'slaves' / path.name).symlink_to(path) + self.assertEqual(self.disks(mapped), self.disks(self.root) | self.disks(self.recordings)) + + def test_ram_and_loop_images_are_not_independent_disks(self): + for device in ('zram0', 'loop0', 'ram0'): + with self.subTest(device=device), self.assertRaises(ValueError): + self.disks(self.block('devices/virtual/block/' + device, device)) + + +if __name__ == '__main__': + loader.exec_module(storage) + unittest.main()