2 * Copyright (C) 2015, 2016, 2017 "IoT.bzh"
3 * Author "Romain Forlot" <romain.forlot@iot.bzh>
4 * Author "Loïc Collignon" <loic.collignon@iot.bzh>
6 * Licensed under the Apache License, Version 2.0 (the "License");
7 * you may not use this file except in compliance with the License.
8 * You may obtain a copy of the License at
10 * http://www.apache.org/licenses/LICENSE-2.0
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
20 #include <linux/can/raw.h>
22 #include <sys/ioctl.h>
24 #include "can-bus-dev.hpp"
25 #include "low-can-binding.hpp"
27 /// @brief Class constructor
28 /// @param dev_name String representing the device name into the linux /dev tree
29 can_bus_dev_t::can_bus_dev_t(const std::string& dev_name)
30 : device_name_{dev_name}
34 /// @brief Open the can socket and returning it
36 int can_bus_dev_t::open()
38 const int canfd_on = 1;
39 const int timestamp_on = 1;
41 struct timeval timeout;
43 DEBUG(binder_interface, "CAN Handler socket : %d", can_socket_.socket());
44 if (can_socket_) return 0;
46 can_socket_.open(PF_CAN, SOCK_RAW, CAN_RAW);
49 DEBUG(binder_interface, "CAN Handler socket correctly initialized : %d", can_socket_.socket());
51 // Set timeout for read
52 can_socket_.setopt(SOL_SOCKET, SO_RCVTIMEO, (char *)&timeout, sizeof(timeout));
54 // Set timestamp for receveid frame
55 if (can_socket_.setopt(SOL_SOCKET, SO_TIMESTAMP, ×tamp_on, sizeof(timestamp_on)) < 0)
56 WARNING(binder_interface, "setsockopt SO_TIMESTAMP error: %s", ::strerror(errno));
57 DEBUG(binder_interface, "Switch CAN Handler socket to use fd mode");
59 // try to switch the socket into CAN_FD mode
60 if (can_socket_.setopt(SOL_CAN_RAW, CAN_RAW_FD_FRAMES, &canfd_on, sizeof(canfd_on)) < 0)
62 NOTICE(binder_interface, "Can not switch into CAN Extended frame format.");
63 is_fdmode_on_ = false;
67 DEBUG(binder_interface, "Correctly set up CAN socket to use FD frames.");
71 // Attempts to open a socket to CAN bus
72 ::strcpy(ifr.ifr_name, device_name_.c_str());
73 DEBUG(binder_interface, "ifr_name is : %s", ifr.ifr_name);
74 if(::ioctl(can_socket_.socket(), SIOCGIFINDEX, &ifr) < 0)
75 ERROR(binder_interface, "ioctl failed. Error was : %s", strerror(errno));
78 txAddress_.can_family = AF_CAN;
79 txAddress_.can_ifindex = ifr.ifr_ifindex;
81 // And bind it to txAddress
82 DEBUG(binder_interface, "Bind the socket");
83 if (::bind(can_socket_.socket(), (struct sockaddr *)&txAddress_, sizeof(txAddress_)) < 0)
84 ERROR(binder_interface, "Bind failed. %s", strerror(errno));
90 else ERROR(binder_interface, "socket could not be created. Error was : %s", ::strerror(errno));