b1dcc3adcc46cc69c55e288f221eefa5eb88ef75
[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         while(is_decoding_)
62         {
63                 {
64                         std::unique_lock<std::mutex> can_message_lock(can_message_mutex_);
65                         new_can_message_.wait(can_message_lock);
66                         can_message = next_can_message();
67                 }
68
69                 /* First we have to found which CanSignal it is */
70                 search_key = build_DynamicField((double)can_message.get_id());
71                 signals = find_can_signals(search_key);
72
73                 /* Decoding the message ! Don't kill the messenger ! */
74                 for(auto& sig : signals)
75                 {
76                         {
77                                 std::lock_guard<std::mutex> subscribed_signals_lock(get_subscribed_signals_mutex());
78                                 std::map<std::string, struct afb_event>& s = get_subscribed_signals();
79                                 
80                                 const auto& it = s.find(sig.genericName);
81                                 if (it != s.end())
82                                         DEBUG(binder_interface, "Iterator key: %s, event valid? %d", it->first.c_str(), afb_event_is_valid(it->second));
83                                 DEBUG(binder_interface, "Operator[] key char: %s, event valid? %d", sig.genericName, afb_event_is_valid(s[sig.genericName]));
84                                 DEBUG(binder_interface, "Operator[] key string: %s, event valid? %d", sig.genericName, afb_event_is_valid(s[std::string(sig.genericName)]));
85                                 DEBUG(binder_interface, "Nb elt matched char: %d", (int)s.count(sig.genericName));
86                                 DEBUG(binder_interface, "Nb elt matched string: %d", (int)s.count(std::string(sig.genericName)));
87                                 if( it != s.end() && afb_event_is_valid(it->second))
88                                 {
89                                         decoded_message = decoder.translateSignal(sig, can_message, getSignals());
90
91                                         openxc_SimpleMessage s_message = build_SimpleMessage(sig.genericName, decoded_message);
92                                         vehicle_message = build_VehicleMessage_with_SimpleMessage(openxc_DynamicField_Type::openxc_DynamicField_Type_NUM, s_message);
93
94                                         std::lock_guard<std::mutex> decoded_can_message_lock(decoded_can_message_mutex_);
95                                         push_new_vehicle_message(vehicle_message);
96                                         new_decoded_can_message_.notify_one();
97                                 }
98                         }
99                 }
100         }
101 }
102
103 void can_bus_t::can_event_push()
104 {
105         openxc_VehicleMessage v_message;
106         openxc_SimpleMessage s_message;
107         json_object* jo;
108         
109         while(is_pushing_)
110         {
111                 {
112                         std::unique_lock<std::mutex> decoded_can_message_lock(decoded_can_message_mutex_);
113                         new_decoded_can_message_.wait(decoded_can_message_lock);
114                         v_message = next_vehicle_message();
115                 }
116
117                 s_message = get_simple_message(v_message);
118
119                 {
120                         std::lock_guard<std::mutex> subscribed_signals_lock(get_subscribed_signals_mutex());
121                         std::map<std::string, struct afb_event>& s = get_subscribed_signals();
122                         if(s.find(std::string(s_message.name)) != s.end() && afb_event_is_valid(s[std::string(s_message.name)]))
123                         {
124                                 jo = json_object_new_object();
125                                 jsonify_simple(s_message, jo);
126                                 afb_event_push(s[std::string(s_message.name)], jo);
127                         }
128                 }
129         }
130 }
131
132 void can_bus_t::start_threads()
133 {
134         is_decoding_ = true;
135         th_decoding_ = std::thread(&can_bus_t::can_decode_message, this);
136         if(!th_decoding_.joinable())
137                 is_decoding_ = false;
138         
139         is_pushing_ = true;
140         th_pushing_ = std::thread(&can_bus_t::can_event_push, this);
141         if(!th_pushing_.joinable())
142                 is_pushing_ = false;
143 }
144
145 void can_bus_t::stop_threads()
146 {
147         is_decoding_ = false;
148         is_pushing_ = false;
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_devices_m_[device] = std::make_shared<can_bus_dev_t>(device);
167                         if (can_devices_m_[device]->open() == 0)
168                         {
169                                 i++;
170                                 DEBUG(binder_interface, "Start reading thread");
171                                 can_devices_m_[device]->start_reading(*this);
172                         }
173                         else
174                                 ERROR(binder_interface, "Can't open device %s", device.c_str());
175                 }
176
177                 NOTICE(binder_interface, "Initialized %d/%d can bus device(s)", i, t);
178                 return 0;
179         }
180         ERROR(binder_interface, "init_can_dev: Error at CAN device initialization. No devices read from configuration file. Did you specify canbus JSON object ?");
181         return 1;
182 }
183
184 std::vector<std::string> can_bus_t::read_conf()
185 {
186         std::vector<std::string> ret;
187         json_object *jo, *canbus;
188         int n, i;
189         const char* taxi;
190
191         FILE *fd = fdopen(conf_file_, "r");
192         if (fd)
193         {
194                 std::string fd_conf_content;
195                 std::fseek(fd, 0, SEEK_END);
196                 fd_conf_content.resize(std::ftell(fd));
197                 std::rewind(fd);
198                 std::fread(&fd_conf_content[0], 1, fd_conf_content.size(), fd);
199                 std::fclose(fd);
200
201                 DEBUG(binder_interface, "Configuration file content : %s", fd_conf_content.c_str());
202                 jo = json_tokener_parse(fd_conf_content.c_str());
203
204                 if (jo == NULL || !json_object_object_get_ex(jo, "canbus", &canbus))
205                 {
206                         ERROR(binder_interface, "Can't find canbus node in the configuration file. Please review it.");
207                         ret.clear();
208                 }
209                 else if (json_object_get_type(canbus) != json_type_array)
210                 {
211                         taxi = json_object_get_string(canbus);
212                         DEBUG(binder_interface, "Can bus found: %s", taxi);
213                         ret.push_back(std::string(taxi));
214                 }
215                 else
216                 {
217                         n = json_object_array_length(canbus);
218                         for (i = 0 ; i < n ; i++)
219                                 ret.push_back(json_object_get_string(json_object_array_get_idx(canbus, i)));
220                 }
221                 return ret;
222         }
223         ERROR(binder_interface, "Problem at reading the conf file");
224         ret.clear();
225         return ret;
226 }
227
228 std::condition_variable& can_bus_t::get_new_can_message()
229 {
230         return new_can_message_;
231 }
232
233 std::mutex& can_bus_t::get_can_message_mutex()
234 {
235         return can_message_mutex_;
236 }
237
238 can_message_t can_bus_t::next_can_message()
239 {
240         can_message_t can_msg;
241
242         if(!can_message_q_.empty())
243         {
244                 can_msg = can_message_q_.front();
245                 can_message_q_.pop();
246                 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(),
247                         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]);
248                 return can_msg;
249         }
250         
251         has_can_message_ = false;
252         return can_msg;
253 }
254
255 void can_bus_t::push_new_can_message(const can_message_t& can_msg)
256 {
257         can_message_q_.push(can_msg);
258 }
259
260 openxc_VehicleMessage can_bus_t::next_vehicle_message()
261 {
262         openxc_VehicleMessage v_msg;
263
264         if(! vehicle_message_q_.empty())
265         {
266                 v_msg = vehicle_message_q_.front();
267                 vehicle_message_q_.pop();
268                 DEBUG(binder_interface, "next_vehicle_message: next vehicle message poped");
269                 return v_msg;
270         }
271         
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 std::map<std::string, std::shared_ptr<can_bus_dev_t>> can_bus_t::get_can_devices()
283 {
284         return can_devices_m_;
285 }
286
287 /********************************************************************************
288 *
289 *               can_bus_dev_t method implementation
290 *
291 *********************************************************************************/
292
293 can_bus_dev_t::can_bus_dev_t(const std::string &dev_name)
294         : device_name_{dev_name}, can_socket_{-1}
295 {
296 }
297
298 int can_bus_dev_t::open()
299 {
300         const int canfd_on = 1;
301         const int timestamp_on = 1;
302         struct ifreq ifr;
303         struct timeval timeout;
304
305         DEBUG(binder_interface, "CAN Handler socket : %d", can_socket_);
306         if (can_socket_ >= 0)
307                 return 0;
308
309         can_socket_ = ::socket(PF_CAN, SOCK_RAW, CAN_RAW);
310         DEBUG(binder_interface, "CAN Handler socket correctly initialized : %d", can_socket_);
311         if (can_socket_ < 0)
312                 ERROR(binder_interface, "socket could not be created. Error was : %s", ::strerror(errno));
313         else
314         {
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, &timestamp_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)
323                 {
324                         NOTICE(binder_interface, "Can not switch into CAN Extended frame format.");
325                         is_fdmode_on_ = false;
326                 } else {
327                         DEBUG(binder_interface, "Correctly set up CAN socket to use FD frames.");
328                         is_fdmode_on_ = true;
329                 }
330
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));
336                 else
337                 {
338                         txAddress_.can_family = AF_CAN;
339                         txAddress_.can_ifindex = ifr.ifr_ifindex;
340
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));
345                         else
346                                 return 0;
347                 }
348                 close();
349         }
350         return -1;
351 }
352
353 int can_bus_dev_t::close()
354 {
355         ::close(can_socket_);
356         can_socket_ = -1;
357         return can_socket_;
358 }
359
360 std::pair<struct canfd_frame&, size_t> can_bus_dev_t::read()
361 {
362         ssize_t nbytes;
363         //int maxdlen;
364         struct canfd_frame cfd;
365
366         /* Test that socket is really opened */
367         if (can_socket_ < 0)
368         {
369                 ERROR(binder_interface, "read_can: Socket unavailable. Closing thread.");
370                 is_running_ = false;
371         }
372
373         nbytes = ::read(can_socket_, &cfd, CANFD_MTU);
374
375         /* if we did not fit into CAN sized messages then stop_reading. */
376         if (nbytes != CANFD_MTU && nbytes != CAN_MTU)
377         {
378                 if (errno == ENETDOWN)
379                         ERROR(binder_interface, "read: %s CAN device down", device_name_);
380                 ERROR(binder_interface, "read: Incomplete CAN(FD) frame");
381                 ::memset(&cfd, 0, sizeof(cfd));
382         }
383
384         return std::pair<struct canfd_frame&, size_t>(cfd, nbytes);
385 }
386
387 void can_bus_dev_t::start_reading(can_bus_t& can_bus)
388 {
389         DEBUG(binder_interface, "Launching reading thread");
390         is_running_ = true;
391         th_reading_ = std::thread(&can_bus_dev_t::can_reader, this, std::ref(can_bus));
392         if(!th_reading_.joinable())
393                 is_running_ = false;
394 }
395
396 void can_bus_dev_t::stop_reading()
397 {
398         is_running_ = false;
399 }
400
401 void can_bus_dev_t::can_reader(can_bus_t& can_bus)
402 {
403         can_message_t can_message;
404
405         while(is_running_)
406         {
407                 can_message.convert_from_canfd_frame(read());
408
409                 {
410                         std::lock_guard<std::mutex> can_message_lock(can_bus.get_can_message_mutex());
411                         can_bus.push_new_can_message(can_message);
412                 }
413                 can_bus.get_new_can_message().notify_one();
414         }
415 }
416
417 int can_bus_dev_t::send_can_message(can_message_t& can_msg)
418 {
419         ssize_t nbytes;
420         canfd_frame f;
421
422         f = can_msg.convert_to_canfd_frame();
423
424         if(can_socket_ >= 0)
425         {
426                 nbytes = ::sendto(can_socket_, &f, sizeof(struct canfd_frame), 0,
427                                 (struct sockaddr*)&txAddress_, sizeof(txAddress_));
428                 if (nbytes == -1)
429                 {
430                         ERROR(binder_interface, "send_can_message: Sending CAN frame failed.");
431                         return -1;
432                 }
433                 return (int)nbytes;
434         }
435         else
436         {
437                 ERROR(binder_interface, "send_can_message: socket not initialized. Attempt to reopen can device socket.");
438                 open();
439         }
440         return 0;
441 }