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-bus.hpp"
27 #include <sys/ioctl.h>
28 #include <sys/socket.h>
29 #include <json-c/json.h>
30 #include <linux/can/raw.h>
32 #include "can-decoder.hpp"
33 #include "openxc-utils.hpp"
37 #include <afb/afb-binding.h>
40 /********************************************************************************
42 * can_bus_t method implementation
44 *********************************************************************************/
46 can_bus_t::can_bus_t(int& conf_file)
47 : conf_file_{conf_file}
51 void can_bus_t::can_decode_message()
53 can_message_t can_message;
54 std::vector <CanSignal> signals;
55 std::vector <CanSignal>::iterator signals_i;
56 openxc_VehicleMessage vehicle_message;
57 openxc_DynamicField search_key, decoded_message;
61 DEBUG(binder_interface, "Beginning of decoding thread.");
65 std::unique_lock<std::mutex> can_message_lock(can_message_mutex_);
66 new_can_message_.wait(can_message_lock);
67 can_message = next_can_message();
70 /* First we have to found which CanSignal it is */
71 search_key = build_DynamicField((double)can_message.get_id());
72 signals = find_can_signals(search_key);
74 /* Decoding the message ! Don't kill the messenger ! */
75 for(auto& sig : signals)
78 std::lock_guard<std::mutex> subscribed_signals_lock(get_subscribed_signals_mutex());
79 std::map<std::string, struct afb_event> subscribed_signals = get_subscribed_signals();
80 const auto& it_event = subscribed_signals.find(sig.genericName);
82 if(it_event != subscribed_signals.end() && afb_event_is_valid(it_event->second))
84 decoded_message = decoder.translateSignal(sig, can_message, getSignals());
86 openxc_SimpleMessage s_message = build_SimpleMessage(sig.genericName, decoded_message);
87 vehicle_message = build_VehicleMessage_with_SimpleMessage(openxc_DynamicField_Type::openxc_DynamicField_Type_NUM, s_message);
89 std::lock_guard<std::mutex> decoded_can_message_lock(decoded_can_message_mutex_);
90 push_new_vehicle_message(vehicle_message);
92 new_decoded_can_message_.notify_one();
98 void can_bus_t::can_event_push()
100 openxc_VehicleMessage v_message;
101 openxc_SimpleMessage s_message;
104 DEBUG(binder_interface, "Beginning of the pushing thread");
108 std::unique_lock<std::mutex> decoded_can_message_lock(decoded_can_message_mutex_);
109 new_decoded_can_message_.wait(decoded_can_message_lock);
110 v_message = next_vehicle_message();
113 s_message = get_simple_message(v_message);
116 std::lock_guard<std::mutex> subscribed_signals_lock(get_subscribed_signals_mutex());
117 std::map<std::string, struct afb_event> subscribed_signals = get_subscribed_signals();
118 const auto& it_event = subscribed_signals.find(s_message.name);
119 if(it_event != subscribed_signals.end() && afb_event_is_valid(it_event->second))
121 jo = json_object_new_object();
122 jsonify_simple(s_message, jo);
123 afb_event_push(it_event->second, jo);
129 void can_bus_t::start_threads()
131 th_decoding_ = std::thread(&can_bus_t::can_decode_message, this);
133 th_pushing_ = std::thread(&can_bus_t::can_event_push, this);
137 void can_bus_t::stop_threads()
139 is_decoding_ = false;
145 bool can_bus_t::is_decoding()
150 bool can_bus_t::is_pushing()
155 int can_bus_t::init_can_dev()
157 std::vector<std::string> devices_name;
161 devices_name = read_conf();
163 if (! devices_name.empty())
165 t = devices_name.size();
168 for(const auto& device : devices_name)
170 can_bus_dev_t can_bus_device_handler(device);
171 if (can_bus_device_handler.open() == 0)
174 DEBUG(binder_interface, "Start reading thread");
175 can_bus_device_handler.start_reading(*this);
178 ERROR(binder_interface, "Can't open device %s", device.c_str());
181 NOTICE(binder_interface, "Initialized %d/%d can bus device(s)", i, t);
184 ERROR(binder_interface, "init_can_dev: Error at CAN device initialization. No devices read from configuration file. Did you specify canbus JSON object ?");
188 std::vector<std::string> can_bus_t::read_conf()
190 std::vector<std::string> ret;
191 json_object *jo, *canbus;
195 FILE *fd = fdopen(conf_file_, "r");
198 std::string fd_conf_content;
199 std::fseek(fd, 0, SEEK_END);
200 fd_conf_content.resize(std::ftell(fd));
202 std::fread(&fd_conf_content[0], 1, fd_conf_content.size(), fd);
205 DEBUG(binder_interface, "Configuration file content : %s", fd_conf_content.c_str());
206 jo = json_tokener_parse(fd_conf_content.c_str());
208 if (jo == NULL || !json_object_object_get_ex(jo, "canbus", &canbus))
210 ERROR(binder_interface, "Can't find canbus node in the configuration file. Please review it.");
213 else if (json_object_get_type(canbus) != json_type_array)
215 taxi = json_object_get_string(canbus);
216 DEBUG(binder_interface, "Can bus found: %s", taxi);
217 ret.push_back(std::string(taxi));
221 n = json_object_array_length(canbus);
222 for (i = 0 ; i < n ; i++)
223 ret.push_back(json_object_get_string(json_object_array_get_idx(canbus, i)));
227 ERROR(binder_interface, "Problem at reading the conf file");
232 std::condition_variable& can_bus_t::get_new_can_message()
234 return new_can_message_;
237 std::mutex& can_bus_t::get_can_message_mutex()
239 return can_message_mutex_;
242 can_message_t can_bus_t::next_can_message()
244 can_message_t can_msg;
246 if(!can_message_q_.empty())
248 can_msg = can_message_q_.front();
249 can_message_q_.pop();
250 DEBUG(binder_interface, "next_can_message: Here is the next can message : id %d, length %d", can_msg.get_id(), can_msg.get_length());
254 NOTICE(binder_interface, "next_can_message: End of can message queue");
255 has_can_message_ = false;
259 void can_bus_t::push_new_can_message(const can_message_t& can_msg)
261 can_message_q_.push(can_msg);
264 openxc_VehicleMessage can_bus_t::next_vehicle_message()
266 openxc_VehicleMessage v_msg;
268 if(! vehicle_message_q_.empty())
270 v_msg = vehicle_message_q_.front();
271 vehicle_message_q_.pop();
272 DEBUG(binder_interface, "next_vehicle_message: next vehicle message poped");
276 NOTICE(binder_interface, "next_vehicle_message: End of vehicle message queue");
277 has_vehicle_message_ = false;
281 void can_bus_t::push_new_vehicle_message(const openxc_VehicleMessage& v_msg)
283 vehicle_message_q_.push(v_msg);
284 has_vehicle_message_ = true;
287 /********************************************************************************
289 * can_bus_dev_t method implementation
291 *********************************************************************************/
293 can_bus_dev_t::can_bus_dev_t(const std::string &dev_name)
294 : device_name_{dev_name}, can_socket_{-1}
298 int can_bus_dev_t::open()
300 const int canfd_on = 1;
301 const int timestamp_on = 1;
303 struct timeval timeout;
305 DEBUG(binder_interface, "CAN Handler socket : %d", can_socket_);
306 if (can_socket_ >= 0)
309 can_socket_ = ::socket(PF_CAN, SOCK_RAW, CAN_RAW);
310 DEBUG(binder_interface, "CAN Handler socket correctly initialized : %d", can_socket_);
312 ERROR(binder_interface, "socket could not be created. Error was : %s", ::strerror(errno));
315 /* Set timeout for read */
316 ::setsockopt(can_socket_, SOL_SOCKET, SO_RCVTIMEO, (char *)&timeout, sizeof(timeout));
317 /* Set timestamp for receveid frame */
318 if (::setsockopt(can_socket_, SOL_SOCKET, SO_TIMESTAMP, ×tamp_on, sizeof(timestamp_on)) < 0)
319 WARNING(binder_interface, "setsockopt SO_TIMESTAMP error: %s", ::strerror(errno));
320 DEBUG(binder_interface, "Switch CAN Handler socket to use fd mode");
321 /* try to switch the socket into CAN_FD mode */
322 if (::setsockopt(can_socket_, SOL_CAN_RAW, CAN_RAW_FD_FRAMES, &canfd_on, sizeof(canfd_on)) < 0)
324 NOTICE(binder_interface, "Can not switch into CAN Extended frame format.");
325 is_fdmode_on_ = false;
327 DEBUG(binder_interface, "Correctly set up CAN socket to use FD frames.");
328 is_fdmode_on_ = true;
331 /* Attempts to open a socket to CAN bus */
332 ::strcpy(ifr.ifr_name, device_name_.c_str());
333 DEBUG(binder_interface, "ifr_name is : %s", ifr.ifr_name);
334 if(::ioctl(can_socket_, SIOCGIFINDEX, &ifr) < 0)
335 ERROR(binder_interface, "ioctl failed. Error was : %s", strerror(errno));
338 txAddress_.can_family = AF_CAN;
339 txAddress_.can_ifindex = ifr.ifr_ifindex;
341 /* And bind it to txAddress */
342 DEBUG(binder_interface, "Bind the socket");
343 if (::bind(can_socket_, (struct sockaddr *)&txAddress_, sizeof(txAddress_)) < 0)
344 ERROR(binder_interface, "Bind failed. %s", strerror(errno));
353 int can_bus_dev_t::close()
355 ::close(can_socket_);
360 canfd_frame can_bus_dev_t::read()
364 canfd_frame canfd_frame;
366 /* Test that socket is really opened */
369 ERROR(binder_interface, "read_can: Socket unavailable. Closing thread.");
373 nbytes = ::read(can_socket_, &canfd_frame, CANFD_MTU);
378 DEBUG(binder_interface, "read_can: Got an CAN FD frame with length %d", canfd_frame.len);
379 //maxdlen = CANFD_MAX_DLEN;
382 DEBUG(binder_interface, "read_can: Got a legacy CAN frame with length %d", canfd_frame.len);
383 //maxdlen = CAN_MAX_DLEN;
386 if (errno == ENETDOWN)
387 ERROR(binder_interface, "read_can: %s binder_interface down", device_name_);
388 ERROR(binder_interface, "read_can: Error reading CAN bus");
389 ::memset(&canfd_frame, 0, sizeof(canfd_frame));
397 bool can_bus_dev_t::is_running()
402 void can_bus_dev_t::start_reading(can_bus_t& can_bus)
404 DEBUG(binder_interface, "Launching reading thread");
405 th_reading_ = std::thread(&can_bus_dev_t::can_reader, this, std::ref(can_bus));
409 void can_bus_dev_t::stop_reading()
415 void can_bus_dev_t::can_reader(can_bus_t& can_bus)
417 can_message_t can_message;
419 DEBUG(binder_interface, "Beginning of reading thread");
422 can_message.convert_from_canfd_frame(read());
425 std::lock_guard<std::mutex> can_message_lock(can_bus.get_can_message_mutex());
426 can_bus.push_new_can_message(can_message);
428 can_bus.get_new_can_message().notify_one();
432 int can_bus_dev_t::send_can_message(can_message_t& can_msg)
437 f = can_msg.convert_to_canfd_frame();
441 nbytes = ::sendto(can_socket_, &f, sizeof(struct canfd_frame), 0,
442 (struct sockaddr*)&txAddress_, sizeof(txAddress_));
445 ERROR(binder_interface, "send_can_message: Sending CAN frame failed.");
452 ERROR(binder_interface, "send_can_message: socket not initialized. Attempt to reopen can device socket.");