d1325d35ff18db96fb85339d466696db26abfe0a
[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, .prefix=nullptr,
89                  .loadCB=config_low_can,
90                  .handle=nullptr,
91                  .actions=nullptr},
92         [1]={.key="plugins" , .uid="plugins", .info=nullptr, .prefix=nullptr,
93                 .loadCB=PluginConfig,
94                 .handle=nullptr,
95                 .actions=nullptr},
96         [2]={.key=nullptr , .uid=nullptr, .info=nullptr, .prefix=nullptr,
97                 .loadCB=PluginConfig,
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, "rx_id", &obj)
318                 && (json_object_is_type(obj, json_type_int)))
319                         event_filter.rx_id = (canid_t) json_object_get_int(obj);
320                 if (json_object_object_get_ex(filter, "tx_id", &obj)
321                 && (json_object_is_type(obj, json_type_int)))
322                         event_filter.tx_id = (canid_t) json_object_get_int(obj);
323         }
324         return event_filter;
325 }
326
327
328 static int one_subscribe_unsubscribe_events(afb_req_t request, bool subscribe, const std::string& tag, json_object* args)
329 {
330         int ret = 0;
331         struct utils::signals_found sf;
332
333         // subscribe or unsubscribe
334         openxc_DynamicField search_key = build_DynamicField(tag);
335         sf = utils::signals_manager_t::instance().find_signals(search_key);
336
337
338 #ifdef USE_FEATURE_ISOTP
339         if(sf.signals.size() > 1)
340         {
341                 sf.signals.remove_if([](std::shared_ptr<signal_t> x){
342                         bool isotp = x->get_message()->is_isotp();
343                         if(isotp)
344                                 AFB_NOTICE("ISO TP messages need to be subscribed one by one (rx, tx)");
345
346                         return isotp;
347                 });
348         }
349 #endif
350
351         if (sf.signals.empty() && sf.diagnostic_messages.empty())
352         {
353                 AFB_NOTICE("No signal(s) found for %s.", tag.c_str());
354                 ret = -1;
355         }
356         else
357         {
358                 event_filter_t event_filter = generate_filter(args);
359                 ret = subscribe_unsubscribe_signals(request, subscribe, sf, event_filter);
360         }
361         return ret;
362 }
363
364 static int one_subscribe_unsubscribe_id(afb_req_t request, bool subscribe, const uint32_t& id, json_object *args)
365 {
366         int ret = 0;
367         std::shared_ptr<message_definition_t> message_definition = application_t::instance().get_message_definition(id);
368         struct utils::signals_found sf;
369
370         if(message_definition)
371                 sf.signals = list_ptr_signal_t(message_definition->get_signals().begin(), message_definition->get_signals().end());
372
373         if(sf.signals.empty())
374         {
375                 AFB_NOTICE("No signal(s) found for %d.", id);
376                 ret = -1;
377         }
378         else
379         {
380                 event_filter_t event_filter = generate_filter(args);
381                 ret = subscribe_unsubscribe_signals(request, subscribe, sf, event_filter);
382         }
383
384         return ret;
385 }
386
387
388 static int process_one_subscribe_args(afb_req_t request, bool subscribe, json_object *args)
389 {
390         int rc = 0, rc2=0;
391         json_object *x = nullptr, *event = nullptr, *id = nullptr;
392
393
394         // 2 cases : ID(PGN) and event
395
396         json_object_object_get_ex(args,"event",&event);
397         json_bool test_id = json_object_object_get_ex(args,"id",&id);
398         if(!test_id)
399                 test_id = json_object_object_get_ex(args,"pgn",&id);
400
401         if(     args == NULL || (id && ((std::string)json_object_get_string(id)).compare("*") == 0))
402         {
403                 rc = one_subscribe_unsubscribe_events(request, subscribe, "*", args);
404         }
405         else
406         {
407                 if(event)
408                 {
409                         if (json_object_get_type(event) != json_type_array) // event is set before and check if it's an array
410                         {
411                                 rc = one_subscribe_unsubscribe_events(request, subscribe, json_object_get_string(event), args);
412                         }
413                         else // event is set and it's not an array
414                         {
415                                 for (int i = 0 ; i < json_object_array_length(event); i++)
416                                 {
417                                         x = json_object_array_get_idx(event, i);
418                                         rc2 = one_subscribe_unsubscribe_events(request, subscribe, json_object_get_string(x), args);
419                                         if (rc >= 0)
420                                                 rc = rc2 >= 0 ? rc + rc2 : rc2;
421                                 }
422                         }
423                 }
424
425                 if(id)
426                 {
427                         if (json_object_get_type(id) != json_type_array) // id is set before and check if it's an array
428                         {
429                                 rc = one_subscribe_unsubscribe_id(request, subscribe, json_object_get_int(id), args);
430                         }
431                         else // event is set and it's not an array
432                         {
433                                 for (int i = 0 ; i < json_object_array_length(id); i++)
434                                 {
435                                         x = json_object_array_get_idx(id, i);
436                                         rc2 = one_subscribe_unsubscribe_id(request, subscribe, json_object_get_int(x), args);
437                                         if (rc >= 0)
438                                                 rc = rc2 >= 0 ? rc + rc2 : rc2;
439                                 }
440                         }
441                 }
442         }
443         return rc;
444 }
445
446 static void do_subscribe_unsubscribe(afb_req_t request, bool subscribe)
447 {
448         int rc = 0;
449         struct json_object *args, *x;
450
451         args = afb_req_json(request);
452         if (json_object_get_type(args) == json_type_array)
453         {
454                 for(int i = 0; i < json_object_array_length(args); i++)
455                 {
456                         x = json_object_array_get_idx(args, i);
457                         rc += process_one_subscribe_args(request, subscribe, x);
458                 }
459         }
460         else
461         {
462                 rc += process_one_subscribe_args(request, subscribe, args);
463         }
464
465         if (rc >= 0)
466                 afb_req_success(request, NULL, NULL);
467         else
468                 afb_req_fail(request, "error", NULL);
469 }
470
471 void auth(afb_req_t request)
472 {
473         afb_req_session_set_LOA(request, 1);
474         afb_req_success(request, NULL, NULL);
475 }
476
477 void subscribe(afb_req_t request)
478 {
479         do_subscribe_unsubscribe(request, true);
480 }
481
482 void unsubscribe(afb_req_t request)
483 {
484         do_subscribe_unsubscribe(request, false);
485 }
486
487 /*
488 static int send_frame(struct canfd_frame& cfd, const std::string& bus_name, socket_type type)
489 {
490         if(bus_name.empty())
491         {
492                 return -1;
493         }
494
495         std::map<std::string, std::shared_ptr<low_can_subscription_t> >& cd = application_t::instance().get_can_devices();
496
497         if( cd.count(bus_name) == 0)
498         {
499                 cd[bus_name] = std::make_shared<low_can_subscription_t>(low_can_subscription_t());
500         }
501
502
503         if(type == socket_type::BCM)
504         {
505                 return low_can_subscription_t::tx_send(*cd[bus_name], cfd, bus_name);
506         }
507         else if(type == socket_type::J1939)
508         {
509                 return low_can_subscription_t::j1939_send(*cd[bus_name], cfd, bus_name);
510         }
511         else{
512                 return -1;
513         }
514 }
515 */
516 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)
517 {
518         if(bus_name.empty())
519                 return -1;
520
521         std::map<std::string, std::shared_ptr<low_can_subscription_t> >& cd = application_t::instance().get_can_devices();
522
523         if( cd.count(bus_name) == 0)
524                 cd[bus_name] = std::make_shared<low_can_subscription_t>(low_can_subscription_t(event_filter));
525
526         cd[bus_name]->set_signal(signal);
527
528
529         if(flags&CAN_PROTOCOL)
530                 return low_can_subscription_t::tx_send(*cd[bus_name], message, bus_name);
531 #ifdef USE_FEATURE_ISOTP
532         else if(flags&ISOTP_PROTOCOL)
533                 return low_can_subscription_t::isotp_send(*cd[bus_name], message, bus_name);
534 #endif
535 #ifdef USE_FEATURE_J1939
536         else if(flags&J1939_PROTOCOL)
537                 return low_can_subscription_t::j1939_send(*cd[bus_name], message, bus_name);
538 #endif
539         else
540                 return -1;
541 }
542
543
544 static void write_raw_frame(afb_req_t request, const std::string& bus_name, message_t *message,
545                             struct json_object *can_data, uint32_t flags, event_filter_t &event_filter)
546 {
547
548         struct utils::signals_found sf;
549
550         utils::signals_manager_t::instance().lookup_signals_by_id(message->get_id(), application_t::instance().get_all_signals(), sf.signals);
551
552         if( !sf.signals.empty() )
553         {
554                 AFB_DEBUG("ID WRITE RAW : %d", sf.signals.front()->get_message()->get_id());
555                 if(flags & CAN_PROTOCOL)
556                 {
557                         if(sf.signals.front()->get_message()->is_fd())
558                         {
559                                 AFB_DEBUG("CANFD_MAX_DLEN");
560                                 message->set_flags(CAN_PROTOCOL_WITH_FD_FRAME);
561                                 message->set_maxdlen(CANFD_MAX_DLEN);
562                         }
563                         else
564                         {
565                                 AFB_DEBUG("CAN_MAX_DLEN");
566                                 message->set_maxdlen(CAN_MAX_DLEN);
567                         }
568
569                         if(sf.signals.front()->get_message()->is_isotp())
570                         {
571                                 flags = ISOTP_PROTOCOL;
572                                 message->set_maxdlen(MAX_ISOTP_FRAMES * message->get_maxdlen());
573                         }
574                 }
575
576 #ifdef USE_FEATURE_J1939
577                 if(flags&J1939_PROTOCOL)
578                         message->set_maxdlen(J1939_MAX_DLEN);
579 #endif
580
581                 if(message->get_length() > 0 && message->get_length() <= message->get_maxdlen())
582                 {
583                         std::vector<uint8_t> data;
584                         for (int i = 0 ; i < message->get_length() ; i++)
585                         {
586                                 struct json_object *one_can_data = json_object_array_get_idx(can_data, i);
587                                 data.push_back((json_object_is_type(one_can_data, json_type_int)) ?
588                                                 (uint8_t)json_object_get_int(one_can_data) : 0);
589                         }
590                         message->set_data(data);
591                 }
592                 else
593                 {
594                         if(flags&CAN_PROTOCOL)
595                                 afb_req_fail(request, "Invalid", "Frame BCM");
596                         else if(flags&J1939_PROTOCOL)
597                                 afb_req_fail(request, "Invalid", "Frame J1939");
598                         else if(flags&ISOTP_PROTOCOL)
599                                 afb_req_fail(request, "Invalid", "Frame ISOTP");
600                         else
601                                 afb_req_fail(request, "Invalid", "Frame");
602
603                         return;
604                 }
605
606                 if(! send_message(message, application_t::instance().get_can_bus_manager().get_can_device_name(bus_name), flags, event_filter, sf.signals.front()))
607                         afb_req_success(request, nullptr, "Message correctly sent");
608                 else
609                         afb_req_fail(request, "Error", "sending the message. See the log for more details.");
610         }
611         else
612         {
613                 afb_req_fail(request, "Error", "no find id in signals. See the log for more details.");
614         }
615
616 }
617
618 static void write_frame(afb_req_t request, const std::string& bus_name, json_object *json_value, event_filter_t &event_filter)
619 {
620         message_t *message;
621         uint32_t id;
622         uint32_t length;
623         struct json_object *can_data = nullptr;
624         std::vector<uint8_t> data;
625
626         AFB_DEBUG("JSON content %s", json_object_get_string(json_value));
627
628         if(!wrap_json_unpack(json_value, "{si, si, so !}",
629                                   "can_id", &id,
630                                   "can_dlc", &length,
631                                   "can_data", &can_data))
632         {
633                 message = new can_message_t(0, id, length, false, 0, data, 0);
634                 write_raw_frame(request, bus_name, message, can_data, CAN_PROTOCOL, event_filter);
635         }
636 #ifdef USE_FEATURE_J1939
637         else if(!wrap_json_unpack(json_value, "{si, si, so !}",
638                                   "pgn", &id,
639                                   "length", &length,
640                                   "data", &can_data))
641         {
642                 message = new j1939_message_t(length, data, 0, J1939_NO_NAME, (pgn_t)id, J1939_NO_ADDR);
643                 write_raw_frame(request, bus_name, message, can_data, J1939_PROTOCOL, event_filter);
644         }
645 #endif
646         else
647         {
648                 afb_req_fail(request, "Invalid", "Frame object malformed");
649                 return;
650         }
651         delete message;
652 }
653
654 static void write_signal(afb_req_t request, const std::string& name, json_object *json_value, event_filter_t &event_filter)
655 {
656         struct canfd_frame cfd;
657         struct utils::signals_found sf;
658         signal_encoder encoder = nullptr;
659         bool send = true;
660
661         ::memset(&cfd, 0, sizeof(cfd));
662
663         openxc_DynamicField search_key = build_DynamicField(name);
664         sf = utils::signals_manager_t::instance().find_signals(search_key);
665         openxc_DynamicField dynafield_value = build_DynamicField(json_value);
666
667         if (sf.signals.empty())
668         {
669                 afb_req_fail_f(request, "No signal(s) found for %s. Message not sent.", name.c_str());
670                 return;
671         }
672
673         std::shared_ptr<signal_t> sig = sf.signals.front();
674         if(! sig->get_writable())
675         {
676                 afb_req_fail_f(request, "%s isn't writable. Message not sent.", sig->get_name().c_str());
677                 return;
678         }
679
680         uint64_t value = (encoder = sig->get_encoder()) ?
681                         encoder(*sig, dynafield_value, &send) :
682                         encoder_t::encode_DynamicField(*sig, dynafield_value, &send);
683
684         uint32_t flags = INVALID_FLAG;
685
686         if(sig->get_message()->is_j1939())
687                 flags = J1939_PROTOCOL;
688         else if(sig->get_message()->is_isotp())
689                 flags = ISOTP_PROTOCOL;
690         else
691                 flags = CAN_PROTOCOL;
692
693 //      cfd = encoder_t::build_frame(sig, value);
694         message_t *message = encoder_t::build_message(sig, value, false, false);
695
696         if(! send_message(message, sig->get_message()->get_bus_device_name(), flags, event_filter, sig) && send)
697                 afb_req_success(request, nullptr, "Message correctly sent");
698         else
699                 afb_req_fail(request, "Error", "Sending the message. See the log for more details.");
700
701         if(sig->get_message()->is_j1939())
702 #ifdef USE_FEATURE_J1939
703                 delete (j1939_message_t*) message;
704 #else
705                 afb_req_fail(request, "Warning", "J1939 not implemented in your kernel.");
706 #endif
707         else
708                 delete (can_message_t*) message;
709 }
710
711 void write(afb_req_t request)
712 {
713         struct json_object* args = nullptr, *json_value = nullptr, *name = nullptr;
714         args = afb_req_json(request);
715
716         if(args != NULL)
717         {
718                 event_filter_t event_filter = generate_filter(args);
719
720                 if(json_object_object_get_ex(args,"bus_name",&name))
721                 {
722                         if(json_object_object_get_ex(args,"frame",&json_value))
723                                 write_frame(request, (std::string)json_object_get_string(name), json_value, event_filter);
724                         else
725                                 afb_req_fail(request, "Error", "Request argument malformed");
726                 }
727                 else if(json_object_object_get_ex(args,"signal_name",&name))
728                 {
729                         if(json_object_object_get_ex(args,"signal_value",&json_value))
730                                 write_signal(request, (std::string)json_object_get_string(name), json_value, event_filter);
731                         else
732                                 afb_req_fail(request, "Error", "Request argument malformed");
733                 }
734                 else
735                 {
736                         afb_req_fail(request, "Error", "Request argument malformed");
737                 }
738         }
739         else
740         {
741                 afb_req_fail(request, "Error", "Request argument null");
742         }
743 }
744
745 static struct json_object *get_signals_value(const std::string& name)
746 {
747         struct utils::signals_found sf;
748         struct json_object *ans = nullptr;
749
750         openxc_DynamicField search_key = build_DynamicField(name);
751         sf = utils::signals_manager_t::instance().find_signals(search_key);
752
753         if (sf.signals.empty())
754         {
755                 AFB_WARNING("No signal(s) found for %s.", name.c_str());
756                 return NULL;
757         }
758         ans = json_object_new_array();
759         for(const auto& sig: sf.signals)
760         {
761                 struct json_object *jobj = json_object_new_object();
762                 json_object_object_add(jobj, "event", json_object_new_string(sig->get_name().c_str()));
763                 json_object_object_add(jobj, "value", json_object_new_double(sig->get_last_value()));
764                 json_object_array_add(ans, jobj);
765         }
766
767         return ans;
768 }
769 void get(afb_req_t request)
770 {
771         int rc = 0;
772         struct json_object* args = nullptr,
773                 *json_name = nullptr;
774         json_object *ans = nullptr;
775
776         args = afb_req_json(request);
777
778         // Process about Raw CAN message on CAN bus directly
779         if (args != nullptr &&
780                 (json_object_object_get_ex(args, "event", &json_name) && json_object_is_type(json_name, json_type_string) ))
781         {
782                 ans = get_signals_value(json_object_get_string(json_name));
783                 if (!ans)
784                         rc = -1;
785         }
786         else
787         {
788                 AFB_ERROR("Request argument malformed. Please use the following syntax:");
789                 rc = -1;
790         }
791
792         if (rc >= 0)
793                 afb_req_success(request, ans, NULL);
794         else
795                 afb_req_fail(request, "error", NULL);
796 }
797
798
799 static struct json_object *list_can_message(const std::string& name)
800 {
801         struct utils::signals_found sf;
802         struct json_object *ans = nullptr;
803
804         openxc_DynamicField search_key = build_DynamicField(name);
805         sf = utils::signals_manager_t::instance().find_signals(search_key);
806
807         if (sf.signals.empty() && sf.diagnostic_messages.empty())
808         {
809                 AFB_WARNING("No signal(s) found for %s.", name.c_str());
810                 return NULL;
811         }
812         ans = json_object_new_array();
813         for(const auto& sig: sf.signals)
814         {
815                 json_object_array_add(ans,
816                         json_object_new_string(sig->get_name().c_str()));
817         }
818         for(const auto& sig: sf.diagnostic_messages)
819         {
820                 json_object_array_add(ans,
821                         json_object_new_string(sig->get_name().c_str()));
822         }
823
824         return ans;
825 }
826
827 void list(afb_req_t request)
828 {
829         int rc = 0;
830         json_object *ans = nullptr;
831         struct json_object* args = nullptr,
832                 *json_name = nullptr;
833         args = afb_req_json(request);
834         const char *name;
835         if ((args != nullptr) &&
836                 (json_object_object_get_ex(args, "event", &json_name) && json_object_is_type(json_name, json_type_string)))
837                 name = json_object_get_string(json_name);
838         else
839                 name = "*";
840
841         ans = list_can_message(name);
842         if (!ans)
843                 rc = -1;
844
845         if (rc >= 0)
846                 afb_req_success(request, ans, NULL);
847         else
848                 afb_req_fail(request, "error", NULL);
849 }
850
851 /// @brief Initialize the binding.
852 ///
853 /// @param[in] service Structure which represent the Application Framework Binder.
854 ///
855 /// @return Exit code, zero if success.
856 int init_binding(afb_api_t api)
857 {
858         int ret = 1;
859         application_t& application = application_t::instance();
860         can_bus_t& can_bus_manager = application.get_can_bus_manager();
861
862         if(application.get_message_set().empty())
863         {
864                 AFB_ERROR("No message_set defined");
865                 return -1;
866         }
867
868         can_bus_manager.set_can_devices();
869         can_bus_manager.start_threads();
870         utils::signals_manager_t& sm = utils::signals_manager_t::instance();
871
872         // Add a recurring dignostic message request to get engine speed at all times.
873         openxc_DynamicField search_key = build_DynamicField("diagnostic_messages.engine.speed");
874         struct utils::signals_found sf = sm.find_signals(search_key);
875
876         if(sf.signals.empty() && sf.diagnostic_messages.size() == 1)
877         {
878                 afb_req_t request = nullptr;
879
880                 struct event_filter_t event_filter;
881                 event_filter.frequency = sf.diagnostic_messages.front()->get_frequency();
882
883                 map_subscription& s = sm.get_subscribed_signals();
884
885                 subscribe_unsubscribe_diagnostic_messages(request, true, sf.diagnostic_messages, event_filter, s, true);
886         }
887
888
889 #ifdef USE_FEATURE_J1939
890         std::string j1939_bus;
891         vect_ptr_msg_def_t current_messages_definition = application.get_messages_definition();
892         for(std::shared_ptr<message_definition_t> message_definition: current_messages_definition)
893         {
894                 if(message_definition->is_j1939())
895                 {
896                         if (j1939_bus == message_definition->get_bus_device_name() )
897                                 continue;
898                         j1939_bus = message_definition->get_bus_device_name();
899
900                         std::shared_ptr<low_can_subscription_t> low_can_j1939 = std::make_shared<low_can_subscription_t>();
901                         application.set_subscription_address_claiming(low_can_j1939);
902
903                         ret = low_can_subscription_t::open_socket(*low_can_j1939,
904                                                                   j1939_bus,
905                                                                   J1939_ADDR_CLAIM_PROTOCOL);
906
907                         if(ret < 0)
908                         {
909                                 AFB_ERROR("Error open socket address claiming for j1939 protocol");
910                                 return -1;
911                         }
912                         add_to_event_loop(low_can_j1939);
913                         break;
914                 }
915         }
916 #endif
917
918         if(ret)
919                 AFB_ERROR("There was something wrong with CAN device Initialization.");
920
921         return ret;
922 }
923
924 int load_config(afb_api_t api)
925 {
926         int ret = 0;
927         CtlConfigT *ctlConfig;
928         const char *dirList = getenv("CONTROL_CONFIG_PATH");
929         std::string bindingDirPath = GetBindingDirPath(api);
930         std::string filepath = bindingDirPath + "/etc";
931
932         if (!dirList)
933                 dirList=CONTROL_CONFIG_PATH;
934
935         filepath.append(":");
936         filepath.append(dirList);
937         const char *configPath = CtlConfigSearch(api, filepath.c_str(), "control");
938
939         if (!configPath)
940         {
941                 AFB_ERROR_V3("CtlPreInit: No control-* config found invalid JSON %s ", filepath.c_str());
942                 return -1;
943         }
944
945         // create one API per file
946         ctlConfig = CtlLoadMetaData(api, configPath);
947         if (!ctlConfig)
948         {
949                 AFB_ERROR_V3("CtrlPreInit No valid control config file in:\n-- %s", configPath);
950                 return -1;
951         }
952
953         // Save the config in the api userdata field
954         afb_api_set_userdata(api, ctlConfig);
955
956         setExternalData(ctlConfig, (void*) &application_t::instance());
957         ret= CtlLoadSections(api, ctlConfig, ctlSections_);
958
959         return ret;
960 }