Implementation and Validation of UDS Services on STM32 with CAN Communication

Implementation and Validation of UDS Services on STM32 with CAN Communication

Unified Diagnostic Services (UDS) is a diagnostic communication protocol widely utilized within automotive electronics. Defined by the ISO 14229-1 standard, UDS plays a key role in managing Electronic Control Units (ECUs) within vehicles. Diagnostic tools can communicate with all installed ECUs that have UDS services enabled, making it invaluable for fault detection, troubleshooting, and reprogramming ECUs as needed.

With UDS, the diagnostic and maintenance processes are significantly streamlined, enhancing vehicle reliability while reducing maintenance time and costs.

UDS Message Format

In UDS, both requests and responses follow a specific format to facilitate diagnostic communication between a diagnostic tool and an ECU. The format varies slightly depending on the type of request or response.

  1. Request Format

  • Request with Subfunction: This request type includes a Service Identifier (SID), a Subfunction code, and additional Request Data.

- Format: SID | SubFunction | Request Data

  • Request without Subfunction: In this case, only the SID and Request Data are included, as no Subfunction is required.

- Format: SID | Request Data

2. Response Format

  • Positive Response: When the ECU successfully processes a request, it sends a positive response. This response includes the SID plus an offset (SID + 0x40), followed by the Subfunction and any additional Response Data.

- Format: SID + 0x40 | SubFunction | Response Data

  • Response without Subfunction: Similar to the positive response with a Subfunction, but only includes SID + 0x40 and the Response Data.

- Format: SID + 0x40 | Response Data

3. Negative Response Format

  • Negative Response: When an error occurs, the ECU returns a negative response. This response contains a standard error code 0x7F, followed by the SID of the original request and a Negative Response Code (NRC).

- Format: 0x7F | SID | NRC

  • Response Pending: If the ECU needs more time to complete the request, it responds with a "Response Pending" status. This response includes 0x7F, the SID, and a special code (0x78) indicating the pending state.

- Format: 0x7F | SID | 0x78

Implementation of UDS Services

Diagnostic Communication Management_functional unit

1. Diagnostic Session Control (0x10)

Managing diagnostic sessions through the DiagnosticSessionControl (0x10) service is essential for enabling various levels of diagnostics and configuration within a vehicle’s Electronic Control Units (ECUs). This service allows the client to request the ECU to switch between multiple diagnostic sessions, each activating a specific set of functionalities.

The DiagnosticSessionControl service activates specific diagnostic sessions within the ECU, such as the default session, programming session, and extended diagnostic session. Each session configures the ECU for unique functionalities. By default, the ECU always starts in the default session, but other sessions can be activated as needed. These advanced sessions enable operations like reprogramming ECU parameters or adjusting critical functions.

Implementation Details

Session Management:

  • Default Session: Every time this session is activated, all diagnostic parameters are reset. It ensures security by locking sensitive functionalities.
  • Advanced Sessions: In programming and extended diagnostic sessions, the ECU allows advanced actions, including firmware downloads and adjustment of security or performance settings.

CAN Communication for Responses:

  • Positive Response: When a session change is validated, a positive response is sent via CAN, including a session identifier and timing parameters like P2Server_max and P2*Server_max, ensuring synchronization and diagnostic compatibility.
  • Negative Response: In case of an incorrect request, the ECU sends a negative response with an error code (NRC) via CAN, indicating issues such as incorrect message format or unmet conditions.

Test Scenarios

Extensive tests were conducted to validate the robustness of the implementation:

  • Session Transitions: Tests confirm the correct transition to advanced sessions, activating specific diagnostic and reprogramming functionalities.
  • Error Handling: Simulating message format errors or unsupported sub-functions confirms that the ECU returns the appropriate error codes via CAN, ensuring reliable communication and diagnostics in compliance with UDS standards

2. ECU Reset (0x11)

The ECU Reset (0x11) service allows the client to request a reset of the Electronic Control Unit (ECU), resetting its functions based on the specified reset type. This service is essential for reinitializing certain ECU functions or parameters, which aids in diagnostics and maintenance operations within the UDS protocol.

The ECUReset service allows the client to specify the desired reset type using the resetType parameter. Based on this command, the ECU can perform various types of resets:

  • Hard Reset: Simulates a complete power cycle, akin to disconnecting and reconnecting the ECU’s power supply.
  • Soft Reset: Restarts only the application program, preserving learned or adaptive data.
  • Enable/Disable Rapid Power Shutdown: Enables or disables the rapid shutdown function, placing the ECU in a low-power state to minimize energy consumption.

Following the reset, the ECU returns to the default session, ready to receive new commands. If needed, the system sends a positive response before executing the reset, and during the reset process, no communication is allowed until completion.

Implementation Details

Reset Handling:

  • Hard Reset: A full reset is triggered by the hard_reset() function, restarting the ECU and optionally clearing volatile and non-volatile memories.
  • Soft Reset: A lighter reset managed by soft_reset() that restarts only necessary parts of the ECU, keeping long-term data intact.
  • Enable/Disable Rapid Power Shutdown: This reset type handles the transition to low-power mode for battery-powered ECUs, reducing standby power consumption.

CAN Responses:

  • Positive Response: If the command is valid, a response is sent with session identifier 0x51. For rapid shutdown requests, the powerDownTime is included to specify the time before the full shutdown.
  • Negative Response: If an unsupported reset type is requested or other errors are detected, a negative response with the appropriate NRC code is returned via CAN.

Test Scenarios

Several tests were conducted to verify the functionality of the ECUReset service and its compliance with UDS specifications:

  • Reset Execution Tests: Each reset type (hard reset, soft reset, and rapid power shutdown) was tested to confirm that the ECU executes the requested reset type and returns the appropriate response.
  • Error Handling: Scenarios involving unsupported sub-functions or incorrect message lengths were simulated to ensure that the ECU returns the appropriate NRC codes, indicating correct error handling.
  • Condition Checks and Security Access: Certain tests simulated unmet conditions or unauthorized access, ensuring that the ECU rejects requests if prerequisites are not met.

