Как настроить IDE для разработки SDV

Android Studio for Platform (ASfP) – это рекомендуемая интегрированная среда разработки (IDE) для платформы программно-определяемых автомобилей (SDV) на базе Android Automotive OS (AAOS). ASfP поддерживает все языки, которые используются на платформе AAOS SDV, включая Rust для пакетов сервисов SDV.

На этой странице описана только настройка SDV. Дополнительную информацию об общих функциях и рабочих процессах ASfP можно найти в статье Android Studio for Platform.

ASfP работает только на 64-разрядных системах Linux с процессорами x86-64. Вы можете установить ее на локальную или самоуправляемую рабочую станцию Linux или запустить предварительно созданную облачную рабочую станцию Android 17 на Google Cloud Workstations, где предварительно настроены ASfP (~/Workspace/asfp-project), Cuttlefish, vsidlc и скомпилированные целевые объекты с двумя виртуальными машинами в ~/Workspace/aaos-26q2. Дополнительную информацию вы найдете в статье Разработка в облаке.

Установка ASfP

По умолчанию максимальный размер кучи в ASfP составляет 30 ГБ. Индексирование платформы checkout использует много памяти, особенно если вы также запускаете несколько виртуальных машин Cuttlefish на одном компьютере. Ограничьте область проекта каталогами, с которыми вы работаете, и при необходимости измените максимальный размер кучи в настройках памяти ASfP.

ASfP поддерживает автоматические обновления в IDE. Подробнее о том, как обновить Android Studio для платформы… Подробнее о том, как скачать и установить Android Studio for Platform и проверить системные требования…

Создайте проект SDV

Прежде чем начать, инициализируйте, синхронизируйте и соберите проект AAOS SDV. Дополнительную информацию о настройке оформления покупки можно найти в разделах Расположение кода и Скачивание, сборка и запуск.

Чтобы создать проект SDV, выполните следующие действия:

  1. Создайте новый проект в ASfP и выберите корневой каталог извлечения AAOS SDV в качестве извлечения репозитория. Подробнее о создании и импорте проектов…
  2. После того как ASfP создаст проект, выберите ASfP > Project (Проект) > Open Config (Открыть конфигурацию), чтобы открыть файл .asfp-project.
  3. Замените содержимое файла следующим примером, а затем укажите в repo путь к вашей рабочей копии (замените aosp_cf_x86_64_sdv_core-aosp_current-userdebug на sdv_core_cf-aosp_current-userdebug в Android 17):

    repo: /path/to/sdv_source
    lunch: aosp_cf_x86_64_sdv_core-aosp_current-userdebug
    directories:
      include:
        -   system/software_defined_vehicle/samples
    other_languages:
      -   rust
    
  4. Обновите данные (lunch, directories) для области, в которой вы работаете. Чтобы индексирование и синхронизация выполнялись быстрее, включайте только те каталоги, которые вы активно изменяете. В таблице ниже перечислены распространенные цели и каталоги SDV по выпускам.

    Направление разработки SDV Целевая версия lunch (Android 17 QPR2 и более поздние версии) lunch target (Android 17) Рекомендуем – directories
    Пакеты сервисов SDV aosp_cf_x86_64_sdv_core-aosp_current-userdebug sdv_core_cf-aosp_current-userdebug Каталог услуг и пакетных предложений, например system/software_defined_vehicle/samples.
    Интеграция с платформой SDV Core aosp_cf_x86_64_sdv_core-aosp_current-userdebug sdv_core_cf-aosp_current-userdebug system/software_defined_vehicle/middleware, system/software_defined_vehicle/automotive_services, device/google/sdv
    Шлюз SDV на SDV IVI aosp_cf_x86_64_auto_sdv-aosp_current-userdebug (или sdv_ivi_cf-aosp_current-userdebug) sdv_ivi_cf-aosp_current-userdebug system/software_defined_vehicle/sdv_gateway, system/software_defined_vehicle/samples/sdv_gateway, packages/services/Car
    Безопасность на экране медиасистемы SDV aosp_cf_x86_64_sdv_media-aosp_current-userdebug sdv_media_har_cf-aosp_current-userdebug packages/services/display_safety, device/google/sdv, device/google/sdv_display_safety
    Безопасность экрана в информационно-развлекательной системе автомобиля с программно-определяемой архитектурой aosp_cf_x86_64_auto_sdv-aosp_current-userdebug (или sdv_ivi_cf-aosp_current-userdebug) sdv_ivi_cf_ds-aosp_current-userdebug packages/apps/Car/DriverUI, packages/services/display_safety/service

    Чтобы также просматривать нативный код платформы, добавьте cpp в other_languages. Дополнительную информацию обо всех параметрах конфигурации можно найти в статье Параметры конфигурации.

  5. Чтобы применить изменения, выберите ASfP > Sync (Синхронизация) > Sync Project (Синхронизировать проект). Подробнее о режимах синхронизации (полная, частичная и без сборки), а также об экспорте и импорте шаблонов .asfp-project для команды читайте в статьях Режимы синхронизации и окно инструмента Soong и Шаблоны проектов для совместного использования (экспорт и импорт).

