cmake_minimum_required(VERSION 3.8)
project(ethercat_control)

set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)

find_package(ament_cmake REQUIRED)
find_package(rclcpp REQUIRED)
find_package(std_msgs REQUIRED)
find_package(sensor_msgs REQUIRED)

# IGH ecrt（如需要，设置自定义路径）
find_library(ECRT_LIB
  NAMES ethercat ecrt
  PATHS /opt/etherlab/lib /usr/local/lib /usr/lib
)
if(NOT ECRT_LIB)
  message(FATAL_ERROR "ecrt not found; set CMAKE_PREFIX_PATH or system ld path.")
endif()

include_directories(include)

# 核心对象文件
add_library(ethercat_core_obj OBJECT
  src/motor_control.cpp
  src/ethercat_core.cpp
)

# 静态/共享库（任选其一）
add_library(ethercat_core STATIC $<TARGET_OBJECTS:ethercat_core_obj>)
target_link_libraries(ethercat_core ${ECRT_LIB} pthread)

# 节点
add_executable(ethercat_node src/ethercat_node.cpp)
target_link_libraries(ethercat_node ethercat_core)
ament_target_dependencies(ethercat_node rclcpp std_msgs sensor_msgs rcl_interfaces)

add_executable(ethercat_csp_test src/ethercat_csp_test.cpp)
ament_target_dependencies(ethercat_csp_test rclcpp std_msgs)
install(TARGETS ethercat_csp_test DESTINATION lib/${PROJECT_NAME})


install(TARGETS ethercat_node
  DESTINATION lib/${PROJECT_NAME})
install(DIRECTORY include/
  DESTINATION include)
# 测试程序
add_executable(ethercat_topic_test src/ethercat_topic_test.cpp)
ament_target_dependencies(ethercat_topic_test rclcpp std_msgs)

install(TARGETS ethercat_topic_test
  DESTINATION lib/${PROJECT_NAME})



# 创建一个手动触发的目标：为真实二进制设置 cap_sys_nice
add_custom_target(setcap_ethercat_node
  COMMAND ${CMAKE_COMMAND} -E echo "Setting cap_sys_nice on:"
  COMMAND ${CMAKE_COMMAND} -E echo "$<TARGET_FILE:ethercat_node>"
  COMMAND sudo setcap cap_sys_nice+ep $<TARGET_FILE:ethercat_node>
  COMMAND getcap $<TARGET_FILE:ethercat_node>
  DEPENDS ethercat_node
  VERBATIM
)

ament_package()
