Rename header file to hpp.
[apps/agl-service-can-low-level.git] / src / 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 "obd2.hpp"
44
45 /*
46  *       Interface between the daemon and the binding
47  */
48 static const struct afb_binding_interface *interface;
49
50 /********************************************************************************
51 *
52 *               Event management
53 *
54 *********************************************************************************/
55
56 /*
57  * TBF TBF TBF
58  * called on an event on the CAN bus
59  */
60 static int on_event(sd_event_source *s, int fd, uint32_t revents, void *userdata)
61 {
62         openxc_CanMessage can_message;
63
64         can_message = openxc_CanMessage_init_default;
65
66         /* read available data */
67         if ((revents & EPOLLIN) != 0)
68         {
69                 read_can(&can_message);
70                 send_event();
71         }
72
73         /* check if error or hangup */
74         if ((revents & (EPOLLERR|EPOLLRDHUP|EPOLLHUP)) != 0)
75         {
76                 sd_event_source_unref(s);
77                 close(fd);
78                 connect_to_event_loop();
79         }
80
81         return 0;
82 }
83
84 /*
85  * USELESS SINCE THREADS SEPARATION
86  *
87  * Get the event loop running.
88  * Will trigger on_event function on EPOLLIN event on socket
89  *
90  * Return 0 or positive value on success. Else negative value for failure.
91 static int connect_to_event_loop(CanBus &CanBus_handler)
92 {
93         sd_event *event_loop;
94         sd_event_source *source;
95         int rc;
96
97         if (CanBus_handler.socket < 0)
98         {
99                 return CanBus_handler.socket;
100         }
101
102         event_loop = afb_daemon_get_event_loop(interface->daemon);
103         rc = sd_event_add_io(event_loop, &source, CanBus_handler.socket, EPOLLIN, on_event, NULL);
104         if (rc < 0)
105         {
106                 CanBus_handler.close();
107                 ERROR(interface, "Can't connect CAN bus %s to the event loop", CanBus_handler.device);
108         } else
109         {
110                 NOTICE(interface, "Connected CAN bus %s to the event loop", CanBus_handler.device);
111         }
112
113         return rc;
114 }
115  */
116
117 /********************************************************************************
118 *
119 *               Subscription and unsubscription
120 *
121 *********************************************************************************/
122
123 static int subscribe_unsubscribe_signal(struct afb_req request, int subscribe, std::map<CanSignal, struct afb_event>::iterator *s_sig)
124  {
125         if (!afb_event_is_valid(s_sig->second)) {
126                 if (!subscribe)
127                         return 1;
128                 sig->event = afb_daemon_make_event(afbitf->daemon, s_sig->first->genericName);
129                 if (!afb_event_is_valid(s_sig->second)) {
130                         return 0;
131                 }
132         }
133
134         if (((subscribe ? afb_req_subscribe : afb_req_unsubscribe)(request, s_sig->second)) < 0) {
135                 return 0;
136         }
137
138         return 1;
139  }
140
141 static int subscribe_unsubscribe_signals(struct afb_req request, int subscribe, std:vector<CanSignal> *signals)
142 {
143         std::vector<CanSignal>::iterator signal_i;
144         std::map <CanSignal, struct afb_event>::iterator s_signal_i;
145         
146         for(signal_i=signals.begin(); signal_i != signals.end(); signal_i++)
147         {
148                 s_signal_i = subscribed_signals.find(signal_i);
149                 if(s_signal_i != subscribed_signals.end())
150                         subscribe_unsubscribe_signal(request, subscribe, s_signal_i);
151                 else
152                 {
153                         std::map <CanSignal, struct afb_event>::iterator it = subscribed_signals.begin();
154                         it = subscribed_signals.insert(it, std::pair<CanSignal, struct afb_event>(signal_i, NULL);
155                         subscribe_unsubscribe_signal(request, subscribe, it);
156                 }
157                 return 0;
158         }
159 }
160
161 static int subscribe_unsubscribe_all(struct afb_req request, int subscribe)
162 {
163         int i, n, e;
164
165         n = sizeof OBD2_PIDS / sizeof * OBD2_PIDS;
166         e = 0;
167         for (i = 0 ; i < n ; i++)
168                 e += !subscribe_unsubscribe_sig(request, subscribe, &OBD2_PIDS[i]);
169         return e == 0;
170 }
171
172 static int subscribe_unsubscribe_name(struct afb_req request, int subscribe, const char *name)
173 {
174          std::vector <CanSignal> *sig;
175
176         if (0 == strcmp(name, "*"))
177                 return subscribe_unsubscribe_all(request, subscribe);
178
179         if(obd2_handler_c.is_obd2_signal(name))
180
181         else
182                 find_can_signals(name, sig);
183         if (sig == NULL) {
184                 return 0;
185         }
186
187         return subscribe_unsubscribe_sig(request, subscribe, sig);
188 }
189
190 static void subscribe_unsubscribe(struct afb_req request, int subscribe)
191 {
192         int ok, i, n;
193         struct json_object *args, *a, *x;
194
195         /* makes the subscription/unsubscription */
196         args = afb_req_json(request);
197         if (args == NULL || !json_object_object_get_ex(args, "event", &a)) {
198                 ok = subscribe_unsubscribe_all(request, subscribe);
199         } else if (json_object_get_type(a) != json_type_array) {
200                 ok = subscribe_unsubscribe_name(request, subscribe, json_object_get_string(a));
201         } else {
202                 n = json_object_array_length(a);
203                 ok = 0;
204                 for (i = 0 ; i < n ; i++) {
205                         x = json_object_array_get_idx(a, i);
206                         if (subscribe_unsubscribe_name(request, subscribe, json_object_get_string(x)))
207                                 ok++;
208                 }
209                 ok = (ok == n);
210         }
211
212         /* send the report */
213         if (ok)
214                 afb_req_success(request, NULL, NULL);
215         else
216                 afb_req_fail(request, "error", NULL);
217 }
218
219 static void subscribe(struct afb_req request)
220 {
221         subscribe_unsubscribe(request, 1);
222 }
223
224 static void unsubscribe(struct afb_req request)
225 {
226         subscribe_unsubscribe(request, 0);
227 }
228 static const struct afb_verb_desc_v1 verbs[]=
229 {
230   { .name= "subscribe",    .session= AFB_SESSION_NONE, .callback= subscribe,    .info= "subscribe to notification of CAN bus messages." },
231   { .name= "unsubscribe",  .session= AFB_SESSION_NONE, .callback= unsubscribe,  .info= "unsubscribe a previous subscription." },
232         {NULL}
233 };
234
235 static const struct afb_binding binding_desc = {
236         .type = AFB_BINDING_VERSION_1,
237         .v1 = {
238                 .info = "CAN bus service",
239                 .prefix = "can",
240                 .verbs = verbs
241         }
242 };
243
244 const struct afb_binding *afbBindingV1Register (const struct afb_binding_interface *itf)
245 {
246         interface = itf;
247
248         return &binding_desc;
249 }
250
251 /**
252  * @brief Initialize the binding.
253  * 
254  * @param[in] service Structure which represent the Application Framework Binder.
255  * 
256  * @return Exit code, zero if success.
257  */
258 int afbBindingV1ServiceInit(struct afb_service service)
259 {
260         std::ifstream fd_conf;
261         std::string fd_conf_content;
262         json_object jo_canbus;
263
264         /* Open JSON conf file */
265         jo_canbus = json_object_new_object();
266         fd_conf = afb_daemon_rootdir_open_locale(interface->daemon, "canbus.json", O_RDONLY, NULL);
267         if (fd_conf)
268         {
269                 fd_conf.seekg(0, std::ios::end);
270                 fd_conf_content.resize(fd_conf.tellg());
271                 fd_conf.seekg(0, std::ios::beg);
272                 fd_conf.read(&fd_conf_content[0], fd_conf_content.size());
273                 fd_conf.close();
274         }
275
276         jo_canbus = json_tokener_parse(&fd_conf_content);
277
278         /* Open CAN socket */
279         can_bus_t CanBus_handler(interface, json_object_get_string(json_object_object_get(jo_canbus, "deviceName"));
280         CanBus_handler.open();
281         CanBus_handler.start_threads();
282 }