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