034e0ac95d15acafe93ea25c48876c1bf693cb41
[apps/agl-service-can-low-level.git] / src / can / can-bus.cpp
1 /*
2  * Copyright (C) 2015, 2016 "IoT.bzh"
3  * Author "Romain Forlot" <romain.forlot@iot.bzh>
4  *
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
8  *
9  *       http://www.apache.org/licenses/LICENSE-2.0
10  *
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.
16  */
17
18 #include "can/can-bus.hpp"
19
20 #include <map>
21 #include <cerrno>
22 #include <vector>
23 #include <string>
24 #include <fcntl.h>
25 #include <unistd.h>
26 #include <net/if.h>
27 #include <sys/ioctl.h>
28 #include <sys/socket.h>
29 #include <json-c/json.h>
30 #include <linux/can/raw.h>
31
32 #include "can/can-decoder.hpp"
33 #include "utils/openxc-utils.hpp"
34 #include "obd2/diagnostic-manager.hpp"
35
36 extern "C"
37 {
38         #include <afb/afb-binding.h>
39 }
40
41 /********************************************************************************
42 *
43 *               can_bus_t method implementation
44 *
45 *********************************************************************************/
46 /**
47 * @brief Class constructor
48 *
49 * @param struct afb_binding_interface *interface between daemon and binding
50 * @param int file handle to the json configuration file.
51 */
52 can_bus_t::can_bus_t(int conf_file)
53         : conf_file_{conf_file}
54 {
55 }
56
57 /**
58 * @brief thread to decoding raw CAN messages. 
59 *
60 * @desc It will take from the can_message_q_ queue the next can message to process then it will search 
61 *  about signal subscribed if there is a valid afb_event for it. We only decode signal for which a 
62 *  subscription has been made. Can message will be decoded using translateSignal that will pass it to the
63 *  corresponding decoding function if there is one assigned for that signal. If not, it will be the default
64 *  noopDecoder function that will operate on it.
65 */
66 void can_bus_t::can_decode_message()
67 {
68         can_message_t can_message;
69         std::vector <CanSignal*> signals;
70         openxc_VehicleMessage vehicle_message;
71         openxc_DynamicField search_key, decoded_message;
72
73         decoder_t decoder;
74
75         while(is_decoding_)
76         {
77                 std::unique_lock<std::mutex> can_message_lock(can_message_mutex_);
78                 new_can_message_cv_.wait(can_message_lock);
79                 can_message = next_can_message();
80         
81                 /* First we have to found which CanSignal it is */
82                 search_key = build_DynamicField((double)can_message.get_id());
83                 signals.clear();
84                 find_can_signals(search_key, signals);
85
86                 /* Decoding the message ! Don't kill the messenger ! */
87                 for(auto& sig : signals)
88                 {
89                         std::lock_guard<std::mutex> subscribed_signals_lock(get_subscribed_signals_mutex());
90                         std::map<std::string, struct afb_event>& s = get_subscribed_signals();
91                         
92                         /* DEBUG message to make easier debugger STL containers...
93                         DEBUG(binder_interface, "Operator[] key char: %s, event valid? %d", sig.generic_name, afb_event_is_valid(s[sig.generic_name]));
94                         DEBUG(binder_interface, "Operator[] key string: %s, event valid? %d", sig.generic_name, afb_event_is_valid(s[std::string(sig.generic_name)]));
95                         DEBUG(binder_interface, "Nb elt matched char: %d", (int)s.count(sig.generic_name));
96                         DEBUG(binder_interface, "Nb elt matched string: %d", (int)s.count(std::string(sig.generic_name))); */
97                         if( s.find(sig->generic_name) != s.end() && afb_event_is_valid(s[sig->generic_name]))
98                         {
99                                 decoded_message = decoder.translateSignal(*sig, can_message, get_can_signals());
100
101                                 openxc_SimpleMessage s_message = build_SimpleMessage(sig->generic_name, decoded_message);
102                                 vehicle_message = build_VehicleMessage_with_SimpleMessage(openxc_DynamicField_Type::openxc_DynamicField_Type_NUM, s_message);
103
104                                 std::lock_guard<std::mutex> decoded_can_message_lock(decoded_can_message_mutex_);
105                                 push_new_vehicle_message(vehicle_message);
106                                 new_decoded_can_message_.notify_one();
107                         }
108                 }
109         }
110 }
111
112 /**
113 * @brief thread to push events to suscribers. It will read subscribed_signals map to look 
114 * which are events that has to be pushed.
115 */
116 void can_bus_t::can_event_push()
117 {
118         openxc_VehicleMessage v_message;
119         openxc_SimpleMessage s_message;
120         json_object* jo;
121         
122         while(is_pushing_)
123         {
124                 std::unique_lock<std::mutex> decoded_can_message_lock(decoded_can_message_mutex_);
125                 new_decoded_can_message_.wait(decoded_can_message_lock);
126                 v_message = next_vehicle_message();
127
128                 s_message = get_simple_message(v_message);
129                 {
130                         std::lock_guard<std::mutex> subscribed_signals_lock(get_subscribed_signals_mutex());
131                         std::map<std::string, struct afb_event>& s = get_subscribed_signals();
132                         if(s.find(std::string(s_message.name)) != s.end() && afb_event_is_valid(s[std::string(s_message.name)]))
133                         {
134                                 jo = json_object_new_object();
135                                 jsonify_simple(s_message, jo);
136                                 afb_event_push(s[std::string(s_message.name)], jo);
137                         }
138                 }
139         }
140 }
141
142 /**
143         * @brief Will initialize threads that will decode
144         *  and push subscribed events.
145         */
146 void can_bus_t::start_threads()
147 {
148         is_decoding_ = true;
149         th_decoding_ = std::thread(&can_bus_t::can_decode_message, this);
150         if(!th_decoding_.joinable())
151                 is_decoding_ = false;
152         
153         is_pushing_ = true;
154         th_pushing_ = std::thread(&can_bus_t::can_event_push, this);
155         if(!th_pushing_.joinable())
156                 is_pushing_ = false;
157 }
158
159 /**
160 * @brief Will stop all threads holded by can_bus_t object
161 *  which are decoding and pushing then will wait that's 
162 * they'll finish their job.
163 */
164 void can_bus_t::stop_threads()
165 {
166         is_decoding_ = false;
167         is_pushing_ = false;
168 }
169
170 /**
171 * @brief Will initialize can_bus_dev_t objects after reading 
172 * the configuration file passed in the constructor.
173 */
174 int can_bus_t::init_can_dev()
175 {
176         std::vector<std::string> devices_name;
177         int i;
178         size_t t;
179
180         devices_name = read_conf();
181
182         if (! devices_name.empty())
183         {
184                 t = devices_name.size();
185                 i=0;
186
187                 for(const auto& device : devices_name)
188                 {
189                         can_devices_m_[device] = std::make_shared<can_bus_dev_t>(device);
190                         if (can_devices_m_[device]->open() == 0)
191                         {
192                                 i++;
193                                 DEBUG(binder_interface, "Start reading thread");
194                                 NOTICE(binder_interface, "%s device opened and reading", device.c_str());
195                                 can_devices_m_[device]->start_reading(*this);
196                         }
197                         else
198                                 ERROR(binder_interface, "Can't open device %s", device.c_str());
199                 }
200
201                 NOTICE(binder_interface, "Initialized %d/%d can bus device(s)", i, t);
202                 return 0;
203         }
204         ERROR(binder_interface, "init_can_dev: Error at CAN device initialization. No devices read from configuration file. Did you specify canbus JSON object ?");
205         return 1;
206 }
207
208 /**
209 * @brief read the conf_file_ and will parse json objects
210 * in it searching for canbus objects devices name.
211 *
212 * @return Vector of can bus device name string.
213 */
214 std::vector<std::string> can_bus_t::read_conf()
215 {
216         std::vector<std::string> ret;
217         json_object *jo, *canbus;
218         int n, i;
219         const char* taxi;
220
221         FILE *fd = fdopen(conf_file_, "r");
222         if (fd)
223         {
224                 std::string fd_conf_content;
225                 std::fseek(fd, 0, SEEK_END);
226                 fd_conf_content.resize(std::ftell(fd));
227                 std::rewind(fd);
228                 std::fread(&fd_conf_content[0], 1, fd_conf_content.size(), fd);
229                 std::fclose(fd);
230
231                 DEBUG(binder_interface, "Configuration file content : %s", fd_conf_content.c_str());
232                 jo = json_tokener_parse(fd_conf_content.c_str());
233
234                 if (jo == NULL || !json_object_object_get_ex(jo, "canbus", &canbus))
235                 {/**
236 * @brief Telling if the pushing thread is running
237 *  This is the boolean value on which the while loop
238 *  take its condition. Set it to false will stop the 
239 *  according thread.
240 *
241 * @return true if pushing thread is running, false if not.
242 */
243
244                         ERROR(binder_interface, "Can't find canbus node in the configuration file. Please review it.");
245                         ret.clear();
246                 }
247                 else if (json_object_get_type(canbus) != json_type_array)
248                 {
249                         taxi = json_object_get_string(canbus);
250                         DEBUG(binder_interface, "Can bus found: %s", taxi);
251                         ret.push_back(std::string(taxi));
252                 }
253                 else
254                 {
255                         n = json_object_array_length(canbus);
256                         for (i = 0 ; i < n ; i++)
257                                 ret.push_back(json_object_get_string(json_object_array_get_idx(canbus, i)));
258                 }
259                 return ret;
260         }
261         ERROR(binder_interface, "Problem at reading the conf file");
262         ret.clear();
263         return ret;
264 }
265
266 /**
267 * @brief return new_can_message_cv_ member
268 *
269 * @return  return new_can_message_cv_ member
270 */
271 std::condition_variable& can_bus_t::get_new_can_message_cv()
272 {
273         return new_can_message_cv_;
274 }
275
276 /**
277 * @brief return can_message_mutex_ member
278 *
279 * @return  return can_message_mutex_ member
280 */
281 std::mutex& can_bus_t::get_can_message_mutex()
282 {
283         return can_message_mutex_;
284 }
285
286 /**
287 * @brief Return first can_message_t on the queue 
288 *
289 * @return a can_message_t 
290 */
291 can_message_t can_bus_t::next_can_message()
292 {
293         can_message_t can_msg;
294
295         if(!can_message_q_.empty())
296         {
297                 can_msg = can_message_q_.front();
298                 can_message_q_.pop();
299                 DEBUG(binder_interface, "next_can_message: Here is the next can message : id %X, length %X, data %02X%02X%02X%02X%02X%02X%02X%02X", can_msg.get_id(), can_msg.get_length(),
300                         can_msg.get_data()[0], can_msg.get_data()[1], can_msg.get_data()[2], can_msg.get_data()[3], can_msg.get_data()[4], can_msg.get_data()[5], can_msg.get_data()[6], can_msg.get_data()[7]);
301                 return can_msg;
302         }
303         
304         return can_msg;
305 }
306
307 /**
308 * @brief Push a can_message_t into the queue
309 *
310 * @param the const reference can_message_t object to push into the queue
311 */
312 void can_bus_t::push_new_can_message(const can_message_t& can_msg)
313 {
314         can_message_q_.push(can_msg);
315 }
316
317 /**
318 * @brief Return first openxc_VehicleMessage on the queue 
319 *
320 * @return a openxc_VehicleMessage containing a decoded can message
321 */
322 openxc_VehicleMessage can_bus_t::next_vehicle_message()
323 {
324         openxc_VehicleMessage v_msg;
325
326         if(! vehicle_message_q_.empty())
327         {
328                 v_msg = vehicle_message_q_.front();
329                 vehicle_message_q_.pop();
330                 DEBUG(binder_interface, "next_vehicle_message: next vehicle message poped");
331                 return v_msg;
332         }
333         
334         return v_msg;
335 }
336
337 /**
338 * @brief Push a openxc_VehicleMessage into the queue
339 *
340 * @param the const reference openxc_VehicleMessage object to push into the queue
341 */
342 void can_bus_t::push_new_vehicle_message(const openxc_VehicleMessage& v_msg)
343 {
344         vehicle_message_q_.push(v_msg);
345 }
346
347 /**
348 * @brief Return a map with the can_bus_dev_t initialized
349 *
350 * @return map can_bus_dev_m_ map
351 */
352 std::map<std::string, std::shared_ptr<can_bus_dev_t>> can_bus_t::get_can_devices()
353 {
354         return can_devices_m_;
355 }
356
357 /********************************************************************************
358 *
359 *               can_bus_dev_t method implementation
360 *
361 *********************************************************************************/
362 /**
363 * @brief Class constructor 
364 *
365 * @param const string representing the device name into the linux /dev tree
366 */
367 can_bus_dev_t::can_bus_dev_t(const std::string& dev_name)
368         : device_name_{dev_name}, can_socket_{-1}, diagnostic_manager_{diagnostic_manager_t(*this)}
369 {}
370
371 /**
372 * @brief Open the can socket and returning it 
373 *
374 * @return 
375 */
376 int can_bus_dev_t::open()
377 {
378         const int canfd_on = 1;
379         const int timestamp_on = 1;
380         struct ifreq ifr;
381         struct timeval timeout;
382
383         DEBUG(binder_interface, "CAN Handler socket : %d", can_socket_);
384         if (can_socket_ >= 0)
385                 return 0;
386
387         can_socket_ = ::socket(PF_CAN, SOCK_RAW, CAN_RAW);
388         DEBUG(binder_interface, "CAN Handler socket correctly initialized : %d", can_socket_);
389         if (can_socket_ < 0)
390                 ERROR(binder_interface, "socket could not be created. Error was : %s", ::strerror(errno));
391         else
392         {
393                 /* Set timeout for read */
394                 ::setsockopt(can_socket_, SOL_SOCKET, SO_RCVTIMEO, (char *)&timeout, sizeof(timeout));
395                 /* Set timestamp for receveid frame */
396                 if (::setsockopt(can_socket_, SOL_SOCKET, SO_TIMESTAMP, &timestamp_on, sizeof(timestamp_on)) < 0)
397                         WARNING(binder_interface, "setsockopt SO_TIMESTAMP error: %s", ::strerror(errno));
398                 DEBUG(binder_interface, "Switch CAN Handler socket to use fd mode");
399                 /* try to switch the socket into CAN_FD mode */
400                 if (::setsockopt(can_socket_, SOL_CAN_RAW, CAN_RAW_FD_FRAMES, &canfd_on, sizeof(canfd_on)) < 0)
401                 {
402                         NOTICE(binder_interface, "Can not switch into CAN Extended frame format.");
403                         is_fdmode_on_ = false;
404                 } else {
405                         DEBUG(binder_interface, "Correctly set up CAN socket to use FD frames.");
406                         is_fdmode_on_ = true;
407                 }
408
409                 /* Attempts to open a socket to CAN bus */
410                 ::strcpy(ifr.ifr_name, device_name_.c_str());
411                 DEBUG(binder_interface, "ifr_name is : %s", ifr.ifr_name);
412                 if(::ioctl(can_socket_, SIOCGIFINDEX, &ifr) < 0)
413                         ERROR(binder_interface, "ioctl failed. Error was : %s", strerror(errno));
414                 else
415                 {
416                         txAddress_.can_family = AF_CAN;
417                         txAddress_.can_ifindex = ifr.ifr_ifindex;
418
419                         /* And bind it to txAddress */
420                         DEBUG(binder_interface, "Bind the socket");
421                         if (::bind(can_socket_, (struct sockaddr *)&txAddress_, sizeof(txAddress_)) < 0)
422                                 ERROR(binder_interface, "Bind failed. %s", strerror(errno));
423                         else
424                                 return 0;
425                 }
426                 close();
427         }
428         return -1;
429 }
430
431 /**
432         * @brief Open the can socket and returning it 
433         *
434         * @return 
435         */
436 int can_bus_dev_t::close()
437 {
438         ::close(can_socket_);
439         can_socket_ = -1;
440         return can_socket_;
441 }
442
443 /**
444 * @brief Read the can socket and retrieve canfd_frame
445 *
446 * @param const struct afb_binding_interface* interface pointer. Used to be able to log 
447 *  using application framework logger.
448 */
449 std::pair<struct canfd_frame&, size_t> can_bus_dev_t::read()
450 {
451         ssize_t nbytes;
452         //int maxdlen;
453         struct canfd_frame cfd;
454
455         /* Test that socket is really opened */
456         if (can_socket_ < 0)
457         {
458                 ERROR(binder_interface, "read_can: Socket unavailable. Closing thread.");
459                 is_running_ = false;
460         }
461
462         nbytes = ::read(can_socket_, &cfd, CANFD_MTU);
463
464         /* if we did not fit into CAN sized messages then stop_reading. */
465         if (nbytes != CANFD_MTU && nbytes != CAN_MTU)
466         {
467                 if (errno == ENETDOWN)
468                         ERROR(binder_interface, "read: %s CAN device down", device_name_);
469                 ERROR(binder_interface, "read: Incomplete CAN(FD) frame");
470                 ::memset(&cfd, 0, sizeof(cfd));
471         }
472         
473         DEBUG(binder_interface, "read: Found id: %X, length: %X, data %02X%02X%02X%02X%02X%02X%02X%02X", cfd.can_id, cfd.len,
474                                                         cfd.data[0], cfd.data[1], cfd.data[2], cfd.data[3], cfd.data[4], cfd.data[5], cfd.data[6], cfd.data[7]);
475         return std::pair<struct canfd_frame&, size_t>(cfd, nbytes);
476 }
477
478 /**
479 * @brief start reading threads and set flag is_running_
480 *
481 * @param can_bus_t reference can_bus_t. it will be passed to the thread 
482 *  to allow using can_bus_t queue.
483 */
484 void can_bus_dev_t::start_reading(can_bus_t& can_bus)
485 {
486         DEBUG(binder_interface, "Launching reading thread");
487         is_running_ = true;
488         th_reading_ = std::thread(&can_bus_dev_t::can_reader, this, std::ref(can_bus));
489         if(!th_reading_.joinable())
490                 is_running_ = false;
491 }
492
493 /**
494 * @brief stop the reading thread setting flag is_running_ to false and
495 * and wait that the thread finish its job.
496 */
497 void can_bus_dev_t::stop_reading()
498 {
499         is_running_ = false;
500 }
501
502 /**
503 *
504 * @brief Thread function used to read the can socket.
505 *
506 * @param[in] can_bus_dev_t object to be used to read the can socket
507 * @param[in] can_bus_t object used to fill can_message_q_ queue
508 */
509 void can_bus_dev_t::can_reader(can_bus_t& can_bus)
510 {
511         can_message_t can_message;
512
513         while(is_running_)
514         {
515                 can_message.convert_from_canfd_frame(read());
516
517                 {
518                         std::lock_guard<std::mutex> can_message_lock(can_bus.get_can_message_mutex());
519                         can_bus.push_new_can_message(can_message);
520                 }
521                 can_bus.get_new_can_message_cv().notify_one();
522         }
523 }
524
525 /**
526 * @brief Send a can message from a can_message_t object.
527
528 * @param const can_message_t& can_msg: the can message object to send 
529 * @param const struct afb_binding_interface* interface pointer. Used to be able to log 
530 *  using application framework logger.
531 */
532 int can_bus_dev_t::send_can_message(can_message_t& can_msg)
533 {
534         ssize_t nbytes;
535         canfd_frame f;
536
537         f = can_msg.convert_to_canfd_frame();
538
539         if(can_socket_ >= 0)
540         {
541                 nbytes = ::sendto(can_socket_, &f, sizeof(struct canfd_frame), 0,
542                                 (struct sockaddr*)&txAddress_, sizeof(txAddress_));
543                 if (nbytes == -1)
544                 {
545                         ERROR(binder_interface, "send_can_message: Sending CAN frame failed.");
546                         return -1;
547                 }
548                 return (int)nbytes;
549         }
550         else
551         {
552                 ERROR(binder_interface, "send_can_message: socket not initialized. Attempt to reopen can device socket.");
553                 open();
554         }
555         return 0;
556 }