Improve mutex lock logic.
[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 can_message_t can_bus_t::next_can_message()
262 {
263         can_message_t can_msg;
264
265         if(!can_message_q_.empty())
266         {
267                 can_msg = can_message_q_.front();
268                 can_message_q_.pop();
269                 DEBUG(binder_interface, "next_can_message: Here is the next can message : id %d, length %d", can_msg.get_id(), can_msg.get_length());
270                 return can_msg;
271         }
272         
273         NOTICE(binder_interface, "next_can_message: End of can message queue");
274         has_can_message_ = false;
275         return can_msg;
276 }
277
278 void can_bus_t::push_new_can_message(const can_message_t& can_msg)
279 {
280         can_message_q_.push(can_msg);
281 }
282
283 bool can_bus_t::has_can_message() const
284 {
285         return has_can_message_;
286 }
287
288 openxc_VehicleMessage can_bus_t::next_vehicle_message()
289 {
290         openxc_VehicleMessage v_msg;
291
292         if(! vehicle_message_q_.empty())
293         {
294                 v_msg = vehicle_message_q_.front();
295                 vehicle_message_q_.pop();
296                 DEBUG(binder_interface, "next_vehicle_message: next vehicle message poped");
297                 return v_msg;
298         }
299         
300         NOTICE(binder_interface, "next_vehicle_message: End of vehicle message queue");
301         has_vehicle_message_ = false;
302         return v_msg;
303 }
304
305 void can_bus_t::push_new_vehicle_message(const openxc_VehicleMessage& v_msg)
306 {
307         vehicle_message_q_.push(v_msg);
308         has_vehicle_message_ = true;
309 }
310
311 bool can_bus_t::has_vehicle_message() const
312 {
313         return has_vehicle_message_;
314 }
315
316 /********************************************************************************
317 *
318 *               can_bus_dev_t method implementation
319 *
320 *********************************************************************************/
321
322 can_bus_dev_t::can_bus_dev_t(const std::string &dev_name)
323         : device_name_{dev_name}
324 {
325 }
326
327 int can_bus_dev_t::open()
328 {
329         const int canfd_on = 1;
330         struct ifreq ifr;
331         struct timeval timeout = {1, 0};
332
333         DEBUG(binder_interface, "CAN Handler socket : %d", can_socket_);
334         if (can_socket_ >= 0)
335                 return 0;
336
337         can_socket_ = ::socket(PF_CAN, SOCK_RAW, CAN_RAW);
338         if (can_socket_ < 0)
339         {
340                 ERROR(binder_interface, "socket could not be created");
341         }
342         else
343         {
344                 /* Set timeout for read */
345                 ::setsockopt(can_socket_, SOL_SOCKET, SO_RCVTIMEO, (char *)&timeout, sizeof(timeout));
346                 /* try to switch the socket into CAN_FD mode */
347                 if (::setsockopt(can_socket_, SOL_CAN_RAW, CAN_RAW_FD_FRAMES, &canfd_on, sizeof(canfd_on)) < 0)
348                 {
349                         NOTICE(binder_interface, "Can not switch into CAN Extended frame format.");
350                         is_fdmode_on_ = false;
351                 } else {
352                         is_fdmode_on_ = true;
353                 }
354
355                 /* Attempts to open a socket to CAN bus */
356                 ::strcpy(ifr.ifr_name, device_name_.c_str());
357                 if(::ioctl(can_socket_, SIOCGIFINDEX, &ifr) < 0)
358                         ERROR(binder_interface, "ioctl failed");
359                 else
360                 {
361                         txAddress_.can_family = AF_CAN;
362                         txAddress_.can_ifindex = ifr.ifr_ifindex;
363
364                         /* And bind it to txAddress */
365                         if (::bind(can_socket_, (struct sockaddr *)&txAddress_, sizeof(txAddress_)) < 0)
366                                 ERROR(binder_interface, "Bind failed");
367                         else
368                                 return 0;
369                 }
370                 close();
371         }
372         return -1;
373 }
374
375 int can_bus_dev_t::close()
376 {
377         ::close(can_socket_);
378         can_socket_ = -1;
379         return can_socket_;
380 }
381
382 canfd_frame can_bus_dev_t::read()
383 {
384         ssize_t nbytes;
385         //int maxdlen;
386         canfd_frame canfd_frame;
387
388         /* Test that socket is really opened */
389         if (can_socket_ < 0)
390         {
391                 ERROR(binder_interface, "read_can: Socket unavailable. Closing thread.");
392                 is_running_ = false;
393         }
394
395         nbytes = ::read(can_socket_, &canfd_frame, CANFD_MTU);
396
397         switch(nbytes)
398         {
399                 case CANFD_MTU:
400                         DEBUG(binder_interface, "read_can: Got an CAN FD frame with length %d", canfd_frame.len);
401                         //maxdlen = CANFD_MAX_DLEN;
402                         break;
403                 case CAN_MTU:
404                         DEBUG(binder_interface, "read_can: Got a legacy CAN frame with length %d", canfd_frame.len);
405                         //maxdlen = CAN_MAX_DLEN;
406                         break;
407                 default:
408                         if (errno == ENETDOWN)
409                                         ERROR(binder_interface, "read_can: %s binder_interface down", device_name_);
410                         ERROR(binder_interface, "read_can: Error reading CAN bus");
411                         ::memset(&canfd_frame, 0, sizeof(canfd_frame));
412                         is_running_ = false;
413                         break;
414         }
415         
416         return canfd_frame;
417 }
418
419 void can_bus_dev_t::start_reading(can_bus_t& can_bus)
420 {
421         th_reading_ = std::thread(can_reader, std::ref(*this), std::ref(can_bus));
422         is_running_ = true;
423 }
424
425 /*
426  * Return is_running_ bool
427  */
428 bool can_bus_dev_t::is_running()
429 {
430         return is_running_;
431 }
432
433 int can_bus_dev_t::send_can_message(can_message_t& can_msg)
434 {
435         ssize_t nbytes;
436         canfd_frame f;
437
438         f = can_msg.convert_to_canfd_frame();
439
440         if(can_socket_ >= 0)
441         {
442                 nbytes = ::sendto(can_socket_, &f, sizeof(struct canfd_frame), 0,
443                                 (struct sockaddr*)&txAddress_, sizeof(txAddress_));
444                 if (nbytes == -1)
445                 {
446                         ERROR(binder_interface, "send_can_message: Sending CAN frame failed.");
447                         return -1;
448                 }
449                 return (int)nbytes;
450         }
451         else
452         {
453                 ERROR(binder_interface, "send_can_message: socket not initialized. Attempt to reopen can device socket.");
454                 open();
455         }
456         return 0;
457 }