3. Security Access (0x27)

The Security Access (0x27) service is integral for enabling secured functionalities within the Electronic Control Unit (ECU) by enforcing access control. This service restricts access to certain sensitive data and diagnostic services, which are critical for vehicle safety, emissions, and security standards.

The Security Access service provides a seed and key mechanism for the client to unlock protected services within the ECU. This process ensures that only authorized users can access secure functionalities. Here’s how it typically works:

  1. Seed Request: The client initiates a request for a “seed” from the ECU.
  2. Seed Response: The ECU generates and sends a unique “seed” back to the client.
  3. Key Calculation and Submission: The client uses the received seed to compute a “key” and sends it back to the ECU.
  4. Validation: The ECU validates the key. If it matches the expected value, access is granted; otherwise, access is denied.

Security Access prevents unauthorized access that could compromise the vehicle's performance or regulatory compliance. The ECU supports various security levels, with each level defined by a unique requestSeed and sendKey pairing. Additionally, the ECU can enforce a delay after multiple incorrect key attempts to further safeguard the system.

Implementation Details

Seed and Key Handling:

  • Seed Generation: The ECU provides different seeds based on the security level requested by the client (e.g., security_seed_lvl1 for Level 1).
  • Key Validation: The ECU compares the client-provided key with the internally stored key for the requested level (e.g., security_key_lvl1 for Level 1). If the keys match, the ECU grants access.

CAN Communication for Responses:

  • Positive Response: Upon a successful unlock attempt, the ECU sends a positive response containing an acknowledgment of the security level.
  • Negative Response: If there are errors in the sequence or format, or if the key is invalid, the ECU sends a negative response with an appropriate Negative Response Code (NRC)

Test Scenarios

To validate the functionality of the Security Access service, the following test scenarios were conducted:

  • Seed Request in Locked State: This test ensures that when the ECU is locked, a seed is generated and returned to the client.
  • Valid Key Submission: The client submits a correct key based on the received seed, allowing access to restricted services. A positive response confirms the successful unlock.
  • Invalid Key Submission: An incorrect key submission triggers the Invalid Key (0x35) response, confirming error handling.
  • Seed Request in Unlocked State: This verifies that once the ECU is unlocked, a zero seed is returned to indicate that the client already has access.
  • Key Submission Without Seed Request: This test simulates an incorrect sequence by sending a key without a prior seed request, expecting the Request Sequence Error (0x24).
  • Incorrect Message Length for Key: Sends an incomplete key, expecting the Incorrect Message Length (0x13) response, verifying that the ECU detects and reports format errors.
  • Delay Enforcement: After repeated incorrect key attempts, the ECU enforces a delay before accepting further seed requests. Any attempt during this period results in a Required Time Delay Not Expired (0x37) response, ensuring robust security.
  • Multiple Security Levels: This test confirms that the ECU can handle different security levels and respond with unique seeds and validation requirements for each level.

4. Communication Control (0x28)

The Communication Control (0x28) service is designed to manage the transmission and reception of messages in a vehicle’s Electronic Control Unit (ECU) communication network. By toggling these functions, the ECU can limit or allow certain types of message traffic for various operational needs, including diagnostics or communication prioritization.

The Communication Control service allows the client to:

  1. Enable or Disable Communication: Toggle the reception (Rx) and transmission (Tx) of specific communication types.
  2. Enhanced Addressing: Use enhanced addressing modes to manage specific nodes or subnet segments within the vehicle’s communication network.

The controlType parameter in the request message defines the type of control action, such as enabling only Rx, only Tx, or both. The communicationType parameter specifies the category of communication to control, and an optional nodeIdentificationNumber can specify a sub-network segment in enhanced addressing scenarios.

Implementation Details

Control Actions:

  • Enable Rx and Tx (controlType = 0x00): Allows both receiving and transmitting messages.
  • Enable Rx and Disable Tx (controlType = 0x01): Enables only the reception of messages.
  • Disable Rx and Enable Tx (controlType = 0x02): Enables only the transmission of messages.
  • Disable Rx and Tx (controlType = 0x03): Disables both reception and transmission.
  • Enhanced Addressing Modes: The control types 0x04 and 0x05 support diagnostic-only or application scheduling modes by addressing specific segments within the network.

CAN Communication:

  • Positive Responses: Successfully applied controls receive a positive response (0x68), confirming the operation.
  • Negative Responses: Error handling includes: Conditions Not Correct (0x22) for critical ECU operations preventing the change.Request Out of Range (0x31) for invalid communication types or IDs.

Test Scenarios

To ensure robustness in handling the Communication Control service, various test scenarios were conducted:

  • Basic Communication Toggling:

Enable Rx and Tx: Confirms that the ECU allows both message reception and transmission.

Enable Rx and Disable Tx: Ensures that only incoming messages are processed.

Disable Rx and Enable Tx: Limits ECU communications to outgoing messages only.

Disable Rx and Tx: Verifies that both sending and receiving are successfully disabled.

  • Enhanced Addressing Modes:

Enable Rx and Tx with Enhanced Info: Tests if the ECU properly uses enhanced addressing to apply communication settings on specific segments.

Enable Rx with Enhanced Info: Confirms enhanced addressing controls for Rx only.

5. Tester Present (0x3E)

The Tester Present (0x3E) service is used to maintain an active diagnostic session between a client and an Electronic Control Unit (ECU). By periodically sending a Tester Present message, the client prevents the ECU from reverting to the default session when there is no active diagnostic command.

The Tester Present service enables the client to:

  • Keep Diagnostic Sessions Active: Ensure the ECU remains in the current diagnostic session by sending periodic requests.
  • Suppress Positive Responses: Use a flag to control whether the ECU should send a response to the Tester Present command.

The sub-function parameter in the request message determines whether the ECU should send a response or remain silent.

Implementation Details

Sub-functions:

  • Standard Tester Present (0x00): The ECU acknowledges the request to maintain the session.
  • Suppress Positive Response (0x80): The ECU does not respond to this command, minimizing traffic but keeping the session active.

