binding: add preinit function to load the config
[apps/agl-service-can-low-level.git] / low-can-binding / 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 #include <string.h>
21
22 #include "diagnostic-manager.hpp"
23
24 #include "../utils/openxc-utils.hpp"
25 #include "../utils/signals.hpp"
26 #include "../binding/application.hpp"
27
28 #define MAX_RECURRING_DIAGNOSTIC_FREQUENCY_HZ 10
29 #define MAX_SIMULTANEOUS_DIAG_REQUESTS 50
30 // There are only 8 slots of in flight diagnostic requests
31 #define MAX_SIMULTANEOUS_IN_FLIGHT_REQUESTS 8
32 #define TIMERFD_ACCURACY 0
33 #define MICRO 1000000
34
35 diagnostic_manager_t::diagnostic_manager_t()
36         : initialized_{false}
37 {}
38
39
40 diagnostic_manager_t::~diagnostic_manager_t()
41 {
42         for(auto r: recurring_requests_)
43         {
44                 delete(r);
45         }
46         for(auto r: non_recurring_requests_)
47         {
48                 delete(r);
49         }
50 }
51
52 /// @brief Diagnostic manager is not initialized at launch but after
53 ///  the initialization of CAN bus devices. For the moment, it is only possible
54 ///  to have 1 diagnostic bus which are the first bus declared in the JSON
55 ///  description file. Configuration instance will return it.
56 ///
57 /// this will initialize DiagnosticShims and cancel all active requests
58 ///  if there are any.
59 bool diagnostic_manager_t::initialize(std::string diagnostic_bus)
60 {
61         if (! diagnostic_bus.empty())
62         {
63                 bus_ = diagnostic_bus;
64                 init_diagnostic_shims();
65                 reset();
66
67                 AFB_DEBUG("Diagnostic Manager initialized");
68                 initialized_ = true;
69                 return initialized_;
70         }
71         AFB_ERROR("Diagnostic Manager missing its bus name in the config");
72         return initialized_;
73 }
74
75 /// @brief initialize shims used by UDS lib and set initialized_ to true.
76 ///  It is needed before used the diagnostic manager fully because shims are
77 ///  required by most member functions.
78 void diagnostic_manager_t::init_diagnostic_shims()
79 {
80         shims_ = diagnostic_init_shims(shims_logger, shims_send, NULL);
81         AFB_DEBUG("Shims initialized");
82 }
83
84 /// @brief Force cleanup all active requests.
85 void diagnostic_manager_t::reset()
86 {
87         AFB_DEBUG("Clearing existing diagnostic requests");
88         cleanup_active_requests(true);
89 }
90
91 /// @brief send function use by diagnostic library. It will open a BCM CAN socket TX_SETUP type.
92 /// That socket will send cyclic messages configured from a diagnostic request.
93 ///
94 /// @param[in] arbitration_id - CAN arbitration ID to use when send message. OBD2 broadcast ID
95 ///  is 0x7DF by example.
96 /// @param[in] data - The data payload for the message. NULL is valid if size is also 0.
97 /// @param[in] size - The size of the data payload, in bytes.
98 ///
99 /// @return true if the CAN message was sent successfully.
100 bool diagnostic_manager_t::shims_send(const uint32_t arbitration_id, const uint8_t* data, const uint8_t size)
101 {
102         diagnostic_manager_t& dm = application_t::instance().get_diagnostic_manager();
103         active_diagnostic_request_t* current_adr = dm.get_last_recurring_requests();
104         utils::socketcan_bcm_t& tx_socket = current_adr->get_socket();
105
106         // Make sure that socket has been opened.
107         if(! tx_socket)
108                 tx_socket.open(dm.get_bus_device_name());
109
110         struct bcm_msg bcm_msg;
111         struct can_frame cf;
112
113         struct timeval freq = current_adr->get_frequency_clock().get_timeval_from_period();
114
115         bcm_msg.msg_head.opcode  = TX_SETUP;
116         bcm_msg.msg_head.can_id  = arbitration_id;
117         bcm_msg.msg_head.flags = SETTIMER|STARTTIMER|TX_CP_CAN_ID;
118         bcm_msg.msg_head.count = 0;
119         bcm_msg.msg_head.ival2.tv_sec = freq.tv_sec;
120         bcm_msg.msg_head.ival2.tv_usec = freq.tv_usec;
121         bcm_msg.msg_head.nframes = 1;
122         cf.can_dlc = size;
123
124         ::memset(cf.data, 0, sizeof(cf.data));
125         ::memcpy(cf.data, data, size);
126
127         bcm_msg.frames[0] = cf;
128
129
130         can_message_t msg = can_message_t();
131
132         msg.set_bcm_msg(bcm_msg);
133
134         tx_socket.write_message(msg);
135         if(tx_socket)
136                 return true;
137         return false;
138 }
139
140 /// @brief The type signature for an optional logging function, if the user
141 /// wishes to provide one. It should print, store or otherwise display the
142 /// message.
143 ///
144 /// message - A format string to log using the given parameters.
145 /// ... (vargs) - the parameters for the format string.
146 ///
147 void diagnostic_manager_t::shims_logger(const char* format, ...)
148 {
149         va_list args;
150         va_start(args, format);
151
152         char buffer[256];
153         vsnprintf(buffer, 256, format, args);
154
155         AFB_DEBUG("%s", buffer);
156         va_end(args);
157 }
158
159 const std::string diagnostic_manager_t::get_bus_name() const
160 {
161         return bus_;
162 }
163
164 const std::string diagnostic_manager_t::get_bus_device_name() const
165 {
166         return application_t::instance().get_can_bus_manager()
167                 .get_can_device_name(bus_);
168 }
169
170 active_diagnostic_request_t* diagnostic_manager_t::get_last_recurring_requests() const
171 {
172         return recurring_requests_.back();
173 }
174
175 /// @brief Return diagnostic manager shims member.
176 DiagnosticShims& diagnostic_manager_t::get_shims()
177 {
178         return shims_;
179 }
180
181 /// @brief Search for a specific active diagnostic request in the provided requests list
182 /// and erase it from the vector. This is useful at unsubscription to clean up the list otherwize
183 /// all received CAN messages will be passed to DiagnosticRequestHandle of all active diagnostic request
184 /// contained in the vector but no event if connected to, so we will decode uneeded request.
185 ///
186 /// @param[in] entry - a pointer of an active_diagnostic_request instance to clean up
187 /// @param[in] requests_list - a vector where to make the search and cleaning.
188 void diagnostic_manager_t::find_and_erase(active_diagnostic_request_t* entry, std::vector<active_diagnostic_request_t*>& requests_list)
189 {
190         auto i = std::find(requests_list.begin(), requests_list.end(), entry);
191         if ( i != requests_list.end())
192                 requests_list.erase(i);
193 }
194
195 /// @brief Free memory allocated on active_diagnostic_request_t object and close the socket.
196 void diagnostic_manager_t::cancel_request(active_diagnostic_request_t* entry)
197 {
198         entry->get_socket().close();
199         delete entry;
200         entry = nullptr;
201 }
202
203 /// @brief Cleanup a specific request if it isn't running and get complete. As it is almost
204 /// impossible to get that state for a recurring request without waiting for that, you can
205 /// force the cleaning operation.
206 ///
207 /// @param[in] entry - the request to clean
208 /// @param[in] force - Force the cleaning or not ?
209 void diagnostic_manager_t::cleanup_request(active_diagnostic_request_t* entry, bool force)
210 {
211         if(entry != nullptr && (force || entry->response_received()))
212         {
213                 char request_string[128] = {0};
214                 diagnostic_request_to_string(&entry->get_handle()->request,
215                         request_string, sizeof(request_string));
216                 if(force && entry->get_recurring())
217                 {
218                         cancel_request(entry);
219                         find_and_erase(entry, recurring_requests_);
220                         AFB_DEBUG("Cancelling completed, recurring request: %s", request_string);
221                 }
222                 else if (!entry->get_recurring())
223                 {
224                         AFB_DEBUG("Cancelling completed, non-recurring request: %s", request_string);
225                         cancel_request(entry);
226                         find_and_erase(entry, non_recurring_requests_);
227                 }
228         }
229 }
230
231 /// @brief Clean up all requests lists, recurring and not recurring.
232 ///
233 /// @param[in] force - Force the cleaning or not ? If true, that will do
234 /// the same effect as a call to reset().
235 void diagnostic_manager_t::cleanup_active_requests(bool force)
236 {
237         for(auto& entry : non_recurring_requests_)
238         {
239                 if (entry != nullptr)
240                         cleanup_request(entry, force);
241         }
242
243         for(auto& entry : recurring_requests_)
244          {
245                 if (entry != nullptr)
246                         cleanup_request(entry, force);
247          }
248 }
249
250 /// @brief Will return the active_diagnostic_request_t pointer for theDiagnosticRequest or nullptr if
251 /// not found.
252 ///
253 /// @param[in] request - Search key, method will go through recurring list to see if it find that request
254 ///  holded by the DiagnosticHandle member.
255 active_diagnostic_request_t* diagnostic_manager_t::find_recurring_request(DiagnosticRequest& request)
256 {
257         for (auto& entry : recurring_requests_)
258         {
259                 if(entry != nullptr)
260                 {
261                         if(diagnostic_request_equals(&entry->get_handle()->request, &request))
262                                 return entry;
263                 }
264         }
265         return nullptr;
266 }
267 /*
268 /// @brief Add and send a new one-time diagnostic request. DON'T USED AT THIS TIME
269 ///
270 /// A one-time (aka non-recurring) request can existing in parallel with a
271 /// recurring request for the same PID or mode, that's not a problem.
272 ///
273 /// For an example, see the docs for addRecurringRequest. This function is very
274 /// similar but leaves out the frequencyHz parameter.
275 ///
276 /// @param[in] request - The parameters for the request.
277 /// @param[in] name - Human readable name this response, to be used when
278 ///      publishing received responses.
279 /// @param[in] wait_for_multiple_responses - If false, When any response is received
280 ///      for this request it will be removed from the active list. If true, the
281 ///      request will remain active until the timeout clock expires, to allow it
282 ///      to receive multiple response. Functional broadcast requests will always
283 ///      waint for the timeout, regardless of this parameter.
284 /// @param[in] decoder - An optional DiagnosticResponseDecoder to parse the payload of
285 ///      responses to this request. If the decoder is NULL, the output will
286 ///      include the raw payload instead of a parsed value.
287 /// @param[in] callback - An optional DiagnosticResponseCallback to be notified whenever a
288 ///      response is received for this request.
289 ///
290 /// @return true if the request was added successfully. Returns false if there
291 /// wasn't a free active request entry.
292 active_diagnostic_request_t* diagnostic_manager_t::add_request(DiagnosticRequest* request, const std::string& name,
293         bool wait_for_multiple_responses, const DiagnosticResponseDecoder decoder,
294         const DiagnosticResponseCallback callback)
295 {
296         cleanup_active_requests(false);
297
298         active_diagnostic_request_t* entry = nullptr;
299
300         if (non_recurring_requests_.size() <= MAX_SIMULTANEOUS_DIAG_REQUESTS)
301         {
302                 active_diagnostic_request_t* entry = new active_diagnostic_request_t(bus_, request->arbitration_id, name,
303                                 wait_for_multiple_responses, decoder, callback, 0, false);
304                 entry->set_handle(shims_, request);
305
306                 char request_string[128] = {0};
307                 diagnostic_request_to_string(&entry->get_handle()->request, request_string,
308                                 sizeof(request_string));
309
310                 // Erase any existing request not already cleaned.
311                 cleanup_request(entry, true);
312                 AFB_DEBUG("Added one-time diagnostic request on bus %s: %s",
313                                 bus_.c_str(), request_string);
314
315                 non_recurring_requests_.push_back(entry);
316         }
317         else
318         {
319                 AFB_WARNING("There isn't enough request entry. Vector exhausted %d/%d", (int)non_recurring_requests_.size(), MAX_SIMULTANEOUS_DIAG_REQUESTS);
320                 non_recurring_requests_.resize(MAX_SIMULTANEOUS_DIAG_REQUESTS);
321         }
322         return entry;
323 }
324 */
325 /// @brief Validate frequency asked don't get higher than the maximum of a classical
326 /// CAN bus OBD2 request.
327 ///
328 /// @param[in] frequencyHz - frequency asked for sending diagnostic requests.
329 ///
330 /// @return True if frequency is below the Maximum false if not.
331 bool diagnostic_manager_t::validate_optional_request_attributes(float frequencyHz)
332 {
333         if(frequencyHz > MAX_RECURRING_DIAGNOSTIC_FREQUENCY_HZ) {
334                 AFB_DEBUG("Requested recurring diagnostic frequency %lf is higher than maximum of %d",
335                         frequencyHz, MAX_RECURRING_DIAGNOSTIC_FREQUENCY_HZ);
336                 return false;
337         }
338         return true;
339 }
340
341 /// @brief Add and send a new recurring diagnostic request.
342 ///
343 /// At most one recurring request can be active for the same arbitration ID, mode
344 /// and (if set) PID on the same bus at one time. If you try and call
345 /// add_recurring_request with the same key, it will return an error.
346 ///
347 /// @param[in] request - The parameters for the request.
348 /// @param[in] name - An optional human readable name this response, to be used when
349 ///      publishing received responses. If the name is NULL, the published output
350 ///      will use the raw OBD-II response format.
351 /// @param[in] wait_for_multiple_responses - If false, When any response is received
352 ///      for this request it will be removed from the active list. If true, the
353 ///      request will remain active until the timeout clock expires, to allow it
354 ///      to receive multiple response. Functional broadcast requests will always
355 ///      waint for the timeout, regardless of this parameter.
356 /// @param[in] decoder - An optional DiagnosticResponseDecoder to parse the payload of
357 ///      responses to this request. If the decoder is NULL, the output will
358 ///      include the raw payload instead of a parsed value.
359 /// @param[in] callback - An optional DiagnosticResponseCallback to be notified whenever a
360 ///      response is received for this request.
361 /// @param[in] frequencyHz - The frequency (in Hz) to send the request. A frequency above
362 ///      MAX_RECURRING_DIAGNOSTIC_FREQUENCY_HZ is not allowed, and will make this
363 ///      function return false.
364 ///
365 /// @return true if the request was added successfully. Returns false if there
366 /// was too much already running requests, or if the frequency was too high.
367 active_diagnostic_request_t* diagnostic_manager_t::add_recurring_request(DiagnosticRequest* request, const char* name,
368                 bool wait_for_multiple_responses, const DiagnosticResponseDecoder decoder,
369                 const DiagnosticResponseCallback callback, float frequencyHz, bool permanent)
370 {
371         active_diagnostic_request_t* entry = nullptr;
372
373         if(!validate_optional_request_attributes(frequencyHz))
374                 return entry;
375
376         cleanup_active_requests(false);
377
378         if(find_recurring_request(*request) == nullptr)
379         {
380                 if(recurring_requests_.size() <= MAX_SIMULTANEOUS_DIAG_REQUESTS)
381                 {
382                         entry = new active_diagnostic_request_t(bus_, request->arbitration_id, name,
383                                         wait_for_multiple_responses, decoder, callback, frequencyHz, permanent);
384                         recurring_requests_.push_back(entry);
385
386                         entry->set_handle(shims_, request);
387                         start_diagnostic_request(&shims_, entry->get_handle());
388                 }
389                 else
390                 {
391                         AFB_WARNING("There isn't enough request entry. Vector exhausted %d/%d", (int)recurring_requests_.size(), MAX_SIMULTANEOUS_DIAG_REQUESTS);
392                         recurring_requests_.resize(MAX_SIMULTANEOUS_DIAG_REQUESTS);
393                 }
394         }
395         else
396                  AFB_DEBUG("Can't add request, one already exists with same key");
397         return entry;
398 }
399
400 /// @brief Will decode the diagnostic response and build the final openxc_VehicleMessage to return.
401 ///
402 /// @param[in] adr - A pointer to an active diagnostic request holding a valid diagnostic handle
403 /// @param[in] response - The response to decode from which the Vehicle message will be built and returned
404 ///
405 /// @return A filled openxc_VehicleMessage or a zeroed struct if there is an error.
406 openxc_VehicleMessage diagnostic_manager_t::relay_diagnostic_response(active_diagnostic_request_t* adr, const DiagnosticResponse& response, const uint64_t timestamp)
407 {
408         openxc_VehicleMessage message = build_VehicleMessage();
409         float value = (float)diagnostic_payload_to_integer(&response);
410
411         struct utils::signals_found found_signals;
412         found_signals = utils::signals_manager_t::instance().find_signals(build_DynamicField((double) adr->get_pid()));
413
414         if(adr->get_decoder() != nullptr)
415                 value = adr->get_decoder()(&response, value);
416
417         if((response.success && adr->get_name().size()) > 0)
418         {
419                 // If name, include 'value' instead of payload, and leave of response
420                 // details.
421                 message = build_VehicleMessage(build_SimpleMessage(adr->get_name(), build_DynamicField(value)));
422                 message.has_diagnostic_response = true;
423                 message.diagnostic_response = build_VehicleMessage(adr, response, value).diagnostic_response;
424         }
425         else
426         {
427                 // If no name, only send full details of response but still include 'value'
428                 // instead of 'payload' if they provided a decoder. The one case you
429                 // can't get is the full detailed response with 'value'. We could add
430                 // another parameter for that but it's onerous to carry that around.
431                 message = build_VehicleMessage(adr, response, value);
432         }
433
434         // If not success but completed then the pid isn't supported
435         if(!response.success)
436         {
437                 found_signals.diagnostic_messages.front()->set_supported(false);
438                 cleanup_request(adr, true);
439                 AFB_NOTICE("PID not supported or ill formed. Please unsubscribe from it. Error code : %d", response.negative_response_code);
440                 message = build_VehicleMessage(build_SimpleMessage(adr->get_name(), build_DynamicField("This PID isn't supported by your vehicle.")));
441         }
442
443         if(adr->get_callback() != nullptr)
444                 adr->get_callback()(adr, &response, value);
445
446         // Reset the completed flag handle to make sure that it will be reprocessed the next time.
447         adr->get_handle()->success = false;
448
449         // Save value and timestamp of diagnostic message
450         if(!found_signals.diagnostic_messages.empty())
451         {
452                 // Then, for each diag_message found
453                 for(const auto& diag_mess: found_signals.diagnostic_messages)
454                 {
455                         // Save value and timestamp for this message
456                         diag_mess->set_received(true);
457                         diag_mess->set_last_value(value);
458                         diag_mess->set_timestamp(timestamp);
459                 }
460         }
461
462         return message;
463 }
464
465 /// @brief Will take the CAN message and pass it to the receive functions that will process
466 /// diagnostic handle for each active diagnostic request then depending on the result we will
467 /// return pass the diagnostic response to decode it.
468 ///
469 /// @param[in] entry - A pointer to an active diagnostic request holding a valid diagnostic handle
470 /// @param[in] cm - A raw CAN message.
471 ///
472 /// @return A pointer to a filled openxc_VehicleMessage or a nullptr if nothing has been found.
473 openxc_VehicleMessage diagnostic_manager_t::relay_diagnostic_handle(active_diagnostic_request_t* entry, std::shared_ptr<message_t> m)
474 {
475         DiagnosticResponse response = diagnostic_receive_can_frame(&shims_, entry->get_handle(), m->get_id(), m->get_data(), (uint8_t)m->get_length());
476         if(response.completed && entry->get_handle()->completed)
477         {
478                 if(entry->get_handle()->success)
479                         return relay_diagnostic_response(entry, response, m->get_timestamp());
480         }
481         else if(!response.completed && response.multi_frame)
482         {
483                 // Reset the timeout clock while completing the multi-frame receive
484                 entry->get_timeout_clock().tick(
485                         entry->get_timeout_clock().get_time_function()());
486         }
487
488         return build_VehicleMessage();
489 }
490
491 /// @brief Find the active diagnostic request with the correct DiagnosticRequestHandle
492 /// member that will understand the CAN message using diagnostic_receive_can_frame function
493 /// from UDS-C library. Then decode it with an ad-hoc method.
494 ///
495 /// @param[in] cm - Raw CAN message received
496 ///
497 /// @return VehicleMessage with decoded value.
498 openxc_VehicleMessage diagnostic_manager_t::find_and_decode_adr(std::shared_ptr<message_t> m)
499 {
500         openxc_VehicleMessage vehicle_message = build_VehicleMessage();
501
502         for ( auto entry : non_recurring_requests_)
503         {
504                 vehicle_message = relay_diagnostic_handle(entry, m);
505                 if (is_valid(vehicle_message))
506                         return vehicle_message;
507         }
508
509         for ( auto entry : recurring_requests_)
510         {
511                 vehicle_message = relay_diagnostic_handle(entry, m);
512                 if (is_valid(vehicle_message))
513                         return vehicle_message;
514         }
515
516         return vehicle_message;
517 }
518
519 /// @brief Tell if the CAN message received is a diagnostic response.
520 /// Request broadcast ID use 0x7DF and assigned ID goes from 0x7E0 to Ox7E7. That allows up to 8 ECU to respond
521 /// at the same time. The response is the assigned ID + 0x8, so response ID can goes from 0x7E8 to 0x7EF.
522 ///
523 /// @param[in] cm - CAN message received from the socket.
524 ///
525 /// @return True if the active diagnostic request match the response.
526 bool diagnostic_manager_t::is_diagnostic_response(std::shared_ptr<message_t> m)
527 {
528         if(m->get_id() & CAN_SFF_MASK || m->get_id() & CAN_EFF_MASK)
529         {
530                 if (m->get_id() >= 0x7e8 && m->get_id() <= 0x7ef)
531                                 return true;
532         }
533         return false;
534 }