Что такое uds протокол

Протокол UDS

Протокол UDS – это “язык” на котором общается диагностическое оборудование. Протокол UDS может работать на различных физических шинах: K-Line, CAN, Ethernet, FlexRay. В этой статье мы рассмотрим механизм работы протокола UDS на шине CAN, как самый распространенный вариант в настоящее время. Рассматривать вопрос будем с практической точки зрения для быстроты восприятия материала. Подробно протокол описан в стандарте ISO-15765.

По протоколу UDS возможно не только считать\стереть коды ошибок – DTC, но и запросить текущие параметры датчиков и блоков управления (ECU), а так же давать команды исполнительным механизмам (например открыть\закрыть центральный замок).
Кроме того с помощью этого протокола осуществляется прошивка блоков управления.

В своей базе протокол UDS строится на транспортном протоколе TP. Транспортном не в смысле его применения на транспорте, а в том смысле что протокол предназначен для транспортировки данных по некоторому каналу передачи.

Описание транспортного протокола TP

Фрейм транспортного протокола строится по следующей схеме:
Что такое uds протокол. Смотреть фото Что такое uds протокол. Смотреть картинку Что такое uds протокол. Картинка про Что такое uds протокол. Фото Что такое uds протокол

TA – Target Address или адрес получателя фрейма
SA – Source address или адрес отправителя фрейма
PCI – Поле в котором кодируется количество передаваемых байт и тип фрейма.

В реализации протокола UDS работающего поверх CAN шины адрес источника не указывается в заголовке фрейма, а адресом получателя является CAN ID всего фрейма.
Например в CAN сообщении 0x7E0 02 09 02 00 00 00 00 00 00 адресатом будет блок управления двигателем, адрес которого равен =0x7E0.

Типы фреймов

Single Frame SF – Однократный фрейм. Фрейм вся информация которого умещается в один CAN пакет.
Что такое uds протокол. Смотреть фото Что такое uds протокол. Смотреть картинку Что такое uds протокол. Картинка про Что такое uds протокол. Фото Что такое uds протокол

First Frame FF – Первый фрейм из серии фреймов
Что такое uds протокол. Смотреть фото Что такое uds протокол. Смотреть картинку Что такое uds протокол. Картинка про Что такое uds протокол. Фото Что такое uds протокол

Поле PCI занимает два байта: Нулевой и первый. 7 бит первого байта и 3 первых бита нулевого байта определяют длину сообщения – максимум 2048 байта.
Четвертый бит нулевого байта равный 1 указывает на то что это First Frame.

Пример: 0x7E8 10 14 49 02 01 57 41 55
PCI = 10 14. First frame. Длина поля данных 0x14 или 20 байт.
DATA: 49 02 01 57 41 55 – шесть байт
Таким образом после этого фрейма должно быть отправлено еще 2 фрейма с нагрузкой по 7 байт данных на каждый, чтобы получилось суммарно 20 байт.

Consecutive Frame CF – последующий фрейм. Каждый фрейм следующий за First Frame от одного отправителя.
Что такое uds протокол. Смотреть фото Что такое uds протокол. Смотреть картинку Что такое uds протокол. Картинка про Что такое uds протокол. Фото Что такое uds протокол

Поле PCI занимает нулевой байт. Старшая половина байта =0x2 и указывает на то что перед нами CF фрейм. Младшая половина указывает порядковый номер CF фрейма от 0x0 до 0xF.
Пример: 0x7E8 21 5A 5A 5A 38 45 37 37
PCI=0x21. Тип фрейма – CF, номер фрейма =1

Flow control Frame – FC – фрейм управления потоком. Отправляется получателем в ответ на First Frame
Что такое uds протокол. Смотреть фото Что такое uds протокол. Смотреть картинку Что такое uds протокол. Картинка про Что такое uds протокол. Фото Что такое uds протокол

FC фрейм служит для управления потоком в случае если используется поток фреймов First Frame-Consicutive Frames.
PCI занимает три байта: Нулевой, первый, второй.
Заголовок 0x3 в заголовке поля PCI указывает что это FC фрейм.
Flow Status говорит отправителю First Frame о статусе получателя 00- Готов к приему CF фреймов, 01- Жди, 02 – Переполнение.
Block Size определяет количество СF фреймов которые готов принять получателю. В некоторых может быть равно нулю и протокол все равно будет работать.
Minimum Separation Time в миллисекундах, задает минимальное время между передаваемыми CF фреймов.

Пример 1: 0x7E0 30 02 00 00 00 00 00 00
FC фрейм.
Готов принять 2 CF фрейма.
С минимальным временем между CF фреймами = 0 миллисекунд.

Пример 2: 0x778 30 08 05 AA AA AA AA AA
FC фрейм
Готово принять 8 CF фреймов
С минимальной задержкой 5 миллисекунд

Такой же пример на конкретных данных.
ID Отправителя = 0x7CE
ID Получателя = 0x7C6
Отправитель передает массив данных размером 0xB5 или 181 байт получателю. На изображении представлен НЕ весь массив!
Что такое uds протокол. Смотреть фото Что такое uds протокол. Смотреть картинку Что такое uds протокол. Картинка про Что такое uds протокол. Фото Что такое uds протокол

Фрейм UDS

Фреймы диагностического протокола UDS строятся поверх транспортных фреймов и выглядят так:
Что такое uds протокол. Смотреть фото Что такое uds протокол. Смотреть картинку Что такое uds протокол. Картинка про Что такое uds протокол. Фото Что такое uds протокол

Где – SID – идентификатор сервиса. (запрос DTC, запрос текущих параметров, команды…)
PID\LEV – Номер запрашиваемого параметра или номер вызываемой функции.

