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