Развертывание пакетов сервисов SDV

В ASfP входит плагин SDV, который развертывает APEX с пакетами сервисов непосредственно на работающем устройстве SDV. По умолчанию плагин отключен. Чтобы использовать его, включите плагин SDV в разделе Настройки > Плагины. Подробнее об упаковке APEX см. в разделе Создание и развертывание пакетов сервисов.

Способ развертывания зависит от того, есть ли уже APEX на устройстве:

  • Если APEX уже установлен, вы можете развернуть изменения непосредственно из ASfP (ASfP APEX развертывает обновления для предустановленных пакетов /product/apex/).
  • Если APEX-файл новый, сначала отправьте его с помощью команды adb remount -R (на Android 17 QPR2 и более поздних версиях), пересоберите и перезапустите образ системы или используйте образ системы, в котором предустановлен ключ, используемый для подписания APEX-файла. После этого вы сможете развернуть его из ASfP.

Чтобы развернуть пакет сервисов APEX, выполните следующие действия:

  1. Запустите устройство SDV с плагином Cuttlefish. Подробнее о том, как запускать устройства SDV на Cuttlefish…
  2. Откройте файл Android.bp, содержащий модуль apex пакета сервисов (generated/apex/<apex_name>/Android.bp в Android 17 QPR2 и более поздних версиях или apex/Android.bp в Android 17), и нажмите на значок Выполнить на полях рядом с блоком apex {.
  3. В открывшемся меню выберите Run 'Deploy APEX_NAME' (Запустить "Развернуть "). В этом же меню можно собрать APEX без развертывания или изменить конфигурацию запуска.

Как запускать устройства SDV на Cuttlefish

В ASfP входит плагин Cuttlefish, который создает и запускает локальные устройства Cuttlefish. Для работы плагина требуется оркестратор хоста Cuttlefish. Если хост-оркестратор недоступен, ASfP покажет инструкции по его настройке.

Чтобы создать устройство SDV, выполните следующие действия:

  1. Выберите Tools (Инструменты) > Device Manager (Диспетчер устройств), нажмите + и выберите Create Cuttlefish Device (Создать устройство Cuttlefish).
  2. Чтобы создать конфигурацию с несколькими виртуальными машинами, выберите Из канонической конфигурации и создайте или импортируйте конфигурацию для своей настройки, например SDV Core с SDV IVI или SDV Media с SDV IVI для Display Safety. Чтобы создать одну виртуальную машину, выберите Из локального дерева исходного кода Android.

Чтобы посмотреть все экраны ВМ на одном экране и получить доступ к дополнительным параметрам устройства, используйте окно инструмента Cuttlefish. Чтобы открыть его, нажмите на значок … на боковой панели и выберите Cuttlefish или найдите Cuttlefish в разделе Help (Справка) > Find Action (Найти действие). Вы также можете просматривать отдельные экраны в окне Running Devices (Активные устройства). Поскольку SDV Core работает без дисплея, используйте Logcat и терминал для проверки.

Отладка и тестирование

В ASfP есть встроенный отладчик LLDB для кода на C++ и Rust. Дополнительную информацию об отладке и тестировании в ASfP можно найти в статьях Отладка кода платформы, Отладка кода Rust, Тестирование кода платформы с помощью atest и Отладка целей cc_test и rust_test в LLDB.

При подключении отладчика к пакету служб подключитесь к процессу, в котором он размещен. Названия процессов имеют формат <bundle_name>:<instance_name>, например OrchestratorSampleRustServiceBundle:sample-main-no-conditions. Следующая команда выводит список соответствующих процессов и их идентификаторов:

adb shell ps -A | grep <bundle_name>

Дополнительную информацию о рабочих процессах отладки SDV, например о подключении к нескольким устройствам и просмотре журналов, можно найти в статье Отладка SDV.

Редактирование файлов VSIDL

В ASfP входит языковой сервер VSIDL (vsidl-lsp), который проверяет system/software_defined_vehicle/vsidl/language/src/protos/sdv/vsidl/v1/ (syntax.proto), чтобы автоматически определить грамматику VSIDL для вашей страницы оплаты. В Android 17 QPR2 и более поздних версиях vsidl-lsp проверяет блоки системного графа apex и host (включая вложенные vm, orchestration и service_bundle_instance health и qos) в дополнение к определениям service_bundle. Подробнее о том, как настроить каталог и граф системы, рассказывается в статьях Автоматическое обновление каталога и интеграция с LSP и Как определить граф системы. Если в каталоге есть файл CATALOG_UPDATE, в редакторе доступны следующие функции для файлов VSIDL:

  • Проверка в реальном времени. Редактор выделяет ключевые слова VSIDL и показывает синтаксические ошибки, неразрешенные типы и ошибки проверки VSIDLC в окне Проблемы. Дополнительную информацию о правилах проверки и кодах ошибок можно найти в спецификации языка.
  • Автозаполнение и документация. Нажмите Ctrl + Пробел, чтобы увидеть подсказки по ключевым словам, сообщениям, сервисам, темам и каналам, или Ctrl + Q, чтобы посмотреть комментарии к документации.
  • Навигация и форматирование. Чтобы перейти к определениям .vsidl или .proto, нажмите Ctrl + B. Чтобы найти ссылки, нажмите Alt + Shift + F7. Чтобы посмотреть структуру файла, нажмите Ctrl + F12. Чтобы отформатировать файл, нажмите Ctrl + Alt + L.

Добавьте контекст SDV для ИИ-помощников

ASfP включает ИИ в Android Studio и встроенного агента с инструментами сборки Soong и atest. Поскольку файлы AGENTS.md хранятся вместе с исходным кодом в системе управления версиями, вы можете использовать одни и те же правила SDV как для встроенного агента ASfP, так и для агентов кодирования на основе командной строки или контейнеров, которые считывают AGENTS.md. Когда вы отправляете запрос, открыв файл в ASfP, агент загружает файлы AGENTS.md из каталога этого файла и его родительских каталогов (если только файл GEMINI.md в том же каталоге не имеет приоритета). Вы можете проверить активные файлы на панели чата в разделе Контекст в разделе Файлы AGENTS.md. Дополнительную информацию вы найдете в статьях Знакомство с Android Studio for Platform и Настройка агента с помощью файлов AGENTS.md.

Шаблоны ниже можно использовать в качестве отправной точки для рабочих процессов, описанных в разделе Создание проекта SDV.

Пакеты сервисов SDV

Поместите файл AGENTS.md, соответствующий вашему выпуску Android, в каталог пакета, включенный в .asfp-project, который содержит папки каталога, сгенерированного кода и кода сервиса. Дополнительную информацию можно найти в статьях Определение графа системы, Генерация промежуточного ПО, Создание и развертывание пакетов сервисов, Создание файла сопоставления SOME/IP и Обзор авторизации связи SDV.

Android 17 QPR2 и более поздних версий

# AAOS SDV service bundle and VSIDL system graph rules

## Source checkout, build, and test
- Sync public AOSP from `-b android-latest-release` (`repo init` syncs all SDV
  repos automatically; pass `-g default,swcar` only when filtering manifest
  groups with `-g`, and never pass `-b main` on public AOSP because `main`
  omits SDV repos)
- Always use 3-part `lunch` targets with `-aosp_current-userdebug` (never 2-part
  `lunch`): `aosp_cf_x86_64_sdv_core-aosp_current-userdebug` or
  `aosp_cf_arm64_sdv_core-aosp_current-userdebug` (`_perf` omits sample
  bundles; `aosp_cf_x86_64_sdv_core_tiny` is the minimal variant)
- Export a distinct `OUT_DIR` per VM terminal before `source build/envsetup.sh`
  and `lunch` when building multiple VMs from one checkout, build modules
  incrementally with Soong (`m <module_name>`, without regenerating
  `super.img`), and run tests with `atest <TestModuleName>` (`rust_test`,
  `rust_test_host`, `cc_test`, or `python_test_host`), without creating
  `Cargo.toml` files or running `cargo`
- In catalog `Android.bp` files, avoid `defaults` on `rust_protobuf` modules
  (`vsidlc` uses a regex parser), include each `.proto` file in at most one
  `rust_protobuf` target, and cover all catalog files in the first `filegroup`
  (`srcs: ["**/*"]`)

## Protobuf, VSIDL system graph, and SOME/IP mapping conventions
- Keep `.proto` files limited to `message`, `enum`, and RPC `service` schemas
  with `sdv/vsidl/v1/annotations.proto` bounds (`variable_type_max_size` on
  `string`/`bytes` and `repeated_field_max_count` on `repeated` fields; `E511`)
- Write VSIDL files in TextProto `VsidlEntry` syntax against
  `system/software_defined_vehicle/vsidl/language/src/protos/sdv/vsidl/v1/syntax.proto`
  (confirm `repeated Apex apex` is present to verify a 26Q4+ checkout):
  declare `service_bundle`, `apex` (`service_bundle_manifest`, plus
  `native_library: "lib<so>"` for C++ `cc_library_shared` bundles), and `host`
  (containing `vm` blocks with `orchestration` and `service_bundle_instance`
  entries for `health` and `qos`) so `vsidlc` generates APEX packaging,
  orchestration, and least-privilege `permissions.textproto` policies
  automatically; isolate `some_ip_mapping` or `vhal_mapping` rules in dedicated
  VSIDL files
- Use `PascalCase` for `service_bundle` names, `snake_case` for
  `build_cfg.target_name`, a globally unique lowercase `package` with at least
  four segments (`com.<org>.sdv.<domain>`; never reuse `com.android.sdv.*` or
  `com.sdv.*`), lowercase dash-case starting with a letter for `topic`,
  `channel`, and instance names, and an even `capacity >= 2` on every
  `publisher`

## Code generation, runtime security, and inner-loop deployment
- Run `vsidlc -c <catalog_dir> -o <output_dir> --services` (or `vsidlc -r <dir>`
  for recursive `CATALOG_UPDATE` regeneration; inspect `E100`-`E700` codes with
  `vsidlc --explain <CODE>`): genrule mode is enabled by default (pass
  `--no-genrule` for static Rust files), Soong rules write under
  `<output_dir>/generated/{rust,apex,vm,services}` (with the main genrule
  `Android.bp` at `<output_dir>/generated/rust/Android.bp`, producing generated
  configs such as `permissions.textproto`, `someip-config.binpb`, and
  `vsidl-config.binpb` at build time), and modifiable handwritten Rust code is
  isolated under `--hwc <path>` (default
  `<output_dir>/hwc/services/<package_path>/<ServiceBundleName>/src/main.rs`) so
  `vsidlc -p` updates `<output_dir>/generated/` without overwriting `hwc/`
- Core SDV agents reside on `/system` (`/system/bin/...`; the SOME/IP broker
  runs as `user system_ext_sdv_someip`, and both `sdv_someip_broker_agent` and
  `sdv_someip_stack_agent` live in `init.aosp_cf_x86_64_sdv_core.rc` or
  `init.aosp_cf_arm64_sdv_core.rc`, with the stack started on
  `dev.bootcomplete=1 && ro.boot.sdv.someip.enable=true`). Default Cuttlefish
  authorization (`sdv-cf` `-z=permissions_only`) is `PermissionsOnly`: bundles
  missing `permissions.textproto` are denied at run time unless
  `sdv.authz.enable=acls_only` is set. Health Monitor VM configuration
  (`HealthMonitorConfiguration` from `ro.sdv.health_monitor.config_path` or
  `persist.sdv.health_monitor.config_path`) sets per-agent `binder_timeout_ms`
  inside `monitored_agent`
  (`ro.boot.sdv.health_monitor.agent_startup_timeout_sec` was removed). OEM A/B
  custom partitions (`oem_ab/Android.bp`) pass non-sparse
  `$OUT/oem_ab_a.img;$OUT/oem_ab_b.img;$OUT/oem_ab_metadata.img` to
  `cvd create --custom_partition_path`
- In Rust bundles, wait for publisher or RPC server availability before
  creating subscribers or clients, stop active tasks in `on_stop`, and run
  blocking work in `tokio::spawn_blocking`
- Fast CLI inner-loop deployment on `userdebug`/`eng` builds (without bumping
  `apex_manifest.json` `version`): run `adb root && adb remount -R &&
  adb wait-for-device && adb root && adb remount` once on a fresh VM, then on
  each edit run `m <apex_module> &&
  adb push $OUT/product/apex/<apex_module>.apex /product/apex/ && adb reboot`.
  ASfP gutter deploy updates preinstalled `/product/apex/` bundles (new bundles
  require `adb remount -R` or a full image build first). Launch Cuttlefish with
  `sdv-cf create --instance_name=instance1` (or
  `cvd create --config=sdv_core_instance1`) when running sample bundles, and use
  `/data/mydir/` plus `sdv_update_manager_client` when verifying staged OTA
  updates

Android 17

# AAOS SDV service bundle and VSIDL rules (Android 17 (26Q2))

## Build and test
- Pin Android 17 (26Q2) checkouts with `-b android17-release` (or
  `android-17.0.0_r1`). When running outside ASfP, export a distinct `OUT_DIR`
  per VM terminal before `source build/envsetup.sh` and
  `lunch sdv_core_cf-aosp_current-userdebug` when building multiple VM targets
  from one checkout, build modules incrementally with Soong (`m <module_name>`,
  which writes only that module's artifact under `$OUT` without regenerating
  `super.img`), and run tests with `atest <TestModuleName>` (`rust_test`,
  `rust_test_host`, `cc_test`, or `python_test_host`), without creating
  `Cargo.toml` files or running `cargo`
- In catalog `Android.bp` files, avoid `defaults` on `rust_protobuf` modules
  (`vsidlc` uses a regex parser), include each `.proto` file in at most one
  `rust_protobuf` target, and cover all catalog files in the first `filegroup`
  (`srcs: ["**/*"]`)

## Protobuf, VSIDL, and AUTOSAR SOME/IP mapping conventions
- Keep `.proto` files limited to `message`, `enum`, and RPC `service` schemas
  (using `sdv/vsidl/v1/annotations.proto` only for field size bounds), without
  topic names, channel names, or queue capacities
- Write `.vsidl` files in TextProto `VsidlEntry` syntax (`package: "..."`,
  `service_bundle { name: "..." }`, `publisher` or `subscriber` with `message`
  and `topic`, and `server` or `client` with `service` and `channel`, without
  `import` statements; RPCs support unary, client-streaming, and
  server-streaming methods, not bidirectional streaming), and isolate
  `some_ip_mapping` (`sdv_type_mapping` and `someip_service_mapping` for
  AUTOSAR electronic control unit (ECU) `ARXML` or `vsomeip` IDs) or
  `vhal_mapping` rules in dedicated `.vsidl` mapping files so core bundles stay
  transport-independent
- Use `PascalCase` for `service_bundle` names (avoiding Rust, C++, and Java
  keywords), `snake_case` for `build_cfg.target_name`, a globally unique
  lowercase `package` with at least four segments (`com.<org>.sdv.<domain>`;
  never reuse platform-reserved `com.android.sdv.*` or sample `com.sdv.*`
  names), and lowercase dash-case starting with a letter (no consecutive or
  trailing hyphens, underscores, or slashes) for `topic`, `channel`, and
  instance names
- Set `capacity` on every `publisher` to an even integer greater than or equal
  to 2, and pair every `subscriber` and RPC `client` with a matching
  `publisher` or `server` in the catalog or its `-d` dependency catalogs

## Code generation, authorization, and APEX packaging
- Export `ANDROID_BUILD_TOP`, check `CATALOG_UPDATE` for catalog-relative
  `output_path` (such as `".."`), `dependency_catalog_paths` (`-d`), and
  `vsidlc_gen_args`, and run `vsidlc -c <catalog_dir> -o <output_dir>`; omit
  `--services` from `vsidlc_gen_args` and avoid `-p` (`--purge`) or
  `regenerator` when `output_path` holds handwritten `services/` code
- Leave generated files in `generated_rs/`, `apex/`, and `configs/` unmodified
  (except when incrementing `version` in `apex/apex_manifest.json` for iterative
  updates or adding manual authorization policies), and implement Rust logic in
  `services/<ServiceBundleName>/src/main.rs` (even though the initial
  `vsidlc --services` skeleton header says not to edit; C++ bundles do not use
  `vsidlc` C++ codegen and instead use `libsdv_lifecycle_client_cpp`,
  `libsdv_comms_cpp`, and `sdv_service_bundle_metadata` with
  `native_library_path: "lib64/lib<so>.so"` in
  `sdv_service_bundles_manifest.textproto`)
- Keep communications authorization `.textproto` policies in `configs/` aligned
  with every `publisher`, `subscriber`, `server`, and `client` unit (omitting
  `capacity` inside manual authorization `.textproto` `publisher` entries)
  because Soong skips `.textproto` validation at build time and failures surface
  only at runtime
- In Rust bundles, wait for publisher or RPC server availability before
  creating subscribers or clients, stop active tasks in `on_stop`, and run
  blocking work in `tokio::spawn_blocking`
- Generate Rust service bundle APEXes with `vsidlc --apex` (`updatable: true`,
  `min_sdk_version: "35"`, and `product_specific: true` in `apex/Android.bp`,
  never `vendor: true` or `soc_specific: true`, with matching unique `name` and
  `version` >= 1 in `apex_manifest.json`), stage iterative CLI updates on
  `sdv_core_cf` by incrementing `version`, building `m <apex_module>`, running
  `adb root` (passing `-s 0.0.0.0:6520` when multiple VMs run), pushing the
  APEX to `/data/mydir/`, and invoking `sdv_update_manager_client` from
  `/apex/com.android.sdv.sample.update_manager.client/bin/`
  (`prepare service-bundle`, `activate`, `adb reboot`, `status`, `commit`),
  flush writes with `adb reboot` before `cvd stop` and resume stopped VMs with
  the matching `cvd start` or `sdv-cf start --instance_name=instance1` (through
  `instance3`) command (running `cvd remove` before `cvd create` when resetting
  overlays), and do not set `supportsRebootlessUpdate: true` or run
  `adb install --force-non-staged` because SDV APEX updates require a reboot

Шлюз SDV на SDV IVI

Поместите этот файл AGENTS.md в каталог клиентского модуля IVI или system/software_defined_vehicle/sdv_gateway/. Подробнее о том, как использовать шлюз SDV в IVI…

# AAOS SDV Gateway on SDV IVI rules

- When running outside ASfP, export a distinct `OUT_DIR` per VM terminal before
  `source build/envsetup.sh` and
  `lunch aosp_cf_x86_64_auto_sdv-aosp_current-userdebug` (or
  `sdv_ivi_cf-aosp_current-userdebug` on Android 17 QPR2 (26Q4), where
  `ENABLE_SDV_INTEGRATION` and Display Safety are enabled by default; on
  Android 17 (26Q2), use `sdv_ivi_cf-aosp_current-userdebug`) when building
  alongside SDV Core (`aosp_cf_x86_64_sdv_core-aosp_current-userdebug`, or
  `sdv_core_cf-aosp_current-userdebug` on Android 17 (26Q2)), build IVI modules
  incrementally with Soong (`m <module_name>`, staging updatable IVI APEXes such
  as `com.oem.sdv.authz` with `adb install --staged` and `adb reboot`, passing
  `-s 0.0.0.0:6521` when a second VM runs alongside `0.0.0.0:6520`, or running
  `m` when updating partition files), resume stopped Cuttlefish VMs with the
  matching `cvd start` (with `--group_name` when multiple groups exist) or
  `sdv-cf start --instance_name=instance2` command after flushing writes with
  `adb reboot`, and run verification with `atest <TestModuleName>`
- On `android-latest-release` (Android 17 QPR2 (26Q4) and higher),
  `libsdvgatewayclient` connects directly to SDV agents without a separate
  `sdv_gateway` daemon. For native C or C++ IVI clients (including vehicle
  hardware abstraction layer (VHAL) integrations), link `libsdvgatewayclient`
  (`#include "libsdvgatewayclient.h"`); for in-tree system Java or Kotlin
  clients, use `libsdvgatewayclient-java`, `libsdvgatewayclient-java-sdk.stubs`,
  `libsdvgatewayclient-java-sdk`, and `com.android.sdv.gateway.client`, and
  declare
  `<uses-library android:name="libsdvgatewayclient-java-sdk" android:required="true" />`
  in `AndroidManifest.xml`
- Start the Binder thread pool before calling `ASDVGateway_Client_new`, and
  call `ASDVGateway_Client_initComms` (or `SdvGatewayClient.initComms`) before
  any service discovery, data tunnel, or RPC calls
- Check `ASDVGateway_Client_isRpcAvailable` or
  `ASDVGateway_Client_isProcessBoundToSdvRpcNetworkInterface` before opening
  RPC sockets on early boot, treat `ASDVGateway_StatusCode_OK` with null
  `ASDVGateway_RpcCredentials_t` as insecure `UNLOCKED` boot mode, and free
  non-null credentials with `ASDVGateway_Client_deleteRpcCredentials`
- Grant `sdv_gateway_client_domain(<domain>)` in SELinux (do not add
  `binder_use` on `/vendor` daemons, which violates Treble `neverallow`; add
  `group inet` on native init services, and `INTERNET` plus
  `CONNECTIVITY_USE_RESTRICTED_NETWORKS` privapp permissions for system Java
  RPC clients)

Безопасность дисплея

Поместите файл AGENTS.md в каталог packages/services/display_safety/ или каталог приложения приборной панели. Дополнительную информацию можно найти в статьях Начало работы с Display Safety, Уровень абстракции платформы HAR, Набор инструментов для проектирования безопасности и DriverUI.

# AAOS Display Safety partner integration rules

- Display Safety spans two guest VMs with separate `lunch` targets: keep
  safety-critical telltales, gauges, camera views, chimes, and early-boot or
  fallback placeholders in the Rust high availability renderer (HAR) and safety
  monitor on SDV Media (`aosp_cf_x86_64_sdv_media-aosp_current-userdebug` on
  `android-latest-release`, or `sdv_media_har_cf-aosp_current-userdebug` on
  Android 17 (26Q2)), and build non-safety cluster UI on SDV IVI
  (`aosp_cf_x86_64_auto_sdv-aosp_current-userdebug`, or
  `sdv_ivi_cf-aosp_current-userdebug` on Android 17 QPR2 (26Q4), where Display
  Safety is included by default; use `sdv_ivi_cf_ds-aosp_current-userdebug` on
  Android 17 (26Q2)) using `ClusterHomeManager` (`Cluster2` rather than legacy
  `Cluster1`)
- Implement target OS and hardware subsystems (display, graphics, exterior view
  system (EVS) cameras, audio, user input, and vehicle signals) in a dedicated
  `har-platform-<target>` platform abstraction layer (PAL) crate implementing
  `har-platform-api` traits rather than modifying core `harry` framework crates,
  and verify PAL crates against the HAR platform test suite with `atest`
- Generate safety monitor configurations and telltale inspection artifacts from
  the compiled `.dcf` document and safety configuration JSON
  (`safety-config.json`, specifying top-level `document_id` and `displays`
  entries with `root_node_id` and `states` telltale node mappings) by running
  `/apex/com.google.sdv.display_safety.har/bin/har_design_compiler` with `-c`
  (`--config-file-path`), `-o` (`--artifacts-output-dir`), `--documents-path`,
  and `--fonts-path`, pulling artifacts into
  `packages/services/display_safety/service/harry-prebuilt/data/assets/common/artifacts/`
  rather than hardcoding telltale pixel coordinates
- Because the HAR display plane composites above Android IVI, ensure HAR clears
  the cluster viewport region to `alpha = 0.0` while valid `HeartbeatRequest`
  gRPC messages arrive from IVI, and set opaque pixels in custom HAR OpenGL ES
  surfaces to `alpha = 1.0` (`0xFF`)
- When running outside ASfP, export a distinct `OUT_DIR` per VM terminal
  (`export OUT_DIR=out-media` and `export OUT_DIR=out-ivi`) before
  `source build/envsetup.sh` and `lunch`: on `android-latest-release`, launch
  both VMs directly with `ds_toolkit launch -mb
  $ANDROID_BUILD_TOP/out-media/target/product/aosp_cf_x86_64_sdv_media -ib
  $ANDROID_BUILD_TOP/out-ivi/target/product/sdv_ivi_cf -ht
  $ANDROID_BUILD_TOP/out-media/host/linux-x86` (on Android 17 (26Q2), where
  `ds_toolkit launch` lacks `-ht`, launch VMs individually with `cvd create` or
  run `ds_toolkit gen_config` with `-mb .../target/product/sdv_har_cf` and
  `-ib .../target/product/sdv_ivi_cf`, set `common.host_package`, and run
  `cvd load`), integrate prebuilt cluster APKs through `DriverUIPrebuilt`
  (`overrides: ["DriverUIStubApp"]`), use `adb reboot` for clean VM restarts and
  pass matching `--extra_bootconfig_args` (plus `--display1` on IVI and
  `--group_name` selectors from `cvd fleet`) when resuming stopped VMs with
  `cvd start`, pass `--user 0` to `adb shell am` cluster commands, and note
  that `adb shell dumpsys SurfaceFlinger` on SDV IVI inspects only Android
  layers rather than the overlying HAR plane