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