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