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