Dumb struct to class conversion
[apps/low-level-can-service.git] / low-can-binding.cpp
1 /*
2  * Copyright (C) 2015, 2016 "IoT.bzh"
3  * Author "Romain Forlot" <romain.forlot@iot.bzh>
4  * Author "Loic Collignon" <loic.collignon@iot.bzh>
5  *
6  * Licensed under the Apache License, Version 2.0 (the "License");
7  * you may not use this file except in compliance with the License.
8  * You may obtain a copy of the License at
9  *
10  *   http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software
13  * distributed under the License is distributed on an "AS IS" BASIS,
14  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  * See the License for the specific language governing permissions and
16  * limitations under the License.
17  */
18
19 #include <unistd.h>
20 #include <sys/types.h>
21 #include <sys/socket.h>
22 #include <sys/ioctl.h>
23 #include <net/if.h>
24 #include <linux/can.h>
25 #include <linux/can/raw.h>
26 #include <fcntl.h>
27 #include <systemd/sd-event.h>
28 #include <errno.h>
29 #include <vector>
30 #include <map>
31 #include <queue>
32 #include <string>
33 #include <functional>
34 #include <memory>
35 #include <thread>
36
37 #include <json-c/json.h>
38 #include <openxc.pb.h>
39
40 #include <afb/afb-binding.h>
41 #include <afb/afb-service-itf.h>
42
43 #include "ll-can-binding.h"
44 #include "obd2.h"
45
46 /*
47  *   Interface between the daemon and the binding
48  */
49 static const struct afb_binding_interface *interface;
50
51 /********************************************************************************
52 *
53 *               CanBus method implementation
54 *
55 *********************************************************************************/
56
57 int CanBus::open()
58 {
59         const int canfd_on = 1;
60         struct ifreq ifr;
61         struct timeval timeout = {1, 0};
62
63         DEBUG(interface, "open_can_dev: CAN Handler socket : %d", socket);
64         if (socket >= 0)
65                 close(socket);
66
67         socket = socket(PF_CAN, SOCK_RAW, CAN_RAW);
68         if (socket < 0)
69         {
70                 ERROR(interface, "open_can_dev: socket could not be created");
71         }
72         else
73         {
74                 /* Set timeout for read */
75                 setsockopt(socket, SOL_SOCKET, SO_RCVTIMEO, (char *)&timeout, sizeof(timeout));
76                 /* try to switch the socket into CAN_FD mode */
77                 if (setsockopt(socket, SOL_CAN_RAW, CAN_RAW_FD_FRAMES, &canfd_on, sizeof(canfd_on)) < 0)
78                 {
79                         NOTICE(interface, "open_can_dev: Can not switch into CAN Extended frame format.");
80                         is_fdmode_on = false;
81                 } else {
82                         is_fdmode_on = true;
83                 }
84
85                 /* Attempts to open a socket to CAN bus */
86                 strcpy(ifr.ifr_name, device);
87                 if(ioctl(socket, SIOCGIFINDEX, &ifr) < 0)
88                         ERROR(interface, "open_can_dev: ioctl failed");
89                 else
90                 {
91                         txAddress.can_family = AF_CAN;
92                         txAddress.can_ifindex = ifr.ifr_ifindex;
93
94                         /* And bind it to txAddress */
95                         if (bind(socket, (struct sockaddr *)&txAddress, sizeof(txAddress)) < 0)
96                         {
97                                 ERROR(interface, "open_can_dev: bind failed");
98                         }
99                         else
100                         {
101                                 fcntl(socket, F_SETFL, O_NONBLOCK);
102                                 return 0;
103                         }
104                 }
105                 close(socket);
106                 socket = -1;
107         }
108         return -1;
109 }
110
111 int CanBus::close()
112 {
113         close(socket);
114         socket = -1;
115 }
116
117 void CanBus::start_threads()
118 {
119     std::queue <canfd_frame> canfd_frame_queue;
120     std::queue <openxc_can_message_type> can_message_queue;
121
122     th_reading = std::thread(can_reader, interface, socket, canfd_frame_queue);
123     th_decoding = std::thread(can_decoder, interface, canfd_frame_queue, can_message_queue);
124     th_pushing = std::thread(can_event_push, interface, can_message_queue);
125 }
126
127 /********************************************************************************
128 *
129 *               Event management
130 *
131 *********************************************************************************/
132
133 /*
134  * TBF TBF TBF
135  * called on an event on the CAN bus
136  */
137 static int on_event(sd_event_source *s, int fd, uint32_t revents, void *userdata)
138 {
139         openxc_CanMessage can_message;
140
141         can_message = openxc_CanMessage_init_default;
142
143         /* read available data */
144         if ((revents & EPOLLIN) != 0)
145         {
146                 read_can(&can_message);
147                 send_event();
148         }
149
150         /* check if error or hangup */
151         if ((revents & (EPOLLERR|EPOLLRDHUP|EPOLLHUP)) != 0)
152         {
153                 sd_event_source_unref(s);
154                 close(fd);
155                 connect_to_event_loop();
156         }
157
158         return 0;
159 }
160
161 /*
162  * Get the event loop running.
163  * Will trigger on_event function on EPOLLIN event on socket
164  *
165  * Return 0 or positive value on success. Else negative value for failure.
166  */
167 static int connect_to_event_loop(CanBus &CanBus_handler)
168 {
169         sd_event *event_loop;
170         sd_event_source *source;
171         int rc;
172
173         if (CanBus_handler.socket < 0)
174         {
175                 return CanBus_handler.socket;
176         }
177
178         event_loop = afb_daemon_get_event_loop(interface->daemon);
179         rc = sd_event_add_io(event_loop, &source, CanBus_handler.socket, EPOLLIN, on_event, NULL);
180         if (rc < 0)
181         {
182                 CanBus_handler.close();
183                 ERROR(interface, "Can't connect CAN bus %s to the event loop", CanBus_handler.device);
184         } else
185         {
186                 NOTICE(interface, "Connected CAN bus %s to the event loop", CanBus_handler.device);
187         }
188
189         return rc;
190 }
191
192 /********************************************************************************
193 *
194 *               Subscription and unsubscription
195 *
196 *********************************************************************************/
197
198 static int subscribe_unsubscribe_sig(struct afb_req request, int subscribe, struct signal *sig)
199 {
200         if (!afb_event_is_valid(sig->event)) {
201                 if (!subscribe)
202                         return 1;
203                 sig->event = afb_daemon_make_event(afbitf->daemon, sig->name);
204                 if (!afb_event_is_valid(sig->event)) {
205                         return 0;
206                 }
207         }
208
209         if (((subscribe ? afb_req_subscribe : afb_req_unsubscribe)(request, sig->event)) < 0) {
210                 return 0;
211         }
212
213         return 1;
214 }
215
216 static int subscribe_unsubscribe_all(struct afb_req request, int subscribe)
217 {
218         int i, n, e;
219
220         n = sizeof OBD2_PIDS / sizeof * OBD2_PIDS;
221         e = 0;
222         for (i = 0 ; i < n ; i++)
223                 e += !subscribe_unsubscribe_sig(request, subscribe, &OBD2_PIDS[i]);
224         return e == 0;
225 }
226
227 static int subscribe_unsubscribe_name(struct afb_req request, int subscribe, const char *name)
228 {
229         struct signal *sig;
230
231         if (0 == strcmp(name, "*"))
232                 return subscribe_unsubscribe_all(request, subscribe);
233
234         sig = getsig(name);
235         if (sig == NULL) {
236                 return 0;
237         }
238
239         return subscribe_unsubscribe_sig(request, subscribe, sig);
240 }
241
242 static void subscribe_unsubscribe(struct afb_req request, int subscribe)
243 {
244         int ok, i, n;
245         struct json_object *args, *a, *x;
246
247         /* makes the subscription/unsubscription */
248         args = afb_req_json(request);
249         if (args == NULL || !json_object_object_get_ex(args, "event", &a)) {
250                 ok = subscribe_unsubscribe_all(request, subscribe);
251         } else if (json_object_get_type(a) != json_type_array) {
252                 ok = subscribe_unsubscribe_name(request, subscribe, json_object_get_string(a));
253         } else {
254                 n = json_object_array_length(a);
255                 ok = 0;
256                 for (i = 0 ; i < n ; i++) {
257                         x = json_object_array_get_idx(a, i);
258                         if (subscribe_unsubscribe_name(request, subscribe, json_object_get_string(x)))
259                                 ok++;
260                 }
261                 ok = (ok == n);
262         }
263
264         /* send the report */
265         if (ok)
266                 afb_req_success(request, NULL, NULL);
267         else
268                 afb_req_fail(request, "error", NULL);
269 }
270
271 static void subscribe(struct afb_req request)
272 {
273         subscribe_unsubscribe(request, 1);
274 }
275
276 static void unsubscribe(struct afb_req request)
277 {
278         subscribe_unsubscribe(request, 0);
279 }
280 static const struct afb_verb_desc_v1 verbs[]=
281 {
282   { .name= "subscribe",    .session= AFB_SESSION_NONE, .callback= subscribe,    .info= "subscribe to notification of CAN bus messages." },
283   { .name= "unsubscribe",  .session= AFB_SESSION_NONE, .callback= unsubscribe,  .info= "unsubscribe a previous subscription." },
284         {NULL}
285 };
286
287 static const struct afb_binding binding_desc = {
288         .type = AFB_BINDING_VERSION_1,
289         .v1 = {
290                 .info = "CAN bus service",
291                 .prefix = "can",
292                 .verbs = verbs
293         }
294 };
295
296 const struct afb_binding *afbBindingV1Register (const struct afb_binding_interface *itf)
297 {
298         interface = itf;
299
300         return &binding_desc;
301 }
302
303 int afbBindingV1ServiceInit(struct afb_service service)
304 {
305         /* Open JSON conf file */
306
307         /* Open CAN socket */
308         CanBus CanBus_handler;
309         CanBus_handler.open();
310     CanBus_handler.start_threads();
311
312         return connect_to_event_loop(CanBus_handler);
313 }