diff --git a/include/socketcan_adapter/socketcan_adapter.hpp b/include/socketcan_adapter/socketcan_adapter.hpp index 62ced76..aea13b3 100644 --- a/include/socketcan_adapter/socketcan_adapter.hpp +++ b/include/socketcan_adapter/socketcan_adapter.hpp @@ -156,6 +156,11 @@ class SocketcanAdapter : public std::enable_shared_from_this /// @return optional error string filled with an error message if any std::optional send(const std::shared_ptr frame); + /// @brief Transmit a can frame via socket + /// @param frame Linux CAN frame to send + /// @return optional error string filled with an error message if any + std::optional send(const can_frame & frame); + /// @brief Set receive timeout /// @param reecive_timeout_s std::chrono::duration sets receive timeout in seconds void set_receive_timeout(const std::chrono::duration & recive_timeout_s); diff --git a/src/socketcan_adapter.cpp b/src/socketcan_adapter.cpp index cfffb7f..b7608d8 100644 --- a/src/socketcan_adapter.cpp +++ b/src/socketcan_adapter.cpp @@ -25,6 +25,7 @@ #include #include +#include #include #include #include @@ -226,6 +227,11 @@ std::optional SocketcanAdapter::send( : std::nullopt; } +std::optional SocketcanAdapter::send(const can_frame & frame) +{ + return send(polymath::socketcan::CanFrame(frame)); +} + std::optional SocketcanAdapter::sendFilters() { socket_error_string_t error_output(""); @@ -326,20 +332,15 @@ bool SocketcanAdapter::joinReceptionThread(const std::chrono::duration & { stop_thread_requested_ = true; - auto start_time = std::chrono::steady_clock::now(); - // Check thread running to tell when to join the thread - while (thread_running_ && ((std::chrono::steady_clock::now() - start_time) < timeout_s)) { - std::this_thread::sleep_for(std::chrono::milliseconds(100)); - } - - // Attempt to force joining at this point - if (can_receive_thread_.joinable()) { - can_receive_thread_.join(); - return true; - } else { - return false; + // Use std::async to wait asynchronously for the thread to stop + std::future join_future = std::async(std::launch::async, [this] { can_receive_thread_.join(); }); + + // Wait for the thread to stop within the timeout period + return join_future.wait_for(timeout_s) == std::future_status::ready; } + + return false; } std::string SocketcanAdapter::get_interface()