Enabling recurrent check of diagnostic requests.
[apps/agl-service-can-low-level.git] / src / diagnostic / diagnostic-manager.cpp
1 /*
2  * Copyright (C) 2015, 2016 "IoT.bzh"
3  * Author "Romain Forlot" <romain.forlot@iot.bzh>
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *       http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  */
17
18 #include <algorithm>
19
20 #include "diagnostic-manager.hpp"
21
22 #include "uds/uds.h"
23 #include "../utils/openxc-utils.hpp"
24 #include "../configuration.hpp"
25
26 #define MAX_RECURRING_DIAGNOSTIC_FREQUENCY_HZ 10
27 #define MAX_SIMULTANEOUS_DIAG_REQUESTS 50
28 #define MAX_REQUEST_ENTRIES 50
29
30 diagnostic_manager_t::diagnostic_manager_t()
31         : request_list_entries_(MAX_REQUEST_ENTRIES), initialized_{false}
32 {}
33
34 bool diagnostic_manager_t::initialize(std::shared_ptr<can_bus_dev_t> cbd)
35 {
36         // Mandatory to set the bus before intiliaze shims.
37         bus_ = cbd;
38
39         init_diagnostic_shims();
40         reset();
41
42         initialized_ = true;
43         DEBUG(binder_interface, "initialize: Diagnostic Manager initialized");
44         return initialized_;
45 }
46
47 /**
48  * @brief initialize shims used by UDS lib and set initialized_ to true.
49  *  It is needed before used the diagnostic manager fully because shims are
50  *  required by most member functions.
51  */
52 void diagnostic_manager_t::init_diagnostic_shims()
53 {
54         shims_ = diagnostic_init_shims(shims_logger, shims_send, NULL);
55         DEBUG(binder_interface, "init_diagnostic_shims: Shims initialized");
56 }
57
58 void diagnostic_manager_t::reset()
59 {
60         if(initialized_)
61         {
62                 DEBUG(binder_interface, "Clearing existing diagnostic requests");
63                 cleanup_active_requests(true);
64         }
65
66         for(int i = 0; i < MAX_SIMULTANEOUS_DIAG_REQUESTS; i++)
67                 free_request_entries_.push_back(request_list_entries_[i]);
68 }
69
70
71 void diagnostic_manager_t::find_and_erase(active_diagnostic_request_t* entry, std::vector<active_diagnostic_request_t*>& requests_list)
72 {
73         auto i = std::find(requests_list.begin(), requests_list.end(), entry);
74         if ( i != requests_list.end())
75                 requests_list.erase(i);
76 }
77
78 /// Move the entry to the free list and decrement the lock count for any
79 /// CAN filters it used.
80 void diagnostic_manager_t::cancel_request(active_diagnostic_request_t* entry)
81 {
82         free_request_entries_.push_back(entry);
83         /* TODO: implement acceptance filters.
84         if(entry.arbitration_id_ == OBD2_FUNCTIONAL_BROADCAST_ID) {
85                 for(uint32_t filter = OBD2_FUNCTIONAL_RESPONSE_START;
86                                 filter < OBD2_FUNCTIONAL_RESPONSE_START +
87                                         OBD2_FUNCTIONAL_RESPONSE_COUNT;
88                                 filter++) {
89                         removeAcceptanceFilter(entry.bus_, filter,
90                                         CanMessageFormat::STANDARD, getCanBuses(),
91                                         getCanBusCount());
92                 }
93         } else {
94                 removeAcceptanceFilter(entry.bus_,
95                                 entry.arbitration_id_ +
96                                         DIAGNOSTIC_RESPONSE_ARBITRATION_ID_OFFSET,
97                                 CanMessageFormat::STANDARD, getCanBuses(), getCanBusCount());
98         }*/
99 }
100
101 void diagnostic_manager_t::cleanup_request(active_diagnostic_request_t* entry, bool force)
102 {
103         if(force || (entry->get_in_flight() && entry->request_completed()))
104         {
105                 entry->set_in_flight(false);
106
107                 char request_string[128] = {0};
108                 diagnostic_request_to_string(&entry->get_handle()->request,
109                         request_string, sizeof(request_string));
110                 if(entry->get_recurring())
111                 {
112                         find_and_erase(entry, recurring_requests_);
113                         if(force)
114                                 cancel_request(entry);
115                         else
116                         {
117                                 DEBUG(binder_interface, "Moving completed recurring request to the back of the queue: %s", request_string);
118                                 recurring_requests_.push_back(entry);
119                         }
120                 }
121                 else
122                 {
123                         DEBUG(binder_interface, "Cancelling completed, non-recurring request: %s", request_string);
124                         find_and_erase(entry, non_recurring_requests_);
125                         cancel_request(entry);
126                 }
127         }
128 }
129
130 /// @brief Clean up the request list, move as many to the free list as possible
131 void diagnostic_manager_t::cleanup_active_requests(bool force)
132 {
133         for(auto& entry : non_recurring_requests_)
134                 cleanup_request(entry, force);
135
136         for(auto& entry : recurring_requests_)
137                 cleanup_request(entry, force);
138 }
139
140 /// @brief Note that this pops it off of whichver list it was on and returns it, so make
141 /// sure to add it to some other list or it'll be lost.
142 active_diagnostic_request_t* diagnostic_manager_t::find_recurring_request(const DiagnosticRequest* request)
143 {
144         for (auto& entry : recurring_requests_)
145         {
146                 active_diagnostic_request_t* candidate = entry;
147                 if(diagnostic_request_equals(&candidate->get_handle()->request, request))
148                 {
149                         find_and_erase(entry, recurring_requests_);
150                         return entry;
151                         break;
152                 }
153         }
154         return nullptr;
155 }
156
157 std::shared_ptr<can_bus_dev_t> diagnostic_manager_t::get_can_bus_dev()
158 {
159         return bus_;
160 }
161
162 active_diagnostic_request_t* diagnostic_manager_t::get_free_entry()
163 {
164         if (request_list_entries_.empty())
165                 return nullptr;
166
167         active_diagnostic_request_t* adr = request_list_entries_.back();
168         request_list_entries_.pop_back();
169         return adr;
170 }
171
172 bool diagnostic_manager_t::add_request(DiagnosticRequest* request, const std::string name,
173         bool wait_for_multiple_responses, const DiagnosticResponseDecoder decoder,
174         const DiagnosticResponseCallback callback)
175 {
176         cleanup_active_requests(false);
177
178         bool added = true;
179         active_diagnostic_request_t* entry = get_free_entry();
180
181         if (entry != nullptr)
182         {
183                 // TODO: implement Acceptance Filter
184                 //      if(updateRequiredAcceptanceFilters(bus, request)) {
185                         entry = new active_diagnostic_request_t(bus_, request, name,
186                                         wait_for_multiple_responses, decoder, callback, 0);
187                         entry->set_handle(shims_, request);
188
189                         char request_string[128] = {0};
190                         diagnostic_request_to_string(&entry->get_handle()->request, request_string,
191                                         sizeof(request_string));
192
193                         find_and_erase(entry, non_recurring_requests_);
194                         DEBUG(binder_interface, "Added one-time diagnostic request on bus %s: %s",
195                                         bus_->get_device_name(), request_string);
196
197                         non_recurring_requests_.push_back(entry);
198         }
199         else
200         {
201                 WARNING(binder_interface, "There isn't enough request entry. Vector exhausted %d/%d", (int)request_list_entries_.size(), (int)request_list_entries_.max_size());
202                 added = false;
203         }
204         return added;
205 }
206
207 bool diagnostic_manager_t::validate_optional_request_attributes(float frequencyHz)
208 {
209         if(frequencyHz > MAX_RECURRING_DIAGNOSTIC_FREQUENCY_HZ) {
210                 DEBUG(binder_interface, "Requested recurring diagnostic frequency %d is higher than maximum of %d",
211                         frequencyHz, MAX_RECURRING_DIAGNOSTIC_FREQUENCY_HZ);
212                 return false;
213         }
214         return true;
215 }
216
217 bool diagnostic_manager_t::add_recurring_request(DiagnosticRequest* request, const char* name,
218                 bool wait_for_multiple_responses, const DiagnosticResponseDecoder decoder,
219                 const DiagnosticResponseCallback callback, float frequencyHz)
220 {
221         if(!validate_optional_request_attributes(frequencyHz))
222                 return false;
223
224         cleanup_active_requests(false);
225
226         bool added = true;
227         if(find_recurring_request(request) == nullptr)
228         {
229                 active_diagnostic_request_t* entry = get_free_entry();
230
231                 if(entry != nullptr)
232                 {
233                         // TODO: implement Acceptance Filter
234                         //if(updateRequiredAcceptanceFilters(bus, request)) {
235                                 entry = new active_diagnostic_request_t(bus_, request, name,
236                                                 wait_for_multiple_responses, decoder, callback, frequencyHz);
237                                 entry->set_handle(shims_, request);
238
239                                 char request_string[128] = {0};
240                                 diagnostic_request_to_string(&entry->get_handle()->request, request_string,
241                                                 sizeof(request_string));
242
243                                 find_and_erase(entry, recurring_requests_);
244                                 DEBUG(binder_interface, "Added recurring diagnostic request (freq: %f) on bus %d: %s",
245                                                 frequencyHz, bus_->get_device_name(), request_string);
246
247                                 recurring_requests_.push_back(entry);
248                 }
249                 else
250                 {
251                         WARNING(binder_interface, "There isn't enough request entry. Vector exhausted %d/%d", (int)request_list_entries_.size(), (int)request_list_entries_.max_size());
252                         added = false;
253                 }
254         }
255         else
256         {
257                 DEBUG(binder_interface, "Can't add request, one already exists with same key");
258                 added = false;
259         }
260         return added;
261 }
262
263 bool diagnostic_manager_t::is_diagnostic_response(const active_diagnostic_request_t& adr, const can_message_t& cm) const
264 {
265         if(cm.get_id() == adr.get_id() + DIAGNOSTIC_RESPONSE_ARBITRATION_ID_OFFSET)
266                 return true;
267         DEBUG(binder_interface, "Doesn't find an active diagnostic request that matches.");
268         return false;
269 }
270
271 active_diagnostic_request_t* diagnostic_manager_t::is_diagnostic_response(const can_message_t& can_message)
272 {
273         for (auto& entry : non_recurring_requests_)
274         {
275                 if(is_diagnostic_response(*entry, can_message))
276                         return entry;
277         }
278
279         for (auto& entry : recurring_requests_)
280         {
281                 if(is_diagnostic_response(*entry, can_message))
282                         return entry;
283         }
284         return nullptr;
285 }
286
287 openxc_VehicleMessage diagnostic_manager_t::relay_diagnostic_response(active_diagnostic_request_t* adr, const DiagnosticResponse& response) const
288 {
289         openxc_VehicleMessage message;
290         float value = (float)diagnostic_payload_to_integer(&response);
291         if(adr->get_decoder() != nullptr)
292         {
293                 value = adr->get_decoder()(&response, value);
294         }
295
296         if((response.success && strnlen(adr->get_name().c_str(), adr->get_name().size())) > 0)
297         {
298                 // If name, include 'value' instead of payload, and leave of response
299                 // details.
300                 message = build_VehicleMessage(build_SimpleMessage(adr->get_name(), build_DynamicField(value)));
301         }
302         else
303         {
304                 // If no name, send full details of response but still include 'value'
305                 // instead of 'payload' if they provided a decoder. The one case you
306                 // can't get is the full detailed response with 'value'. We could add
307                 // another parameter for that but it's onerous to carry that around.
308                 message = build_VehicleMessage(adr, response, value);
309         }
310
311         if(adr->get_callback() != nullptr)
312         {
313                 adr->get_callback()(adr, &response, value);
314         }
315
316         return message;
317 }
318
319 bool diagnostic_manager_t::conflicting(active_diagnostic_request_t* request, active_diagnostic_request_t* candidate) const
320 {
321         return (candidate->get_in_flight() && candidate != request &&
322                         candidate->get_can_bus_dev() == request->get_can_bus_dev() &&
323                         candidate->get_id() == request->get_id());
324 }
325
326
327 /// @brief Returns true if there are no other active requests to the same arbitration ID.
328 bool diagnostic_manager_t::clear_to_send(active_diagnostic_request_t* request) const
329 {
330         for ( auto entry : non_recurring_requests_)
331         {
332                 if(conflicting(request, entry))
333                         return false;
334         }
335
336         for ( auto entry : recurring_requests_)
337         {
338                 if(conflicting(request, entry))
339                         return false;
340         }
341         return true;
342 }
343
344 int diagnostic_manager_t::send_request(sd_event_source *s, uint64_t usec, void *userdata)
345 {
346         diagnostic_manager_t& dm = configuration_t::instance().get_diagnostic_manager();
347         DiagnosticRequest* request = (DiagnosticRequest*)userdata;
348         active_diagnostic_request_t* adr = dm.find_recurring_request(request);
349
350         if(adr != nullptr && adr->get_can_bus_dev() == dm.get_can_bus_dev() && adr->should_send() &&
351                 dm.clear_to_send(adr))
352         {
353                 DEBUG(binder_interface, "Got active_diagnostic_request from recurring_requests_ queue.");
354                 adr->get_frequency_clock().tick();
355                 start_diagnostic_request(&dm.get_shims(), adr->get_handle());
356                 if(adr->get_handle()->completed && !adr->get_handle()->success)
357                 {
358                         DEBUG(binder_interface, "Fatal error sending diagnostic request");
359                         return 0;
360                 }
361                 adr->get_timeout_clock().tick();
362                 adr->set_in_flight(true);
363                 return 1;
364         }
365         return -1;
366 }
367
368 DiagnosticShims& diagnostic_manager_t::get_shims()
369 {
370         return shims_;
371 }
372
373 bool diagnostic_manager_t::shims_send(const uint32_t arbitration_id, const uint8_t* data, const uint8_t size)
374 {
375         std::shared_ptr<can_bus_dev_t> can_bus_dev = configuration_t::instance().get_diagnostic_manager().get_can_bus_dev();
376         return can_bus_dev->shims_send(arbitration_id, data, size);
377 }
378
379 void diagnostic_manager_t::shims_logger(const char* m, ...)
380 {
381         DEBUG(binder_interface, "%s", m);
382 }
383
384 void diagnostic_manager_t::shims_timer()
385 {}
386