2 * Copyright (C) 2015, 2018 "IoT.bzh"
3 * Author "Romain Forlot" <romain.forlot@iot.bzh>
4 * Author "Loic Collignon" <loic.collignon@iot.bzh>
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
10 * http://www.apache.org/licenses/LICENSE-2.0
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.
19 #include "low-can-hat.hpp"
20 #include "low-can-apidef.h"
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"
42 #ifdef USE_FEATURE_J1939
43 #include "../can/message/j1939-message.hpp"
44 #include <linux/can/j1939.h>
47 ///*****************************************************************************
49 /// Controller Definitions and Callbacks
51 ///****************************************************************************/
53 int config_low_can(afb_api_t apiHandle, CtlSectionT *section, json_object *json_obj)
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;
61 if(! ctrlConfig || ! ctrlConfig->external)
64 application_t *application = (application_t*) ctrlConfig->external;
66 if(wrap_json_unpack(json_obj, "{si, s?s}",
67 "active_message_set", &active_message_set,
68 "diagnostic_bus", &diagnotic_bus))
71 application->set_active_message_set((uint8_t)active_message_set);
73 if(wrap_json_unpack(json_obj, "{so}",
74 "dev-mapping", &dev_mapping))
77 application->get_can_bus_manager().set_can_devices(dev_mapping);
79 /// Initialize Diagnostic manager that will handle obd2 requests.
80 /// We pass by default the first CAN bus device to its Initialization.
81 if(! diagnotic_bus || application_t::instance().get_diagnostic_manager().initialize(diagnotic_bus))
82 AFB_WARNING("Diagnostic Manager: not initialized. No diagnostic messages will be processed.");
87 CtlSectionT ctlSections_[] = {
88 [0]={.key="config" , .uid="config", .info=nullptr,
89 .loadCB=config_low_can,
92 [1]={.key="plugins" , .uid="plugins", .info=nullptr,
96 [2]={.key=nullptr , .uid=nullptr, .info=nullptr,
102 ///*****************************************************************************
104 /// Subscription and unsubscription
106 ///****************************************************************************/
108 /// @brief This will determine if an event handle needs to be created and checks if
109 /// we got a valid afb_event to get subscribe or unsubscribe. After that launch the subscription or unsubscription
110 /// against the application framework using that event handle.
111 static int subscribe_unsubscribe_signal(afb_req_t request,
113 std::shared_ptr<low_can_subscription_t>& can_subscription,
117 int sub_index = can_subscription->get_index();
118 bool subscription_exists = s.count(sub_index);
123 /* There is no valid request to subscribe so this must be an
124 * internal permanent diagnostic request. Skip the subscription
125 * part and don't register it into the current "low-can"
131 // Event doesn't exist , so let's create it
132 if ((ret = can_subscription->subscribe(request)) < 0)
135 if(! subscription_exists)
136 s[sub_index] = can_subscription;
141 // Unsubscrition part
142 if(! subscription_exists)
144 AFB_NOTICE("There isn't any valid subscriptions for that request.");
147 else if (subscription_exists &&
148 ! afb_event_is_valid(s[sub_index]->get_event()) )
150 AFB_NOTICE("Event isn't valid, no need to unsubscribed.");
154 if( (ret = s[sub_index]->unsubscribe(request)) < 0)
156 s.find(sub_index)->second->set_index(-1);
161 static int add_to_event_loop(std::shared_ptr<low_can_subscription_t>& can_subscription)
163 struct sd_event_source* event_source = nullptr;
164 return ( sd_event_add_io(afb_daemon_get_event_loop(),
166 can_subscription->get_socket()->socket(),
169 can_subscription.get()));
172 static int subscribe_unsubscribe_diagnostic_messages(afb_req_t request,
174 list_ptr_diag_msg_t diagnostic_messages,
175 struct event_filter_t& event_filter,
177 bool perm_rec_diag_req)
180 application_t& app = application_t::instance();
181 diagnostic_manager_t& diag_m = app.get_diagnostic_manager();
183 for(const auto& sig : diagnostic_messages)
185 DiagnosticRequest* diag_req = new DiagnosticRequest(sig->build_diagnostic_request());
186 event_filter.frequency = event_filter.frequency == 0 ? sig->get_frequency() : event_filter.frequency;
187 std::shared_ptr<low_can_subscription_t> can_subscription;
189 auto it = std::find_if(s.begin(), s.end(), [&sig](std::pair<int, std::shared_ptr<low_can_subscription_t> > sub)
191 return (! sub.second->get_diagnostic_message().empty());
193 can_subscription = it != s.end() ?
195 std::make_shared<low_can_subscription_t>(low_can_subscription_t(event_filter));
196 // If the requested diagnostic message is not supported by the car then unsubcribe it
197 // no matter what we want, worst case will be a failed unsubscription but at least we won't
198 // poll a PID for nothing.
199 if(sig->get_supported() && subscribe)
201 if (!app.is_engine_on())
202 AFB_WARNING("signal: Engine is off, %s won't received responses until it's on", sig->get_name().c_str());
204 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);
205 if(can_subscription->create_rx_filter(sig) < 0)
207 AFB_DEBUG("Signal: %s subscribed", sig->get_name().c_str());
208 if(it == s.end() && add_to_event_loop(can_subscription) < 0)
210 diag_m.cleanup_request(
211 diag_m.find_recurring_request(*diag_req), true);
212 AFB_WARNING("signal: %s isn't supported. Canceling operation.", sig->get_name().c_str());
218 if(sig->get_supported())
220 AFB_DEBUG("%s cancelled due to unsubscribe", sig->get_name().c_str());
224 AFB_WARNING("signal: %s isn't supported. Canceling operation.", sig->get_name().c_str());
228 int ret = subscribe_unsubscribe_signal(request, subscribe, can_subscription, s);
237 static int subscribe_unsubscribe_signals(afb_req_t request,
239 list_ptr_signal_t signals,
240 struct event_filter_t& event_filter,
244 for(const auto& sig: signals)
246 auto it = std::find_if(s.begin(), s.end(), [&sig, &event_filter](std::pair<int, std::shared_ptr<low_can_subscription_t> > sub)
248 return sub.second->is_signal_subscription_corresponding(sig, event_filter) ;
250 std::shared_ptr<low_can_subscription_t> can_subscription;
252 can_subscription = it->second;
255 can_subscription = std::make_shared<low_can_subscription_t>(low_can_subscription_t(event_filter));
256 if(can_subscription->create_rx_filter(sig) < 0)
258 if(add_to_event_loop(can_subscription) < 0)
262 if(subscribe_unsubscribe_signal(request, subscribe, can_subscription, s) < 0)
266 AFB_DEBUG("%s Signal: %s %ssubscribed", sig->get_message()->is_fd() ? "FD": "", sig->get_name().c_str(), subscribe ? "":"un");
272 /// @brief subscribe to all signals in the vector signals
274 /// @param[in] afb_req request : contains original request use to subscribe or unsubscribe
275 /// @param[in] subscribe boolean value, which chooses between a subscription operation or an unsubscription
276 /// @param[in] signals - struct containing vectors with signal_t and diagnostic_messages to subscribe
277 /// @param[in] event_filter - stuct containing filter on the signal
279 /// @return Number of correctly subscribed signal
281 static int subscribe_unsubscribe_signals(afb_req_t request,
283 const struct utils::signals_found& signals,
284 struct event_filter_t& event_filter)
287 utils::signals_manager_t& sm = utils::signals_manager_t::instance();
289 std::lock_guard<std::mutex> subscribed_signals_lock(sm.get_subscribed_signals_mutex());
290 map_subscription& s = sm.get_subscribed_signals();
292 rets += subscribe_unsubscribe_diagnostic_messages(request, subscribe, signals.diagnostic_messages, event_filter, s, false);
293 rets += subscribe_unsubscribe_signals(request, subscribe, signals.signals, event_filter, s);
298 static event_filter_t generate_filter(json_object* args)
300 event_filter_t event_filter = {};
301 struct json_object *filter, *obj;
303 // computes the filter
304 if (json_object_object_get_ex(args, "filter", &filter))
306 if (json_object_object_get_ex(filter, "frequency", &obj)
307 && (json_object_is_type(obj, json_type_double) || json_object_is_type(obj, json_type_int)))
308 event_filter.frequency = (float)json_object_get_double(obj);
309 if (json_object_object_get_ex(filter, "min", &obj)
310 && (json_object_is_type(obj, json_type_double) || json_object_is_type(obj, json_type_int)))
311 event_filter.min = (float)json_object_get_double(obj);
312 if (json_object_object_get_ex(filter, "max", &obj)
313 && (json_object_is_type(obj, json_type_double) || json_object_is_type(obj, json_type_int)))
314 event_filter.max = (float)json_object_get_double(obj);
315 if (json_object_object_get_ex(filter, "promisc", &obj)
316 && (json_object_is_type(obj, json_type_boolean)))
317 event_filter.promisc = (bool)json_object_get_boolean(obj);
318 if (json_object_object_get_ex(filter, "rx_id", &obj)
319 && (json_object_is_type(obj, json_type_int)))
320 event_filter.rx_id = (canid_t) json_object_get_int(obj);
321 if (json_object_object_get_ex(filter, "tx_id", &obj)
322 && (json_object_is_type(obj, json_type_int)))
323 event_filter.tx_id = (canid_t) json_object_get_int(obj);
329 static int one_subscribe_unsubscribe_events(afb_req_t request, bool subscribe, const std::string& tag, json_object* args)
332 struct utils::signals_found sf;
334 // subscribe or unsubscribe
335 openxc_DynamicField search_key = build_DynamicField(tag);
336 sf = utils::signals_manager_t::instance().find_signals(search_key);
339 #ifdef USE_FEATURE_ISOTP
340 if(sf.signals.size() > 1)
342 sf.signals.remove_if([](std::shared_ptr<signal_t> x){
343 bool isotp = x->get_message()->is_isotp();
345 AFB_NOTICE("ISO TP messages need to be subscribed one by one (rx, tx)");
352 if (sf.signals.empty() && sf.diagnostic_messages.empty())
354 AFB_NOTICE("No signal(s) found for %s.", tag.c_str());
359 event_filter_t event_filter = generate_filter(args);
360 ret = subscribe_unsubscribe_signals(request, subscribe, sf, event_filter);
365 static int one_subscribe_unsubscribe_id(afb_req_t request, bool subscribe, const uint32_t& id, json_object *args)
367 std::shared_ptr<message_definition_t> message_definition = application_t::instance().get_message_definition(id);
368 struct utils::signals_found sf;
370 if(message_definition)
371 sf.signals = list_ptr_signal_t(message_definition->get_signals().begin(), message_definition->get_signals().end());
373 if(sf.signals.empty())
375 AFB_NOTICE("No signal(s) found for %d.", id);
379 event_filter_t event_filter = generate_filter(args);
380 std::shared_ptr<low_can_subscription_t> can_subscription = std::make_shared<low_can_subscription_t>(low_can_subscription_t(event_filter));
381 can_subscription->set_message_definition(message_definition);
383 utils::signals_manager_t& sm = utils::signals_manager_t::instance();
384 std::lock_guard<std::mutex> subscribed_signals_lock(sm.get_subscribed_signals_mutex());
385 map_subscription& s = sm.get_subscribed_signals();
387 if(can_subscription->create_rx_filter(message_definition) < 0)
389 if(add_to_event_loop(can_subscription) < 0)
392 if(subscribe_unsubscribe_signal(request, subscribe, can_subscription, s) < 0)
399 static int process_one_subscribe_args(afb_req_t request, bool subscribe, json_object *args)
402 json_object *x = nullptr, *event = nullptr, *id = nullptr;
405 // 2 cases : ID(PGN) and event
407 json_object_object_get_ex(args,"event",&event);
408 json_object_object_get_ex(args,"id",&id) || json_object_object_get_ex(args,"pgn",&id);
410 if( args == NULL || (id && ((std::string)json_object_get_string(id)).compare("*") == 0))
412 rc = one_subscribe_unsubscribe_events(request, subscribe, "*", args);
418 if (json_object_get_type(event) != json_type_array) // event is set before and check if it's an array
420 rc = one_subscribe_unsubscribe_events(request, subscribe, json_object_get_string(event), args);
422 else // event is set and it's not an array
424 for (int i = 0 ; i < json_object_array_length(event); i++)
426 x = json_object_array_get_idx(event, i);
427 rc2 = one_subscribe_unsubscribe_events(request, subscribe, json_object_get_string(x), args);
429 rc = rc2 >= 0 ? rc + rc2 : rc2;
436 if (json_object_get_type(id) != json_type_array) // id is set before and check if it's an array
438 rc = one_subscribe_unsubscribe_id(request, subscribe, json_object_get_int(id), args);
440 else // event is set and it's not an array
442 for (int i = 0 ; i < json_object_array_length(id); i++)
444 x = json_object_array_get_idx(id, i);
445 rc2 = one_subscribe_unsubscribe_id(request, subscribe, json_object_get_int(x), args);
447 rc = rc2 >= 0 ? rc + rc2 : rc2;
455 static void do_subscribe_unsubscribe(afb_req_t request, bool subscribe)
458 struct json_object *args, *x;
460 args = afb_req_json(request);
461 if (json_object_get_type(args) == json_type_array)
463 for(int i = 0; i < json_object_array_length(args); i++)
465 x = json_object_array_get_idx(args, i);
466 rc += process_one_subscribe_args(request, subscribe, x);
471 rc += process_one_subscribe_args(request, subscribe, args);
475 afb_req_success(request, NULL, NULL);
477 afb_req_fail(request, "error", NULL);
480 void auth(afb_req_t request)
482 afb_req_session_set_LOA(request, 1);
483 afb_req_success(request, NULL, NULL);
486 void subscribe(afb_req_t request)
488 do_subscribe_unsubscribe(request, true);
491 void unsubscribe(afb_req_t request)
493 do_subscribe_unsubscribe(request, false);
496 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)
501 std::map<std::string, std::shared_ptr<low_can_subscription_t> >& cd = application_t::instance().get_can_devices();
503 if( cd.count(bus_name) == 0)
504 cd[bus_name] = std::make_shared<low_can_subscription_t>(low_can_subscription_t(event_filter));
506 cd[bus_name]->set_signal(signal);
509 if(flags&CAN_PROTOCOL)
510 return low_can_subscription_t::tx_send(*cd[bus_name], message, bus_name);
511 #ifdef USE_FEATURE_ISOTP
512 else if(flags&ISOTP_PROTOCOL)
513 return low_can_subscription_t::isotp_send(*cd[bus_name], message, bus_name);
515 #ifdef USE_FEATURE_J1939
516 else if(flags&J1939_PROTOCOL)
517 return low_can_subscription_t::j1939_send(*cd[bus_name], message, bus_name);
524 static void write_raw_frame(afb_req_t request, const std::string& bus_name, message_t *message,
525 struct json_object *can_data, uint32_t flags, event_filter_t &event_filter)
528 struct utils::signals_found sf;
530 utils::signals_manager_t::instance().lookup_signals_by_id(message->get_id(), application_t::instance().get_all_signals(), sf.signals);
532 if( !sf.signals.empty() )
534 AFB_DEBUG("ID WRITE RAW : %d", sf.signals.front()->get_message()->get_id());
535 if(flags & CAN_PROTOCOL)
537 if(sf.signals.front()->get_message()->is_fd())
539 AFB_DEBUG("CANFD_MAX_DLEN");
540 message->set_flags(CAN_PROTOCOL_WITH_FD_FRAME);
541 message->set_maxdlen(CANFD_MAX_DLEN);
545 AFB_DEBUG("CAN_MAX_DLEN");
546 message->set_maxdlen(CAN_MAX_DLEN);
549 if(sf.signals.front()->get_message()->is_isotp())
551 flags = ISOTP_PROTOCOL;
552 message->set_maxdlen(MAX_ISOTP_FRAMES * message->get_maxdlen());
556 #ifdef USE_FEATURE_J1939
557 if(flags&J1939_PROTOCOL)
558 message->set_maxdlen(J1939_MAX_DLEN);
561 if(message->get_length() > 0 &&
562 message->get_length() <= message->get_maxdlen() &&
563 json_object_get_type(can_data) == json_type_array)
565 std::vector<uint8_t> data;
566 for (int i = 0 ; i < message->get_length() ; i++)
568 struct json_object *one_can_data = json_object_array_get_idx(can_data, i);
569 data.push_back((json_object_is_type(one_can_data, json_type_int)) ?
570 (uint8_t)json_object_get_int(one_can_data) : 0);
572 message->set_data(data);
576 if(flags&CAN_PROTOCOL)
577 afb_req_fail(request, "Invalid", "Frame BCM");
578 else if(flags&J1939_PROTOCOL)
579 afb_req_fail(request, "Invalid", "Frame J1939");
580 else if(flags&ISOTP_PROTOCOL)
581 afb_req_fail(request, "Invalid", "Frame ISOTP");
583 afb_req_fail(request, "Invalid", "Frame");
588 if(! send_message(message, application_t::instance().get_can_bus_manager().get_can_device_name(bus_name), flags, event_filter, sf.signals.front()))
589 afb_req_success(request, nullptr, "Message correctly sent");
591 afb_req_fail(request, "Error", "sending the message. See the log for more details.");
595 afb_req_fail(request, "Error", "no find id in signals. See the log for more details.");
600 static void write_frame(afb_req_t request, const std::string& bus_name, json_object *json_value, event_filter_t &event_filter)
605 struct json_object *can_data = nullptr;
606 std::vector<uint8_t> data;
608 AFB_DEBUG("JSON content %s", json_object_get_string(json_value));
610 if(!wrap_json_unpack(json_value, "{si, si, so !}",
613 "can_data", &can_data))
615 message = new can_message_t(0, id, length, false, 0, data, 0);
616 write_raw_frame(request, bus_name, message, can_data, CAN_PROTOCOL, event_filter);
618 #ifdef USE_FEATURE_J1939
619 else if(!wrap_json_unpack(json_value, "{si, si, so !}",
624 message = new j1939_message_t(length, data, 0, J1939_NO_NAME, (pgn_t)id, J1939_NO_ADDR);
625 write_raw_frame(request, bus_name, message, can_data, J1939_PROTOCOL, event_filter);
630 afb_req_fail(request, "Invalid", "Frame object malformed");
636 static void write_signal(afb_req_t request, const std::string& name, json_object *json_value, event_filter_t &event_filter)
638 struct canfd_frame cfd;
639 struct utils::signals_found sf;
640 signal_encoder encoder = nullptr;
643 ::memset(&cfd, 0, sizeof(cfd));
645 openxc_DynamicField search_key = build_DynamicField(name);
646 sf = utils::signals_manager_t::instance().find_signals(search_key);
647 openxc_DynamicField dynafield_value = build_DynamicField(json_value);
649 if (sf.signals.empty())
651 afb_req_fail_f(request, "No signal(s) found for %s. Message not sent.", name.c_str());
655 std::shared_ptr<signal_t> sig = sf.signals.front();
656 if(! sig->get_writable())
658 afb_req_fail_f(request, "%s isn't writable. Message not sent.", sig->get_name().c_str());
662 uint64_t value = (encoder = sig->get_encoder()) ?
663 encoder(*sig, dynafield_value, &send) :
664 encoder_t::encode_DynamicField(*sig, dynafield_value, &send);
666 uint32_t flags = INVALID_FLAG;
668 if(sig->get_message()->is_j1939())
669 flags = J1939_PROTOCOL;
670 else if(sig->get_message()->is_isotp())
671 flags = ISOTP_PROTOCOL;
673 flags = CAN_PROTOCOL;
675 // cfd = encoder_t::build_frame(sig, value);
676 message_t *message = encoder_t::build_message(sig, value, false, false);
678 if(! send_message(message, sig->get_message()->get_bus_device_name(), flags, event_filter, sig) && send)
679 afb_req_success(request, nullptr, "Message correctly sent");
681 afb_req_fail(request, "Error", "Sending the message. See the log for more details.");
683 if(sig->get_message()->is_j1939())
684 #ifdef USE_FEATURE_J1939
685 delete (j1939_message_t*) message;
687 afb_req_fail(request, "Warning", "J1939 not implemented in your kernel.");
690 delete (can_message_t*) message;
693 void write(afb_req_t request)
695 struct json_object* args = nullptr, *json_value = nullptr, *name = nullptr;
696 args = afb_req_json(request);
700 event_filter_t event_filter = generate_filter(args);
702 if(json_object_object_get_ex(args,"bus_name",&name))
704 if(json_object_object_get_ex(args,"frame",&json_value))
705 write_frame(request, (std::string)json_object_get_string(name), json_value, event_filter);
707 afb_req_fail(request, "Error", "Request argument malformed");
709 else if(json_object_object_get_ex(args,"signal_name",&name))
711 if(json_object_object_get_ex(args,"signal_value",&json_value))
712 write_signal(request, (std::string)json_object_get_string(name), json_value, event_filter);
714 afb_req_fail(request, "Error", "Request argument malformed");
718 afb_req_fail(request, "Error", "Request argument malformed");
723 afb_req_fail(request, "Error", "Request argument null");
727 static struct json_object *get_signals_value(const std::string& name)
729 struct utils::signals_found sf;
730 struct json_object *ans = nullptr;
732 openxc_DynamicField search_key = build_DynamicField(name);
733 sf = utils::signals_manager_t::instance().find_signals(search_key);
735 if (sf.signals.empty())
737 AFB_WARNING("No signal(s) found for %s.", name.c_str());
740 ans = json_object_new_array();
741 for(const auto& sig: sf.signals)
743 struct json_object *jobj = json_object_new_object();
744 json_object_object_add(jobj, "event", json_object_new_string(sig->get_name().c_str()));
745 json_object_object_add(jobj, "value", json_object_new_double(sig->get_last_value()));
746 json_object_array_add(ans, jobj);
752 static struct json_object *get_id_value(const uint32_t& id)
754 std::shared_ptr<message_definition_t> message_definition = application_t::instance().get_message_definition(id);
755 struct utils::signals_found sf;
756 struct json_object *ans = nullptr;
758 if(message_definition)
759 sf.signals = list_ptr_signal_t(message_definition->get_signals().begin(), message_definition->get_signals().end());
761 if(sf.signals.empty())
763 AFB_WARNING("no signal(s) found for %d.", id);
767 ans = json_object_new_object();
768 struct json_object *jsignals = json_object_new_array();
769 json_object_object_add(ans, "signals", jsignals);
770 for(const auto& sig: sf.signals)
772 struct json_object *jobj = json_object_new_object();
773 json_object_object_add(jobj, "name", json_object_new_string(sig->get_name().c_str()));
774 json_object_object_add(jobj, "value", json_object_new_double(sig->get_last_value()));
775 json_object_array_add(jsignals, jobj);
781 void get(afb_req_t request)
784 struct json_object* args = nullptr,
785 *json_name = nullptr;
786 json_object *ans = nullptr;
788 args = afb_req_json(request);
790 // Process about Raw CAN message on CAN bus directly
791 if (args != nullptr &&
792 (json_object_object_get_ex(args, "event", &json_name) && json_object_is_type(json_name, json_type_string) ))
794 ans = get_signals_value(json_object_get_string(json_name));
798 else if (args != nullptr &&
799 (json_object_object_get_ex(args, "id", &json_name)))
801 if (json_object_get_type(json_name) == json_type_string) // id is set before and check if it's an array
803 ans = get_id_value(json_object_get_int(json_name));
805 else if(json_object_get_type(json_name) == json_type_array)
807 ans = json_object_new_array();
808 for (int i = 0 ; i < json_object_array_length(json_name); i++)
810 json_object *sub_ans = nullptr;
811 json_object *x = json_object_array_get_idx(json_name, i);
812 sub_ans = get_id_value(json_object_get_int(x));
816 struct json_object *jobj = json_object_new_object();
817 struct json_object *jid = json_object_new_string(json_object_get_string(x));
818 json_object_object_add(jobj, "id", jid);
819 json_object_object_add(jobj, "data", sub_ans);
820 json_object_array_add(ans, jobj);
831 AFB_ERROR("Request argument malformed. Please use the following syntax:");
836 afb_req_success(request, ans, NULL);
838 afb_req_fail(request, "error", NULL);
842 static struct json_object *list_can_message(const std::string& name)
844 struct utils::signals_found sf;
845 struct json_object *ans = nullptr;
847 openxc_DynamicField search_key = build_DynamicField(name);
848 sf = utils::signals_manager_t::instance().find_signals(search_key);
850 if (sf.signals.empty() && sf.diagnostic_messages.empty())
852 AFB_WARNING("No signal(s) found for %s.", name.c_str());
855 ans = json_object_new_array();
856 for(const auto& sig: sf.signals)
858 json_object_array_add(ans,
859 json_object_new_string(sig->get_name().c_str()));
861 for(const auto& sig: sf.diagnostic_messages)
863 json_object_array_add(ans,
864 json_object_new_string(sig->get_name().c_str()));
870 void list(afb_req_t request)
873 json_object *ans = nullptr;
874 struct json_object* args = nullptr,
875 *json_name = nullptr;
876 args = afb_req_json(request);
878 if ((args != nullptr) &&
879 (json_object_object_get_ex(args, "event", &json_name) && json_object_is_type(json_name, json_type_string)))
880 name = json_object_get_string(json_name);
884 ans = list_can_message(name);
889 afb_req_success(request, ans, NULL);
891 afb_req_fail(request, "error", NULL);
895 /// @brief Initialize the binding.
897 /// @param[in] service Structure which represent the Application Framework Binder.
899 /// @return Exit code, zero if success.
900 int init_binding(afb_api_t api)
903 application_t& application = application_t::instance();
904 can_bus_t& can_bus_manager = application.get_can_bus_manager();
906 if(application.get_message_set().empty())
908 AFB_ERROR("No message_set defined");
912 can_bus_manager.start_threads();
913 utils::signals_manager_t& sm = utils::signals_manager_t::instance();
915 if (application.get_diagnostic_manager().is_initialized())
917 // Add a recurring dignostic message request to get engine speed at all times.
918 openxc_DynamicField search_key = build_DynamicField("diagnostic_messages.engine.speed");
919 struct utils::signals_found sf = sm.find_signals(search_key);
921 if(sf.signals.empty() && sf.diagnostic_messages.size() == 1)
923 afb_req_t request = nullptr;
925 struct event_filter_t event_filter;
926 event_filter.frequency = sf.diagnostic_messages.front()->get_frequency();
928 map_subscription& s = sm.get_subscribed_signals();
930 subscribe_unsubscribe_diagnostic_messages(request, true, sf.diagnostic_messages, event_filter, s, true);
934 #ifdef USE_FEATURE_J1939
935 std::string j1939_bus;
936 vect_ptr_msg_def_t current_messages_definition = application.get_messages_definition();
937 for(std::shared_ptr<message_definition_t> message_definition: current_messages_definition)
939 if(message_definition->is_j1939())
941 if (j1939_bus == message_definition->get_bus_device_name() )
943 j1939_bus = message_definition->get_bus_device_name();
945 std::shared_ptr<low_can_subscription_t> low_can_j1939 = std::make_shared<low_can_subscription_t>();
946 application.set_subscription_address_claiming(low_can_j1939);
948 ret = low_can_subscription_t::open_socket(*low_can_j1939,
950 J1939_ADDR_CLAIM_PROTOCOL);
954 AFB_ERROR("Error open socket address claiming for j1939 protocol");
957 add_to_event_loop(low_can_j1939);
964 AFB_ERROR("There was something wrong with CAN device Initialization.");
969 int load_config(afb_api_t api)
972 CtlConfigT *ctlConfig;
973 const char *dirList = getenv("CONTROL_CONFIG_PATH");
974 std::string bindingDirPath = GetBindingDirPath(api);
975 std::string filepath = bindingDirPath + "/etc";
978 dirList=CONTROL_CONFIG_PATH;
980 filepath.append(":");
981 filepath.append(dirList);
982 const char *configPath = CtlConfigSearch(api, filepath.c_str(), "control");
986 AFB_ERROR_V3("CtlPreInit: No control-%s* config found invalid JSON %s ", GetBinderName(), filepath.c_str());
990 // create one API per file
991 ctlConfig = CtlLoadMetaData(api, configPath);
994 AFB_ERROR_V3("CtrlPreInit No valid control config file in:\n-- %s", configPath);
998 // Save the config in the api userdata field
999 afb_api_set_userdata(api, ctlConfig);
1001 setExternalData(ctlConfig, (void*) &application_t::instance());
1002 ret= CtlLoadSections(api, ctlConfig, ctlSections_);