# Host (PC) tests of the chapter-20 data logger and its bootloader.
# GebraBit advanced STM32 course, chapter 20 (method of chapter 18).
#
#   cmake -S host_tests -B build/host -G Ninja [-DENABLE_COVERAGE=ON]
#   cmake --build build/host
#   ctest --test-dir build/host --output-on-failure
#   cmake --build build/host --target coverage   (ENABLE_COVERAGE=ON + gcovr)
#   cmake --build build/host --target lint       (cppcheck, chapter-3 options)
#
# The production sources are compiled straight from the two firmware
# projects (no copies), so the tested code IS the shipped code.
cmake_minimum_required(VERSION 3.22)
project(gebrabit_adv20_host LANGUAGES C)

if(CMAKE_CROSSCOMPILING)
  message(FATAL_ERROR "Host test build: use the firmware presets for the STM32.")
endif()

set(CMAKE_C_STANDARD 11)
set(CMAKE_C_STANDARD_REQUIRED ON)
set(CMAKE_C_EXTENSIONS ON)          # CMSIS-DSP host build and the pty simulator need GNU C
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
if(NOT CMAKE_BUILD_TYPE)
  set(CMAKE_BUILD_TYPE Debug)
endif()

option(ENABLE_COVERAGE "Compile and link everything with --coverage (gcov)" OFF)
if(ENABLE_COVERAGE)
  add_compile_options(--coverage -O0 -g -fprofile-abs-path)
  add_link_options(--coverage)
endif()

set(STRICT_WARNINGS -Wall -Wextra -Werror)
get_filename_component(LOGGER ${CMAKE_CURRENT_SOURCE_DIR}/../gebrabit_adv20_logger ABSOLUTE)
get_filename_component(BOOT   ${CMAKE_CURRENT_SOURCE_DIR}/../gebrabit_adv20_boot ABSOLUTE)
get_filename_component(GB_ROOT ${CMAKE_CURRENT_SOURCE_DIR}/.. ABSOLUTE)
set(VEC    ${CMAKE_CURRENT_SOURCE_DIR}/vectors)

include(CTest)

# Unity v2.7.0 (MIT), vendored as in chapter 18
add_library(unity STATIC third_party/unity/unity.c)
target_include_directories(unity PUBLIC third_party/unity)
target_compile_definitions(unity PUBLIC UNITY_INCLUDE_DOUBLE)

# ---- production code of the application (hardware independent) ---------
add_library(lg_core STATIC
  ${LOGGER}/Core/Src/lg_regs.c
  ${LOGGER}/Core/Src/lg_record.c
  ${LOGGER}/Core/Src/lg_sample.c
  ${LOGGER}/Core/Src/modbus_slave.c
  ${LOGGER}/Core/Src/log_store.c
  ${LOGGER}/Core/Src/devinfo.c)
target_include_directories(lg_core PUBLIC ${LOGGER}/Core/Inc)
target_compile_definitions(lg_core PUBLIC LOG_MAX_PAGES=8U)
target_compile_options(lg_core PRIVATE ${STRICT_WARNINGS})

# CMSIS-DSP v1.16.2 biquad, compiled for the PC (generic C path)
add_library(cmsisdsp_host STATIC
  ${LOGGER}/Middlewares/CMSIS-DSP/Source/FilteringFunctions/arm_biquad_cascade_df2T_f32.c
  ${LOGGER}/Middlewares/CMSIS-DSP/Source/FilteringFunctions/arm_biquad_cascade_df2T_init_f32.c)
target_include_directories(cmsisdsp_host SYSTEM PUBLIC ${LOGGER}/Middlewares/CMSIS-DSP/Include
  PRIVATE ${LOGGER}/Middlewares/CMSIS-DSP/PrivateInclude)
target_compile_definitions(cmsisdsp_host PUBLIC __GNUC_PYTHON__ DISABLEFLOAT16)

add_library(lg_filter STATIC ${LOGGER}/Core/Src/lp_filter.c)
target_include_directories(lg_filter PUBLIC ${LOGGER}/Core/Inc)
target_link_libraries(lg_filter PUBLIC cmsisdsp_host m)
target_compile_options(lg_filter PRIVATE ${STRICT_WARNINGS})

