Re-arranging objects splitting all objects over
[apps/low-level-can-service.git] / src / can-bus.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-bus.hpp"
19
20 #include <map>
21 #include <vector>
22 #include <string>
23 #include <fcntl.h>
24 #include <unistd.h>
25 #include <net/if.h>
26 #include <sys/ioctl.h>
27 #include <sys/socket.h>
28 #include <json-c/json.h>
29 #include <linux/can/raw.h>
30
31 extern "C"
32 {
33         #include <afb/afb-binding.h>
34 }
35
36 /********************************************************************************
37 *
38 *               can_bus_t method implementation
39 *
40 *********************************************************************************/
41
42 can_bus_t::can_bus_t(int& conf_file)
43         : conf_file_{conf_file}
44 {
45 }
46
47 void can_bus_t::start_threads()
48 {
49         th_decoding_ = std::thread(can_decode_message, std::ref(*this));
50         is_decoding_ = true;
51         th_pushing_ = std::thread(can_event_push, std::ref(*this));
52         is_pushing_ = true;
53 }
54
55 void can_bus_t::stop_threads()
56 {
57         is_decoding_ = false;
58         is_pushing_ = false;
59 }
60
61 bool can_bus_t::is_decoding()
62 {
63         return is_decoding_;
64 }
65
66 bool can_bus_t::is_pushing()
67 {
68         return is_pushing_;
69 }
70
71 int can_bus_t::init_can_dev()
72 {
73         std::vector<std::string> devices_name;
74         int i;
75         size_t t;
76
77         devices_name = read_conf();
78
79         if (! devices_name.empty())
80         {
81                 t = devices_name.size();
82                 i=0;
83
84                 for(const auto& device : devices_name)
85                 {
86                         can_bus_dev_t can_bus_device_handler(device);
87                         if (can_bus_device_handler.open())
88                         {
89                                 i++;
90                                 can_bus_device_handler.start_reading(std::ref(*this));
91                         }
92                         else
93                                 ERROR(binder_interface, "Can't open device %s", device);
94                 }
95
96                 NOTICE(binder_interface, "Initialized %d/%d can bus device(s)", i, t);
97                 return 0;
98         }
99         ERROR(binder_interface, "init_can_dev: Error at CAN device initialization. No devices read from configuration file. Did you specify canbus JSON object ?");
100         return 1;
101 }
102
103 std::vector<std::string> can_bus_t::read_conf()
104 {
105         std::vector<std::string> ret;
106         json_object *jo, *canbus;
107         int n, i;
108         const char* taxi;
109
110         FILE *fd = fdopen(conf_file_, "r");
111         if (fd)
112         {
113                 std::string fd_conf_content;
114                 std::fseek(fd, 0, SEEK_END);
115                 fd_conf_content.resize(std::ftell(fd));
116                 std::rewind(fd);
117                 std::fread(&fd_conf_content[0], 1, fd_conf_content.size(), fd);
118                 std::fclose(fd);
119
120                 DEBUG(binder_interface, "Conf file content : %s", fd_conf_content.c_str());
121                 jo = json_tokener_parse(fd_conf_content.c_str());
122
123                 if (jo == NULL || !json_object_object_get_ex(jo, "canbus", &canbus))
124                 {
125                         ERROR(binder_interface, "Can't find canbus node in the configuration file. Please review it.");
126                         ret.clear();
127                 }
128                 else if (json_object_get_type(canbus) != json_type_array)
129                 {
130                         taxi = json_object_get_string(canbus);
131                         DEBUG(binder_interface, "Can bus found: %s", taxi);
132                         ret.push_back(std::string(taxi));
133                 }
134                 else
135                 {
136                         n = json_object_array_length(canbus);
137                         for (i = 0 ; i < n ; i++)
138                                 ret.push_back(json_object_get_string(json_object_array_get_idx(canbus, i)));
139                 }
140                 return ret;
141         }
142         ERROR(binder_interface, "Problem at reading the conf file");
143         ret.clear();
144         return ret;
145 }
146
147 std::condition_variable& can_bus_t::get_new_can_message()
148 {
149         return new_can_message_;
150 }
151
152 std::mutex& can_bus_t::get_can_message_mutex()
153 {
154         return can_message_mutex_;
155 }
156
157 std::condition_variable& can_bus_t::get_new_decoded_can_message()
158 {
159         return new_decoded_can_message_;
160 }
161
162 std::mutex& can_bus_t::get_decoded_can_message_mutex()
163 {
164         return decoded_can_message_mutex_;
165 }
166
167 can_message_t can_bus_t::next_can_message()
168 {
169         can_message_t can_msg;
170
171         if(!can_message_q_.empty())
172         {
173                 can_msg = can_message_q_.front();
174                 can_message_q_.pop();
175                 DEBUG(binder_interface, "next_can_message: Here is the next can message : id %d, length %d", can_msg.get_id(), can_msg.get_length());
176                 return can_msg;
177         }
178         
179         NOTICE(binder_interface, "next_can_message: End of can message queue");
180         has_can_message_ = false;
181         return can_msg;
182 }
183
184 void can_bus_t::push_new_can_message(const can_message_t& can_msg)
185 {
186         can_message_q_.push(can_msg);
187 }
188
189 bool can_bus_t::has_can_message() const
190 {
191         return has_can_message_;
192 }
193
194 openxc_VehicleMessage can_bus_t::next_vehicle_message()
195 {
196         openxc_VehicleMessage v_msg;
197
198         if(! vehicle_message_q_.empty())
199         {
200                 v_msg = vehicle_message_q_.front();
201                 vehicle_message_q_.pop();
202                 DEBUG(binder_interface, "next_vehicle_message: next vehicle message poped");
203                 return v_msg;
204         }
205         
206         NOTICE(binder_interface, "next_vehicle_message: End of vehicle message queue");
207         has_vehicle_message_ = false;
208         return v_msg;
209 }
210
211 void can_bus_t::push_new_vehicle_message(const openxc_VehicleMessage& v_msg)
212 {
213         vehicle_message_q_.push(v_msg);
214         has_vehicle_message_ = true;
215 }
216
217 bool can_bus_t::has_vehicle_message() const
218 {
219         return has_vehicle_message_;
220 }
221
222 /********************************************************************************
223 *
224 *               can_bus_dev_t method implementation
225 *
226 *********************************************************************************/
227
228 can_bus_dev_t::can_bus_dev_t(const std::string &dev_name)
229         : device_name_{dev_name}
230 {
231 }
232
233 int can_bus_dev_t::open()
234 {
235         const int canfd_on = 1;
236         struct ifreq ifr;
237         struct timeval timeout = {1, 0};
238
239         DEBUG(binder_interface, "CAN Handler socket : %d", can_socket_);
240         if (can_socket_ >= 0)
241                 return 0;
242
243         can_socket_ = ::socket(PF_CAN, SOCK_RAW, CAN_RAW);
244         if (can_socket_ < 0)
245         {
246                 ERROR(binder_interface, "socket could not be created");
247         }
248         else
249         {
250                 /* Set timeout for read */
251                 ::setsockopt(can_socket_, SOL_SOCKET, SO_RCVTIMEO, (char *)&timeout, sizeof(timeout));
252                 /* try to switch the socket into CAN_FD mode */
253                 if (::setsockopt(can_socket_, SOL_CAN_RAW, CAN_RAW_FD_FRAMES, &canfd_on, sizeof(canfd_on)) < 0)
254                 {
255                         NOTICE(binder_interface, "Can not switch into CAN Extended frame format.");
256                         is_fdmode_on_ = false;
257                 } else {
258                         is_fdmode_on_ = true;
259                 }
260
261                 /* Attempts to open a socket to CAN bus */
262                 ::strcpy(ifr.ifr_name, device_name_.c_str());
263                 if(::ioctl(can_socket_, SIOCGIFINDEX, &ifr) < 0)
264                         ERROR(binder_interface, "ioctl failed");
265                 else
266                 {
267                         txAddress_.can_family = AF_CAN;
268                         txAddress_.can_ifindex = ifr.ifr_ifindex;
269
270                         /* And bind it to txAddress */
271                         if (::bind(can_socket_, (struct sockaddr *)&txAddress_, sizeof(txAddress_)) < 0)
272                                 ERROR(binder_interface, "Bind failed");
273                         else
274                                 return 0;
275                 }
276                 close();
277         }
278         return -1;
279 }
280
281 int can_bus_dev_t::close()
282 {
283         ::close(can_socket_);
284         can_socket_ = -1;
285         return can_socket_;
286 }
287
288 canfd_frame can_bus_dev_t::read()
289 {
290         ssize_t nbytes;
291         //int maxdlen;
292         canfd_frame canfd_frame;
293
294         /* Test that socket is really opened */
295         if (can_socket_ < 0)
296         {
297                 ERROR(binder_interface, "read_can: Socket unavailable. Closing thread.");
298                 is_running_ = false;
299         }
300
301         nbytes = ::read(can_socket_, &canfd_frame, CANFD_MTU);
302
303         switch(nbytes)
304         {
305                 case CANFD_MTU:
306                         DEBUG(binder_interface, "read_can: Got an CAN FD frame with length %d", canfd_frame.len);
307                         //maxdlen = CANFD_MAX_DLEN;
308                         break;
309                 case CAN_MTU:
310                         DEBUG(binder_interface, "read_can: Got a legacy CAN frame with length %d", canfd_frame.len);
311                         //maxdlen = CAN_MAX_DLEN;
312                         break;
313                 default:
314                         if (errno == ENETDOWN)
315                                         ERROR(binder_interface, "read_can: %s binder_interface down", device_name_);
316                         ERROR(binder_interface, "read_can: Error reading CAN bus");
317                         ::memset(&canfd_frame, 0, sizeof(canfd_frame));
318                         is_running_ = false;
319                         break;
320         }
321         
322         return canfd_frame;
323 }
324
325 void can_bus_dev_t::start_reading(can_bus_t& can_bus)
326 {
327         th_reading_ = std::thread(can_reader, std::ref(*this), std::ref(can_bus));
328         is_running_ = true;
329 }
330
331 /*
332  * Return is_running_ bool
333  */
334 bool can_bus_dev_t::is_running()
335 {
336         return is_running_;
337 }
338
339 int can_bus_dev_t::send_can_message(can_message_t& can_msg)
340 {
341         ssize_t nbytes;
342         canfd_frame f;
343
344         f = can_msg.convert_to_canfd_frame();
345
346         if(can_socket_ >= 0)
347         {
348                 nbytes = ::sendto(can_socket_, &f, sizeof(struct canfd_frame), 0,
349                                 (struct sockaddr*)&txAddress_, sizeof(txAddress_));
350                 if (nbytes == -1)
351                 {
352                         ERROR(binder_interface, "send_can_message: Sending CAN frame failed.");
353                         return -1;
354                 }
355                 return (int)nbytes;
356         }
357         else
358         {
359                 ERROR(binder_interface, "send_can_message: socket not initialized. Attempt to reopen can device socket.");
360                 open();
361         }
362         return 0;
363 }