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