2 * Copyright (C) 2015, 2018 "IoT.bzh"
3 * Copyright (C) 2021 Konsulko Group
4 * Author "Romain Forlot" <romain.forlot@iot.bzh>
5 * Author "Loic Collignon" <loic.collignon@iot.bzh>
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
20 #include "low-can-hat.hpp"
21 #include "low-can-apidef.h"
30 #include <wrap-json.h>
31 #include <systemd/sd-event.h>
32 #include <ctl-config.h>
33 #include "openxc.pb.h"
34 #include "application.hpp"
35 #include "../can/can-encoder.hpp"
36 #include "../can/can-bus.hpp"
37 #include "../can/signals.hpp"
38 #include "../can/message/message.hpp"
39 #include "../utils/signals.hpp"
40 #include "../diagnostic/diagnostic-message.hpp"
41 #include "../utils/openxc-utils.hpp"
42 #include "../utils/config-parser.hpp"
44 #ifdef USE_FEATURE_J1939
45 #include "../can/message/j1939-message.hpp"
46 #include <linux/can/j1939.h>
49 ///*****************************************************************************
51 /// Controller Definitions and Callbacks
53 ///****************************************************************************/
55 int config_low_can(afb_api_t apiHandle, CtlSectionT *section, json_object *json_obj)
57 AFB_DEBUG("Config %s", json_object_to_json_string(json_obj));
58 CtlConfigT *ctrlConfig = (CtlConfigT *) afb_api_get_userdata(apiHandle);
59 int active_message_set = 0;
60 json_object *dev_mapping = nullptr;
61 const char *diagnostic_bus = nullptr;
63 if(! ctrlConfig || ! ctrlConfig->external)
66 application_t *application = (application_t*) ctrlConfig->external;
68 if(wrap_json_unpack(json_obj, "{si, s?s}",
69 "active_message_set", &active_message_set,
70 "diagnostic_bus", &diagnostic_bus)) {
71 AFB_ERROR("active_message_set and/or diagnostic_bus missing in controller JSON");
75 if(active_message_set < 0 ||
76 active_message_set > (application->get_messages_definition().size() - 1)) {
77 AFB_ERROR("Invalid active message set %d", active_message_set);
80 application->set_active_message_set((uint8_t) active_message_set);
82 utils::config_parser_t conf_file("/etc/dev-mapping.conf");
83 if(conf_file.check_conf())
85 // If a mapping file in /etc exists, use it
86 AFB_INFO("Using /etc/dev-mapping.conf");
87 application->get_can_bus_manager().set_can_devices(conf_file.get_devices_name());
89 // Use whatever configuration is in the controller JSON
90 if(wrap_json_unpack(json_obj, "{so}",
91 "dev-mapping", &dev_mapping)) {
92 AFB_ERROR("No device mapping in controller JSON");
96 application->get_can_bus_manager().set_can_devices(dev_mapping);
99 // Find all required buses
100 std::set<std::string> buses;
101 std::set<std::string> j1939_buses;
102 vect_ptr_msg_def_t msg_defs = application->get_messages_definition();
103 for(std::shared_ptr<message_definition_t> &msg_def : msg_defs) {
104 if(!msg_def->is_j1939())
105 buses.insert(msg_def->get_bus_name());
107 j1939_buses.insert(msg_def->get_bus_name());
109 #ifdef USE_FEATURE_J1939
110 // NOTE: With C++17 just: buses.merge(j1939_buses)
111 for(auto it = begin(j1939_buses); it != end(j1939_buses); ++it)
115 // Check that required buses have device mappings
116 for(auto it = begin(buses); it != end(buses); ++it) {
117 std::string dev = application->get_can_bus_manager().get_can_device_name(*it);
119 AFB_ERROR("No CAN device defined for bus \"%s\"", it->c_str());
122 AFB_INFO("Using CAN device %s for bus \"%s\"", dev.c_str(), it->c_str());
125 // Check that diagnostic bus is one of the configured buses
126 if(diagnostic_bus && buses.count(diagnostic_bus) == 0) {
127 AFB_ERROR("No CAN device mapping defined for diagnostic bus \"%s\"", diagnostic_bus);
132 /// Initialize Diagnostic manager that will handle obd2 requests.
133 /// We pass by default the first CAN bus device to its Initialization.
134 if(! diagnostic_bus || application_t::instance().get_diagnostic_manager().initialize(diagnostic_bus))
135 AFB_WARNING("Diagnostic Manager: not initialized. No diagnostic messages will be processed.");
140 CtlSectionT ctlSections_[] = {
141 [0]={.key="plugins" , .uid="plugins", .info=nullptr,
142 .loadCB=PluginConfig,
145 [1]={.key="config" , .uid="config", .info=nullptr,
146 .loadCB=config_low_can,
149 [2]={.key=nullptr , .uid=nullptr, .info=nullptr,
155 ///*****************************************************************************
157 /// Subscription and unsubscription
159 ///****************************************************************************/
161 /// @brief This will determine if an event handle needs to be created and checks if
162 /// we got a valid afb_event to get subscribe or unsubscribe. After that launch the subscription or unsubscription
163 /// against the application framework using that event handle.
164 static int subscribe_unsubscribe_signal(afb_req_t request,
166 std::shared_ptr<low_can_subscription_t>& can_subscription,
170 int sub_index = can_subscription->get_index();
171 bool subscription_exists = s.count(sub_index);
176 /* There is no valid request to subscribe so this must be an
177 * internal permanent diagnostic request. Skip the subscription
178 * part and don't register it into the current "low-can"
184 // Event doesn't exist , so let's create it
185 if ((ret = can_subscription->subscribe(request)) < 0)
188 if(! subscription_exists)
189 s[sub_index] = can_subscription;
194 // Unsubscrition part
195 if(! subscription_exists)
197 AFB_NOTICE("There isn't any valid subscriptions for that request.");
200 else if (subscription_exists &&
201 ! afb_event_is_valid(s[sub_index]->get_event()) )
203 AFB_NOTICE("Event isn't valid, no need to unsubscribed.");
207 if( (ret = s[sub_index]->unsubscribe(request)) < 0)
209 s.find(sub_index)->second->set_index(-1);
214 static int add_to_event_loop(std::shared_ptr<low_can_subscription_t>& can_subscription)
216 struct sd_event_source* event_source = nullptr;
217 return ( sd_event_add_io(afb_daemon_get_event_loop(),
219 can_subscription->get_socket()->socket(),
222 can_subscription.get()));
225 static int subscribe_unsubscribe_diagnostic_messages(afb_req_t request,
227 list_ptr_diag_msg_t diagnostic_messages,
228 struct event_filter_t& event_filter,
230 bool perm_rec_diag_req)
233 application_t& app = application_t::instance();
234 diagnostic_manager_t& diag_m = app.get_diagnostic_manager();
236 for(const auto& sig : diagnostic_messages)
238 DiagnosticRequest* diag_req = new DiagnosticRequest(sig->build_diagnostic_request());
239 event_filter.frequency = event_filter.frequency == 0 ? sig->get_frequency() : event_filter.frequency;
240 std::shared_ptr<low_can_subscription_t> can_subscription;
242 auto it = std::find_if(s.begin(), s.end(), [&sig](std::pair<int, std::shared_ptr<low_can_subscription_t> > sub)
244 return (! sub.second->get_diagnostic_message().empty());
246 can_subscription = it != s.end() ?
248 std::make_shared<low_can_subscription_t>(low_can_subscription_t(event_filter));
249 // If the requested diagnostic message is not supported by the car then unsubcribe it
250 // no matter what we want, worst case will be a failed unsubscription but at least we won't
251 // poll a PID for nothing.
252 if(sig->get_supported() && subscribe)
254 if (!app.is_engine_on())
255 AFB_WARNING("signal: Engine is off, %s won't received responses until it's on", sig->get_name().c_str());
257 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);
258 if(can_subscription->create_rx_filter(sig) < 0)
260 AFB_DEBUG("Signal: %s subscribed", sig->get_name().c_str());
261 if(it == s.end() && add_to_event_loop(can_subscription) < 0)
263 diag_m.cleanup_request(
264 diag_m.find_recurring_request(*diag_req), true);
265 AFB_WARNING("signal: %s isn't supported. Canceling operation.", sig->get_name().c_str());
271 if(sig->get_supported())
273 AFB_DEBUG("%s cancelled due to unsubscribe", sig->get_name().c_str());
277 AFB_WARNING("signal: %s isn't supported. Canceling operation.", sig->get_name().c_str());
281 int ret = subscribe_unsubscribe_signal(request, subscribe, can_subscription, s);
290 static int subscribe_unsubscribe_signals(afb_req_t request,
292 list_ptr_signal_t signals,
293 struct event_filter_t& event_filter,
297 for(const auto& sig: signals)
299 auto it = std::find_if(s.begin(), s.end(), [&sig, &event_filter](std::pair<int, std::shared_ptr<low_can_subscription_t> > sub)
301 return sub.second->is_signal_subscription_corresponding(sig, event_filter) ;
303 std::shared_ptr<low_can_subscription_t> can_subscription;
305 can_subscription = it->second;
308 can_subscription = std::make_shared<low_can_subscription_t>(low_can_subscription_t(event_filter));
309 if(can_subscription->create_rx_filter(sig) < 0)
311 if(add_to_event_loop(can_subscription) < 0)
315 if(subscribe_unsubscribe_signal(request, subscribe, can_subscription, s) < 0)
319 AFB_DEBUG("%s Signal: %s %ssubscribed", sig->get_message()->is_fd() ? "FD": "", sig->get_name().c_str(), subscribe ? "":"un");
325 /// @brief subscribe to all signals in the vector signals
327 /// @param[in] afb_req request : contains original request use to subscribe or unsubscribe
328 /// @param[in] subscribe boolean value, which chooses between a subscription operation or an unsubscription
329 /// @param[in] signals - struct containing vectors with signal_t and diagnostic_messages to subscribe
330 /// @param[in] event_filter - stuct containing filter on the signal
332 /// @return Number of correctly subscribed signal
334 static int subscribe_unsubscribe_signals(afb_req_t request,
336 const struct utils::signals_found& signals,
337 struct event_filter_t& event_filter)
340 utils::signals_manager_t& sm = utils::signals_manager_t::instance();
342 std::lock_guard<std::mutex> subscribed_signals_lock(sm.get_subscribed_signals_mutex());
343 map_subscription& s = sm.get_subscribed_signals();
345 rets += subscribe_unsubscribe_diagnostic_messages(request, subscribe, signals.diagnostic_messages, event_filter, s, false);
346 rets += subscribe_unsubscribe_signals(request, subscribe, signals.signals, event_filter, s);
351 static event_filter_t generate_filter(json_object* args)
353 event_filter_t event_filter = {};
354 struct json_object *filter, *obj;
356 // computes the filter
357 if (json_object_object_get_ex(args, "filter", &filter))
359 if (json_object_object_get_ex(filter, "frequency", &obj)
360 && (json_object_is_type(obj, json_type_double) || json_object_is_type(obj, json_type_int)))
361 event_filter.frequency = (float)json_object_get_double(obj);
362 if (json_object_object_get_ex(filter, "min", &obj)
363 && (json_object_is_type(obj, json_type_double) || json_object_is_type(obj, json_type_int)))
364 event_filter.min = (float)json_object_get_double(obj);
365 if (json_object_object_get_ex(filter, "max", &obj)
366 && (json_object_is_type(obj, json_type_double) || json_object_is_type(obj, json_type_int)))
367 event_filter.max = (float)json_object_get_double(obj);
368 if (json_object_object_get_ex(filter, "promisc", &obj)
369 && (json_object_is_type(obj, json_type_boolean)))
370 event_filter.promisc = (bool)json_object_get_boolean(obj);
371 if (json_object_object_get_ex(filter, "rx_id", &obj)
372 && (json_object_is_type(obj, json_type_int)))
373 event_filter.rx_id = (canid_t) json_object_get_int(obj);
374 if (json_object_object_get_ex(filter, "tx_id", &obj)
375 && (json_object_is_type(obj, json_type_int)))
376 event_filter.tx_id = (canid_t) json_object_get_int(obj);
382 static int one_subscribe_unsubscribe_events(afb_req_t request, bool subscribe, const std::string& tag, json_object* args)
385 struct utils::signals_found sf;
387 // subscribe or unsubscribe
388 openxc_DynamicField search_key = build_DynamicField(tag);
389 sf = utils::signals_manager_t::instance().find_signals(search_key);
392 #ifdef USE_FEATURE_ISOTP
393 if(sf.signals.size() > 1)
395 sf.signals.remove_if([](std::shared_ptr<signal_t> x){
396 bool isotp = x->get_message()->is_isotp();
398 AFB_NOTICE("ISO TP messages need to be subscribed one by one (rx, tx)");
405 if (sf.signals.empty() && sf.diagnostic_messages.empty())
407 AFB_NOTICE("No signal(s) found for %s.", tag.c_str());
412 event_filter_t event_filter = generate_filter(args);
413 ret = subscribe_unsubscribe_signals(request, subscribe, sf, event_filter);
418 static int one_subscribe_unsubscribe_id(afb_req_t request, bool subscribe, const uint32_t& id, json_object *args)
420 std::shared_ptr<message_definition_t> message_definition = application_t::instance().get_message_definition(id);
421 struct utils::signals_found sf;
423 if(message_definition)
424 sf.signals = list_ptr_signal_t(message_definition->get_signals().begin(), message_definition->get_signals().end());
426 if(sf.signals.empty())
428 AFB_NOTICE("No signal(s) found for %d.", id);
432 event_filter_t event_filter = generate_filter(args);
433 std::shared_ptr<low_can_subscription_t> can_subscription = std::make_shared<low_can_subscription_t>(low_can_subscription_t(event_filter));
434 can_subscription->set_message_definition(message_definition);
436 utils::signals_manager_t& sm = utils::signals_manager_t::instance();
437 std::lock_guard<std::mutex> subscribed_signals_lock(sm.get_subscribed_signals_mutex());
438 map_subscription& s = sm.get_subscribed_signals();
440 if(can_subscription->create_rx_filter(message_definition) < 0)
442 if(add_to_event_loop(can_subscription) < 0)
445 if(subscribe_unsubscribe_signal(request, subscribe, can_subscription, s) < 0)
452 static int process_one_subscribe_args(afb_req_t request, bool subscribe, json_object *args)
455 json_object *x = nullptr, *event = nullptr, *id = nullptr;
458 // 2 cases : ID(PGN) and event
460 json_object_object_get_ex(args,"event",&event);
461 json_object_object_get_ex(args,"id",&id) || json_object_object_get_ex(args,"pgn",&id);
463 if( args == NULL || (id && ((std::string)json_object_get_string(id)).compare("*") == 0))
465 rc = one_subscribe_unsubscribe_events(request, subscribe, "*", args);
471 if (json_object_get_type(event) != json_type_array) // event is set before and check if it's an array
473 rc = one_subscribe_unsubscribe_events(request, subscribe, json_object_get_string(event), args);
475 else // event is set and it's not an array
477 for (int i = 0 ; i < json_object_array_length(event); i++)
479 x = json_object_array_get_idx(event, i);
480 rc2 = one_subscribe_unsubscribe_events(request, subscribe, json_object_get_string(x), args);
482 rc = rc2 >= 0 ? rc + rc2 : rc2;
489 if (json_object_get_type(id) != json_type_array) // id is set before and check if it's an array
491 rc = one_subscribe_unsubscribe_id(request, subscribe, json_object_get_int(id), args);
493 else // event is set and it's not an array
495 for (int i = 0 ; i < json_object_array_length(id); i++)
497 x = json_object_array_get_idx(id, i);
498 rc2 = one_subscribe_unsubscribe_id(request, subscribe, json_object_get_int(x), args);
500 rc = rc2 >= 0 ? rc + rc2 : rc2;
508 static void do_subscribe_unsubscribe(afb_req_t request, bool subscribe)
511 struct json_object *args, *x;
513 args = afb_req_json(request);
514 if (json_object_get_type(args) == json_type_array)
516 for(int i = 0; i < json_object_array_length(args); i++)
518 x = json_object_array_get_idx(args, i);
519 rc += process_one_subscribe_args(request, subscribe, x);
524 rc += process_one_subscribe_args(request, subscribe, args);
528 afb_req_success(request, NULL, NULL);
530 afb_req_fail(request, "error", NULL);
533 void auth(afb_req_t request)
535 afb_req_session_set_LOA(request, 1);
536 afb_req_success(request, NULL, NULL);
539 void subscribe(afb_req_t request)
541 do_subscribe_unsubscribe(request, true);
544 void unsubscribe(afb_req_t request)
546 do_subscribe_unsubscribe(request, false);
549 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)
554 std::map<std::string, std::shared_ptr<low_can_subscription_t> >& cd = application_t::instance().get_can_devices();
556 if( cd.count(bus_name) == 0)
557 cd[bus_name] = std::make_shared<low_can_subscription_t>(low_can_subscription_t(event_filter));
559 cd[bus_name]->set_signal(signal);
562 if(flags&CAN_PROTOCOL)
563 return low_can_subscription_t::tx_send(*cd[bus_name], message, bus_name);
564 #ifdef USE_FEATURE_ISOTP
565 else if(flags&ISOTP_PROTOCOL)
566 return low_can_subscription_t::isotp_send(*cd[bus_name], message, bus_name);
568 #ifdef USE_FEATURE_J1939
569 else if(flags&J1939_PROTOCOL)
570 return low_can_subscription_t::j1939_send(*cd[bus_name], message, bus_name);
577 static void write_raw_frame(afb_req_t request, const std::string& bus_name, message_t *message,
578 struct json_object *can_data, uint32_t flags, event_filter_t &event_filter)
581 struct utils::signals_found sf;
583 utils::signals_manager_t::instance().lookup_signals_by_id(message->get_id(), application_t::instance().get_all_signals(), sf.signals);
585 if( !sf.signals.empty() )
587 AFB_DEBUG("ID WRITE RAW : %d", sf.signals.front()->get_message()->get_id());
588 if(flags & CAN_PROTOCOL)
590 if(sf.signals.front()->get_message()->is_fd())
592 AFB_DEBUG("CANFD_MAX_DLEN");
593 message->set_flags(CAN_PROTOCOL_WITH_FD_FRAME);
594 message->set_maxdlen(CANFD_MAX_DLEN);
598 AFB_DEBUG("CAN_MAX_DLEN");
599 message->set_maxdlen(CAN_MAX_DLEN);
602 if(sf.signals.front()->get_message()->is_isotp())
604 flags = ISOTP_PROTOCOL;
605 message->set_maxdlen(MAX_ISOTP_FRAMES * message->get_maxdlen());
609 #ifdef USE_FEATURE_J1939
610 if(flags&J1939_PROTOCOL)
611 message->set_maxdlen(J1939_MAX_DLEN);
614 if(message->get_length() > 0 &&
615 message->get_length() <= message->get_maxdlen() &&
616 json_object_get_type(can_data) == json_type_array)
618 std::vector<uint8_t> data;
619 for (int i = 0 ; i < message->get_length() ; i++)
621 struct json_object *one_can_data = json_object_array_get_idx(can_data, i);
622 data.push_back((json_object_is_type(one_can_data, json_type_int)) ?
623 (uint8_t)json_object_get_int(one_can_data) : 0);
625 message->set_data(data);
629 if(flags&CAN_PROTOCOL)
630 afb_req_fail(request, "Invalid", "Frame BCM");
631 else if(flags&J1939_PROTOCOL)
632 afb_req_fail(request, "Invalid", "Frame J1939");
633 else if(flags&ISOTP_PROTOCOL)
634 afb_req_fail(request, "Invalid", "Frame ISOTP");
636 afb_req_fail(request, "Invalid", "Frame");
641 if(! send_message(message, application_t::instance().get_can_bus_manager().get_can_device_name(bus_name), flags, event_filter, sf.signals.front()))
642 afb_req_success(request, nullptr, "Message correctly sent");
644 afb_req_fail(request, "Error", "sending the message. See the log for more details.");
648 afb_req_fail(request, "Error", "no find id in signals. See the log for more details.");
653 static void write_frame(afb_req_t request, const std::string& bus_name, json_object *json_value, event_filter_t &event_filter)
658 struct json_object *can_data = nullptr;
659 std::vector<uint8_t> data;
661 AFB_DEBUG("JSON content %s", json_object_get_string(json_value));
663 if(!wrap_json_unpack(json_value, "{si, si, so !}",
666 "can_data", &can_data))
668 message = new can_message_t(0, id, length, false, 0, data, 0);
669 write_raw_frame(request, bus_name, message, can_data, CAN_PROTOCOL, event_filter);
671 #ifdef USE_FEATURE_J1939
672 else if(!wrap_json_unpack(json_value, "{si, si, so !}",
677 message = new j1939_message_t(length, data, 0, J1939_NO_NAME, (pgn_t)id, J1939_NO_ADDR);
678 write_raw_frame(request, bus_name, message, can_data, J1939_PROTOCOL, event_filter);
683 afb_req_fail(request, "Invalid", "Frame object malformed");
689 static void write_signal(afb_req_t request, const std::string& name, json_object *json_value, event_filter_t &event_filter)
691 struct canfd_frame cfd;
692 struct utils::signals_found sf;
693 signal_encoder encoder = nullptr;
696 ::memset(&cfd, 0, sizeof(cfd));
698 openxc_DynamicField search_key = build_DynamicField(name);
699 sf = utils::signals_manager_t::instance().find_signals(search_key);
700 openxc_DynamicField dynafield_value = build_DynamicField(json_value);
702 if (sf.signals.empty())
704 afb_req_fail_f(request, "No signal(s) found for %s. Message not sent.", name.c_str());
708 std::shared_ptr<signal_t> sig = sf.signals.front();
709 if(! sig->get_writable())
711 afb_req_fail_f(request, "%s isn't writable. Message not sent.", sig->get_name().c_str());
715 uint64_t value = (encoder = sig->get_encoder()) ?
716 encoder(*sig, dynafield_value, &send) :
717 encoder_t::encode_DynamicField(*sig, dynafield_value, &send);
719 uint32_t flags = INVALID_FLAG;
721 if(sig->get_message()->is_j1939())
722 flags = J1939_PROTOCOL;
723 else if(sig->get_message()->is_isotp())
724 flags = ISOTP_PROTOCOL;
726 flags = CAN_PROTOCOL;
728 // cfd = encoder_t::build_frame(sig, value);
729 message_t *message = encoder_t::build_message(sig, value, false, false);
731 if(! send_message(message, sig->get_message()->get_bus_device_name(), flags, event_filter, sig) && send)
732 afb_req_success(request, nullptr, "Message correctly sent");
734 afb_req_fail(request, "Error", "Sending the message. See the log for more details.");
736 if(sig->get_message()->is_j1939())
737 #ifdef USE_FEATURE_J1939
738 delete (j1939_message_t*) message;
740 afb_req_fail(request, "Warning", "J1939 not implemented in your kernel.");
743 delete (can_message_t*) message;
746 void write(afb_req_t request)
748 struct json_object* args = nullptr, *json_value = nullptr, *name = nullptr;
749 args = afb_req_json(request);
753 event_filter_t event_filter = generate_filter(args);
755 if(json_object_object_get_ex(args,"bus_name",&name))
757 if(json_object_object_get_ex(args,"frame",&json_value))
758 write_frame(request, (std::string)json_object_get_string(name), json_value, event_filter);
760 afb_req_fail(request, "Error", "Request argument malformed");
762 else if(json_object_object_get_ex(args,"signal_name",&name))
764 if(json_object_object_get_ex(args,"signal_value",&json_value))
765 write_signal(request, (std::string)json_object_get_string(name), json_value, event_filter);
767 afb_req_fail(request, "Error", "Request argument malformed");
771 afb_req_fail(request, "Error", "Request argument malformed");
776 afb_req_fail(request, "Error", "Request argument null");
780 static struct json_object *get_signals_value(const std::string& name)
782 struct utils::signals_found sf;
783 struct json_object *ans = nullptr;
785 openxc_DynamicField search_key = build_DynamicField(name);
786 sf = utils::signals_manager_t::instance().find_signals(search_key);
788 if (sf.signals.empty())
790 AFB_WARNING("No signal(s) found for %s.", name.c_str());
793 ans = json_object_new_array();
794 for(const auto& sig: sf.signals)
796 struct json_object *jobj = json_object_new_object();
797 json_object_object_add(jobj, "event", json_object_new_string(sig->get_name().c_str()));
798 json_object_object_add(jobj, "value", json_object_new_double(sig->get_last_value()));
799 json_object_array_add(ans, jobj);
805 static struct json_object *get_id_value(const uint32_t& id)
807 std::shared_ptr<message_definition_t> message_definition = application_t::instance().get_message_definition(id);
808 struct utils::signals_found sf;
809 struct json_object *ans = nullptr;
811 if(message_definition)
812 sf.signals = list_ptr_signal_t(message_definition->get_signals().begin(), message_definition->get_signals().end());
814 if(sf.signals.empty())
816 AFB_WARNING("no signal(s) found for %d.", id);
820 ans = json_object_new_object();
821 struct json_object *jsignals = json_object_new_array();
822 json_object_object_add(ans, "signals", jsignals);
823 for(const auto& sig: sf.signals)
825 struct json_object *jobj = json_object_new_object();
826 json_object_object_add(jobj, "name", json_object_new_string(sig->get_name().c_str()));
827 json_object_object_add(jobj, "value", json_object_new_double(sig->get_last_value()));
828 json_object_array_add(jsignals, jobj);
834 void get(afb_req_t request)
837 struct json_object* args = nullptr,
838 *json_name = nullptr;
839 json_object *ans = nullptr;
841 args = afb_req_json(request);
843 // Process about Raw CAN message on CAN bus directly
844 if (args != nullptr &&
845 (json_object_object_get_ex(args, "event", &json_name) && json_object_is_type(json_name, json_type_string) ))
847 ans = get_signals_value(json_object_get_string(json_name));
851 else if (args != nullptr &&
852 (json_object_object_get_ex(args, "id", &json_name)))
854 if (json_object_get_type(json_name) == json_type_string) // id is set before and check if it's an array
856 ans = get_id_value(json_object_get_int(json_name));
858 else if(json_object_get_type(json_name) == json_type_array)
860 ans = json_object_new_array();
861 for (int i = 0 ; i < json_object_array_length(json_name); i++)
863 json_object *sub_ans = nullptr;
864 json_object *x = json_object_array_get_idx(json_name, i);
865 sub_ans = get_id_value(json_object_get_int(x));
869 struct json_object *jobj = json_object_new_object();
870 struct json_object *jid = json_object_new_string(json_object_get_string(x));
871 json_object_object_add(jobj, "id", jid);
872 json_object_object_add(jobj, "data", sub_ans);
873 json_object_array_add(ans, jobj);
884 AFB_ERROR("Request argument malformed. Please use the following syntax:");
889 afb_req_success(request, ans, NULL);
891 afb_req_fail(request, "error", NULL);
895 static struct json_object *list_can_message(const std::string& name)
897 struct utils::signals_found sf;
898 struct json_object *ans = nullptr;
900 openxc_DynamicField search_key = build_DynamicField(name);
901 sf = utils::signals_manager_t::instance().find_signals(search_key);
903 if (sf.signals.empty() && sf.diagnostic_messages.empty())
905 AFB_WARNING("No signal(s) found for %s.", name.c_str());
908 ans = json_object_new_array();
909 for(const auto& sig: sf.signals)
911 json_object_array_add(ans,
912 json_object_new_string(sig->get_name().c_str()));
914 for(const auto& sig: sf.diagnostic_messages)
916 json_object_array_add(ans,
917 json_object_new_string(sig->get_name().c_str()));
923 void list(afb_req_t request)
926 json_object *ans = nullptr;
927 struct json_object* args = nullptr,
928 *json_name = nullptr;
929 args = afb_req_json(request);
931 if ((args != nullptr) &&
932 (json_object_object_get_ex(args, "event", &json_name) && json_object_is_type(json_name, json_type_string)))
933 name = json_object_get_string(json_name);
937 ans = list_can_message(name);
942 afb_req_success(request, ans, NULL);
944 afb_req_fail(request, "error", NULL);
948 /// @brief Initialize the binding.
950 /// @param[in] service Structure which represent the Application Framework Binder.
952 /// @return Exit code, zero if success.
953 int init_binding(afb_api_t api)
956 application_t& application = application_t::instance();
957 can_bus_t& can_bus_manager = application.get_can_bus_manager();
959 if(application.get_message_set().empty())
961 AFB_ERROR("No message_set defined");
965 can_bus_manager.start_threads();
966 utils::signals_manager_t& sm = utils::signals_manager_t::instance();
968 if (application.get_diagnostic_manager().is_initialized())
970 // Add a recurring dignostic message request to get engine speed at all times.
971 openxc_DynamicField search_key = build_DynamicField("diagnostic_messages.engine.speed");
972 struct utils::signals_found sf = sm.find_signals(search_key);
974 if(sf.signals.empty() && sf.diagnostic_messages.size() == 1)
976 afb_req_t request = nullptr;
978 struct event_filter_t event_filter;
979 event_filter.frequency = sf.diagnostic_messages.front()->get_frequency();
981 map_subscription& s = sm.get_subscribed_signals();
983 subscribe_unsubscribe_diagnostic_messages(request, true, sf.diagnostic_messages, event_filter, s, true);
987 #ifdef USE_FEATURE_J1939
988 std::string j1939_bus;
989 vect_ptr_msg_def_t current_messages_definition = application.get_messages_definition();
990 for(std::shared_ptr<message_definition_t> message_definition: current_messages_definition)
992 if(message_definition->is_j1939())
994 if (j1939_bus == message_definition->get_bus_device_name() )
996 j1939_bus = message_definition->get_bus_device_name();
998 std::shared_ptr<low_can_subscription_t> low_can_j1939 = std::make_shared<low_can_subscription_t>();
999 application.set_subscription_address_claiming(low_can_j1939);
1001 ret = low_can_subscription_t::open_socket(*low_can_j1939,
1003 J1939_ADDR_CLAIM_PROTOCOL);
1007 AFB_ERROR("Error open socket address claiming for j1939 protocol");
1010 add_to_event_loop(low_can_j1939);
1017 AFB_ERROR("There was something wrong with CAN device Initialization.");
1022 int load_config(afb_api_t api)
1025 CtlConfigT *ctlConfig;
1026 const char *dirList = getenv("CONTROL_CONFIG_PATH");
1027 std::string bindingDirPath = GetBindingDirPath(api);
1028 std::string filepath = bindingDirPath + "/etc";
1031 dirList=CONTROL_CONFIG_PATH;
1033 filepath.append(":");
1034 filepath.append(dirList);
1035 const char *configPath = CtlConfigSearch(api, filepath.c_str(), "control");
1039 AFB_ERROR_V3("CtlPreInit: No control-%s* config found invalid JSON %s ", GetBinderName(), filepath.c_str());
1043 // create one API per file
1044 ctlConfig = CtlLoadMetaData(api, configPath);
1047 AFB_ERROR_V3("CtrlPreInit No valid control config file in:\n-- %s", configPath);
1051 // Save the config in the api userdata field
1052 afb_api_set_userdata(api, ctlConfig);
1054 setExternalData(ctlConfig, (void*) &application_t::instance());
1055 ret= CtlLoadSections(api, ctlConfig, ctlSections_);