X-Git-Url: https://gerrit.automotivelinux.org/gerrit/gitweb?a=blobdiff_plain;f=low-can-binding%2Fbinding%2Flow-can-cb.cpp;h=32adac869e2462ee94f292bbcea06eb80bbb2374;hb=HEAD;hp=1c01738fc2dc116b5cf9988f922731cfc78f1767;hpb=4e1db7198dc91adce159abbea60667400569d38c;p=apps%2Fagl-service-can-low-level.git diff --git a/low-can-binding/binding/low-can-cb.cpp b/low-can-binding/binding/low-can-cb.cpp index 1c01738f..32adac86 100644 --- a/low-can-binding/binding/low-can-cb.cpp +++ b/low-can-binding/binding/low-can-cb.cpp @@ -1,5 +1,6 @@ /* * Copyright (C) 2015, 2018 "IoT.bzh" + * Copyright (C) 2021 Konsulko Group * Author "Romain Forlot" * Author "Loic Collignon" * @@ -23,9 +24,12 @@ #include #include #include +#include #include +#include #include #include +#include #include "openxc.pb.h" #include "application.hpp" #include "../can/can-encoder.hpp" @@ -35,96 +39,124 @@ #include "../utils/signals.hpp" #include "../diagnostic/diagnostic-message.hpp" #include "../utils/openxc-utils.hpp" -#include "../utils/signals.hpp" +#include "../utils/config-parser.hpp" #ifdef USE_FEATURE_J1939 #include "../can/message/j1939-message.hpp" #include #endif -///****************************************************************************** + +///***************************************************************************** /// -/// SystemD event loop Callbacks +/// Controller Definitions and Callbacks /// -///*******************************************************************************/ +///****************************************************************************/ -void on_no_clients(std::shared_ptr can_subscription, uint32_t pid, map_subscription& s) +int config_low_can(afb_api_t apiHandle, CtlSectionT *section, json_object *json_obj) { - bool is_permanent_recurring_request = false; - - if( ! can_subscription->get_diagnostic_message().empty() && can_subscription->get_diagnostic_message(pid) != nullptr) - { - DiagnosticRequest diag_req = can_subscription->get_diagnostic_message(pid)->build_diagnostic_request(); - active_diagnostic_request_t* adr = application_t::instance().get_diagnostic_manager().find_recurring_request(diag_req); - if( adr != nullptr) - { - is_permanent_recurring_request = adr->get_permanent(); + AFB_DEBUG("Config %s", json_object_to_json_string(json_obj)); + CtlConfigT *ctrlConfig = (CtlConfigT *) afb_api_get_userdata(apiHandle); + int active_message_set = 0; + json_object *dev_mapping = nullptr; + const char *diagnostic_bus = nullptr; - if(! is_permanent_recurring_request) - application_t::instance().get_diagnostic_manager().cleanup_request(adr, true); - } - } + if(! ctrlConfig || ! ctrlConfig->external) + return -1; - if(! is_permanent_recurring_request) - on_no_clients(can_subscription, s); -} + application_t *application = (application_t*) ctrlConfig->external; -void on_no_clients(std::shared_ptr can_subscription, map_subscription& s) -{ - auto it = s.find(can_subscription->get_index()); - s.erase(it); -} - -static void push_n_notify(std::shared_ptr m) -{ - can_bus_t& cbm = application_t::instance().get_can_bus_manager(); - { - std::lock_guard can_message_lock(cbm.get_can_message_mutex()); - cbm.push_new_can_message(m); + if(wrap_json_unpack(json_obj, "{si, s?s}", + "active_message_set", &active_message_set, + "diagnostic_bus", &diagnostic_bus)) { + AFB_ERROR("active_message_set and/or diagnostic_bus missing in controller JSON"); + return -1; } - cbm.get_new_can_message_cv().notify_one(); -} -int read_message(sd_event_source *event_source, int fd, uint32_t revents, void *userdata) -{ + if(active_message_set < 0 || + active_message_set > (application->get_messages_definition().size() - 1)) { + AFB_ERROR("Invalid active message set %d", active_message_set); + return -1; + } + application->set_active_message_set((uint8_t) active_message_set); - low_can_subscription_t* can_subscription = (low_can_subscription_t*)userdata; + utils::config_parser_t conf_file("/etc/dev-mapping.conf"); + if(conf_file.check_conf()) + { + // If a mapping file in /etc exists, use it + AFB_INFO("Using /etc/dev-mapping.conf"); + application->get_can_bus_manager().set_can_devices(conf_file.get_devices_name()); + } else { + // Use whatever configuration is in the controller JSON + if(wrap_json_unpack(json_obj, "{so}", + "dev-mapping", &dev_mapping)) { + AFB_ERROR("No device mapping in controller JSON"); + return -1; + } + application->get_can_bus_manager().set_can_devices(dev_mapping); + } - if ((revents & EPOLLIN) != 0) - { - utils::signals_manager_t& sm = utils::signals_manager_t::instance(); - std::lock_guard subscribed_signals_lock(sm.get_subscribed_signals_mutex()); - if(can_subscription->get_index() != -1) - { - std::shared_ptr s = can_subscription->get_socket(); - if(s->socket() && s->socket() != -1) - { - std::shared_ptr message = s->read_message(); + // Find all required buses + std::set buses; + std::set j1939_buses; + vect_ptr_msg_def_t msg_defs = application->get_messages_definition(); + for(std::shared_ptr &msg_def : msg_defs) { + if(!msg_def->is_j1939()) + buses.insert(msg_def->get_bus_name()); + else + j1939_buses.insert(msg_def->get_bus_name()); + } +#ifdef USE_FEATURE_J1939 + // NOTE: With C++17 just: buses.merge(j1939_buses) + for(auto it = begin(j1939_buses); it != end(j1939_buses); ++it) + buses.insert(*it); +#endif - // Sure we got a valid CAN message ? - if (! message->get_id() == 0 && ! message->get_length() == 0 && !(message->get_flags()&INVALID_FLAG)) - { - push_n_notify(message); - } - } + // Check that required buses have device mappings + for(auto it = begin(buses); it != end(buses); ++it) { + std::string dev = application->get_can_bus_manager().get_can_device_name(*it); + if(dev == "") { + AFB_ERROR("No CAN device defined for bus \"%s\"", it->c_str()); + return -1; } + AFB_INFO("Using CAN device %s for bus \"%s\"", dev.c_str(), it->c_str()); } - // check if error or hangup - if ((revents & (EPOLLERR | EPOLLRDHUP | EPOLLHUP)) != 0) - { - sd_event_source_unref(event_source); - can_subscription->get_socket()->close(); + // Check that diagnostic bus is one of the configured buses + if(diagnostic_bus && buses.count(diagnostic_bus) == 0) { + AFB_ERROR("No CAN device mapping defined for diagnostic bus \"%s\"", diagnostic_bus); + return -1; + } + /// Initialize Diagnostic manager that will handle obd2 requests. + /// We pass by default the first CAN bus device to its Initialization. + if(! diagnostic_bus || application_t::instance().get_diagnostic_manager().initialize(diagnostic_bus)) + AFB_WARNING("Diagnostic Manager: not initialized. No diagnostic messages will be processed."); + return 0; } -///****************************************************************************** +CtlSectionT ctlSections_[] = { + [0]={.key="plugins" , .uid="plugins", .info=nullptr, + .loadCB=PluginConfig, + .handle=nullptr, + .actions=nullptr}, + [1]={.key="config" , .uid="config", .info=nullptr, + .loadCB=config_low_can, + .handle=nullptr, + .actions=nullptr}, + [2]={.key=nullptr , .uid=nullptr, .info=nullptr, + .loadCB=nullptr, + .handle=nullptr, + .actions=nullptr}, +}; + +///***************************************************************************** /// /// Subscription and unsubscription /// -///*******************************************************************************/ +///****************************************************************************/ /// @brief This will determine if an event handle needs to be created and checks if /// we got a valid afb_event to get subscribe or unsubscribe. After that launch the subscription or unsubscription @@ -147,9 +179,7 @@ static int subscribe_unsubscribe_signal(afb_req_t request, * subsciptions. */ if(! request) - { return 0; - } // Event doesn't exist , so let's create it if ((ret = can_subscription->subscribe(request)) < 0) @@ -209,7 +239,7 @@ static int subscribe_unsubscribe_diagnostic_messages(afb_req_t request, event_filter.frequency = event_filter.frequency == 0 ? sig->get_frequency() : event_filter.frequency; std::shared_ptr can_subscription; - auto it = std::find_if(s.begin(), s.end(), [&sig](std::pair > sub) + auto it = std::find_if(s.begin(), s.end(), [&sig](std::pair > sub) { return (! sub.second->get_diagnostic_message().empty()); }); @@ -221,7 +251,7 @@ static int subscribe_unsubscribe_diagnostic_messages(afb_req_t request, // poll a PID for nothing. if(sig->get_supported() && subscribe) { - if (!app.isEngineOn()) + if (!app.is_engine_on()) AFB_WARNING("signal: Engine is off, %s won't received responses until it's on", sig->get_name().c_str()); 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); @@ -320,7 +350,7 @@ static int subscribe_unsubscribe_signals(afb_req_t request, static event_filter_t generate_filter(json_object* args) { - event_filter_t event_filter; + event_filter_t event_filter = {}; struct json_object *filter, *obj; // computes the filter @@ -335,6 +365,9 @@ static event_filter_t generate_filter(json_object* args) if (json_object_object_get_ex(filter, "max", &obj) && (json_object_is_type(obj, json_type_double) || json_object_is_type(obj, json_type_int))) event_filter.max = (float)json_object_get_double(obj); + if (json_object_object_get_ex(filter, "promisc", &obj) + && (json_object_is_type(obj, json_type_boolean))) + event_filter.promisc = (bool)json_object_get_boolean(obj); if (json_object_object_get_ex(filter, "rx_id", &obj) && (json_object_is_type(obj, json_type_int))) event_filter.rx_id = (canid_t) json_object_get_int(obj); @@ -382,27 +415,37 @@ static int one_subscribe_unsubscribe_events(afb_req_t request, bool subscribe, c return ret; } -static int one_subscribe_unsubscribe_id(afb_req_t request, bool subscribe, const uint32_t& id ,json_object *args) +static int one_subscribe_unsubscribe_id(afb_req_t request, bool subscribe, const uint32_t& id, json_object *args) { - int ret = 0; std::shared_ptr message_definition = application_t::instance().get_message_definition(id); struct utils::signals_found sf; if(message_definition) - sf.signals = list_ptr_signal_t(message_definition->get_signals().begin(),message_definition->get_signals().end()); + sf.signals = list_ptr_signal_t(message_definition->get_signals().begin(), message_definition->get_signals().end()); if(sf.signals.empty()) { AFB_NOTICE("No signal(s) found for %d.", id); - ret = -1; - } - else - { - event_filter_t event_filter = generate_filter(args); - ret = subscribe_unsubscribe_signals(request, subscribe, sf, event_filter); + return -1; } - return ret; + event_filter_t event_filter = generate_filter(args); + std::shared_ptr can_subscription = std::make_shared(low_can_subscription_t(event_filter)); + can_subscription->set_message_definition(message_definition); + + utils::signals_manager_t& sm = utils::signals_manager_t::instance(); + std::lock_guard subscribed_signals_lock(sm.get_subscribed_signals_mutex()); + map_subscription& s = sm.get_subscribed_signals(); + + if(can_subscription->create_rx_filter(message_definition) < 0) + return -1; + if(add_to_event_loop(can_subscription) < 0) + return -1; + + if(subscribe_unsubscribe_signal(request, subscribe, can_subscription, s) < 0) + return -1; + + return 0; } @@ -415,11 +458,9 @@ static int process_one_subscribe_args(afb_req_t request, bool subscribe, json_ob // 2 cases : ID(PGN) and event json_object_object_get_ex(args,"event",&event); - json_bool test_id = json_object_object_get_ex(args,"id",&id); - if(!test_id) - test_id = json_object_object_get_ex(args,"pgn",&id); + json_object_object_get_ex(args,"id",&id) || json_object_object_get_ex(args,"pgn",&id); - if( args == NULL || (id && ((std::string)json_object_get_string(id)).compare("*") == 0)) + if( args == NULL || (id && ((std::string)json_object_get_string(id)).compare("*") == 0)) { rc = one_subscribe_unsubscribe_events(request, subscribe, "*", args); } @@ -505,35 +546,6 @@ void unsubscribe(afb_req_t request) do_subscribe_unsubscribe(request, false); } -/* -static int send_frame(struct canfd_frame& cfd, const std::string& bus_name, socket_type type) -{ - if(bus_name.empty()) - { - return -1; - } - - std::map >& cd = application_t::instance().get_can_devices(); - - if( cd.count(bus_name) == 0) - { - cd[bus_name] = std::make_shared(low_can_subscription_t()); - } - - - if(type == socket_type::BCM) - { - return low_can_subscription_t::tx_send(*cd[bus_name], cfd, bus_name); - } - else if(type == socket_type::J1939) - { - return low_can_subscription_t::j1939_send(*cd[bus_name], cfd, bus_name); - } - else{ - return -1; - } -} -*/ static int send_message(message_t *message, const std::string& bus_name, uint32_t flags, event_filter_t &event_filter, std::shared_ptr signal) { if(bus_name.empty()) @@ -547,7 +559,7 @@ static int send_message(message_t *message, const std::string& bus_name, uint32_ cd[bus_name]->set_signal(signal); - if(flags&BCM_PROTOCOL) + if(flags&CAN_PROTOCOL) return low_can_subscription_t::tx_send(*cd[bus_name], message, bus_name); #ifdef USE_FEATURE_ISOTP else if(flags&ISOTP_PROTOCOL) @@ -563,7 +575,7 @@ static int send_message(message_t *message, const std::string& bus_name, uint32_ static void write_raw_frame(afb_req_t request, const std::string& bus_name, message_t *message, - struct json_object *can_data, uint32_t flags, event_filter_t &event_filter) + struct json_object *can_data, uint32_t flags, event_filter_t &event_filter) { struct utils::signals_found sf; @@ -572,13 +584,13 @@ static void write_raw_frame(afb_req_t request, const std::string& bus_name, mess if( !sf.signals.empty() ) { - AFB_DEBUG("ID WRITE RAW : %d",sf.signals.front()->get_message()->get_id()); - if(flags & BCM_PROTOCOL) + AFB_DEBUG("ID WRITE RAW : %d", sf.signals.front()->get_message()->get_id()); + if(flags & CAN_PROTOCOL) { if(sf.signals.front()->get_message()->is_fd()) { AFB_DEBUG("CANFD_MAX_DLEN"); - message->set_flags(CAN_FD_FRAME); + message->set_flags(CAN_PROTOCOL_WITH_FD_FRAME); message->set_maxdlen(CANFD_MAX_DLEN); } else @@ -599,7 +611,9 @@ static void write_raw_frame(afb_req_t request, const std::string& bus_name, mess message->set_maxdlen(J1939_MAX_DLEN); #endif - if(message->get_length() > 0 && message->get_length() <= message->get_maxdlen()) + if(message->get_length() > 0 && + message->get_length() <= message->get_maxdlen() && + json_object_get_type(can_data) == json_type_array) { std::vector data; for (int i = 0 ; i < message->get_length() ; i++) @@ -612,7 +626,7 @@ static void write_raw_frame(afb_req_t request, const std::string& bus_name, mess } else { - if(flags&BCM_PROTOCOL) + if(flags&CAN_PROTOCOL) afb_req_fail(request, "Invalid", "Frame BCM"); else if(flags&J1939_PROTOCOL) afb_req_fail(request, "Invalid", "Frame J1939"); @@ -639,20 +653,20 @@ static void write_raw_frame(afb_req_t request, const std::string& bus_name, mess static void write_frame(afb_req_t request, const std::string& bus_name, json_object *json_value, event_filter_t &event_filter) { message_t *message; - int id; - int length; + uint32_t id; + uint32_t length; struct json_object *can_data = nullptr; std::vector data; - AFB_DEBUG("JSON content %s",json_object_get_string(json_value)); + AFB_DEBUG("JSON content %s", json_object_get_string(json_value)); if(!wrap_json_unpack(json_value, "{si, si, so !}", "can_id", &id, "can_dlc", &length, "can_data", &can_data)) { - message = new can_message_t(0,(uint32_t)id,(uint32_t)length,false,0,data,0); - write_raw_frame(request,bus_name,message,can_data,BCM_PROTOCOL,event_filter); + message = new can_message_t(0, id, length, false, 0, data, 0); + write_raw_frame(request, bus_name, message, can_data, CAN_PROTOCOL, event_filter); } #ifdef USE_FEATURE_J1939 else if(!wrap_json_unpack(json_value, "{si, si, so !}", @@ -660,8 +674,8 @@ static void write_frame(afb_req_t request, const std::string& bus_name, json_obj "length", &length, "data", &can_data)) { - message = new j1939_message_t((uint32_t)length,data,0,J1939_NO_NAME,(pgn_t)id,J1939_NO_ADDR); - write_raw_frame(request,bus_name,message,can_data,J1939_PROTOCOL, event_filter); + message = new j1939_message_t(length, data, 0, J1939_NO_NAME, (pgn_t)id, J1939_NO_ADDR); + write_raw_frame(request, bus_name, message, can_data, J1939_PROTOCOL, event_filter); } #endif else @@ -709,10 +723,10 @@ static void write_signal(afb_req_t request, const std::string& name, json_object else if(sig->get_message()->is_isotp()) flags = ISOTP_PROTOCOL; else - flags = BCM_PROTOCOL; + flags = CAN_PROTOCOL; // cfd = encoder_t::build_frame(sig, value); - message_t *message = encoder_t::build_message(sig,value,false,false); + message_t *message = encoder_t::build_message(sig, value, false, false); if(! send_message(message, sig->get_message()->get_bus_device_name(), flags, event_filter, sig) && send) afb_req_success(request, nullptr, "Message correctly sent"); @@ -787,6 +801,36 @@ static struct json_object *get_signals_value(const std::string& name) return ans; } + +static struct json_object *get_id_value(const uint32_t& id) +{ + std::shared_ptr message_definition = application_t::instance().get_message_definition(id); + struct utils::signals_found sf; + struct json_object *ans = nullptr; + + if(message_definition) + sf.signals = list_ptr_signal_t(message_definition->get_signals().begin(), message_definition->get_signals().end()); + + if(sf.signals.empty()) + { + AFB_WARNING("no signal(s) found for %d.", id); + return NULL; + } + + ans = json_object_new_object(); + struct json_object *jsignals = json_object_new_array(); + json_object_object_add(ans, "signals", jsignals); + for(const auto& sig: sf.signals) + { + struct json_object *jobj = json_object_new_object(); + json_object_object_add(jobj, "name", json_object_new_string(sig->get_name().c_str())); + json_object_object_add(jobj, "value", json_object_new_double(sig->get_last_value())); + json_object_array_add(jsignals, jobj); + } + + return ans; +} + void get(afb_req_t request) { int rc = 0; @@ -804,6 +848,37 @@ void get(afb_req_t request) if (!ans) rc = -1; } + else if (args != nullptr && + (json_object_object_get_ex(args, "id", &json_name))) + { + if (json_object_get_type(json_name) == json_type_string) // id is set before and check if it's an array + { + ans = get_id_value(json_object_get_int(json_name)); + } + else if(json_object_get_type(json_name) == json_type_array) + { + ans = json_object_new_array(); + for (int i = 0 ; i < json_object_array_length(json_name); i++) + { + json_object *sub_ans = nullptr; + json_object *x = json_object_array_get_idx(json_name, i); + sub_ans = get_id_value(json_object_get_int(x)); + if(!sub_ans) + rc = -1; + else { + struct json_object *jobj = json_object_new_object(); + struct json_object *jid = json_object_new_string(json_object_get_string(x)); + json_object_object_add(jobj, "id", jid); + json_object_object_add(jobj, "data", sub_ans); + json_object_array_add(ans, jobj); + } + } + } + else + rc = -1; + if (!ans) + rc = -1; + } else { AFB_ERROR("Request argument malformed. Please use the following syntax:"); @@ -877,36 +952,37 @@ void list(afb_req_t request) /// @return Exit code, zero if success. int init_binding(afb_api_t api) { - int ret = 1; + int ret = 0; application_t& application = application_t::instance(); can_bus_t& can_bus_manager = application.get_can_bus_manager(); - can_bus_manager.set_can_devices(); + if(application.get_message_set().empty()) + { + AFB_ERROR("No message_set defined"); + return -1; + } + can_bus_manager.start_threads(); utils::signals_manager_t& sm = utils::signals_manager_t::instance(); - /// Initialize Diagnostic manager that will handle obd2 requests. - /// We pass by default the first CAN bus device to its Initialization. - /// TODO: be able to choose the CAN bus device that will be use as Diagnostic bus. - if(application_t::instance().get_diagnostic_manager().initialize()) - ret = 0; - - // Add a recurring dignostic message request to get engine speed at all times. - openxc_DynamicField search_key = build_DynamicField("diagnostic_messages.engine.speed"); - struct utils::signals_found sf = sm.find_signals(search_key); - - if(sf.signals.empty() && sf.diagnostic_messages.size() == 1) + if (application.get_diagnostic_manager().is_initialized()) { - afb_req_t request = nullptr; + // Add a recurring dignostic message request to get engine speed at all times. + openxc_DynamicField search_key = build_DynamicField("diagnostic_messages.engine.speed"); + struct utils::signals_found sf = sm.find_signals(search_key); - struct event_filter_t event_filter; - event_filter.frequency = sf.diagnostic_messages.front()->get_frequency(); + if(sf.signals.empty() && sf.diagnostic_messages.size() == 1) + { + afb_req_t request = nullptr; - map_subscription& s = sm.get_subscribed_signals(); + struct event_filter_t event_filter; + event_filter.frequency = sf.diagnostic_messages.front()->get_frequency(); - subscribe_unsubscribe_diagnostic_messages(request, true, sf.diagnostic_messages, event_filter, s, true); - } + map_subscription& s = sm.get_subscribed_signals(); + subscribe_unsubscribe_diagnostic_messages(request, true, sf.diagnostic_messages, event_filter, s, true); + } + } #ifdef USE_FEATURE_J1939 std::string j1939_bus; @@ -923,8 +999,8 @@ int init_binding(afb_api_t api) application.set_subscription_address_claiming(low_can_j1939); ret = low_can_subscription_t::open_socket(*low_can_j1939, - j1939_bus, - J1939_ADDR_CLAIM_PROTOCOL); + j1939_bus, + J1939_ADDR_CLAIM_PROTOCOL); if(ret < 0) { @@ -942,3 +1018,41 @@ int init_binding(afb_api_t api) return ret; } + +int load_config(afb_api_t api) +{ + int ret = 0; + CtlConfigT *ctlConfig; + const char *dirList = getenv("CONTROL_CONFIG_PATH"); + std::string bindingDirPath = GetBindingDirPath(api); + std::string filepath = bindingDirPath + "/etc"; + + if (!dirList) + dirList=CONTROL_CONFIG_PATH; + + filepath.append(":"); + filepath.append(dirList); + const char *configPath = CtlConfigSearch(api, filepath.c_str(), "control"); + + if (!configPath) + { + AFB_ERROR_V3("CtlPreInit: No control-%s* config found invalid JSON %s ", GetBinderName(), filepath.c_str()); + return -1; + } + + // create one API per file + ctlConfig = CtlLoadMetaData(api, configPath); + if (!ctlConfig) + { + AFB_ERROR_V3("CtrlPreInit No valid control config file in:\n-- %s", configPath); + return -1; + } + + // Save the config in the api userdata field + afb_api_set_userdata(api, ctlConfig); + + setExternalData(ctlConfig, (void*) &application_t::instance()); + ret= CtlLoadSections(api, ctlConfig, ctlSections_); + + return ret; +}