can_frame.h 1.33 KB
#pragma once

#include "socket-cpp/platform.h"
#include <string>
#include <cstring>
//#include <sys/un.h>
#include <linux/can.h>

namespace osdev {
namespace components {
namespace socket-cpp {

/**
 * Class that represents a Linux SocketCAN frame.
 * This inherits from the Linux CAN frame struct, just providing easier
   construction.
 */
class can_frame : public ::can_frame
{
	using base = ::can_frame;

	/** The size of the underlying address struct, in bytes */
	static constexpr size_t SZ = sizeof(::can_frame);

public:
	/**
	 * Constructs an empty frame.
	 * The frame is initialized to all zeroes.
	 */
	can_frame() : base{} {}
	/**
	 * Constructs a frame with the specified ID and data.
	 * @param canID The CAN identifier for the frame
	 * @param data The data field for the frame
	 */
	can_frame(canid_t canID, const std::string& data)
		: can_frame{ canID, data.data(), data.length() } {}
	/**
	 * Constructs a frame with the specified ID and data.
	 * @param canID The CAN identifier for the frame
	 * @param data The data field for the frame
	 * @param n The number of bytes in the data field
	 */
	can_frame(canid_t canID, const void* data, size_t n) : base{} {
		this->can_id = canID;
		this->can_dlc = n;
		::memcpy(&this->data, data, n);
	}
};

}   // End namespace socket-cpp
}   // End namespace components
}   // End namespace osdev