Lab 6: Atomic Calibration Store, ARGB32 Gauge Rasterizer & SignalSpy Harness
Persist HMI configuration crash-atomically via QSaveFile fsync-and-rename, composite premultiplied ARGB32 QPainter gauges and batched QtCharts waveforms, and automate headless offscreen QTest TAP 13 CI.
Prerequisites in this module
What ./check.sh verifies
- Builds libcore.a and lab_cli cleanly with -std=c++20 -Wall -Wextra -Werror -pedantic.
- Fix compiler warnings or errors in files/core.cpp.
- Archives core.o into libcore.a and links independent TAP verifier.
- Preserve public declarations in files/core.hpp so tests.cpp links.
step 1/15 · inspect starter files and specification
Integrate and verify an end-to-end C++20 HMI Gauge Capstone uniting QSaveFile-style fsync + rename calibration persistence, clipped premultiplied ARGB32 SourceOver rasterization, ring-buffered waveform snapshots, and QSignalSpy-style rising-edge hysteresis tests.
learner@ksa:~/gl-q01/lab-m06ls -lastarter/Makefilestarter/cli.cppstarter/core.cppstarter/core.hpplearner@ksa:~/gl-q01/lab-m06starter: starter/Makefile
learner@ksa:~/gl-q01/lab-m06$ bat starter/Makefile File: starter/Makefile CC_BIN = g++ AR = ar CFLAGS_ALL = -std=c++20 -Wall -Wextra -Werror -pedantic -O2 LDLIBS = all: libcore.a lab_cli libcore.a: core.o $(AR) rcs $@ $^ lab_cli: cli.o libcore.a $(CC_BIN) $(CFLAGS_ALL) cli.o libcore.a $(LDLIBS) -o $@ %.o: %.cpp core.hpp $(CC_BIN) $(CFLAGS_ALL) -c $< -o $@ .PHONY: all clean clean: rm -f core.o cli.o libcore.a lab_clistarter: starter/cli.cpp
learner@ksa:~/gl-q01/lab-m06$ bat starter/cli.cpp File: starter/cli.cpp #include "core.hpp" #include <algorithm> #include <array> #include <cstdint> #include <cstdio> #include <cstring> #include <ctime> static std::uint64_t now_ns() noexcept { timespec ts{}; clock_gettime(CLOCK_MONOTONIC, &ts); return static_cast<std::uint64_t>(ts.tv_sec) * 1000000000ULL + static_cast<std::uint64_t>(ts.tv_nsec); } int main(int argc, char **argv) { const std::uint32_t bg = hmi::pack_premul_argb32(255, 16, 24, 32); hmi::ArgbCanvas canvas(160, 160, bg); hmi::GaugeController ctl({-10, 400}, 256); if (argc > 1 && std::strcmp(argv[1], "--bench") == 0) { constexpr int kWarmup = 5; constexpr int kSamples = 40; constexpr int kBatch = 200; std::array<std::uint64_t, kSamples> ns{}; volatile std::uint32_t sink = 0U; for (int i = 0; i < kWarmup + kSamples; ++i) { const std::uint64_t t0 = now_ns(); for (int r = 0; r < kBatch; ++r) { ctl.set_raw_kpa(200 + (r % 260)); ctl.render_gauge(canvas); auto wave = ctl.snapshot_waveform_batch(); sink ^= canvas.pixel(80, 80) + static_cast<std::uint32_t>(wave.size()); } const std::uint64_t dt = (now_ns() - t0) / kBatch; if (i >= kWarmup) { ns[static_cast<std::size_t>(i - kWarmup)] = dt; } } std::sort(ns.begin(), ns.end()); std::printf("bench_gauge_render_ns: p50=%llu p95=%llu p99=%llu (sink=%u)\n", static_cast<unsigned long long>(ns[20]), static_cast<unsigned long long>(ns[37]), static_cast<unsigned long long>(ns[39]), sink); return 0; } int alarms = 0; ctl.on_alarm = [&](int) { ++alarms; }; ctl.set_raw_kpa(260); // 250 kPa nominal ctl.set_raw_kpa(425); // 415 kPa >= 400 alarm! ctl.set_raw_kpa(440); // stays high -> still 1 alarm ctl.render_gauge(canvas); const auto wave = ctl.snapshot_waveform_batch(); std::printf("capstone_gauge: comp_kpa=%d alarms=%d center_argb=0x%08X wave_pts=%zu\n", ctl.compensated_kpa(), alarms, canvas.pixel(80, 80), wave.size()); return (ctl.compensated_kpa() == 430 && alarms == 1 && wave.size() == 3U) ? 0 : 1; }starter: starter/core.cpp
learner@ksa:~/gl-q01/lab-m06$ bat starter/core.cpp File: starter/core.cpp #include "core.hpp" #include <algorithm> #include <cmath> #include <cstdlib> #include <fcntl.h> #include <numbers> #include <sstream> #include <unistd.h> namespace hmi { bool save_calibration_atomic(const std::string &path, const Calibration &cal, bool simulate_abort) { if (cal.alarm_kpa <= 0 || cal.alarm_kpa > 500) { return false; } const std::string tmp = path + ".tmp"; const int fd = ::openat(AT_FDCWD, tmp.c_str(), O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0600); if (fd < 0) { return false; } const std::string body = "zero=" + std::to_string(cal.zero_offset_kpa) + "\n" + "alarm=" + std::to_string(cal.alarm_kpa) + "\n"; std::size_t written = 0; while (written < body.size()) { const ssize_t n = ::write(fd, body.data() + written, body.size() - written); if (n <= 0) { ::close(fd); ::unlink(tmp.c_str()); return false; } written += static_cast<std::size_t>(n); } if (simulate_abort) { ::close(fd); return false; } if (::fsync(fd) != 0) { ::close(fd); ::unlink(tmp.c_str()); return false; } ::close(fd); if (::rename(tmp.c_str(), path.c_str()) != 0) { ::unlink(tmp.c_str()); return false; } return true; } bool load_calibration(const std::string &path, Calibration &out) { const int fd = ::openat(AT_FDCWD, path.c_str(), O_RDONLY | O_CLOEXEC); if (fd < 0) { return false; } char buf[256]{}; const ssize_t n = ::read(fd, buf, sizeof(buf) - 1U); ::close(fd); if (n <= 0) { return false; } std::istringstream iss(std::string(buf, static_cast<std::size_t>(n))); std::string line; int zero = 0; int alarm = -1; bool got_zero = false; bool got_alarm = false; while (std::getline(iss, line)) { if (line.rfind("zero=", 0) == 0) { zero = std::atoi(line.c_str() + 5); got_zero = true; } else if (line.rfind("alarm=", 0) == 0) { alarm = std::atoi(line.c_str() + 6); got_alarm = true; } } if (!got_zero || !got_alarm || alarm <= 0 || alarm > 500) { return false; } out.zero_offset_kpa = zero; out.alarm_kpa = alarm; return true; } std::uint32_t pack_premul_argb32(std::uint8_t a, std::uint8_t r, std::uint8_t g, std::uint8_t b) noexcept { const std::uint32_t pr = (static_cast<std::uint32_t>(r) * a + 127U) / 255U; const std::uint32_t pg = (static_cast<std::uint32_t>(g) * a + 127U) / 255U; const std::uint32_t pb = (static_cast<std::uint32_t>(b) * a + 127U) / 255U; return (static_cast<std::uint32_t>(a) << 24U) | (pr << 16U) | (pg << 8U) | pb; } std::uint32_t blend_premul_source_over(std::uint32_t src, std::uint32_t dst) noexcept { const std::uint32_t sa = (src >> 24U) & 0xFFU; if (sa == 255U) { return src; } if (sa == 0U) { return dst; } const std::uint32_t inv = 255U - sa; auto ch = [inv](std::uint32_t s, std::uint32_t d, unsigned shift) { const std::uint32_t sc = (s >> shift) & 0xFFU; const std::uint32_t dc = (d >> shift) & 0xFFU; return std::min(255U, sc + (dc * inv + 127U) / 255U); }; return (ch(src, dst, 24U) << 24U) | (ch(src, dst, 16U) << 16U) | (ch(src, dst, 8U) << 8U) | ch(src, dst, 0U); } ArgbCanvas::ArgbCanvas(int w, int h, std::uint32_t bg) : m_w(w), m_h(h), m_clip{0, 0, w, h}, m_pixels(static_cast<std::size_t>(w * h), bg) {} void ArgbCanvas::put_pixel(int x, int y, std::uint32_t premul_src) noexcept { if (x < 0 || x >= m_w || y < 0 || y >= m_h) { return; } auto &dst = m_pixels[static_cast<std::size_t>(y * m_w + x)]; dst = blend_premul_source_over(premul_src, dst); } void ArgbCanvas::draw_segment(int x0, int y0, int x1, int y1, std::uint32_t premul_src) noexcept { const int dx = std::abs(x1 - x0); const int sx = x0 < x1 ? 1 : -1; const int dy = -std::abs(y1 - y0); const int sy = y0 < y1 ? 1 : -1; int err = dx + dy; for (;;) { put_pixel(x0, y0, premul_src); if (x0 == x1 && y0 == y1) { break; } const int e2 = 2 * err; if (e2 >= dy) { err += dy; x0 += sx; } if (e2 <= dx) { err += dx; y0 += sy; } } } std::uint32_t ArgbCanvas::pixel(int x, int y) const noexcept { return m_pixels[static_cast<std::size_t>(y * m_w + x)]; } GaugeController::GaugeController(Calibration cal, std::size_t wave_cap) : m_cal(cal), m_ring(std::max<std::size_t>(1U, wave_cap), 0) {} void GaugeController::apply_calibration(Calibration cal) noexcept { m_cal = cal; } void GaugeController::set_raw_kpa(int raw_sensor_kpa) { const int comp = std::clamp(raw_sensor_kpa + m_cal.zero_offset_kpa, 0, 500); m_ring[m_head] = comp; m_head = (m_head + 1U) % m_ring.size(); if (m_count < m_ring.size()) { ++m_count; } if (comp == m_compensated_kpa) { return; } const bool was_alarm = (m_compensated_kpa >= m_cal.alarm_kpa); m_compensated_kpa = comp; const bool now_alarm = (m_compensated_kpa >= m_cal.alarm_kpa); if (now_alarm && on_alarm) { on_alarm(m_compensated_kpa); } } void GaugeController::render_gauge(ArgbCanvas &canvas) const noexcept { const int cx = canvas.width() / 2; const int cy = canvas.height() / 2; const double radius = std::min(cx, cy) * 0.75; const double deg = 210.0 - (240.0 * m_compensated_kpa / 500.0); const double rad = deg * std::numbers::pi / 180.0; const int tx = cx + static_cast<int>(std::lround(radius * std::cos(rad))); const int ty = cy - static_cast<int>(std::lround(radius * std::sin(rad))); const std::uint32_t color = in_alarm() ? pack_premul_argb32(255, 220, 38, 38) : pack_premul_argb32(255, 14, 165, 233); canvas.draw_segment(cx, cy, tx, ty, color); } std::vector<std::pair<int, int>> GaugeController::snapshot_waveform_batch() const { std::vector<std::pair<int, int>> batch; batch.reserve(m_count); const std::size_t start = (m_count == m_ring.size()) ? m_head : 0U; for (std::size_t i = 0; i < m_count; ++i) { const std::size_t idx = (start + i) % m_ring.size(); batch.emplace_back(static_cast<int>(i), m_ring[idx]); } return batch; } } // namespace hmistarter: starter/core.hpp
learner@ksa:~/gl-q01/lab-m06$ bat starter/core.hpp File: starter/core.hpp #pragma once #include <cstddef> #include <cstdint> #include <functional> #include <string> #include <utility> #include <vector> namespace hmi { struct Calibration { int zero_offset_kpa = 0; int alarm_kpa = 400; }; struct ClipRect { int x = 0; int y = 0; int w = 0; int h = 0; constexpr bool contains(int px, int py) const noexcept { return px >= x && px < (x + w) && py >= y && py < (y + h); } }; bool save_calibration_atomic(const std::string &path, const Calibration &cal, bool simulate_abort = false); bool load_calibration(const std::string &path, Calibration &out); std::uint32_t pack_premul_argb32(std::uint8_t a, std::uint8_t r, std::uint8_t g, std::uint8_t b) noexcept; std::uint32_t blend_premul_source_over(std::uint32_t src, std::uint32_t dst) noexcept; class ArgbCanvas { public: ArgbCanvas(int w, int h, std::uint32_t bg); void set_clip(ClipRect clip) noexcept { m_clip = clip; } void put_pixel(int x, int y, std::uint32_t premul_src) noexcept; void draw_segment(int x0, int y0, int x1, int y1, std::uint32_t premul_src) noexcept; std::uint32_t pixel(int x, int y) const noexcept; int width() const noexcept { return m_w; } int height() const noexcept { return m_h; } private: int m_w; int m_h; ClipRect m_clip; std::vector<std::uint32_t> m_pixels; }; class GaugeController { public: explicit GaugeController(Calibration cal = {}, std::size_t wave_cap = 64); void apply_calibration(Calibration cal) noexcept; void set_raw_kpa(int raw_sensor_kpa); int compensated_kpa() const noexcept { return m_compensated_kpa; } bool in_alarm() const noexcept { return m_compensated_kpa >= m_cal.alarm_kpa; } void render_gauge(ArgbCanvas &canvas) const noexcept; std::vector<std::pair<int, int>> snapshot_waveform_batch() const; std::function<void(int)> on_alarm; private: Calibration m_cal; int m_compensated_kpa = 0; std::vector<int> m_ring; std::size_t m_head = 0; std::size_t m_count = 0; }; } // namespace hmistep 2/15 · 2. learning objectives
- Guarantee crash-atomic configuration saves via
openat(.tmp) -> write -> fsync -> renameand clean.tmpunlinking on abort. - Enforce dirty-region
ClipRectboundaries and premultiplied ARGB32 Porter-DuffSourceOvercompositing on custom gauge needles. - Verify tare-compensated rising-edge alarm hysteresis and chronological ring-buffer waveform batches for
QLineSeries::replace().
step 3/15 · 3. environment requirements
All automated verification steps run in unprivileged user space on a POSIX Linux host using g++ -std=c++20 -Wall -Wextra -Werror -pedantic and clock_gettime(CLOCK_MONOTONIC). Recorded transcripts in captures.json were generated on x86_64 running kernel 7.0.0-42-generic and prove protocol, state-machine, and memory invariants only. Physical bus timing, DMA cache coherency, and board peripheral behavior require target validation on Linux kernel 6.12 LTS (ARMv7-A Cortex-A7).
step 4/15 · 4. required software and hardware
- Host workstation:
g++(-std=c++20 -Wall -Wextra -Werror -pedantic), GNUmake,ar(binutils), and POSIX/bin/sh. - Target environment (optional hardware step, Section 13):
ARMv7-ACortex-A7industrial HMI panel (800x480RGB LCD,8 GBeMMC) runningLinux kernel6.12 LTS, Qt 6.8QtWidgets+QtCharts, and headless CI gates underQT_QPA_PLATFORM=offscreen -o -,tap.
step 5/15 · 5. complete executable commands
learner@ksa:~/gl-q01/lab-m06$ bat script.sh File: script.sh make -B -C files ./files/lab_cli ./files/lab_cli --bench sh check.shstep 6/15 · 6. annotated source code
files/core.cpp enforces the production invariants that starter/core.cpp breaks:
learner@ksa:~/gl-q01/lab-m06$ bat example.cpp File: example.cpp void GaugeController::set_raw_kpa(int raw_sensor_kpa) { const int comp = std::clamp(raw_sensor_kpa + m_cal.zero_offset_kpa, 0, 500); m_ring[m_head] = comp; m_head = (m_head + 1U) % m_ring.size(); if (m_count < m_ring.size()) ++m_count; if (comp == m_compensated_kpa) return; const bool was_alarm = (m_compensated_kpa >= m_cal.alarm_kpa); m_compensated_kpa = comp; const bool now_alarm = (m_compensated_kpa >= m_cal.alarm_kpa); if (now_alarm && !was_alarm && on_alarm) { on_alarm(m_compensated_kpa); // Rising-edge hysteresis only! } }starter/core.cpp contains three realistic capstone bugs: save_calibration_atomic leaks .tmp on abort, ArgbCanvas::put_pixel ignores m_clip.contains(x, y), and GaugeController::set_raw_kpa fires on_alarm on every sample while high instead of only on rising-edge crossings.
step 7/15 · 7. expected output
Passing files/ run (sh check.sh, exit code 0):
learner@ksa:~/gl-q01/lab-m06$ bat listing.txt File: listing.txt TAP version 13 1..5 ok 1 - builds libcore.a and lab_cli cleanly with -std=c++20 -Wall -Wextra -Werror -pedantic ok 2 - archives core.o into libcore.a and links independent TAP verifier ok 3 - commits calibration atomically via fsync+rename and unlinks .tmp cleanly on abort ok 4 - composites premultiplied ARGB32 SourceOver strokes strictly inside dirty ClipRect bounds ok 5 - applies zero-offset tare, latches rising-edge alarm spy counts, and batches ring waveforms # pass 5/5CLI verification output (./files/lab_cli):
learner@ksa:~/gl-q01/lab-m06$ bat listing.txt File: listing.txt capstone_gauge: comp_kpa=430 alarms=1 center_argb=0xFFDC2626 wave_pts=3Defective starter/ run (exit code 1): emits FAIL: diagnostics on the broken contract assertions.
step 8/15 · 8. explanation of observed behavior
Check 3 commits {-15, 380} via fsync + rename, triggers a simulated abort on {+99, 450}, confirms .tmp was unlinked, and reloads intact {-15, 380}. Check 4 draws a 50% translucent stroke across {10, 10, 40, 40}, proving premultiplied blending inside the clip and untouched background at (60, 20). Check 5 drives GaugeController across five tare-compensated readings, asserting rising-edge spy hits {405, 410}, 4-point chronological ring ordering, and alarm-crimson (220) needle rendering.
step 9/15 · 9. experiment variations
- Near transfer: Add a falling-edge hysteresis deadband (
clear_alarm_kpa = alarm_kpa - 15) som_in_alarmstays latched until pressure drops at least15 kPabelowalarm_kpa, preventing alarm chatter at399 <-> 400 kPa. - Far transfer: Port
GaugeControllerandTestHmiPanelinto a CMakeQt6::Widgets+Qt6::Charts+Qt6::Testtarget and executeQT_QPA_PLATFORM=offscreen ctest --output-on-failurein your CI container.
step 10/15 · 10. performance measurements
Recorded host benchmark (./files/lab_cli --bench, CLOCK_MONOTONIC, warmup=5, N=40 batches):
learner@ksa:~/gl-q01/lab-m06$ bat listing.txt File: listing.txt bench_gauge_render_ns: p50=1123 p95=1464 p99=1964 (sink=0)The CLOCK_MONOTONIC benchmark measures combined host C++20 set_raw_kpa + 160x160 software Bresenham needle rasterization + 256-sample waveform batch snapshot latency in DRAM. Target 60 Hz frame budgets (16.67 ms) on Cortex-A7 hardware must also include QChart polyline rasterization and DRM scanout.
step 11/15 · 11. troubleshooting
| Symptom | Root cause | Fix |
|---|---|---|
| Check 3 fails with aborted save leaked .tmp file | simulate_abort closed fd without calling ::unlink(tmp.c_str()) | Call ::unlink(tmp.c_str()) on every error and abort path before returning false |
| Check 4 fails with dirty clip violated at (60,20) | ArgbCanvas::put_pixel bypassed !m_clip.contains(x, y) | Restore !m_clip.contains(x, y) in the early-return guard of put_pixel() |
| Check 5 fails with rising-edge alarm spy count=3 (expected 2) | on_alarm emitted whenever now_alarm was true without checking !was_alarm | Emit on_alarm only when (now_alarm && !was_alarm) |
step 12/15 · 12. guided questions
- Why does snapshot_waveform_batch() copy ring elements starting at m_head once m_count == m_ring.size()?
- *Hint 1:* Trace where the oldest sample sits in a circular buffer after wrap-around.
- *Hint 2:* Once full, m_head points to the next slot to be overwritten—which is the oldest surviving sample—so reading (m_head + i) % N yields chronological left-to-right chart order.
- Why is rising-edge + deadband hysteresis essential when wiring a gauge threshold signal to a FaultLogModel?
- *Hint 1:* Imagine ADC thermal noise oscillating 399 -> 400 -> 399 -> 400 kPa at 500 Hz.
- *Hint 2:* Without rising-edge gating and hysteresis, 1-LSB ADC noise floods the fault log and operator buzzer with 250 duplicate alarms per second.
step 13/15 · 13. independent challenges
Extend ArgbCanvas with Wu anti-aliased line rasterization (pack_premul_argb32 fractional coverage alphas) and verify every blended pixel across a 360-degree sweep maintains the premultiplied invariant R', G', B' <= A.
step 14/15 · 14. solutions and explanations
Transactional fsync + rename + unlink persistence, dirty-clipped premultiplied ARGB32 compositing, batched ring-buffer waveform snapshots, and rising-edge SignalSpy tests complete a production-grade Qt 6 HMI.
step 15/15 · run verification and inspect output
Run the verification command and confirm the output matches the expected contract.
learner@ksa:~/gl-q01/lab-m06./files/lab_clilearner@ksa:~/gl-q01/lab-m06capstone_gauge: comp_kpa=430 alarms=1 center_argb=0xFFDC2626 wave_pts=3Progressive hints & solution
hint 1
Compare starter/Makefile against the module lessons. Focus first on: Builds libcore.a and lab_cli cleanly with -std=c++20 -Wall -Wextra -Werror -pedantic.
hint 2
Compile with -std=c11 -Wall -Wextra -Werror, check every system-call return value before touching output buffers, and verify cleanup on error paths.
solution
warning: Reveal the reference solution files? Running ./check.sh against your own attempt first builds stronger retention.
solution: files/Makefile
learner@ksa:~/gl-q01/lab-m06$ bat files/Makefile File: files/Makefile CC_BIN = g++ AR = ar CFLAGS_ALL = -std=c++20 -Wall -Wextra -Werror -pedantic -O2 LDLIBS = all: libcore.a lab_cli libcore.a: core.o $(AR) rcs $@ $^ lab_cli: cli.o libcore.a $(CC_BIN) $(CFLAGS_ALL) cli.o libcore.a $(LDLIBS) -o $@ %.o: %.cpp core.hpp $(CC_BIN) $(CFLAGS_ALL) -c $< -o $@ .PHONY: all clean clean: rm -f core.o cli.o libcore.a lab_clisolution: files/cli.cpp
learner@ksa:~/gl-q01/lab-m06$ bat files/cli.cpp File: files/cli.cpp #include "core.hpp" #include <algorithm> #include <array> #include <cstdint> #include <cstdio> #include <cstring> #include <ctime> static std::uint64_t now_ns() noexcept { timespec ts{}; clock_gettime(CLOCK_MONOTONIC, &ts); return static_cast<std::uint64_t>(ts.tv_sec) * 1000000000ULL + static_cast<std::uint64_t>(ts.tv_nsec); } int main(int argc, char **argv) { const std::uint32_t bg = hmi::pack_premul_argb32(255, 16, 24, 32); hmi::ArgbCanvas canvas(160, 160, bg); hmi::GaugeController ctl({-10, 400}, 256); if (argc > 1 && std::strcmp(argv[1], "--bench") == 0) { constexpr int kWarmup = 5; constexpr int kSamples = 40; constexpr int kBatch = 200; std::array<std::uint64_t, kSamples> ns{}; volatile std::uint32_t sink = 0U; for (int i = 0; i < kWarmup + kSamples; ++i) { const std::uint64_t t0 = now_ns(); for (int r = 0; r < kBatch; ++r) { ctl.set_raw_kpa(200 + (r % 260)); ctl.render_gauge(canvas); auto wave = ctl.snapshot_waveform_batch(); sink ^= canvas.pixel(80, 80) + static_cast<std::uint32_t>(wave.size()); } const std::uint64_t dt = (now_ns() - t0) / kBatch; if (i >= kWarmup) { ns[static_cast<std::size_t>(i - kWarmup)] = dt; } } std::sort(ns.begin(), ns.end()); std::printf("bench_gauge_render_ns: p50=%llu p95=%llu p99=%llu (sink=%u)\n", static_cast<unsigned long long>(ns[20]), static_cast<unsigned long long>(ns[37]), static_cast<unsigned long long>(ns[39]), sink); return 0; } int alarms = 0; ctl.on_alarm = [&](int) { ++alarms; }; ctl.set_raw_kpa(260); // 250 kPa nominal ctl.set_raw_kpa(425); // 415 kPa >= 400 alarm! ctl.set_raw_kpa(440); // stays high -> still 1 alarm ctl.render_gauge(canvas); const auto wave = ctl.snapshot_waveform_batch(); std::printf("capstone_gauge: comp_kpa=%d alarms=%d center_argb=0x%08X wave_pts=%zu\n", ctl.compensated_kpa(), alarms, canvas.pixel(80, 80), wave.size()); return (ctl.compensated_kpa() == 430 && alarms == 1 && wave.size() == 3U) ? 0 : 1; }solution: files/core.cpp
learner@ksa:~/gl-q01/lab-m06$ bat files/core.cpp File: files/core.cpp #include "core.hpp" #include <algorithm> #include <cmath> #include <cstdlib> #include <fcntl.h> #include <numbers> #include <sstream> #include <unistd.h> namespace hmi { bool save_calibration_atomic(const std::string &path, const Calibration &cal, bool simulate_abort) { if (cal.alarm_kpa <= 0 || cal.alarm_kpa > 500) { return false; } const std::string tmp = path + ".tmp"; const int fd = ::openat(AT_FDCWD, tmp.c_str(), O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0600); if (fd < 0) { return false; } const std::string body = "zero=" + std::to_string(cal.zero_offset_kpa) + "\n" + "alarm=" + std::to_string(cal.alarm_kpa) + "\n"; std::size_t written = 0; while (written < body.size()) { const ssize_t n = ::write(fd, body.data() + written, body.size() - written); if (n <= 0) { ::close(fd); ::unlink(tmp.c_str()); return false; } written += static_cast<std::size_t>(n); } if (simulate_abort) { ::close(fd); ::unlink(tmp.c_str()); return false; } if (::fsync(fd) != 0) { ::close(fd); ::unlink(tmp.c_str()); return false; } ::close(fd); if (::rename(tmp.c_str(), path.c_str()) != 0) { ::unlink(tmp.c_str()); return false; } return true; } bool load_calibration(const std::string &path, Calibration &out) { const int fd = ::openat(AT_FDCWD, path.c_str(), O_RDONLY | O_CLOEXEC); if (fd < 0) { return false; } char buf[256]{}; const ssize_t n = ::read(fd, buf, sizeof(buf) - 1U); ::close(fd); if (n <= 0) { return false; } std::istringstream iss(std::string(buf, static_cast<std::size_t>(n))); std::string line; int zero = 0; int alarm = -1; bool got_zero = false; bool got_alarm = false; while (std::getline(iss, line)) { if (line.rfind("zero=", 0) == 0) { zero = std::atoi(line.c_str() + 5); got_zero = true; } else if (line.rfind("alarm=", 0) == 0) { alarm = std::atoi(line.c_str() + 6); got_alarm = true; } } if (!got_zero || !got_alarm || alarm <= 0 || alarm > 500) { return false; } out.zero_offset_kpa = zero; out.alarm_kpa = alarm; return true; } std::uint32_t pack_premul_argb32(std::uint8_t a, std::uint8_t r, std::uint8_t g, std::uint8_t b) noexcept { const std::uint32_t pr = (static_cast<std::uint32_t>(r) * a + 127U) / 255U; const std::uint32_t pg = (static_cast<std::uint32_t>(g) * a + 127U) / 255U; const std::uint32_t pb = (static_cast<std::uint32_t>(b) * a + 127U) / 255U; return (static_cast<std::uint32_t>(a) << 24U) | (pr << 16U) | (pg << 8U) | pb; } std::uint32_t blend_premul_source_over(std::uint32_t src, std::uint32_t dst) noexcept { const std::uint32_t sa = (src >> 24U) & 0xFFU; if (sa == 255U) { return src; } if (sa == 0U) { return dst; } const std::uint32_t inv = 255U - sa; auto ch = [inv](std::uint32_t s, std::uint32_t d, unsigned shift) { const std::uint32_t sc = (s >> shift) & 0xFFU; const std::uint32_t dc = (d >> shift) & 0xFFU; return std::min(255U, sc + (dc * inv + 127U) / 255U); }; return (ch(src, dst, 24U) << 24U) | (ch(src, dst, 16U) << 16U) | (ch(src, dst, 8U) << 8U) | ch(src, dst, 0U); } ArgbCanvas::ArgbCanvas(int w, int h, std::uint32_t bg) : m_w(w), m_h(h), m_clip{0, 0, w, h}, m_pixels(static_cast<std::size_t>(w * h), bg) {} void ArgbCanvas::put_pixel(int x, int y, std::uint32_t premul_src) noexcept { if (x < 0 || x >= m_w || y < 0 || y >= m_h || !m_clip.contains(x, y)) { return; } auto &dst = m_pixels[static_cast<std::size_t>(y * m_w + x)]; dst = blend_premul_source_over(premul_src, dst); } void ArgbCanvas::draw_segment(int x0, int y0, int x1, int y1, std::uint32_t premul_src) noexcept { const int dx = std::abs(x1 - x0); const int sx = x0 < x1 ? 1 : -1; const int dy = -std::abs(y1 - y0); const int sy = y0 < y1 ? 1 : -1; int err = dx + dy; for (;;) { put_pixel(x0, y0, premul_src); if (x0 == x1 && y0 == y1) { break; } const int e2 = 2 * err; if (e2 >= dy) { err += dy; x0 += sx; } if (e2 <= dx) { err += dx; y0 += sy; } } } std::uint32_t ArgbCanvas::pixel(int x, int y) const noexcept { return m_pixels[static_cast<std::size_t>(y * m_w + x)]; } GaugeController::GaugeController(Calibration cal, std::size_t wave_cap) : m_cal(cal), m_ring(std::max<std::size_t>(1U, wave_cap), 0) {} void GaugeController::apply_calibration(Calibration cal) noexcept { m_cal = cal; } void GaugeController::set_raw_kpa(int raw_sensor_kpa) { const int comp = std::clamp(raw_sensor_kpa + m_cal.zero_offset_kpa, 0, 500); m_ring[m_head] = comp; m_head = (m_head + 1U) % m_ring.size(); if (m_count < m_ring.size()) { ++m_count; } if (comp == m_compensated_kpa) { return; } const bool was_alarm = (m_compensated_kpa >= m_cal.alarm_kpa); m_compensated_kpa = comp; const bool now_alarm = (m_compensated_kpa >= m_cal.alarm_kpa); if (now_alarm && !was_alarm && on_alarm) { on_alarm(m_compensated_kpa); } } void GaugeController::render_gauge(ArgbCanvas &canvas) const noexcept { const int cx = canvas.width() / 2; const int cy = canvas.height() / 2; const double radius = std::min(cx, cy) * 0.75; const double deg = 210.0 - (240.0 * m_compensated_kpa / 500.0); const double rad = deg * std::numbers::pi / 180.0; const int tx = cx + static_cast<int>(std::lround(radius * std::cos(rad))); const int ty = cy - static_cast<int>(std::lround(radius * std::sin(rad))); const std::uint32_t color = in_alarm() ? pack_premul_argb32(255, 220, 38, 38) : pack_premul_argb32(255, 14, 165, 233); canvas.draw_segment(cx, cy, tx, ty, color); } std::vector<std::pair<int, int>> GaugeController::snapshot_waveform_batch() const { std::vector<std::pair<int, int>> batch; batch.reserve(m_count); const std::size_t start = (m_count == m_ring.size()) ? m_head : 0U; for (std::size_t i = 0; i < m_count; ++i) { const std::size_t idx = (start + i) % m_ring.size(); batch.emplace_back(static_cast<int>(i), m_ring[idx]); } return batch; } } // namespace hmisolution: files/core.hpp
learner@ksa:~/gl-q01/lab-m06$ bat files/core.hpp File: files/core.hpp #pragma once #include <cstddef> #include <cstdint> #include <functional> #include <string> #include <utility> #include <vector> namespace hmi { struct Calibration { int zero_offset_kpa = 0; int alarm_kpa = 400; }; struct ClipRect { int x = 0; int y = 0; int w = 0; int h = 0; constexpr bool contains(int px, int py) const noexcept { return px >= x && px < (x + w) && py >= y && py < (y + h); } }; bool save_calibration_atomic(const std::string &path, const Calibration &cal, bool simulate_abort = false); bool load_calibration(const std::string &path, Calibration &out); std::uint32_t pack_premul_argb32(std::uint8_t a, std::uint8_t r, std::uint8_t g, std::uint8_t b) noexcept; std::uint32_t blend_premul_source_over(std::uint32_t src, std::uint32_t dst) noexcept; class ArgbCanvas { public: ArgbCanvas(int w, int h, std::uint32_t bg); void set_clip(ClipRect clip) noexcept { m_clip = clip; } void put_pixel(int x, int y, std::uint32_t premul_src) noexcept; void draw_segment(int x0, int y0, int x1, int y1, std::uint32_t premul_src) noexcept; std::uint32_t pixel(int x, int y) const noexcept; int width() const noexcept { return m_w; } int height() const noexcept { return m_h; } private: int m_w; int m_h; ClipRect m_clip; std::vector<std::uint32_t> m_pixels; }; class GaugeController { public: explicit GaugeController(Calibration cal = {}, std::size_t wave_cap = 64); void apply_calibration(Calibration cal) noexcept; void set_raw_kpa(int raw_sensor_kpa); int compensated_kpa() const noexcept { return m_compensated_kpa; } bool in_alarm() const noexcept { return m_compensated_kpa >= m_cal.alarm_kpa; } void render_gauge(ArgbCanvas &canvas) const noexcept; std::vector<std::pair<int, int>> snapshot_waveform_batch() const; std::function<void(int)> on_alarm; private: Calibration m_cal; int m_compensated_kpa = 0; std::vector<int> m_ring; std::size_t m_head = 0; std::size_t m_count = 0; }; } // namespace hmiRun the check
From labs/lab_m06_qpainter_gauge_qtest/, run ./check.sh. A complete solution emits TAP version 13 with every test point marked ok and exits 0:
learner@ksa:~/gl-q01/lab-m06./check.shTAP version 131..5ok 1 - builds libcore.a and lab_cli cleanly with -std=c++20 -Wall -Wextra -Werror -pedanticok 2 - archives core.o into libcore.a and links independent TAP verifierok 3 - commits calibration atomically via fsync+rename and unlinks .tmp cleanly on abortok 4 - composites premultiplied ARGB32 SourceOver strokes strictly inside dirty ClipRect boundsok 5 - applies zero-offset tare, latches rising-edge alarm spy counts, and batches ring waveforms# pass 5/5On an incomplete starter tree, ./check.sh exits non-zero and marks the unmet assertion not ok with an indented YAML diagnostic block:
learner@ksa:~/gl-q01/lab-m06./check.shTAP version 131..5not ok 1 - builds libcore.a and lab_cli cleanly with -std=c++20 -Wall -Wextra -Werror -pedanticFAIL: fix compiler warnings or errors in files/core.cppok 2 - archives core.o into libcore.a and links independent TAP verifierok 3 - commits calibration atomically via fsync+rename and unlinks .tmp cleanly on abortok 4 - composites premultiplied ARGB32 SourceOver strokes strictly inside dirty ClipRect boundsok 5 - applies zero-offset tare, latches rising-edge alarm spy counts, and batches ring waveforms# pass 4/5note: How to read TAP diagnostics: 1..N states the total test plan; each ok k confirms a passed check; not ok k pinpoints the failing check alongside message: (what went wrong) and hint: (where to look next) between --- and ....
inspect harness: check.sh
learner@ksa:~/gl-q01/lab-m06$ bat check.sh File: check.sh #!/bin/sh set -u cd "$(dirname "$0")" || exit 1 PASS=0 WORK=$(mktemp -d "${TMPDIR:-/tmp}/ksa_lab.XXXXXX") || exit 1 trap 'rm -rf "$WORK"' EXIT HUP INT TERM cp -R files "$WORK/files" printf 'TAP version 13\n1..5\n' if make -B -C "$WORK/files" >"$WORK/build.log" 2>&1; then printf 'ok 1 - builds libcore.a and lab_cli cleanly with -std=c++20 -Wall -Wextra -Werror -pedantic\n' PASS=$((PASS + 1)) else printf 'not ok 1 - builds libcore.a and lab_cli cleanly with -std=c++20 -Wall -Wextra -Werror -pedantic\n' printf 'FAIL: fix compiler warnings or errors in files/core.cpp\n' fi if [ -f "$WORK/files/libcore.a" ] && g++ -std=c++20 -Wall -Wextra -Werror -pedantic -O2 -I"$WORK/files" tests.cpp "$WORK/files/libcore.a" -o "$WORK/verify" >>"$WORK/build.log" 2>&1; then printf 'ok 2 - archives core.o into libcore.a and links independent TAP verifier\n' PASS=$((PASS + 1)) else printf 'not ok 2 - archives core.o into libcore.a and links independent TAP verifier\n' printf 'FAIL: preserve public declarations in files/core.hpp so tests.cpp links\n' fi if [ -x "$WORK/verify" ] && OUT=$("$WORK/verify" 1 2>&1); then printf 'ok 3 - commits calibration atomically via fsync+rename and unlinks .tmp cleanly on abort\n' PASS=$((PASS + 1)) else printf 'not ok 3 - commits calibration atomically via fsync+rename and unlinks .tmp cleanly on abort\n' printf 'FAIL: unlink(tmp.c_str()) whenever simulate_abort or write/fsync fails so no .tmp file leaks\n' printf " ---\n message: 'got %s'\n hint: 'unlink(tmp.c_str()) whenever simulate_abort or write/fsync fails so no .tmp file leaks'\n ...\n" "${OUT:-build_failed}" fi if [ -x "$WORK/verify" ] && OUT=$("$WORK/verify" 2 2>&1); then printf 'ok 4 - composites premultiplied ARGB32 SourceOver strokes strictly inside dirty ClipRect bounds\n' PASS=$((PASS + 1)) else printf 'not ok 4 - composites premultiplied ARGB32 SourceOver strokes strictly inside dirty ClipRect bounds\n' printf 'FAIL: enforce m_clip.contains(x, y) inside ArgbCanvas::put_pixel() before blending\n' printf " ---\n message: 'got %s'\n hint: 'enforce m_clip.contains(x, y) inside ArgbCanvas::put_pixel() before blending'\n ...\n" "${OUT:-build_failed}" fi if [ -x "$WORK/verify" ] && OUT=$("$WORK/verify" 3 2>&1); then printf 'ok 5 - applies zero-offset tare, latches rising-edge alarm spy counts, and batches ring waveforms\n' PASS=$((PASS + 1)) else printf 'not ok 5 - applies zero-offset tare, latches rising-edge alarm spy counts, and batches ring waveforms\n' printf 'FAIL: emit on_alarm(m_compensated_kpa) only on rising edge (now_alarm && !was_alarm)\n' printf " ---\n message: 'got %s'\n hint: 'emit on_alarm(m_compensated_kpa) only on rising edge (now_alarm && !was_alarm)'\n ...\n" "${OUT:-build_failed}" fi printf '# pass %d/5\n' "$PASS" [ "$PASS" -eq 5 ]Definition of done
Verification checklist
status: 0/3 checks verified
Troubleshooting
Compiler fails under -Werror on sign conversion or unused args
Use exact POSIX return types (ssize_t for read()/write(), size_t for byte counts) rather than relaxing flags.
./check.sh reports missing files in files/
Invoke ./check.sh from inside labs/lab_m06_qpainter_gauge_qtest/ so relative paths to files/ resolve directly.