Fix: Don't processing filter argument
[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/timer.hpp"
35 #include "../utils/signals.hpp"
36 #include "../diagnostic/diagnostic-message.hpp"
37 #include "../utils/openxc-utils.hpp"
38 #include "canutil/write.h"
39
40 extern "C"
41 {
42         #include <afb/afb-service-itf.h>
43 };
44
45 ///******************************************************************************
46 ///
47 ///     low_can_subscription_t object
48 ///
49 ///*******************************************************************************/
50
51 low_can_subscription_t::low_can_subscription_t()
52         : index_{-1},
53         event_filter_{event_filter_t()},
54         socket_{}
55 {}
56
57 low_can_subscription_t::low_can_subscription_t(struct event_filter_t event_filter)
58         : event_filter_{event_filter}
59 {}
60
61 low_can_subscription_t::low_can_subscription_t( low_can_subscription_t&& s)
62         : index_{s.index_},
63         event_filter_{s.event_filter_},
64         socket_{std::move(s.socket_)}
65 {}
66
67         low_can_subscription_t& low_can_subscription_t::operator=(const low_can_subscription_t& s)
68 {
69         socket_ = std::move(s.socket_);
70         return *this;
71 }
72
73 low_can_subscription_t::operator bool() const
74 {
75         return socket_.socket() != INVALID_SOCKET;
76 }
77
78 int low_can_subscription_t::get_index() const
79 {
80         return index_;
81 }
82
83 const std::shared_ptr<can_signal_t> low_can_subscription_t::get_can_signal() const
84 {
85         return can_signal_;
86 }
87
88 const std::string low_can_subscription_t::get_sig_name() const
89 {
90         return can_signal_->get_name();
91 }
92
93 float low_can_subscription_t::get_frequency() const
94 {
95         return event_filter_.frequency;
96 }
97
98 float low_can_subscription_t::get_min() const
99 {
100         return event_filter_.min;
101 }
102
103 float low_can_subscription_t::get_max() const
104 {
105         return event_filter_.max;
106 }
107
108 utils::socketcan_bcm_t& low_can_subscription_t::get_socket()
109 {
110         return socket_;
111 }
112
113 void low_can_subscription_t::set_frequency(float freq)
114 {
115         event_filter_.frequency = freq;
116 }
117
118 void low_can_subscription_t::set_min(float min)
119 {
120         event_filter_.min = min;
121 }
122
123 void low_can_subscription_t::set_max(float max)
124 {
125         event_filter_.max = max;
126 }
127
128 /// @brief Create a RX_SETUP receive job used by the BCM socket.
129 ///
130 /// @return 0 if ok else -1
131 int low_can_subscription_t::create_rx_filter(std::shared_ptr<can_signal_t> sig)
132 {
133         can_signal_= sig;
134         return create_rx_filter();
135 }
136
137 /// @brief Create a RX_SETUP receive job used by the BCM socket.
138 ///
139 /// @return 0 if ok else -1
140 int low_can_subscription_t::create_rx_filter()
141 {
142         // Make sure that socket has been opened.
143         if(! socket_)
144         {
145                 socket_.open(can_signal_->get_message()->get_bus_device_name());
146                 index_ = (int)socket_.socket();
147         }
148
149         struct utils::simple_bcm_msg bcm_msg;
150         struct can_frame cfd;
151
152         memset(&cfd, 0, sizeof(cfd));
153         memset(&bcm_msg.msg_head, 0, sizeof(bcm_msg.msg_head));
154         float val = (float)(1 << can_signal_->get_bit_size()) - 1;
155
156         struct timeval freq;
157         frequency_clock_t f(event_filter_.frequency);
158         freq = f.get_timeval_from_period();
159
160         bcm_msg.msg_head.opcode  = RX_SETUP;
161         bcm_msg.msg_head.can_id  = can_signal_->get_message()->get_id();
162         bcm_msg.msg_head.flags = SETTIMER|RX_NO_AUTOTIMER;
163         bcm_msg.msg_head.ival2.tv_sec = freq.tv_sec ;
164         bcm_msg.msg_head.ival2.tv_usec = freq.tv_usec;
165         bcm_msg.msg_head.nframes = 1;
166         bitfield_encode_float(val,
167                                                         can_signal_->get_bit_position(),
168                                                         can_signal_->get_bit_size(),
169                                                         can_signal_->get_factor(),
170                                                         can_signal_->get_offset(),
171                                                         cfd.data,
172                                                         CAN_MAX_DLEN);
173
174         bcm_msg.frames = cfd;
175
176         if(socket_ << bcm_msg)
177                 return 0;
178         return -1;
179 }
180
181 ///******************************************************************************
182 ///
183 ///             SystemD event loop Callbacks
184 ///
185 ///*******************************************************************************/
186
187 void on_no_clients(const std::string& message)
188 {
189         DiagnosticRequest* diag_req = application_t::instance().get_request_from_diagnostic_message(message);
190         if(diag_req != nullptr)
191         {
192                 active_diagnostic_request_t* adr = application_t::instance().get_diagnostic_manager().find_recurring_request(diag_req);
193                 if( adr != nullptr)
194                         application_t::instance().get_diagnostic_manager().cleanup_request(adr, true);
195         }
196         delete diag_req;
197         diag_req = nullptr;
198 }
199
200 static void push_n_notify(const can_message_t& cm)
201 {
202         can_bus_t& cbm = application_t::instance().get_can_bus_manager();
203         std::lock_guard<std::mutex> can_message_lock(cbm.get_can_message_mutex());
204         { cbm.push_new_can_message(cm); }
205         cbm.get_new_can_message_cv().notify_one();
206 }
207
208 int read_message(sd_event_source *s, int fd, uint32_t revents, void *userdata)
209 {
210         can_message_t cm;
211         low_can_subscription_t* can_subscription;
212         diagnostic_manager_t& diag_m = application_t::instance().get_diagnostic_manager();
213
214         if(userdata != nullptr)
215         {
216                 can_subscription = (low_can_subscription_t*)userdata;
217                 utils::socketcan_bcm_t& s = can_subscription->get_socket();
218                 s >> cm;
219         }
220         else
221         {
222                 utils::socketcan_bcm_t& s = diag_m.get_socket();
223                 s >> cm;
224         }
225
226         push_n_notify(cm);
227
228         /* check if error or hangup */
229         if ((revents & (EPOLLERR|EPOLLRDHUP|EPOLLHUP)) != 0)
230         {
231                 sd_event_source_unref(s);
232                 if(userdata != nullptr)
233                 {
234                         can_subscription->get_socket().close();
235                         can_subscription->create_rx_filter();
236                         NOTICE(binder_interface, "%s: Recreated RX_SETUP BCM job for can_subscription: %s", __FUNCTION__, can_subscription->get_sig_name().c_str());
237                 }
238                 else
239                 {
240                         diag_m.get_socket().close();
241                         diag_m.cleanup_active_requests(true);
242                         ERROR(binder_interface, "%s: Error on diagnostic manager socket, cancelling active requests.", __FUNCTION__);
243                 }
244                 return -1;
245         }
246
247         return 0;
248 }
249
250 ///******************************************************************************
251 ///
252 ///             Subscription and unsubscription
253 ///
254 ///*******************************************************************************/
255
256 static int make_subscription_unsubscription(struct afb_req request, std::shared_ptr<low_can_subscription_t>& can_subscription, std::map<int, std::pair<std::shared_ptr<low_can_subscription_t>, struct afb_event> >& s, bool subscribe)
257 {
258         /* Make the subscription or unsubscription to the event */
259         if (((subscribe ? afb_req_subscribe : afb_req_unsubscribe)(request, s[can_subscription->get_index()].second)) < 0)
260         {
261                 ERROR(binder_interface, "%s: Operation goes wrong for signal: %s", __FUNCTION__, can_subscription->get_sig_name().c_str());
262                 return -1;
263         }
264         return 0;
265 }
266
267 static int create_event_handle(std::shared_ptr<low_can_subscription_t>& can_subscription, std::map<int, std::pair<std::shared_ptr<low_can_subscription_t>, struct afb_event> >& s)
268 {
269         int sub_index = can_subscription->get_index();
270         struct afb_event event = afb_daemon_make_event(binder_interface->daemon, can_subscription->get_sig_name().c_str());
271         s[sub_index] = std::make_pair(can_subscription, event);
272         if (!afb_event_is_valid(s[sub_index].second))
273         {
274                 ERROR(binder_interface, "%s: Can't create an event for %s, something goes wrong.", __FUNCTION__, can_subscription->get_sig_name().c_str());
275                 return -1;
276         }
277         return 0;
278 }
279
280 /// @brief Will determine if it is needed or not to create the event handle and checks it to be sure that
281 /// we got a valid afb_event to get subscribe or unsubscribe. Then launch the subscription or unsubscription
282 /// against the application framework using that event handle.
283 static int subscribe_unsubscribe_signal(struct afb_req request, bool subscribe, std::shared_ptr<low_can_subscription_t>& can_subscription)
284 {
285         int ret;
286         int sub_index = can_subscription->get_index();
287         utils::signals_manager_t& sm = utils::signals_manager_t::instance();
288
289         std::lock_guard<std::mutex> subscribed_signals_lock(sm.get_subscribed_signals_mutex());
290         std::map<int, std::pair<std::shared_ptr<low_can_subscription_t>, struct afb_event> >& s = sm.get_subscribed_signals();
291         if (can_subscription && s.find(sub_index) != s.end())
292         {
293                 if (!afb_event_is_valid(s[sub_index].second) && !subscribe)
294                 {
295                         NOTICE(binder_interface, "%s: Event isn't valid, no need to unsubscribed.", __FUNCTION__);
296                         ret = -1;
297                 }
298                 else
299                 {
300                         // Event it isn't valid anymore, recreate it
301                         ret = create_event_handle(can_subscription, s);
302                 }
303         }
304         else
305         {
306                 /* Event doesn't exist , so let's create it */
307                 struct afb_event empty_event = {nullptr, nullptr};
308                 s[sub_index] = std::make_pair(can_subscription, empty_event);
309                 ret = create_event_handle(can_subscription, s);
310         }
311
312         // Check whether or not the event handler has been correctly created and
313         // make the subscription/unsubscription operation is so.
314         if (ret < 0)
315                 return ret;
316         return make_subscription_unsubscription(request, can_subscription, s, subscribe);
317 }
318
319 ///
320 /// @brief subscribe to all signals in the vector signals
321 ///
322 /// @param[in] afb_req request : contain original request use to subscribe or unsubscribe
323 /// @param[in] subscribe boolean value used to chose between a subscription operation or an unsubscription
324 /// @param[in] signals -  struct containing vectors with can_signal_t and diagnostic_messages to subscribe
325 ///
326 /// @return Number of correctly subscribed signal
327 ///
328 static int subscribe_unsubscribe_signals(struct afb_req request, bool subscribe, const struct utils::signals_found& signals, struct event_filter_t& event_filter)
329 {
330         int rets = 0;
331
332         //TODO: Implement way to dynamically call the right function no matter
333         // how much signals types we have.
334         application_t& conf = application_t::instance();
335
336         for(const auto& sig : signals.diagnostic_messages)
337         {
338                 int ret = 0;
339                 diagnostic_manager_t& diag_m = conf.get_diagnostic_manager();
340                 DiagnosticRequest* diag_req = conf.get_request_from_diagnostic_message(sig->get_name());
341
342                 // If the requested diagnostic message isn't supported by the car then unsubcribe it
343                 // no matter what we want, worse case will be a fail unsubscription but at least we don't
344                 // poll a PID for nothing.
345                 if(sig->get_supported() && subscribe)
346                 {
347                         float frequency = std::isnan(event_filter.frequency) ? sig->get_frequency() : event_filter.frequency;
348
349                         diag_m.add_recurring_request(diag_req, sig->get_name().c_str(), false, sig->get_decoder(), sig->get_callback(), frequency);
350                         //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);
351                 }
352                 else
353                 {
354                         diag_m.cleanup_request(
355                                 diag_m.find_recurring_request(diag_req), true);
356                         WARNING(binder_interface, "%s: signal: %s isn't supported. Canceling operation.", __FUNCTION__, sig->get_name().c_str());
357                         delete diag_req;
358                         diag_req = nullptr;
359                         return -1;
360                 }
361
362                 std::shared_ptr<low_can_subscription_t> can_subscription(new low_can_subscription_t(event_filter));
363                 ret = subscribe_unsubscribe_signal(request, subscribe, can_subscription);
364                 if(ret < 0)
365                         return ret;
366                 rets++;
367                 DEBUG(binder_interface, "%s: Signal: %s subscribed", __FUNCTION__, sig->get_name().c_str());
368         }
369
370         for(const auto& sig: signals.can_signals)
371         {
372                 std::shared_ptr<low_can_subscription_t> can_subscription(new low_can_subscription_t(event_filter));
373                 if(can_subscription->create_rx_filter(sig) < 0)
374                         {return -1;}
375                 else if(subscribe_unsubscribe_signal(request, subscribe, can_subscription) < 0)
376                         {return -1;}
377
378                 struct sd_event_source* e_source;
379                 sd_event_add_io(afb_daemon_get_event_loop(binder_interface->daemon), &e_source, can_subscription->get_socket().socket(), EPOLLIN, read_message, can_subscription.get());
380                 rets++;
381                 DEBUG(binder_interface, "%s: signal: %s subscribed", __FUNCTION__, sig->get_name().c_str());
382         }
383         return rets;
384 }
385
386 static int one_subscribe_unsubscribe(struct afb_req request, bool subscribe, const std::string& tag, json_object* args)
387 {
388         int ret = 0;
389         struct event_filter_t event_filter;
390         struct json_object  *filter, *obj;
391         struct utils::signals_found sf;
392
393         // computes the filter
394         if (json_object_object_get_ex(args, "filter", &filter))
395         {
396                 if (json_object_object_get_ex(filter, "frequency", &obj)
397                 && (json_object_is_type(obj, json_type_double) || json_object_is_type(obj, json_type_int)))
398                 {
399                         event_filter.frequency = (float)json_object_get_double(obj);
400                         ret += 1;
401                 }
402                 if (json_object_object_get_ex(filter, "min", &obj)
403                 && (json_object_is_type(obj, json_type_double) || json_object_is_type(obj, json_type_int)))
404                 {
405                         event_filter.min = (float)json_object_get_double(obj);
406                         ret += 2;
407                 }
408                 if (json_object_object_get_ex(filter, "max", &obj)
409                 && (json_object_is_type(obj, json_type_double) || json_object_is_type(obj, json_type_int)))
410                 {
411                         event_filter.max = (float)json_object_get_double(obj);
412                         ret += 4;
413                 }
414         }
415
416         // subscribe or unsubscribe
417         openxc_DynamicField search_key = build_DynamicField(tag);
418         sf = utils::signals_manager_t::instance().find_signals(search_key);
419         if (sf.can_signals.empty() && sf.diagnostic_messages.empty())
420                 NOTICE(binder_interface, "%s: No signal(s) found for %s.", __FUNCTION__, tag.c_str());
421         else
422                 ret = subscribe_unsubscribe_signals(request, subscribe, sf, event_filter);
423
424         return ret;
425 }
426
427 static void do_subscribe_unsubscribe(struct afb_req request, bool subscribe)
428 {
429         int i, n, rc, rc2;
430         struct json_object *args, *event, *x;
431
432         args = afb_req_json(request);
433         if (args == NULL || !json_object_object_get_ex(args, "event", &event))
434         {
435                 rc = one_subscribe_unsubscribe(request, subscribe, "*", args);
436         }
437         else if (json_object_get_type(event) != json_type_array)
438         {
439                 rc = one_subscribe_unsubscribe(request, subscribe, json_object_get_string(event), args);
440         }
441         else
442         {
443                 rc = 0;
444                 n = json_object_array_length(event);
445                 for (i = 0 ; i < n ; i++)
446                 {
447                         x = json_object_array_get_idx(event, i);
448                         rc2 = one_subscribe_unsubscribe(request, subscribe, json_object_get_string(x), args);
449                         if (rc >= 0)
450                                 rc = rc2 >= 0 ? rc + rc2 : rc2;
451                 }
452         }
453
454         if (rc >= 0)
455                 afb_req_success(request, NULL, NULL);
456         else
457                 afb_req_fail(request, "error", NULL);
458 }
459
460 void subscribe(struct afb_req request)
461 {
462         do_subscribe_unsubscribe(request, true);
463 }
464
465 void unsubscribe(struct afb_req request)
466 {
467         do_subscribe_unsubscribe(request, false);
468 }