Use raw pointer to point on parent object.
[apps/low-level-can-service.git] / CAN-binder / low-can-binding / diagnostic / diagnostic-manager.cpp
1 /*
2  * Copyright (C) 2015, 2016 "IoT.bzh"
3  * Author "Romain Forlot" <romain.forlot@iot.bzh>
4  *
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
8  *
9  *       http://www.apache.org/licenses/LICENSE-2.0
10  *
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.
16  */
17
18 #include <systemd/sd-event.h>
19 #include <algorithm>
20
21 #include "diagnostic-manager.hpp"
22
23 #include "../utils/openxc-utils.hpp"
24 #include "../utils/signals.hpp"
25 #include "../binding/configuration.hpp"
26
27 #define MAX_RECURRING_DIAGNOSTIC_FREQUENCY_HZ 10
28 #define MAX_SIMULTANEOUS_DIAG_REQUESTS 50
29 // There are only 8 slots of in flight diagnostic requests
30 #define MAX_SIMULTANEOUS_IN_FLIGHT_REQUESTS 8
31 #define TIMERFD_ACCURACY 0
32 #define MICRO 1000000
33
34 diagnostic_manager_t::diagnostic_manager_t()
35         : initialized_{false}
36 {}
37
38 /// @brief Diagnostic manager isn't initialized at launch but after
39 ///  CAN bus devices initialization. For the moment, it is only possible
40 ///  to have 1 diagnostic bus which are the first bus declared in the JSON
41 ///  description file. Configuration instance will return it.
42 ///
43 /// this will initialize DiagnosticShims and cancel all active requests 
44 ///  if there are any.
45 bool diagnostic_manager_t::initialize()
46 {
47         // Mandatory to set the bus before intialize shims.
48         bus_ = configuration_t::instance().get_diagnostic_bus();
49
50         init_diagnostic_shims();
51         reset();
52
53         initialized_ = true;
54         DEBUG(binder_interface, "%s: Diagnostic Manager initialized", __FUNCTION__);
55         return initialized_;
56 }
57
58 /// @brief initialize shims used by UDS lib and set initialized_ to true.
59 ///  It is needed before used the diagnostic manager fully because shims are
60 ///  required by most member functions.
61 void diagnostic_manager_t::init_diagnostic_shims()
62 {
63         shims_ = diagnostic_init_shims(shims_logger, shims_send, NULL);
64         DEBUG(binder_interface, "%s: Shims initialized", __FUNCTION__);
65 }
66
67 /// @brief Force cleanup all active requests.
68 void diagnostic_manager_t::reset()
69 {
70         DEBUG(binder_interface, "%s: Clearing existing diagnostic requests", __FUNCTION__);
71         cleanup_active_requests(true);
72 }
73
74 /// @brief send function use by diagnostic library. Only one bus used for now
75 ///  so diagnostic request is sent using the default diagnostic bus not matter of
76 ///  which is specified in the diagnostic message definition.
77 ///
78 /// @param[in] arbitration_id - CAN arbitration ID to use when send message. OBD2 broadcast ID
79 ///  is 0x7DF by example.
80 /// @param[in] data - The data payload for the message. NULL is valid if size is also 0.
81 /// @param[in] size - The size of the data payload, in bytes.
82 ///
83 /// @return true if the CAN message was sent successfully. 
84 bool diagnostic_manager_t::shims_send(const uint32_t arbitration_id, const uint8_t* data, const uint8_t size)
85 {
86         std::shared_ptr<can_bus_dev_t> can_bus_dev = can_bus_t::get_can_device(configuration_t::instance().get_diagnostic_manager().bus_);
87         if(can_bus_dev != nullptr)
88                 return can_bus_dev->shims_send(arbitration_id, data, size);
89         ERROR(binder_interface, "%s: Can not retrieve diagnostic bus: %s", __FUNCTION__, configuration_t::instance().get_diagnostic_manager().bus_.c_str());
90         return false;
91 }
92
93 /// @brief The type signature for an optional logging function, if the user
94 /// wishes to provide one. It should print, store or otherwise display the
95 /// message.
96 ///
97 /// message - A format string to log using the given parameters.
98 /// ... (vargs) - the parameters for the format string.
99 ///
100 void diagnostic_manager_t::shims_logger(const char* format, ...)
101 {
102         va_list args;
103         va_start(args, format);
104
105         char buffer[256];
106         vsnprintf(buffer, 256, format, args);
107
108         DEBUG(binder_interface, "%s: %s", __FUNCTION__, buffer);
109 }
110
111 /// @brief The type signature for a... OpenXC TODO: not used yet.
112 void diagnostic_manager_t::shims_timer()
113 {}
114
115 std::shared_ptr<can_bus_dev_t> diagnostic_manager_t::get_can_bus_dev()
116 {
117         return can_bus_t::get_can_device(bus_);
118 }
119
120 /// @brief Return diagnostic manager shims member.
121 DiagnosticShims& diagnostic_manager_t::get_shims()
122 {
123         return shims_;
124 }
125
126 /// @brief Search for a specific active diagnostic request in the provided requests list
127 /// and erase it from the vector. This is useful at unsubscription to clean up the list otherwize
128 /// all received CAN messages will be passed to DiagnosticRequestHandle of all active diagnostic request
129 /// contained in the vector but no event if connected to, so we will decode uneeded request.
130 ///
131 /// @param[in] entry - a pointer of an active_diagnostic_request instance to clean up
132 /// @param[in] requests_list - a vector where to make the search and cleaning.
133 void diagnostic_manager_t::find_and_erase(active_diagnostic_request_t* entry, std::vector<active_diagnostic_request_t*>& requests_list)
134 {
135         auto i = std::find(requests_list.begin(), requests_list.end(), entry);
136         if ( i != requests_list.end())
137                 requests_list.erase(i);
138 }
139
140 // @brief TODO: implement cancel_request if needed... Don't know.
141 void diagnostic_manager_t::cancel_request(active_diagnostic_request_t* entry)
142 {
143
144         /* TODO: implement acceptance filters.
145         if(entry.arbitration_id_ == OBD2_FUNCTIONAL_BROADCAST_ID) {
146                 for(uint32_t filter = OBD2_FUNCTIONAL_RESPONSE_START;
147                                 filter < OBD2_FUNCTIONAL_RESPONSE_START +
148                                         OBD2_FUNCTIONAL_RESPONSE_COUNT;
149                                 filter++) {
150                         removeAcceptanceFilter(entry.bus_, filter,
151                                         CanMessageFormat::STANDARD, getCanBuses(),
152                                         getCanBusCount());
153                 }
154         } else {
155                 removeAcceptanceFilter(entry.bus_,
156                                 entry.arbitration_id_ +
157                                         DIAGNOSTIC_RESPONSE_ARBITRATION_ID_OFFSET,
158                                 CanMessageFormat::STANDARD, getCanBuses(), getCanBusCount());
159         }*/
160 }
161
162 /// @brief Cleanup a specific request if it isn't running and get complete. As it is almost
163 /// impossible to get that state for a recurring request without waiting for that, you can 
164 /// force the cleaning operation.
165 ///
166 /// @param[in] entry - the request to clean
167 /// @param[in] force - Force the cleaning or not ?
168 void diagnostic_manager_t::cleanup_request(active_diagnostic_request_t* entry, bool force)
169 {
170         if((force || (entry != nullptr && entry->get_in_flight() && entry->request_completed())))
171         {
172                 entry->set_in_flight(false);
173
174                 char request_string[128] = {0};
175                 diagnostic_request_to_string(&entry->get_handle()->request,
176                         request_string, sizeof(request_string));
177                 if(force && entry->get_recurring())
178                 {
179                         find_and_erase(entry, recurring_requests_);
180                         cancel_request(entry);
181                         DEBUG(binder_interface, "%s: Cancelling completed, recurring request: %s", __FUNCTION__, request_string);
182                 }
183                 else
184                 {
185                         DEBUG(binder_interface, "%s: Cancelling completed, non-recurring request: %s", __FUNCTION__, request_string);
186                         find_and_erase(entry, non_recurring_requests_);
187                         cancel_request(entry);
188                 }
189         }
190 }
191
192 /// @brief Clean up all requests lists, recurring and not recurring.
193 ///
194 /// @param[in] force - Force the cleaning or not ? If true, that will do
195 /// the same effect as a call to reset().
196 void diagnostic_manager_t::cleanup_active_requests(bool force)
197 {
198         for(auto& entry : non_recurring_requests_)
199                 if (entry != nullptr)
200                         cleanup_request(entry, force);
201
202         for(auto& entry : recurring_requests_)
203                 if (entry != nullptr)
204                         cleanup_request(entry, force);
205 }
206
207 /// @brief Will return the active_diagnostic_request_t pointer for theDiagnosticRequest or nullptr if
208 /// not found.
209 ///
210 /// @param[in] request - Search key, method will go through recurring list to see if it find that request
211 ///  holded by the DiagnosticHandle member.
212 active_diagnostic_request_t* diagnostic_manager_t::find_recurring_request(const DiagnosticRequest* request)
213 {
214         for (auto& entry : recurring_requests_)
215         {
216                 if(entry != nullptr)
217                 {
218                         if(diagnostic_request_equals(&entry->get_handle()->request, request))
219                         {
220                                 return entry;
221                                 break;
222                         }
223                 }
224         }
225         return nullptr;
226 }
227
228 /// @brief Add and send a new one-time diagnostic request.
229 ///
230 /// A one-time (aka non-recurring) request can existing in parallel with a
231 /// recurring request for the same PID or mode, that's not a problem.
232 ///
233 /// For an example, see the docs for addRecurringRequest. This function is very
234 /// similar but leaves out the frequencyHz parameter.
235 ///
236 /// @param[in] request - The parameters for the request.
237 /// @param[in] name - Human readable name this response, to be used when
238 ///      publishing received responses. TODO: If the name is NULL, the published output
239 ///      will use the raw OBD-II response format.
240 /// @param[in] wait_for_multiple_responses - If false, When any response is received
241 ///      for this request it will be removed from the active list. If true, the
242 ///      request will remain active until the timeout clock expires, to allow it
243 ///      to receive multiple response. Functional broadcast requests will always
244 ///      waint for the timeout, regardless of this parameter.
245 /// @param[in] decoder - An optional DiagnosticResponseDecoder to parse the payload of
246 ///      responses to this request. If the decoder is NULL, the output will
247 ///      include the raw payload instead of a parsed value.
248 /// @param[in] callback - An optional DiagnosticResponseCallback to be notified whenever a
249 ///      response is received for this request.
250 ///
251 /// @return true if the request was added successfully. Returns false if there
252 /// wasn't a free active request entry, if the frequency was too high or if the
253 /// CAN acceptance filters could not be configured,
254 bool diagnostic_manager_t::add_request(DiagnosticRequest* request, const std::string name,
255         bool wait_for_multiple_responses, const DiagnosticResponseDecoder decoder,
256         const DiagnosticResponseCallback callback)
257 {
258         cleanup_active_requests(false);
259
260         bool added = true;
261
262         if (non_recurring_requests_.size() <= MAX_SIMULTANEOUS_DIAG_REQUESTS)
263         {
264                 // TODO: implement Acceptance Filter
265                 //      if(updateRequiredAcceptanceFilters(bus, request)) {
266                         active_diagnostic_request_t* entry = new active_diagnostic_request_t(bus_, request, name,
267                                         wait_for_multiple_responses, decoder, callback, 0);
268                         entry->set_handle(shims_, request);
269
270                         char request_string[128] = {0};
271                         diagnostic_request_to_string(&entry->get_handle()->request, request_string,
272                                         sizeof(request_string));
273
274                         find_and_erase(entry, non_recurring_requests_);
275                         DEBUG(binder_interface, "%s: Added one-time diagnostic request on bus %s: %s", __FUNCTION__,
276                                         bus_.c_str(), request_string);
277
278                         non_recurring_requests_.push_back(entry);
279         }
280         else
281         {
282                 WARNING(binder_interface, "%s: There isn't enough request entry. Vector exhausted %d/%d", __FUNCTION__, (int)non_recurring_requests_.size(), MAX_SIMULTANEOUS_DIAG_REQUESTS);
283                 non_recurring_requests_.resize(MAX_SIMULTANEOUS_DIAG_REQUESTS);
284                 added = false;
285         }
286         return added;
287 }
288
289 bool diagnostic_manager_t::validate_optional_request_attributes(float frequencyHz)
290 {
291         if(frequencyHz > MAX_RECURRING_DIAGNOSTIC_FREQUENCY_HZ) {
292                 DEBUG(binder_interface, "%s: Requested recurring diagnostic frequency %lf is higher than maximum of %d", __FUNCTION__,
293                         frequencyHz, MAX_RECURRING_DIAGNOSTIC_FREQUENCY_HZ);
294                 return false;
295         }
296         return true;
297 }
298
299 /// @brief Add and send a new recurring diagnostic request.
300 ///
301 /// At most one recurring request can be active for the same arbitration ID, mode
302 /// and (if set) PID on the same bus at one time. If you try and call
303 /// addRecurringRequest with the same key, it will return an error.
304 ///
305 /// TODO: This also adds any neccessary CAN acceptance filters so we can receive the
306 /// response. If the request is to the functional broadcast ID (0x7df) filters
307 /// are added for all functional addresses (0x7e8 to 0x7f0).
308 ///
309 /// Example:
310 ///
311 ///     // Creating a functional broadcast, mode 1 request for PID 2.
312 ///     DiagnosticRequest request = {
313 ///         arbitration_id: 0x7df,
314 ///         mode: 1,
315 ///         has_pid: true,
316 ///         pid: 2
317 ///     };
318 ///
319 ///     // Add a recurring request, to be sent at 1Hz, and published with the
320 ///     // name "my_pid_request"
321 ///     addRecurringRequest(&getConfiguration()->diagnosticsManager,
322 ///          canBus,
323 ///          &request,
324 ///          "my_pid_request",
325 ///          false,
326 ///          NULL,
327 ///          NULL,
328 ///          1);
329 ///
330 /// @param[in] request - The parameters for the request.
331 /// @param[in] name - An optional human readable name this response, to be used when
332 ///      publishing received responses. If the name is NULL, the published output
333 ///      will use the raw OBD-II response format.
334 /// @param[in] wait_for_multiple_responses - If false, When any response is received
335 ///      for this request it will be removed from the active list. If true, the
336 ///      request will remain active until the timeout clock expires, to allow it
337 ///      to receive multiple response. Functional broadcast requests will always
338 ///      waint for the timeout, regardless of this parameter.
339 /// @param[in] decoder - An optional DiagnosticResponseDecoder to parse the payload of
340 ///      responses to this request. If the decoder is NULL, the output will
341 ///      include the raw payload instead of a parsed value.
342 /// @param[in] callback - An optional DiagnosticResponseCallback to be notified whenever a
343 ///      response is received for this request.
344 /// @param[in] frequencyHz - The frequency (in Hz) to send the request. A frequency above
345 ///      MAX_RECURRING_DIAGNOSTIC_FREQUENCY_HZ is not allowed, and will make this
346 ///      function return false.
347 ///
348 /// @return true if the request was added successfully. Returns false if there
349 /// was too much already running requests, if the frequency was too high TODO:or if the
350 /// CAN acceptance filters could not be configured,
351 ///
352 bool diagnostic_manager_t::add_recurring_request(DiagnosticRequest* request, const char* name,
353                 bool wait_for_multiple_responses, const DiagnosticResponseDecoder decoder,
354                 const DiagnosticResponseCallback callback, float frequencyHz)
355 {
356         if(!validate_optional_request_attributes(frequencyHz))
357                 return false;
358
359         cleanup_active_requests(false);
360
361         bool added = true;
362         if(find_recurring_request(request) == nullptr)
363         {
364                 if(recurring_requests_.size() <= MAX_SIMULTANEOUS_DIAG_REQUESTS)
365                 {
366                         sd_event_source *source;
367                         // TODO: implement Acceptance Filter
368                         //if(updateRequiredAcceptanceFilters(bus, request)) {
369                         active_diagnostic_request_t* entry = new active_diagnostic_request_t(bus_, request, name,
370                                         wait_for_multiple_responses, decoder, callback, frequencyHz);
371                         entry->set_handle(shims_, request);
372
373                         uint64_t usec;
374                         sd_event_now(afb_daemon_get_event_loop(binder_interface->daemon), CLOCK_BOOTTIME, &usec);
375                         if(recurring_requests_.size() > 0)
376                         {
377                                 DEBUG(binder_interface, "%s: Added 100ms to usec to stagger sending requests", __FUNCTION__);
378                                 usec += 100000;
379                         }
380
381                         DEBUG(binder_interface, "%s: Added recurring diagnostic request (freq: %f) on bus %s at %ld. Event loop state: %d", __FUNCTION__,
382                                         frequencyHz,
383                                         bus_.c_str(),
384                                         usec,
385                                         sd_event_get_state(afb_daemon_get_event_loop(binder_interface->daemon)));
386
387                         if(sd_event_add_time(afb_daemon_get_event_loop(binder_interface->daemon), &source,
388                                         CLOCK_BOOTTIME, usec, TIMERFD_ACCURACY, send_request, request) < 0)
389                         {
390                                 ERROR(binder_interface, "%s: Request fails to be schedule through event loop", __FUNCTION__);
391                                 added = false;
392                         }
393                         recurring_requests_.push_back(entry);
394                 }
395                 else
396                 {
397                         WARNING(binder_interface, "%s: There isn't enough request entry. Vector exhausted %d/%d", __FUNCTION__, (int)recurring_requests_.size(), MAX_SIMULTANEOUS_DIAG_REQUESTS);
398                         recurring_requests_.resize(MAX_SIMULTANEOUS_DIAG_REQUESTS);
399                         added = false;
400                 }
401         }
402         else
403         {
404                 DEBUG(binder_interface, "%s: Can't add request, one already exists with same key", __FUNCTION__);
405                 added = false;
406         }
407         return added;
408 }
409
410 /// @brief Returns true if there are two active requests running for the same arbitration ID.
411 bool diagnostic_manager_t::conflicting(active_diagnostic_request_t* request, active_diagnostic_request_t* candidate) const
412 {
413         return (candidate->get_in_flight() && candidate != request &&
414                         candidate->get_can_bus_dev() == request->get_can_bus_dev() &&
415                         candidate->get_id() == request->get_id());
416 }
417
418
419 /// @brief Returns true if there are no other active requests to the same arbitration ID
420 /// and if there aren't more than 8 requests in flight at the same time.
421 bool diagnostic_manager_t::clear_to_send(active_diagnostic_request_t* request) const
422 {
423         int total_in_flight = 0;
424         for ( auto entry : non_recurring_requests_)
425         {
426                 if(conflicting(request, entry))
427                         return false;
428                 if(entry->get_in_flight())
429                         total_in_flight++;
430         }
431
432         for ( auto entry : recurring_requests_)
433         {
434                 if(conflicting(request, entry))
435                         return false;
436                 if(entry->get_in_flight())
437                         total_in_flight++;
438         }
439
440         if(total_in_flight > MAX_SIMULTANEOUS_IN_FLIGHT_REQUESTS)
441                 return false;
442         return true;
443 }
444
445 int diagnostic_manager_t::reschedule_request(sd_event_source *s, uint64_t usec, active_diagnostic_request_t* adr)
446 {
447         usec = usec + (uint64_t)(adr->get_frequency_clock().frequency_to_period());
448         DEBUG(binder_interface, "%s: Event loop state: %d. usec: %ld", __FUNCTION__, sd_event_get_state(afb_daemon_get_event_loop(binder_interface->daemon)), usec);
449         if(sd_event_source_set_time(s, usec) >= 0)
450                 if(sd_event_source_set_enabled(s, SD_EVENT_ON) >= 0)
451                         return 0;
452         sd_event_source_unref(s);
453         return -1;
454 }
455
456 /// @brief Systemd timer event callback use to send CAN messages at regular interval. Depending
457 /// on the diagnostic message frequency.
458 ///
459 /// This should be called from systemd binder event loop and the event is created on add_recurring_request
460 ///
461 /// @param[in] s - Systemd event source pointer used to reschedule the new iteration.
462 /// @param[in] usec - previous call timestamp in microseconds.
463 /// @param[in] userdata - the DiagnosticRequest struct, use to retrieve the active request from the list.
464 ///
465 /// @return positive integer if sent and rescheduled or negative value if something wrong. If an error occurs
466 /// event will be disabled.
467 int diagnostic_manager_t::send_request(sd_event_source *s, uint64_t usec, void *userdata)
468 {
469         diagnostic_manager_t& dm = configuration_t::instance().get_diagnostic_manager();
470         DiagnosticRequest* request = (DiagnosticRequest*)userdata;
471         active_diagnostic_request_t* adr = dm.find_recurring_request(request);
472
473         dm.cleanup_active_requests(false);
474         if(adr != nullptr && adr->get_can_bus_dev() == dm.get_can_bus_dev() && adr->should_send() &&
475                 dm.clear_to_send(adr))
476         {
477                 adr->get_frequency_clock().tick();
478                 start_diagnostic_request(&dm.shims_, adr->get_handle());
479                 if(adr->get_handle()->completed && !adr->get_handle()->success)
480                 {
481                                 ERROR(binder_interface, "%s: Fatal error sending diagnostic request", __FUNCTION__);
482                                 sd_event_source_unref(s);
483                                 return -1;
484                 }
485
486                 adr->get_timeout_clock().tick();
487                 adr->set_in_flight(true);
488         }
489
490         if(adr != nullptr && adr->get_recurring())
491         {
492                 return dm.reschedule_request(s, usec, adr);
493         }
494
495         sd_event_source_unref(s);
496         NOTICE(binder_interface, "%s: Request doesn't exist anymore. Canceling.'", __FUNCTION__);
497         return -2;
498 }
499
500 /// @brief Will decode the diagnostic response and build the final openxc_VehicleMessage to return.
501 ///
502 /// @param[in] adr - A pointer to an active diagnostic request holding a valid diagnostic handle
503 /// @param[in] response - The response to decode from which the Vehicle message will be built and returned
504 ///
505 /// @return A filled openxc_VehicleMessage or a zeroed struct if there is an error.
506 openxc_VehicleMessage diagnostic_manager_t::relay_diagnostic_response(active_diagnostic_request_t* adr, const DiagnosticResponse& response)
507 {
508         openxc_VehicleMessage message = build_VehicleMessage();
509         float value = (float)diagnostic_payload_to_integer(&response);
510         if(adr->get_decoder() != nullptr)
511         {
512                 value = adr->get_decoder()(&response, value);
513         }
514
515         if((response.success && strnlen(adr->get_name().c_str(), adr->get_name().size())) > 0)
516         {
517                 // If name, include 'value' instead of payload, and leave of response
518                 // details.
519                 message = build_VehicleMessage(build_SimpleMessage(adr->get_name(), build_DynamicField(value)));
520         }
521         else
522         {
523                 // If no name, send full details of response but still include 'value'
524                 // instead of 'payload' if they provided a decoder. The one case you
525                 // can't get is the full detailed response with 'value'. We could add
526                 // another parameter for that but it's onerous to carry that around.
527                 message = build_VehicleMessage(adr, response, value);
528         }
529
530         // If not success but completed then the pid isn't supported
531         if(!response.success)
532         {
533                 struct utils::signals_found found_signals;
534                 found_signals = utils::signals_manager_t::instance().find_signals(build_DynamicField(adr->get_name()));
535                 found_signals.diagnostic_messages.front()->set_supported(false);
536                 cleanup_request(adr, true);
537                 NOTICE(binder_interface, "%s: PID not supported or ill formed. Please unsubscribe from it. Error code : %d", __FUNCTION__, response.negative_response_code);
538                 message = build_VehicleMessage(build_SimpleMessage(adr->get_name(), build_DynamicField("This PID isn't supported by your vehicle.")));
539         }
540
541         if(adr->get_callback() != nullptr)
542         {
543                 adr->get_callback()(adr, &response, value);
544         }
545
546         return message;
547 }
548
549 /// @brief Will take the CAN message and pass it to the receive functions that will process
550 /// diagnostic handle for each active diagnostic request then depending on the result we will 
551 /// return pass the diagnostic response to decode it.
552 ///
553 /// @param[in] entry - A pointer to an active diagnostic request holding a valid diagnostic handle
554 /// @param[in] cm - A raw CAN message.
555 ///
556 /// @return A pointer to a filled openxc_VehicleMessage or a nullptr if nothing has been found.
557 openxc_VehicleMessage diagnostic_manager_t::relay_diagnostic_handle(active_diagnostic_request_t* entry, const can_message_t& cm)
558 {
559         DiagnosticResponse response = diagnostic_receive_can_frame(&shims_, entry->get_handle(), cm.get_id(), cm.get_data(), cm.get_length());
560         if(response.completed && entry->get_handle()->completed)
561         {
562                 if(entry->get_handle()->success)
563                         return relay_diagnostic_response(entry, response);
564         }
565         else if(!response.completed && response.multi_frame)
566         {
567                 // Reset the timeout clock while completing the multi-frame receive
568                 entry->get_timeout_clock().tick();
569         }
570
571         return build_VehicleMessage();
572 }
573
574 /// @brief Find the active diagnostic request with the correct DiagnosticRequestHandle
575 /// member that will understand the CAN message using diagnostic_receive_can_frame function
576 /// from UDS-C library. Then decode it with an ad-hoc method.
577 ///
578 /// @param[in] cm - Raw CAN message received
579 ///
580 /// @return VehicleMessage with decoded value.
581 openxc_VehicleMessage diagnostic_manager_t::find_and_decode_adr(const can_message_t& cm)
582 {
583         openxc_VehicleMessage vehicle_message = build_VehicleMessage();
584
585         for ( auto entry : non_recurring_requests_)
586         {
587                 vehicle_message = relay_diagnostic_handle(entry, cm);
588                 if (is_valid(vehicle_message))
589                         return vehicle_message;
590         }
591
592         for ( auto entry : recurring_requests_)
593         {
594                 vehicle_message = relay_diagnostic_handle(entry, cm);
595                 if (is_valid(vehicle_message))
596                         return vehicle_message;
597         }
598
599         return vehicle_message;
600 }
601
602 /// @brief Tell if the CAN message received is a diagnostic response.
603 /// Request broadcast ID use 0x7DF and assigned ID goes from 0x7E0 to Ox7E7. That allows up to 8 ECU to respond 
604 /// at the same time. The response is the assigned ID + 0x8, so response ID can goes from 0x7E8 to 0x7EF.
605 ///
606 /// @param[in] cm - CAN message received from the socket.
607 ///
608 /// @return True if the active diagnostic request match the response.
609 bool diagnostic_manager_t::is_diagnostic_response(const can_message_t& cm)
610 {
611         if (cm.get_id() >= 0x7e8 && cm.get_id() <= 0x7ef)
612                         return true;
613         return false;
614 }