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