cmake_minimum_required(VERSION 3.22)

#
# This file is generated only once,
# and is not re-generated if converter is called multiple times.
#
# User is free to modify the file as much as necessary
#

# Setup compiler settings
set(CMAKE_C_STANDARD 11)
set(CMAKE_C_STANDARD_REQUIRED ON)
set(CMAKE_C_EXTENSIONS ON)


# Define the build type
if(NOT CMAKE_BUILD_TYPE)
    set(CMAKE_BUILD_TYPE "Debug")
endif()

# Set the project name
set(CMAKE_PROJECT_NAME gebrabit_adv20_logger)

# Chapter 20: CubeMX regenerates STM32F303XX_FLASH.ld and drops the
# chapter's regions and ASSERTs; the result would still link (at 0x08000000,
# over the bootloader). Stop here instead.
file(READ ${CMAKE_SOURCE_DIR}/STM32F303XX_FLASH.ld _gb_ld)
if(NOT _gb_ld MATCHES "Chapter 20: layout checks")
    message(FATAL_ERROR "STM32F303XX_FLASH.ld is not the chapter-20 version "
            "(regenerated by CubeMX?). Restore it from STM32F303XX_FLASH.ld.ch20")
endif()

# Include toolchain file
include("cmake/gcc-arm-none-eabi.cmake")

# Enable compile command to ease indexing with e.g. clangd
set(CMAKE_EXPORT_COMPILE_COMMANDS TRUE)

# Core project settings
project(${CMAKE_PROJECT_NAME})
message("Build type: " ${CMAKE_BUILD_TYPE})

# Enable CMake support for ASM and C languages
enable_language(C ASM)

# Relative __FILE__ in configASSERT strings: size does not depend on the folder
add_compile_options(-fmacro-prefix-map=${CMAKE_SOURCE_DIR}/=)

# Create an executable object type
add_executable(${CMAKE_PROJECT_NAME})

# Add STM32CubeMX generated sources
add_subdirectory(cmake/stm32cubemx)

# ---------------------------------------------------------------------------
# Chapter 19: firmware version from git, refreshed at EVERY build.
# ---------------------------------------------------------------------------
set(FW_FALLBACK_VERSION "1.0.0" CACHE STRING "X.Y.Z used when no vX.Y.Z tag exists")
set(GB_GEN_DIR ${CMAKE_BINARY_DIR}/gen)
set(GB_VERSION_ARGS
    -DSRC_DIR=${CMAKE_SOURCE_DIR}
    -DOUT_H=${GB_GEN_DIR}/fw_version.h
    -DOUT_JSON=${GB_GEN_DIR}/fw_version.json
    -DBUILD_TYPE=${CMAKE_BUILD_TYPE}
    -DFALLBACK_VERSION=${FW_FALLBACK_VERSION})
execute_process(COMMAND ${CMAKE_COMMAND} ${GB_VERSION_ARGS} -P ${CMAKE_SOURCE_DIR}/cmake/fw_version.cmake)
add_custom_target(gb_fw_version ALL
    COMMAND ${CMAKE_COMMAND} ${GB_VERSION_ARGS} -P ${CMAKE_SOURCE_DIR}/cmake/fw_version.cmake
    BYPRODUCTS ${GB_GEN_DIR}/fw_version.h ${GB_GEN_DIR}/fw_version.json
    COMMENT "git describe -> fw_version.h"
    VERBATIM)
add_dependencies(${CMAKE_PROJECT_NAME} gb_fw_version)

# Link directories setup
target_link_directories(${CMAKE_PROJECT_NAME} PRIVATE
    # Add user defined library search paths
)

# Add sources to executable
target_sources(${CMAKE_PROJECT_NAME} PRIVATE
    # Add user sources here
    # hardware independent (host-tested, ../host_tests)
    Core/Src/ao.c                 # ch14 active object
    Core/Src/lp_filter.c          # ch4 filter stage (CMSIS-DSP biquad)
    Core/Src/lg_sample.c          # ch20 sample ring
    Core/Src/lg_record.c          # ch20 log payload + ch15 calendar
    Core/Src/lg_regs.c            # ch20 Modbus register map
    Core/Src/modbus_slave.c       # ch9
    Core/Src/bmp390.c             # ch12
    Core/Src/i2c_bus_clear.c      # ch12
    Core/Src/log_store.c          # ch15
    Core/Src/fault_record.c       # ch16
    Core/Src/wdg_sup.c            # ch16
    Core/Src/image.c              # ch17 (one-slot variant)
    Core/Src/devinfo.c            # ch19
    # target side
    Core/Src/bus_i2c.c            # ch12 HAL + DMA
    Core/Src/mb_port.c            # ch9 port, event-driven
    Core/Src/flash_port.c         # ch15 HAL Flash + CRC unit
    Core/Src/fault.c              # ch16 handlers, MPU, backup registers
    Core/Src/app_image.c          # ch17 header, confirm, enter bootloader
    Core/Src/console.c            # ch20 USART2 TX ring
    Core/Src/app.c                # ch20 active objects
)

