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