#include <net/if.h>
#include <sys/ioctl.h>
+#include <fcntl.h>
+
+#include "../binding/application.hpp"
namespace utils
{
- /// @brief Construct a default, invalid, socket.
- socketcan_bcm_t::socketcan_bcm_t()
- : socketcan_t{}
- {}
-
- /// @brief Destruct the socket.
- socketcan_bcm_t::~socketcan_bcm_t()
- {}
-
/// @brief Connect the socket.
/// @return 0 if success.
int socketcan_bcm_t::connect(const struct sockaddr* addr, socklen_t len)
// Attempts to open a socket to CAN bus
::strcpy(ifr.ifr_name, device_name.c_str());
- DEBUG(binder_interface, "%s: ifr_name is : %s", __FUNCTION__, ifr.ifr_name);
+ DEBUG("BCM socket ifr_name is : %s", ifr.ifr_name);
if(::ioctl(socket_, SIOCGIFINDEX, &ifr) < 0)
{
- ERROR(binder_interface, "%s: ioctl failed. Error was : %s", __FUNCTION__, strerror(errno));
+ ERROR("ioctl failed. Error was : %s", strerror(errno));
close();
}
else
if(connect((struct sockaddr *)&tx_address_, sizeof(tx_address_)) < 0)
{
- ERROR(binder_interface, "%s: Connect failed. %s", __FUNCTION__, strerror(errno));
+ ERROR("Connect failed. %s", strerror(errno));
close();
}
+ // Needed because of using systemD event loop. See sd_event_add_io manual.
+ fcntl(socketcan_t::socket_, F_SETFL, O_NONBLOCK);
}
return socket_;
}
+
+ /// Read the socket to retrieve the associated CAN message. All the hard work is do into
+ /// convert_from_frame method and if there isn't CAN message retrieve, only BCM head struct,
+ /// then CAN message will be zeroed and must be handled later.
+ socketcan_bcm_t& operator>>(socketcan_bcm_t& s, can_message_t& cm)
+ {
+ struct utils::simple_bcm_msg msg;
+
+ ::memset(&msg, 0, sizeof(msg));
+ const struct sockaddr_can& addr = s.get_tx_address();
+ socklen_t addrlen = sizeof(addr);
+ struct ifreq ifr;
+
+ ssize_t nbytes = ::recvfrom(s.socket(), &msg, sizeof(msg), 0, (struct sockaddr*)&addr, &addrlen);
+ ifr.ifr_ifindex = addr.can_ifindex;
+ ioctl(s.socket(), SIOCGIFNAME, &ifr);
+ long unsigned int frame_size = nbytes-sizeof(struct bcm_msg_head);
+
+ DEBUG("Data available: %li bytes read. BCM head, opcode: %i, can_id: %i, nframes: %i", frame_size, msg.msg_head.opcode, msg.msg_head.can_id, msg.msg_head.nframes);
+ DEBUG("read: Found on bus %s:\n id: %X, length: %X, data %02X%02X%02X%02X%02X%02X%02X%02X", ifr.ifr_name, msg.msg_head.can_id, msg.frames.can_dlc,
+ msg.frames.data[0], msg.frames.data[1], msg.frames.data[2], msg.frames.data[3], msg.frames.data[4], msg.frames.data[5], msg.frames.data[6], msg.frames.data[7]);
+
+ struct timeval tv;
+ ioctl(s.socket(), SIOCGSTAMP, &tv);
+ uint64_t timestamp = 1000000 * tv.tv_sec + tv.tv_usec;
+ cm = ::can_message_t::convert_from_frame(msg.frames ,
+ frame_size,
+ timestamp);
+ cm.set_sub_id((int)s.socket());
+
+ return s;
+ }
}
\ No newline at end of file