CAN Communication:

  • Positive Responses: A positive response (0x7E) is sent when sub-function 0x00 is used, confirming that the session remains active.
  • Negative Responses: Error handling includes:Sub-function Not Supported (0x12): Sent if an unsupported sub-function is requested.Incorrect Message Length (0x13): Sent if the message format is incorrect.

Test Scenarios

To validate the functionality of the Tester Present service, the following tests were conducted:

Basic Session Maintenance:

  • Standard Tester Present: Confirms that the ECU responds with 0x7E, indicating the session remains active.
  • Suppress Positive Response: Confirms that the ECU receives the request but does not send a response, as expected.

Error Handling:

  • Invalid Sub-function: An unsupported sub-function (e.g., 0x01) is sent, confirming the ECU responds with NRC 0x12.
  • Incorrect Message Length: An incomplete message is sent, expecting NRC 0x13, which confirms the ECU correctly detects and reports formatting errors.

6. Access Timing Parameter (0x83)

The Access Timing Parameter (0x83) service allows a client to read and modify the default timing parameters of an ECU's communication link while the link remains active. This service can be used for adjusting response timings, which can be necessary for specific diagnostic sessions or communication configurations.

The Access Timing Parameter service provides the following functionalities:

  • Read Extended Timing Parameter Set: Reads the ECU's additional timing parameters for the current session.
  • Set Timing Parameters to Default Values: Resets timing parameters to ECU defaults.
  • Read Currently Active Timing Parameters: Checks the currently applied timing parameters.
  • Set Timing Parameters to Given Values: Sets custom timing values provided by the client.

Implementation Details

Control Actions:

  1. Read Extended Timing Parameters (0x01): The ECU responds with the extended timing parameters if available.
  2. Set Timing Parameters to Default (0x02): Resets all parameters to default values and confirms with a positive response.
  3. Read Active Timing Parameters (0x03): Returns the currently active timing parameters to the client.
  4. Set Timing Parameters to Given Values (0x04): Applies client-specified timing values if valid.

CAN Communication:

  • Positive Responses: A positive response (0xC3) indicates successful application or retrieval of timing parameters.
  • Negative Responses: Error handling includes:Sub-function Not Supported (0x12): Sent if an unsupported sub-function is requested.Incorrect Message Length (0x13): Sent if the message format is incorrect.Conditions Not Correct (0x22): If the ECU is unable to set the requested parameters.Request Out of Range (0x31): If the timing parameter values are outside valid ranges.

Test Scenarios

To ensure robustness in handling the Access Timing Parameter service, the following test scenarios were conducted:

Basic Timing Parameter Control:

  • Read Extended Timing Parameters: Confirms that the ECU provides the extended timing set when requested.
  • Set Timing to Default Values: Verifies that timing parameters are reset to default.
  • Read Active Timing Parameters: Confirms that the currently active timing parameters can be retrieved.
  • Set Custom Timing Parameters: Ensures that specific timing values are applied successfully.

7. Secured Data Transmission (0x84)

The Secured Data Transmission (0x84) service is designed to securely transmit data between a client and an ECU using encryption, ensuring data security and preventing unauthorized access. This service allows diagnostic communication in a secured mode and supports secure point-to-point communication only, requiring physical addressing.

  • Unsecured Transmission Mode: Data is sent without encryption, passing directly through the application layer.
  • Secured Transmission Mode: Data is encrypted by a security sub-layer, which securely transmits and receives diagnostic or external data using encryption.

Implementation Details

Encryption and Decryption:

  • Data is encrypted before transmission using a designated encryption key, adding security layers.
  • The server decrypts received data, validates security parameters, and transmits the secured response.

Response Types:

  • Positive Response (0xC4): Indicates successful data transmission, containing the processed secure data.
  • Negative Response Codes (NRC):Incorrect Message Length or Invalid Format (0x13): Returned if the data length or format is incorrect.Reserved Codes (0x38 - 0x4F): Reserved for extended data link security.

Test Scenarios

To validate the Secured Data Transmission service, the following tests were conducted:

  • Valid Secured Data Transmission: Sends encrypted data with correct length and format, expecting a positive response (0xC4).
  • Incorrect Message Length: Sends incomplete data, confirming that the ECU returns NRC 0x13 for invalid length.
  • Invalid Data Format: Sends data with incorrect structure, expecting NRC 0x13 due to formatting issues.
  • Transmission with Incorrect Key: Encrypts data using an invalid key, testing the decryption process and validating if unauthorized access is detected.

8. Control DTC Setting (0x85)

The Control DTC Setting (0x85) service allows the client to enable or disable the updating of Diagnostic Trouble Code (DTC) status bits in an ECU. DTC status bits record diagnostic data specific to each detected fault, providing insight for maintenance and troubleshooting. The service is used primarily to manage whether the ECU updates these bits or keeps them static under certain diagnostic conditions.

  • Enable Updating (DTCSettingType = 0x01): Resumes normal DTC status updating.
  • Disable Updating (DTCSettingType = 0x02): Freezes the current DTC status, halting further updates.

Implementation Details

DTC Control Actions:

  • Enable Updating (0x01): Resumes updating DTC bits.
  • Disable Updating (0x02): Temporarily freezes the status bits until re-enabled.

CAN Communication:

  • Positive Response (0xC5): Confirms the command was successfully executed.
  • Negative Response Codes (NRC): Sub-function Not Supported (0x12): Returned if an unsupported sub-function is requested. Incorrect Message Length (0x13): Returned if the message length is incorrect. Conditions Not Correct (0x22): Indicates that the current ECU conditions do not allow for DTC control updates.

Test Scenarios

To validate the functionality of the Control DTC Setting service, several tests were conducted:

Enable DTC Updating: Sends a request to enable DTC updating, expecting a positive response (0xC5) with the echo of sub-function (0x01).

Disable DTC Updating: Sends a request to disable DTC updating, expecting a positive response (0xC5) with the echo of sub-function (0x02).

Unsupported Sub-function: Sends a request with an unsupported sub-function (e.g., 0x03), expecting a negative response with NRC 0x12.