Пример
Запрос
CAN DLC=8 DATA: 03 22 22 06 00 00 00 00
SID = 0x22
PID = 22 06
Положительный ответ
CAN ID=0x77E DLC=8 DATA: 04 62 22 06 9A 00 00 00
SID+0x40 = 0x62
PID = 22 06
Response parameter =0x9A

Подробный разбор конкретных примеров использования протокола UDS

Пример 1. Запрос VIN номера

1 Диагностический прибор: DLC=8 DATA: 02 09 02 00 00 00 00 00
2 Ответ автомобиля: DLC=8 DATA: 10 14 49 02 01 57 41 55 “WAU”
3 Диагностический прибор: DLC=8 DATA: 30 02 00 00 00 00 00 00
4 Ответ автомобиля: DLC=8 DATA: 21 5A 5A 5A 38 45 37 37 “ZZZ8E77”
5 Ответ автомобиля: DLC=8 DATA: 22 41 30 37 37 37 37 32 “A077772”


Запрос от диагностического прибора
ID=0x7E0 DLC=8 DATA: 02 09 02 00 00 00 00 00

Ответ ECU: DLC=8 DATA: 10 14 49 02 01 57 41 55

Запрос от диагностического прибора ID=0x7E0 DLC=8 DATA: 30 02 00 00 00 00 00 00

Байт 0: 0x30 – Flow control. Команда блоку управления выдать все байты данных запрашиваемого параметра блоком из двух CF фреймов с минимальной задержкой 0 миллисекунд.

Ответ ECU: DLC=8 DATA: 21 5A 5A 5A 38 45 37 37
Ответ ECU: DLC=8 DATA: 22 30 37 37 37 37 37 32

Затем блок управления отдает все байты данных запрашиваемого параметрах, которые упакованы в необходимое число CF фреймов. В описываемом примере таких фрейма два.

Байт 0: 0x21, 0x22 – номера CF фреймов в серии.

Байты 1…7: Байты данных запрашиваемого параметра.

Пример 2. Запрос уровня топлива

Рассмотрим более простой пример – запрос уровня топлива по протоколу UDS у панели приборов автомобиля VW Touareg NF.

1 Диагностический прибор: DLC=8 DATA: 03 22 22 06 00 00 00 00
2 Ответ автомобиля: ID=0x77E DLC=8 DATA: 04 62 22 06 9A 00 00 00

Запрос от диагностического прибора ID=0x714 DLC=8 DATA: 03 22 22 02 00 00 00 00

Ответ ECU: DLC=8 DATA: 04 62 22 06 9A 00 00 00

Пример 3. Команда активации исполнительного механизма

В качестве примера команды активации исполнительного механизма рассмотрим управление приводом центрального замка автомобилей Renault.

В этом случае мы видим использование уже двух команд: Открытие сессии и команда на закрытие замка. Очень часто команды на управление исполнительными механизмами требуют открытия сессии расширенного диагностического режима.

Таблица сервисов доступных в протоколе UDS

В таблице представлены сервисы которые заложены в протокол. Не все блоки управления поддерживают полный набор сервисов.

Источник

Хакаем CAN шину авто. Мобильное приложение вместо панели приборов

Я продолжаю изучать CAN шину авто. В предыдущих статьях я голосом открывал окна в машине и собирал виртуальную панель приборов на RPi. Теперь я разрабатываю мобильное приложение VAG Virtual Cockpit, которое должно полностью заменить приборную панель любой модели VW/Audi/Skoda/Seat. Работает оно так: телефон подключается к ELM327 адаптеру по Wi-Fi или Bluetooth и отправляет диагностические запросы в CAN шину, в ответ получает информацию о датчиках.

По ходу разработки мобильного приложения пришлось узнать, что разные электронные блоки управления (двигателя, трансмиссии, приборной панели и др.) подключенные к CAN шине могут использовать разные протоколы для диагностики, а именно UDS и KWP2000 в обертке из VW Transport Protocol 2.0.

Программный сниффер VCDS

Чтобы узнать по какому протоколу общаются электронные блоки я использовал специальную версию VCDS с программным сниффером в комплекте. В этот раз никаких железных снифферов на Arduino или RPi не пришлось изобретать. С помощью CAN-Sniffer можно подсмотреть общение между VCDS и автомобилем, чтобы затем телефон мог прикинуться диагностической утилитой и отправлять те же самые запросы.

Я собрал некоторую статистику по использованию диагностических протоколов на разных моделях автомобилей:

Протокол UDS

Что такое uds протокол. Смотреть фото Что такое uds протокол. Смотреть картинку Что такое uds протокол. Картинка про Что такое uds протокол. Фото Что такое uds протоколДиагностические данные от двигателя по протоколу UDS (Skoda Octavia A7)

В моей машине (Skoda Octavia A5) приборка использует UDS протокол, это дало мне легкий старт разработки, т.к. данные были в простом формате Single Frame SF (фрейм, вся информация которого умещается в один CAN пакет) и большинство значений легко поддавались расшифровке. Volkswagen не дает документацию на формат значений, поэтому формулу расшифровки для каждого датчика приходилось подбирать методом логического мышления. Про UDS протокол очень хорошо и с подробным разбором фреймов написано на canhacker.ru.

Что такое uds протокол. Смотреть фото Что такое uds протокол. Смотреть картинку Что такое uds протокол. Картинка про Что такое uds протокол. Фото Что такое uds протоколРазбор UDS пакета в формате Single Frame

Пример запроса и ответа температуры моторного масла:

Запрос температуры моторного масла:

Ответ температуры моторного масла:

Первая версия мобильного приложения VAG Virtual Cockpit умела подключаться только к приборной панели по UDS.

VW Transport Protocol 2.0

Т.к. KWP2000 использует сообщения переменной длины, а CAN шина позволяет передавать сообщения не больше 8 байт, то VW TP 2.0 разбивает длинное сообщение KWP2000 на части при отправке по CAN шине и собирает заново при получении.

