84cbaaa4e21817d6bebf448e0917c8441318ac75
[apps/agl-service-can-low-level.git] / src / 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-bus.hpp"
19
20 #include <map>
21 #include <vector>
22 #include <string>
23 #include <fcntl.h>
24 #include <unistd.h>
25 #include <net/if.h>
26 #include <sys/ioctl.h>
27 #include <sys/socket.h>
28 #include <json-c/json.h>
29 #include <linux/can/raw.h>
30
31 extern "C"
32 {
33         #include <afb/afb-binding.h>
34 }
35
36 /********************************************************************************
37 *
38 *               can_bus_t method implementation
39 *
40 *********************************************************************************/
41
42 can_bus_t::can_bus_t(int& conf_file)
43         : conf_file_{conf_file}
44 {
45 }
46
47 void can_bus_t::can_decode_message()
48 {
49         can_message_t can_message;
50         std::vector <CanSignal> signals;
51         std::vector <CanSignal>::iterator signals_i;
52         openxc_VehicleMessage vehicle_message;
53         openxc_DynamicField search_key, decoded_message;
54
55         decoder_t decoder;
56
57         DEBUG(binder_interface, "Beginning of decoding thread.");
58         while(is_decoding())
59         {
60                 {
61                         std::unique_lock<std::mutex> can_message_lock(can_message_mutex_);
62                         new_can_message_.wait(can_message_lock);
63                         can_message = next_can_message();
64                 }
65
66                 /* First we have to found which CanSignal it is */
67                 search_key = build_DynamicField((double)can_message.get_id());
68                 signals = find_can_signals(search_key);
69
70                 /* Decoding the message ! Don't kill the messenger ! */
71                 for(auto& sig : signals)
72                 {
73                         {
74                                 std::lock_guard<std::mutex> subscribed_signals_lock(get_subscribed_signals_mutex());
75                                 std::map<std::string, struct afb_event> subscribed_signals = get_subscribed_signals();
76                                 const auto& it_event = subscribed_signals.find(sig.genericName);
77                                 
78                                 if(it_event != subscribed_signals.end() && afb_event_is_valid(it_event->second))
79                                 {
80                                         decoded_message = decoder.translateSignal(sig, can_message, getSignals());
81
82                                         openxc_SimpleMessage s_message = build_SimpleMessage(sig.genericName, decoded_message);
83                                         vehicle_message = build_VehicleMessage_with_SimpleMessage(openxc_DynamicField_Type::openxc_DynamicField_Type_NUM, s_message);
84
85                                         std::lock_guard<std::mutex> decoded_can_message_lock(decoded_can_message_mutex_);
86                                         push_new_vehicle_message(vehicle_message);
87                                 }
88                                 new_decoded_can_message_.notify_one();
89                         }
90                 }
91         }
92 }
93
94 void can_bus_t::can_event_push()
95 {
96         openxc_VehicleMessage v_message;
97         openxc_SimpleMessage s_message;
98         json_object* jo;
99         
100         DEBUG(binder_interface, "Beginning of the pushing thread");
101         while(is_pushing())
102         {
103                 {
104                         std::unique_lock<std::mutex> decoded_can_message_lock(decoded_can_message_mutex_);
105                         new_decoded_can_message_.wait(decoded_can_message_lock);
106                         v_message = next_vehicle_message();
107                 }
108
109                 s_message = get_simple_message(v_message);
110
111                 {
112                         std::lock_guard<std::mutex> subscribed_signals_lock(get_subscribed_signals_mutex());
113                         std::map<std::string, struct afb_event> subscribed_signals = get_subscribed_signals();
114                         const auto& it_event = subscribed_signals.find(s_message.name);
115                         if(it_event != subscribed_signals.end() && afb_event_is_valid(it_event->second))
116                         {
117                                 jo = json_object_new_object();
118                                 jsonify_simple(s_message, jo);
119                                 afb_event_push(it_event->second, jo);
120                         }
121                 }
122         }
123 }
124
125 void can_bus_t::start_threads()
126 {
127         th_decoding_ = std::thread(&can_bus_t::can_decode_message, this);
128         is_decoding_ = true;
129         th_pushing_ = std::thread(&can_bus_t::can_event_push, this);
130         is_pushing_ = true;
131 }
132
133 void can_bus_t::stop_threads()
134 {
135         is_decoding_ = false;
136         is_pushing_ = false;
137         th_decoding_.join();
138         th_pushing_.join();
139 }
140
141 bool can_bus_t::is_decoding()
142 {
143         return is_decoding_;
144 }
145
146 bool can_bus_t::is_pushing()
147 {
148         return is_pushing_;
149 }
150
151 int can_bus_t::init_can_dev()
152 {
153         std::vector<std::string> devices_name;
154         int i;
155         size_t t;
156
157         devices_name = read_conf();
158
159         if (! devices_name.empty())
160         {
161                 t = devices_name.size();
162                 i=0;
163
164                 for(const auto& device : devices_name)
165                 {
166                         can_bus_dev_t can_bus_device_handler(device);
167                         if (can_bus_device_handler.open())
168                         {
169                                 i++;
170                                 can_bus_device_handler.start_reading(std::ref(*this));
171                         }
172                         else
173                                 ERROR(binder_interface, "Can't open device %s", device);
174                 }
175
176                 NOTICE(binder_interface, "Initialized %d/%d can bus device(s)", i, t);
177                 return 0;
178         }
179         ERROR(binder_interface, "init_can_dev: Error at CAN device initialization. No devices read from configuration file. Did you specify canbus JSON object ?");
180         return 1;
181 }
182
183 std::vector<std::string> can_bus_t::read_conf()
184 {
185         std::vector<std::string> ret;
186         json_object *jo, *canbus;
187         int n, i;
188         const char* taxi;
189
190         FILE *fd = fdopen(conf_file_, "r");
191         if (fd)
192         {
193                 std::string fd_conf_content;
194                 std::fseek(fd, 0, SEEK_END);
195                 fd_conf_content.resize(std::ftell(fd));
196                 std::rewind(fd);
197                 std::fread(&fd_conf_content[0], 1, fd_conf_content.size(), fd);
198                 std::fclose(fd);
199
200                 DEBUG(binder_interface, "Conf file content : %s", fd_conf_content.c_str());
201                 jo = json_tokener_parse(fd_conf_content.c_str());
202
203                 if (jo == NULL || !json_object_object_get_ex(jo, "canbus", &canbus))
204                 {
205                         ERROR(binder_interface, "Can't find canbus node in the configuration file. Please review it.");
206                         ret.clear();
207                 }
208                 else if (json_object_get_type(canbus) != json_type_array)
209                 {
210                         taxi = json_object_get_string(canbus);
211                         DEBUG(binder_interface, "Can bus found: %s", taxi);
212                         ret.push_back(std::string(taxi));
213                 }
214                 else
215                 {
216                         n = json_object_array_length(canbus);
217                         for (i = 0 ; i < n ; i++)
218                                 ret.push_back(json_object_get_string(json_object_array_get_idx(canbus, i)));
219                 }
220                 return ret;
221         }
222         ERROR(binder_interface, "Problem at reading the conf file");
223         ret.clear();
224         return ret;
225 }
226
227 std::condition_variable& can_bus_t::get_new_can_message()
228 {
229         return new_can_message_;
230 }
231
232 std::mutex& can_bus_t::get_can_message_mutex()
233 {
234         return can_message_mutex_;
235 }
236
237 can_message_t can_bus_t::next_can_message()
238 {
239         can_message_t can_msg;
240
241         if(!can_message_q_.empty())
242         {
243                 can_msg = can_message_q_.front();
244                 can_message_q_.pop();
245                 DEBUG(binder_interface, "next_can_message: Here is the next can message : id %d, length %d", can_msg.get_id(), can_msg.get_length());
246                 return can_msg;
247         }
248         
249         NOTICE(binder_interface, "next_can_message: End of can message queue");
250         has_can_message_ = false;
251         return can_msg;
252 }
253
254 void can_bus_t::push_new_can_message(const can_message_t& can_msg)
255 {
256         can_message_q_.push(can_msg);
257 }
258
259 openxc_VehicleMessage can_bus_t::next_vehicle_message()
260 {
261         openxc_VehicleMessage v_msg;
262
263         if(! vehicle_message_q_.empty())
264         {
265                 v_msg = vehicle_message_q_.front();
266                 vehicle_message_q_.pop();
267                 DEBUG(binder_interface, "next_vehicle_message: next vehicle message poped");
268                 return v_msg;
269         }
270         
271         NOTICE(binder_interface, "next_vehicle_message: End of vehicle message queue");
272         has_vehicle_message_ = false;
273         return v_msg;
274 }
275
276 void can_bus_t::push_new_vehicle_message(const openxc_VehicleMessage& v_msg)
277 {
278         vehicle_message_q_.push(v_msg);
279         has_vehicle_message_ = true;
280 }
281
282 /********************************************************************************
283 *
284 *               can_bus_dev_t method implementation
285 *
286 *********************************************************************************/
287
288 can_bus_dev_t::can_bus_dev_t(const std::string &dev_name)
289         : device_name_{dev_name}, can_socket_{-1}
290 {
291 }
292
293 int can_bus_dev_t::open()
294 {
295         const int canfd_on = 1;
296         const int timestamp_on = 1;
297         struct ifreq ifr;
298         struct timeval timeout;
299
300         DEBUG(binder_interface, "CAN Handler socket : %d", can_socket_);
301         if (can_socket_ >= 0)
302                 return 0;
303
304         can_socket_ = ::socket(PF_CAN, SOCK_RAW, CAN_RAW);
305         DEBUG(binder_interface, "CAN Handler socket correctly initialized : %d", can_socket_);
306         if (can_socket_ < 0)
307                 ERROR(binder_interface, "socket could not be created. Error was : %s", ::strerror(errno));
308         else
309         {
310                 /* Set timeout for read */
311                 ::setsockopt(can_socket_, SOL_SOCKET, SO_RCVTIMEO, (char *)&timeout, sizeof(timeout));
312                 /* Set timestamp for receveid frame */
313                 if (::setsockopt(can_socket_, SOL_SOCKET, SO_TIMESTAMP, &timestamp_on, sizeof(timestamp_on)) < 0)
314                         WARNING(binder_interface, "setsockopt SO_TIMESTAMP error: %s", ::strerror(errno));
315                 DEBUG(binder_interface, "Switch CAN Handler socket to use fd mode");
316                 /* try to switch the socket into CAN_FD mode */
317                 if (::setsockopt(can_socket_, SOL_CAN_RAW, CAN_RAW_FD_FRAMES, &canfd_on, sizeof(canfd_on)) < 0)
318                 {
319                         NOTICE(binder_interface, "Can not switch into CAN Extended frame format.");
320                         is_fdmode_on_ = false;
321                 } else {
322                         DEBUG(binder_interface, "Correctly set up CAN socket to use FD frames.");
323                         is_fdmode_on_ = true;
324                 }
325
326                 /* Attempts to open a socket to CAN bus */
327                 ::strcpy(ifr.ifr_name, device_name_.c_str());
328                 DEBUG(binder_interface, "ifr_name is : %s", ifr.ifr_name);
329                 if(::ioctl(can_socket_, SIOCGIFINDEX, &ifr) < 0)
330                         ERROR(binder_interface, "ioctl failed. Error was : %s", strerror(errno));
331                 else
332                 {
333                         txAddress_.can_family = AF_CAN;
334                         txAddress_.can_ifindex = ifr.ifr_ifindex;
335
336                         /* And bind it to txAddress */
337                         DEBUG(binder_interface, "Bind the socket");
338                         if (::bind(can_socket_, (struct sockaddr *)&txAddress_, sizeof(txAddress_)) < 0)
339                                 ERROR(binder_interface, "Bind failed. %s", strerror(errno));
340                         else
341                                 return 0;
342                 }
343                 close();
344         }
345         return -1;
346 }
347
348 int can_bus_dev_t::close()
349 {
350         ::close(can_socket_);
351         can_socket_ = -1;
352         return can_socket_;
353 }
354
355 canfd_frame can_bus_dev_t::read()
356 {
357         ssize_t nbytes;
358         //int maxdlen;
359         canfd_frame canfd_frame;
360
361         /* Test that socket is really opened */
362         if (can_socket_ < 0)
363         {
364                 ERROR(binder_interface, "read_can: Socket unavailable. Closing thread.");
365                 is_running_ = false;
366         }
367
368         nbytes = ::read(can_socket_, &canfd_frame, CANFD_MTU);
369
370         switch(nbytes)
371         {
372                 case CANFD_MTU:
373                         DEBUG(binder_interface, "read_can: Got an CAN FD frame with length %d", canfd_frame.len);
374                         //maxdlen = CANFD_MAX_DLEN;
375                         break;
376                 case CAN_MTU:
377                         DEBUG(binder_interface, "read_can: Got a legacy CAN frame with length %d", canfd_frame.len);
378                         //maxdlen = CAN_MAX_DLEN;
379                         break;
380                 default:
381                         if (errno == ENETDOWN)
382                                         ERROR(binder_interface, "read_can: %s binder_interface down", device_name_);
383                         ERROR(binder_interface, "read_can: Error reading CAN bus");
384                         ::memset(&canfd_frame, 0, sizeof(canfd_frame));
385                         is_running_ = false;
386                         break;
387         }
388         
389         return canfd_frame;
390 }
391
392 bool can_bus_dev_t::is_running()
393 {
394         return is_running_;
395 }
396
397 void can_bus_dev_t::start_reading(can_bus_t& can_bus)
398 {
399         DEBUG(binder_interface, "Launching reading thread");
400         th_reading_ = std::thread(&can_bus_dev_t::can_reader, this, std::ref(can_bus));
401         is_running_ = true;
402 }
403
404 void can_bus_dev_t::stop_reading()
405 {
406         is_running_ = false;
407         th_reading_.join();
408 }
409
410 void can_bus_dev_t::can_reader(can_bus_t& can_bus)
411 {
412         can_message_t can_message;
413
414         DEBUG(binder_interface, "Beginning of reading thread");
415         while(is_running())
416         {
417                 can_message.convert_from_canfd_frame(read());
418
419                 {
420                         std::lock_guard<std::mutex> can_message_lock(can_bus.get_can_message_mutex());
421                         can_bus.push_new_can_message(can_message);
422                 }
423                 can_bus.get_new_can_message().notify_one();
424         }
425 }
426
427 int can_bus_dev_t::send_can_message(can_message_t& can_msg)
428 {
429         ssize_t nbytes;
430         canfd_frame f;
431
432         f = can_msg.convert_to_canfd_frame();
433
434         if(can_socket_ >= 0)
435         {
436                 nbytes = ::sendto(can_socket_, &f, sizeof(struct canfd_frame), 0,
437                                 (struct sockaddr*)&txAddress_, sizeof(txAddress_));
438                 if (nbytes == -1)
439                 {
440                         ERROR(binder_interface, "send_can_message: Sending CAN frame failed.");
441                         return -1;
442                 }
443                 return (int)nbytes;
444         }
445         else
446         {
447                 ERROR(binder_interface, "send_can_message: socket not initialized. Attempt to reopen can device socket.");
448                 open();
449         }
450         return 0;
451 }