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