Fix: timer.* issues
[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 #pragma once
19
20 /********************************************************************************
21 *
22 *               can_bus_dev_t method implementation
23 *
24 *********************************************************************************/
25
26
27 can_bus_dev_t::can_bus_dev_t(afb_binding_interface *itf, const std:string &dev_name)
28         : device_name_{dev_name}
29 {
30 }
31
32 int can_bus_dev_t::open()
33 {
34         const int canfd_on = 1;
35         struct ifreq ifr;
36         struct timeval timeout = {1, 0};
37
38         DEBUG(interface_, "open_can_dev: CAN Handler socket : %d", can_socket_);
39         if (can_socket_ >= 0)
40                 return 0;
41
42         can_socket_ = ::socket(PF_CAN, SOCK_RAW, CAN_RAW);
43         if (socket < 0)
44         {
45                 ERROR(interface_, "open_can_dev: socket could not be created");
46         }
47         else
48         {
49                 /* Set timeout for read */
50                 ::setsockopt(can_socket_, SOL_SOCKET, SO_RCVTIMEO, (char *)&timeout, sizeof(timeout));
51                 /* try to switch the socket into CAN_FD mode */
52                 if (::setsockopt(can_socket_, SOL_CAN_RAW, CAN_RAW_FD_FRAMES, &canfd_on, sizeof(canfd_on)) < 0)
53                 {
54                         NOTICE(interface_, "open_can_dev: Can not switch into CAN Extended frame format.");
55                         is_fdmode_on_ = false;
56                 } else {
57                         is_fdmode_on_ = true;
58                 }
59
60                 /* Attempts to open a socket to CAN bus */
61                 ::strcpy(ifr.ifr_name, device);
62                 if(ioctl(can_socket_, SIOCGIFINDEX, &ifr) < 0)
63                         ERROR(interface_, "open_can_dev: ioctl failed");
64                 else
65                 {
66                         txAddress.can_family = AF_CAN;
67                         txAddress.can_ifindex = ifr.ifr_ifindex;
68
69                         /* And bind it to txAddress */
70                         if (::bind(can_socket_, (struct sockaddr *)&txAddress_, sizeof(txAddress_)) < 0)
71                         {
72                                 ERROR(interface_, "open_can_dev: bind failed");
73                         }
74                         else
75                         {
76                                 ::fcntl(can_socket_, F_SETFL, O_NONBLOCK);
77                                 return 0;
78                         }
79                 }
80                 close();
81         }
82         return -1;
83 }
84
85 int can_bus_dev_t::close()
86 {
87         ::close(can_socket_);
88         can_socket_ = -1;
89 }
90
91
92 canfd_frame can_bus_dev_t::read()
93 {
94         ssize_t nbytes;
95         //int maxdlen;
96         canfd_frame canfd_frame;
97
98         /* Test that socket is really opened */
99         if (can_socket_ < 0)
100         {
101                 ERROR(interface_, "read_can: Socket unavailable. Closing thread.");
102                 is_running_ = false;
103         }
104
105         nbytes = ::read(can_socket_, &canfd_frame, CANFD_MTU);
106
107         switch(nbytes)
108         {
109                 case CANFD_MTU:
110                         DEBUG(interface_, "read_can: Got an CAN FD frame with length %d", canfd_frame.len);
111                         //maxdlen = CANFD_MAX_DLEN;
112                         break;
113                 case CAN_MTU:
114                         DEBUG(interface_, "read_can: Got a legacy CAN frame with length %d", canfd_frame.len);
115                         //maxdlen = CAN_MAX_DLEN;
116                         break;
117                 default:
118                         if (errno == ENETDOWN)
119                                         ERROR(interface_, "read_can: %s interface down", device);
120                         ERROR(interface_, "read_can: Error reading CAN bus");
121                         ::memset(&canfd_frame, 0, sizeof(canfd_frame));
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(afb_binding_interface *itf, std::ifstream& 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 /**
210  * @brief Initialize as many as can_bus_dev_t objects with their respective reading thread
211  * 
212  * params[std::ifstream& conf_file] conf_file ifstream to the JSON configuration 
213  * file located at the rootdir of the binding
214  */
215 int init_can_dev()
216 {
217         std::vector<std::string> devices_name;
218         int i, t, ret;
219
220         devices_name = read_conf(conf_file_);
221
222         if (devices_name)
223         {
224                 t = devices_name.size();
225                 i=0
226
227                 for(const auto& device : devices_name)
228                 {
229                         can_bus_dev_t(device);
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         std::string fd_conf_content;
249         json_object jo, canbus;
250         int n, i, ok;
251
252         /* Open JSON conf file */
253         if (conf_file_)
254         {
255                 conf_file_.seekg(0, std::ios::end);
256                 conf_file_.resize(conf_file_.tellg());
257                 conf_file_.seekg(0, std::ios::beg);
258                 conf_file_.read(&fd_conf_content[0], fd_conf_content.size());
259                 conf_file_.close();
260
261                 jo = json_tokener_parse(&fd_conf_content);
262
263                 if (jo == NULL || !json_object_object_get_ex(&jo, "canbus", &&canbus))
264                 {
265                         ERROR(interface_, "Can't find canbus node in the configuration file. Please review it.");
266                         ret = nullptr;
267                 }
268                 else if (json_object_get_type(canbus) != json_type_array)
269                         ret.push_back(json_object_get_string(a));
270                 else
271                 {
272                         n = json_object_array_length(a);
273                         ok = 0;
274                         for (i = 0 ; i < n ; i++)
275                         ret.push_back(json_object_get_string(json_object_array_get_idx(a, i)));
276                 }
277         return ret;
278         }
279         ERROR(interface_, "Problem at reading the conf file");
280         return nullptr;
281 }
282
283 /**
284  * @brief Send a can message from a can_message_t object.
285  * TODO: specify which can_dev to use as we can use many
286  * 
287  * params[const can_message_t& can_msg] the can message object to send
288  * 
289  */
290 int can_bus_t::send_can_message(const can_message_t &can_msg)
291 {
292         int nbytes;
293         canfd_frame *f;
294
295         f = can_msg.convert_to_canfd_frame();
296
297         if(can_socket_ >= 0)
298         {
299                 nbytes = ::sendto(can_socket_, &f, sizeof(struct canfd_frame), 0,
300                                 (struct sockaddr*)&txAddress, sizeof(txAddress));
301                                 
302                 if (nbytes == -1)
303                 {
304                         ERROR(interface_, "send_can_message: Sending CAN frame failed.");
305                         return -1;
306                 }
307                 return nbytes;
308         }
309         else
310         {
311                 ERROR(interface_, "send_can_message: socket not initialized. Attempt to reopen can device socket.");
312                 open();
313         }
314         return 0;
315 }
316
317 /**
318  * @brief: Get a VehicleMessage from vehicle_message_q and return it
319  * then point to the next VehicleMessage in queue.
320  * 
321  * @return the next queue element or NULL if queue is empty.
322  */
323 openxc_VehicleMessage* can_bus_t::next_vehicle_message()
324 {
325         if(! vehicle_message_q_.empty())
326         {
327                 openxc_VehicleMessage v_msg = vehicle_message_q_.front();
328                 vehicle_message_q_.pop();
329                 return &v_msg;
330         }
331
332         has_vehicle_message_ = false;
333 }
334
335 /**
336  * @brief Append a new element to the vehicle message queue and set
337  * has_vehicle_message_ boolean to true
338  * 
339  * @params[const openxc_VehicleMessage& v_msg] the openxc_VehicleMessage to append
340  * 
341  */
342 void can_bus_t::push_new_vehicle_message(const openxc_VehicleMessage& v_msg)
343 {
344         vehicle_message_q_.push(v_msg);
345         has_vehicle_message_ = true;
346 }
347
348 /**
349  * @brief Flag that let you know when vehicle message queue is exhausted
350  * 
351  * @return[bool] has_vehicle_message_ bool
352  */
353 bool can_bus_t::has_vehicle_message() const
354 {
355         return has_vehicle_message_;
356 }
357
358 /********************************************************************************
359 *
360 *               CanMessage method implementation
361 *
362 *********************************************************************************/
363
364 can_message_t::can_message_t(afb_binding_interface *itf)
365         : interface_{itf}
366 {}
367
368 uint32_t can_message_t::get_id() const
369 {
370         (id_ != 0) ? return id_ : return 0;
371 }
372
373 int can_message_t::get_format() const
374 {
375         (format_ != CanMessageFormat::SIMPLE || format_ != CanMessageFormat::EXTENDED) return -1 : return format_;
376 }
377
378 uint8_t can_message_t::get_data() const
379 {
380         return data_;
381 }
382 uint8_t can_message_t::get_lenght() const
383 {
384         return lenght_;
385 }
386
387 void can_message_t::set_id(uint32_t &new_id)
388 {
389         switch(format):
390                 case CanMessageFormat::SIMPLE:
391                         id = new_id & CAN_SFF_MASK;
392                 case CanMessageFormat::EXTENDED:
393                         id = new_id & CAN_EFF_MASK;
394                 default:
395                         ERROR(interface_, "ERROR: Can set id, not a compatible format or format not set prior to set id.");
396 }
397
398 void can_message_t::set_format(CanMessageFormat &new_format)
399 {
400         if(new_format == CanMessageFormat::SIMPLE || new_format == CanMessageFormat::EXTENDED)
401                 format = new_format;
402         else
403                 ERROR(interface_, "ERROR: Can set format, wrong format chosen");
404 }
405
406 void can_message_t::set_data(uint8_t &new_data)
407 {
408         ::memcpy(data_, new_data, new_data.size());
409         lenght_ = new_data(size);
410 }
411
412 /*
413  * This is the preferred way to initialize a CanMessage object 
414  * from a read canfd_frame message.
415  * 
416  * params: canfd_frame pointer
417  */
418 void can_message_t::convert_from_canfd_frame(canfd_frame &frame)
419 {
420         lenght_ = (frame.len > CAN_MAX_DLEN) ? CAN_MAX_DLEN : frame.len;
421         lenght_ = (frame.len > CANFD_MAX_DLEN) ? CANFD_MAX_DLEN : frame.len;
422
423         switch (frame.can_id): 
424                 case (frame.can_id & CAN_ERR_FLAG):
425                         id_ = frame.can_id & (CAN_ERR_MASK|CAN_ERR_FLAG);
426                         break;
427                 case (frame.can_id & CAN_EFF_FLAG):
428                         id_ = frame.can_id & CAN_EFF_MASK;
429                         format_ = CanMessageFormat::EXTENDED;
430                         break;
431                 default:
432                         format_ = CanMessageFormat::STANDARD;
433                         id_ = frame.can_id & CAN_SFF_MASK;
434                         break;
435
436         if (sizeof(frame.data) <= data_.size())
437         {
438                 ::memcpy(data_, canfd_frame.data, lenght_);
439                 return 0;
440         } else if (sizeof(frame.data) >= CAN_MAX_DLEN)
441                 ERROR(interface_, "can_message_t: canfd_frame data too long to be stored into CanMessage object");
442 }
443
444 canfd_frame convert_to_canfd_frame()
445 {
446         canfd_frame frame;
447
448         frame.can_id = get_id();
449         frame.len = get_lenght();
450         ::memcpy(frame.data, get_data(), lenght_);
451
452         return frame;
453 }