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