Update doc revision and pdf cover.
[apps/low-level-can-service.git] / CAN-binder / low-can-binding / binding / low-can-cb.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 "low-can-hat.hpp"
20
21 #include <map>
22 #include <queue>
23 #include <mutex>
24 #include <vector>
25 #include <thread>
26 #include <json-c/json.h>
27 #include <systemd/sd-event.h>
28
29 #include "openxc.pb.h"
30 #include "application.hpp"
31 #include "../can/can-bus.hpp"
32 #include "../can/can-signals.hpp"
33 #include "../can/can-message.hpp"
34 #include "../utils/signals.hpp"
35 #include "../diagnostic/diagnostic-message.hpp"
36 #include "../utils/openxc-utils.hpp"
37
38
39 ///******************************************************************************
40 ///
41 ///             SystemD event loop Callbacks
42 ///
43 ///*******************************************************************************/
44
45 void on_no_clients(std::shared_ptr<low_can_subscription_t> can_subscription, uint32_t pid, std::map<int, std::shared_ptr<low_can_subscription_t> >& s)
46 {
47         if( ! can_subscription->get_diagnostic_message().empty() && can_subscription->get_diagnostic_message(pid) != nullptr)
48         {
49                 DiagnosticRequest diag_req = can_subscription->get_diagnostic_message(pid)->build_diagnostic_request();
50                 active_diagnostic_request_t* adr = application_t::instance().get_diagnostic_manager().find_recurring_request(diag_req);
51                 if( adr != nullptr)
52                         application_t::instance().get_diagnostic_manager().cleanup_request(adr, true);
53         }
54
55         on_no_clients(can_subscription, s);
56 }
57
58 void on_no_clients(std::shared_ptr<low_can_subscription_t> can_subscription, std::map<int, std::shared_ptr<low_can_subscription_t> >& s)
59 {
60         auto it = s.find(can_subscription->get_index());
61         s.erase(it);
62 }
63
64 static void push_n_notify(const can_message_t& cm)
65 {
66         can_bus_t& cbm = application_t::instance().get_can_bus_manager();
67         {
68                 std::lock_guard<std::mutex> can_message_lock(cbm.get_can_message_mutex());
69                 cbm.push_new_can_message(cm);
70         }
71         cbm.get_new_can_message_cv().notify_one();
72 }
73
74 int read_message(sd_event_source *event_source, int fd, uint32_t revents, void *userdata)
75 {
76         low_can_subscription_t* can_subscription = (low_can_subscription_t*)userdata;
77         if ((revents & EPOLLIN) != 0)
78         {
79                 can_message_t cm;
80                 utils::socketcan_bcm_t& s = can_subscription->get_socket();
81                 s >> cm;
82
83                 // Sure we got a valid CAN message ?
84                 if(! cm.get_id() == 0 && ! cm.get_length() == 0)
85                         {push_n_notify(cm);}
86         }
87
88         // check if error or hangup
89         if ((revents & (EPOLLERR|EPOLLRDHUP|EPOLLHUP)) != 0)
90         {
91                 sd_event_source_unref(event_source);
92                 can_subscription->get_socket().close();
93         }
94         return 0;
95 }
96
97 ///******************************************************************************
98 ///
99 ///             Subscription and unsubscription
100 ///
101 ///*******************************************************************************/
102
103 static int make_subscription_unsubscription(struct afb_req request, std::shared_ptr<low_can_subscription_t>& can_subscription, std::map<int, std::shared_ptr<low_can_subscription_t> >& s, bool subscribe)
104 {
105         /* Make the subscription or unsubscription to the event */
106         if (((subscribe ? afb_req_subscribe : afb_req_unsubscribe)(request, s[can_subscription->get_index()]->get_event())) < 0)
107         {
108                 ERROR("Operation goes wrong for signal: %s", can_subscription->get_name().c_str());
109                 return -1;
110         }
111         return 0;
112 }
113
114 static int create_event_handle(std::shared_ptr<low_can_subscription_t>& can_subscription, std::map<int, std::shared_ptr<low_can_subscription_t> >& s)
115 {
116         int sub_index = can_subscription->get_index();
117         can_subscription->set_event(afb_daemon_make_event(can_subscription->get_name().c_str()));
118         s[sub_index] = can_subscription;
119         if (!afb_event_is_valid(s[sub_index]->get_event()))
120         {
121                 ERROR("Can't create an event for %s, something goes wrong.", can_subscription->get_name().c_str());
122                 return -1;
123         }
124         return 0;
125 }
126
127 /// @brief Will determine if it is needed or not to create the event handle and checks it to be sure that
128 /// we got a valid afb_event to get subscribe or unsubscribe. Then launch the subscription or unsubscription
129 /// against the application framework using that event handle.
130 static int subscribe_unsubscribe_signal(struct afb_req request, bool subscribe, std::shared_ptr<low_can_subscription_t>& can_subscription, std::map<int, std::shared_ptr<low_can_subscription_t> >& s)
131 {
132         int ret = -1;
133         int sub_index = can_subscription->get_index();
134
135         if (can_subscription && s.find(sub_index) != s.end())
136         {
137                 if (!afb_event_is_valid(s[sub_index]->get_event()) && !subscribe)
138                 {
139                         NOTICE("Event isn't valid, no need to unsubscribed.");
140                         ret = -1;
141                 }
142                 ret = 0;
143         }
144         else
145         {
146                 /* Event doesn't exist , so let's create it */
147                 can_subscription->set_event({nullptr, nullptr});
148                 s[sub_index] = can_subscription;
149                 ret = create_event_handle(can_subscription, s);
150         }
151
152         // Check whether or not the event handler has been correctly created and
153         // make the subscription/unsubscription operation is so.
154         if (ret < 0)
155                 return ret;
156         return make_subscription_unsubscription(request, can_subscription, s, subscribe);
157 }
158
159 static int add_to_event_loop(std::shared_ptr<low_can_subscription_t>& can_subscription)
160 {
161                 struct sd_event_source* event_source = nullptr;
162                 return ( sd_event_add_io(afb_daemon_get_event_loop(),
163                         &event_source,
164                         can_subscription->get_socket().socket(),
165                         EPOLLIN,
166                         read_message,
167                         can_subscription.get()));
168 }
169
170 static int subscribe_unsubscribe_diagnostic_messages(struct afb_req request, bool subscribe, std::vector<std::shared_ptr<diagnostic_message_t> > diagnostic_messages, struct event_filter_t& event_filter, std::map<int, std::shared_ptr<low_can_subscription_t> >& s)
171 {
172         int rets = 0;
173         application_t& app = application_t::instance();
174         diagnostic_manager_t& diag_m = app.get_diagnostic_manager();
175
176         for(const auto& sig : diagnostic_messages)
177         {
178                 DiagnosticRequest* diag_req = new DiagnosticRequest(sig->build_diagnostic_request());
179                 event_filter.frequency = std::isnan(event_filter.frequency) ? sig->get_frequency() : event_filter.frequency;
180                 std::shared_ptr<low_can_subscription_t> can_subscription;
181
182                 auto it =  std::find_if(s.begin(), s.end(), [&sig](std::pair<int, std::shared_ptr<low_can_subscription_t> > sub){ return (! sub.second->get_diagnostic_message().empty());});
183                 can_subscription = it != s.end() ?
184                         it->second : 
185                         std::make_shared<low_can_subscription_t>(low_can_subscription_t(event_filter));
186                 // If the requested diagnostic message isn't supported by the car then unsubcribe it
187                 // no matter what we want, worse case will be a fail unsubscription but at least we don't
188                 // poll a PID for nothing.
189                 //TODO: Adding callback requesting ignition status:     diag_req, sig.c_str(), false, diagnostic_message_t::decode_obd2_response, diagnostic_message_t::check_ignition_status, frequency);
190                 if(sig->get_supported() && subscribe)
191                 {
192                         diag_m.add_recurring_request(diag_req, sig->get_name().c_str(), false, sig->get_decoder(), sig->get_callback(), event_filter.frequency);
193                         if(can_subscription->create_rx_filter(sig) < 0)
194                                 {return -1;}
195                         DEBUG("Signal: %s subscribed", sig->get_name().c_str());
196                         if(it == s.end() && add_to_event_loop(can_subscription) < 0)
197                         {
198                                 diag_m.cleanup_request(
199                                         diag_m.find_recurring_request(*diag_req), true);
200                                 WARNING("signal: %s isn't supported. Canceling operation.",  sig->get_name().c_str());
201                                 return -1;
202                         }
203                 }
204                 else
205                 {
206                         if(sig->get_supported())
207                         {DEBUG("%s cancelled due to unsubscribe", sig->get_name().c_str());}
208                         else
209                         {
210                                 WARNING("signal: %s isn't supported. Canceling operation.", sig->get_name().c_str());
211                                 return -1;
212                         }
213                 }
214                 int ret = subscribe_unsubscribe_signal(request, subscribe, can_subscription, s);
215                 if(ret < 0)
216                         return ret;
217
218                 rets++;
219         }
220
221         return rets;
222 }
223
224 static int subscribe_unsubscribe_can_signals(struct afb_req request, bool subscribe, std::vector<std::shared_ptr<can_signal_t> > can_signals, struct event_filter_t& event_filter, std::map<int, std::shared_ptr<low_can_subscription_t> >& s)
225 {
226         int rets = 0;
227         for(const auto& sig: can_signals)
228         {
229                 auto it =  std::find_if(s.begin(), s.end(), [&sig](std::pair<int, std::shared_ptr<low_can_subscription_t> > sub){ return sub.second->get_can_signal() == sig; });
230                 std::shared_ptr<low_can_subscription_t> can_subscription;
231                 if(it != s.end())
232                 {
233                          can_subscription = it->second;
234                 }
235                 else
236                 {
237                          can_subscription = std::make_shared<low_can_subscription_t>(low_can_subscription_t(event_filter));
238                         if(can_subscription->create_rx_filter(sig) < 0)
239                                 {return -1;}
240                         if(add_to_event_loop(can_subscription) < 0)
241                                 {return -1;}
242                 }
243
244                 if(subscribe_unsubscribe_signal(request, subscribe, can_subscription, s) < 0)
245                         {return -1;}
246
247                 rets++;
248                 DEBUG("signal: %s subscribed", sig->get_name().c_str());
249         }
250         return rets;
251 }
252
253 ///
254 /// @brief subscribe to all signals in the vector signals
255 ///
256 /// @param[in] afb_req request : contain original request use to subscribe or unsubscribe
257 /// @param[in] subscribe boolean value used to chose between a subscription operation or an unsubscription
258 /// @param[in] signals -  struct containing vectors with can_signal_t and diagnostic_messages to subscribe
259 ///
260 /// @return Number of correctly subscribed signal
261 ///
262 static int subscribe_unsubscribe_signals(struct afb_req request, bool subscribe, const struct utils::signals_found& signals, struct event_filter_t& event_filter)
263 {
264         int rets = 0;
265         utils::signals_manager_t& sm = utils::signals_manager_t::instance();
266
267         std::lock_guard<std::mutex> subscribed_signals_lock(sm.get_subscribed_signals_mutex());
268         std::map<int, std::shared_ptr<low_can_subscription_t> >& s = sm.get_subscribed_signals();
269
270         rets += subscribe_unsubscribe_diagnostic_messages(request, subscribe, signals.diagnostic_messages, event_filter, s);
271         rets += subscribe_unsubscribe_can_signals(request, subscribe, signals.can_signals, event_filter, s);
272
273         return rets;
274 }
275
276 static int one_subscribe_unsubscribe(struct afb_req request, bool subscribe, const std::string& tag, json_object* args)
277 {
278         int ret = 0;
279         struct event_filter_t event_filter;
280         struct json_object  *filter, *obj;
281         struct utils::signals_found sf;
282
283         // computes the filter
284         if (json_object_object_get_ex(args, "filter", &filter))
285         {
286                 if (json_object_object_get_ex(filter, "frequency", &obj)
287                 && (json_object_is_type(obj, json_type_double) || json_object_is_type(obj, json_type_int)))
288                 {
289                         event_filter.frequency = (float)json_object_get_double(obj);
290                         ret += 1;
291                 }
292                 if (json_object_object_get_ex(filter, "min", &obj)
293                 && (json_object_is_type(obj, json_type_double) || json_object_is_type(obj, json_type_int)))
294                 {
295                         event_filter.min = (float)json_object_get_double(obj);
296                         ret += 2;
297                 }
298                 if (json_object_object_get_ex(filter, "max", &obj)
299                 && (json_object_is_type(obj, json_type_double) || json_object_is_type(obj, json_type_int)))
300                 {
301                         event_filter.max = (float)json_object_get_double(obj);
302                         ret += 4;
303                 }
304         }
305
306         // subscribe or unsubscribe
307         openxc_DynamicField search_key = build_DynamicField(tag);
308         sf = utils::signals_manager_t::instance().find_signals(search_key);
309         if (sf.can_signals.empty() && sf.diagnostic_messages.empty())
310                 NOTICE("No signal(s) found for %s.", tag.c_str());
311         else
312                 ret = subscribe_unsubscribe_signals(request, subscribe, sf, event_filter);
313
314         return ret;
315 }
316
317 static void do_subscribe_unsubscribe(struct afb_req request, bool subscribe)
318 {
319         int i, n, rc, rc2;
320         struct json_object *args, *event, *x;
321
322         args = afb_req_json(request);
323         if (args == NULL || !json_object_object_get_ex(args, "event", &event))
324         {
325                 rc = one_subscribe_unsubscribe(request, subscribe, "*", args);
326         }
327         else if (json_object_get_type(event) != json_type_array)
328         {
329                 rc = one_subscribe_unsubscribe(request, subscribe, json_object_get_string(event), args);
330         }
331         else
332         {
333                 rc = 0;
334                 n = json_object_array_length(event);
335                 for (i = 0 ; i < n ; i++)
336                 {
337                         x = json_object_array_get_idx(event, i);
338                         rc2 = one_subscribe_unsubscribe(request, subscribe, json_object_get_string(x), args);
339                         if (rc >= 0)
340                                 rc = rc2 >= 0 ? rc + rc2 : rc2;
341                 }
342         }
343
344         if (rc >= 0)
345                 afb_req_success(request, NULL, NULL);
346         else
347                 afb_req_fail(request, "error", NULL);
348 }
349
350 void subscribe(struct afb_req request)
351 {
352         do_subscribe_unsubscribe(request, true);
353 }
354
355 void unsubscribe(struct afb_req request)
356 {
357         do_subscribe_unsubscribe(request, false);
358 }