Реализация бизнес-логики

  1. Убедитесь, что в каталоге VSIDL есть необходимые файлы сборки, protobuf и VSIDL. Чтобы начать с существующего образца, вы можете найти пример действительной папки каталога в /system/software_defined_vehicle/samples/vsidl/stable/catalog.

    Пример структуры каталога:

    my_catalog/
    ├── Android.bp          # Defines rust_protobuf modules for .proto files
    ├── types.proto         # Protobuf message / RPC service definitions
    └── architecture.vsidl  # VSIDL service bundle definitions
    
  2. Напишите собственный код для реализации бизнес-логики.

    vsidlc генерирует привязки промежуточного ПО и каркас пакета сервисов (lib.rs, service_bundle.rs и main.rs) для Rust. Если вы пишете пакет сервисов на C++, реализуйте интерфейсы жизненного цикла (libsdv_lifecycle_client_cpp) и связи (libsdv_comms_cpp) напрямую:

    • Серверы RPC (Rust): реализуйте сгенерированные типажи из lib.rs.
    • Клиенты публикации, подписки и RPC (Rust). Вызовите сгенерированные функции в service_bundle.rs, чтобы взаимодействовать с другими сервисами.
    • Жизненный цикл и обмен данными (C++): создайте подкласс ServiceBundle и инициализируйте издателей, подписчиков или конечные точки RPC в onStart.

    Ржавчина

    1. Создайте базовую реализацию, выполнив следующую команду:

      vsidlc -c /path/to/catalog -o /path/to/output --services
      

      Запуск vsidlc с флагом --services генерирует шаблонную реализацию Rust для каждого пакета сервисов. В нем есть исходный код (main.rs) и файл конфигурации сборки (Android.bp) со всеми зависимостями, поэтому ваш пакет может сразу же обмениваться сообщениями по умолчанию, пока вы сосредоточены на бизнес-логике.

    2. Для каждого пакета сервисов найдите реализацию Rust в:

      /path/to/output/services/ServiceBundleName/src/main.rs.

    3. По умолчанию сгенерированная реализация создает сообщения со значениями по умолчанию и отправляет их между издателями и подписчиками или клиентами и серверами RPC. Чтобы изменить это поведение, найдите комментарии TODO в файле main.rs и измените их в соответствии со своими предпочтениями. Пример:

      rust async fn handle_tire_pressure_range_unique_publisher( publisher: sdv::mw::Publisher<TirePressureRange>, ) { loop { // TODO: Modify the frequency of publishing messages here. sleep(Duration::from_secs(1)).await; // TODO: Modify the message content here. let message = TirePressureRange::default(); info!("Publishing on TirePressureRange#UNIQUE"); publisher.publish(&message).unwrap(); } }

    4. Чтобы изменения, внесенные вами в сгенерированные файлы, не были перезаписаны при следующем запуске vsidlc, переместите папку services из папки /path/to/output.

    C++

    1. Создайте новый заголовочный файл src/lib.hpp с классом для пакета сервисов:

      #pragma once
      #include <sdv/service_bundle.h>
      #include <sdv/context.hpp>
      
      namespace com::sdv::oem::service_bundle {
      
      // Sample implementation of the service bundle interface.
      class ServiceBundleName : public android::sdv::service_bundle::ServiceBundle {
      public:
          ServiceBundleName(sdv_comms::ctx::Context context);
          ~ServiceBundleName();
          void onStart() override;
          void onStop() override;
      };
      }  // namespace com::sdv::oem::service_bundle
      
    2. Создайте новый исходный файл src/lib.cpp с реализацией класса:

      #include "src/lib.hpp"
      #include <sdv/sb_macro.h>
      #include <iostream>
      using com::sdv::oem::service_bundle::ServiceBundleName;
      
      // Register the new service bundle.
      REGISTER_SERVICE_BUNDLE(ServiceBundleName);
      
      // Sample implementation of the service bundle interface.
      namespace com::sdv::oem::service_bundle {
      // Creates a new instance of the ServiceBundleName.
      // Called when service bundle is created by the system.
      // Context object is provided as a parameter that gives access to the
      // communication stack APIs.
      ServiceBundleName::ServiceBundleName([[maybe_unused]] sdv_comms::ctx::Context context) :
        ServiceBundle(context) {
          // Memory allocations and static data loading should be done as
          // part of this method.
          //
          // Loading of the dynamic resources (sockets, files, etc)
          // is strongly discouraged due to possible Suspend-to-RAM scenario.
          //
          // The dynamic data can be loaded in the onStart method.
      }
      
      // Called when the service bundle is started by the system.
      void ServiceBundleName::onStart() {
          // Allocate dynamic resources (sockets, files, publishers, and
          // subscribers such as TirePressureRange#UNIQUE) during this call.
      }
      
      // Called when the service bundle is stopped by the system in preparation
      // for shutdown or suspend to RAM/Disc.
      void ServiceBundleName::onStop() {
          // Stop active publishing loops and release the dynamic resources
          // that were allocated in the onStart method.
      }
      
      // Called when the service bundle is destroyed by the system.
      ServiceBundleName::~ServiceBundleName() {
          // Static resources deallocation needs to be implemented in the destructor.
      }
      }  // namespace com::sdv::oem::service_bundle
      
    3. Создайте цель Soong для библиотеки пакета сервисов в новом или существующем файле Android.bp.

      // Service bundle library.
      cc_library_shared {
        name: "libservice_bundle",
        srcs: ["src/lib.cpp",],
        // Allows the library to be available inside APEX.
        apex_available: [
            "//apex_available:platform",
            "//apex_available:anyapex",
        ],
        shared_libs: [
          // Service Bundle lifecycle C++ API.
          "libsdv_lifecycle_client_cpp",
          // commstack library that provides context object reference
          "libsdv_comms_cpp",
        ],
      
        // Service bundle package is packed into /product apexes.
        product_specific: true,
      }
      

Что дальше

Чтобы развернуть пакеты сервисов, ознакомьтесь со статьей Как создавать и развертывать пакеты сервисов.