Что такое uds протокол. Смотреть фото Что такое uds протокол. Смотреть картинку Что такое uds протокол. Картинка про Что такое uds протокол. Фото Что такое uds протоколДиагностические данные от двигателя по протоколу KWP2000 (Skoda Octavia A5)

ЭБУ двигателя моей машины использует протокол VW TP 2.0, поэтому мне пришлось изучить его. Видимо Volkswagen разрабатывала транспортный протокол не только для работы по надежной CAN шине, но и для менее надежных линий связи, иначе нет объяснения для чего требуется такая избыточная проверка целостности данных. Главным источником информации по VW TP 2.0 является сайт https://jazdw.net/tp20.

Разбор протокола VW TP 2.0 на примере подключения к первой группе двигателя:

200 01 C0 00 10 00 03 01

201 00 D0 00 03 40 07 01

740 A0 0F 8A FF 32 FF

Настраиваем ЭБУ на отправку сразу 16 пакетов и выставляем временные параметры

300 A1 0F 8A FF 4A FF

Получили положительный ответ

740 10 00 02 10 89

Получили первый ACK

300 10 00 02 50 89

Мы отправили первый ACK, что получили ответ

740 11 00 02 21 01

Получили второй ACK

300 22 00 1A 61 01 01 C8 13

300 23 05 0A 99 14 32 86 10

300 24 FF BE 25 00 00 25 00

300 15 00 25 00 00 25 00 00

Отправляем ACK. Прибывляем к нашему предыдущему ACK количество полученных пакетов 0xB1 + 0x4 = 0xB5

Запрос KeepAlive, что мы еще на связи

740 A1 0F 8A FF 4A FF

Мы разрываем связь

ЭБУ в ответ тоже разрывает связь

Во второй версии мобильного приложения VAG Virtual Cockpit появилась возможность диагностировать двигатель и трансмиссию по протоколу VW TP 2.0.

Диагностический адаптер ELM327

Для меня некоторое время было вопросом, как получить данные из CAN шины и передать на телефон. Можно было бы разработать собственный шлюз с Wi-Fi или Bluetooth, как это делают производители сигнализаций, например Starline. Но изучив документацию на популярный автомобильный сканер ELM327 понял, что его можно настроить с помощью AT команд на доступ к CAN шине.

Что такое uds протокол. Смотреть фото Что такое uds протокол. Смотреть картинку Что такое uds протокол. Картинка про Что такое uds протокол. Фото Что такое uds протоколКопия диагностического сканера ELM327 Не все ELM327 одинаково полезны

Оригинальный ELM327 от компании elmelectronics стоит порядка 50$, в России я таких не встречал в продаже. У нас продаются только китайские копии/подделки, разного качества и цены 10-30$. Бывают полноценные копии, которые поддерживают все протоколы, а бывают и те которые умеют отвечать только на несколько команд, остальные игнорируют, такие адаптеры не имеют доступ к CAN шине. Я например пользуюсь копией Viecar BLE 4.0, который поддерживает 100% всех функций оригинала.

Для работы с протоколом UDS через ELM327 нужно указать адреса назначения, источника и разрешить длинные 8 байтные сообщения, по умолчанию пропускается максимум 7 байт.

Последовательность ELM327 AT команд для работы с UDS по CAN шине:

Для работы с протоколом KWP2000 через ELM327 нужно только указать адреса назначения и источника.

Последовательность ELM327 AT команд для работы с VW TP 2.0 по CAN шине:

Мобильное приложение VAG Virtual Cockpit

Для разработки мобильного приложения подключаемого к автомобилю требовалось:

Сниффером собрать трафик от диагностической утилиты VCDS

Изучить работу протоколов UDS, VW TP 2.0, KWP2000

Настроить диагностический сканер ELM327 на работу с UDS и VW TP 2.0

Изучить новый для меня язык программирования Swift

Что такое uds протокол. Смотреть фото Что такое uds протокол. Смотреть картинку Что такое uds протокол. Картинка про Что такое uds протокол. Фото Что такое uds протоколМобильное приложение VAG Virtual Cockpit для iOS

В итоге получилось приложение, которое сочетает в себе функции отображения точных данных панели приборов и диагностика основных параметров двигателя и трансмиссии.

На данный момент приложение показывает следующие параметры:

Приборная панель

Двигатель

Трансмиссия (температура)

1) Какая дверь открыта
2) Скорость
3) Обороты
4) Температура масла
5) Температура ОЖ
6) Топливо в баке в л.
7) Запас хода в км.
8) Средний расход
9) Время в машине
10) Пробег
11) Температура за бортом

1) Обороты
2) Массовый расход воздуха
3) Температура забора воздуха
4) Температура выхлопа (рассчитанная)
5) Критический уровень масла
6) Уровень масла
7) Наддув турбины (реальный)
8) Наддув турбины (ожидаемый)
9) Пропуски зажигания в цилиндрах
10) Углы откатов зажигания в цилиндрах

1) ATF AISIN (G93)
2) DSG6 (G93)
3) Блок управления DSG6 (G510)
4) Масло диска сцепления DSG6 (G509)
5) Мехатроник DSG7 (G510)
6) Процессор DSG7
7) Диск сцепления DSG7

Я стремлюсь чтобы приложение поддерживало как можно больше моделей автомобилей. Пока что поддерживаются производители: Volkswagen, Skoda, Seat, Audi. На разных комплектациях могут отображаться не все параметры, но это поправимо.

Сейчас я провожу тестирование версии 3.0. Приложение доступно только на iOS, после релиза 3.0 перейду к разработке версии для Android.

Если интересно потестировать и есть желание принять участие в проекте, то установить приложение можно по ссылке. Также я веду бортжурнал на drive2.ru, где делюсь полезной информацией и новостями о VAG Virtual Cockpit.

Источник

UDS Protocol