# ---- production code of the bootloader --------------------------------------
add_library(boot_core STATIC
  ${BOOT}/Core/Src/image.c ${BOOT}/Core/Src/boot_cmd.c ${BOOT}/Core/Src/proto_cmd.c
  ${BOOT}/Core/Src/frame.c ${BOOT}/Core/Src/cobs.c
  tests/fakes/sim_flash.c)
target_include_directories(boot_core PUBLIC ${BOOT}/Core/Inc tests/fakes)
target_compile_options(boot_core PRIVATE ${STRICT_WARNINGS})

add_library(fake_nor STATIC tests/fakes/fake_nor_flash.c)
target_include_directories(fake_nor PUBLIC tests/fakes)
target_link_libraries(fake_nor PUBLIC lg_core)
target_compile_options(fake_nor PRIVATE ${STRICT_WARNINGS})

# ---- Unity tests: one executable = one CTest test ------------------------
function(add_unity_test name label)
  add_executable(${name} tests/${name}.c)
  target_link_libraries(${name} PRIVATE ${ARGN} unity)
  target_compile_options(${name} PRIVATE ${STRICT_WARNINGS})
  add_test(NAME ${name} COMMAND ${name} ${TEST_ARGS_${name}})
  set_tests_properties(${name} PROPERTIES LABELS "${label}" TIMEOUT 60)
endfunction()

set(TEST_ARGS_test_lp_filter ${VEC}/lp_vectors.txt)
add_unity_test(test_lg_regs      "modbus"         lg_core)
add_unity_test(test_lp_filter    "dsp;vectors"    lg_filter)
add_unity_test(test_lg_record    "log"            fake_nor)
add_unity_test(test_lg_sample    "ao"             lg_core)
add_unity_test(test_log_store    "log;ch18"       fake_nor)
add_unity_test(test_devinfo      "production"     lg_core)
add_unity_test(test_image_single "boot"           boot_core)

# ---- earlier chapters' own host tests, run against the capstone copies -----
add_executable(legacy_ch16 legacy/ch16_host_test.c
  ${LOGGER}/Core/Src/fault_record.c ${LOGGER}/Core/Src/wdg_sup.c)
target_include_directories(legacy_ch16 PRIVATE ${LOGGER}/Core/Inc)
target_compile_options(legacy_ch16 PRIVATE ${STRICT_WARNINGS})
add_test(NAME legacy_ch16_fault_wdg COMMAND legacy_ch16)
set_tests_properties(legacy_ch16_fault_wdg PROPERTIES LABELS "reliability;legacy"
  FAIL_REGULAR_EXPRESSION "[1-9][0-9]* failed")

add_executable(legacy_ch12 legacy/ch12_host_test.c
  ${LOGGER}/Core/Src/bmp390.c ${LOGGER}/Core/Src/i2c_bus_clear.c)
target_include_directories(legacy_ch12 PRIVATE ${LOGGER}/Core/Inc)
target_compile_options(legacy_ch12 PRIVATE ${STRICT_WARNINGS})
target_link_libraries(legacy_ch12 PRIVATE m)
add_test(NAME legacy_ch12_bmp390 COMMAND legacy_ch12 ${VEC}/ch12_bmp390_vectors.txt)
set_tests_properties(legacy_ch12_bmp390 PROPERTIES LABELS "sensor;legacy"
  FAIL_REGULAR_EXPRESSION "[1-9][0-9]* failed")

# ---- the files both firmware projects share must be identical --------------
foreach(f Core/Inc/flash_layout.h Core/Inc/boot_shared.h Core/Inc/image.h Core/Src/image.c)
  string(MAKE_C_IDENTIFIER ${f} _id)
  add_test(NAME same_${_id} COMMAND ${CMAKE_COMMAND} -E compare_files ${BOOT}/${f} ${LOGGER}/${f})
  set_tests_properties(same_${_id} PROPERTIES LABELS "copies")
endforeach()
foreach(f image_tool.py proto_lib.py proto_tool.py)
  string(MAKE_C_IDENTIFIER ${f} _id)
  add_test(NAME same_tools_${_id} COMMAND ${CMAKE_COMMAND} -E compare_files
    ${BOOT}/tools/${f} ${LOGGER}/tools/${f})
  set_tests_properties(same_tools_${_id} PROPERTIES LABELS "copies")
