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