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