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