can_socket.cpp 1.13 KB
#include "socket-cpp/can_socket.h"
#include "socket-cpp/socket.h"
#include <sys/ioctl.h>

using namespace std;
using namespace std::chrono;
using namespace osdev::components::socket-cpp;

can_socket::can_socket(const can_address& addr)
{
	socket_t socketHandle = create_handle( SOCK_RAW, CAN_RAW );

	if ( check_socket_bool( socketHandle ) ) 
    {
		reset( socketHandle );
		bind( addr );
	}
}

system_clock::time_point can_socket::last_frame_time()
{
	timeval tv {};

	// TODO: Handle error
	::ioctl(handle(), SIOCGSTAMP, &tv);
	return to_timepoint(tv);
}

double can_socket::last_frame_timestamp()
{
	timeval tv {};

	// TODO: Handle error
	::ioctl(handle(), SIOCGSTAMP, &tv);
	return double(tv.tv_sec) + 1.0e-6 * tv.tv_usec;
}


// --------------------------------------------------------------------------

ssize_t can_socket::recv_from(can_frame *frame, int flags,
							  can_address* srcAddr /*=nullptr*/)
{
	sockaddr* p = srcAddr ? srcAddr->sockaddr_ptr() : nullptr;
    socklen_t len = srcAddr ? srcAddr->size() : 0;

	// TODO: Check returned length
	return check_ret(::recvfrom(handle(), frame, sizeof(can_frame),
								flags, p, &len));
}