2 * Copyright (C) 2015, 2016 "IoT.bzh"
3 * Author "Romain Forlot" <romain.forlot@iot.bzh>
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
9 * http://www.apache.org/licenses/LICENSE-2.0
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
18 #include <systemd/sd-event.h>
21 #include "diagnostic-manager.hpp"
24 #include "../utils/openxc-utils.hpp"
25 #include "../configuration.hpp"
27 #define MAX_RECURRING_DIAGNOSTIC_FREQUENCY_HZ 10
28 #define MAX_SIMULTANEOUS_DIAG_REQUESTS 50
29 #define TIMERFD_ACCURACY 0
32 diagnostic_manager_t::diagnostic_manager_t()
36 bool diagnostic_manager_t::initialize(std::shared_ptr<can_bus_dev_t> cbd)
38 // Mandatory to set the bus before intiliaze shims.
41 init_diagnostic_shims();
45 DEBUG(binder_interface, "initialize: Diagnostic Manager initialized");
50 * @brief initialize shims used by UDS lib and set initialized_ to true.
51 * It is needed before used the diagnostic manager fully because shims are
52 * required by most member functions.
54 void diagnostic_manager_t::init_diagnostic_shims()
56 shims_ = diagnostic_init_shims(shims_logger, shims_send, NULL);
57 DEBUG(binder_interface, "init_diagnostic_shims: Shims initialized");
60 void diagnostic_manager_t::reset()
64 DEBUG(binder_interface, "Clearing existing diagnostic requests");
65 cleanup_active_requests(true);
70 void diagnostic_manager_t::find_and_erase(active_diagnostic_request_t* entry, std::vector<active_diagnostic_request_t*>& requests_list)
72 auto i = std::find(requests_list.begin(), requests_list.end(), entry);
73 if ( i != requests_list.end())
74 requests_list.erase(i);
77 /// Move the entry to the free list and decrement the lock count for any
78 /// CAN filters it used.
79 void diagnostic_manager_t::cancel_request(active_diagnostic_request_t* entry)
82 /* TODO: implement acceptance filters.
83 if(entry.arbitration_id_ == OBD2_FUNCTIONAL_BROADCAST_ID) {
84 for(uint32_t filter = OBD2_FUNCTIONAL_RESPONSE_START;
85 filter < OBD2_FUNCTIONAL_RESPONSE_START +
86 OBD2_FUNCTIONAL_RESPONSE_COUNT;
88 removeAcceptanceFilter(entry.bus_, filter,
89 CanMessageFormat::STANDARD, getCanBuses(),
93 removeAcceptanceFilter(entry.bus_,
94 entry.arbitration_id_ +
95 DIAGNOSTIC_RESPONSE_ARBITRATION_ID_OFFSET,
96 CanMessageFormat::STANDARD, getCanBuses(), getCanBusCount());
100 void diagnostic_manager_t::cleanup_request(active_diagnostic_request_t* entry, bool force)
102 if(force || (entry->get_in_flight() && entry->request_completed()))
104 entry->set_in_flight(false);
106 char request_string[128] = {0};
107 diagnostic_request_to_string(&entry->get_handle()->request,
108 request_string, sizeof(request_string));
109 if(entry->get_recurring())
111 find_and_erase(entry, recurring_requests_);
113 cancel_request(entry);
117 DEBUG(binder_interface, "cleanup_request: Cancelling completed, non-recurring request: %s", request_string);
118 find_and_erase(entry, non_recurring_requests_);
119 cancel_request(entry);
124 /// @brief Clean up the request list
125 void diagnostic_manager_t::cleanup_active_requests(bool force)
127 for(auto& entry : non_recurring_requests_)
128 if (entry != nullptr)
129 cleanup_request(entry, force);
131 for(auto& entry : recurring_requests_)
132 if (entry != nullptr)
133 cleanup_request(entry, force);
136 /// @brief Will return the active_diagnostic_request_t pointer of found request or nullptr if
138 active_diagnostic_request_t* diagnostic_manager_t::find_recurring_request(const DiagnosticRequest* request)
140 for (auto& entry : recurring_requests_)
144 if(diagnostic_request_equals(&entry->get_handle()->request, request))
154 std::shared_ptr<can_bus_dev_t> diagnostic_manager_t::get_can_bus_dev()
159 bool diagnostic_manager_t::add_request(DiagnosticRequest* request, const std::string name,
160 bool wait_for_multiple_responses, const DiagnosticResponseDecoder decoder,
161 const DiagnosticResponseCallback callback)
163 cleanup_active_requests(false);
167 if (non_recurring_requests_.size() <= MAX_SIMULTANEOUS_DIAG_REQUESTS)
169 // TODO: implement Acceptance Filter
170 // if(updateRequiredAcceptanceFilters(bus, request)) {
171 active_diagnostic_request_t* entry = new active_diagnostic_request_t(bus_, request, name,
172 wait_for_multiple_responses, decoder, callback, 0);
173 entry->set_handle(shims_, request);
175 char request_string[128] = {0};
176 diagnostic_request_to_string(&entry->get_handle()->request, request_string,
177 sizeof(request_string));
179 find_and_erase(entry, non_recurring_requests_);
180 DEBUG(binder_interface, "Added one-time diagnostic request on bus %s: %s",
181 bus_->get_device_name(), request_string);
183 non_recurring_requests_.push_back(entry);
187 WARNING(binder_interface, "There isn't enough request entry. Vector exhausted %d/%d", (int)non_recurring_requests_.size());
188 non_recurring_requests_.resize(MAX_SIMULTANEOUS_DIAG_REQUESTS);
194 bool diagnostic_manager_t::validate_optional_request_attributes(float frequencyHz)
196 if(frequencyHz > MAX_RECURRING_DIAGNOSTIC_FREQUENCY_HZ) {
197 DEBUG(binder_interface, "Requested recurring diagnostic frequency %d is higher than maximum of %d",
198 frequencyHz, MAX_RECURRING_DIAGNOSTIC_FREQUENCY_HZ);
204 bool diagnostic_manager_t::add_recurring_request(DiagnosticRequest* request, const char* name,
205 bool wait_for_multiple_responses, const DiagnosticResponseDecoder decoder,
206 const DiagnosticResponseCallback callback, float frequencyHz)
208 if(!validate_optional_request_attributes(frequencyHz))
211 cleanup_active_requests(false);
214 if(find_recurring_request(request) == nullptr)
216 if(recurring_requests_.size() <= MAX_SIMULTANEOUS_DIAG_REQUESTS)
218 sd_event_source *source;
219 // TODO: implement Acceptance Filter
220 //if(updateRequiredAcceptanceFilters(bus, request)) {
221 active_diagnostic_request_t* entry = new active_diagnostic_request_t(bus_, request, name,
222 wait_for_multiple_responses, decoder, callback, frequencyHz);
223 entry->set_handle(shims_, request);
225 char request_string[128] = {0};
226 diagnostic_request_to_string(&entry->get_handle()->request, request_string,
227 sizeof(request_string));
229 DEBUG(binder_interface, "add_recurring_request: Added recurring diagnostic request (freq: %f) on bus %s: %s",
230 frequencyHz, bus_->get_device_name().c_str(), request_string);
233 sd_event_now(afb_daemon_get_event_loop(binder_interface->daemon), CLOCK_MONOTONIC, &usec);
234 if(sd_event_add_time(afb_daemon_get_event_loop(binder_interface->daemon), &source,
235 CLOCK_MONOTONIC, usec, TIMERFD_ACCURACY, send_request, request) < 0)
237 ERROR(binder_interface, "add_recurring_request: Request fails to be schedule through event loop");
240 recurring_requests_.push_back(entry);
244 WARNING(binder_interface, "add_recurring_request: There isn't enough request entry. Vector exhausted %d/%d", (int)recurring_requests_.size(), MAX_SIMULTANEOUS_DIAG_REQUESTS);
245 recurring_requests_.resize(MAX_SIMULTANEOUS_DIAG_REQUESTS);
251 DEBUG(binder_interface, "add_recurring_request: Can't add request, one already exists with same key");
257 bool diagnostic_manager_t::is_diagnostic_response(const active_diagnostic_request_t& adr, const can_message_t& cm) const
259 if(cm.get_id() == adr.get_id() + DIAGNOSTIC_RESPONSE_ARBITRATION_ID_OFFSET)
261 DEBUG(binder_interface, "Doesn't find an active diagnostic request that matches.");
265 active_diagnostic_request_t* diagnostic_manager_t::is_diagnostic_response(const can_message_t& can_message)
267 for (auto& entry : non_recurring_requests_)
269 if(is_diagnostic_response(*entry, can_message))
273 for (auto& entry : recurring_requests_)
275 if(is_diagnostic_response(*entry, can_message))
281 openxc_VehicleMessage diagnostic_manager_t::relay_diagnostic_response(active_diagnostic_request_t* adr, const DiagnosticResponse& response) const
283 openxc_VehicleMessage message;
284 float value = (float)diagnostic_payload_to_integer(&response);
285 if(adr->get_decoder() != nullptr)
287 value = adr->get_decoder()(&response, value);
290 if((response.success && strnlen(adr->get_name().c_str(), adr->get_name().size())) > 0)
292 // If name, include 'value' instead of payload, and leave of response
294 message = build_VehicleMessage(build_SimpleMessage(adr->get_name(), build_DynamicField(value)));
298 // If no name, send full details of response but still include 'value'
299 // instead of 'payload' if they provided a decoder. The one case you
300 // can't get is the full detailed response with 'value'. We could add
301 // another parameter for that but it's onerous to carry that around.
302 message = build_VehicleMessage(adr, response, value);
305 if(adr->get_callback() != nullptr)
307 adr->get_callback()(adr, &response, value);
313 bool diagnostic_manager_t::conflicting(active_diagnostic_request_t* request, active_diagnostic_request_t* candidate) const
315 return (candidate->get_in_flight() && candidate != request &&
316 candidate->get_can_bus_dev() == request->get_can_bus_dev() &&
317 candidate->get_id() == request->get_id());
321 /// @brief Returns true if there are no other active requests to the same arbitration ID.
322 bool diagnostic_manager_t::clear_to_send(active_diagnostic_request_t* request) const
324 for ( auto entry : non_recurring_requests_)
326 if(conflicting(request, entry))
330 for ( auto entry : recurring_requests_)
332 if(conflicting(request, entry))
338 int diagnostic_manager_t::send_request(sd_event_source *s, uint64_t usec, void *userdata)
340 diagnostic_manager_t& dm = configuration_t::instance().get_diagnostic_manager();
341 DiagnosticRequest* request = (DiagnosticRequest*)userdata;
342 active_diagnostic_request_t* adr = dm.find_recurring_request(request);
344 // if(adr != nullptr && adr->get_can_bus_dev() == dm.get_can_bus_dev() && adr->should_send() &&
345 // dm.clear_to_send(adr))
346 if(adr != nullptr && adr->get_can_bus_dev() == dm.bus_)
348 adr->get_frequency_clock().tick();
349 start_diagnostic_request(&dm.shims_, adr->get_handle());
350 if(adr->get_handle()->completed && !adr->get_handle()->success)
352 DEBUG(binder_interface, "send_request: Fatal error sending diagnostic request");
355 adr->get_timeout_clock().tick();
356 adr->set_in_flight(true);
358 if(adr->get_recurring())
360 usec = usec + (uint64_t)(frequency_clock_t::frequency_to_period(adr->get_frequency_clock().get_frequency())*MICRO);
361 DEBUG(binder_interface, "send_request: Event loop state: %d. usec: %ld", sd_event_get_state(afb_daemon_get_event_loop(binder_interface->daemon)), usec);
362 if(sd_event_source_set_time(s, usec+1000000) >= 0)
363 if(sd_event_source_set_enabled(s, SD_EVENT_ON) >= 0)
367 sd_event_source_unref(s);
368 ERROR(binder_interface, "send_request: Something goes wrong when submitting a new request to the CAN bus");
372 DiagnosticShims& diagnostic_manager_t::get_shims()
377 bool diagnostic_manager_t::shims_send(const uint32_t arbitration_id, const uint8_t* data, const uint8_t size)
379 std::shared_ptr<can_bus_dev_t> can_bus_dev = configuration_t::instance().get_diagnostic_manager().get_can_bus_dev();
380 return can_bus_dev->shims_send(arbitration_id, data, size);
383 void diagnostic_manager_t::shims_logger(const char* format, ...)
386 va_start(args, format);
389 vsnprintf(buffer, 256, format, args);
391 DEBUG(binder_interface, "shims_logger: %s", buffer);
394 void diagnostic_manager_t::shims_timer()