Change the way to check signal type making prefix_
[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 active_diagnostic_request_t* diagnostic_manager_t::find_recurring_request(const DiagnosticRequest* request)
142 {
143         for (auto& entry : recurring_requests_)
144         {
145                 active_diagnostic_request_t* candidate = entry;
146                 if(diagnostic_request_equals(&candidate->get_handle()->request, request))
147                 {
148                         find_and_erase(entry, recurring_requests_);
149                         return entry;
150                         break;
151                 }
152         }
153         return nullptr;
154 }
155
156 std::shared_ptr<can_bus_dev_t> diagnostic_manager_t::get_can_bus_dev()
157 {
158         return bus_;
159 }
160
161 active_diagnostic_request_t* diagnostic_manager_t::get_free_entry()
162 {
163         if (request_list_entries_.empty())
164                 return nullptr;
165
166         active_diagnostic_request_t* adr = request_list_entries_.back();
167         request_list_entries_.pop_back();
168         return adr;
169 }
170
171 bool diagnostic_manager_t::add_request(DiagnosticRequest* request, const std::string name,
172         bool wait_for_multiple_responses, const DiagnosticResponseDecoder decoder,
173         const DiagnosticResponseCallback callback)
174 {
175         cleanup_active_requests(false);
176
177         bool added = true;
178         active_diagnostic_request_t* entry = get_free_entry();
179
180         if (entry != nullptr)
181         {
182                 // TODO: implement Acceptance Filter
183                 //      if(updateRequiredAcceptanceFilters(bus, request)) {
184                         entry = new active_diagnostic_request_t(bus_, request, name,
185                                         wait_for_multiple_responses, decoder, callback, 0);
186                         entry->set_handle(shims_, request);
187
188                         char request_string[128] = {0};
189                         diagnostic_request_to_string(&entry->get_handle()->request, request_string,
190                                         sizeof(request_string));
191
192                         find_and_erase(entry, non_recurring_requests_);
193                         DEBUG(binder_interface, "Added one-time diagnostic request on bus %s: %s",
194                                         bus_->get_device_name(), request_string);
195
196                         non_recurring_requests_.push_back(entry);
197         }
198         else
199         {
200                 WARNING(binder_interface, "There isn't enough request entry. Vector exhausted %d/%d", (int)request_list_entries_.size(), (int)request_list_entries_.max_size());
201                 added = false;
202         }
203         return added;
204 }
205
206 bool diagnostic_manager_t::validate_optional_request_attributes(float frequencyHz)
207 {
208         if(frequencyHz > MAX_RECURRING_DIAGNOSTIC_FREQUENCY_HZ) {
209                 DEBUG(binder_interface, "Requested recurring diagnostic frequency %d is higher than maximum of %d",
210                         frequencyHz, MAX_RECURRING_DIAGNOSTIC_FREQUENCY_HZ);
211                 return false;
212         }
213         return true;
214 }
215
216 bool diagnostic_manager_t::add_recurring_request(DiagnosticRequest* request, const char* name,
217                 bool wait_for_multiple_responses, const DiagnosticResponseDecoder decoder,
218                 const DiagnosticResponseCallback callback, float frequencyHz)
219 {
220         if(!validate_optional_request_attributes(frequencyHz))
221                 return false;
222
223         cleanup_active_requests(false);
224
225         bool added = true;
226         if(find_recurring_request(request) == nullptr)
227         {
228                 active_diagnostic_request_t* entry = get_free_entry();
229
230                 if(entry != nullptr)
231                 {
232                         // TODO: implement Acceptance Filter
233                         //if(updateRequiredAcceptanceFilters(bus, request)) {
234                                 entry = new active_diagnostic_request_t(bus_, request, name,
235                                                 wait_for_multiple_responses, decoder, callback, frequencyHz);
236                                 entry->set_handle(shims_, request);
237
238                                 char request_string[128] = {0};
239                                 diagnostic_request_to_string(&entry->get_handle()->request, request_string,
240                                                 sizeof(request_string));
241
242                                 find_and_erase(entry, recurring_requests_);
243                                 DEBUG(binder_interface, "Added recurring diagnostic request (freq: %f) on bus %d: %s",
244                                                 frequencyHz, bus_->get_device_name(), request_string);
245
246                                 recurring_requests_.push_back(entry);
247                 }
248                 else
249                 {
250                         WARNING(binder_interface, "There isn't enough request entry. Vector exhausted %d/%d", (int)request_list_entries_.size(), (int)request_list_entries_.max_size());
251                         added = false;
252                 }
253         }
254         else
255         {
256                 DEBUG(binder_interface, "Can't add request, one already exists with same key");
257                 added = false;
258         }
259         return added;
260 }
261
262 bool diagnostic_manager_t::conflicting(active_diagnostic_request_t* request, active_diagnostic_request_t* candidate) const
263 {
264         return (candidate->get_in_flight() && candidate != request &&
265                         candidate->get_can_bus_dev() == request->get_can_bus_dev() &&
266                         candidate->get_id() == request->get_id());
267 }
268
269
270 /// @brief Returns true if there are no other active requests to the same arbitration ID.
271 bool diagnostic_manager_t::clear_to_send(active_diagnostic_request_t* request) const
272 {
273         for ( auto entry : non_recurring_requests_)
274         {
275                 if(conflicting(request, entry))
276                         return false;
277         }
278
279         for ( auto entry : recurring_requests_)
280         {
281                 if(conflicting(request, entry))
282                         return false;
283         }
284         return true;
285 }
286
287 int diagnostic_manager_t::send_request(sd_event_source *s, uint64_t usec, void *userdata)
288 {
289         diagnostic_manager_t& dm = configuration_t::instance().get_diagnostic_manager();
290         DiagnosticRequest* request = (DiagnosticRequest*)userdata;
291         active_diagnostic_request_t* adr = dm.find_recurring_request(request);
292
293         if(adr != nullptr && adr->get_can_bus_dev() == dm.get_can_bus_dev() && adr->should_send() &&
294                 dm.clear_to_send(adr))
295         {
296                 DEBUG(binder_interface, "Got active_diagnostic_request from recurring_requests_ queue.");
297                 adr->get_frequency_clock().tick();
298                 start_diagnostic_request(&dm.get_shims(), adr->get_handle());
299                 if(adr->get_handle()->completed && !adr->get_handle()->success)
300                 {
301                         DEBUG(binder_interface, "Fatal error sending diagnostic request");
302                         return 0;
303                 }
304                 adr->get_timeout_clock().tick();
305                 adr->set_in_flight(true);
306                 return 1;
307         }
308         return -1;
309 }
310
311 DiagnosticShims& diagnostic_manager_t::get_shims()
312 {
313         return shims_;
314 }
315
316 bool diagnostic_manager_t::shims_send(const uint32_t arbitration_id, const uint8_t* data, const uint8_t size)
317 {
318         std::shared_ptr<can_bus_dev_t> can_bus_dev = configuration_t::instance().get_diagnostic_manager().get_can_bus_dev();
319         return can_bus_dev->shims_send(arbitration_id, data, size);
320 }
321
322 void diagnostic_manager_t::shims_logger(const char* m, ...)
323 {
324         DEBUG(binder_interface, "%s", m);
325 }
326
327 void diagnostic_manager_t::shims_timer()
328 {}
329