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