Conditions Not Correct: Tests the scenario where the ECU is not in a session that supports DTC control, expecting NRC 0x22 to indicate incorrect conditions.

9. Response on Event (0x86)

The Response on Event (0x86) service allows a client to configure an ECU to monitor and automatically respond to specific events. This service enables dynamic diagnostic actions triggered by real-time events within the ECU, enhancing responsiveness and adaptability to varying diagnostic conditions.

Start or Stop Event Monitoring: Configure the ECU to start or stop responding to specified events.

Event Type and Window Duration: Define the event type, duration, and any parameters to control the timing and conditions of event-triggered responses.

Event Types Supported:

  • DTC Status Change (0x01): Triggered when there’s a change in DTC status.
  • Timer Interrupt (0x02): Triggered by a timer set at predefined intervals.
  • Data Identifier Change (0x03): Triggered by changes in specified data identifiers.

Implementation Details

Event Control Actions:

  • Start Event (0x05): Initializes the specified event monitoring logic.
  • Stop Event (0x00): Disables all active event monitoring without clearing event configurations.
  • Clear Event (0x06): Completely clears all event configurations.

CAN Communication:

Positive Response (0xC6): Confirms successful event setup or termination.

Negative Response Codes (NRC): Sub-function Not Supported (0x12): Returned if an unsupported event is requested. Incorrect Message Length (0x13): Indicates an invalid message length. Request Out of Range (0x31): Signifies an error in parameters like event type or unsupported DIDs.

Test Scenarios

To verify the Response on Event service functionality, various tests were conducted:

Start Event on DTC Status Change: Starts event monitoring for DTC status changes, expecting a positive response (0xC6) echoing the configured event.

Start Event on Timer Interrupt: Begins event monitoring on a timer interval, with a positive response confirming the event parameters.

Stop Response on Event: Tests disabling event-triggered responses, expecting a confirmation response (0xC6).

Clear Response on Event: Completely clears all configured events, validating that no lingering events remain active.

10. Link Control (0x87) Service

The Link Control (0x87) service is primarily used to control communication parameters (e.g., baud rate) to optimize bus bandwidth for diagnostic purposes, particularly in non-default diagnostic sessions. This feature is crucial during activities such as programming, where high data throughput is essential.

Mode Transition Steps:

Step #1: Verification of the transition capability to ensure the server(s) can handle the requested transition (e.g., higher baud rate). All servers should respond affirmatively before proceeding.

Step #2: Execution of the mode transition. For functional communication, suppressing positive responses is recommended to avoid conflicting states across multiple servers.

Implementation Details

Mode Verification and Transition:

  • Verify Mode with Fixed Parameter: The client requests a verification for a fixed parameter.
  • Verify Mode with Specific Parameter: The client requests a verification for a user-specified parameter.
  • Execute Transition: Once verification is successful, the client initiates the transition to the new mode.

Test Scenarios

To ensure proper implementation of the Link Control service, the following test scenarios were executed:

Verify Mode Transition with Fixed Parameter: Verifies if the server can transition to a fixed communication mode, expecting a positive response echoing the request parameters.

Verify Mode Transition with Specific Parameter: Checks if the server can handle a custom mode parameter transition, receiving a positive response for successful configuration.

Execute Mode Transition: After successful verification, initiates the actual mode transition. Depending on configuration, either a confirmation response or silence (suppressing responses) is expected.

Data Transmission functional unit

1. Read Data by Identifier (0x22)

The Read Data by Identifier (0x22) service allows a client to retrieve specific data records from an ECU, identified by unique Data Identifiers (DIDs). This service enables the client to access information like system status, internal data, and analog/digital signal values as needed for diagnostics.

  • Request and Response: The client requests one or more DIDs, and the ECU responds with the associated data records in a single message, allowing efficient data retrieval.
  • Flexibility: Multiple DIDs can be requested simultaneously, though the ECU may impose limits to avoid overloading.

Implementation Details

  • Positive Response: If the request is valid, the ECU responds with the requested data in a structured format, echoing each DID alongside its respective data.
  • Negative Response: If the request is invalid (e.g., unsupported DID or incorrect message length), the ECU returns an error code (NRC) via CAN to indicate the specific issue.

Test Scenarios

  • Data Retrieval: Tests verify successful data retrieval for single and multiple DIDs.
  • Error Handling: Scenarios such as invalid DID requests and security-restricted DIDs confirm that appropriate error responses are issued, ensuring robust compliance with UDS standards.

2. Read Memory by Address (0x23)

The Read Memory by Address (0x23) service allows the client to request memory data from a specified starting address and for a defined size, enabling the reading of specific memory sections within the ECU for diagnostics.

  • Address and Length Specification: The client specifies the start address and the size of the memory segment. The address and size format are defined by the addressAndLengthFormatIdentifier parameter.
  • Memory Access Control: Supports memory ranges, with potential for secure access restrictions on certain memory areas.

Implementation details

  • Positive Response: Upon a valid request, the ECU sends the requested data from the specified memory location with response identifier 0x63.
  • Negative Response: For invalid requests (e.g., out-of-bounds addresses or access restrictions), the ECU responds with an appropriate error code (NRC) via CAN.

Test Scenarios

  • Memory Access Tests: Verify successful access to different memory locations with varying address sizes.
  • Error Handling: Tests ensure appropriate responses for conditions like incorrect address range, invalid message format, and secure memory access restrictions, adhering to UDS standards.

3. Read Data by Periodic Identifier (0x2A)

The Read Data by Periodic Identifier (0x2A) service allows the client to request periodic transmission of specific data values from the ECU based on specified intervals. This is particularly useful for monitoring dynamic data continuously without multiple requests.

  • Transmission Modes: The client can specify different transmission modes (e.g., slow, medium, fast) for the requested periodic data identifiers.
  • Stop Transmission: The client can stop periodic data transmissions by specifying the stopSending mode, either for specific data identifiers or all of them.

