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