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