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