UDS Protocol Tutorial

This UDS Protocol tutorial will give you the best UDS protocol knowledge on the ISO-14229 standard. Which will help you in your career to get a good opportunity in the automotive field? The SAE planned to add diagnostic functionality in every vehicle for safety and maintenance purposes.

So if you have done your engineering and trying to get a job in the Automotive field? or working in some other field and are interested to change into the automotive field? or want to learn deep knowledge as you are going to implement UDS protocol in your company? then this is the best place to learn and work either in the Embedded automotive Development or testing field.

This UDS protocol is very famous in the name of Diagnostic Communication Manager (DCM). It is mostly used in AUTOSAR layered software architecture.

Introduction to UDS Protocol

The UDS Protocol is the latest automotive vehicle diagnostic protocol used to diagnose any vehicle all over the world. This protocol is defined in ISO-14229 standard so that every automobile OEM will follow this standard to provide a very common computer system that can be used to diagnose any vehicle. But before that, I want to clear your doubt what is the difference between the communication protocol and diagnostic protocol.

The communication protocol is used to communicate between two or more machines or computers. In the automotive field, we are saying it ECU. So here we will be using as ECU so don’t be confused. If you have any health issues as a human you can understand and get cured after taking a solution from a doctor.

UDS Implementation In Automotive ECU

But how a machine can explain what is the problem in its processor or any I/O peripheral, or any short circuit or anything. So to get this feature in a machine we can write some diagnostic programs which can run periodically inside the processor and if there is any fault nothing but the DTC and it can store in the Non-Volatile memory of the processor so that later the human can read this and to repair the vehicle easily.

So to make this possible in ECU, ISO technical Committee and SAE Committee made this standard that having different services and subfunctions to identify and run these services by requesting these service commands from any computer system and get the results. So that the ECUs also can tell the human what is the problem inside it to fix it easily.

ISO-14229 Standards Available

The UDS protocol specification is defined in different sub-standards of ISO 14229. The ISO-14229 Standard UDS Protocol consists of the following parts, under the general title Road vehicles — Unified diagnostic services (UDS):

How UDS Protocol Does diagnostic?

Let me explain to you a story for new engineers to understand. Suppose you are a human and if you have any health issues you are going to the hospital. In the hospital, there are different floors for different diagnostic purposes. As you can say the first floor is for General or emergency purposes, The 2nd floor is for diagnostic centers where each room is for different services like blood, skin, eye, etc. 3rd floor is for Operation Center, the 4th floor is for safety as you can say before happening anything you can take protection from doctor to not happen anything.

The same scenario can also happen in the machine, so resolve this the diagnostic protocol needs. So that any human or another machine can do the diagnostic on another machine using this protocol called as UDS Protocol

What is UDS Protocol?