endforeach()

# ---- PC simulation of the whole device on a pseudo-terminal ----------------
# Modbus application (real lg_regs, log_store, lp_filter, lg_record) and the
# real bootloader commands (boot_cmd, image) in one process; see sim/lg_sim.c.
add_executable(lg_sim sim/lg_sim.c
  ${LOGGER}/Core/Src/lg_regs.c ${LOGGER}/Core/Src/lg_record.c ${LOGGER}/Core/Src/lg_sample.c
  ${LOGGER}/Core/Src/modbus_slave.c ${LOGGER}/Core/Src/log_store.c ${LOGGER}/Core/Src/lp_filter.c
  ${BOOT}/Core/Src/image.c ${BOOT}/Core/Src/boot_cmd.c ${BOOT}/Core/Src/proto_cmd.c
  ${BOOT}/Core/Src/frame.c ${BOOT}/Core/Src/cobs.c tests/fakes/sim_flash.c)
target_include_directories(lg_sim PRIVATE ${BOOT}/Core/Inc ${LOGGER}/Core/Inc tests/fakes)
target_compile_definitions(lg_sim PRIVATE LOG_MAX_PAGES=8U)
target_link_libraries(lg_sim PRIVATE cmsisdsp_host m)
target_compile_options(lg_sim PRIVATE ${STRICT_WARNINGS})

find_package(Python3 COMPONENTS Interpreter)
if(Python3_FOUND)
  add_test(NAME tool_unit COMMAND ${Python3_EXECUTABLE} -I ${LOGGER}/tools/test_lg_tool.py)
  set_tests_properties(tool_unit PROPERTIES LABELS "python" TIMEOUT 60)
  # needs the signed images of the firmware build (tools/build_images.sh)
  add_test(NAME e2e_modbus_update COMMAND ${Python3_EXECUTABLE} -I ${LOGGER}/tools/test_e2e.py
           --sim $<TARGET_FILE:lg_sim> --images ${CMAKE_BINARY_DIR}/../images)
  set_tests_properties(e2e_modbus_update PROPERTIES LABELS "e2e;python" TIMEOUT 600
                       SKIP_REGULAR_EXPRESSION "skipped=")
endif()

# ---- coverage of the production code ----------------------------------------
if(ENABLE_COVERAGE)
  find_program(GCOVR_EXE NAMES gcovr)
  if(GCOVR_EXE)
    add_custom_target(coverage
      COMMAND ${CMAKE_CTEST_COMMAND} --test-dir ${CMAKE_BINARY_DIR} -LE e2e --output-on-failure
      COMMAND ${GCOVR_EXE} --root ${GB_ROOT}
              --filter ${LOGGER}/Core/Src/ --filter ${BOOT}/Core/Src/
              --txt ${CMAKE_BINARY_DIR}/coverage.txt --print-summary ${CMAKE_BINARY_DIR}
      WORKING_DIRECTORY ${CMAKE_BINARY_DIR}
      VERBATIM)
  endif()
endif()

# ---- cppcheck (chapter 3 options) on the hardware-independent modules -------
find_program(CPPCHECK_EXE NAMES cppcheck)
if(CPPCHECK_EXE)
  add_custom_target(lint
    COMMAND ${CPPCHECK_EXE} --std=c11 --platform=arm32-wchar_t4
            --enable=warning,style,performance,portability --inline-suppr --quiet
            --error-exitcode=1 -I${LOGGER}/Core/Inc -DLOG_MAX_PAGES=8U
            --suppress=missingIncludeSystem --suppress=unusedFunction
            ${LOGGER}/Core/Src/lg_regs.c ${LOGGER}/Core/Src/lg_record.c
            ${LOGGER}/Core/Src/lg_sample.c ${LOGGER}/Core/Src/console.c
            ${LOGGER}/Core/Src/mb_port.c ${LOGGER}/Core/Src/app.c
            ${BOOT}/Core/Src/image.c
    COMMENT "cppcheck on the chapter-20 modules"
    VERBATIM)
endif()
