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