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