diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 44b11d0b..c2171148 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -46,7 +46,7 @@ jobs: - name: Run host unit tests run: | - pio test -e native + pio test -e native -e native_zt706s pio test -e native_ui - name: Check the main screens in every language diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 748f708d..28b0c002 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -65,7 +65,7 @@ Host unit tests for hardware-independent code (protocol decoders, DMM packets an on your computer, without a device: ```sh -pio test -e native +pio test -e native -e native_zt706s -e native_ui ``` A host C++ compiler (GCC or Clang) is needed. `pio run` does not build the tests. To add a suite, @@ -79,8 +79,8 @@ in `platformio.ini`. 3. Make sure `pio run` builds all four environments without new warnings. 4. Test on hardware when the change affects the device behaviour, and say which model you used. If you could not test, say so. -5. Follow the style of the surrounding code: C++17, no exceptions, no RTTI and no heap - allocation outside LVGL. +5. Use the C++23 features supported by the pinned Arm GCC 12.3 toolchain. Keep exceptions and + RTTI disabled and limit heap allocation to LVGL. 6. Do not modify the code in `vendor/`, except to update a third-party component as a whole. 7. Do not add code that writes to the factory block (`0x08000000`–`0x0801FFFF`). diff --git a/docs/ENGINEERING_REVIEW.md b/docs/ENGINEERING_REVIEW.md new file mode 100644 index 00000000..105b0cfd --- /dev/null +++ b/docs/ENGINEERING_REVIEW.md @@ -0,0 +1,51 @@ +# Firmware engineering review + +Reviewed the public OpenOSC tree at `3a500ab` (version 0.22.10) on 2026-11-30. The ZT706S application is the primary target. Its generator uses a serial module, while the ZT703S has a DAC/PWM output. Both share the scope, much of the multimeter, the storage stack and the update formats. The measurements below compare a build of that commit with the reviewed changes, using the same pinned compilers and release flags. + +## Coverage and upstream context + +| Area | Review and verification | +| --- | --- | +| Acquisition, DSP, calibration, instrument control and generator | Examined capture and interrupt handoff, FFT peak selection, timer divider selection, board capabilities and use of DMA-visible memory. Built both board configurations. Checked timer planning against a full prescaler search. | +| DMM, protocol decode, presentation, settings and localization | Traced packet decoding through the model-specific range tables, history, column reductions and UI. Ran the native and screen suites. The added ZT706S environment exercises its own packet, range and package rules in CI. | +| Platform, startup, display and power | Reviewed clock setup, watchdog servicing, the main and recovery loops, volatile register access, linker sections and stack reservations. Compared linked images and memory banks. | +| Storage, logging, USB/SCPI and recovery | Followed cache ownership, writeback, image validation, resource and program CRCs, USB session reset and main-loop dispatch. Checked both recovery images and the packaged applications. | +| ESP32-C3 companion | Built the public application and web recovery with ESP-IDF. Examined file requests, UART replies, portal shutdown and update-slot handling. The optional panel variant requires a separate private bundle. | +| Build tools, configuration and dependencies | Reviewed PlatformIO, the release workflow, board generation, translations and packaging. Ran Cppcheck 2.22 over the project and vendor source trees, then with the ZT706S application, recovery and ESP32-C3 compilation databases. Generated fonts, SDK macros and linker symbols limit the standalone analyzer's coverage. Vendor review covered integration, compilation and static scanning. | + +Upstream work on transient DMM readings changes which packets contribute to statistics. The history changes here concern storage and display of readings after acceptance. High-frequency acquisition remains an open hardware validation item. [DMM pull request 151](https://github.com/bve/OpenOSC/pull/151) · [Scope validation issue 190](https://github.com/bve/OpenOSC/issues/190) + +## Corrections and tradeoffs + +- **Scope cache.** The 15,416-byte column cache previously had an initialized flash copy because its empty viewport contained a nonzero field. An optional viewport expresses whether the cache has a key. The linker now places the entire cache in DTCM `.bss`. On the ZT706S its size is still 15,416 bytes. +- **FFT.** The Blackman window starts its peak search at bin three. The old expression formed a pointer three positions past the beginning of a two-element array before subtracting one. The revised expression forms the valid end iterator directly. +- **DMM trend.** The absolute slot number now follows the 64-bit instrument clock. The redraw computes the visible ring window once and reuses it for both passes over the 240 columns. Tests cover the previous 32-bit boundary, ring expiry, HOLD marks and changing span. +- **Generator timing.** The search now considers a prescaler whose ideal reload falls just beyond the 16-bit register. It stops after exchanging the two divisor factors can only repeat or worsen candidates. In a host benchmark of 300 fractional requests at a 200 MHz timer clock, the median of three runs fell from 3.00 s to 0.019 s with the same checksum of selected registers. The benchmark used GCC 13.3 with `-Os` and requests from 5.0113 to 8.39 Hz. +- **C runtime heap.** Both STM32 images now use linker-defined allocation bounds. Newlib reports `ENOMEM` when a request would pass the end of SRAM4 in the application or enter the reserved 96 KiB stack in recovery. Failed requests preserve the previous break. LVGL continues to use its separate 60 KiB arena. +- **Storage and updates.** A read entirely within a dirty erase block uses its newer RAM contents. Host writes replacing a full 4 KiB block skip the preliminary read used to preserve untouched bytes. NOR verification still runs. Legacy image validation skips the second streaming CRC used only by bundled images. +- **Companion file transfer.** The HTTP worker now waits for a UART reply, portal shutdown or the existing timeout on a static semaphore. This removes the 10 ms polling wakeup while a request is pending. The companion application spends 80 additional bytes of static RAM on the change. + +The STM32 firmware and host targets select C++23 for C++ translation units with the existing Arm GCC 12.3 toolchain on device. C dependencies retain their own language mode. The companion's ESP-IDF build already selects GNU C++23. The STM32 builds keep size optimization, LTO, disabled exceptions and disabled RTTI. + +The JSF AV C++ review used Rev C as advisory guidance. Rules 203 and 204 informed the arithmetic and volatile side-effect changes. Rules 206 and 208 informed the allocation and exception review. OpenOSC uses placement construction in fixed memory, a bounded LVGL heap, compiler-specific sections, MMIO and assembly. Formal compliance would require a rule-by-rule assessment, documented deviations and target verification. + +## Linked footprint + +PlatformIO reports the following byte counts. Its STM32 RAM figure covers ordinary data and BSS. Dedicated banks and reserved stack require inspection of the ELF and linker script. + +| Image | Flash before | Flash after | RAM before | RAM after | +| --- | ---: | ---: | ---: | ---: | +| ZT706S application | 1,348,480 | 1,333,520 | 79,524 | 79,524 | +| ZT703S application | 1,360,704 | 1,345,816 | 79,124 | 79,124 | +| Each STM32 recovery | 85,536 | 85,640 | 9,100 | 9,096 | +| ESP32-C3 companion | 1,251,350 | 1,251,404 | 51,212 | 51,292 | +| ESP32-C3 web recovery | 774,738 | 774,738 | 30,172 | 30,172 | + +On ZT706S the linker leaves 50,264 bytes between the end of BSS and the stack top. This is a reservation, and live stack depth still needs device measurement. AXI sections reach 1,048,480 bytes into the 1 MiB bank, leaving **96 bytes**. The AHB record bank uses its full 128 KiB. In SRAM4, 1,856 bytes remain between the application's C heap start and its enforced limit. The firmware passes the existing section and stack assertions. [Application linker script](../ld/application.ld) + +## Verification and open findings + +The four STM32 images and both public ESP32-C3 images built. All seven release assets passed SHA-256 verification. All 130 native test cases and 39 Python tests passed. The screen suite passed under AddressSanitizer, LeakSanitizer and UndefinedBehaviorSanitizer in English, Chinese, Russian and Spanish. Board configuration, translations and localized font coverage passed their consistency checks. Additional host harnesses exercised NOR cache ownership and failed flush retries, mailbox replies, stale responses, timeout and shutdown, and heap growth and shrinkage at both bounds and at the extremes of `ptrdiff_t`. + +- **USB command loss remains open.** A CDC DTR transition can rearm a ready OUT buffer, and session synchronization resets the parser. That provides a code path consistent with the reported lost mode command. A transport fix needs to preserve completed commands and isolate partial commands and replies across sessions. The upstream reproduction used a ZT703S. [USB issue 177](https://github.com/bve/OpenOSC/issues/177) +- **Bench validation is outstanding.** No handheld was available during this review. ZT706S trigger stability, generator output and acknowledgments, USB close/reopen behavior, installed-image boot, NOR power-loss behavior and battery current remain unmeasured. Host timings establish an algorithmic improvement. A power comparison needs the same clock profile, brightness, acquisition settings and companion state on the device. diff --git a/include/openosc/measurement/dmm/session.hpp b/include/openosc/measurement/dmm/session.hpp index 11bf26d7..6ffb907a 100644 --- a/include/openosc/measurement/dmm/session.hpp +++ b/include/openosc/measurement/dmm/session.hpp @@ -78,6 +78,15 @@ class History { uint64_t spanUs() const { return uint64_t(SpanSeconds[span_]) * 1000000; } // Column `index` (0 oldest .. Columns-1 newest) of the window ending at endUs (or at the newest // reading, when that is later); false without readings in it. + class Window { + public: + const Column *column(unsigned index) const; + private: + friend class History; + const Column *ring_ = nullptr; + unsigned first_ = 0, end_ = 0, start_ = 0; + }; + Window window(uint64_t endUs) const; bool column(unsigned index, uint64_t endUs, Column &output) const; bool empty() const { return !any_; } void reset() { @@ -92,14 +101,17 @@ class History { // Mark `index` (0..MaxMarks-1) as a column of the window ending at endUs (as column()); false: none there. bool markColumn(unsigned index, uint64_t endUs, unsigned &column) const { if (index >= MaxMarks || !marks_[index]) return false; - const uint32_t end = slotOf(endUs > latestUs_ ? endUs : latestUs_), slot = slotOf(marks_[index] - 1); + const uint64_t end = slotOf(endUs > latestUs_ ? endUs : latestUs_), slot = slotOf(marks_[index] - 1); if (slot > end || end - slot >= Columns) return false; - column = Columns - 1 - (end - slot); + column = Columns - 1 - unsigned(end - slot); return true; } private: - uint32_t slotOf(uint64_t us) const { return uint32_t(us * Columns / spanUs()); } + uint64_t slotOf(uint64_t us) const { + const uint64_t span = spanUs(); + return (us / span) * Columns + (us % span) * Columns / span; + } static void merge(Column &into, const Column &from); Column columns_[Columns]; // By slot % Columns. uint64_t marks_[MaxMarks]{}; // Trend times + 1 (0: none), a ring from nextMark_. diff --git a/include/openosc/ui/scope/column_cache.hpp b/include/openosc/ui/scope/column_cache.hpp index 2273a888..fb897575 100644 --- a/include/openosc/ui/scope/column_cache.hpp +++ b/include/openosc/ui/scope/column_cache.hpp @@ -2,6 +2,7 @@ #include "openosc/acquisition/frame.hpp" #include "openosc/ui/scope/options.hpp" #include "openosc/ui/scope/viewport.hpp" +#include namespace openosc::plot { // The next frame's column reductions, done ahead while the display waits on DMA2D (RenderIdle, @@ -21,18 +22,19 @@ class ColumnCache { return same(frame, viewport) ? done_ : 0; } const scope::ColumnStats (&columns(unsigned x) const)[2] { return stats_[x]; } - void clear() { valid_ = false; done_ = 0; } + void clear() { viewport_.reset(); done_ = 0; } static bool applies(const scope::FrameView &frame, const Options &options, const Viewport &viewport); static bool reduce(const scope::FrameView &frame, uint32_t first, uint32_t last, scope::ColumnStats (&out)[2]); private: bool same(const scope::FrameMetadata &m, const Viewport &v) const { - return valid_ && m.sequence == sequence_ && m.timestampUs == timestamp_ && m.triggerIndex == trigger_ && v == viewport_; + return viewport_ && m.sequence == sequence_ && m.timestampUs == timestamp_ && m.triggerIndex == trigger_ && v == *viewport_; } uint32_t sequence_ = 0, trigger_ = 0, done_ = 0; uint64_t timestamp_ = 0; - Viewport viewport_{}; - bool valid_ = false; + // An empty cache has no viewport. This also keeps its zero-initialized + // column array in .bss instead of copying it from flash at startup. + std::optional viewport_; scope::ColumnStats stats_[MaximumWidth][2]; }; } // namespace openosc::plot diff --git a/ld/application.ld b/ld/application.ld index 4651c2a8..8d8025d0 100644 --- a/ld/application.ld +++ b/ld/application.ld @@ -52,6 +52,7 @@ SECTIONS { .generator (NOLOAD) : { . = ALIGN(32); KEEP(*(.generator)) } > SRAM4 .settings_workspace (NOLOAD) : { . = ALIGN(32); KEEP(*(.settings_workspace)) . = ALIGN(32); } > SRAM4 . = ALIGN(8); _end = .; PROVIDE(end = .); + _heap_limit = ORIGIN(SRAM4) + LENGTH(SRAM4); /* ITCM (CPU and MDMA only, no DMA1/2 or DMA2D): the protocol decoder's workspace (its job, lease and two result sets) and, in OPENOSC_USB_TRACE builds, the trace ring. Reset_Handler enables ITCM and zeroes both in 64-bit ECC words before any constructor runs (the job is built in place later). */ @@ -68,6 +69,7 @@ SECTIONS { .dmm_log (NOLOAD) : { . = ALIGN(8); _sdmm_log = .; KEEP(*(.dmm_log)) . = ALIGN(8); _edmm_log = .; } > ITCM /DISCARD/ : { *(.comment) *(.note*) } ASSERT(_ebss + 49152 < _estack, "Application leaves less than 48 KiB stack") + ASSERT(_end >= ORIGIN(SRAM4) && _end <= _heap_limit, "C heap must start in SRAM4") ASSERT(ADDR(.runtime_vectors) == ORIGIN(RAM) && SIZEOF(.runtime_vectors) == 1024, "Runtime vectors must open DTCM") ASSERT(ADDR(.framebuffer) == 0x24000000, "Panel framebuffer address changed") ASSERT(SIZEOF(.dma_data) >= 1024, "Initialized USB DMA buffers were not linked") diff --git a/ld/recovery_common.ld b/ld/recovery_common.ld index 1c1d2f8d..6e80f4e6 100644 --- a/ld/recovery_common.ld +++ b/ld/recovery_common.ld @@ -25,8 +25,9 @@ SECTIONS { _sidata = LOADADDR(.data); .bss (NOLOAD) : { . = ALIGN(1024); _sbss = .; *(.bss*) *(COMMON) . = ALIGN(8); _ebss = .; } > RAM . = ALIGN(8); _end = .; PROVIDE(end = .); + _heap_limit = _estack - 96K; /DISCARD/ : { *(.comment) *(.note*) } - ASSERT(_ebss + 98304 < _estack, "Recovery RAM leaves less than 96 KiB stack") + ASSERT(_end < _heap_limit, "Recovery RAM leaves less than 96 KiB stack") ASSERT(LOADADDR(.data) + SIZEOF(.data) <= ORIGIN(BOOT) + LENGTH(BOOT), "Recovery exceeds fixed 128 KiB reservation") /* The image's own vector table (vectors.S) is taken before the code is copied: its handler must lie in the image, not in the relocated CODE. */ diff --git a/platformio.ini b/platformio.ini index 8ca884de..331cd756 100644 --- a/platformio.ini +++ b/platformio.ini @@ -8,6 +8,7 @@ platform_packages = toolchain-gccarmnoneeabi@1.120301.0 board = zt703s custom_openosc_image = recovery extra_scripts = + pre:scripts/cxx_standard.py pre:scripts/build.py post:scripts/linker_dependencies.py build_unflags = -O2 -Og @@ -115,25 +116,26 @@ build_src_filter = - - +[host_tests] +build_flags = + -DUNITY_INCLUDE_DOUBLE + -Iinclude + -Wall + -Wextra + -Wno-unused-parameter + ; Host unit tests: `pio test -e native` (not part of `pio run`). Only hardware-independent sources ; are compiled; the [env] settings for the device builds are overridden here. [env:native] platform = native platform_packages = -extra_scripts = +extra_scripts = pre:scripts/cxx_standard.py board_build.ldscript = test_framework = unity test_ignore = test_ui_* test_build_src = yes build_unflags = -build_flags = - -std=gnu++17 - -DOPENOSC_BOARD=703 - -DUNITY_INCLUDE_DOUBLE - -Iinclude - -Wall - -Wextra - -Wno-unused-parameter +build_flags = ${host_tests.build_flags} -DOPENOSC_BOARD=703 build_src_filter = -<*> + @@ -142,6 +144,8 @@ build_src_filter = + + + + + + + + + + @@ -154,6 +158,14 @@ build_src_filter = + + +[env:native_zt706s] +extends = env:native +build_flags = ${host_tests.build_flags} -DOPENOSC_BOARD=706 +test_filter = + test_dmm_packet + test_dmm_ranges + test_update_package + ; The localized text on LVGL's own layout (UTF-8 measurement, fallback fonts, the choice of versions and ; faces, every locale character drawable), every Settings page in every language through the real views, ; and the language setting in the preferences file: LVGL from vendor/, the firmware's fonts, @@ -161,7 +173,7 @@ build_src_filter = [env:native_ui] platform = native platform_packages = -extra_scripts = +extra_scripts = pre:scripts/cxx_standard.py board_build.ldscript = test_framework = unity test_filter = test_ui_* @@ -169,7 +181,6 @@ test_build_src = yes lib_deps = symlink://vendor/lvgl build_unflags = build_flags = - -std=gnu++17 -Itest/support -DLV_CONF_INCLUDE_SIMPLE -DOPENOSC_TEXT_DIAGNOSTICS diff --git a/scripts/build.py b/scripts/build.py index 092ebc0a..92af0063 100644 --- a/scripts/build.py +++ b/scripts/build.py @@ -37,7 +37,7 @@ ] env.Append(CPPPATH=[str(root / path) for path in include_dirs]) env.Append(ASFLAGS=["-mfloat-abi=hard", "-mfpu=fpv5-d16"]) -env.Append(CXXFLAGS=["-std=gnu++17", "-fno-exceptions", "-fno-rtti", "-fno-threadsafe-statics"]) +env.Append(CXXFLAGS=["-fno-exceptions", "-fno-rtti", "-fno-threadsafe-statics"]) env.Append(LINKFLAGS=["-flto", "-nostartfiles", "-mfloat-abi=hard", "-mfpu=fpv5-d16", "--specs=nano.specs", "--specs=nosys.specs", "-Wl,-Map," + env.subst("$BUILD_DIR/firmware.map")]) diff --git a/scripts/cxx_standard.py b/scripts/cxx_standard.py new file mode 100644 index 00000000..94847476 --- /dev/null +++ b/scripts/cxx_standard.py @@ -0,0 +1,5 @@ +"""Use the same C++ dialect for the STM32 images and their host tests.""" + +Import("env") + +env.Append(CXXFLAGS=["-std=gnu++23"]) diff --git a/scripts/test_ui_screens.py b/scripts/test_ui_screens.py index 22204992..c6a87917 100644 --- a/scripts/test_ui_screens.py +++ b/scripts/test_ui_screens.py @@ -29,7 +29,7 @@ "-DLV_CONF_INCLUDE_SIMPLE=1", "-DOPENOSC_BOARD=703", "-DOPENOSC_TEXT_DIAGNOSTICS=1", "-Itest/support", "-Ivendor/lvgl", "-Iinclude", f"-I{cmsis_dsp.INCLUDE}", "-Ivendor/cmsis", *[f"-D{d}" for d in cmsis_dsp.DEFINES]] CC = ["gcc", "-std=c99", *FLAGS] -CXX = ["g++", "-std=c++17", "-Wall", "-Wextra", "-Werror", *FLAGS] +CXX = ["g++", "-std=c++23", "-Wall", "-Wextra", "-Werror", *FLAGS] def compile_one(command, source): diff --git a/scripts/ui_sources.py b/scripts/ui_sources.py index cae9386d..b5ef9315 100644 --- a/scripts/ui_sources.py +++ b/scripts/ui_sources.py @@ -16,7 +16,7 @@ "src/acquisition/measurements.cpp", "src/acquisition/auto_setup.cpp", "src/acquisition/signal_band.cpp", "src/acquisition/tone_estimate.cpp", "src/acquisition/spectrum.cpp", "src/acquisition/spectrum_peak.cpp", "src/generator/waveform.cpp", - "src/platform/timer_plan.cpp", "src/measurement/dmm/session.cpp", "src/measurement/dmm/hold.cpp", + "src/platform/timer_plan.cpp", "src/measurement/dmm/session.cpp", "src/measurement/dmm/history.cpp", "src/measurement/dmm/hold.cpp", "src/measurement/dmm/statistics.cpp", "src/measurement/dmm/function.cpp", "src/measurement/dmm/key_command.cpp", "src/measurement/dmm/ranges.cpp", "src/measurement/dmm/decoder.cpp", "src/measurement/dmm/packet.cpp"] diff --git a/src/acquisition/adc_clock.cpp b/src/acquisition/adc_clock.cpp index 20531857..c06e4030 100644 --- a/src/acquisition/adc_clock.cpp +++ b/src/acquisition/adc_clock.cpp @@ -35,7 +35,10 @@ void AdcClock::start(uint16_t prescaler, uint16_t period, uint32_t timerHz, bool __HAL_RCC_GPIOE_CLK_ENABLE(); TIM1->CR1=0; TIM1->DIER=0; TIM1->SMCR=0; TIM1->CR2=TIM_CR2_MMS_1; - TIM1->PSC=prescaler; TIM1->ARR=period-1u; TIM1->CCR1=TIM1->CCR3=compare(period, interleaved); + TIM1->PSC=prescaler; TIM1->ARR=period-1u; + const uint16_t edge = compare(period, interleaved); + TIM1->CCR3 = edge; + TIM1->CCR1 = edge; TIM1->CCMR1=(6U<<4)|TIM_CCMR1_OC1PE; TIM1->CCMR2=(6U<<4)|TIM_CCMR2_OC3PE; TIM1->CCER=outputs(timerHz, prescaler, period, interleaved); @@ -55,7 +58,8 @@ void AdcClock::configure(uint16_t prescaler, uint16_t period, uint32_t timerHz, TIM1->CCR1 == edge && TIM1->CCR3 == edge)) return; // An unchanged plan keeps the running clock (no restart between records). TIM1->CCER = ccer; - TIM1->CCR1 = TIM1->CCR3 = edge; // Preloaded: applied with PSC/ARR at the update. + TIM1->CCR3 = edge; + TIM1->CCR1 = edge; // Preloaded: applied with PSC/ARR at the update. TIM1->PSC = prescaler; TIM1->ARR = period - 1u; TIM1->EGR = TIM_EGR_UG; // Now; TIM3 does not take TRGO yet (SMCR 0). settle(prescaler, period); diff --git a/src/acquisition/capture.cpp b/src/acquisition/capture.cpp index efa75028..5d3a7ca9 100644 --- a/src/acquisition/capture.cpp +++ b/src/acquisition/capture.cpp @@ -284,17 +284,18 @@ void CaptureDma::interrupt(unsigned bank) { return; if (rolling_ || gated_) { const bool inTime=cycleGuard_.observe(bank,DWT->CYCCNT); - if (!inTime || !advanceSegment(bank,++cycles_[bank])) { + if (inTime) cycles_[bank] = cycles_[bank] + 1; + if (!inTime || !advanceSegment(bank, cycles_[bank])) { captureFault(1U << 21 | bank << 8 | (inTime ? 2U : 1U) | uint32_t(cycles_[bank] & 0xff) << 12); abandon(DataStatus::Overflow); return; } - if (rolling_ && !bank) ++completed_; + if (rolling_ && !bank) completed_ = completed_ + 1; return; } complete_ |= 1U << bank; if (complete_ != 15) return; - ++completed_; + completed_ = completed_ + 1; if (!quiesce(false)) return; const uint16_t *banks[4] = {buffer_.lanes[0], buffer_.lanes[1], buffer_.lanes[2], buffer_.lanes[3]}; diff --git a/src/acquisition/pulse_counters.cpp b/src/acquisition/pulse_counters.cpp index 9e6f77e6..9a8eb9ee 100644 --- a/src/acquisition/pulse_counters.cpp +++ b/src/acquisition/pulse_counters.cpp @@ -17,7 +17,8 @@ void pin(GPIO_TypeDef *port,uint32_t pins,uint32_t alternate) { } void timer(TIM_TypeDef *target,uint32_t maximum) { target->CR1=0; target->CR2=0; target->DIER=0; target->SMCR=0; target->CCER=0; - target->CCMR1=target->CCMR2=0; + target->CCMR2 = 0; + target->CCMR1 = 0; target->PSC=0; target->ARR=maximum; target->EGR=TIM_EGR_UG; target->SR=0; target->SMCR=smcr(0); } @@ -50,7 +51,8 @@ bool PulseCounters::start() { pin(GPIOA,GPIO_PIN_15,GPIO_AF1_TIM2); pin(GPIOE,GPIO_PIN_0,GPIO_AF2_TIM4); timer(TIM2,UINT32_MAX); timer(TIM4,65535); TIM5->CR1=0; TIM5->CR2=0; TIM5->DIER=0; TIM5->SMCR=0; TIM5->CCER=0; - TIM5->CCMR1=TIM5->CCMR2=0; + TIM5->CCMR2 = 0; + TIM5->CCMR1 = 0; TIM5->PSC=clock/1000000-1; TIM5->ARR=UINT32_MAX; TIM5->EGR=TIM_EGR_UG; TIM5->SR=0; TIM5->CR1=TIM_CR1_ARPE|TIM_CR1_CEN; @@ -58,13 +60,15 @@ bool PulseCounters::start() { high_=0; active_=this; Interrupts::attach(TIM4_IRQn,interrupt,5); TIM4->DIER=TIM_DIER_UIE; - TIM2->CR1=TIM4->CR1=TIM_CR1_ARPE|TIM_CR1_CEN; + constexpr uint32_t start = TIM_CR1_ARPE | TIM_CR1_CEN; + TIM4->CR1 = start; + TIM2->CR1 = start; invalidate(Board::milliseconds()); return true; } void PulseCounters::interrupt() { if (active_ && (TIM4->SR&TIM_SR_UIF)) { - ++active_->high_; + active_->high_ = active_->high_ + 1; TIM4->SR=~TIM_SR_UIF; // W0C: preserve unrelated pending flags. } } @@ -185,7 +189,10 @@ void PulseCounters::timed(bool on) { void PulseCounters::stop() { if (!lease_.valid()) return; if (policy_.timing()) { TIM2->DIER=0; Interrupts::detach(TIM2_IRQn); TIM2->SR=0; } - TIM2->CR1=TIM4->CR1=TIM5->CR1=0; TIM4->DIER=0; + TIM5->CR1 = 0; + TIM4->CR1 = 0; + TIM2->CR1 = 0; + TIM4->DIER = 0; Interrupts::detach(TIM4_IRQn); TIM4->SR=0; active_=nullptr; GPIO_InitTypeDef gpio{}; gpio.Mode=GPIO_MODE_INPUT; gpio.Pull=GPIO_NOPULL; gpio.Pin=GPIO_PIN_15; HAL_GPIO_Init(GPIOA,&gpio); diff --git a/src/acquisition/spectrum_peak.cpp b/src/acquisition/spectrum_peak.cpp index d02c8052..0c952a83 100644 --- a/src/acquisition/spectrum_peak.cpp +++ b/src/acquisition/spectrum_peak.cpp @@ -48,7 +48,7 @@ unsigned SpectrumPeak::find(const float *amplitude,unsigned bins,unsigned window for (unsigned k=1;k= 6) - flag(samples, uint16_t(Note | DecodeEvent::Open), result); + flag(samples, static_cast(Note) | DecodeEvent::Open, result); flushFragment(samples, result); clampToRecord(result, samples); } diff --git a/src/decode/protocols/lin.cpp b/src/decode/protocols/lin.cpp index e4ffa4ab..f6ab92b0 100644 --- a/src/decode/protocols/lin.cpp +++ b/src/decode/protocols/lin.cpp @@ -180,9 +180,9 @@ void LinDecoder::finish(uint32_t samples, ResultSet &result) { } if (pendingSpace_) { pendingSpace_ = false; store(0, true, rx_.start(), rx_.end(), result); } if (frame_) { - if (rx_.active()) closeFrame(samples, uint16_t(DecodeEvent::Cut | NotChecked), result); // A byte past the end. + if (rx_.active()) closeFrame(samples, DecodeEvent::Cut | static_cast(NotChecked), result); // A byte past the end. else if (state_ == State::Bytes && pidSeen_ && !length_) closeFrame(lastEnd_, DecodeEvent::Open, result); - else closeFrame(samples, uint16_t(DecodeEvent::Cut | NotChecked), result); + else closeFrame(samples, DecodeEvent::Cut | static_cast(NotChecked), result); } rx_.cancel(); flushFragment(samples, result, level_ == 0); diff --git a/src/decode/protocols/types.cpp b/src/decode/protocols/types.cpp index 7ee853b6..b57d86ef 100644 --- a/src/decode/protocols/types.cpp +++ b/src/decode/protocols/types.cpp @@ -68,7 +68,7 @@ void EventWriter::push(ResultSet &result, uint16_t value, uint32_t first, uint32 if (!stored_) header_.last = last; if (store(result, value)) { result.lastEvent()->last = last; return; } if (stored_) { // The pool ran out inside the unit: what is stored stays, its rest is lost. - result.lastEvent()->flags |= uint16_t(Truncated | DecodeEvent::Cut); + result.lastEvent()->flags |= static_cast(Truncated) | DecodeEvent::Cut; ++dropped_; exhausted_ = lostUnit_ = true; return; diff --git a/src/display/panel.cpp b/src/display/panel.cpp index f4ddb424..c15b1733 100644 --- a/src/display/panel.cpp +++ b/src/display/panel.cpp @@ -61,7 +61,9 @@ void Display::offerBootFrame() const { bool Display::takeBootFrame(boot_splash::Style *style) { const bool offered = bootFrame()[0] == BootFrameMagic && bootFrame()[1] == ~BootFrameMagic; const auto tag = bootFrame()[2]; - bootFrame()[0] = bootFrame()[1] = bootFrame()[2] = 0; + bootFrame()[2] = 0; + bootFrame()[1] = 0; + bootFrame()[0] = 0; const bool live = offered && (RCC->CR & RCC_CR_PLL3RDY) && scanningBootBuffer(); if (style) *style = live && (tag & 0xffffff00U) == BootStyleMagic ? boot_splash::Style(tag & 0xffU) : boot_splash::Style::Count; diff --git a/src/esp32c3/main/file_mailbox.hpp b/src/esp32c3/main/file_mailbox.hpp index 6aeeb7fe..3dff2488 100644 --- a/src/esp32c3/main/file_mailbox.hpp +++ b/src/esp32c3/main/file_mailbox.hpp @@ -9,14 +9,24 @@ namespace openosc::companion { // The HTTP server is the sole requester. The UART loop only exchanges queued frames. class FileMailbox { public: - FileMailbox() : mutex_(xSemaphoreCreateMutexStatic(&storage_)) {} + FileMailbox() : mutex_(xSemaphoreCreateMutexStatic(&storage_)), + answered_(xSemaphoreCreateBinaryStatic(&answerStorage_)) {} bool active() const { return active_.load(); } void active(bool value) { active_ = value; } - void online(bool value) { online_ = value; } + void online(bool value) { + Lock lock(mutex_); + online_ = value; + if (!online_ && pending_) { + pending_ = false; + xSemaphoreGive(answered_); + } + } bool call(files::Operation op, const uint8_t *data, unsigned size, Frame &reply) { - if (!online_ || size > files::Chunk) return false; + if (size > files::Chunk || (size && !data)) return false; { Lock lock(mutex_); + if (!online_) return false; + xSemaphoreTake(answered_, 0); // Discard a reply that raced the previous timeout. if (++id_ == 0) ++id_; request_ = {}; request_.size = size + 3; @@ -26,23 +36,19 @@ class FileMailbox { reply_.size = 0; pending_ = true; } - const auto start = xTaskGetTickCount(); - while (online_ && xTaskGetTickCount() - start < pdMS_TO_TICKS(4500)) { - { - Lock lock(mutex_); - if (reply_.size) { reply = reply_; return true; } - } - vTaskDelay(pdMS_TO_TICKS(10)); - } + xSemaphoreTake(answered_, pdMS_TO_TICKS(4500)); Lock lock(mutex_); pending_ = false; - return false; + if (!online_ || !reply_.size) return false; + reply = reply_; + return true; } void exchange(const Frame &incoming, Frame &outgoing) { Lock lock(mutex_); if (pending_ && incoming.size >= 2 && incoming.data[0] == id_) { reply_ = incoming; pending_ = false; + xSemaphoreGive(answered_); } if (pending_) { outgoing.size = request_.size; @@ -60,9 +66,10 @@ class FileMailbox { private: SemaphoreHandle_t mutex_; }; - StaticSemaphore_t storage_{}; - SemaphoreHandle_t mutex_; - std::atomic pending_{false}, online_{false}, active_{false}; + StaticSemaphore_t storage_{}, answerStorage_{}; + SemaphoreHandle_t mutex_, answered_; + bool pending_ = false, online_ = false; // Protected by mutex_. + std::atomic active_{false}; Frame request_{}, reply_{}; uint8_t id_ = 0; }; diff --git a/src/generator/module_output.cpp b/src/generator/module_output.cpp index daed3cda..8095c788 100644 --- a/src/generator/module_output.cpp +++ b/src/generator/module_output.cpp @@ -41,7 +41,11 @@ void interrupt() { } if (status & Errors) USART3->ICR = USART_ICR_ORECF | USART_ICR_FECF | USART_ICR_NECF | USART_ICR_PECF; if ((control & USART_CR1_TXEIE_TXFNFIE) && (status & USART_ISR_TXE_TXFNF)) { - if (wire.index < wire.length) USART3->TDR = wire.data[wire.index++]; + const auto index = wire.index; + if (index < wire.length) { + wire.index = index + 1; + USART3->TDR = wire.data[index]; + } if (wire.index >= wire.length) { // The last byte is in: TC from before it means nothing. USART3->ICR = USART_ICR_TCCF; USART3->CR1 = (USART3->CR1 & ~USART_CR1_TXEIE_TXFNFIE) | USART_CR1_TCIE; @@ -68,7 +72,7 @@ bool ModuleOutput::start() { USART3->CR2 = 0; USART3->CR3 = 0; USART3->PRESC = 0; USART3->BRR = (HAL_RCC_GetPCLK1Freq() + BaudRate / 2) / BaudRate; USART3->ICR = 0xffffffffU; - wire.data = nullptr; wire.index = wire.length = 0; wire.tail = wire.head; + wire.data = nullptr; wire.length = 0; wire.index = 0; wire.tail = wire.head; if (!Interrupts::attach(USART3_IRQn, interrupt, Priority)) { portFailed_ = true; return false; } USART3->CR1 = USART_CR1_TE | USART_CR1_RE | USART_CR1_RXNEIE_RXFNEIE | USART_CR1_UE; running_ = true; portFailed_ = false; onWire_ = false; diff --git a/src/measurement/dmm/history.cpp b/src/measurement/dmm/history.cpp new file mode 100644 index 00000000..9accca30 --- /dev/null +++ b/src/measurement/dmm/history.cpp @@ -0,0 +1,89 @@ +#include "openosc/measurement/dmm/session.hpp" +#include +#include +#include +#include + +namespace openosc::dmm { +void History::merge(Column &into, const Column &from) { + if (into.empty()) { into = from; return; } + into.minimum = std::min(into.minimum, from.minimum); + into.maximum = std::max(into.maximum, from.maximum); +} +void History::push(double value, uint64_t timeUs) { + if (!std::isfinite(value)) + return; + const uint64_t slot = slotOf(timeUs), latest = slotOf(latestUs_); + if (any_ && slot + Columns <= latest) return; // Older than the window. + // A newer slot: the slots passed since the newest reading have none of their own yet. + if (any_ && slot > latest) + for (uint32_t k = 0; k < std::min(slot - latest, Columns); ++k) columns_[(slot - k) % Columns] = Column{}; + const float reading = float(value); + Column sample; + sample.minimum = sample.maximum = reading; + merge(columns_[slot % Columns], sample); + if (!any_ || timeUs > latestUs_) latestUs_ = timeUs; + any_ = true; +} +bool History::span(unsigned index) { + if (index >= SpanCount) index = SpanCount - 1; + if (index == span_) return false; + if (!any_) { span_ = index; return true; } + Column previous[Columns]; + std::copy(std::begin(columns_), std::end(columns_), std::begin(previous)); + const uint32_t before = SpanSeconds[span_], after = SpanSeconds[index]; + const uint64_t oldLatest = slotOf(latestUs_); + span_ = index; + for (auto &column : columns_) column = Column{}; + const uint64_t latest = slotOf(latestUs_); + const uint64_t first = latest + 1 >= Columns ? latest + 1 - Columns : 0; + uint64_t oldest = UINT64_MAX; // The first new slot with readings. + for (unsigned i = 0; i < Columns; ++i) { + if (oldLatest + i < Columns - 1) continue; // Before time 0. + const uint64_t old = oldLatest + i - (Columns - 1); + const auto &column = previous[old % Columns]; + if (column.empty()) continue; + // Finer: only one envelope is known for the coarse column's whole time, so it is a flat step at + // its middle over that time (thin, not a band; no slope drawn between readings never taken). + // Its part older than the new window is dropped. Coarser: the envelopes merge. + Column level = column; + if (after < before) level.minimum = level.maximum = std::midpoint(column.minimum, column.maximum); + // Both grids have Columns slots per span. Map their boundaries directly so a + // fractional microsecond cannot introduce a sample in the preceding slot. + uint64_t from = old * before / after, to = ((old + 1) * before - 1) / after; + if (to > latest) to = latest; + if (from < first) from = first; + for (uint64_t slot = from; slot <= to; ++slot) { merge(columns_[slot % Columns], level); oldest = std::min(oldest, slot); } + } + any_ = oldest != UINT64_MAX; + if (!any_) latestUs_ = 0; + // A HOLD mark with no curve left before it is dropped too (it does not come back on a longer span). + for (auto &mark : marks_) + if (mark && slotOf(mark - 1) <= oldest) mark = 0; + return true; +} +History::Window History::window(uint64_t endUs) const { + Window view; + if (!any_) return view; + const uint64_t latest = slotOf(latestUs_); + const uint64_t end = endUs > latestUs_ ? slotOf(endUs) : latest; + if (end - latest >= Columns) return view; + const uint64_t oldest = end >= Columns - 1 ? end - (Columns - 1) : 0; + view.ring_ = columns_; + view.first_ = Columns - 1 - unsigned(end - oldest); + view.end_ = Columns - unsigned(end - latest); + view.start_ = unsigned(oldest % Columns); + return view; +} +const History::Column *History::Window::column(unsigned index) const { + if (index < first_ || index >= end_) return nullptr; + const auto &entry = ring_[(start_ + index - first_) % Columns]; + return entry.empty() ? nullptr : &entry; +} +bool History::column(unsigned index, uint64_t endUs, Column &output) const { + const auto *entry = window(endUs).column(index); + if (!entry) return false; + output = *entry; + return true; +} +} // namespace openosc::dmm diff --git a/src/measurement/dmm/session.cpp b/src/measurement/dmm/session.cpp index 4fdfb192..a9bc71b4 100644 --- a/src/measurement/dmm/session.cpp +++ b/src/measurement/dmm/session.cpp @@ -1,10 +1,7 @@ #include "openosc/measurement/dmm/session.hpp" #include "openosc/measurement/dmm/function.hpp" #include "openosc/data/decimal.hpp" -#include #include -#include -#include namespace openosc::dmm { namespace { @@ -71,75 +68,6 @@ void Session::typeK(bool enabled, uint64_t nowUs) { resetTemperatureReading(nowUs); } -void History::merge(Column &into, const Column &from) { - if (into.empty()) { into = from; return; } - into.minimum = std::min(into.minimum, from.minimum); - into.maximum = std::max(into.maximum, from.maximum); -} -void History::push(double value, uint64_t timeUs) { - if (!std::isfinite(value)) - return; - const uint32_t slot = slotOf(timeUs), latest = slotOf(latestUs_); - if (any_ && slot + Columns <= latest) return; // Older than the window. - // A newer slot: the slots passed since the newest reading have none of their own yet. - if (any_ && slot > latest) - for (uint32_t k = 0; k < std::min(slot - latest, Columns); ++k) columns_[(slot - k) % Columns] = Column{}; - const float reading = float(value); - Column sample; - sample.minimum = sample.maximum = reading; - merge(columns_[slot % Columns], sample); - if (!any_ || timeUs > latestUs_) latestUs_ = timeUs; - any_ = true; -} -bool History::span(unsigned index) { - if (index >= SpanCount) index = SpanCount - 1; - if (index == span_) return false; - Column previous[Columns]; // 2.9 KiB of stack, only for the key press: not kept in DTCM. - std::copy(std::begin(columns_), std::end(columns_), std::begin(previous)); - const uint64_t before = spanUs(); - const uint32_t oldLatest = slotOf(latestUs_); - span_ = index; - for (auto &column : columns_) column = Column{}; - if (!any_) return true; - const uint32_t latest = slotOf(latestUs_); - const uint32_t first = latest + 1 >= Columns ? latest + 1 - Columns : 0; - uint32_t oldest = UINT32_MAX; // The first new slot with readings. - for (unsigned i = 0; i < Columns; ++i) { - if (oldLatest + i < Columns - 1) continue; // Before time 0. - const uint32_t old = oldLatest + i - (Columns - 1); - const auto &column = previous[old % Columns]; - if (column.empty()) continue; - // The old column's time [start, end), within the readings kept, in new slots. - const uint64_t start = uint64_t(old) * before / Columns, end = (uint64_t(old) + 1) * before / Columns; - // Finer: only one envelope is known for the coarse column's whole time, so it is a flat step at - // its middle over that time (thin, not a band; no slope drawn between readings never taken). - // Its part older than the new window is dropped. Coarser: the envelopes merge. - Column level = column; - if (spanUs() < before) level.minimum = level.maximum = column.minimum + (column.maximum - column.minimum) / 2; - uint32_t from = slotOf(start), to = slotOf((end > start ? end : start + 1) - 1); - if (to > latest) to = latest; - if (from < first) from = first; - for (uint32_t slot = from; slot <= to; ++slot) { merge(columns_[slot % Columns], level); oldest = std::min(oldest, slot); } - } - any_ = oldest != UINT32_MAX; - if (!any_) latestUs_ = 0; - // A HOLD mark with no curve left before it is dropped too (it does not come back on a longer span). - for (auto &mark : marks_) - if (mark && slotOf(mark - 1) <= oldest) mark = 0; - return true; -} -bool History::column(unsigned index, uint64_t endUs, Column &output) const { - if (!any_ || index >= Columns) return false; - const uint32_t latest = slotOf(latestUs_), end = slotOf(endUs > latestUs_ ? endUs : latestUs_); - if (end + index < Columns - 1) return false; // Before time 0. - const uint32_t slot = end + index - (Columns - 1); - // Newer than the newest reading, or older than the slots kept. - if (slot > latest || slot + Columns <= latest) return false; - const auto &column = columns_[slot % Columns]; - if (column.empty()) return false; - output = column; - return true; -} void Session::reselect() { resetStatistics(); // The charge stays: only a confirmed packet of another function resets it. settle_.clear(); diff --git a/src/measurement/dmm/uart_dma.cpp b/src/measurement/dmm/uart_dma.cpp index 22f3bcfa..f60315d2 100644 --- a/src/measurement/dmm/uart_dma.cpp +++ b/src/measurement/dmm/uart_dma.cpp @@ -63,7 +63,8 @@ bool UartDma::start() { written_ = 0; read_ = 0; received_ = 0; - errors_ = overflows_ = 0; + overflows_ = 0; + errors_ = 0; active_ = this; Interrupts::attach(UART5_IRQn, uartInterrupt); Interrupts::attach(DMA1_Stream4_IRQn, dmaInterrupt); @@ -112,7 +113,7 @@ void UartDma::receive() { const uint32_t written = written_.load(std::memory_order_relaxed), read = read_.load(std::memory_order_acquire); if (written - read >= sizeof queue_) { - ++overflows_; + overflows_ = overflows_ + 1; continue; } queue_[written & 255] = byte; @@ -147,7 +148,7 @@ void UartDma::service(uint32_t now) { void UartDma::interrupt() { const uint32_t status = UART5->ISR; if (status & (USART_ISR_ORE | USART_ISR_FE | USART_ISR_NE)) { - ++errors_; + errors_ = errors_ + 1; UART5->ICR = USART_ICR_ORECF | USART_ICR_FECF | USART_ICR_NECF; } if (status & USART_ISR_IDLE) { @@ -155,7 +156,9 @@ void UartDma::interrupt() { receive(); } if ((UART5->CR1 & USART_CR1_TXEIE_TXFNFIE) && (status & USART_ISR_TXE_TXFNF)) { - UART5->TDR = tx_[transmitted_++]; + const auto index = transmitted_; + transmitted_ = index + 1; + UART5->TDR = tx_[index]; if (transmitted_ == 2) { UART5->CR1 &= ~USART_CR1_TXEIE_TXFNFIE; UART5->CR1 |= USART_CR1_TCIE; @@ -185,7 +188,7 @@ void UartDma::dmaInterrupt() { const uint32_t flags = DMA1->HISR; DMA1->HIFCR = 0x3d; if (flags & (Fifo | DirectMode | Transfer)) { - ++active_->errors_; + active_->errors_ = active_->errors_ + 1; if ((flags & Transfer) || !(DMA1_Stream4->CR & DMA_SxCR_EN)) { active_->status_ = DataStatus::HardwareError; return; diff --git a/src/platform/board.cpp b/src/platform/board.cpp index eb02ba66..3e5d45d6 100644 --- a/src/platform/board.cpp +++ b/src/platform/board.cpp @@ -89,7 +89,7 @@ void Board::configurePe10(bool generatorMode) { // Servicing while waiting: not a proof of progress (Watchdog::heartbeat/progress are). void Board::service() { Watchdog::service(HAL_GetTick(), reinterpret_cast(__builtin_return_address(0))); - ++boot_diagnostics.heartbeat; + boot_diagnostics.heartbeat = boot_diagnostics.heartbeat + 1; } uint32_t Board::milliseconds() { return HAL_GetTick(); } void Board::delay(uint32_t ms) { diff --git a/src/platform/control_latch.cpp b/src/platform/control_latch.cpp index 4cda0fd1..696fb195 100644 --- a/src/platform/control_latch.cpp +++ b/src/platform/control_latch.cpp @@ -9,8 +9,10 @@ namespace { // that the register's outputs, including the power-hold bits, ripple as briefly as possible. volatile uint32_t settleLoops = 8; void settle() { - for (volatile unsigned wait = 0; wait < settleLoops; ++wait) + for (volatile unsigned wait = 0; wait < settleLoops;) { __NOP(); + wait = wait + 1; + } } } // namespace void ControlLatch::write(uint16_t value) { diff --git a/src/platform/heap.c b/src/platform/heap.c new file mode 100644 index 00000000..cc3d2bc8 --- /dev/null +++ b/src/platform/heap.c @@ -0,0 +1,33 @@ +#include +#include +#include + +/* newlib's _sbrk_r copies this syscall error into its caller's reentrancy state. */ +#undef errno +extern int errno; + +extern unsigned char _end[]; +extern unsigned char _heap_limit[]; + +/* The caller lives in the toolchain archive outside the LTO unit. */ +__attribute__((used)) void *_sbrk(ptrdiff_t increment) +{ + static uintptr_t current = (uintptr_t)_end; + const uintptr_t previous = current; + if (increment >= 0) { + const uintptr_t growth = (uintptr_t)increment; + if (growth <= (uintptr_t)_heap_limit - current) { + current += growth; + return (void *)previous; + } + } else { + /* Unsigned negation also handles PTRDIFF_MIN. */ + const uintptr_t shrink = (uintptr_t)0 - (uintptr_t)increment; + if (shrink <= current - (uintptr_t)_end) { + current -= shrink; + return (void *)previous; + } + } + errno = ENOMEM; + return (void *)-1; +} diff --git a/src/platform/recovery_request.cpp b/src/platform/recovery_request.cpp index dfe64743..ac5187ce 100644 --- a/src/platform/recovery_request.cpp +++ b/src/platform/recovery_request.cpp @@ -25,7 +25,10 @@ RecoveryRequest::Request RecoveryRequest::take() { if (r.magic != Magic || r.inverse != ~Magic) return request; const uint32_t kind = r.kind, crc = r.crc; for (unsigned i = 0; i < NameBytes; ++i) request.name[i] = r.name[i]; - r.magic = r.inverse = r.kind = r.crc = 0; + r.crc = 0; + r.kind = 0; + r.inverse = 0; + r.magic = 0; for (unsigned i = 0; i < NameBytes; ++i) r.name[i] = 0; __DSB(); request.recovery = true; @@ -40,7 +43,8 @@ void RecoveryRequest::post(const char *install) { if (install) std::strncpy(name, install, NameBytes - 1); const uint32_t kind = install ? KindInstall : KindMenu; volatile Record &r = record(); - r.magic = r.inverse = 0; // Not a request while it is written. + r.inverse = 0; + r.magic = 0; // Not a request while it is written. r.kind = kind; r.crc = check(kind, name); for (unsigned i = 0; i < NameBytes; ++i) r.name[i] = name[i]; r.magic = Magic; r.inverse = ~Magic; // Last: a record is a request only whole. diff --git a/src/platform/timer_plan.cpp b/src/platform/timer_plan.cpp index 9b780d63..bb826f61 100644 --- a/src/platform/timer_plan.cpp +++ b/src/platform/timer_plan.cpp @@ -1,4 +1,5 @@ #include "openosc/platform/timer_plan.hpp" +#include #include #include #include @@ -13,30 +14,36 @@ bool TimerPlan::calculate(uint32_t clock, Rational requested, TimerPlan &output, source > uint64_t(requested.numerator) * 65536 * 65536) return false; const uint64_t max = uint64_t(requested.numerator) * 65536; - const uint32_t first = static_cast(source / max + (source % max != 0)); + // Include the last prescaler whose ideal period can exceed the register. + // Its maximum period may be closer than rounding at the next prescaler. + const uint32_t first = static_cast(source / max); + const double target = requested.value(); double best = std::numeric_limits::infinity(); TimerPlan candidate; for (uint32_t prescaler = first ? first : 1; prescaler <= 65536; ++prescaler) { const uint64_t denominator = uint64_t(requested.numerator) * prescaler; - const uint64_t ideal = source / denominator; + const uint64_t ideal = std::min(source / denominator, 65536); if (ideal + 1 < minimum) break; for (uint64_t period : {ideal, ideal + 1}) { if (period < minimum || period > 65536) continue; const uint64_t divisor = uint64_t(prescaler) * period; + const double error = std::fabs(double(clock) / divisor - target); + if (error >= best) + continue; const uint64_t common = std::gcd(uint64_t(clock), divisor); if (divisor / common > UINT32_MAX) continue; - const double error = std::fabs(double(clock) / divisor - requested.value()); - if (error >= best) - continue; best = error; candidate.prescaler = prescaler - 1; candidate.reload = period - 1; candidate.actualHz = {uint32_t(clock / common), uint32_t(divisor / common)}; } - if (best == 0) + // Beyond the square root, every smaller period paired with a larger + // prescaler has already been considered with the two factors swapped. + // Larger square divisors only move farther from the requested rate. + if (best == 0 || ideal < prescaler) break; } if (!std::isfinite(best)) diff --git a/src/storage/block_device.cpp b/src/storage/block_device.cpp index d32e9af0..aa102088 100644 --- a/src/storage/block_device.cpp +++ b/src/storage/block_device.cpp @@ -79,6 +79,13 @@ bool BlockDevice::readBytes(uint32_t address, uint32_t bytes, uint8_t* data, Med const uint64_t capacity = uint64_t(sectorCount()) * sectorSize_; if (requester != owner_ || (!data && bytes) || address > capacity || bytes > capacity - address) return false; if (!bytes) return true; + if (cacheValid_ && dirty_ && address >= cached_) { + const uint32_t offset = address - cached_; + if (offset < sizeof scratch_ && bytes <= sizeof scratch_ - offset) { + std::memcpy(data, scratch_ + offset, bytes); + return true; + } + } if (!nor_.read(address, data, bytes)) return false; if (cacheValid_ && dirty_ && address < cached_ + 4096 && cached_ < address + bytes) { // Newer than the NOR. const uint32_t from = address > cached_ ? address : cached_, to = address + bytes < cached_ + 4096 ? address + bytes : cached_ + 4096; @@ -96,7 +103,7 @@ bool BlockDevice::write(uint32_t lba, uint32_t count, const uint8_t* data, Media uint32_t chunk = 4096 - offset; if (chunk > remaining) chunk = remaining; if (owner_ != MediaOwner::Local) { // The host (in its interrupt): write-through, off the cache state. - if (!nor_.read(physical, scratch_, sizeof scratch_)) return false; + if (chunk < sizeof scratch_ && !nor_.read(physical, scratch_, sizeof scratch_)) return false; std::memcpy(scratch_ + offset, data, chunk); if (!writeBlock(physical)) return false; address += chunk; data += chunk; remaining -= chunk; diff --git a/src/ui/components/function_symbols.cpp b/src/ui/components/function_symbols.cpp index 5897ae79..2f533c3b 100644 --- a/src/ui/components/function_symbols.cpp +++ b/src/ui/components/function_symbols.cpp @@ -7,7 +7,7 @@ namespace openosc::ui { namespace { using S = FunctionSymbols::Symbol; -constexpr char TemperatureGlyph[] = u8"\ueb38"; // Tabler Icons Webfont, temperature. +constexpr char TemperatureGlyph[] = "\xee\xac\xb8"; // Tabler Icons Webfont, temperature. const lv_font_t *temperatureFont(int height) { return height >= 20 ? &openosc_icons_24 : &openosc_icons_12; } int temperatureWidth(const lv_font_t *font) { return lv_font_get_glyph_width(font, U'\ueb38', 0); } struct Quantity { const char *letters; bool ac; }; diff --git a/src/ui/components/menu_row.cpp b/src/ui/components/menu_row.cpp index a89b4250..f8ad7ec4 100644 --- a/src/ui/components/menu_row.cpp +++ b/src/ui/components/menu_row.cpp @@ -87,12 +87,12 @@ void MenuRow::toggle(bool checked) { lv_obj_set_style_bg_opa(control, LV_OPA_COVER, LV_PART_MAIN); lv_obj_set_style_bg_color(control, lv_color_hex(ink_.track), LV_PART_MAIN); lv_obj_set_style_radius(control, LV_RADIUS_CIRCLE, LV_PART_MAIN); - lv_obj_set_style_bg_opa(control, LV_OPA_COVER, LV_PART_INDICATOR | LV_STATE_CHECKED); - lv_obj_set_style_bg_color(control, lv_color_hex(ink_.accent), LV_PART_INDICATOR | LV_STATE_CHECKED); + lv_obj_set_style_bg_opa(control, LV_OPA_COVER, lv_style_selector_t(LV_PART_INDICATOR) | LV_STATE_CHECKED); + lv_obj_set_style_bg_color(control, lv_color_hex(ink_.accent), lv_style_selector_t(LV_PART_INDICATOR) | LV_STATE_CHECKED); lv_obj_set_style_radius(control, LV_RADIUS_CIRCLE, LV_PART_INDICATOR); lv_obj_set_style_bg_opa(control, LV_OPA_COVER, LV_PART_KNOB); lv_obj_set_style_bg_color(control, lv_color_hex(ink_.knob), LV_PART_KNOB); - lv_obj_set_style_bg_color(control, lv_color_hex(ink_.knobOn), LV_PART_KNOB | LV_STATE_CHECKED); + lv_obj_set_style_bg_color(control, lv_color_hex(ink_.knobOn), lv_style_selector_t(LV_PART_KNOB) | LV_STATE_CHECKED); lv_obj_set_style_radius(control, LV_RADIUS_CIRCLE, LV_PART_KNOB); lv_obj_set_style_anim_duration(control, 0, 0); if (checked) lv_obj_add_state(control, LV_STATE_CHECKED); diff --git a/src/ui/components/meter_trend.cpp b/src/ui/components/meter_trend.cpp index 5d743b66..600984e2 100644 --- a/src/ui/components/meter_trend.cpp +++ b/src/ui/components/meter_trend.cpp @@ -248,11 +248,12 @@ void MeterTrend::update(const dmm::History *history, uint64_t nowUs, Quantity qu // The window's envelope. bool any = false; double low = 0, high = 0; - dmm::History::Column column; + const auto window = history ? history->window(nowUs) : dmm::History::Window{}; for (unsigned c = 0; history && c < dmm::History::Columns; ++c) { - if (!history->column(c, nowUs, column)) continue; - if (!any || column.minimum < low) low = column.minimum; - if (!any || column.maximum > high) high = column.maximum; + const auto *column = window.column(c); + if (!column) continue; + if (!any || column->minimum < low) low = column->minimum; + if (!any || column->maximum > high) high = column->maximum; any = true; } const bool temperature = quantity == Quantity::Temperature, delta = relative || peerRelative; @@ -282,7 +283,7 @@ void MeterTrend::update(const dmm::History *history, uint64_t nowUs, Quantity qu bool changed = false; for (unsigned c = 0; c < dmm::History::Columns; ++c) { uint8_t low = NoRow, high = NoRow; - if (any && history->column(c, nowUs, column)) { low = row(column.minimum); high = row(column.maximum); } + if (const auto *column = window.column(c)) { low = row(column->minimum); high = row(column->maximum); } if (rows_[2 * c] != low || rows_[2 * c + 1] != high) { rows_[2 * c] = low; rows_[2 * c + 1] = high; changed = true; } } if (changed) lv_obj_invalidate(plot_); diff --git a/src/ui/scope/column_cache.cpp b/src/ui/scope/column_cache.cpp index 9f60c2d5..fee7744c 100644 --- a/src/ui/scope/column_cache.cpp +++ b/src/ui/scope/column_cache.cpp @@ -19,16 +19,16 @@ bool ColumnCache::prepare(const scope::FrameView &frame, const Options &options, const auto &m = frame.metadata(); if (!same(m, viewport)) { sequence_ = m.sequence; timestamp_ = m.timestampUs; trigger_ = m.triggerIndex; - viewport_ = viewport; done_ = 0; valid_ = true; + viewport_ = viewport; done_ = 0; } uint32_t read = 0; - while (done_ < viewport_.width && read < points) { + while (done_ < viewport.width && read < points) { uint32_t first, last; - viewport_.column(done_, m.samples, first, last); + viewport.column(done_, m.samples, first, last); if (!reduce(frame, first, last, stats_[done_])) { clear(); return true; } read += last - first; ++done_; } - return done_ == viewport_.width; + return done_ == viewport.width; } } // namespace openosc::plot diff --git a/src/update/image_check.cpp b/src/update/image_check.cpp index bc8f8a22..6f097517 100644 --- a/src/update/image_check.cpp +++ b/src/update/image_check.cpp @@ -32,7 +32,8 @@ const char* ImageCheck::checkPayload(FIL& file) { } if (f_lseek(&file, payloadOffset_) != FR_OK) return "CANNOT SEEK IMAGE PAYLOAD"; Crc32 crc, whole; - whole.update(&image_, sizeof image_); + const bool bundled = package_.format == PackageFormat; + if (bundled) whole.update(&image_, sizeof image_); uint32_t position = 0; while (position < image_.payloadBytes) { uint32_t chunk = image_.payloadBytes - position; @@ -49,7 +50,7 @@ const char* ImageCheck::checkPayload(FIL& file) { if (result != ImageError::None) return ImageValidator::message(result); } crc.update(buffer_, count); - whole.update(buffer_, count); + if (bundled) whole.update(buffer_, count); position += count; if (raw() && position == trailer.programBytes && crc.value() != trailer.programCrc) return "FULL FILE CRC FAILED"; @@ -59,7 +60,7 @@ const char* ImageCheck::checkPayload(FIL& file) { image_.payloadCrc = crc.value(); image_.headerCrc = ImageValidator::headerCrc(image_); } else if (crc.value() != image_.payloadCrc) return "FULL FILE CRC FAILED"; - if (package_.format == PackageFormat && whole.value() != package_.imageCrc) return "FULL FILE CRC FAILED"; + if (bundled && whole.value() != package_.imageCrc) return "FULL FILE CRC FAILED"; return nullptr; } // Each resource's CRC; a font pack's own header too (format 1 or 2: one some application can read). diff --git a/src/usb/instrument/class.cpp b/src/usb/instrument/class.cpp index c6e64169..ea72e9d2 100644 --- a/src/usb/instrument/class.cpp +++ b/src/usb/instrument/class.cpp @@ -41,7 +41,7 @@ uint8_t init(USBD_HandleTypeDef *dev, uint8_t) { } if (USBD_LL_OpenEP(dev,0x82,USBD_EP_TYPE_INTR,8) != USBD_OK) return USBD_FAIL; dev->ep_in[2].is_used = 1; - instrument.configured = true; ++instrument.generation; instrument.dtr = false; + instrument.configured = true; instrument.generation = instrument.generation + 1; instrument.dtr = false; instrument.clearMask|=3; tmcRecovery.reset(instrument.generation); // SET_CONFIGURATION (USBTMC Table 17): a new session. for (unsigned i=0;i<2;++i) { @@ -51,7 +51,7 @@ uint8_t init(USBD_HandleTypeDef *dev, uint8_t) { return USBD_OK; } uint8_t deinit(USBD_HandleTypeDef *dev, uint8_t) { - instrument.configured = false; ++instrument.generation; + instrument.configured = false; instrument.generation = instrument.generation + 1; tmcRecovery.reset(instrument.generation); // Bus reset or a new configuration (4.2.1.1, rule 7). for (uint8_t ep : {uint8_t(1),uint8_t(3)}) { USBD_LL_CloseEP(dev,ep); USBD_LL_CloseEP(dev,ep | 0x80); diff --git a/src/usb/msc_storage.cpp b/src/usb/msc_storage.cpp index 501c9c23..7e3bcf6b 100644 --- a/src/usb/msc_storage.cpp +++ b/src/usb/msc_storage.cpp @@ -29,14 +29,14 @@ int8_t read(uint8_t lun, uint8_t* data, uint32_t address, uint16_t count) { openosc::usbHostClaimed = true; if (!ready(lun)) return -1; bool result = storage->read(address, count, data, openosc::MediaOwner::Host); - if (result) openosc::boot_diagnostics.usbReads += count; + if (result) openosc::boot_diagnostics.usbReads = openosc::boot_diagnostics.usbReads + count; return result ? 0 : -1; } int8_t write(uint8_t lun, uint8_t* data, uint32_t address, uint16_t count) { openosc::usbHostClaimed = true; if (!ready(lun)) return -1; bool result = storage->write(address, count, data, openosc::MediaOwner::Host); - if (result) openosc::boot_diagnostics.usbWrites += count; + if (result) openosc::boot_diagnostics.usbWrites = openosc::boot_diagnostics.usbWrites + count; return result ? 0 : -1; } int8_t maxLun() { return 0; } diff --git a/src/usb/pcd_callbacks.cpp b/src/usb/pcd_callbacks.cpp index 1ebe0d6f..879d3e15 100644 --- a/src/usb/pcd_callbacks.cpp +++ b/src/usb/pcd_callbacks.cpp @@ -8,7 +8,7 @@ USBD_HandleTypeDef* device(PCD_HandleTypeDef* handle) { return static_cast(reinterpret_cast(handle->Instance) + USB_OTG_IN_ENDPOINT_BASE); @@ -47,7 +47,7 @@ extern "C" void HAL_PCD_DataInStageCallback(PCD_HandleTypeDef* handle, uint8_t e } extern "C" void HAL_PCD_ResetCallback(PCD_HandleTypeDef* handle) { #ifdef OPENOSC_APPLICATION - ++openosc::usbResets; + openosc::usbResets = openosc::usbResets + 1; #endif USBD_LL_SetSpeed(device(handle), USBD_SPEED_FULL); USBD_LL_Reset(device(handle)); diff --git a/test/test_dmm_history/test_history.cpp b/test/test_dmm_history/test_history.cpp new file mode 100644 index 00000000..6012ecc7 --- /dev/null +++ b/test/test_dmm_history/test_history.cpp @@ -0,0 +1,71 @@ +#include "openosc/measurement/dmm/session.hpp" +#include + +using openosc::dmm::History; + +void setUp() {} +void tearDown() {} + +void test_view_scrolls_and_expires() { + History history; + history.push(3, 0); + history.push(-2, 100); + const auto view = history.window(250000); // Default scale is 250 ms per column. + const auto *reading = view.column(History::Columns - 2); + TEST_ASSERT_NOT_NULL(reading); + TEST_ASSERT_EQUAL_FLOAT(-2, reading->minimum); + TEST_ASSERT_EQUAL_FLOAT(3, reading->maximum); + TEST_ASSERT_NULL(view.column(History::Columns - 1)); + TEST_ASSERT_NULL(view.column(0)); + TEST_ASSERT_NULL(view.column(History::Columns)); + TEST_ASSERT_NULL(history.window(history.spanUs()).column(0)); +} + +void test_slot_rollover_preserves_readings_and_hold_marks() { + History history; + history.span(0); + constexpr uint64_t rollover = ((uint64_t{1} << 32) * 10000000 + History::Columns - 1) / History::Columns; + history.push(1, rollover - 41667); + history.mark(rollover - 41667); + history.push(2, rollover); + const auto view = history.window(rollover); + for (unsigned i = 0; i < 2; ++i) { + const auto *reading = view.column(History::Columns - 2 + i); + TEST_ASSERT_NOT_NULL(reading); + TEST_ASSERT_EQUAL_FLOAT(i + 1, reading->minimum); + } + unsigned mark = 0; + TEST_ASSERT_TRUE(history.markColumn(0, rollover, mark)); + TEST_ASSERT_EQUAL_UINT(History::Columns - 2, mark); + history.span(1); + const auto *reading = history.window(rollover).column(History::Columns - 1); + TEST_ASSERT_NOT_NULL(reading); + TEST_ASSERT_EQUAL_FLOAT(2, reading->maximum); +} + +void test_rebin_preserves_gaps_and_combines_extrema() { + History history; + history.span(0); + history.push(4, 125000); + history.push(8, 166667); + history.span(1); // Slots 3 and 4 now both belong to slot 1. + const auto coarse = history.window(249999); + TEST_ASSERT_NULL(coarse.column(History::Columns - 2)); + const auto *reading = coarse.column(History::Columns - 1); + TEST_ASSERT_NOT_NULL(reading); + TEST_ASSERT_EQUAL_FLOAT(4, reading->minimum); + TEST_ASSERT_EQUAL_FLOAT(8, reading->maximum); + history.span(0); + const auto *level = history.window(166667).column(History::Columns - 1); + TEST_ASSERT_NOT_NULL(level); + TEST_ASSERT_EQUAL_FLOAT(6, level->minimum); + TEST_ASSERT_EQUAL_FLOAT(6, level->maximum); +} + +int main() { + UNITY_BEGIN(); + RUN_TEST(test_view_scrolls_and_expires); + RUN_TEST(test_slot_rollover_preserves_readings_and_hold_marks); + RUN_TEST(test_rebin_preserves_gaps_and_combines_extrema); + return UNITY_END(); +} diff --git a/test/test_dmm_packet/test_dmm_packet.cpp b/test/test_dmm_packet/test_dmm_packet.cpp index 261ae49a..3f0ad273 100644 --- a/test/test_dmm_packet/test_dmm_packet.cpp +++ b/test/test_dmm_packet/test_dmm_packet.cpp @@ -17,19 +17,19 @@ constexpr uint8_t Overload25MOhm[Packet::Bytes] = {0xff, 0x00, 0x10, 0x61, 0xeb, // patterns, p[4] the leftmost; bit 4 of a digit is the point before it (of p[4]: the sign). struct Synthetic { uint8_t bytes[Packet::Bytes]{0xff}; - uint8_t *p = bytes + 1; void seal() { bytes[17] = Packet::checksum(bytes); } }; // "1.2345" V DC, auto range: 1 2 3 4 5 = 0x0a 0xad 0x8f 0x4e 0xc7, the point on the "2". Synthetic volts(bool negative) { Synthetic s; - s.p[4] = uint8_t(0x0a | (negative ? 0x10 : 0)); - s.p[3] = 0xad | 0x10; - s.p[2] = 0x8f; - s.p[1] = 0x4e; - s.p[0] = 0xc7; - s.p[10] = 0x10 | 0x04; // DC, AUTO. - s.p[15] = 0x02; // V. + auto *p = s.bytes + 1; + p[4] = uint8_t(0x0a | (negative ? 0x10 : 0)); + p[3] = 0xad | 0x10; + p[2] = 0x8f; + p[1] = 0x4e; + p[0] = 0xc7; + p[10] = 0x10 | 0x04; // DC, AUTO. + p[15] = 0x02; // V. s.seal(); return s; } @@ -101,8 +101,12 @@ void test_decode_captured_overload() { TEST_ASSERT_FALSE(r.primary.valid()); TEST_ASSERT_EQUAL_UINT32(66000, r.rawMagnitude); unsigned index = 99; - TEST_ASSERT_NOT_NULL(Ranges::current(r, &index)); - TEST_ASSERT_EQUAL_UINT(5, index); // 25 MOhm, by the overload alias. + if constexpr (board::Current::Features.dmmCounts == board::DmmCounts::Counts25000) { + TEST_ASSERT_NOT_NULL(Ranges::current(r, &index)); + TEST_ASSERT_EQUAL_UINT(5, index); // 25 MOhm, by the ZT703S overload alias. + } else { + TEST_ASSERT_NULL(Ranges::current(r, &index)); + } } void test_segment_patterns() { diff --git a/test/test_timer_plan/test_timer_plan.cpp b/test/test_timer_plan/test_timer_plan.cpp new file mode 100644 index 00000000..4a957279 --- /dev/null +++ b/test/test_timer_plan/test_timer_plan.cpp @@ -0,0 +1,44 @@ +#include "openosc/platform/timer_plan.hpp" +#include +#include +#include + +using openosc::Rational; +using openosc::TimerPlan; + +void setUp() {} +void tearDown() {} + +void test_maximum_period_can_be_the_closest_rate() { + TimerPlan plan; + TEST_ASSERT_TRUE(TimerPlan::calculate(4294901761U, {1, 1}, plan, 65536)); + TEST_ASSERT_EQUAL_UINT16(65534, plan.prescaler); + TEST_ASSERT_EQUAL_UINT16(65535, plan.reload); +} + +void test_plan_matches_full_prescaler_search() { + for (const unsigned minimum : {1U, 2U, 30U, 1000U}) { + for (const Rational target : {Rational{1000, 1}, {6727487, 1000}, {41, 100}, {4000000, 3}}) { + constexpr uint32_t clock = 200000000; + if (target.value() * minimum > clock) continue; + TimerPlan plan; + TEST_ASSERT_TRUE(TimerPlan::calculate(clock, target, plan, minimum)); + TEST_ASSERT_TRUE(plan.reload + 1U >= minimum); + const uint64_t divider = uint64_t(plan.prescaler + 1U) * (plan.reload + 1U); + TEST_ASSERT_EQUAL_DOUBLE(double(clock) / divider, plan.actualHz.value()); + const double error = std::abs(plan.actualHz.value() - target.value()); + for (unsigned p = 1; p <= 65536; ++p) { + const double period = std::clamp(clock / (p * target.value()), double(minimum), 65536.); + for (double q : {std::floor(period), std::ceil(period)}) + TEST_ASSERT_TRUE(error <= std::abs(clock / (p * q) - target.value())); + } + } + } +} + +int main() { + UNITY_BEGIN(); + RUN_TEST(test_maximum_period_can_be_the_closest_rate); + RUN_TEST(test_plan_matches_full_prescaler_search); + return UNITY_END(); +}