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