Implemente way to send diagnostic request when subscribed.
[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 "../configuration.hpp"
24
25 #define MAX_RECURRING_DIAGNOSTIC_FREQUENCY_HZ 10
26 #define MAX_SIMULTANEOUS_DIAG_REQUESTS 50
27 #define MAX_REQUEST_ENTRIES 50
28
29 diagnostic_manager_t::diagnostic_manager_t()
30         : request_list_entries_(MAX_REQUEST_ENTRIES), initialized_{false}
31 {}
32
33 bool diagnostic_manager_t::initialize(std::shared_ptr<can_bus_dev_t> cbd)
34 {
35         // Mandatory to set the bus before intiliaze shims.
36         bus_ = cbd;
37
38         init_diagnostic_shims();
39         reset();
40
41         initialized_ = true;
42         DEBUG(binder_interface, "initialize: Diagnostic Manager initialized");
43         return initialized_;
44 }
45
46 /**
47  * @brief initialize shims used by UDS lib and set initialized_ to true.
48  *  It is needed before used the diagnostic manager fully because shims are
49  *  required by most member functions.
50  */
51 void diagnostic_manager_t::init_diagnostic_shims()
52 {
53         shims_ = diagnostic_init_shims(shims_logger, shims_send, NULL);
54         DEBUG(binder_interface, "init_diagnostic_shims: Shims initialized");
55 }
56
57 void diagnostic_manager_t::reset()
58 {
59         if(initialized_)
60         {
61                 DEBUG(binder_interface, "Clearing existing diagnostic requests");
62                 cleanup_active_requests(true);
63         }
64
65         for(int i = 0; i < MAX_SIMULTANEOUS_DIAG_REQUESTS; i++)
66                 free_request_entries_.push_back(request_list_entries_[i]);
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         free_request_entries_.push_back(entry);
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                         else
115                         {
116                                 DEBUG(binder_interface, "Moving completed recurring request to the back of the queue: %s", request_string);
117                                 recurring_requests_.push_back(entry);
118                         }
119                 }
120                 else
121                 {
122                         DEBUG(binder_interface, "Cancelling completed, non-recurring request: %s", request_string);
123                         find_and_erase(entry, non_recurring_requests_);
124                         cancel_request(entry);
125                 }
126         }
127 }
128
129 /// @brief Clean up the request list, move as many to the free list as possible
130 void diagnostic_manager_t::cleanup_active_requests(bool force)
131 {
132         for(auto& entry : non_recurring_requests_)
133                 cleanup_request(entry, force);
134
135         for(auto& entry : recurring_requests_)
136                 cleanup_request(entry, force);
137 }
138
139 /// @brief Note that this pops it off of whichver list it was on and returns it, so make
140 /// sure to add it to some other list or it'll be lost.
141 bool diagnostic_manager_t::lookup_recurring_request(const DiagnosticRequest* request)
142 {
143         active_diagnostic_request_t existingEntry;
144         for (auto& entry : recurring_requests_)
145         {
146                 active_diagnostic_request_t* candidate = entry;
147                 if(candidate->get_can_bus_dev()->get_device_name() == bus_->get_device_name() &&
148                         diagnostic_request_equals(&candidate->get_handle()->request, request))
149                 {
150                         find_and_erase(entry, recurring_requests_);
151                         return true;
152                         break;
153                 }
154         }
155         return false;
156 }
157
158 std::shared_ptr<can_bus_dev_t> diagnostic_manager_t::get_can_bus_dev()
159 {
160         return bus_;
161 }
162
163 active_diagnostic_request_t* diagnostic_manager_t::get_free_entry()
164 {
165         if (request_list_entries_.empty())
166                 return nullptr;
167
168         active_diagnostic_request_t* adr = request_list_entries_.back();
169         request_list_entries_.pop_back();
170         return adr;
171 }
172
173 bool diagnostic_manager_t::add_request(DiagnosticRequest* request, const std::string name,
174         bool wait_for_multiple_responses, const DiagnosticResponseDecoder decoder,
175         const DiagnosticResponseCallback callback)
176 {
177         cleanup_active_requests(false);
178
179         bool added = true;
180         active_diagnostic_request_t* entry = get_free_entry();
181
182         if (entry != nullptr)
183         {
184                 // TODO: implement Acceptance Filter
185                 //      if(updateRequiredAcceptanceFilters(bus, request)) {
186                         entry = new active_diagnostic_request_t(bus_, request, name,
187                                         wait_for_multiple_responses, decoder, callback, 0);
188                         entry->set_handle(shims_, request);
189
190                         char request_string[128] = {0};
191                         diagnostic_request_to_string(&entry->get_handle()->request, request_string,
192                                         sizeof(request_string));
193
194                         find_and_erase(entry, non_recurring_requests_);
195                         DEBUG(binder_interface, "Added one-time diagnostic request on bus %s: %s",
196                                         bus_->get_device_name(), request_string);
197
198                         non_recurring_requests_.push_back(entry);
199         }
200         else
201         {
202                 WARNING(binder_interface, "There isn't enough request entry. Vector exhausted %d/%d", (int)request_list_entries_.size(), (int)request_list_entries_.max_size());
203                 added = false;
204         }
205         return added;
206 }
207
208 bool diagnostic_manager_t::validate_optional_request_attributes(float frequencyHz)
209 {
210         if(frequencyHz > MAX_RECURRING_DIAGNOSTIC_FREQUENCY_HZ) {
211                 DEBUG(binder_interface, "Requested recurring diagnostic frequency %d is higher than maximum of %d",
212                         frequencyHz, MAX_RECURRING_DIAGNOSTIC_FREQUENCY_HZ);
213                 return false;
214         }
215         return true;
216 }
217
218 bool diagnostic_manager_t::add_recurring_request(DiagnosticRequest* request, const char* name,
219                 bool wait_for_multiple_responses, const DiagnosticResponseDecoder decoder,
220                 const DiagnosticResponseCallback callback, float frequencyHz)
221 {
222         if(!validate_optional_request_attributes(frequencyHz))
223                 return false;
224
225         cleanup_active_requests(false);
226
227         bool added = true;
228         if(lookup_recurring_request(request))
229         {
230                 active_diagnostic_request_t* entry = get_free_entry();
231
232                 if(entry != nullptr)
233                 {
234                         // TODO: implement Acceptance Filter
235                         //if(updateRequiredAcceptanceFilters(bus, request)) {
236                                 entry = new active_diagnostic_request_t(bus_, request, name,
237                                                 wait_for_multiple_responses, decoder, callback, frequencyHz);
238                                 entry->set_handle(shims_, request);
239
240                                 char request_string[128] = {0};
241                                 diagnostic_request_to_string(&entry->get_handle()->request, request_string,
242                                                 sizeof(request_string));
243
244                                 find_and_erase(entry, recurring_requests_);
245                                 DEBUG(binder_interface, "Added recurring diagnostic request (freq: %f) on bus %d: %s",
246                                                 frequencyHz, bus_->get_device_name(), request_string);
247
248                                 recurring_requests_.push_back(entry);
249                 }
250                 else
251                 {
252                         WARNING(binder_interface, "There isn't enough request entry. Vector exhausted %d/%d", (int)request_list_entries_.size(), (int)request_list_entries_.max_size());
253                         added = false;
254                 }
255         }
256         else
257         {
258                 DEBUG(binder_interface, "Can't add request, one already exists with same key");
259                 added = false;
260         }
261         return added;
262 }
263
264 bool diagnostic_manager_t::conflicting(active_diagnostic_request_t* request, active_diagnostic_request_t* candidate) const
265 {
266         return (candidate->get_in_flight() && candidate != request &&
267                         candidate->get_can_bus_dev() == request->get_can_bus_dev() &&
268                         candidate->get_id() == request->get_id());
269 }
270
271
272 /// @brief Returns true if there are no other active requests to the same arbitration ID.
273 bool diagnostic_manager_t::clear_to_send(active_diagnostic_request_t* request) const
274 {
275         for ( auto entry : non_recurring_requests_)
276         {
277                 if(conflicting(request, entry))
278                         return false;
279         }
280
281         for ( auto entry : recurring_requests_)
282         {
283                 if(conflicting(request, entry))
284                         return false;
285         }
286         return true;
287 }
288
289 int diagnostic_manager_t::send_request(sd_event_source *s, uint64_t usec, void *userdata)
290 {
291         diagnostic_manager_t& dm = configuration_t::instance().get_diagnostic_manager();
292         DiagnosticRequest* request = (DiagnosticRequest*)userdata;
293         active_diagnostic_request_t* adr = dm.lookup_recurring_request(request);
294
295         if(adr != nullptr && adr->get_can_bus_dev() == dm.get_can_bus_dev() && adr->should_send() &&
296                 dm.clear_to_send(adr))
297         {
298                 DEBUG(binder_interface, "Got active_diagnostic_request from recurring_requests_ queue.");
299                 adr->get_frequency_clock().tick();
300                 start_diagnostic_request(&dm.get_shims(), adr->get_handle());
301                 if(adr->get_handle()->completed && !adr->get_handle()->success)
302                 {
303                         DEBUG(binder_interface, "Fatal error sending diagnostic request");
304                         return 0;
305                 }
306                 adr->get_timeout_clock().tick();
307                 adr->set_in_flight(true);
308                 return 1;
309         }
310         return -1;
311 }
312
313 DiagnosticShims& diagnostic_manager_t::get_shims()
314 {
315         return shims_;
316 }
317
318 bool diagnostic_manager_t::shims_send(const uint32_t arbitration_id, const uint8_t* data, const uint8_t size)
319 {
320         std::shared_ptr<can_bus_dev_t> can_bus_dev = configuration_t::instance().get_diagnostic_manager().get_can_bus_dev();
321         return can_bus_dev->shims_send(arbitration_id, data, size);
322 }
323
324 void diagnostic_manager_t::shims_logger(const char* m, ...)
325 {
326         DEBUG(binder_interface, "%s", m);
327 }
328
329 void diagnostic_manager_t::shims_timer()
330 {}
331