Implementation details

  • Positive Response: An initial positive response (0x6A) confirms the start of periodic transmission, followed by periodic data responses without the service identifier.
  • Negative Response: If conditions aren't met, a negative response (NRC) is sent, addressing issues such as unsupported identifiers or invalid message format.

Test Scenarios

  • Transmission Tests: Verify data transmission for various rates, ensuring that data is sent at the specified intervals.
  • Error Handling: Ensure proper handling of errors like unsupported identifiers, format issues, and security checks, meeting UDS standards for communication reliability.

4. Dynamically Define Data Identifier (0x2C)

The Dynamically Define Data Identifier (0x2C) service enables the client to define a custom data identifier (DID) in the ECU that can group data from other identifiers or memory addresses, enabling later retrieval as a single data block. This flexibility facilitates targeted diagnostics and reduces bandwidth by grouping data into composite records.

  • Define by Identifier: Allows grouping data from existing DIDs, specifying start positions and sizes to create the new identifier.
  • Define by Memory Address: Allows referencing data directly from specific memory addresses.
  • Clear Definition: Clears the custom DID definitions from memory when no longer needed.

Implementation details

  • Positive Response: A response with the new DID confirms successful creation, while a similar response for clear confirms the removal of the DID.
  • Negative Response: Error handling includes checks for invalid DIDs, unsupported sub-functions, or incorrect message lengths.

Test Scenarios

  • Definition Tests: Tests confirm successful DID definition using identifiers and memory addresses, including positive responses for both.
  • Error Handling: Scenarios with unsupported sub-functions, invalid message lengths, and redefined DIDs validate robust error handling, ensuring the ECU's compliance with UDS standards.

5. Write Data By Identifier (0x2E)

The WriteDataByIdentifier (0x2E) service enables a client to write specific data to an ECU location associated with a data identifier (DID). Common use cases include updating configuration data, resetting learned values, or programming option-specific content.

  • Data Identifier (DID): The client specifies the target data location in the ECU using a DID, where data records are written.
  • Security and Access: The service checks if the specified DID allows write access and if security conditions are met.
  • Conditions and Permissions: Specific DIDs may be restricted, read-only, or require certain sessions to allow writing.

Implementation details

  • Positive Response: Confirms successful data writing with the specified DID echoed back.
  • Negative Response: Handles errors like unsupported DIDs, unmet security/access requirements, or incorrect message lengths.

Test Scenarios

  • Successful Write Test: Writes data to a supported DID, confirming the correct positive response.
  • Error Handling Tests: Includes tests for unsupported DIDs, incorrect sessions, unmet security requirements, and incorrect message lengths, ensuring proper negative response handling and compliance with UDS standards.

Stored Data Transmission functional unit

1. Clear Diagnostic Information (0x14)

The ClearDiagnosticInformation (0x14) service enables the client to clear stored diagnostic information within the Electronic Control Unit (ECU). This service allows the client to reset diagnostic data for a specific group of Diagnostic Trouble Codes (DTCs), such as powertrain, chassis, or body, as well as individual DTCs. Clearing diagnostic information can be useful for resetting ECU status after repairs or maintenance.

The service is structured to handle cases where multiple copies of DTC status information exist in the ECU (e.g., in RAM and EEPROM). The ECU is required to clear the primary data used for DTC status reporting while following the designated backup strategy for other copies.

Implementation Details

DTC Group Management: Each DTC group is defined by a groupOfDTC parameter, a 3-byte identifier. Unsupported groups trigger a Request Out of Range (0x31) response.

ECU Response Mechanisms:

  • Positive Response (0x54): Indicates successful DTC clearing, even if no DTCs are stored.
  • Negative Response Codes (NRC):Incorrect Message Length (0x13): Sent if the message length is invalid. Conditions Not Correct (0x22): Triggered if current ECU conditions prevent DTC clearing.General Programming Failure (0x72): Indicates internal errors in the ECU memory.

Test Scenarios

Positive Response for Supported Group: Confirms successful DTC clearing for valid groups, expecting a response (0x54).

2. Read DTC Information Service (0x19)

The ReadDTCInformation service (ID 0x19) is a crucial component within the Unified Diagnostic Services (UDS) suite, designed to provide comprehensive information on Diagnostic Trouble Codes (DTC) stored within the Electronic Control Unit (ECU). This service enables a client to effectively diagnose the condition of various vehicle systems by accessing stored DTCs and extracting specific details about the status, severity, and history of each error code.

Through ReadDTCInformation, the client can:

  • Retrieve general statistics, such as the number of active or archived DTCs.
  • Receive specific details for each DTC, including its status, severity, and snapshot data.
  • Access emissions-related (OBD) error data to verify regulatory compliance.

Sub-Functions of the ReadDTCInformation Service

Each sub-function of the Read DTC Information service addresses a specific request:

REPORT_NUMBER_OF_DTC_BY_STATUS_MASK (0x01): Retrieves the count of DTCs matching a given status mask, providing an overview of active, confirmed, or pending faults.

REPORT_DTC_BY_STATUS_MASK (0x02): Returns a list of DTCs matching a specific status, providing detailed information for each fault, including its code and status.

REPORT_DTC_SNAPSHOT_IDENTIFICATION (0x03): Provides a summary of DTCs with snapshot records, including a capture ID for each DTC to review conditions at the time of detection.

REPORT_DTC_SNAPSHOT_RECORD_BY_DTC_NUMBER (0x04): Returns the snapshot data associated with a specific DTC, allowing examination of values recorded by the ECU at fault detection.

REPORT_DTC_STORED_DATA_BY_RECORD_NUMBER (0x05): Supplies additional recorded data for a specific DTC, such as test and identification data.

REPORT_DTC_EXT_DATA_RECORD_BY_DTC_NUMBER (0x06): Returns extended data associated with a specific DTC, providing advanced diagnostic details.

REPORT_NUMBER_OF_DTC_BY_SEVERITY_MASK (0x07): Counts the number of DTCs matching a specific severity mask.

REPORT_DTC_BY_SEVERITY_MASK_RECORD (0x08): Returns a list of DTCs based on their status and severity, including details for each fault.