The UDS protocol is a diagnostic protocol used in Automotive Vehicles to find the cause of a problem for the health check. Basically, it is used in the automotive field for vehicle diagnostic, ECU new software flashing, etc. Nowadays the use of the protocol is increasing due to its flexibility. This protocol is defined in ISO-14229-1 standard and it is derived from the ISO 14230-3 (KWP-2000) and ISO 15765-3 (Diagnostic Communication over the CAN (DoCAN).

The UDS protocol services are using the 5th (Session layer) and 7th (Application) layer of the OSI model while the CAN protocol works on the 1st (Physical) and 2nd (Data Link layer) layer of the OSI model. Basically, the UDS protocol is working on the CAN protocol for the communication between the client by request and server by a response to do the diagnostic on the server by request and which we are telling as Diagnostic over CAN (DoCAN).

Why Diagnostic need in a vehicle?

When any problem is happening with a human and he is going to the hospital to do the diagnostic and getting a solution, like this for a vehicle also it needs to be diagnostic as to inform the human about his problem such as:

UDS Protocol Physical and Functional Addressing:

There is a possibility for the diagnostic tester (client) to send physical or functional UDS requests. A functional request is a broadcast-type message which will be sent to all ECUs which are on the CAN network. The Physical UDS-requests are only sent to a single ECU on the network. Suppose already you know in which module or ECU the faults are happening, then the diagnostic engineer in the service center can directly connect to that ECU to send the diagnostic request (Physical addressing) and read the diagnostic data, and fix the issue.

If the engineer doesn’t know where is the fault happening obviously he will be sending the request (Functional addressing) globally to all the ECU available in the vehicle, read all the active DTC, and fix it. The UDS Protocol uses both the addressing method to give a spontaneous interface to the tester for easy diagnostic.

Session Layer Timings In The UDS-standard:

Contained within the UDS standard there is a standard governing the session layer services in the Open Systems Interconnection (OSI)-model called ISO 14229-2 nothing but UDS Protocol. The most important session layer timings in this project are the P2 and P2 extended timings that specify the maximum time the server (ECU) or client (tester) has to wait or respond to the UDS request.

These values are communicated by the ECU through the UDS-response to the Diagnostic Session Control service. The P2 specifies the default timing which should be used, the ECU has, however, the option to send an NRC 0x78, then the P2 extended timing value will be maximum time, which is the server (ECU) has to respond?

UDS Protocol Frame Format

Since the UDS protocol is working on the CAN protocol so that the maximum 8-bytes of the data can be requested and get to the response in a message. Like CAN protocol, in UDS protocol, there are 2-types of frames are available. The UDS protocol frame format is defined below.

Again the Response frame is divided into two types:

UDS Protocol Request Frame Format:

Whenever the client wants to request anything from the data then the tester will send this request the frame to get the response from the server on the CAN data field. This frame had consisted of 3 fields:

NOTE: D1=BIT7(POSRESPONSEINDICATIONBIT) +SUB-FUNCTION ID(BIT0…BIT6)

UDS Protocol Response Frame Format:

Whenever a diagnostic engineer or tester will request any service to a vehicle, there is a possibility of two types of response from the vehicle or a particular ECU as per physical or functional request type.

Positive Response Frame Format:

Whenever the tester will request to the server if it is correct and the server has been executed the request successfully, then it will send the response message concerning this request by adding 0x40 to the respective service ID for reference. Positive response 1st byte should be Request Service ID + 0x40.

Negative Response Frame Format:

If the client did not request in a proper frame format or the server is not able to execute the request due to the internal problem, then it will send a negative response to the client.

Here I will explain only about the UDS frame format, if you are thinking to know more or total frame format like as I told you can not communicate using this protocol for that you need to use any communication protocol like as: CAN, LIN, etc. then you can read my Diagnostic Over CAN (DoCAN) Tutorial.

UDS Protocol Architecture

Those services allow a tester (client) to control diagnostic functions in an on-vehicle Electronic Control Unit (server) applied for example on the electronic fuel injection, automatic gearbox, anti-lock braking system, etc., connected on a serial data link embedded in a road vehicle.

Furthermore, this part of the standard specifies generic services that allow the diagnostic tester (client) to store or to resume non-diagnostic message transmission on the data link. However, part 1 of the standard does not specify any implementation requirements. Figure 7 shows a general configuration of the client-server connection within a vehicle network.

Что такое uds протокол. Смотреть фото Что такое uds протокол. Смотреть картинку Что такое uds протокол. Картинка про Что такое uds протокол. Фото Что такое uds протоколClient-Server Communication in Vehicle

For vehicle 3, the servers are directly connected to the diagnostic data link, and vehicle 4 connects its server/gateway directly to the vehicle 3 server/gateway. For vehicle 4, the servers are connected over an internal data link and indirectly connected to the diagnostic data link through the gateways. ISO 14229-1 or UDS Protocol applies to the diagnostic communications over the diagnostic data link; the diagnostic communications over the internal data link may conform to the same or another protocol.

The server, usually a function that is part of the ECU, uses the application layer services to send response data, provided by the requested diagnostic service back to the client. The client is usually referred to as an External Test Equipment when it is off-board but can in some systems, also be an on-board tester. The usage of the application layer services is independent of the client being an off-board or on-board tester. It is a possibility to have more than one client on the same vehicle system.

The most typical network configuration of the client-server communication for the vehicle diagnostics: the client as an Off-board tester. Communication is based on a request-response model. In the context of diagnostics, the following concepts are useful for a better understanding of the semantics handled on the UDS standard environment:

UDS Protocol Stack

As stated before, UDS is independent of lower-layer protocols. therefore, car diagnostics could be executed, for example, by using the Unified Diagnostic Services (UDS) on top at an application layer-level, generic network layer services at an intermediate level and employing the means of the controller area networks (CAN) or another communication bus protocol (like LIN, FlexRay or Ethernet) for the data link and physical layers’ levels, at lower stages.

Such an approach is compliant with the generic OSI model for the networks. Figure 9 shows the hierarchical arrangement of layers for the implementation of diagnostic services over the CAN according to standard ISO-15765-3.

When executing diagnostics over the CAN, the Client (diagnostic tester) initiates a request and waits for confirmation. The server (function in ECU) then receives the indication and sends a response.

Functions of Diagnostic Services In UDS Protocol

Besides specifying services’ primitives and protocols that describe the client-server interaction, UDS also defines within its framework several functional units that comprise several services each, identified with a hexadecimal code. These units are intended for the different individual purposes that support the overall diagnostic function/task. The UDS protocol having different services for the different types of work tasks to do on the server. These are having 6- types as:

Each functional group has more than one service ID for different-2 tasks so to get the detail of the above functional group and related services.

Diagnostic and communication management:

There are 10 services are available in this module to control the diagnostic and the communication-related in the ECU.

Diagnostic Session Control (0x10):

The heart of the UDS Protocol is the Diagnostic session control service. The diagnostic session control is the main door of the diagnostic server in the ECU by which the tester or the diagnostic engineer will enter into the diagnostic lab of the server and be able to take the decision that what is the status of the problem and to which session he has to go to do the session.

Basically, this service is used to enable the different diagnostic sessions in the server to work on it. In every session, they have defined some diagnostic services which only enable these sessions so that they will work perfectly without any negative impact on the server.

Basically, most of the OEMs are using 3-4 Sub-functions which are really important and we are also going to discuss only those here. mostly if you have any other doubt or any query please search to get in my blog post and Q&A forum page even if you can also write to us at [email protected]

Default Session (0x01)

Whenever any ECU will get powered on, the ECU will be activated with the default diagnostic session. In this session, only some basic diagnostic functionalities will have access that can be executed at the run time means if the vehicle is running you can do these tasks without any hamper or disturbance of the run time vehicle. Let’s go discuss the request and response frame format details as to how it is really working or implemented by a developer.

PCISIDSBFDB4DB3DB2DB1DB0
0210010000000000

Default session Request message from Client to Server

Here I will explain the byte from left to right for better understanding, so please don’t make confusion yourself.

Where 1st byte is: 02–> PCI (Protocol Control Information) byte for CAN-TP.

The MSB 4-bit –> 0x0 –> CAN-TP frame type & 0x2 –> LSB 4-bit –> DLC.

2nd byte: SID –> 0x10

3rd byte: Sub-function –> 01.

Since for this request, 2-byte is sufficient, and 1-byte is used for PCI, except 3-byte others are not required.

NOTE: If you are not understanding what is PCI and CAN-TP please search in my main menu for CAN-TP, first learn the CAN-TP protocol and then come to this page for UDS protocol. Normally before learning this protocol, first you need to know the CAN protocol and CAN-TP protocol. If any doubt then you can comment in the comment below, else can send me the mail at [email protected]

UDS Response: Server –>Client:

Positive Response:

065001001907D000

Default session response from Server to Client

Byte [1]: 06 –> PCI (Protocol Control Information) byte for CAN-TP.

The MSB 4-bit –> 0x0 –> CAN-TP frame type & 0x6 –> LSB 4-bit –> DLC.

Byte [2]: SID –> 0x50 (Positive response = Request SID + 0x40).

Byte 4: P2 Server timing parameter (0x19 –> 25 ms in decimal).

Byte 7: P2* Server timing parameter (0x7D0 –> 2 second in decimal).

Negative Response:

037F1012/13/2200000000

Negative Response Frame For Diagnostic Session Control Service

Where 1st byte is: 04 –> PCI (Protocol Control Information) byte for CAN-TP.

The MSB 4-bit –> 0x0 –> CAN-TP frame type & 0x4 –> LSB 4-bit –> DLC.

3rd byte: 0x10 –> SID.

4th byte: 0x1 –> SFID.

Diagnostic Session Control Request message layout:

Data byteParameter nameHex value
0PCI0x01
1Diagnostic Session Request Service ID0x10
2Diagnostic Session Type0x01-0x05

Example: Request Programming Session:

Byte01234567
Value0x010x100x020x550x550x550x550x55

NOTE: All the negative response ID is defined below.

ECU Reset Service Identifier (0x11)

The objective of this service is to reset the particular target ECU or all the ECU nothing but the vehicle. There are different types of reset available or defined in the UDS Protocol standard document, Such as hard reset, soft reset, key off-on reset, etc for reset of any ECU. Each reset type has its own functionality for how to reset and what needs to be reset. To know more and deep about this service please select or click the above link to read the ECU Reset Service ID

Security Access (27X)

This service Identifier is used to unlock an ECU in a vehicle. To learn about security access I have written a separate tutorial for this. If you want to know more about it you can follow this link as Security Access SID

(4) Communication Control Setting: UDS Protocol

This service is used to control the communication with the server i.e enable or disable transmission and reception of messages from the server.

Sub-Function:

SBF-IDSBF Name
0x00Enable Rx & Tx
0x01Enable Rx & Disable Tx
0x02Disable Rx & Enable Tx
0x03Disable Rx & Tx

Example:

Request: Client–>Server: 03 28 00 03
Where, 03 –> PCI (0–> Single Frame & 3–> TP Data Length)
28 –> SID
00–> SBF (Enable Rx & Tx)
03–> Communication Type as both (Normal & Diagnostic)
+Ve Response: 02 68 00
Where, 02 –> PCI (0–> Single Frame & 3–> TP Data Length)
0x68 –> +Ve response ID (0X28 + 0X40)
0X00 –> SBF

(5) TesterPresent (3E hex): UDS Protocol

The purpose of this service is that the Indication to a server (or servers) that a client is still connected to the vehicle and that certain diagnostic services and/or communications that have been previously activated are to remain active. To keep one or multiple servers in a diagnostic session other than the default Session. ServicesKeeps communication alive: avoid communication timeout. There is no Subfunction parameter like other services.

Example:

Request: Client–>Server: 02 3E 00
+Ve Response: Server–>Client: 02 7E 00

(6) Access Timing Parameter (0x83): UDS Protocol

This service is used to read and change the default timing parameters of a communication link for the duration of this communication link. By using this service the Timeout values and message separation time can be read /written.

SBF-IDSBF Name
0x01readExtendedTimingParameterSet.
0x02setTimingParametersToDefaultValues.
0x03readCurrentlyActiveTimingParameters.
0x04setTimingParametersToGivenValues.

Access Timing Parameter Service Sub-function Table

(7) Secure Data Transmission (0x84): UDS Protocol

The purpose of this service is to transmit data that is protected against attacks from third parties, which could endanger data security, according to ISO 15764. This service is applicable if a client-server intends to use diagnostic services defined in a secured mode. A secured mode in this context means that the data transmitted is protected by cryptographic methods. Security Sub Layer of the transmitter encodes the encapsulated service. Security Sub Layer of the receiver decodes the encapsulated service.

(8) Control DTC setting (0x85): UDS Protocol

The ControlDTCSetting service shall be used by a client to stop or resume the setting of diagnostic trouble codes (DTCs) in the ECU. It is used to Activate / Deactivate storing of errors into error memory. Mostly, it is used during flash programming and development.

SBF-IDSBF Name
0x01DTC On
0x02DTC Off

Example:

Client –> Server (Request Message)
02 85 01
Where,02 –> PCI [0–> Single Frame & 2–> CAN_TP Length]
85 –> SID
01 –> SBF [DTC Control setting ON]
Server –> Client (+Ve Response)
02 C5 01
02 –> PCI [0–> Single Frame & 2–> CAN_TP Length]
C5 –> +Ve Response SID
01 –> +Ve response acceptance SBF

(9) Response On Event (0x86): UDS Protocol

The ResponseOnEvent service requests a server to start or stop the transmission of responses on a specified event. This service provides the possibility of automatically executing a diagnostic service if a specified event occurs in the server. The client specifies the event (including optional event parameters) and the service (including service parameters) to be executed if the event occurs. See Figure 12 for a brief overview of client and server behavior. Using this service you can Configure the ECU to send a response without a request in case of a defined event.

Sub-Functions:

SBF-IDSBF Name
0x00stopResponseOnEvent
0x01onDTCStatusChange
0x02onTimerInterrupt
0x03onChangeOfDataIdentifier
0x04reportActivatedEvents
0x05startResponseOnEvent
0x06clearResponseOnEvent
0x07onComparisonOfValues

(10) Link Control (0x87): UDS Protocol

This service is used to control the communication link baud rate between the Tester and the ECU(s) for the exchange of diagnostic data. This service optionally applies to those data link layers which allow for a baud rate transition during an active diagnostic session.

Sub-Functions:

SBF-IDSBF Name
0x1verifyBaudrateTransitionWithFixedBaudrate
0x2verifyBaudrateTransitionWithSpecificBaudrate
0x3transitionBaudrate

The baudrateIdentifier value determines the Baudrate. For example, 11 – CAN 250 KBPS, 12 – CAN500KBPS, 13 – CAN 1 Mbps

Data transmission functional unit: UDS Protocol

These Services are used to read or write the data to/from the server for the different functional requirements.

Read Data By Identifier (22 hex): UDS Protocol

The ReadDataByIdentifier service allows the client to request data record values from the server identified by one or more data identifiers. The ECU may limit the number of data identifiers that can be read in one request. DataIdentifier – Identifies the ECU data record(s) that are being requested by the ECU.

For Example:

WriteDataByIdentifier (2E hex): UDS Protocol

This service allows the client/Tester to write information into the server/ECU at an internal location specified by the provided data identifier. The WriteDataByIdentifier service is used by the client to write a data Record to a server. The data is identified by a data identifier and may or may not be secured.

Dynamically defined data identifier(s) shall not be used with this service. It is the vehicle manufacturer’s responsibility that the server conditions are met when performing this service. Possible uses for this service are:

–> programming configuration information into the server (e.g. VIN);
–> clearing non-volatile memory;
–> resetting learned values.
–> setting option content.

ReadMemoryByAddress (0x23): UDS Protocol

The ReadMemoryByAddress service allows the client to request memory data from the server via a provided starting address and to specify the size of memory to be read.

The ReadMemoryByAddress request message is used to request memory data from the server identified by the parameter memory address and memory size. The number of bytes used for the memory address and memory size parameter is defined by addressAndLengthFormatIdentifier (low and high nibble). It is also possible to use a fixed addressAndLengthFormatIdentifier and unused bytes within the memory address or memory size parameter are padded with the value 00 hex in the higher range address locations.

WriteMemoryByAddress (0x3D): UDS Protocol

This service allows the client/Tester to write information into the server/ECU at one or more contiguous memory locations. The tester sends a memory address, and the number of bytes, and a data string (according to the number of bytes ). The ECU writes the data string into its memory. The addressAndLengthFormatIdentifier parameter in the request specifies The number of bytes used for the memory address and memory size parameter.

ReadScalingDataByIdentifier (24 hex): UDS Protocol

This service is used to read the scaling information of a record identified by a provided data identifier from the ECU. The client request message contains one data identifier value that identifies data record(s) maintained by the server. The format and definition of the data record shall be vehicle-manufacturer-specific and may include analog input and output signals, digital input and output signals, internal data, and system status information if supported by the server.

ReadDataByPeriodicIdentifier (2A hex): UDS Protocol

The UDS Protocol is used to read the periodic data identifier from the server by using a 0x21 service Identifier. This service allows the client to request the periodic transmission of data record values from the server identified by one or more periodicDataIdentifiers.The client request message contains one or more 1-byte periodicDataIdentifier values that identify data record(s) maintained by the server. The periodicDataIdentifier represents the low byte of a data identifier out of the data identifier range reserved for this service (F2xx hex, refer to C.1 for allowed periodicDataIdentifier values), e.g. the periodicDataIdentifier E3 hex used in this service is the data identifier F2E3 hex. The transmission mode is also specified in the request. For Ex :sendAtSlowRate, sendAtMediumRate, sendAtFastRate, stop sending and the values for above is manufacturer specific.

Dynamically Define Data Identifier (2C hex): UDS Protocol

The purpose of this service is to provide the client with the ability to group one or more data elements into a data superset that can be requested en masse via the ReadDataByIdentifier or ReadDataByPeriodicIdentifier service. The data elements to be grouped can be referenced by either. This provides the client with the ability to group one or more data elements into a data superset that can be requested. The data elements to be grouped can be reference by:

Stored Data Transmission Functional Unit: UDS Protocol

ReadDTCInformation (19 hex): UDS Protocol

The 0x19 service is the heart of ISO 14229 standard UDS Protocol. The main intent of this service is to read the Diagnostic Trouble Codes from the server or ECU. It has multiple sub-functions by which you can read different data required for diagnostic analysis. You can follow this link to read more on the Read DTC Information (0x19) Service Identifier.

Clear Diagnostic Information (14 hex): UDS Protocol

Input-Output control functional unit: UDS Protocol

Input-Output Control By Identifier (2F hex): UDS Protocol

Remote activation of routine functional unit: UDS Protocol

Routine Control (31 hex): UDS Protocol

The Vehicle Diagnostics may require testing the faulty component in a given range of parameters. Moreover, during the vehicle testing phase, some system tests may be required to run over a period of time. to perform a test, a routine is triggered by the client, or to put it in another word, and a routine is started by the client in the server’s memory. There are two methods in this remote request service of UDS Protocol, one is where the client interrupts the routine to stop it, and the other is when the server/ECU finishes the routine after a specified time frame. Using this service, the client can start a routine, stop a routine, and check the result of the routine produced after a successful execution.

One of the Routine Control services defined in the UDS standard is the Erase Memory or Erase Flash routine. It will perform the erasure of EEPROM and flash memory before loading a new block. It has the routine identifier FF01, specified on bytes #3-4 in the UDS request. The remaining bytes of the request contain a routine control option record which is of variable length depending on vehicle manufacturing specification and which routine identifier is used. An example of a start Erase Flash Routine Control service.

Let me explain actually why we need this routine control service. the service diagnostic engineer in the garage may use this service to run the engine fan for a certain period of time and record the results. This would help him understand a particular issue well and rectify it without using any hit and trial method.

Requests: RoutineControlType:

RoutineIdentifier: This parameter identifies a server’s local routine.

Routine Control Request message layout:

Data byteParameter nameHex value
0PCI0x01
1Routine Control SID0x31
2routine identifier0x00-0xFF
3routineControlType0x01-0x03

Example:

A typical Erase Flash Routine Control UDS request. This request aims to start an erasure of an EEPROM or flash memory sector before downloading block 0x15.

Value12345678
Byte0x310x010xFF0x000x010x15

Responses:

Positive response codes:

Negative response codes:

Upload download functional unit: UDS Protocol

Request Download (34 hex): UDS Protocol

The request download service is called when data is to be transferred to the ECU. The request shall contain the size of the data to be transferred and the address to where it shall be placed. The ECU responds with the size of its buffer so that the sender can divide the data into appropriate-sized blocks and send them one at a time.

Requests: Four different request parameters can be included in the request.

Request Download Request message Format:

Data byteParameter nameHex value
0PCI0x01
1Request Download SID0x34
2data format identifier0x00 – 0xFF
3addressAndLengthFormatIdentifier0x00 – 0xFF
4…nmemoryAddress0x00-0xFF
n…mmemory Size0x00-0xFF

Responses:

Positive response codes:

Max Number Of Block Length: This parameter is used by the request download positive response message to inform the client how many data bytes (maxNumberOfBlockLength) shall be included in each TransferData request message from the client. This length reflects the complete message length, including the service identifier and the data parameters present in the TransferData request message. This parameter allows the client to adapt to the receive buffer size of the server before it starts transferring data to the server.

Request Download Response message LayOut:

Data byteParameter nameHex value
0PCI0x01
1Request Download RSID0x74
2lengthFormatIdentifier0x00-0xFF
3maxNumberOfBlockLength0x00-0xFF

Example:

Client –> Server (Request)
34 00 45 01 00 04 00 00 00 09 93 78
Server –> Client (+Ve Response)
74 20 0F FA
Server –> Client (-Ve Response)
7F 74 13/22/31

The Request Download Service (0x34) Full tutorial is available in our new article. If you are interested to learn please click this RequestDownloadService(0x34) Tutorial.

Negative response codes:

Request Upload (35 hex): UDS Protocol

The client requests the negotiation of a data transfer from the server to the client. This service is just the reverse of the 0x34 SID. Suppose you have downloaded some software or DID’s or PID’s, after some time it gets crashed, to check the original file what you downloaded and now either it crashed or not you can upload to your computer and compare also.

Data ByteParameter NameHex Value
1RequestUpload SID35
2dataFormatIdentifier00-FF
3addressAndLengthFormatIdentifier00-FF
4memoryAddress[]=[Byte1(MSB) – Byten()LSB]00-FF to 00-FF
5memorySize[]= [Byte1(MSB) – Byten()LSB]00-FF to 00-FF

Data Format Identifier: This data parameter is a one-byte value with each nibble encoded separately. The high nibble specifies the “compression Method”, and the low nibble specifies the “encrypting Method”. The value 00 hex specifies that no compression Method nor encrypting Method is used. Values other than 00 hex are vehicle manufacturer specific.

AddressAndLengthFormatIdentifier: This parameter is a one-byte value with each nibble encoded separately for identification of address and data in the memory array.

Memory Address: The parameter memory Address is the starting address of server memory from which data is to be retrieved. The number of bytes used for this address is defined by the low nibble (bit 3 – 0) of the address Format Identifier. Byte#m in the memory Address parameter is always the least significant byte of the address being referenced in the server. The most significant byte of the address can be used as a memory Identifier.

Memory Size: This parameter shall be used by the server to compare the uncompressed memory size with the total amount of data transferred during the Transfer Data service. This increases programming security. The number of bytes used for this site is defined by the high nibble (bit 7 – 4) of the address And Length Format Identifier.

Example:

Client –> Server (Request)
35 00 45 01 00 04 00 00 00 09 93 78
Server –> Client (Response)

Transfer Data (36 hex): UDS Protocol

The Transfer Data service receives blocks of data and checks so the blocks are received in the right order. If the right block is received, then it is written to the correct memory location and a positive response is sent.

Requests:

BlockSequenceCounter: The blockSequenceCounter parameter value starts at 01 hex with the first TransferData request that follows the RequestDownload (34 hex) service. its value is incremented by 1 for each subsequent TransferData request. At the value of FF hex, the blockSequenceCounter rolls over and starts at 00 hex with the next TransferData request message.

Transfer Data Request message Frame Format:

Data byteParameter nameHex value
0PCI0x01/0x10/0x20-0x2F
1Transfer Data SID0x36
2blockSequenceCounter0x00-0xFF
3..ndata0x00-0xFF

Responses:

Positive response codes:

Transfer Data Response message layout:

Data byteParameter nameHex value
0PCI0x01/0x10/0x20-0x2F
1Transfer Data SID0x76
2block Sequence Counter0x00-0xFF

Negative response codes:

The server shall use this response code:

Request Out Of Range (31 hex): This return code shall be sent if the transfer Request Parameter Record contains additional control parameters (e.g. additional address information) and this control information is invalid.

The repetition of a Transfer Data request message with a block Sequence Counter equal to the one included in the previous Transfer Data request message shall be accepted by the server.

Request TransferExit (37 hex): UDS Protocol

When the transfer of data is complete a message to the Request Transfer Exit service is sent. If Transfer Data is complete and has received all data a positive response is sent back.

Request:

Request Transfer Exit Request message layout:

Data byteParameter nameHex value
0PCI0x01
1Request Transfer Exit SID0x37

Response:

Request Transfer Exit Response message layout:

Data byteParameter nameHex value
0PCI0x01
1Request Transfer Exit RSID0x77

Negative response codes:

Request File Transfer (38 hex): UDS Protocol

The Request File Transfer service is used to initiate a file data transfer from client to server or server to client by using the download or upload feature. This service is an alternate method of request download and request upload service for better protection and advanced data transfer method.

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *