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