REPORT_SEVERITY_INFORMATION_OF_DTC (0x09): Provides severity information for a specific DTC.

REPORT_SUPPORTED_DTC (0x0A): Supplies a list of all DTCs supported by the ECU.

REPORT_FIRST_TEST_FAILED_DTC (0x0B): Returns the first DTC that failed a test.

REPORT_FIRST_CONFIRMED_DTC (0x0C): Provides the first confirmed DTC.

REPORT_MOST_RECENT_TEST_FAILED_DTC (0x0D): Returns the most recent DTC that failed a test.

REPORT_MOST_RECENT_CONFIRMED_DTC (0x0E): Returns the most recently confirmed DTC.

REPORT_MIRROR_MEMORY_DTC_BY_STATUS_MASK (0x0F): Returns the DTCs in the mirror memory matching a specific status mask.

REPORT_MIRROR_MEMORY_DTC_EXT_DATA_RECORD (0x10): Provides extended data for DTCs in mirror memory.

REPORT_NUMBER_OF_MIRROR_MEMORY_DTC_BY_STATUS_MASK (0x11): Counts DTCs in mirror memory based on a status mask.

REPORT_NUMBER_OF_EMISSIONS_OBD_DTC_BY_STATUS_MASK (0x12): Counts emissions-related OBD DTCs that match a status mask.

REPORT_EMISSIONS_OBD_DTC_BY_STATUS_MASK (0x13): Returns OBD-related DTCs based on a status mask.

REPORT_DTC_FAULT_DETECTION_COUNTER (0x14): Provides the fault detection counter for DTCs with a defined occurrence frequency.

REPORT_DTC_WITH_PERMANENT_STATUS (0x15): Returns a list of DTCs with a permanent status.

REPORT_DTC_EXT_DATA_RECORD_BY_RECORD_NUMBER (0x16): Supplies extended data associated with a specific record number.

REPORT_USER_DEF_MEMORY_DTC_BY_STATUS_MASK (0x17): Lists user-defined memory DTCs based on a status mask.

REPORT_USER_DEF_MEMORY_DTC_SNAPSHOT_RECORD (0x18): Provides snapshot records for DTCs in user-defined memory.

REPORT_USER_DEF_MEMORY_DTC_EXT_DATA_RECORD (0x19): Supplies extended data for DTCs in user-defined memory.

REPORT_WWH_OBD_DTC_BY_MASK_RECORD (0x1A): Lists WWH-OBD DTCs based on a mask.

REPORT_WWH_OBD_DTC_WITH_PERMANENT_STATUS (0x1B): Returns WWH-OBD DTCs with permanent status.

Implementation Details

The implementation of the ReadDTCInformation service in the code relies on several key principles:

  • DTC and Sub-Function Management: Each sub-function is implemented as a separate function, allowing for structured and individual testing of each feature. For example, report_number_of_dtc_by_status_mask() counts DTCs based on a given status mask, while report_dtc_snapshot_record_by_dtc_number() retrieves snapshot data.
  • Positive and Negative Responses: The ECU must respond with a positive acknowledgment when the request conditions are met or a negative response with an NRC (Negative Response Code) to indicate errors, such as:
  • Dynamic Memory Management: Some sub-functions, such as REPORT_DTC_BY_STATUS_MASK, require dynamic memory allocation to create space for returned DTCs. Memory allocation includes checks to prevent overflow issues.
  • CAN Communication: Messages are sent mainly over the CAN bus, adhering to an 8-byte-per-message limitation.

Test Scenarios

Each sub-function of the ReadDTCInformation service is tested to validate its correct operation and detect potential errors.

Positive test scenarios validate:

  • Accurate DTC retrieval based on requested parameters.
  • Properly formatted positive responses with correct information.

Negative test scenarios evaluate:

  • Correct negative responses for incorrect message lengths.
  • Appropriate handling of out-of-range requests.
  • Verification that unsupported sub-functions result in error responses.

These tests ensure the robustness and reliability of the Read DTC Information service in diverse diagnostic situations.

InputOutput Control functional unit

1. InputOutputControlByIdentifier (0x2F)

The InputOutputControlByIdentifier (0x2F) service provides the client with the capability to temporarily control or override specific input and output signals within the ECU. This service is typically employed during diagnostics or testing to adjust values for input signals or to force outputs to a desired state. It is ideal for simpler control adjustments, whereas the RoutineControl service may be preferred for more complex operations.

The service works by targeting a specific dataIdentifier, representing input signals, internal functions, or outputs within the ECU. The client sends a control command that can specify multiple parameters if a controlEnableMask is used, allowing for targeted control over individual bits or multiple values within a single data identifier.

Implementation Details

Control Options:

  • Short Term Adjustment: Allows the client to adjust the state of an ECU component temporarily.
  • Return Control to ECU: Restores the ECU’s default control over the targeted input/output signal.
  • Freeze Current State: Maintains the current state for testing without interference from other controls.

Communication Responses:

  • Positive Response: Confirming successful processing of the control command with the dataIdentifier and the control status.
  • Negative Responses: NRC_INCORRECT_MESSAGE_LENGTH (0x13): Triggered for incorrect message formatting. NRC_CONDITIONS_NOT_CORRECT (0x22): Indicates unmet ECU conditions for control. NRC_REQUEST_OUT_OF_RANGE (0x31): Returned when an unsupported dataIdentifier or invalid control option is requested.

Test Scenarios

Various test scenarios validate the functionality and error handling for the InputOutputControlByIdentifier service:

  • Positive Control Tests:

Short Term Adjustment: Verifies that the ECU correctly adjusts an actuator or signal for temporary control.

Return Control to ECU: Confirms that the ECU can reclaim control after testing is complete.

Freeze Current State: Locks parameters at their current state for testing stability.

  • Negative Response Handling:

Unsupported Data Identifiers: Verifies that out-of-range identifiers produce NRC_REQUEST_OUT_OF_RANGE.

Invalid Conditions: Confirms the ECU responds with NRC_CONDITIONS_NOT_CORRECT for unsupported options or states.

