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