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