The InputOutputControlByIdentifier service is essential for dynamic diagnostic testing, providing effective control over ECU parameters and contributing to comprehensive ECU functionality validation in a controlled testing environment.

Routine functional unit

1. Routine Control (0x31)

The RoutineControl service (ID 0x31) provides the client with the ability to initiate, halt, or retrieve the results of specific routines defined within the ECU. It is commonly used for tasks that require a sequence of operations or specific, controlled behaviors such as memory erasure, resetting adaptive data, executing self-tests, or temporarily taking over certain ECU functions. This service is suited for more complex operations, as compared to the simpler InputOutputControlByIdentifier service.

The RoutineControl service allows the client to:

  • Start a routine: Initiates a pre-defined sequence within the ECU.
  • Stop a routine: Halts the ongoing routine.
  • Request routine results: Retrieves the results generated by a previously executed routine.

These routines, identified by a unique routineIdentifier, can function independently or as part of the ECU’s normal operation. In some cases, the ECU may require an authorized session or specific security access before allowing a routine to start, making this service essential for both diagnostics and maintenance procedures.

Implementation Details

Routine Management:

  • Starting a Routine: Initiates the specified sequence within the ECU, often requiring prior diagnostic session activation or security clearance.
  • Stopping a Routine: Halts the operation of a running routine, enabling controlled transitions within the ECU.
  • Requesting Routine Results: Provides the client with outcomes or exit statuses for previously executed routines.

Response Mechanisms:

  • Positive Response: Confirms successful execution with routine information and status data if applicable.
  • Negative Responses: Sub-function Not Supported (0x12): When an unsupported operation is requested. Incorrect Message Length or Format (0x13): For incorrectly structured messages. Conditions Not Correct (0x22): When prerequisites are unmet. Request Out of Range (0x31): When an unsupported routineIdentifier or invalid parameters are sent. Security Access Denied (0x33): For unauthorized access to secure routines. General Programming Failure (0x72): When the routine encounters internal memory errors.

Test Scenarios

To ensure correct functionality and error handling, multiple test scenarios were executed:

Positive Response Validation:

  • Start Routine: Tests that the ECU can correctly initiate specified routines under valid conditions.
  • Stop Routine: Confirms that active routines can be halted without affecting other ECU functions.
  • Request Routine Results: Verifies that the ECU returns accurate and complete routine results.

Upload Download functional unit

1. Request Download (0x34)

The RequestDownload service (ID 0x34) is designed for initiating data transfers from the client to the server within the ECU. This service prepares the ECU to receive data, setting up the necessary configurations and parameters to ensure the download process operates smoothly. Once a valid request is received, the ECU allocates resources and validates parameters before returning a positive response.

The RequestDownload service allows the client to specify:

  • Data Format Identifier: Defines whether compression or encryption is applied to the data. The standard value is 0x00, which indicates no compression or encryption. Custom values can be implemented based on vehicle manufacturer specifications.
  • Address and Length Format Identifier: Specifies the memory address length and data length within the ECU, encoded in a one-byte value.
  • Memory Address: Specifies the starting memory location within the ECU where data will be written.
  • Memory Size: Represents the total memory allocated for the transfer. This size is validated by the server to ensure data integrity during the TransferData phase.

The RequestDownload service provides a structured approach for secure data transfer, often used for firmware updates, configuration adjustments, or diagnostic information transfer.

Implementation Details

Data and Memory Address Validation:

  • The service validates dataFormatIdentifier, ensuring it matches the client-server configuration.
  • memory Address and memorySize are checked for validity against the ECU's addressable memory, ensuring the specified parameters fit within the allocated space.

Security and Access Control:

  • If the ECU is in a secured state, any unauthorized RequestDownload will result in a negative response, enhancing the safety and integrity of the data transfer.

Test Scenarios

To ensure functionality and robustness, various test scenarios are employed:

  • Positive Response Validation: Confirms that the ECU successfully prepares for data transfer when valid parameters for address, data format, and memory size are provided.

2. Request Upload (0x35)

The RequestUpload service (ID 0x35) is used to initiate data transfers from the ECU (server) to the client, facilitating tasks like retrieving diagnostic data, configuration parameters, or firmware files stored within the ECU. Upon receiving a valid RequestUpload message, the ECU takes necessary preparatory actions before returning a positive response and enabling data transfer.

The RequestUpload service specifies:

  • Data Format Identifier: This one-byte parameter indicates if compression or encryption is applied to the data. A value of 0x00 specifies no additional encoding, while custom values may vary according to vehicle manufacturer requirements.
  • Address and Length Format Identifier: This parameter, in a single byte, encodes the length of the memory address and data size, defining the structure of the data to be uploaded.
  • Memory Address: Specifies the starting memory location within the ECU from which data will be retrieved.
  • Memory Size: Indicates the total data size to be uploaded, validated by the ECU to ensure consistency during the TransferData phase.

This service allows secure data retrieval and structured access to diagnostic or operational data, typically used for system configurations or maintenance tasks.

Implementation Details

  • Data and Memory Address Validation: The service verifies the dataFormatIdentifier against the client-server configuration. The memoryAddress and memorySize parameters are checked for validity within the addressable memory space of the ECU.
  • Security and Access Control: When the ECU is in a secured state, unauthorized requests are denied, reinforcing secure data management.

Test Scenarios

To confirm the functionality and security of the RequestUpload service, several test scenarios are employed:

  • Positive Response Validation: Ensures the ECU responds correctly and prepares for data upload when provided with valid data format, memory address, and memory size parameters.

3. Transfer Data (0x36)

Transfer Data (0x36) The TransferData service (ID 0x36) facilitates data exchange between the client and the server in an ECU, supporting both download (client to server) and upload (server to client) operations. This service is part of a data transfer sequence that follows a RequestDownload or RequestUpload initiation, making it an essential element in firmware updates, memory operations, or diagnostic data retrieval.

