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