9c21b6751b3eb99626ef9bf6c909b3c75916e12d
[apps/agl-service-can-low-level.git] / low-can-binding / binding / low-can-cb.cpp
1 /*
2  * Copyright (C) 2015, 2018 "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 #include "low-can-apidef.h"
21
22 #include <map>
23 #include <queue>
24 #include <mutex>
25 #include <vector>
26 #include <thread>
27 #include <wrap-json.h>
28 #include <systemd/sd-event.h>
29
30 #include "openxc.pb.h"
31 #include "application.hpp"
32 #include "../can/can-encoder.hpp"
33 #include "../can/can-bus.hpp"
34 #include "../can/signals.hpp"
35 #include "../can/message/message.hpp"
36 #include "../utils/signals.hpp"
37 #include "../diagnostic/diagnostic-message.hpp"
38 #include "../utils/openxc-utils.hpp"
39
40 ///******************************************************************************
41 ///
42 ///             SystemD event loop Callbacks
43 ///
44 ///*******************************************************************************/
45
46 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)
47 {
48         bool is_permanent_recurring_request = false;
49
50         if( ! can_subscription->get_diagnostic_message().empty() && can_subscription->get_diagnostic_message(pid) != nullptr)
51         {
52                 DiagnosticRequest diag_req = can_subscription->get_diagnostic_message(pid)->build_diagnostic_request();
53                 active_diagnostic_request_t* adr = application_t::instance().get_diagnostic_manager().find_recurring_request(diag_req);
54                 if( adr != nullptr)
55                 {
56                         is_permanent_recurring_request = adr->get_permanent();
57
58                         if(! is_permanent_recurring_request)
59                                 application_t::instance().get_diagnostic_manager().cleanup_request(adr, true);
60                 }
61         }
62
63         if(! is_permanent_recurring_request)
64                 on_no_clients(can_subscription, s);
65 }
66
67 void on_no_clients(std::shared_ptr<low_can_subscription_t> can_subscription, std::map<int, std::shared_ptr<low_can_subscription_t> >& s)
68 {
69         auto it = s.find(can_subscription->get_index());
70         s.erase(it);
71 }
72
73 static void push_n_notify(std::shared_ptr<message_t> m)
74 {
75         can_bus_t& cbm = application_t::instance().get_can_bus_manager();
76         {
77                 std::lock_guard<std::mutex> can_message_lock(cbm.get_can_message_mutex());
78                 cbm.push_new_can_message(m);
79         }
80         cbm.get_new_can_message_cv().notify_one();
81 }
82
83 int read_message(sd_event_source *event_source, int fd, uint32_t revents, void *userdata)
84 {
85         low_can_subscription_t* can_subscription = (low_can_subscription_t*)userdata;
86
87
88         if ((revents & EPOLLIN) != 0)
89         {
90                 std::shared_ptr<utils::socketcan_t> s = can_subscription->get_socket();
91                 std::shared_ptr<message_t> message = s->read_message();
92
93                 // Sure we got a valid CAN message ?
94                 if (! message->get_id() == 0 && ! message->get_length() == 0)
95                 {
96                         push_n_notify(message);
97                 }
98         }
99
100         // check if error or hangup
101         if ((revents & (EPOLLERR|EPOLLRDHUP|EPOLLHUP)) != 0)
102         {
103                 sd_event_source_unref(event_source);
104                 can_subscription->get_socket()->close();
105         }
106
107         return 0;
108 }
109
110 ///******************************************************************************
111 ///
112 ///             Subscription and unsubscription
113 ///
114 ///*******************************************************************************/
115
116 /// @brief This will determine if an event handle needs to be created and checks if
117 /// we got a valid afb_event to get subscribe or unsubscribe. After that launch the subscription or unsubscription
118 /// against the application framework using that event handle.
119 static int subscribe_unsubscribe_signal(afb_req_t request,
120                                         bool subscribe,
121                                         std::shared_ptr<low_can_subscription_t>& can_subscription,
122                                         std::map<int, std::shared_ptr<low_can_subscription_t> >& s)
123 {
124         int ret = 0;
125         int sub_index = can_subscription->get_index();
126         bool subscription_exists = s.count(sub_index);
127
128         // Susbcription part
129         if(subscribe)
130         {
131                 /* There is no valid request to subscribe so this must be an
132                  * internal permanent diagnostic request. Skip the subscription
133                  * part and don't register it into the current "low-can"
134                  * subsciptions.
135                  */
136                 if(! request)
137                 {
138                         return 0;
139                 }
140
141                 // Event doesn't exist , so let's create it
142                 if (! subscription_exists &&
143                     (ret = can_subscription->subscribe(request)) < 0)
144                         return ret;
145
146                 if(! subscription_exists)
147                                 s[sub_index] = can_subscription;
148
149                 return ret;
150         }
151
152         // Unsubscrition part
153         if(! subscription_exists)
154         {
155                 AFB_NOTICE("There isn't any valid subscriptions for that request.");
156                 return ret;
157         }
158         else if (subscription_exists &&
159                  ! afb_event_is_valid(s[sub_index]->get_event()) )
160         {
161                 AFB_NOTICE("Event isn't valid, no need to unsubscribed.");
162                 return ret;
163         }
164
165         if( (ret = s[sub_index]->unsubscribe(request)) < 0)
166                 return ret;
167         s.erase(sub_index);
168
169         return ret;
170 }
171
172 static int add_to_event_loop(std::shared_ptr<low_can_subscription_t>& can_subscription)
173 {
174                 struct sd_event_source* event_source = nullptr;
175                 return ( sd_event_add_io(afb_daemon_get_event_loop(),
176                         &event_source,
177                         can_subscription->get_socket()->socket(),
178                         EPOLLIN,
179                         read_message,
180                         can_subscription.get()));
181 }
182
183 static int subscribe_unsubscribe_diagnostic_messages(afb_req_t request,
184                                                      bool subscribe,
185                                                      std::vector<std::shared_ptr<diagnostic_message_t> > diagnostic_messages,
186                                                      struct event_filter_t& event_filter,
187                                                      std::map<int, std::shared_ptr<low_can_subscription_t> >& s,
188                                                      bool perm_rec_diag_req)
189 {
190         int rets = 0;
191         application_t& app = application_t::instance();
192         diagnostic_manager_t& diag_m = app.get_diagnostic_manager();
193
194         for(const auto& sig : diagnostic_messages)
195         {
196                 DiagnosticRequest* diag_req = new DiagnosticRequest(sig->build_diagnostic_request());
197                 event_filter.frequency = event_filter.frequency == 0 ? sig->get_frequency() : event_filter.frequency;
198                 std::shared_ptr<low_can_subscription_t> can_subscription;
199
200                 auto it =  std::find_if(s.begin(), s.end(), [&sig](std::pair<int, std::shared_ptr<low_can_subscription_t> > sub)
201                 {
202                         return (! sub.second->get_diagnostic_message().empty());
203                 });
204                 can_subscription = it != s.end() ?
205                         it->second :
206                         std::make_shared<low_can_subscription_t>(low_can_subscription_t(event_filter));
207                 // If the requested diagnostic message is not supported by the car then unsubcribe it
208                 // no matter what we want, worst case will be a failed unsubscription but at least we won't
209                 // poll a PID for nothing.
210                 if(sig->get_supported() && subscribe)
211                 {
212                         if (!app.isEngineOn())
213                                 AFB_WARNING("signal: Engine is off, %s won't received responses until it's on",  sig->get_name().c_str());
214
215                         diag_m.add_recurring_request(diag_req, sig->get_name().c_str(), false, sig->get_decoder(), sig->get_callback(), event_filter.frequency, perm_rec_diag_req);
216                         if(can_subscription->create_rx_filter(sig) < 0)
217                                 {return -1;}
218                         AFB_DEBUG("Signal: %s subscribed", sig->get_name().c_str());
219                         if(it == s.end() && add_to_event_loop(can_subscription) < 0)
220                         {
221                                 diag_m.cleanup_request(
222                                         diag_m.find_recurring_request(*diag_req), true);
223                                 AFB_WARNING("signal: %s isn't supported. Canceling operation.",  sig->get_name().c_str());
224                                 return -1;
225                         }
226                 }
227                 else
228                 {
229                         if(sig->get_supported())
230                         {AFB_DEBUG("%s cancelled due to unsubscribe", sig->get_name().c_str());}
231                         else
232                         {
233                                 AFB_WARNING("signal: %s isn't supported. Canceling operation.", sig->get_name().c_str());
234                                 return -1;
235                         }
236                 }
237                 int ret = subscribe_unsubscribe_signal(request, subscribe, can_subscription, s);
238                 if(ret < 0)
239                         return ret;
240
241                 rets++;
242         }
243
244         return rets;
245 }
246
247 static int subscribe_unsubscribe_signals(afb_req_t request,
248                                              bool subscribe,
249                                              std::vector<std::shared_ptr<signal_t> > signals,
250                                              struct event_filter_t& event_filter,
251                                              std::map<int, std::shared_ptr<low_can_subscription_t> >& s)
252 {
253         int rets = 0;
254         for(const auto& sig: signals)
255         {
256                 auto it =  std::find_if(s.begin(), s.end(), [&sig, &event_filter](std::pair<int, std::shared_ptr<low_can_subscription_t> > sub)
257                 {
258                         return sub.second->is_signal_subscription_corresponding(sig, event_filter) ;
259                 });
260                 std::shared_ptr<low_can_subscription_t> can_subscription;
261                 if(it != s.end())
262                         {can_subscription = it->second;}
263                 else
264                 {
265                         can_subscription = std::make_shared<low_can_subscription_t>(low_can_subscription_t(event_filter));
266                         if(can_subscription->create_rx_filter(sig) < 0)
267                                 {return -1;}
268                         if(add_to_event_loop(can_subscription) < 0)
269                                 {return -1;}
270                 }
271
272                 if(subscribe_unsubscribe_signal(request, subscribe, can_subscription, s) < 0)
273                         {return -1;}
274
275                 rets++;
276                 AFB_DEBUG("%s Signal: %s %ssubscribed", sig->get_message()->is_fd() ? "FD": "", sig->get_name().c_str(), subscribe ? "":"un");
277         }
278         return rets;
279 }
280
281 ///
282 /// @brief subscribe to all signals in the vector signals
283 ///
284 /// @param[in] afb_req request : contains original request use to subscribe or unsubscribe
285 /// @param[in] subscribe boolean value, which chooses between a subscription operation or an unsubscription
286 /// @param[in] signals -  struct containing vectors with signal_t and diagnostic_messages to subscribe
287 ///
288 /// @return Number of correctly subscribed signal
289 ///
290 static int subscribe_unsubscribe_signals(afb_req_t request,
291                                          bool subscribe,
292                                          const struct utils::signals_found& signals,
293                                          struct event_filter_t& event_filter)
294 {
295         int rets = 0;
296         utils::signals_manager_t& sm = utils::signals_manager_t::instance();
297
298         std::lock_guard<std::mutex> subscribed_signals_lock(sm.get_subscribed_signals_mutex());
299         std::map<int, std::shared_ptr<low_can_subscription_t> >& s = sm.get_subscribed_signals();
300
301         rets += subscribe_unsubscribe_diagnostic_messages(request, subscribe, signals.diagnostic_messages, event_filter, s, false);
302         rets += subscribe_unsubscribe_signals(request, subscribe, signals.signals, event_filter, s);
303
304         return rets;
305 }
306
307 static event_filter_t generate_filter(json_object* args)
308 {
309         event_filter_t event_filter;
310         struct json_object  *filter, *obj;
311
312                 // computes the filter
313         if (json_object_object_get_ex(args, "filter", &filter))
314         {
315                 if (json_object_object_get_ex(filter, "frequency", &obj)
316                 && (json_object_is_type(obj, json_type_double) || json_object_is_type(obj, json_type_int)))
317                         {event_filter.frequency = (float)json_object_get_double(obj);}
318                 if (json_object_object_get_ex(filter, "min", &obj)
319                 && (json_object_is_type(obj, json_type_double) || json_object_is_type(obj, json_type_int)))
320                         {event_filter.min = (float)json_object_get_double(obj);}
321                 if (json_object_object_get_ex(filter, "max", &obj)
322                 && (json_object_is_type(obj, json_type_double) || json_object_is_type(obj, json_type_int)))
323                         {event_filter.max = (float)json_object_get_double(obj);}
324         }
325         return event_filter;
326 }
327
328
329 static int one_subscribe_unsubscribe_events(afb_req_t request, bool subscribe, const std::string& tag, json_object* args)
330 {
331         int ret = 0;
332         struct utils::signals_found sf;
333
334         // subscribe or unsubscribe
335         openxc_DynamicField search_key = build_DynamicField(tag);
336         sf = utils::signals_manager_t::instance().find_signals(search_key);
337         if (sf.signals.empty() && sf.diagnostic_messages.empty())
338         {
339                 AFB_NOTICE("No signal(s) found for %s.", tag.c_str());
340                 ret = -1;
341         }
342         else
343         {
344                 event_filter_t event_filter = generate_filter(args);
345                 ret = subscribe_unsubscribe_signals(request, subscribe, sf, event_filter);
346         }
347         return ret;
348 }
349
350 static int one_subscribe_unsubscribe_id(afb_req_t request, bool subscribe, const uint32_t& id ,json_object *args)
351 {
352         int ret = 0;
353         std::shared_ptr<message_definition_t> message_definition = application_t::instance().get_message_definition(id);
354         struct utils::signals_found sf;
355
356         if(message_definition)
357         {
358                 sf.signals = message_definition->get_signals();
359         }
360
361         if(sf.signals.empty())
362         {
363                 AFB_NOTICE("No signal(s) found for %d.", id);
364                 ret = -1;
365         }
366         else
367         {
368                 event_filter_t event_filter = generate_filter(args);
369                 ret = subscribe_unsubscribe_signals(request, subscribe, sf, event_filter);
370         }
371         return ret;
372 }
373
374
375 static int process_one_subscribe_args(afb_req_t request, bool subscribe, json_object *args)
376 {
377         int rc = 0, rc2=0;
378         json_object *x = nullptr, *event = nullptr, *id = nullptr;
379
380
381         // 2 cases : ID(PGN) and event
382
383         json_object_object_get_ex(args,"event",&event);
384         json_bool test_id = json_object_object_get_ex(args,"id",&id);
385         if(!test_id)
386         {
387                 test_id = json_object_object_get_ex(args,"pgn",&id);
388         }
389
390         if(     args == NULL || (id && ((std::string)json_object_get_string(id)).compare("*") == 0))
391         {
392                 rc = one_subscribe_unsubscribe_events(request, subscribe, "*", args);
393         }
394         else
395         {
396                 if(event)
397                 {
398                         if (json_object_get_type(event) != json_type_array) // event is set before and check if it's an array
399                         {
400                                 rc = one_subscribe_unsubscribe_events(request, subscribe, json_object_get_string(event), args);
401                         }
402                         else // event is set and it's not an array
403                         {
404                                 for (int i = 0 ; i < json_object_array_length(event); i++)
405                                 {
406                                         x = json_object_array_get_idx(event, i);
407                                         rc2 = one_subscribe_unsubscribe_events(request, subscribe, json_object_get_string(x), args);
408                                         if (rc >= 0)
409                                                 rc = rc2 >= 0 ? rc + rc2 : rc2;
410                                 }
411                         }
412                 }
413
414                 if(id)
415                 {
416                         if (json_object_get_type(id) != json_type_array) // id is set before and check if it's an array
417                         {
418                                 rc = one_subscribe_unsubscribe_id(request, subscribe, json_object_get_int(id), args);
419                         }
420                         else // event is set and it's not an array
421                         {
422                                 for (int i = 0 ; i < json_object_array_length(id); i++)
423                                 {
424                                         x = json_object_array_get_idx(id, i);
425                                         rc2 = one_subscribe_unsubscribe_id(request, subscribe, json_object_get_int(x), args);
426                                         if (rc >= 0)
427                                                 rc = rc2 >= 0 ? rc + rc2 : rc2;
428                                 }
429                         }
430                 }
431         }
432         return rc;
433 }
434
435 static void do_subscribe_unsubscribe(afb_req_t request, bool subscribe)
436 {
437         int rc = 0;
438         struct json_object *args, *x;
439
440         args = afb_req_json(request);
441         if (json_object_get_type(args) == json_type_array)
442         {
443                 for(int i = 0; i < json_object_array_length(args); i++)
444                 {
445                         x = json_object_array_get_idx(args, i);
446                         rc += process_one_subscribe_args(request, subscribe, x);
447                 }
448         }
449         else
450         {
451                 rc += process_one_subscribe_args(request, subscribe, args);
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 auth(afb_req_t request)
461 {
462         afb_req_session_set_LOA(request, 1);
463         afb_req_success(request, NULL, NULL);
464 }
465
466 void subscribe(afb_req_t request)
467 {
468         do_subscribe_unsubscribe(request, true);
469 }
470
471 void unsubscribe(afb_req_t request)
472 {
473         do_subscribe_unsubscribe(request, false);
474 }
475
476 /*
477 static int send_frame(struct canfd_frame& cfd, const std::string& bus_name, socket_type type)
478 {
479         if(bus_name.empty())
480         {
481                 return -1;
482         }
483
484         std::map<std::string, std::shared_ptr<low_can_subscription_t> >& cd = application_t::instance().get_can_devices();
485
486         if( cd.count(bus_name) == 0)
487         {
488                 cd[bus_name] = std::make_shared<low_can_subscription_t>(low_can_subscription_t());
489         }
490
491
492         if(type == socket_type::BCM)
493         {
494                 return low_can_subscription_t::tx_send(*cd[bus_name], cfd, bus_name);
495         }
496         else{
497                 return -1;
498         }
499 }
500 */
501 static int send_message(message_t *message, const std::string& bus_name, socket_type type)
502 {
503         if(bus_name.empty())
504         {
505                 return -1;
506         }
507
508         std::map<std::string, std::shared_ptr<low_can_subscription_t> >& cd = application_t::instance().get_can_devices();
509
510         if( cd.count(bus_name) == 0)
511         {
512                 cd[bus_name] = std::make_shared<low_can_subscription_t>(low_can_subscription_t());
513         }
514
515
516         if(type == socket_type::BCM)
517         {
518                 return low_can_subscription_t::tx_send(*cd[bus_name], message, bus_name);
519         }
520         else
521         {
522                 return -1;
523         }
524 }
525
526
527 static void write_raw_frame(afb_req_t request, const std::string& bus_name, message_t *message, struct json_object *can_data, socket_type type)
528 {
529         if((message->get_length() <= 8 && message->get_length() > 0 && type == socket_type::BCM)
530 #ifdef USE_FEATURE_J1939
531         || (message->get_length() < J1939_MAX_DLEN && type == socket_type::J1939)
532 #endif
533         )
534         {
535
536                 std::vector<uint8_t> data;
537                 for (int i = 0 ; i < message->get_length() ; i++)
538                 {
539                         struct json_object *one_can_data = json_object_array_get_idx(can_data, i);
540                         data.push_back((json_object_is_type(one_can_data, json_type_int)) ?
541                                         (uint8_t)json_object_get_int(one_can_data) : 0);
542                 }
543                 message->set_data(data);
544         }
545         else
546         {
547                 if(type == socket_type::BCM)
548                 {
549                         afb_req_fail(request, "Invalid", "Data array must hold 1 to 8 values.");
550                 }
551                 else
552                 {
553                         afb_req_fail(request, "Invalid", "Invalid socket type");
554                 }
555                 return;
556         }
557
558         if(! send_message(message, application_t::instance().get_can_bus_manager().get_can_device_name(bus_name),type))
559         {
560                 afb_req_success(request, nullptr, "Message correctly sent");
561         }
562         else
563         {
564                 afb_req_fail(request, "Error", "sending the message. See the log for more details.");
565         }
566 }
567
568 static void write_frame(afb_req_t request, const std::string& bus_name, json_object *json_value)
569 {
570         message_t *message;
571         int id;
572         int length;
573         struct json_object *can_data = nullptr;
574         std::vector<uint8_t> data;
575
576         AFB_DEBUG("JSON content %s",json_object_get_string(json_value));
577
578         if(!wrap_json_unpack(json_value, "{si, si, so !}",
579                               "can_id", &id,
580                               "can_dlc", &length,
581                               "can_data", &can_data))
582         {
583                 message = new can_message_t(CANFD_MAX_DLEN,(uint32_t)id,(uint32_t)length,message_format_t::STANDARD,false,0,data,0);
584                 write_raw_frame(request,bus_name,message,can_data,socket_type::BCM);
585         }
586         else
587         {
588                 afb_req_fail(request, "Invalid", "Frame object malformed");
589                 return;
590         }
591         delete message;
592 }
593
594 static void write_signal(afb_req_t request, const std::string& name, json_object *json_value)
595 {
596         struct canfd_frame cfd;
597         struct utils::signals_found sf;
598         signal_encoder encoder = nullptr;
599         bool send = true;
600
601         ::memset(&cfd, 0, sizeof(cfd));
602
603         openxc_DynamicField search_key = build_DynamicField(name);
604         sf = utils::signals_manager_t::instance().find_signals(search_key);
605         openxc_DynamicField dynafield_value = build_DynamicField(json_value);
606
607         if (sf.signals.empty())
608         {
609                 afb_req_fail_f(request, "No signal(s) found for %s. Message not sent.", name.c_str());
610                 return;
611         }
612
613         std::shared_ptr<signal_t>& sig = sf.signals[0];
614         if(! sig->get_writable())
615         {
616                 afb_req_fail_f(request, "%s isn't writable. Message not sent.", sig->get_name().c_str());
617                 return;
618         }
619
620         uint64_t value = (encoder = sig->get_encoder()) ?
621                         encoder(*sig, dynafield_value, &send) :
622                         encoder_t::encode_DynamicField(*sig, dynafield_value, &send);
623
624         socket_type type = socket_type::INVALID;
625
626         if(sig->get_message()->is_j1939())
627         {
628                 type = socket_type::J1939;
629         }
630         else
631         {
632                 type = socket_type::BCM;
633         }
634
635 //      cfd = encoder_t::build_frame(sig, value);
636         message_t *message = encoder_t::build_message(sig,value);
637
638         if(! send_message(message, sig->get_message()->get_bus_device_name(), type) && send)
639         {
640                 afb_req_success(request, nullptr, "Message correctly sent");
641         }
642         else
643         {
644                 afb_req_fail(request, "Error", "Sending the message. See the log for more details.");
645         }
646
647         if(sig->get_message()->is_j1939())
648         {
649 #ifdef USE_FEATURE_J1939
650                 delete (j1939_message_t*) message;
651 #endif
652         }
653         else
654         {
655                 delete (can_message_t*) message;
656         }
657 }
658
659 void write(afb_req_t request)
660 {
661         struct json_object* args = nullptr, *json_value = nullptr;
662         const char *name = nullptr;
663
664         args = afb_req_json(request);
665
666         // Process about Raw CAN message on CAN bus directly
667         if (args != NULL && ! wrap_json_unpack(args, "{ss, so !}",
668                                                "bus_name", &name,
669                                                "frame", &json_value))
670                 write_frame(request, name, json_value);
671
672         // Search signal then encode value.
673         else if(args != NULL &&
674                 ! wrap_json_unpack(args, "{ss, so !}",
675                                    "signal_name", &name,
676                                    "signal_value", &json_value))
677                 write_signal(request, std::string(name), json_value);
678         else
679                 afb_req_fail(request, "Error", "Request argument malformed");
680 }
681
682 static struct json_object *get_signals_value(const std::string& name)
683 {
684         struct utils::signals_found sf;
685         struct json_object *ans = nullptr;
686
687         openxc_DynamicField search_key = build_DynamicField(name);
688         sf = utils::signals_manager_t::instance().find_signals(search_key);
689
690         if (sf.signals.empty())
691         {
692                 AFB_WARNING("No signal(s) found for %s.", name.c_str());
693                 return NULL;
694         }
695         ans = json_object_new_array();
696         for(const auto& sig: sf.signals)
697         {
698                 struct json_object *jobj = json_object_new_object();
699                 json_object_object_add(jobj, "event", json_object_new_string(sig->get_name().c_str()));
700                 json_object_object_add(jobj, "value", json_object_new_double(sig->get_last_value()));
701                 json_object_array_add(ans, jobj);
702         }
703
704         return ans;
705 }
706 void get(afb_req_t request)
707 {
708         int rc = 0;
709         struct json_object* args = nullptr,
710                 *json_name = nullptr;
711         json_object *ans = nullptr;
712
713         args = afb_req_json(request);
714
715         // Process about Raw CAN message on CAN bus directly
716         if (args != nullptr &&
717                 (json_object_object_get_ex(args, "event", &json_name) && json_object_is_type(json_name, json_type_string) ))
718         {
719                 ans = get_signals_value(json_object_get_string(json_name));
720                 if (!ans)
721                         rc = -1;
722         }
723         else
724         {
725                 AFB_ERROR("Request argument malformed. Please use the following syntax:");
726                 rc = -1;
727         }
728
729         if (rc >= 0)
730                 afb_req_success(request, ans, NULL);
731         else
732                 afb_req_fail(request, "error", NULL);
733 }
734
735
736 static struct json_object *list_can_message(const std::string& name)
737 {
738         struct utils::signals_found sf;
739         struct json_object *ans = nullptr;
740
741         openxc_DynamicField search_key = build_DynamicField(name);
742         sf = utils::signals_manager_t::instance().find_signals(search_key);
743
744         if (sf.signals.empty() && sf.diagnostic_messages.empty())
745         {
746                 AFB_WARNING("No signal(s) found for %s.", name.c_str());
747                 return NULL;
748         }
749         ans = json_object_new_array();
750         for(const auto& sig: sf.signals)
751         {
752                 json_object_array_add(ans,
753                         json_object_new_string(sig->get_name().c_str()));
754         }
755         for(const auto& sig: sf.diagnostic_messages)
756         {
757                 json_object_array_add(ans,
758                         json_object_new_string(sig->get_name().c_str()));
759         }
760
761         return ans;
762 }
763
764 void list(afb_req_t request)
765 {
766         int rc = 0;
767         json_object *ans = nullptr;
768         struct json_object* args = nullptr,
769                 *json_name = nullptr;
770         args = afb_req_json(request);
771         const char *name;
772         if ((args != nullptr) &&
773                 (json_object_object_get_ex(args, "event", &json_name) && json_object_is_type(json_name, json_type_string)))
774         {
775                 name = json_object_get_string(json_name);
776         }
777         else
778         {
779                 name = "*";
780         }
781
782         ans = list_can_message(name);
783         if (!ans)
784                 rc = -1;
785
786         if (rc >= 0)
787         {
788                 afb_req_success(request, ans, NULL);
789         }
790         else
791         {
792                 afb_req_fail(request, "error", NULL);
793         }
794 }
795
796 /// @brief Initialize the binding.
797 ///
798 /// @param[in] service Structure which represent the Application Framework Binder.
799 ///
800 /// @return Exit code, zero if success.
801 int init_binding(afb_api_t api)
802 {
803         uint32_t ret = 1;
804         can_bus_t& can_bus_manager = application_t::instance().get_can_bus_manager();
805
806         can_bus_manager.set_can_devices();
807         can_bus_manager.start_threads();
808         utils::signals_manager_t& sm = utils::signals_manager_t::instance();
809
810         /// Initialize Diagnostic manager that will handle obd2 requests.
811         /// We pass by default the first CAN bus device to its Initialization.
812         /// TODO: be able to choose the CAN bus device that will be use as Diagnostic bus.
813         if(application_t::instance().get_diagnostic_manager().initialize())
814                 ret = 0;
815
816         // Add a recurring dignostic message request to get engine speed at all times.
817         openxc_DynamicField search_key = build_DynamicField("diagnostic_messages.engine.speed");
818         struct utils::signals_found sf = sm.find_signals(search_key);
819
820         if(sf.signals.empty() && sf.diagnostic_messages.size() == 1)
821         {
822                 afb_req_t request = nullptr;
823
824                 struct event_filter_t event_filter;
825                 event_filter.frequency = sf.diagnostic_messages.front()->get_frequency();
826
827                 std::map<int, std::shared_ptr<low_can_subscription_t> >& s = sm.get_subscribed_signals();
828
829                 subscribe_unsubscribe_diagnostic_messages(request, true, sf.diagnostic_messages, event_filter, s, true);
830         }
831
832         if(ret)
833                 AFB_ERROR("There was something wrong with CAN device Initialization.");
834
835         return ret;
836 }