2 * Copyright (C) 2015, 2016 "IoT.bzh"
3 * Author "Romain Forlot" <romain.forlot@iot.bzh>
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
9 * http://www.apache.org/licenses/LICENSE-2.0
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.
18 #include <systemd/sd-event.h>
22 #include "diagnostic-manager.hpp"
24 #include "../utils/openxc-utils.hpp"
25 #include "../utils/signals.hpp"
26 #include "../binding/configuration.hpp"
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
35 diagnostic_manager_t::diagnostic_manager_t()
39 /// @brief Diagnostic manager isn't initialized at launch but after
40 /// CAN bus devices initialization. For the moment, it is only possible
41 /// to have 1 diagnostic bus which are the first bus declared in the JSON
42 /// description file. Configuration instance will return it.
44 /// this will initialize DiagnosticShims and cancel all active requests
46 bool diagnostic_manager_t::initialize()
48 // Mandatory to set the bus before intialize shims.
49 bus_ = configuration_t::instance().get_diagnostic_bus();
51 init_diagnostic_shims();
52 event_source_ = nullptr;
56 DEBUG(binder_interface, "%s: Diagnostic Manager initialized", __FUNCTION__);
60 void diagnostic_manager_t::read_socket()
63 can_bus_t& cbm = configuration_t::instance().get_can_bus_manager();
65 std::lock_guard<std::mutex> can_message_lock(cbm.get_can_message_mutex());
66 { cbm.push_new_can_message(msg); }
67 cbm.get_new_can_message_cv().notify_one();
70 utils::socketcan_bcm_t& diagnostic_manager_t::get_socket()
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()
80 shims_ = diagnostic_init_shims(shims_logger, shims_send, NULL);
81 DEBUG(binder_interface, "%s: Shims initialized", __FUNCTION__);
84 /// @brief Force cleanup all active requests.
85 void diagnostic_manager_t::reset()
87 DEBUG(binder_interface, "%s: Clearing existing diagnostic requests", __FUNCTION__);
88 cleanup_active_requests(true);
91 /// @brief Adds 8 RX_SETUP jobs to the BCM rx_socket_ then diagnotic manager
92 /// listens on CAN ID range 7E8 - 7EF affected to the OBD2 communications.
94 /// @return -1 or negative value on error, 0 if ok.
95 int diagnostic_manager_t::add_rx_filter(uint32_t can_id)
97 // Make sure that socket has been opened.
101 struct utils::simple_bcm_msg bcm_msg;
102 memset(&bcm_msg.msg_head, 0, sizeof(bcm_msg.msg_head));
104 const struct timeval freq = recurring_requests_.back()->get_timeout_clock().get_timeval_from_period();
106 bcm_msg.msg_head.opcode = RX_SETUP;
107 bcm_msg.msg_head.flags = SETTIMER|RX_FILTER_ID;
108 bcm_msg.msg_head.ival2.tv_sec = freq.tv_sec;
109 bcm_msg.msg_head.ival2.tv_usec = freq.tv_usec;
111 // If it isn't an OBD2 CAN ID then just add a simple RX_SETUP job
112 if(can_id != OBD2_FUNCTIONAL_BROADCAST_ID)
114 bcm_msg.msg_head.can_id = can_id;
122 for(uint8_t i = 0; i < 8; i++)
124 can_id = OBD2_FUNCTIONAL_RESPONSE_START + i;
125 bcm_msg.msg_head.can_id = can_id;
136 /// @brief send function use by diagnostic library. Only one bus used for now
137 /// so diagnostic request is sent using the default diagnostic bus not matter of
138 /// which is specified in the diagnostic message definition.
140 /// @param[in] arbitration_id - CAN arbitration ID to use when send message. OBD2 broadcast ID
141 /// is 0x7DF by example.
142 /// @param[in] data - The data payload for the message. NULL is valid if size is also 0.
143 /// @param[in] size - The size of the data payload, in bytes.
145 /// @return true if the CAN message was sent successfully.
146 bool diagnostic_manager_t::shims_send(const uint32_t arbitration_id, const uint8_t* data, const uint8_t size)
148 diagnostic_manager_t& dm = configuration_t::instance().get_diagnostic_manager();
149 active_diagnostic_request_t* current_adr = dm.get_last_recurring_requests();
150 utils::socketcan_bcm_t& tx_socket = current_adr->get_socket();
152 // Make sure that socket has been opened.
157 struct utils::simple_bcm_msg bcm_msg;
158 struct can_frame cfd;
160 memset(&cfd, 0, sizeof(cfd));
161 memset(&bcm_msg.msg_head, 0, sizeof(bcm_msg.msg_head));
163 struct timeval freq = current_adr->get_frequency_clock().get_timeval_from_period();
165 bcm_msg.msg_head.opcode = TX_SETUP;
166 bcm_msg.msg_head.can_id = arbitration_id;
167 bcm_msg.msg_head.flags = SETTIMER|STARTTIMER|TX_CP_CAN_ID;
168 bcm_msg.msg_head.ival2.tv_sec = freq.tv_sec;
169 bcm_msg.msg_head.ival2.tv_usec = freq.tv_usec;
170 bcm_msg.msg_head.nframes = 1;
172 ::memcpy(cfd.data, data, size);
174 bcm_msg.frames = cfd;
176 tx_socket << bcm_msg;
182 /// @brief The type signature for an optional logging function, if the user
183 /// wishes to provide one. It should print, store or otherwise display the
186 /// message - A format string to log using the given parameters.
187 /// ... (vargs) - the parameters for the format string.
189 void diagnostic_manager_t::shims_logger(const char* format, ...)
192 va_start(args, format);
195 vsnprintf(buffer, 256, format, args);
197 DEBUG(binder_interface, "%s: %s", __FUNCTION__, buffer);
200 /// @brief The type signature for a... OpenXC TODO: not used yet.
201 void diagnostic_manager_t::shims_timer()
204 std::string diagnostic_manager_t::get_can_bus()
209 active_diagnostic_request_t* diagnostic_manager_t::get_last_recurring_requests() const
211 return recurring_requests_.back();
214 /// @brief Return diagnostic manager shims member.
215 DiagnosticShims& diagnostic_manager_t::get_shims()
220 /// @brief Search for a specific active diagnostic request in the provided requests list
221 /// and erase it from the vector. This is useful at unsubscription to clean up the list otherwize
222 /// all received CAN messages will be passed to DiagnosticRequestHandle of all active diagnostic request
223 /// contained in the vector but no event if connected to, so we will decode uneeded request.
225 /// @param[in] entry - a pointer of an active_diagnostic_request instance to clean up
226 /// @param[in] requests_list - a vector where to make the search and cleaning.
227 void diagnostic_manager_t::find_and_erase(active_diagnostic_request_t* entry, std::vector<active_diagnostic_request_t*>& requests_list)
229 auto i = std::find(requests_list.begin(), requests_list.end(), entry);
230 if ( i != requests_list.end())
231 requests_list.erase(i);
234 // @brief TODO: implement cancel_request if needed... Don't know.
235 void diagnostic_manager_t::cancel_request(active_diagnostic_request_t* entry)
237 entry->get_socket().close();
240 /// @brief Cleanup a specific request if it isn't running and get complete. As it is almost
241 /// impossible to get that state for a recurring request without waiting for that, you can
242 /// force the cleaning operation.
244 /// @param[in] entry - the request to clean
245 /// @param[in] force - Force the cleaning or not ?
246 void diagnostic_manager_t::cleanup_request(active_diagnostic_request_t* entry, bool force)
248 if((force || (entry != nullptr && entry->response_received())))
250 char request_string[128] = {0};
251 diagnostic_request_to_string(&entry->get_handle()->request,
252 request_string, sizeof(request_string));
253 if(force && entry->get_recurring())
255 find_and_erase(entry, recurring_requests_);
256 cancel_request(entry);
257 DEBUG(binder_interface, "%s: Cancelling completed, recurring request: %s", __FUNCTION__, request_string);
261 DEBUG(binder_interface, "%s: Cancelling completed, non-recurring request: %s", __FUNCTION__, request_string);
262 find_and_erase(entry, non_recurring_requests_);
263 cancel_request(entry);
268 /// @brief Clean up all requests lists, recurring and not recurring.
270 /// @param[in] force - Force the cleaning or not ? If true, that will do
271 /// the same effect as a call to reset().
272 void diagnostic_manager_t::cleanup_active_requests(bool force)
274 for(auto& entry : non_recurring_requests_)
275 if (entry != nullptr)
276 cleanup_request(entry, force);
278 for(auto& entry : recurring_requests_)
279 if (entry != nullptr)
280 cleanup_request(entry, force);
283 /// @brief Will return the active_diagnostic_request_t pointer for theDiagnosticRequest or nullptr if
286 /// @param[in] request - Search key, method will go through recurring list to see if it find that request
287 /// holded by the DiagnosticHandle member.
288 active_diagnostic_request_t* diagnostic_manager_t::find_recurring_request(const DiagnosticRequest* request)
290 for (auto& entry : recurring_requests_)
294 if(diagnostic_request_equals(&entry->get_handle()->request, request))
304 /// @brief Add and send a new one-time diagnostic request.
306 /// A one-time (aka non-recurring) request can existing in parallel with a
307 /// recurring request for the same PID or mode, that's not a problem.
309 /// For an example, see the docs for addRecurringRequest. This function is very
310 /// similar but leaves out the frequencyHz parameter.
312 /// @param[in] request - The parameters for the request.
313 /// @param[in] name - Human readable name this response, to be used when
314 /// publishing received responses. TODO: If the name is NULL, the published output
315 /// will use the raw OBD-II response format.
316 /// @param[in] wait_for_multiple_responses - If false, When any response is received
317 /// for this request it will be removed from the active list. If true, the
318 /// request will remain active until the timeout clock expires, to allow it
319 /// to receive multiple response. Functional broadcast requests will always
320 /// waint for the timeout, regardless of this parameter.
321 /// @param[in] decoder - An optional DiagnosticResponseDecoder to parse the payload of
322 /// responses to this request. If the decoder is NULL, the output will
323 /// include the raw payload instead of a parsed value.
324 /// @param[in] callback - An optional DiagnosticResponseCallback to be notified whenever a
325 /// response is received for this request.
327 /// @return true if the request was added successfully. Returns false if there
328 /// wasn't a free active request entry, if the frequency was too high or if the
329 /// CAN acceptance filters could not be configured,
330 active_diagnostic_request_t* diagnostic_manager_t::add_request(DiagnosticRequest* request, const std::string name,
331 bool wait_for_multiple_responses, const DiagnosticResponseDecoder decoder,
332 const DiagnosticResponseCallback callback)
334 cleanup_active_requests(false);
336 active_diagnostic_request_t* entry = nullptr;
338 if (non_recurring_requests_.size() <= MAX_SIMULTANEOUS_DIAG_REQUESTS)
340 // TODO: implement Acceptance Filter
341 // if(updateRequiredAcceptanceFilters(bus, request)) {
342 active_diagnostic_request_t* entry = new active_diagnostic_request_t(bus_, request, name,
343 wait_for_multiple_responses, decoder, callback, 0);
344 entry->set_handle(shims_, request);
346 char request_string[128] = {0};
347 diagnostic_request_to_string(&entry->get_handle()->request, request_string,
348 sizeof(request_string));
350 find_and_erase(entry, non_recurring_requests_);
351 DEBUG(binder_interface, "%s: Added one-time diagnostic request on bus %s: %s", __FUNCTION__,
352 bus_.c_str(), request_string);
354 non_recurring_requests_.push_back(entry);
358 WARNING(binder_interface, "%s: There isn't enough request entry. Vector exhausted %d/%d", __FUNCTION__, (int)non_recurring_requests_.size(), MAX_SIMULTANEOUS_DIAG_REQUESTS);
359 non_recurring_requests_.resize(MAX_SIMULTANEOUS_DIAG_REQUESTS);
364 bool diagnostic_manager_t::validate_optional_request_attributes(float frequencyHz)
366 if(frequencyHz > MAX_RECURRING_DIAGNOSTIC_FREQUENCY_HZ) {
367 DEBUG(binder_interface, "%s: Requested recurring diagnostic frequency %lf is higher than maximum of %d", __FUNCTION__,
368 frequencyHz, MAX_RECURRING_DIAGNOSTIC_FREQUENCY_HZ);
374 /// @brief Add and send a new recurring diagnostic request.
376 /// At most one recurring request can be active for the same arbitration ID, mode
377 /// and (if set) PID on the same bus at one time. If you try and call
378 /// addRecurringRequest with the same key, it will return an error.
380 /// TODO: This also adds any neccessary CAN acceptance filters so we can receive the
381 /// response. If the request is to the functional broadcast ID (0x7df) filters
382 /// are added for all functional addresses (0x7e8 to 0x7f0).
386 /// // Creating a functional broadcast, mode 1 request for PID 2.
387 /// DiagnosticRequest request = {
388 /// arbitration_id: 0x7df,
394 /// // Add a recurring request, to be sent at 1Hz, and published with the
395 /// // name "my_pid_request"
396 /// addRecurringRequest(&getConfiguration()->diagnosticsManager,
399 /// "my_pid_request",
405 /// @param[in] request - The parameters for the request.
406 /// @param[in] name - An optional human readable name this response, to be used when
407 /// publishing received responses. If the name is NULL, the published output
408 /// will use the raw OBD-II response format.
409 /// @param[in] wait_for_multiple_responses - If false, When any response is received
410 /// for this request it will be removed from the active list. If true, the
411 /// request will remain active until the timeout clock expires, to allow it
412 /// to receive multiple response. Functional broadcast requests will always
413 /// waint for the timeout, regardless of this parameter.
414 /// @param[in] decoder - An optional DiagnosticResponseDecoder to parse the payload of
415 /// responses to this request. If the decoder is NULL, the output will
416 /// include the raw payload instead of a parsed value.
417 /// @param[in] callback - An optional DiagnosticResponseCallback to be notified whenever a
418 /// response is received for this request.
419 /// @param[in] frequencyHz - The frequency (in Hz) to send the request. A frequency above
420 /// MAX_RECURRING_DIAGNOSTIC_FREQUENCY_HZ is not allowed, and will make this
421 /// function return false.
423 /// @return true if the request was added successfully. Returns false if there
424 /// was too much already running requests, if the frequency was too high TODO:or if the
425 /// CAN acceptance filters could not be configured,
426 active_diagnostic_request_t* diagnostic_manager_t::add_recurring_request(DiagnosticRequest* request, const char* name,
427 bool wait_for_multiple_responses, const DiagnosticResponseDecoder decoder,
428 const DiagnosticResponseCallback callback, float frequencyHz)
430 active_diagnostic_request_t* entry = nullptr;
432 if(!validate_optional_request_attributes(frequencyHz))
435 cleanup_active_requests(false);
437 if(find_recurring_request(request) == nullptr)
439 if(recurring_requests_.size() <= MAX_SIMULTANEOUS_DIAG_REQUESTS)
441 // TODO: implement Acceptance Filter
442 //if(updateRequiredAcceptanceFilters(bus, request)) {
443 entry = new active_diagnostic_request_t(bus_, request, name,
444 wait_for_multiple_responses, decoder, callback, frequencyHz);
445 recurring_requests_.push_back(entry);
447 entry->set_handle(shims_, request);
448 if(add_rx_filter(OBD2_FUNCTIONAL_BROADCAST_ID) < 0)
449 { recurring_requests_.pop_back(); }
452 start_diagnostic_request(&shims_, entry->get_handle());
453 if(event_source_ == nullptr && sd_event_add_io(afb_daemon_get_event_loop(binder_interface->daemon),
457 read_diagnostic_message,
460 cleanup_request(entry, true);
461 WARNING(binder_interface, "%s: signal: %s isn't supported. Canceling operation.", __FUNCTION__, entry->get_name().c_str());
468 WARNING(binder_interface, "%s: There isn't enough request entry. Vector exhausted %d/%d", __FUNCTION__, (int)recurring_requests_.size(), MAX_SIMULTANEOUS_DIAG_REQUESTS);
469 recurring_requests_.resize(MAX_SIMULTANEOUS_DIAG_REQUESTS);
473 { DEBUG(binder_interface, "%s: Can't add request, one already exists with same key", __FUNCTION__);}
477 /// @brief Will decode the diagnostic response and build the final openxc_VehicleMessage to return.
479 /// @param[in] adr - A pointer to an active diagnostic request holding a valid diagnostic handle
480 /// @param[in] response - The response to decode from which the Vehicle message will be built and returned
482 /// @return A filled openxc_VehicleMessage or a zeroed struct if there is an error.
483 openxc_VehicleMessage diagnostic_manager_t::relay_diagnostic_response(active_diagnostic_request_t* adr, const DiagnosticResponse& response)
485 openxc_VehicleMessage message = build_VehicleMessage();
486 float value = (float)diagnostic_payload_to_integer(&response);
487 if(adr->get_decoder() != nullptr)
489 value = adr->get_decoder()(&response, value);
492 if((response.success && adr->get_name().size()) > 0)
494 // If name, include 'value' instead of payload, and leave of response
496 message = build_VehicleMessage(build_SimpleMessage(adr->get_name(), build_DynamicField(value)));
500 // If no name, send full details of response but still include 'value'
501 // instead of 'payload' if they provided a decoder. The one case you
502 // can't get is the full detailed response with 'value'. We could add
503 // another parameter for that but it's onerous to carry that around.
504 message = build_VehicleMessage(adr, response, value);
507 // If not success but completed then the pid isn't supported
508 if(!response.success)
510 struct utils::signals_found found_signals;
511 found_signals = utils::signals_manager_t::instance().find_signals(build_DynamicField(adr->get_name()));
512 found_signals.diagnostic_messages.front()->set_supported(false);
513 cleanup_request(adr, true);
514 NOTICE(binder_interface, "%s: PID not supported or ill formed. Please unsubscribe from it. Error code : %d", __FUNCTION__, response.negative_response_code);
515 message = build_VehicleMessage(build_SimpleMessage(adr->get_name(), build_DynamicField("This PID isn't supported by your vehicle.")));
518 if(adr->get_callback() != nullptr)
520 adr->get_callback()(adr, &response, value);
523 // Reset the completed flag handle to make sure that it will be reprocessed the next time.
524 adr->get_handle()->success = false;
528 /// @brief Will take the CAN message and pass it to the receive functions that will process
529 /// diagnostic handle for each active diagnostic request then depending on the result we will
530 /// return pass the diagnostic response to decode it.
532 /// @param[in] entry - A pointer to an active diagnostic request holding a valid diagnostic handle
533 /// @param[in] cm - A raw CAN message.
535 /// @return A pointer to a filled openxc_VehicleMessage or a nullptr if nothing has been found.
536 openxc_VehicleMessage diagnostic_manager_t::relay_diagnostic_handle(active_diagnostic_request_t* entry, const can_message_t& cm)
538 DiagnosticResponse response = diagnostic_receive_can_frame(&shims_, entry->get_handle(), cm.get_id(), cm.get_data(), cm.get_length());
539 if(response.completed && entry->get_handle()->completed)
541 if(entry->get_handle()->success)
542 return relay_diagnostic_response(entry, response);
544 else if(!response.completed && response.multi_frame)
546 // Reset the timeout clock while completing the multi-frame receive
547 entry->get_timeout_clock().tick();
550 return build_VehicleMessage();
553 /// @brief Find the active diagnostic request with the correct DiagnosticRequestHandle
554 /// member that will understand the CAN message using diagnostic_receive_can_frame function
555 /// from UDS-C library. Then decode it with an ad-hoc method.
557 /// @param[in] cm - Raw CAN message received
559 /// @return VehicleMessage with decoded value.
560 openxc_VehicleMessage diagnostic_manager_t::find_and_decode_adr(const can_message_t& cm)
562 openxc_VehicleMessage vehicle_message = build_VehicleMessage();
564 for ( auto entry : non_recurring_requests_)
566 vehicle_message = relay_diagnostic_handle(entry, cm);
567 if (is_valid(vehicle_message))
568 return vehicle_message;
571 for ( auto entry : recurring_requests_)
573 vehicle_message = relay_diagnostic_handle(entry, cm);
574 if (is_valid(vehicle_message))
575 return vehicle_message;
578 return vehicle_message;
581 /// @brief Tell if the CAN message received is a diagnostic response.
582 /// Request broadcast ID use 0x7DF and assigned ID goes from 0x7E0 to Ox7E7. That allows up to 8 ECU to respond
583 /// at the same time. The response is the assigned ID + 0x8, so response ID can goes from 0x7E8 to 0x7EF.
585 /// @param[in] cm - CAN message received from the socket.
587 /// @return True if the active diagnostic request match the response.
588 bool diagnostic_manager_t::is_diagnostic_response(const can_message_t& cm)
590 if (cm.get_id() >= 0x7e8 && cm.get_id() <= 0x7ef)