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