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