Keep raw pointer for now as we have to move them around vector.
[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         reset();
33 }
34
35 diagnostic_manager_t::diagnostic_manager_t(can_bus_dev_t& bus)
36         : bus_(&bus), request_list_entries_(MAX_REQUEST_ENTRIES), initialized_{false}
37 {
38         reset();
39 }
40
41 void diagnostic_manager_t::find_and_erase(active_diagnostic_request_t* entry, std::vector<active_diagnostic_request_t*>& requests_list)
42 {
43         auto i = std::find(requests_list.begin(), requests_list.end(), entry);
44         if ( i != requests_list.end())
45                 requests_list.erase(i);
46 }
47
48 /// Move the entry to the free list and decrement the lock count for any
49 /// CAN filters it used.
50 void diagnostic_manager_t::cancel_request(active_diagnostic_request_t* entry)
51 {
52         free_request_entries_.push_back(entry);
53         /* TODO: implement acceptance filters.
54         if(entry.arbitration_id_ == OBD2_FUNCTIONAL_BROADCAST_ID) {
55                 for(uint32_t filter = OBD2_FUNCTIONAL_RESPONSE_START;
56                                 filter < OBD2_FUNCTIONAL_RESPONSE_START +
57                                         OBD2_FUNCTIONAL_RESPONSE_COUNT;
58                                 filter++) {
59                         removeAcceptanceFilter(entry.bus_, filter,
60                                         CanMessageFormat::STANDARD, getCanBuses(),
61                                         getCanBusCount());
62                 }
63         } else {
64                 removeAcceptanceFilter(entry.bus_,
65                                 entry.arbitration_id_ +
66                                         DIAGNOSTIC_RESPONSE_ARBITRATION_ID_OFFSET,
67                                 CanMessageFormat::STANDARD, getCanBuses(), getCanBusCount());
68         }*/
69 }
70
71 void diagnostic_manager_t::cleanup_request(active_diagnostic_request_t* entry, bool force)
72 {
73         if(force || (entry->get_in_flight() && entry->request_completed()))
74         {
75                 entry->set_in_flight(false);
76
77                 char request_string[128] = {0};
78                 diagnostic_request_to_string(&entry->get_handle()->request,
79                         request_string, sizeof(request_string));
80                 if(entry->get_recurring())
81                 {
82                         find_and_erase(entry, recurring_requests_);
83                         if(force)
84                                 cancel_request(entry);
85                         else
86                         {
87                                 DEBUG(binder_interface, "Moving completed recurring request to the back of the queue: %s", request_string);
88                                 recurring_requests_.push_back(entry);
89                         }
90                 }
91                 else
92                 {
93                         DEBUG(binder_interface, "Cancelling completed, non-recurring request: %s", request_string);
94                         find_and_erase(entry, non_recurring_requests_);
95                         cancel_request(entry);
96                 }
97         }
98 }
99
100 /// @brief Clean up the request list, move as many to the free list as possible
101 void diagnostic_manager_t::cleanup_active_requests(bool force)
102 {
103         for(auto& entry : non_recurring_requests_)
104                 cleanup_request(entry, force);
105
106         for(auto& entry : recurring_requests_)
107                 cleanup_request(entry, force);
108 }
109
110 /// @brief Note that this pops it off of whichver list it was on and returns it, so make
111 /// sure to add it to some other list or it'll be lost.
112 bool diagnostic_manager_t::lookup_recurring_request(const DiagnosticRequest* request)
113 {
114         active_diagnostic_request_t existingEntry;
115         for (auto& entry : recurring_requests_)
116         {
117                 active_diagnostic_request_t* candidate = entry;
118                 if(candidate->get_can_bus_dev()->get_device_name() == bus_->get_device_name() &&
119                         diagnostic_request_equals(&candidate->get_handle()->request, request))
120                 {
121                         find_and_erase(entry, recurring_requests_);
122                         return true;
123                         break;
124                 }
125         }
126         return false;
127 }
128
129 void diagnostic_manager_t::reset()
130 {
131         if(initialized_)
132         {
133                 DEBUG(binder_interface, "Clearing existing diagnostic requests");
134                 cleanup_active_requests(true);
135         }
136
137         for(int i = 0; i < MAX_SIMULTANEOUS_DIAG_REQUESTS; i++)
138                 free_request_entries_.push_back(request_list_entries_[i]);
139 }
140
141 can_bus_dev_t* diagnostic_manager_t::get_can_bus_dev()
142 {
143         return bus_;
144 }
145
146 active_diagnostic_request_t* diagnostic_manager_t::get_free_entry()
147 {
148         if (request_list_entries_.empty())
149                 return nullptr;
150
151         active_diagnostic_request_t* adr = request_list_entries_.back();
152         request_list_entries_.pop_back();
153         return adr;
154 }
155
156 bool diagnostic_manager_t::add_request(DiagnosticRequest* request, const std::string name,
157         bool wait_for_multiple_responses, const DiagnosticResponseDecoder decoder,
158         const DiagnosticResponseCallback callback)
159 {
160         cleanup_active_requests(false);
161
162         bool added = true;
163         active_diagnostic_request_t* entry = get_free_entry();
164
165         if (entry != nullptr)
166         {
167                 // TODO: implement Acceptance Filter
168                 //      if(updateRequiredAcceptanceFilters(bus, request)) {
169                         entry = new active_diagnostic_request_t(bus_, request, name,
170                                         wait_for_multiple_responses, decoder, callback, 0);
171                         entry->set_handle(shims_, request);
172
173                         char request_string[128] = {0};
174                         diagnostic_request_to_string(&entry->get_handle()->request, request_string,
175                                         sizeof(request_string));
176
177                         find_and_erase(entry, non_recurring_requests_);
178                         DEBUG(binder_interface, "Added one-time diagnostic request on bus %s: %s",
179                                         bus_->get_device_name(), request_string);
180
181                         non_recurring_requests_.push_back(entry);
182         }
183         else
184         {
185                 WARNING(binder_interface, "There isn't enough request entry. Vector exhausted %d/%d", (int)request_list_entries_.size(), (int)request_list_entries_.max_size());
186                 added = false;
187         }
188         return added;
189 }
190
191 bool diagnostic_manager_t::validate_optional_request_attributes(float frequencyHz)
192 {
193         if(frequencyHz > MAX_RECURRING_DIAGNOSTIC_FREQUENCY_HZ) {
194                 DEBUG(binder_interface, "Requested recurring diagnostic frequency %d is higher than maximum of %d",
195                         frequencyHz, MAX_RECURRING_DIAGNOSTIC_FREQUENCY_HZ);
196                 return false;
197         }
198         return true;
199 }
200
201 bool diagnostic_manager_t::add_recurring_request(DiagnosticRequest* request, const char* name,
202                 bool wait_for_multiple_responses, const DiagnosticResponseDecoder decoder,
203                 const DiagnosticResponseCallback callback, float frequencyHz)
204 {
205         if(!validate_optional_request_attributes(frequencyHz))
206                 return false;
207
208         cleanup_active_requests(false);
209
210         bool added = true;
211         if(lookup_recurring_request(request))
212         {
213                 active_diagnostic_request_t* entry = get_free_entry();
214
215                 if(entry != nullptr)
216                 {
217                         // TODO: implement Acceptance Filter
218                         //if(updateRequiredAcceptanceFilters(bus, request)) {
219                                 entry = new active_diagnostic_request_t(bus_, request, name,
220                                                 wait_for_multiple_responses, decoder, callback, frequencyHz);
221                                 entry->set_handle(shims_, request);
222
223                                 char request_string[128] = {0};
224                                 diagnostic_request_to_string(&entry->get_handle()->request, request_string,
225                                                 sizeof(request_string));
226
227                                 find_and_erase(entry, recurring_requests_);
228                                 DEBUG(binder_interface, "Added recurring diagnostic request (freq: %f) on bus %d: %s",
229                                                 frequencyHz, bus_->get_device_name(), request_string);
230
231                                 recurring_requests_.push_back(entry);
232                 }
233                 else
234                 {
235                         WARNING(binder_interface, "There isn't enough request entry. Vector exhausted %d/%d", (int)request_list_entries_.size(), (int)request_list_entries_.max_size());
236                         added = false;
237                 }
238         }
239         else
240         {
241                 DEBUG(binder_interface, "Can't add request, one already exists with same key");
242                 added = false;
243         }
244         return added;
245 }
246
247 bool diagnostic_manager_t::shims_send(const uint32_t arbitration_id, const uint8_t* data, const uint8_t size)
248 {
249         can_bus_dev_t *can_bus_dev = config->get_diagnostic_manager().get_can_bus_dev();
250         return can_bus_dev->shims_send(arbitration_id, data, size);
251 }
252
253 void diagnostic_manager_t::shims_logger(const char* m, ...)
254 {
255         DEBUG(binder_interface, "%s", m);
256 }
257
258 void diagnostic_manager_t::shims_timer()
259 {}
260
261 /**
262  * @brief initialize shims used by UDS lib and set initialized_ to true.
263  *  It is needed before used the diagnostic manager fully because shims are
264  *  required by most member functions.
265  */
266 void diagnostic_manager_t::init_diagnostic_shims()
267 {
268         shims_ = diagnostic_init_shims(shims_logger, shims_send, NULL);
269         initialized_ = true;
270 }