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