Improve comments
[apps/low-level-can-service.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 "uds/uds.h"
24 #include "../utils/openxc-utils.hpp"
25 #include "../configuration.hpp"
26
27 #define MAX_RECURRING_DIAGNOSTIC_FREQUENCY_HZ 10
28 #define MAX_SIMULTANEOUS_DIAG_REQUESTS 50
29 #define TIMERFD_ACCURACY 0
30 #define MICRO 1000000
31
32 diagnostic_manager_t::diagnostic_manager_t()
33         : initialized_{false}
34 {}
35
36 bool diagnostic_manager_t::initialize()
37 {
38         // Mandatory to set the bus before intiliaze shims.
39         bus_ = configuration_t::instance().get_diagnostic_bus();
40
41         init_diagnostic_shims();
42         reset();
43
44         initialized_ = true;
45         DEBUG(binder_interface, "initialize: Diagnostic Manager initialized");
46         return initialized_;
47 }
48
49 /**
50  * @brief initialize shims used by UDS lib and set initialized_ to true.
51  *  It is needed before used the diagnostic manager fully because shims are
52  *  required by most member functions.
53  */
54 void diagnostic_manager_t::init_diagnostic_shims()
55 {
56         shims_ = diagnostic_init_shims(shims_logger, shims_send, NULL);
57         DEBUG(binder_interface, "init_diagnostic_shims: Shims initialized");
58 }
59
60 void diagnostic_manager_t::reset()
61 {
62         if(initialized_)
63         {
64                 DEBUG(binder_interface, "Clearing existing diagnostic requests");
65                 cleanup_active_requests(true);
66         }
67 }
68
69
70 void diagnostic_manager_t::find_and_erase(active_diagnostic_request_t* entry, std::vector<active_diagnostic_request_t*>& requests_list)
71 {
72         auto i = std::find(requests_list.begin(), requests_list.end(), entry);
73         if ( i != requests_list.end())
74                 requests_list.erase(i);
75 }
76
77 /// Move the entry to the free list and decrement the lock count for any
78 /// CAN filters it used.
79 void diagnostic_manager_t::cancel_request(active_diagnostic_request_t* entry)
80 {
81
82         /* TODO: implement acceptance filters.
83         if(entry.arbitration_id_ == OBD2_FUNCTIONAL_BROADCAST_ID) {
84                 for(uint32_t filter = OBD2_FUNCTIONAL_RESPONSE_START;
85                                 filter < OBD2_FUNCTIONAL_RESPONSE_START +
86                                         OBD2_FUNCTIONAL_RESPONSE_COUNT;
87                                 filter++) {
88                         removeAcceptanceFilter(entry.bus_, filter,
89                                         CanMessageFormat::STANDARD, getCanBuses(),
90                                         getCanBusCount());
91                 }
92         } else {
93                 removeAcceptanceFilter(entry.bus_,
94                                 entry.arbitration_id_ +
95                                         DIAGNOSTIC_RESPONSE_ARBITRATION_ID_OFFSET,
96                                 CanMessageFormat::STANDARD, getCanBuses(), getCanBusCount());
97         }*/
98 }
99
100 void diagnostic_manager_t::cleanup_request(active_diagnostic_request_t* entry, bool force)
101 {
102         if(force || (entry->get_in_flight() && entry->request_completed()))
103         {
104                 entry->set_in_flight(false);
105
106                 char request_string[128] = {0};
107                 diagnostic_request_to_string(&entry->get_handle()->request,
108                         request_string, sizeof(request_string));
109                 if(entry->get_recurring())
110                 {
111                         find_and_erase(entry, recurring_requests_);
112                         if(force)
113                                 cancel_request(entry);
114                         DEBUG(binder_interface, "cleanup_request: Cancelling completed, recurring request: %s", request_string);
115                 }
116                 else
117                 {
118                         DEBUG(binder_interface, "cleanup_request: Cancelling completed, non-recurring request: %s", request_string);
119                         find_and_erase(entry, non_recurring_requests_);
120                         cancel_request(entry);
121                 }
122         }
123 }
124
125 /// @brief Clean up the request list
126 void diagnostic_manager_t::cleanup_active_requests(bool force)
127 {
128         for(auto& entry : non_recurring_requests_)
129                 if (entry != nullptr)
130                         cleanup_request(entry, force);
131
132         for(auto& entry : recurring_requests_)
133                 if (entry != nullptr)
134                         cleanup_request(entry, force);
135 }
136
137 /// @brief Will return the active_diagnostic_request_t pointer of found request or nullptr if
138 /// not found.
139 active_diagnostic_request_t* diagnostic_manager_t::find_recurring_request(const DiagnosticRequest* request)
140 {
141         for (auto& entry : recurring_requests_)
142         {
143                 if(entry != nullptr)
144                 {
145                         if(diagnostic_request_equals(&entry->get_handle()->request, request))
146                         {
147                                 return entry;
148                                 break;
149                         }
150                 }
151         }
152         return nullptr;
153 }
154
155 std::shared_ptr<can_bus_dev_t> diagnostic_manager_t::get_can_bus_dev()
156 {
157         return can_bus_t::get_can_device(bus_);
158 }
159
160 bool diagnostic_manager_t::add_request(DiagnosticRequest* request, const std::string name,
161         bool wait_for_multiple_responses, const DiagnosticResponseDecoder decoder,
162         const DiagnosticResponseCallback callback)
163 {
164         cleanup_active_requests(false);
165
166         bool added = true;
167
168         if (non_recurring_requests_.size() <= MAX_SIMULTANEOUS_DIAG_REQUESTS)
169         {
170                 // TODO: implement Acceptance Filter
171                 //      if(updateRequiredAcceptanceFilters(bus, request)) {
172                         active_diagnostic_request_t* entry = new active_diagnostic_request_t(bus_, request, name,
173                                         wait_for_multiple_responses, decoder, callback, 0);
174                         entry->set_handle(shims_, request);
175
176                         char request_string[128] = {0};
177                         diagnostic_request_to_string(&entry->get_handle()->request, request_string,
178                                         sizeof(request_string));
179
180                         find_and_erase(entry, non_recurring_requests_);
181                         DEBUG(binder_interface, "Added one-time diagnostic request on bus %s: %s",
182                                         bus_, request_string);
183
184                         non_recurring_requests_.push_back(entry);
185         }
186         else
187         {
188                 WARNING(binder_interface, "There isn't enough request entry. Vector exhausted %d/%d", (int)non_recurring_requests_.size());
189                 non_recurring_requests_.resize(MAX_SIMULTANEOUS_DIAG_REQUESTS);
190                 added = false;
191         }
192         return added;
193 }
194
195 bool diagnostic_manager_t::validate_optional_request_attributes(float frequencyHz)
196 {
197         if(frequencyHz > MAX_RECURRING_DIAGNOSTIC_FREQUENCY_HZ) {
198                 DEBUG(binder_interface, "Requested recurring diagnostic frequency %d is higher than maximum of %d",
199                         frequencyHz, MAX_RECURRING_DIAGNOSTIC_FREQUENCY_HZ);
200                 return false;
201         }
202         return true;
203 }
204
205 bool diagnostic_manager_t::add_recurring_request(DiagnosticRequest* request, const char* name,
206                 bool wait_for_multiple_responses, const DiagnosticResponseDecoder decoder,
207                 const DiagnosticResponseCallback callback, float frequencyHz)
208 {
209         if(!validate_optional_request_attributes(frequencyHz))
210                 return false;
211
212         cleanup_active_requests(false);
213
214         bool added = true;
215         if(find_recurring_request(request) == nullptr)
216         {
217                 if(recurring_requests_.size() <= MAX_SIMULTANEOUS_DIAG_REQUESTS)
218                 {
219                         sd_event_source *source;
220                         // TODO: implement Acceptance Filter
221                         //if(updateRequiredAcceptanceFilters(bus, request)) {
222                         active_diagnostic_request_t* entry = new active_diagnostic_request_t(bus_, request, name,
223                                         wait_for_multiple_responses, decoder, callback, frequencyHz);
224                         entry->set_handle(shims_, request);
225
226                         char request_string[128] = {0};
227                         diagnostic_request_to_string(&entry->get_handle()->request, request_string,
228                                         sizeof(request_string));
229
230                         DEBUG(binder_interface, "add_recurring_request: Added recurring diagnostic request (freq: %f) on bus %s: %s",
231                                         frequencyHz, bus_.c_str(), request_string);
232
233                         uint64_t usec;
234                         sd_event_now(afb_daemon_get_event_loop(binder_interface->daemon), CLOCK_MONOTONIC, &usec);
235                         if(sd_event_add_time(afb_daemon_get_event_loop(binder_interface->daemon), &source,
236                                         CLOCK_MONOTONIC, usec, TIMERFD_ACCURACY, send_request, request) < 0)
237                         {
238                                 ERROR(binder_interface, "add_recurring_request: Request fails to be schedule through event loop");
239                                 added = false;
240                         }
241                         recurring_requests_.push_back(entry);
242                 }
243                 else
244                 {
245                         WARNING(binder_interface, "add_recurring_request: There isn't enough request entry. Vector exhausted %d/%d", (int)recurring_requests_.size(), MAX_SIMULTANEOUS_DIAG_REQUESTS);
246                         recurring_requests_.resize(MAX_SIMULTANEOUS_DIAG_REQUESTS);
247                         added = false;
248                 }
249         }
250         else
251         {
252                 DEBUG(binder_interface, "add_recurring_request: Can't add request, one already exists with same key");
253                 added = false;
254         }
255         return added;
256 }
257
258
259 bool diagnostic_manager_t::conflicting(active_diagnostic_request_t* request, active_diagnostic_request_t* candidate) const
260 {
261         return (candidate->get_in_flight() && candidate != request &&
262                         candidate->get_can_bus_dev() == request->get_can_bus_dev() &&
263                         candidate->get_id() == request->get_id());
264 }
265
266
267 /// @brief Returns true if there are no other active requests to the same arbitration ID.
268 bool diagnostic_manager_t::clear_to_send(active_diagnostic_request_t* request) const
269 {
270         for ( auto entry : non_recurring_requests_)
271         {
272                 if(conflicting(request, entry))
273                         return false;
274         }
275
276         for ( auto entry : recurring_requests_)
277         {
278                 if(conflicting(request, entry))
279                         return false;
280         }
281         return true;
282 }
283
284 int diagnostic_manager_t::send_request(sd_event_source *s, uint64_t usec, void *userdata)
285 {
286         diagnostic_manager_t& dm = configuration_t::instance().get_diagnostic_manager();
287         DiagnosticRequest* request = (DiagnosticRequest*)userdata;
288         active_diagnostic_request_t* adr = dm.find_recurring_request(request);
289
290 //      if(adr != nullptr && adr->get_can_bus_dev() == dm.get_can_bus_dev() && adr->should_send() &&
291 //              dm.clear_to_send(adr))
292         if(adr != nullptr && adr->get_can_bus_dev() == dm.get_can_bus_dev())
293         {
294                 adr->get_frequency_clock().tick();
295                 start_diagnostic_request(&dm.shims_, adr->get_handle());
296                 if(adr->get_handle()->completed && !adr->get_handle()->success)
297                 {
298                         DEBUG(binder_interface, "send_request: Fatal error sending diagnostic request");
299                         return 0;
300                 }
301                 adr->get_timeout_clock().tick();
302                 adr->set_in_flight(true);
303
304                 if(adr->get_recurring())
305                 {
306                         usec = usec + (uint64_t)(frequency_clock_t::frequency_to_period(adr->get_frequency_clock().get_frequency())*MICRO);
307                         DEBUG(binder_interface, "send_request: Event loop state: %d. usec: %ld", sd_event_get_state(afb_daemon_get_event_loop(binder_interface->daemon)), usec);
308                         if(sd_event_source_set_time(s, usec+1000000) >= 0)
309                                 if(sd_event_source_set_enabled(s, SD_EVENT_ON) >= 0)
310                                         return 1;
311                 }
312         }
313         sd_event_source_unref(s);
314         ERROR(binder_interface, "send_request: Something goes wrong when submitting a new request to the CAN bus");
315         return -1;
316 }
317
318 openxc_VehicleMessage diagnostic_manager_t::relay_diagnostic_response(active_diagnostic_request_t* adr, const DiagnosticResponse& response) const
319 {
320         openxc_VehicleMessage message = build_VehicleMessage();
321         float value = (float)diagnostic_payload_to_integer(&response);
322         if(adr->get_decoder() != nullptr)
323         {
324                 value = adr->get_decoder()(&response, value);
325         }
326
327         if((response.success && strnlen(adr->get_name().c_str(), adr->get_name().size())) > 0)
328         {
329                 // If name, include 'value' instead of payload, and leave of response
330                 // details.
331                 message = build_VehicleMessage(build_SimpleMessage(adr->get_name(), build_DynamicField(value)));
332         }
333         else
334         {
335                 // If no name, send full details of response but still include 'value'
336                 // instead of 'payload' if they provided a decoder. The one case you
337                 // can't get is the full detailed response with 'value'. We could add
338                 // another parameter for that but it's onerous to carry that around.
339                 message = build_VehicleMessage(adr, response, value);
340         }
341
342         if(adr->get_callback() != nullptr)
343         {
344                 adr->get_callback()(adr, &response, value);
345         }
346
347         return message;
348 }
349
350 /// @brief Will take the CAN message and pass it to the receive functions that will process
351 /// diagnostic handle for each active diagnostic request then depending on the result we will 
352 /// return pass the diagnostic response to decode it.
353 ///
354 /// @param[in] entry - A pointer to an active diagnostic request holding a valid diagnostic handle
355 /// @param[in] cm - A raw CAN message.
356 ///
357 /// @return A pointer to a filled openxc_VehicleMessage or a nullptr if nothing has been found.
358 openxc_VehicleMessage diagnostic_manager_t::relay_diagnostic_handle(active_diagnostic_request_t* entry, const can_message_t& cm)
359 {
360         DiagnosticResponse response = diagnostic_receive_can_frame(&shims_, entry->get_handle(), cm.get_id(), cm.get_data(), cm.get_length());
361         if(response.completed && entry->get_handle()->completed)
362         {
363                 if(entry->get_handle()->success)
364                         return relay_diagnostic_response(entry, response);
365         }
366         else if(!response.completed && response.multi_frame)
367         {
368                 // Reset the timeout clock while completing the multi-frame receive
369                 entry->get_timeout_clock().tick();
370         }
371
372         return build_VehicleMessage();
373 }
374
375 /// @brief Find the active diagnostic request with the correct DiagnosticRequestHandle
376 /// member that will understand the CAN message using diagnostic_receive_can_frame function
377 /// from UDS-C library. Then decode it with an ad-hoc method.
378 ///
379 /// @param[in] cm - Raw CAN message received
380 ///
381 /// @return VehicleMessage with decoded value.
382 openxc_VehicleMessage diagnostic_manager_t::find_and_decode_adr(const can_message_t& cm)
383 {
384         openxc_VehicleMessage vehicle_message = build_VehicleMessage();
385
386         for ( auto entry : non_recurring_requests_)
387         {
388                 vehicle_message = relay_diagnostic_handle(entry, cm);
389                 if (is_valid(vehicle_message))
390                         return vehicle_message;
391         }
392
393         for ( auto entry : recurring_requests_)
394         {
395                 vehicle_message = relay_diagnostic_handle(entry, cm);
396                 if (is_valid(vehicle_message))
397                         return vehicle_message;
398         }
399
400         return vehicle_message;
401 }
402
403 /// @brief Tell if the CAN message received is a diagnostic response.
404 /// Request broadcast ID use 0x7DF and assigned ID goes from 0x7E0 to Ox7E7. That allows up to 8 ECU to respond 
405 /// at the same time. The response is the assigned ID + 0x8, so response ID can goes from 0x7E8 to 0x7EF.
406 ///
407 /// @param[in] cm - CAN message received from the socket.
408 ///
409 /// @return True if the active diagnostic request match the response.
410 bool diagnostic_manager_t::is_diagnostic_response(const can_message_t& cm)
411 {
412         if (cm.get_id() >= 0x7e8 && cm.get_id() <= 0x7ef)
413                         return true;
414         return false;
415 }
416
417 DiagnosticShims& diagnostic_manager_t::get_shims()
418 {
419         return shims_;
420 }
421
422 bool diagnostic_manager_t::shims_send(const uint32_t arbitration_id, const uint8_t* data, const uint8_t size)
423 {
424         std::shared_ptr<can_bus_dev_t> can_bus_dev = can_bus_t::get_can_device(configuration_t::instance().get_diagnostic_manager().bus_);
425         return can_bus_dev->shims_send(arbitration_id, data, size);
426 }
427
428 void diagnostic_manager_t::shims_logger(const char* format, ...)
429 {
430         va_list args;
431         va_start(args, format);
432
433         char buffer[256];
434         vsnprintf(buffer, 256, format, args);
435
436         DEBUG(binder_interface, "shims_logger: %s", buffer);
437 }
438
439 void diagnostic_manager_t::shims_timer()
440 {}