2 * Copyright (C) 2015, 2016 "IoT.bzh"
3 * Author "Romain Forlot" <romain.forlot@iot.bzh>
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
9 * http://www.apache.org/licenses/LICENSE-2.0
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
18 #include "can-utils.hpp"
27 #include <sys/ioctl.h>
28 #include <sys/socket.h>
29 #include <json-c/json.h>
30 #include <linux/can/raw.h>
31 #include <systemd/sd-event.h>
35 #include <afb/afb-binding.h>
38 /********************************************************************************
40 * CanMessage method implementation
42 *********************************************************************************/
44 can_message_t::can_message_t()
45 : id_{0}, length_{0}, format_{CanMessageFormat::ERROR}, data_{0,0,0,0,0,0,0,0}
48 uint32_t can_message_t::get_id() const
53 int can_message_t::get_format() const
55 if (format_ != CanMessageFormat::STANDARD || format_ != CanMessageFormat::EXTENDED)
56 return CanMessageFormat::ERROR;
60 const uint8_t* can_message_t::get_data() const
64 uint8_t can_message_t::get_length() const
69 bool can_message_t::is_correct_to_send()
71 if (id_ != 0 && length_ != 0 && format_ != CanMessageFormat::ERROR)
74 for(i=0;i<CAN_MESSAGE_SIZE;i++)
81 void can_message_t::set_id(const uint32_t new_id)
85 case CanMessageFormat::STANDARD:
86 id_ = new_id & CAN_SFF_MASK;
88 case CanMessageFormat::EXTENDED:
89 id_ = new_id & CAN_EFF_MASK;
92 ERROR(binder_interface, "ERROR: Can set id, not a compatible format or format not set prior to set id.");
97 void can_message_t::set_format(const CanMessageFormat new_format)
99 if(new_format == CanMessageFormat::STANDARD || new_format == CanMessageFormat::EXTENDED)
100 format_ = new_format;
102 ERROR(binder_interface, "ERROR: Can set format, wrong format chosen");
105 void can_message_t::set_data(const uint8_t new_data)
107 if ((sizeof(new_data) / sizeof(uint8_t) > CAN_MESSAGE_SIZE))
108 ERROR(binder_interface, "Can set data, your data array is too big");
111 ::memcpy(&data_, &new_data, sizeof(new_data));
112 length_ = sizeof(new_data);
116 void can_message_t::convert_from_canfd_frame(const canfd_frame& frame)
118 length_ = (frame.len > CAN_MAX_DLEN) ? (uint8_t)CAN_MAX_DLEN : frame.len;
119 length_ = (frame.len > CANFD_MAX_DLEN) ? (uint8_t)CANFD_MAX_DLEN : frame.len;
121 if (frame.can_id & CAN_ERR_FLAG)
123 id_ = frame.can_id & (CAN_ERR_MASK|CAN_ERR_FLAG);
124 format_ = CanMessageFormat::ERROR;
126 else if (frame.can_id & CAN_EFF_FLAG)
128 id_ = frame.can_id & CAN_EFF_MASK;
129 format_ = CanMessageFormat::EXTENDED;
133 id_ = frame.can_id & CAN_SFF_MASK;
134 format_ = CanMessageFormat::STANDARD;
137 if (sizeof(frame.data) <= sizeof(data_))
138 ::memcpy(&data_, frame.data, length_);
139 else if (sizeof(frame.data) >= CAN_MAX_DLEN)
140 ERROR(binder_interface, "can_message_t: canfd_frame data too long to be stored into CanMessage object");
143 canfd_frame can_message_t::convert_to_canfd_frame()
147 if(is_correct_to_send())
149 frame.can_id = get_id();
150 frame.len = get_length();
151 ::memcpy(frame.data, get_data(), length_);
154 ERROR(binder_interface, "can_message_t not correctly initialized to be sent");
159 /********************************************************************************
161 * can_bus_t method implementation
163 *********************************************************************************/
165 can_bus_t::can_bus_t(int& conf_file)
166 : conf_file_{conf_file}
170 void can_bus_t::start_threads()
172 th_decoding_ = std::thread(can_decode_message, std::ref(*this));
173 th_pushing_ = std::thread(can_event_push, std::ref(*this));
177 int can_bus_t::init_can_dev()
179 std::vector<std::string> devices_name;
183 devices_name = read_conf();
185 if (! devices_name.empty())
187 t = devices_name.size();
190 std::lock_guard<std::mutex> can_frame_lock(can_frame_mutex);
191 for(const auto& device : devices_name)
193 can_bus_dev_t can_bus_device_handler(device);
194 (can_bus_device_handler.open()) ? i++ : ERROR(binder_interface, "Can't open device %s", device);
195 can_bus_device_handler.start_reading(std::ref(*this));
197 can_frame_mutex.unlock();
199 NOTICE(binder_interface, "Initialized %d/%d can bus device(s)", i, t);
202 ERROR(binder_interface, "init_can_dev: Error at CAN device initialization. No devices read from configuration file. Did you specify canbus JSON object ?");
206 std::vector<std::string> can_bus_t::read_conf()
208 std::vector<std::string> ret;
209 json_object *jo, *canbus;
212 FILE *fd = fdopen(conf_file_, "r");
215 std::string fd_conf_content;
216 std::fseek(fd, 0, SEEK_END);
217 fd_conf_content.resize(std::ftell(fd));
219 std::fread(&fd_conf_content[0], 1, fd_conf_content.size(), fd);
222 jo = json_tokener_parse(fd_conf_content.c_str());
224 if (jo == NULL || !json_object_object_get_ex(jo, "canbus", &canbus))
226 ERROR(binder_interface, "Can't find canbus node in the configuration file. Please review it.");
229 else if (json_object_get_type(canbus) != json_type_array)
230 ret.push_back(json_object_get_string(canbus));
233 n = json_object_array_length(canbus);
234 for (i = 0 ; i < n ; i++)
235 ret.push_back(json_object_get_string(json_object_array_get_idx(canbus, i)));
239 ERROR(binder_interface, "Problem at reading the conf file");
244 can_message_t can_bus_t::next_can_message()
246 can_message_t can_msg;
248 if(!can_message_q_.empty())
250 can_msg = can_message_q_.front();
251 can_message_q_.pop();
252 DEBUG(binder_interface, "next_can_message: Here is the next can message : id %d, length %d", can_msg.get_id(), can_msg.get_length());
256 NOTICE(binder_interface, "next_can_message: End of can message queue");
257 has_can_message_ = false;
261 void can_bus_t::push_new_can_message(const can_message_t& can_msg)
263 can_message_q_.push(can_msg);
266 bool can_bus_t::has_can_message() const
268 return has_can_message_;
271 openxc_VehicleMessage can_bus_t::next_vehicle_message()
273 openxc_VehicleMessage v_msg;
275 if(! vehicle_message_q_.empty())
277 v_msg = vehicle_message_q_.front();
278 vehicle_message_q_.pop();
279 DEBUG(binder_interface, "next_vehicle_message: next vehicle message poped");
283 NOTICE(binder_interface, "next_vehicle_message: End of vehicle message queue");
284 has_vehicle_message_ = false;
288 void can_bus_t::push_new_vehicle_message(const openxc_VehicleMessage& v_msg)
290 vehicle_message_q_.push(v_msg);
291 has_vehicle_message_ = true;
294 bool can_bus_t::has_vehicle_message() const
296 return has_vehicle_message_;
299 /********************************************************************************
301 * This is the sd_event_add_io callback function declaration.
302 * Its implementation can be found into low-can-binding.cpp.
304 *********************************************************************************/
306 int can_frame_received(sd_event_source *s, int fd, uint32_t revents, void *userdata);
308 /********************************************************************************
310 * can_bus_dev_t method implementation
312 *********************************************************************************/
314 can_bus_dev_t::can_bus_dev_t(const std::string &dev_name)
315 : device_name_{dev_name}
319 int can_bus_dev_t::event_loop_connection()
321 sd_event_source *source;
324 /* adds to the event loop */
325 rc = sd_event_add_io(afb_daemon_get_event_loop(binder_interface->daemon), &source, can_socket_, EPOLLIN, can_frame_received, this);
328 ERROR(binder_interface, "Can't coonect CAN device %s to the event loop", device_name_);
330 NOTICE(binder_interface, "Connected to %s", device_name_);
335 int can_bus_dev_t::open()
337 const int canfd_on = 1;
339 struct timeval timeout = {1, 0};
341 DEBUG(binder_interface, "CAN Handler socket : %d", can_socket_);
342 if (can_socket_ >= 0)
345 can_socket_ = ::socket(PF_CAN, SOCK_RAW, CAN_RAW);
348 ERROR(binder_interface, "socket could not be created");
352 /* Set timeout for read */
353 ::setsockopt(can_socket_, SOL_SOCKET, SO_RCVTIMEO, (char *)&timeout, sizeof(timeout));
354 /* try to switch the socket into CAN_FD mode */
355 if (::setsockopt(can_socket_, SOL_CAN_RAW, CAN_RAW_FD_FRAMES, &canfd_on, sizeof(canfd_on)) < 0)
357 NOTICE(binder_interface, "Can not switch into CAN Extended frame format.");
358 is_fdmode_on_ = false;
360 is_fdmode_on_ = true;
363 /* Attempts to open a socket to CAN bus */
364 ::strcpy(ifr.ifr_name, device_name_.c_str());
365 if(::ioctl(can_socket_, SIOCGIFINDEX, &ifr) < 0)
366 ERROR(binder_interface, "ioctl failed");
369 txAddress_.can_family = AF_CAN;
370 txAddress_.can_ifindex = ifr.ifr_ifindex;
372 /* And bind it to txAddress */
373 if (::bind(can_socket_, (struct sockaddr *)&txAddress_, sizeof(txAddress_)) < 0)
375 ERROR(binder_interface, "Bind failed");
379 ::fcntl(can_socket_, F_SETFL, O_NONBLOCK);
388 int can_bus_dev_t::close()
390 ::close(can_socket_);
395 canfd_frame can_bus_dev_t::read()
399 canfd_frame canfd_frame;
401 /* Test that socket is really opened */
404 ERROR(binder_interface, "read_can: Socket unavailable. Closing thread.");
408 nbytes = ::read(can_socket_, &canfd_frame, CANFD_MTU);
413 DEBUG(binder_interface, "read_can: Got an CAN FD frame with length %d", canfd_frame.len);
414 //maxdlen = CANFD_MAX_DLEN;
417 DEBUG(binder_interface, "read_can: Got a legacy CAN frame with length %d", canfd_frame.len);
418 //maxdlen = CAN_MAX_DLEN;
421 if (errno == ENETDOWN)
422 ERROR(binder_interface, "read_can: %s binder_interface down", device_name_);
423 ERROR(binder_interface, "read_can: Error reading CAN bus");
424 ::memset(&canfd_frame, 0, sizeof(canfd_frame));
432 void can_bus_dev_t::start_reading(can_bus_t& can_bus)
434 th_reading_ = std::thread(can_reader, std::ref(*this), std::ref(can_bus));
439 * Return is_running_ bool
441 bool can_bus_dev_t::is_running()
446 int can_bus_dev_t::send_can_message(can_message_t& can_msg)
451 f = can_msg.convert_to_canfd_frame();
455 nbytes = ::sendto(can_socket_, &f, sizeof(struct canfd_frame), 0,
456 (struct sockaddr*)&txAddress_, sizeof(txAddress_));
459 ERROR(binder_interface, "send_can_message: Sending CAN frame failed.");
466 ERROR(binder_interface, "send_can_message: socket not initialized. Attempt to reopen can device socket.");