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