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