The TransferData service uses:

  • Block Sequence Counter: This counter initiates at 0x01 for the first TransferData request and increments with each subsequent data packet, rolling over after reaching 0xFF. It allows the server to recognize retransmissions and provides reliable error handling.
  • Transfer Request/Response Parameters: In download mode, these parameters include data to be written to the ECU’s memory. In upload mode, they represent the data retrieved from the ECU.

Implementation Details

  • Data Sequence Handling:

The server initializes the blockSequenceCounter at the start of each RequestDownload or RequestUpload.

When errors or timeouts occur, the blockSequenceCounter assists the server in distinguishing new transmissions from repeated requests, enabling efficient retransmission handling.

  • Error Handling:

If a TransferData request arrives out of sequence, a "Wrong Block Sequence Counter" (NRC) is issued.

If the message is incorrectly formatted or the transfer conditions are unmet, the ECU returns an appropriate error response, such as Incorrect Message Length or Request Sequence Error.

Test Scenarios

Several test scenarios ensure the reliability of the TransferData service:

  • Positive Response Verification: Validates that the server accepts sequential TransferData messages and responds with the correct block sequence counter.
  • Error Scenarios: Includes tests for improper message lengths, sequence errors, and block sequence mismatches to confirm the ECU's ability to handle and recover from transmission issues.

4. Request Transfer Exit (0x37)

Request Transfer Exit (0x37) The RequestTransferExit service (ID 0x37) is used by the client to terminate an ongoing data transfer between the client and the server within the ECU. It finalizes either an upload or download session, allowing the server to complete any necessary post-transfer actions, such as validation or storage of received data.

  • Transfer Request Parameter Record: This field includes parameters that the server may require to complete the transfer process. The format and length of this field are specific to the vehicle manufacturer.

Implementation Details

  • Finalization and Validation:

The server validates that the request is received while a data transfer is active. If not, a "Request Sequence Error" is returned, indicating that no active transfer session exists.

The transferRequestParameterRecord is validated to confirm its integrity and suitability for the server’s specific post-transfer requirements.

  • Error Handling:

If the message length is incorrect or improperly formatted, the server responds with an "Incorrect Message Length" error.

If the provided parameters are invalid or outside the acceptable range, the server issues a "Request Out of Range" response.

Any issues detected during finalization, such as integrity check failures, will result in a "General Programming Failure" error code.

Test Scenarios

Several test cases validate the robustness of the RequestTransferExit service:

  • Successful Termination: Confirms that the ECU completes the data transfer with valid parameters and returns a positive response.
  • Error in Request Sequence: Ensures that the ECU detects and reports errors if no active transfer session is in progress when RequestTransferExit is received.
  • Parameter Validation: Tests for invalid or out-of-range parameters, ensuring that appropriate error codes are returned.

5. Request File Transfer (0x38)

The RequestFileTransfer service (ID 0x38) allows a client to initiate file transfers between the client and server in either direction, enabling file upload, download, and directory management. It serves as an alternative to RequestDownload and RequestUpload for ECUs that support file systems, and it includes additional operations, such as file deletion and directory retrieval.

  • Mode of Operation: Defines the action for the specified file or directory, such as adding, deleting, replacing, or reading files.
  • File Path and Name: Specifies the file location within the server’s file system, detailing the path and name of the file or directory.
  • Data Format Identifier: Identifies data compression and encryption methods.
  • File Size Parameters: Specifies the size of both compressed and uncompressed files, if applicable.

Implementation Details

File Operation Modes:

  • Operations are defined based on modeOfOperation, such as adding, deleting, and reading files or directories.
  • Mode validation is essential, as only values between 0x01 to 0x05 are allowed.

Positive Response:

  • On a valid request, the server sends a positive response indicating modeOfOperation and other file size or directory information parameters, if required.

Error Handling:

  • If the message length, mode, or any specified parameter is invalid, the server responds with the appropriate Negative Response Code (NRC) to indicate errors, such as Incorrect Message Length or Request Out of Range.

Test Scenarios

To ensure robust performance, the following test cases are applied:

  • Valid File Transfer Initiation: Ensures the server correctly initiates file transfers with valid paths, mode, and file parameters.
  • Invalid Length Handling: Confirms that the server returns an error when the message length is incorrect.
  • Mode of Operation Validation: Ensures that modes outside the allowed range return a Request Out of Range error.

?

Conclusion

The Unified Diagnostic Services (UDS) protocol is a cornerstone in managing the embedded systems of modern vehicles. Governed by the ISO 14229-1 standard, UDS unifies and simplifies diagnostics, maintenance, and reprogramming of Electronic Control Units (ECUs). With a rigorous structure of services, UDS ensures reliable and secure communication between diagnostic tools and ECUs, enhancing fault detection, precise troubleshooting, and maintenance cost optimization. As vehicles become increasingly connected and automated, the UDS protocol continues to evolve to meet the growing demands for remote diagnostics and enhanced security, making it an indispensable asset for the automotive industry.

?

DHANAPAL SOLAIMUTHU

Senior Engineer - PES I Diagnostics Developer and Tester for EV, ICE | Testing and Validation | AUTOSAR Configurator COM, DEM | .cdd | CANoe | Automotive Ethernet | DoIP | CAN | OBD II | UDS | J1939

4 个月

Great job!!

回复

Very Helpful! Thanks for sharing

回复
Duong TRAN ????

Technical (Project/Department) Manager | Senior Team Leader | Senior R&D Engineer | +20 Years Experience

4 个月

An good article written about UDS protocol. Thanks for sharing your knowledge ??

回复
Imane BOUGRINE

Automotive Diagnostic Engineer | Diagnostic Subdomain Lead @ Stellantis

4 个月

Very informative, thanks for sharing! I noticed that Read Scaling Data By Identifier (0x24) and Write Memory By Address (0x3D) weren’t mentioned. Also, which version of ISO 14229 did you reference? as the Access Timing Parameters (0x83) service doesn’t appear in the latest published version (2020)

Younesse Z.

Software Integration Engineer at Stellantis | IoT and Embedded Systems Development enginner

4 个月

Good job ????

回复

要查看或添加评论,请登录

NIZAR MOJAB的更多文章

社区洞察

其他会员也浏览了