#include <latch>
#include <thread>
using namespace std::chrono_literals;
bool check_can_interfaces()
{
std::vector<std::string> interfaces = { "can0", "can1" };
std::string path =
"/sys/class/net/" +
interface;
fmt::println(
"CAN interface '{}' does not exist",
interface);
return false;
}
}
fmt::println("All required CAN interfaces (can0, can1) are available");
return true;
}
void sender_thread(std::latch& bus_active, std::latch& finished)
{
bus_active.arrive_and_wait();
fmt::println("Bus is not active for adapter {}", can0.name());
} else {
std::this_thread::sleep_for(100ms);
std::string msg = "hello";
can_msg_frame frame{ .can_id = 2552495936, .len = (uint8_t) msg.length() };
std::memcpy(frame.data, msg.data(), std::min(sizeof(frame.data), msg.length()));
if (
auto err = socket.
send(frame); err == std::errc{}) {
fmt::println("Sent {}", msg);
} else {
}
}
finished.count_down();
}
void receiver_thread(std::latch& bus_active, std::latch& finished)
{
bus_active.arrive_and_wait();
fmt::println("Bus is not active for adapter {}", can1.name());
} else {
if (
auto err = socket.
receive(frame, 200ms); err.
recv_err == std::errc{}) {
std::string received_msg{ (
char*) frame.data, (
char*) frame.data + frame.
len };
fmt::println("Received: {}", received_msg);
} else {
fmt::println("Failed to receive CAN frame: {}",
}
}
finished.count_down();
}
int main()
{
#ifdef __linux__
if (!check_can_interfaces()) {
fmt::println("Required CAN interfaces are not available");
return 1;
}
#endif
std::latch bus_active{ 2 };
std::latch finished{ 2 };
std::jthread sender(sender_thread, std::ref(bus_active), std::ref(finished));
std::jthread receiver(receiver_thread, std::ref(bus_active), std::ref(finished));
finished.wait();
fmt::println("Done");
}
The CAN interface setup class.
Definition can_adapter.h:48
Convenience wrapper class around a CAN socket.
Definition can_socket.h:22
std::errc bind(const can_adapter &adapter)
Open the socket and bind to an adapter.
receive_result receive(can_msg_frame &frame, std::chrono::milliseconds timeout=std::chrono::milliseconds::zero()) const
Receive a CAN frame.
std::errc send(const can_msg_frame &frame) const
Send a CAN frame.
Utilities for file manipulation.
constexpr uint32_t bitrate_125k
Common CAN bitrates.
Definition can_adapter_interface.h:27
@ error_active
RX/TX error count < 96.
Definition can_common.h:47
std::string errno_string(int err)
Wrapper for strerror that returns a std::string.
bool file_exists(const std::string &path)
Utility to check if a path exists. Same semantics as std::filesystem::exists, but won't do character ...
Definition file_utils.h:113
CAN frame structure.
Definition can_common.h:32
uint8_t len
Frame payload length.
Definition can_common.h:34
The interface struct.
Definition network_manager.h:46
std::errc recv_err
The error code for receving the CAN frame.
Definition can_socket_interface.h:27
syscall wrapper interface.