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