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