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