# Add include paths
target_include_directories(${CMAKE_PROJECT_NAME} PRIVATE
    # Add user defined include paths
    ${GB_GEN_DIR}                 # fw_version.h
)

# Chapter 20 test image for the recovery path: never confirms, resets after 3 s
option(LG_TEST_BAD_IMAGE "Build the never-confirming test image (recovery demo)" OFF)
if(LG_TEST_BAD_IMAGE)
    set(_gb_sfx "_bad")
endif()

# Add project symbols (macros)
target_compile_definitions(${CMAKE_PROJECT_NAME} PRIVATE
    # Add user defined symbols
    LOG_MAX_PAGES=8U              # ch15 log_store: 8 pages in this layout
    LG_TEST_BAD_IMAGE=$<IF:$<BOOL:${LG_TEST_BAD_IMAGE}>,1,0>
)

# Add linked libraries
target_link_libraries(${CMAKE_PROJECT_NAME}
    stm32cubemx

    # Add user defined libraries
)

# ---------------------------------------------------------------------------
# GebraBit manual native FreeRTOS integration (as in base lessons 40-46),
# not CubeMX-generated middleware. FreeRTOSConfig.h is in Core/Inc.
# Only the kernel files the application uses (no event groups/streams).
# ---------------------------------------------------------------------------
set(FREERTOS_KERNEL_DIR ${CMAKE_SOURCE_DIR}/Middlewares/Third_Party/FreeRTOS-Kernel)
target_sources(${CMAKE_PROJECT_NAME} PRIVATE
  ${FREERTOS_KERNEL_DIR}/tasks.c
  ${FREERTOS_KERNEL_DIR}/queue.c
  ${FREERTOS_KERNEL_DIR}/list.c
  ${FREERTOS_KERNEL_DIR}/timers.c
  ${FREERTOS_KERNEL_DIR}/portable/MemMang/heap_4.c
  ${FREERTOS_KERNEL_DIR}/portable/GCC/ARM_CM4F/port.c)
target_include_directories(${CMAKE_PROJECT_NAME} PRIVATE
  ${FREERTOS_KERNEL_DIR}/include
  ${FREERTOS_KERNEL_DIR}/portable/GCC/ARM_CM4F)

# ---------------------------------------------------------------------------
# CMSIS-DSP v1.16.2 (Apache-2.0): only the biquad DF2T f32 files (ch4 style).
# ---------------------------------------------------------------------------
set(CMSISDSP_DIR ${CMAKE_SOURCE_DIR}/Middlewares/CMSIS-DSP)
add_library(cmsisdsp STATIC
    ${CMSISDSP_DIR}/Source/FilteringFunctions/arm_biquad_cascade_df2T_f32.c
    ${CMSISDSP_DIR}/Source/FilteringFunctions/arm_biquad_cascade_df2T_init_f32.c)
target_include_directories(cmsisdsp
    SYSTEM PUBLIC ${CMSISDSP_DIR}/Include ${CMAKE_SOURCE_DIR}/Drivers/CMSIS/Include
    PRIVATE ${CMSISDSP_DIR}/PrivateInclude)
target_compile_definitions(cmsisdsp PUBLIC DISABLEFLOAT16 PRIVATE ARM_MATH_LOOPUNROLL)
target_compile_options(cmsisdsp PRIVATE -O2)
target_link_libraries(${CMAKE_PROJECT_NAME} cmsisdsp)

# ---------------------------------------------------------------------------
# Chapter 17: fill size + CRC into the header (ELF updated in place), then
# write <name>_v<ver>.bin/.hex for the update tool and for SWD.
# ---------------------------------------------------------------------------
find_package(Python3 REQUIRED COMPONENTS Interpreter)
set_property(TARGET ${CMAKE_PROJECT_NAME} APPEND PROPERTY LINK_DEPENDS
    ${CMAKE_SOURCE_DIR}/STM32F303XX_FLASH.ld)
add_custom_command(TARGET ${CMAKE_PROJECT_NAME} POST_BUILD
    COMMAND ${Python3_EXECUTABLE} -I ${CMAKE_SOURCE_DIR}/tools/sign_image.py
            --elf $<TARGET_FILE:${CMAKE_PROJECT_NAME}>
            --objcopy ${CMAKE_OBJCOPY}
            --slot-base 0x08008000
            --out ${CMAKE_BINARY_DIR}/${CMAKE_PROJECT_NAME}_signed${_gb_sfx}
    COMMAND ${CMAKE_SIZE} -A -x $<TARGET_FILE:${CMAKE_PROJECT_NAME}>
    COMMAND ${CMAKE_SIZE} $<TARGET_FILE:${CMAKE_PROJECT_NAME}>
    VERBATIM)

# ---------------------------------------------------------------------------
# Chapter 20 (as the ch17 bootloader): in Debug the application's own code
# stays at -O0, but the HAL library is compiled with -Os (last -O wins).
# Everything at -O0 needs 77 464 B = 95.2 % of the 81 376 B slot; with this
# line the Debug image keeps a real margin (numbers in the chapter's table).
# ---------------------------------------------------------------------------
target_compile_options(STM32_Drivers PRIVATE $<$<CONFIG:Debug>:-Os>)
