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