Fix: Initialization and entries flow
[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, new active_diagnostic_request_t()), 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(uint8_t i = 0; i < MAX_REQUEST_ENTRIES; i++)
67         {
68                 free_request_entries_.push_back(request_list_entries_.back());
69                 request_list_entries_.pop_back();
70         }
71 }
72
73
74 void diagnostic_manager_t::find_and_erase(active_diagnostic_request_t* entry, std::vector<active_diagnostic_request_t*>& requests_list)
75 {
76         auto i = std::find(requests_list.begin(), requests_list.end(), entry);
77         if ( i != requests_list.end())
78                 requests_list.erase(i);
79 }
80
81 /// Move the entry to the free list and decrement the lock count for any
82 /// CAN filters it used.
83 void diagnostic_manager_t::cancel_request(active_diagnostic_request_t* entry)
84 {
85         free_request_entries_.push_back(entry);
86         /* TODO: implement acceptance filters.
87         if(entry.arbitration_id_ == OBD2_FUNCTIONAL_BROADCAST_ID) {
88                 for(uint32_t filter = OBD2_FUNCTIONAL_RESPONSE_START;
89                                 filter < OBD2_FUNCTIONAL_RESPONSE_START +
90                                         OBD2_FUNCTIONAL_RESPONSE_COUNT;
91                                 filter++) {
92                         removeAcceptanceFilter(entry.bus_, filter,
93                                         CanMessageFormat::STANDARD, getCanBuses(),
94                                         getCanBusCount());
95                 }
96         } else {
97                 removeAcceptanceFilter(entry.bus_,
98                                 entry.arbitration_id_ +
99                                         DIAGNOSTIC_RESPONSE_ARBITRATION_ID_OFFSET,
100                                 CanMessageFormat::STANDARD, getCanBuses(), getCanBusCount());
101         }*/
102 }
103
104 void diagnostic_manager_t::cleanup_request(active_diagnostic_request_t* entry, bool force)
105 {
106         if(force || (entry->get_in_flight() && entry->request_completed()))
107         {
108                 entry->set_in_flight(false);
109
110                 char request_string[128] = {0};
111                 diagnostic_request_to_string(&entry->get_handle()->request,
112                         request_string, sizeof(request_string));
113                 if(entry->get_recurring())
114                 {
115                         find_and_erase(entry, recurring_requests_);
116                         if(force)
117                                 cancel_request(entry);
118                         else
119                         {
120                                 DEBUG(binder_interface, "Moving completed recurring request to the back of the queue: %s", request_string);
121                                 recurring_requests_.push_back(entry);
122                         }
123                 }
124                 else
125                 {
126                         DEBUG(binder_interface, "Cancelling completed, non-recurring request: %s", request_string);
127                         find_and_erase(entry, non_recurring_requests_);
128                         cancel_request(entry);
129                 }
130         }
131 }
132
133 /// @brief Clean up the request list, move as many to the free list as possible
134 void diagnostic_manager_t::cleanup_active_requests(bool force)
135 {
136         for(auto& entry : non_recurring_requests_)
137                 cleanup_request(entry, force);
138
139         for(auto& entry : recurring_requests_)
140                 cleanup_request(entry, force);
141 }
142
143 /// @brief Note that this pops it off of whichver list it was on and returns it, so make
144 /// sure to add it to some other list or it'll be lost.
145 active_diagnostic_request_t* diagnostic_manager_t::find_recurring_request(const DiagnosticRequest* request)
146 {
147         for (auto& entry : recurring_requests_)
148         {
149                 active_diagnostic_request_t* candidate = entry;
150                 if(diagnostic_request_equals(&candidate->get_handle()->request, request))
151                 {
152                         find_and_erase(entry, recurring_requests_);
153                         return entry;
154                         break;
155                 }
156         }
157         return nullptr;
158 }
159
160 std::shared_ptr<can_bus_dev_t> diagnostic_manager_t::get_can_bus_dev()
161 {
162         return bus_;
163 }
164
165 active_diagnostic_request_t* diagnostic_manager_t::get_free_entry()
166 {
167         if (free_request_entries_.empty())
168                 return nullptr;
169
170         active_diagnostic_request_t* adr = free_request_entries_.back();
171         free_request_entries_.pop_back();
172         return adr;
173 }
174
175 bool diagnostic_manager_t::add_request(DiagnosticRequest* request, const std::string name,
176         bool wait_for_multiple_responses, const DiagnosticResponseDecoder decoder,
177         const DiagnosticResponseCallback callback)
178 {
179         cleanup_active_requests(false);
180
181         bool added = true;
182         active_diagnostic_request_t* entry = get_free_entry();
183
184         if (entry != nullptr)
185         {
186                 // TODO: implement Acceptance Filter
187                 //      if(updateRequiredAcceptanceFilters(bus, request)) {
188                         entry = new active_diagnostic_request_t(bus_, request, name,
189                                         wait_for_multiple_responses, decoder, callback, 0);
190                         entry->set_handle(shims_, request);
191
192                         char request_string[128] = {0};
193                         diagnostic_request_to_string(&entry->get_handle()->request, request_string,
194                                         sizeof(request_string));
195
196                         find_and_erase(entry, non_recurring_requests_);
197                         DEBUG(binder_interface, "Added one-time diagnostic request on bus %s: %s",
198                                         bus_->get_device_name(), request_string);
199
200                         non_recurring_requests_.push_back(entry);
201         }
202         else
203         {
204                 WARNING(binder_interface, "There isn't enough request entry. Vector exhausted %d/%d", (int)request_list_entries_.size(), (int)request_list_entries_.max_size());
205                 added = false;
206         }
207         return added;
208 }
209
210 bool diagnostic_manager_t::validate_optional_request_attributes(float frequencyHz)
211 {
212         if(frequencyHz > MAX_RECURRING_DIAGNOSTIC_FREQUENCY_HZ) {
213                 DEBUG(binder_interface, "Requested recurring diagnostic frequency %d is higher than maximum of %d",
214                         frequencyHz, MAX_RECURRING_DIAGNOSTIC_FREQUENCY_HZ);
215                 return false;
216         }
217         return true;
218 }
219
220 bool diagnostic_manager_t::add_recurring_request(DiagnosticRequest* request, const char* name,
221                 bool wait_for_multiple_responses, const DiagnosticResponseDecoder decoder,
222                 const DiagnosticResponseCallback callback, float frequencyHz)
223 {
224         if(!validate_optional_request_attributes(frequencyHz))
225                 return false;
226
227         cleanup_active_requests(false);
228
229         bool added = true;
230         if(find_recurring_request(request) == nullptr)
231         {
232                 active_diagnostic_request_t* entry = get_free_entry();
233
234                 if(entry != nullptr)
235                 {
236                         // TODO: implement Acceptance Filter
237                         //if(updateRequiredAcceptanceFilters(bus, request)) {
238                                 entry = new active_diagnostic_request_t(bus_, request, name,
239                                                 wait_for_multiple_responses, decoder, callback, frequencyHz);
240                                 entry->set_handle(shims_, request);
241
242                                 char request_string[128] = {0};
243                                 diagnostic_request_to_string(&entry->get_handle()->request, request_string,
244                                                 sizeof(request_string));
245
246                                 find_and_erase(entry, recurring_requests_);
247                                 DEBUG(binder_interface, "Added recurring diagnostic request (freq: %f) on bus %s: %s",
248                                                 frequencyHz, bus_->get_device_name().c_str(), request_string);
249
250                                 recurring_requests_.push_back(entry);
251                 }
252                 else
253                 {
254                         WARNING(binder_interface, "There isn't enough request entry. Vector exhausted %d/%d", (int)request_list_entries_.size(), (int)request_list_entries_.max_size());
255                         added = false;
256                 }
257         }
258         else
259         {
260                 DEBUG(binder_interface, "Can't add request, one already exists with same key");
261                 added = false;
262         }
263         return added;
264 }
265
266 bool diagnostic_manager_t::is_diagnostic_response(const active_diagnostic_request_t& adr, const can_message_t& cm) const
267 {
268         if(cm.get_id() == adr.get_id() + DIAGNOSTIC_RESPONSE_ARBITRATION_ID_OFFSET)
269                 return true;
270         DEBUG(binder_interface, "Doesn't find an active diagnostic request that matches.");
271         return false;
272 }
273
274 active_diagnostic_request_t* diagnostic_manager_t::is_diagnostic_response(const can_message_t& can_message)
275 {
276         for (auto& entry : non_recurring_requests_)
277         {
278                 if(is_diagnostic_response(*entry, can_message))
279                         return entry;
280         }
281
282         for (auto& entry : recurring_requests_)
283         {
284                 if(is_diagnostic_response(*entry, can_message))
285                         return entry;
286         }
287         return nullptr;
288 }
289
290 openxc_VehicleMessage diagnostic_manager_t::relay_diagnostic_response(active_diagnostic_request_t* adr, const DiagnosticResponse& response) const
291 {
292         openxc_VehicleMessage message;
293         float value = (float)diagnostic_payload_to_integer(&response);
294         if(adr->get_decoder() != nullptr)
295         {
296                 value = adr->get_decoder()(&response, value);
297         }
298
299         if((response.success && strnlen(adr->get_name().c_str(), adr->get_name().size())) > 0)
300         {
301                 // If name, include 'value' instead of payload, and leave of response
302                 // details.
303                 message = build_VehicleMessage(build_SimpleMessage(adr->get_name(), build_DynamicField(value)));
304         }
305         else
306         {
307                 // If no name, send full details of response but still include 'value'
308                 // instead of 'payload' if they provided a decoder. The one case you
309                 // can't get is the full detailed response with 'value'. We could add
310                 // another parameter for that but it's onerous to carry that around.
311                 message = build_VehicleMessage(adr, response, value);
312         }
313
314         if(adr->get_callback() != nullptr)
315         {
316                 adr->get_callback()(adr, &response, value);
317         }
318
319         return message;
320 }
321
322 bool diagnostic_manager_t::conflicting(active_diagnostic_request_t* request, active_diagnostic_request_t* candidate) const
323 {
324         return (candidate->get_in_flight() && candidate != request &&
325                         candidate->get_can_bus_dev() == request->get_can_bus_dev() &&
326                         candidate->get_id() == request->get_id());
327 }
328
329
330 /// @brief Returns true if there are no other active requests to the same arbitration ID.
331 bool diagnostic_manager_t::clear_to_send(active_diagnostic_request_t* request) const
332 {
333         for ( auto entry : non_recurring_requests_)
334         {
335                 if(conflicting(request, entry))
336                         return false;
337         }
338
339         for ( auto entry : recurring_requests_)
340         {
341                 if(conflicting(request, entry))
342                         return false;
343         }
344         return true;
345 }
346
347 int diagnostic_manager_t::send_request(sd_event_source *s, uint64_t usec, void *userdata)
348 {
349         diagnostic_manager_t& dm = configuration_t::instance().get_diagnostic_manager();
350         DiagnosticRequest* request = (DiagnosticRequest*)userdata;
351         active_diagnostic_request_t* adr = dm.find_recurring_request(request);
352
353         if(adr != nullptr && adr->get_can_bus_dev() == dm.get_can_bus_dev() && adr->should_send() &&
354                 dm.clear_to_send(adr))
355         {
356                 DEBUG(binder_interface, "Got active_diagnostic_request from recurring_requests_ queue.");
357                 adr->get_frequency_clock().tick();
358                 start_diagnostic_request(&dm.get_shims(), adr->get_handle());
359                 if(adr->get_handle()->completed && !adr->get_handle()->success)
360                 {
361                         DEBUG(binder_interface, "Fatal error sending diagnostic request");
362                         return 0;
363                 }
364                 adr->get_timeout_clock().tick();
365                 adr->set_in_flight(true);
366                 return 1;
367         }
368         return -1;
369 }
370
371 DiagnosticShims& diagnostic_manager_t::get_shims()
372 {
373         return shims_;
374 }
375
376 bool diagnostic_manager_t::shims_send(const uint32_t arbitration_id, const uint8_t* data, const uint8_t size)
377 {
378         std::shared_ptr<can_bus_dev_t> can_bus_dev = configuration_t::instance().get_diagnostic_manager().get_can_bus_dev();
379         return can_bus_dev->shims_send(arbitration_id, data, size);
380 }
381
382 void diagnostic_manager_t::shims_logger(const char* m, ...)
383 {
384         DEBUG(binder_interface, "%s", m);
385 }
386
387 void diagnostic_manager_t::shims_timer()
388 {}
389