שימוש בשער SDV במערכת IVI

שער הרכב מוגדר התוכנה (SDV) במערכות המולטימדיה (IVI) מאפשר תקשורת בין מערכות IVI לבין שירותי SDV מרוחקים. השער מאפשר לאפליקציות Java של יצרן ציוד מקורי (OEM) ולשירותים מקוריים, כמו שכבת הפשטת חומרה של הרכב (VHAL), לקיים אינטראקציה עם שירותי SDV. השער משתמש בשיטות תקשורת מבוססות, כולל רישום שירות, גילוי וקריאות לשירות מרוחק (RPC).

השער הזה עומד בדרישות ספציפיות של פרויקט AAOS SDV, כמו הפעלת הטמעת קובץ עזר של VHAL באמצעות SDV Data Tunnel למידע על מאפיינים. היא גם מאפשרת לאפליקציות ל-Android ב-Java וב-Kotlin ב-IVI להשתמש במחסנית SDV Comms, להירשם כשירותים, למצוא שירותי SDV אחרים ולתקשר איתם.

במאמר מיקומי קוד מפורטים מיקומי הקוד של SDV Gateway ולקוחות לדוגמה של SDV Gateway.

מודלים של שילוב SDV Gateway

בקטע הזה מתוארת הארכיטקטורה של שער SDV ב-IVI, ומוסבר איך שירותי C או C++‎ מקוריים משתלבים עם ספריית הלקוח של השער.

שימוש בתקשורת SDV-IVI דרך שער SDV בארכיטקטורת IVI

שער ה-SDV מתקשר עם אפליקציות Java, שירותים מקומיים, מחסנית התקשורת של ה-SDV ורשת הרכב. באיור 1 מוצגות האינטראקציות האלה:

אינטראקציות עם SDV Gateway

איור 1. אינטראקציות עם שער SDV.

בתרשים המערכת הזה:

  • האפליקציות מתקשרות עם שער ה-SDV דרך שירותי הלקוח שלו.
  • ‫AAOS SDV SDK מספק לכם:
    • ‫ISdvGateway AIDL API לתקשורת בין תהליכים (IPC).
    • ספריות תקשורת לאינטראקציה ברשת.
    • ממשק API נוח ב-C לשילוב שירותים מקוריים.
  • ממשק ה-API של ISdvGateway AIDL מיושם על ידי שירות SDV Gateway ותת-המערכת.
  • שירות SDV Gateway מנהל את:
    • זיהוי שירותים דו-כיווני.
    • תקשורת עם שירותי SDV מרחוק.
    • לוגיקה עסקית בסיסית.
  • מערכת המשנה של שער SDV מתחברת לרשת הרכב.
  • שירותים מקומיים, כולל ההטמעה של VHAL, יכולים להשתמש ב-ISdvGateway AIDL API ישירות או דרך C API של ה-SDK.
  • שרת ה-proxy של VHAL משמש כהטמעה של VHAL, ומשלב את השילוב של מיפוי VSIDL.

מודל שילוב של שער SDV בשירות מקומי של IVI

מודל השילוב מוצג באיור 2:

מודל השילוב של SDV Gateway

איור 2. מודל השילוב של SDV Gateway.

שימוש בשער SDV בשירות מקורי של IVI

איור 3 ממחיש את השימוש בשער SDV ב-IVI:

שער SDV ב-IVI

איור 3. שער SDV ב-IVI.

תנאים מקדימים

הפעלת מאגר ה-Thread של Binder:

  • כדי לקבל קריאות חוזרות (callbacks) אסינכרוניות משירותי Binder, ספריית הלקוח של SDV Gateway צריכה מאגר שרשורים (thread pool) פעיל של Binder.

  • ה-API שנדרש כדי ליצור לקוח SDV Gateway נכשל כשמאגר השרשורים של Binder לא מופעל.

הכללת ספריית לקוח מקורית של Gateway

ספריית לקוח Native Gateway חושפת ממשק API של C. כדי להשתמש ב-C API, צריך להוסיף מופע של libsdvgatewayclient כתלות:

cc_binary {
    name: "your_binary_name",
    srcs: ["main.cpp"],
    shared_libs: [
        "libsdvgatewayclient",
    ],
}

טעינת לקוח Gateway מקורי

#include "libsdvgatewayclient.h"

יצירת מכונה של לקוח מקומי

ASDVGateway_Client* client;
ASDVGateway_StatusCode_t statusCode = ASDVGateway_Client_new(
     &client, /*outStatus*/nullptr);

אחרי שהלקוח נוצר, הוא:

  • שומר את המצב של כל האינטראקציות הבאות עם שירות Gateway.

  • משמש כהקשר של כל האינטראקציות עם שירותים אחרים שמותאמים ל-SDV, ומועבר כפרמטרים הראשונים לפונקציות של C API.

קודי סטטוס והודעות שגיאה

לרוב הפונקציות של C API יש את ההגדרה הזו:

ASDVGateway_StatusCode_t ApiFunctionName(..., ASDVGateway_Status_t* outStatus);

כדי להעריך את ההצלחה, אפשר לבדוק את קוד הסטטוס שמוחזר, שהוא מסוג ASDVGateway_StatusCode_t. אפשר גם להעביר מצביע למבנה שבו הפונקציה יכולה למלא את קוד הסטטוס והודעת שגיאה. המצביע מועבר כפרמטר האחרון, שנקרא outStatus. ערך null פירושו שלא נעשה שימוש במבנה הפלט.

המתקשר צריך להקצות את מבנה סטטוס הזיכרון להודעת השגיאה. מבנה הסטטוס יכול להכיל גם את קוד הסטטוס וגם הודעת שגיאה. יש דוגמה לאחזור של הודעת השגיאה כשיוצרים לקוח חדש.

כדי להעריך את מידת ההצלחה:

  1. בודקים את קוד הסטטוס שמוחזר, שהוא מסוג ASDVGateway_StatusCode_t.

  2. מעבירים מצביע למבנה שבו הפונקציה יכולה למלא את קוד הסטטוס ואת הודעת השגיאה.

    • הסמן מועבר כפרמטר האחרון, שנקרא outStatus.
    • ערך null פירושו שלא נעשה שימוש במבנה הפלט.
    • הגורם שמתקשר צריך להקצות את מבנה סטטוס הזיכרון להודעת השגיאה.
    • מבנה הסטטוס יכול להכיל את קוד הסטטוס והודעת שגיאה.

הנה דוגמה שמראה איך לאחזר את הודעת השגיאה של לקוח חדש:

#include <iostream>
#include <array>

struct StatusWithErrorMsg : ASDVGateway_Status_t {
    StatusWithErrorMsg() {
        // Ensure the base struct pointers point to our internal buffer
        errorMessage = errorMessageBuffer.data();
        maxErrorMessageSize = errorMessageBuffer.size();

        // Good practice: Zero-initialize the buffer
        errorMessageBuffer.fill(0);
    }

    std::array<char, 256> errorMessageBuffer;
};

// --- Execution ---

ASDVGateway_Client* client = nullptr;
StatusWithErrorMsg status;

// Initialize the client
ASDVGateway_StatusCode_t statusCode = ASDVGateway_Client_new(&client, &status);

// Log Results
std::cout << "Returned statusCode:    " << statusCode << std::endl;
std::cout << "Status Struct Code:     " << status.statusCode << std::endl;
std::cout << "Status Error Message:   " << status.errorMessage << std::endl;

בדוגמה הזו:

  • קוד הסטטוס שמופיע במבנה הסטטוס זהה לקוד הסטטוס שמוחזר.

  • הודעת השגיאה מוגבלת ל-maxErrorMessageSize תווים (כולל תו הסיום null‏ \0). אם לא מתרחשת שגיאה (קוד הסטטוס הוא OK), הודעת השגיאה היא מחרוזת ריקה.

התחלת התקשורת

הפונקציה Init comms מאתחלת את התקשורת בין האפליקציה שמבצעת את השיחה לבין אפליקציות אחרות באמצעות SDV Comm Stack ו-SDV Gateway. אפשר להפעיל את Init comms בשני ההקשרים האלה:

  • אחרי שיוצרים את הלקוח.

  • לפני כל אינטראקציה של Data Tunnel,‏ RPC או זיהוי שירותים.

הנה דוגמה:

ASDVGateway_InitCommsParams_t params{
    .packageName         = "android.sdv.samples.gateway.client",
    .serviceBundleName   = "NativeTestApp",
    .serviceInstanceName = "default",
};

// Initialize communications and capture the status code
ASDVGateway_StatusCode_t statusCode = ASDVGateway_Client_initComms(client, &params, &status);

// Recommended check
if (statusCode != ASDVGateway_StatusCode_OK) {
    std::cerr << "Failed to init comms: " << status.errorMessage << std::endl;
}

זיהוי שירותים

אתם יכולים לקבל התראות כשיחידות שירות מסוג או שם מסוים נרשמות או מוסרות מהרישום. פונקציית הקריאה החוזרת מקבלת הודעה בשרשור שבבעלות הלקוח של השער. הקריאה החוזרת הזו מופעלת בהתחלה עם כל יחידות השירות שנרשמו מיד אחרי הקריאה ל-API. אחרי ההפעלה הראשונית, ההתראות ממשיכות עם עדכונים עד שהמאזין מוסר באופן מפורש.

class NativeSdvGatewayTestApp {
public:
    static void ServiceUnitChangeListenerCallback(
        const ASDVGateway_ServiceUnitChangeEventType eventType,
        const ASDVGateway_ServiceUnitDefinition* serviceUnitDefinition,
        void* userData
    ) {
        auto* testApp = reinterpret_cast<NativeSdvGatewayTestApp*>(userData);

        if (testApp) {
            // Logic to react when services are registered or unregistered
            // e.g., testApp->handleServiceChange(eventType, serviceUnitDefinition);
        }
    }
};

// --- Listener Registration ---

// Ensure thisApp remains in scope as long as the listener is active
NativeSdvGatewayTestApp* thisApp = get_current_app_context();

ASDVGateway_UnitType_t unitType{
    .sdvPackageName     = "android.sdv.samples.sdv_gateway",
    .serviceBundleName  = "DtPublisher",
    .unitTypeName       = "TirePressure",
};

// Register the listener
ASDVGateway_Client_registerListenerForServiceUnitChangeByType(
    client,
    &unitType,
    NativeSdvGatewayTestApp::ServiceUnitChangeListenerCallback,
    static_cast<void*>(thisApp), // userData
    &listenerHandle,
    &status
);

// --- Cleanup ---

// Unregistering stops all notification to the callback function
ASDVGateway_Client_unregisterListenerForServiceUnitChangeByType(
    client,
    listenerHandle,
    &status
);

כדי לאחזר את יחידות השירות הרשומות בלי התראות נוספות, משתמשים בממשקי ה-API‏ ASDVGateway_Client_fetchServiceUnitsByType ו-ASDVGateway_Client_fetchServiceUnitsByName.

class NativeSdvGatewayTestApp {
public:
    /**
     * Callback triggered for each service unit found that matches the requested type.
     */
    static void FetchServiceUnitsCallback(
        const ASDVGateway_ServiceUnitDefinition* serviceUnitDefinition,
        void* userData
    ) {
        auto* app = reinterpret_cast<NativeSdvGatewayTestApp*>(userData);

        if (serviceUnitDefinition) {
            // The service unit is registered with service discovery.
            // Example: processServiceUnit(serviceUnitDefinition);
        }
    }
};

// --- Execution ---

ASDVGateway_UnitType_t unitType{
    .sdvPackageName     = "android.sdv.samples.sdv_gateway",
    .serviceBundleName  = "DtPublisher",
    .unitTypeName       = "TirePressure",
};

// Context used to differentiate between various fetchServiceUnits calls
void* userData = static_cast<void*>(thisApp);

ASDVGateway_Client_fetchServiceUnitsByType(
    client,
    &unitType,
    NativeSdvGatewayTestApp::FetchServiceUnitsCallback,
    userData,
    &status
);

הקריאה החוזרת מופעלת באופן סינכרוני בשרשור של פונקציית הקריאה החוזרת (caller) במהלך הקריאה ל-API של ASDVGateway_Client_fetchServiceUnitsByType. כדי לקבל את יחידות השירות הרשומות לפי שם במקום לפי סוג יחידה, משתמשים ב-ASDVGateway_Client_fetchServiceUnitsByName:

ASDVGateway_StatusCode_t ASDVGateway_Client_fetchServiceUnitsByName(
    // [in]  Opaque pointer to a client object.
    const ASDVGateway_Client* client,

    // [in]  Pointer to a structure containing the package name,
    //       service bundle name, and service unit name.
    const ASDVGateway_UnitNameDiscoveryArgs_t* unitName,

    // [in]  Callback function to be called for each service unit
    //       definition registered. Called synchronously in the
    //       caller's thread before the fetch completes.
    ASDVGateway_FetchServiceUnitsCallback callback,

    // [in]  Optional value passed back as a parameter of the callback.
    void* userData,

    // [out] Optional pointer to status structure for result
    //       codes and error messages.
    ASDVGateway_Status_t* outStatus
);

תהליך RPC

ספריית הלקוח של Gateway מטפלת בהגדרות של Transport Layer Security ‏(TLS) לתקשורת עם אפליקציות אחרות שתומכות ב-SDV. באופן ספציפי, הוא מאחזר את הגדרות ה-TLS שנדרשות לתקשורת. כך נקבע השימוש ב-TLS:

  • ‫TLS משמש כשמצב האתחול של SDV הוא LOCKED.

  • תקשורת לא מאובטחת משמשת כשמצב ההפעלה של ה-SDV הוא UNLOCKED. כשמשתמשים ב-TLS, ספריית הלקוח של Gateway יוצרת זוג מפתחות שרק תהליך האפליקציה מכיר. הלקוח מאחזר את פרטי הכניסה ל-RPC כדי ליצור שרת RPC או ערוץ לקוח RPC. ‫RPC משתמש ב-VLAN ייעודי של SDV-RPC. ספריית הלקוח של Gateway קוראת ל-android_setprocnetwork כדי להחליף את רשת ברירת המחדל של התהליך ל-SDV-RPC VLAN במהלך הקריאה ל-ASDVGateway_Client_initComms או אחריה.

זמינות של RPC

אם הלקוח מוגדר להתחיל באתחול מוקדם, יכול להיות שהוא יתחיל לפני ש-SDV-RPC VLAN יהיה זמין. לפני שמנסים ליצור שקעי שרת RPC או שקעי לקוח RPC, צריך לוודא ש-RPC זמין:

// Check if the RPC (Remote Procedure Call) service is available
bool isRpcAvailable = ASDVGateway_Client_isRpcAvailable(client);

if (isRpcAvailable) {
    // Proceed with RPC calls
} else {
    // Handle the case where RPC is not yet ready or available
}

או

// Check if the process is correctly bound to the SDV RPC Network Interface/VLAN
bool isRpcNetworkBound = ASDVGateway_Client_isProcessBoundToSdvRpcNetworkInterface(client);

if (!isRpcNetworkBound) {
    // Usually implies the process isn't running on the correct network interface
    // or the VLAN configuration is missing.
    std::cerr << "Warning: Process is not bound to the SDV RPC VLAN." << std::endl;
}

מגדירים מאזין לאירועי לקוח באמצעות ASDVGateway_Client_setClientNotificationCallback כדי לקבל התראה כשסטטוס הזמינות של ה-RPC משתנה. עדיף להשתמש ב-ASDVGateway_Client_isProcessBoundToSdvRpcNetworkInterface אם האפליקציה מחליפה את הרשת של התהליך, כי היא בודקת גם ש-RPC זמין וגם שהתהליך קשור ל-SDV-RPC VLAN.

החלפת רשת ברירת המחדל של התהליך

יכול להיות שתצטרכו לעבור מ-SDV-RPC VLAN כרשת ברירת המחדל של התהליך כדי לפתוח שקעים לחיבורים לאינטרנט. מפעילים את ASDVGateway_Client_unbindProcessFromSdvRpcNetworkInterface ואת ASDVGateway_Client_bindProcessToSdvRpcNetworkInterface כדי לבטל את הקישור של התהליך ל-SDV-RPC VLAN ולקשר אותו מחדש. שתי הקריאות פועלות כמו מתגים גלובליים, ומחליפות את ממשק הרשת שאליו השקעים קשורים בכל השרשורים של התהליך.

// 1. Unbind: Sockets return to the "default" network interface (e.g., wlan0, eth0)
ASDVGateway_StatusCode_t unbindStatus =
    ASDVGateway_Client_unbindProcessFromSdvRpcNetworkInterface(client, &status);

// 2. Bind: Sockets are now bound to the dedicated SDV-RPC VLAN
ASDVGateway_StatusCode_t bindStatus =
    ASDVGateway_Client_bindProcessToSdvRpcNetworkInterface(client, &status);

// Validation
if (bindStatus == ASDVGateway_StatusCode_OK) {
    // Sockets are successfully bound to the SDV-RPC VLAN
}

התראות RPC

מגדירים את מאזין הלקוח לקבלת התראות על שינויים בזמינות של ה-RPC ועל עדכונים לאישורי הבסיס ששרת RPC צריך לקבל:

class NativeSdvGatewayTestApp {
public:
    static void ClientNotificationCallback(
        ASDVGateway_ClientNotificationType_t notificationType,
        void* userData
    ) {
        auto* testApp = reinterpret_cast<NativeSdvGatewayTestApp*>(userData);
        if (!testApp) return;

        switch (notificationType) {
            case ASDVGateway_ClientNotificationType_RootCertsChanged:
                std::cout << "onClientNotification: Root Certs Changed" << std::endl;
                // Handle certificate rotation logic here
                break;

            case ASDVGateway_ClientNotificationType_RpcAvailabilityChanged:
                std::cout << "onClientNotification: RPC Availability Changed" << std::endl;
                // Handle reconnection or UI updates here
                break;

            default:
                std::cout << "onClientNotification: Received Unknown Notification ("
                          << notificationType << ")" << std::endl;
                break;
        }
    }
};

// --- Registration ---

NativeSdvGatewayTestApp* thisApp = get_current_app_context();

// Register the notification callback to monitor system-level changes
ASDVGateway_StatusCode_t statusCode = ASDVGateway_Client_setClientNotificationCallback(
    client,
    NativeSdvGatewayTestApp::ClientNotificationCallback,
    static_cast<void*>(thisApp), // userData
    &status
);

תהליך שרת RPC

כדי ליצור את שרת ה-RPC, צריך להשתמש בפרטי כניסה:

ASDVGateway_RpcCredentials_t* rpcCredentials = nullptr;

// Retrieve the credentials from the client
ASDVGateway_StatusCode_t statusCode = ASDVGateway_Client_rpcCredentials(client, &rpcCredentials, &status);

// Validation: Differentiating between an error and a deliberate "insecure mode"
if (status.statusCode != ASDVGateway_StatusCode_OK) {
    std::cerr << "Error retrieving credentials: " << status.errorMessage << std::endl;
    return;
}

// Logic for choosing Security Credentials
if (rpcCredentials == nullptr) {
    // If the call succeeded but credentials are null, the system expects insecure communication
    std::cout << "Configuring for Insecure Mode" << std::endl;
} else {
    std::cout << "Configuring for Secure Mode:" << std::endl;
    std::cout << "  Private Key: " << (rpcCredentials->privateKeyPem ? "Present" : "Missing") << std::endl;
    std::cout << "  RootCerts:   " << rpcCredentials->rootCertsPem << std::endl;
    std::cout << "  CertChain:   " << rpcCredentials->certChainPem << std::endl;
    std::cout << "  SAN:         " << rpcCredentials->subjectAlternativeName << std::endl;
}

// --- Cleanup ---

// Release the memory once the RPC server/client is initialized
if (rpcCredentials != nullptr) {
    ASDVGateway_Client_deleteRpcCredentials(client, rpcCredentials);
}

אחרי שיוצרים את שרת ה-RPC ויודעים מהי יציאת ההאזנה שלו, רושמים את שרת ה-RPC כדי שהוא יוכל לגלות אפליקציות אחרות:

ASDVGateway_RegisterRpcServerParams_t params{
    .serviceUnitName = "android-sdv-samples-sunroof-sunroof",
    .unitType = ASDVGateway_UnitType_t{
        .sdvPackageName     = "android.sdv.samples.sunroof",
        .serviceBundleName  = "SunroofServer",
        .unitTypeName       = "Sunroof",
    },
    .listeningPort = listeningPort,
    .serverUnitMetadata = ASDVGateway_ServerUnitMetadata_t{
        .version = 1,
    },
};

// Register the RPC server with the SDV Gateway
ASDVGateway_StatusCode_t statusCode = ASDVGateway_Client_registerRpcServer(
    client,
    &params,
    &status
);

// Basic error handling
if (statusCode != ASDVGateway_StatusCode_OK) {
    std::cerr << "Failed to register RPC server: " << status.errorMessage << std::endl;
}

כשהמערכת מעדכנת את אישורי הבסיס בזמן הריצה (לדוגמה, במהלך שינויים במצב של ה-VM), שרתי ה-RPC צריכים לרענן את רשימת האישורים המקובלים:

  • מגדירים מאזין לאירועי לקוח באמצעות ASDVGateway_Client_setClientNotificationCallback כדי לקבל התראה כשאישורי הבסיס עודכנו.

  • מפעילים את ASDVGateway_Client_rpcCredentials כדי לקבל את אישורי הבסיס המעודכנים.

תהליך הלקוח ב-RPC

זה התהליך של לקוח ה-RPC:

ASDVGateway_FindRpcServerByNameParams_t params{
    .packageName        = "android.sdv.samples.cluster",
    .serviceBundleName  = "ClusterServer",
    .serviceUnitName    = "android-sdv-samples-cluster-cluster",
};

ASDVGateway_SocketAddress_t socketAddress;
ASDVGateway_RpcCredentials_t* rpcCredentials = nullptr;

// Perform the lookup to find the server's location and security requirements
ASDVGateway_StatusCode_t statusCode = ASDVGateway_Client_findRpcServerByName(
    mClient,
    &params,
    &socketAddress,
    &rpcCredentials,
    &status
);

// Mandatory check: Distinguish between system errors and intentional "Insecure Mode"
if (status.statusCode != ASDVGateway_StatusCode_OK) {
    std::cerr << "Failed to find RPC server: " << status.errorMessage << std::endl;
    return;
}

// Logic for establishing the RPC channel
if (rpcCredentials == nullptr) {
    std::cout << "Connecting via Insecure Mode to "
              << socketAddress.address << ":" << socketAddress.port << std::endl;
} else {
    std::cout << "Connecting via Secure Mode to "
              << socketAddress.address << ":" << socketAddress.port << std::endl;

    std::cout << "  RootCerts: " << rpcCredentials->rootCertsPem << std::endl;
    std::cout << "  SAN:       " << rpcCredentials->subjectAlternativeName << std::endl;
    // Note: privateKeyPem and certChainPem are typically used if the client
    // needs to perform mutual TLS (mTLS).
}

// Cleanup: Release the credential memory once the RPC channel is established
if (rpcCredentials != nullptr) {
    ASDVGateway_Client_deleteRpcCredentials(client, rpcCredentials);
}

יצירת בעל תוכן דיגיטלי ופרסום הודעות

ממשק ה-API של ASDVGateway_Client_createPublication משמש לרישום יחידת שירות של בעל אפליקציה ב-SDV Gateway דרך ממשק ה-AIDL שלו, וליצירת תור הודעות מהיר (FMQ) בתהליך האפליקציה. ‫Binder מעורב רק בהגדרה של ה-FMQ, ולא בכתיבת הודעות. לאחר מכן, משתמשים ב-API של ASDVGateway_Client_publishMessages כדי לפרסם הודעות באתר החדשות שנוצר. התהליך הזה כולל כתיבה ל-FMQ של הפרסום והודעה על כך שהודעות נכתבו.

ASDVGateway_CreatePublicationParams_t params{
    .serviceUnitName = "mirror-position-adjust-impl-1",
    .unitType = ASDVGateway_UnitType_t{
        .sdvPackageName     = "android.sdv.samples.sdv_gateway",
        .serviceBundleName  = "DtPublisher",
        .unitTypeName       = "MirrorPositionAdjust",
    },
    .publisherUnitMetadata = ASDVGateway_PublisherUnitMetadata_t{
        .version          = 1,
        .messageSizeBytes = 64,
        .messageCount     = 16,
    },
};

ASDVGateway_PublicationMetadata_t metadata;

// 1. Create the Publication (allocates resources on the gateway)
ASDVGateway_StatusCode_t createStatus = ASDVGateway_Client_createPublication(
    client,
    &params,
    &metadata,
    &status
);

if (status.statusCode != ASDVGateway_StatusCode_OK) {
    std::cerr << "Failed to create publication: " << status.errorMessage << std::endl;
    return;
}

// 2. Publish Messages
// Note: serializedMessage should contain your encoded protobuf data
std::vector<uint8_t> serializedMessage;

ASDVGateway_Client_publishMessages(
    client,
    serializedMessage.data(),
    serializedMessage.size(),
    metadata.publicationId,
    &status
);

יצירת מנוי עם מאזין להתראות

כדי להירשם לפרסום ולקבל התראות מ-Data Tunnel (כמו זמינות של הודעות), משתמשים ב-API של ASDVGateway_Client_subscribeToPublicationByName. ה-API הזה גם מגדיר את ה-FMQ לקריאת הודעות שפורסמו. אפשר להגדיר קריאה חוזרת (callback) של התראה במהלך תהליך ההרשמה או אחריו.

#include <map>
#include <memory>
#include <iostream>

class NativeSdvGatewayTestApp {
public:
    struct SubscriptionContext {
        int32_t subscriptionId;
        std::string topicName;
        // Add other context-specific data here (e.g., counters, buffers)
    };

    /**
     * Callback triggered when new data is published to a subscribed topic.
     */
    static void SubscriptionNotificationCallback(
        const ASDVGateway_SubscriptionNotificationData_t* notification,
        void* userData
    ) {
        // The SDV Gateway client passes back the userData pointer.
        // We ensure validity by managing the lifecycle of SubscriptionContext
        // within the mSubscriptions map.
        auto* ctx = reinterpret_cast<SubscriptionContext*>(userData);

        if (ctx && notification) {
            // React to data being available for the subscription.
            // Example: handleIncomingData(notification->data, notification->size);
            std::cout << "Notification received for sub ID: " << ctx->subscriptionId << std::endl;
        }
    }

private:
    // Maps subscription handles/IDs to their respective contexts
    std::map<int32_t, std::unique_ptr<SubscriptionContext>> mSubscriptions;
};

// --- Usage ---
NativeSdvGatewayTestApp app;

כשנרשמים, אפשר לציין אפשרויות נוספות לצד שם יחידת השירות של בעל התוכן הדיגיטלי. האפשרויות האלה מאפשרות לכם לאחזר את ההודעה האחרונה שפורסמה לפני ההרשמה, ולהגדיר את מרווח הזמן המינימלי בין ההתראות.

ASDVGateway_SubscribeToPublicationByNameParams_t params{
    .sdvVmName           = "vm1",
    .packageName         = "test.package.impl.name",
    .serviceBundleName   = "TestBundleImpl",
    .serviceUnitName     = "GrpcServerImpl",
};

ASDVGateway_Subscriber_Options_t options{
    // Ensure we receive the most recent message immediately upon subscribing
    .flags         = ASDVGATEWAY_SUBSCRIBER_OPTIONS_FLAG_FETCHLASTMESSAGE,
    .minIntervalMs = 0, // No rate limiting; receive updates as they happen
};

// 1. Prepare the context for the callback
auto subCtx = std::make_unique<SubscriptionContext>();
ASDVGateway_PublicationMetadata_t metadata{};

// 2. Perform the subscription
ASDVGateway_StatusCode_t statusCode = ASDVGateway_Client_subscribeToPublicationByName(
    client,
    &params,
    &options,
    NativeSdvGatewayTestApp::SubscriptionNotificationCallback,
    static_cast<void*>(subCtx.get()), // Pass the raw pointer as userData
    &metadata,
    &status
);

// 3. Validation and Lifecycle Management
if (status.statusCode != ASDVGateway_StatusCode_OK) {
    // Error handling: subCtx will be automatically deleted here
    std::cerr << "Subscription failed: " << status.errorMessage << std::endl;
    return;
}

// Store the context using the publicationId as the key.
// Once moved, the map owns the lifetime of subCtx.
app.mSubscriptions.emplace(metadata.publicationId, std::move(subCtx));

משתמשים ב-API של ASDVGateway_Client_readAvailableMessages כדי לקרוא הודעות מהפרסום:

uint32_t messagesAvailable = 0;

// 1. Check how many messages are waiting in the queue
ASDVGateway_StatusCode_t availStatus = ASDVGateway_Client_availableToRead(
    client,
    metadata.publicationId,
    &messagesAvailable,
    &status
);

if (status.statusCode != ASDVGateway_StatusCode_OK) {
    // Error handling for availability check
    return;
}

if (messagesAvailable == 0) {
    // No messages available for this publication at this time
    return;
}

// 2. Prepare the buffer
// metadata.messageSizeBytes was provided during the publication/subscription setup
std::vector<uint8_t> bytesForMessages;
bytesForMessages.resize(metadata.messageSizeBytes * messagesAvailable);

// 3. Read the messages from the Gateway into your local buffer
uint32_t actualMessageCount = 0; // Filled by the SDK with the number of messages read
ASDVGateway_StatusCode_t readStatus = ASDVGateway_Client_readAvailableMessages(
    client,
    metadata.publicationId,
    bytesForMessages.data(),
    bytesForMessages.size(),
    &actualMessageCount,
    &status
);

if (status.statusCode == ASDVGateway_StatusCode_OK) {
    // Successfully read 'actualMessageCount' messages
    // Process bytesForMessages...
}

כדי להגדיר את הקריאה החוזרת (callback) אחרי ההרשמה, משתמשים ב-API של ASDVGateway_Client_setNotificationCallbackForPublicationId:

ASDVGateway_StatusCode_t ASDVGateway_Client_setNotificationCallbackForPublicationId(
    // [in]  Opaque pointer to the client object.
    const ASDVGateway_Client* client,

    // [in]  Identifies the specific publication to monitor.
    const int32_t publicationId,

    // [in]  Function pointer triggered when new data is available
    //       for the specified publication.
    ASDVGateway_SubscriptionNotificationCallback notificationCallback,

    // [in]  Optional user-defined context passed back to the callback.
    void* notificationCallbackUserData,

    // [out] Optional pointer to a status structure for result codes
    //       and error messages.
    ASDVGateway_Status_t* outStatus
);

הגדרת שירות init

קודם כל, פועלים לפי ההוראות במאמר זהות לשירותים מקומיים כדי להקצות זהות שירות לשירות באמצעות מזהה Android‏ (AID) שלו.

נניח שלשירות קוראים native_sdv_gateway_client_service, קובץ ההפעלה נמצא במחיצה /vendor בנתיב /vendor/bin/native_sdv_gateway_client_service, ואתם משתמשים ב-vendor_gateway_client בתור מזהה Android‏ (AID) להפעלת השירות. בהגדרה הזו, אפשר להגדיר את שירות ה-init הבא:

service native_sdv_gateway_client_service /vendor/bin/native_sdv_gateway_client_service
    class core
    user vendor_gateway_client
    group inet
    disabled
    oneshot

ההגדרה הזו משתמשת בפרמטרים הבאים:

  • ‫vendor_gateway_client הוא ה-AID שנוצר או נבחר בשביל השירות.
  • כדי להשתמש בממשק הרשת לתקשורת בין מכונות וירטואליות של SDV, צריך את group inet ללקוחות של שער SDV. אפשר להוסיף קבוצות אחרות לפי הצורך.
  • בדוגמה הזו נעשה שימוש ב-disabled וב-oneshot. יכול להיות שתצטרכו לשנות את אפשרויות השירות של השירות שלכם. הפעלת השירות אחרי sdv_gateway.

יצירת כללי SELinux לשירות

כדי להשתמש בממשקי ה-API של SDV Gateway, צריך את כללי SELinux הבאים לשירות:

# Define the domain for the service
type native_sdv_gateway_client_service, domain;

# Define the executable file type on the vendor partition
type native_sdv_gateway_client_service_exec, exec_type, file_type, vendor_file_type;

# Macro to transition from 'init' to this service's domain upon execution
init_daemon_domain(native_sdv_gateway_client_service)

# Macro to grant the necessary permissions to communicate with the SDV Gateway
sdv_gateway_client_domain(native_sdv_gateway_client_service)

בכללי SELinux:

  • ‫init_daemon_domain מאפשר להפעיל את השירות מ-init.

  • sdv_gateway_client_domain מספק את כל הרשאות SELinux הנדרשות לאינטראקציה עם שער SDV. השורה הבאה מעניקה את הכללים האלה לקובץ ההפעלה:

    /vendor/bin/native_sdv_gateway_client_service    u:object_r:native_sdv_gateway_client_service_exec:s0
    

דוגמת קוד

כדי לקבל מידע נוסף על הפעלת דוגמת קוד Native שמדגימה איך ממשקי ה-API של C מתועדים, ראו system/software_defined_vehicle/samples/sdv_gateway/NativeSdvGatewayTestApp/README.md.

שער SDV באפליקציית IVI Java

מודל האינטראקציה של שער SDV ב-IVI מוצג בתרשים הזה:

שער SDV באפליקציית IVI Java

איור 4. שער SDV באפליקציית IVI Java.

באופן ספציפי, המודל:

  • שולח את כל הקריאות לשכבת ה-JNI.
  • מחבר בין Java API ל-C API.
  • מגדיר אינטראקציות של AIDL עם ISdvGateway:
    • התחלת התקשורת
    • חיפוש או יצירה של שרת ה-RPC
    • יצירת ה-Pub/Sub
    • ביצוע אינטראקציות של Data Tunnel לזיהוי שירותים
    • קבלת התראות (לדוגמה, נתונים זמינים)
    • קריאה וכתיבה של הודעות (FMQ ל-Pub/Sub) ליצירת זוג מפתחות ואישורים ל-TLS

הכללת ספריות לקוח של Gateway

ספריית Java ו-JNI wrapper ל-C API של libsdvgatewayclient מותקנים ב-APEX ביעד ה-IVI. מוסיפים תלות בזמן הידור ל-stub של ספריית Java, לספריית Java שצריך להשתמש בה בזמן הריצה ול-APEX הנדרש שמכיל את ספריית Java.

android_app {
    name: "YourAppName",
    // ...
    static_libs: [
        "libsdvgatewayclient-java",
    ],
    libs: [
        "libsdvgatewayclient-java-sdk.stubs",
    ],
    uses_libs: [
        "libsdvgatewayclient-java-sdk",
    ],
    required: [
        "com.sdv.google.gateway.client",
    ],
    // ...
}

אם מדובר באפליקציה נפרדת שפותחה מחוץ לעץ ה-SDV, התהליך דומה:

  1. מעתיקים את קובץ ה-JAR של ספריית ה-Java שנוצר ואת קובץ ה-JAR שתומך ב-RPC לתיקיית הספריות של האפליקציה. מידע נוסף מופיע במאמר system/software_defined_vehicle/sdv_gateway/libsdvgatewayclient_apex/README.md.

  2. מוסיפים את קובץ ה-JAR של ה-stubs כתלות מסוג compile-only. לדוגמה, מעדכנים את ההגדרות של Gradle כך שיהיו תלויות ב-stubs, על ידי הוספת רשומה של compileOnly לקטע dependencies:

    dependencies {
        // The library supporting functions for SDK RPC.
        // Statically linked into the app APK.
        implementation(files("libs/libsdvgatewayclient-java.jar"))
    
        // Stub of the SDV-Gateway client library.
        // Used only for compilation; the real implementation is provided
        // by the com.sdv.google.gateway.client APEX at runtime.
        compileOnly(files("libs/libsdvgatewayclient-java-sdk.jar"))
    }
    
  3. מוסיפים את ספריית Java לקטע של האפליקציה בקובץ AndroidManifest.xml.

    <manifest xmlns:android="http://schemas.android.com/apk/res/android">
    
        <application>
    
            <!--
              Declares that this app requires the SDV Gateway client library.
              The 'android:required="true"' attribute ensures the app won't
              install/run if the library is missing from the system.
            -->
            <uses-library
                android:name="libsdvgatewayclient-java-sdk"
                android:required="true" />
    
        </application>
    
    </manifest>
    

טעינת ספריות

יוצרים אובייקט SdvGatewayClient (שמסופק על ידי ספריית הלקוח):

import google.sdv.gateway.client.SdvGatewayClient;

// --- Inside your Activity, Service, or ViewModel ---

// Initialize the SDV Gateway Client
SdvGatewayClient gatewayClient = new SdvGatewayClient();

התחלת התקשורת

מפעילים את initComms() באמצעות שם האפליקציה בתור שם חבילת השירות:

// Define a unique name for your service bundle (usually constant)
private static final String SERVICE_BUNDLE_NAME = "MySdvServiceBundle";

// ... inside an Activity or Service context ...

try {
    // Initialize communications with the SDV Gateway
    // context.getPackageName() provides "android.sdv.samples.gateway.client" or similar
    gatewayClient.initComms(context.getPackageName(), SERVICE_BUNDLE_NAME);

    Log.i("SDV_GATEWAY", "Communications initialized successfully");
} catch (Exception e) {
    // Unlike the C API which uses status codes,
    // the Java SDK often throws exceptions for initialization failures.
    Log.e("SDV_GATEWAY", "Failed to initialize communications", e);
}

זיהוי שירותים

ה-Java API מכיל שיטות לביצוע הפעולות הבאות:

  • קבלת התראה כשיחידות שירות עם סוג יחידה ספציפי (או לחלופין, תואמות לשם ספציפי) נרשמות או מוסרות מהרישום.

  • מציגים את יחידות השירות הנוכחיות עם סוג יחידה ספציפי (או לחלופין, מתאימים לשם ספציפי של סוג יחידת שירות). כדי לקבל התראות על שינויים ביחידות השירות, צריך ליצור מאזין:

import google.sdv.gateway.client.ServiceUnitChangeListener;
import google.sdv.gateway.client.ServiceUnitChangeEventType;
import google.sdv.gateway.client.ServiceUnitDefinition;

// --- Implementation ---

ServiceUnitChangeListener listener = new ServiceUnitChangeListener() {
    @Override
    public void onServiceUnitChanged(
        ServiceUnitChangeEventType eventType,
        ServiceUnitDefinition serviceUnitDefinition
    ) {
        // This is triggered when services matching your criteria
        // are registered or unregistered on the vehicle network.
        if (eventType == ServiceUnitChangeEventType.REGISTERED) {
            // Handle new service discovery
        } else if (eventType == ServiceUnitChangeEventType.UNREGISTERED) {
            // Handle service removal
        }
    }
};

ה-method‏ addListenerForServiceUnitChangeByName ב-Java שולחת התראה למאזין:

// 1. Register the listener for a specific service unit by name
AutoCloseable handle = gatewayClient.addListenerForServiceUnitChangeByName(
    new UnitNameDiscoveryArgs(
        "",                                   // sdvVmName (empty for local/auto-discovery)
        "android.sdv.samples.cluster",        // sdvPackageName
        "ClusterServer",                      // serviceBundleName
        "android-sdv-samples-cluster-cluster" // serviceUnitName
    ),
    listener
);

// --- Later in the application lifecycle ---

// 2. To stop receiving notifications and clean up resources, close the handle.
try {
    if (handle != null) {
        handle.close();
    }
} catch (Exception e) {
    Log.e("SDV_GATEWAY", "Error while closing the listener handle", e);
}

לחלופין, אפשר להשתמש ב-method‏ addListenerForServiceUnitChangeByType של Java כדי להודיע למאזין כששירותים עם סוג היחידה שצוין רשומים או לא רשומים:

// 1. Register a listener based on the Service Unit Type
AutoCloseable handle = gatewayClient.addListenerForServiceUnitChangeByType(
    new UnitType(
        "com.android.testapp.sdvcarmonitor", // sdvPackageName
        "SunroofRpcServer",                  // serviceBundleName
        "Sunroof"                            // unitTypeName
    ),
    listener
);

// --- Execution Loop / Lifecycle ---

// 2. To stop receiving notifications and clean up memory, close the handle.
// This effectively unregisters the listener from the SDV Gateway.
try {
    if (handle != null) {
        handle.close();
    }
} catch (Exception e) {
    Log.e("SDV_GATEWAY", "Failed to close the service unit listener handle", e);
}

ב-addListenerForServiceUnitChangeByName וב-addListenerForServiceUnitChangeByType, אחרי שמוסיפים את המאזין, הוא מקבל התראות על כל יחידות השירות הרשומות. כדי לקבל רק יחידות שירות רשומות לפי שם או סוג, משתמשים בממשקי ה-API של Java‏ listServiceUnitsByName ו-listServiceUnitsByType:

import google.sdv.gateway.client.ServiceUnitDefinition;
import google.sdv.gateway.client.UnitNameDiscoveryArgs;
import google.sdv.gateway.client.UnitType;

// --- 1. Synchronous Lookup by Specific Name ---
ServiceUnitDefinition[] definitionsByName = gatewayClient.listServiceUnitsByName(
    new UnitNameDiscoveryArgs(
        "",                                   // sdvVmName
        "android.sdv.samples.cluster",        // sdvPackageName
        "ClusterServer",                      // serviceBundleName
        "android-sdv-samples-cluster-cluster" // serviceUnitName
    )
);

// --- 2. Synchronous Lookup by Service Type ---
ServiceUnitDefinition[] definitionsByType = gatewayClient.listServiceUnitsByType(
    new UnitType(
        "com.android.testapp.sdvcarmonitor", // sdvPackageName
        "SunroofRpcServer",                  // serviceBundleName
        "Sunroof"                            // unitTypeName
    )
);

// Example processing
if (definitionsByType.length > 0) {
    ServiceUnitDefinition firstSunroof = definitionsByType[0];
    // Proceed to connect...
}

תהליך שרת RPC

לקוחות של SDV Gateway במערכות IVI משתמשים בקריאה לשירות מרוחק של Google‏ (gRPC) כדי לתקשר עם שירותי SDV. האינטראקציות האלה מסתמכות על הגדרות פרוטו מקטלוג VSIDL, שתואמות או דומות לאלה שמשמשות ב-SDV Core. באפליקציות Java, ההטמעה שנבחרה היא gRPC-Java. הגדרת proto לדוגמה של שרת, sunroof.proto, מסופקת לשרת אפליקציות.

service Sunroof {
    /**
     * Retrieves the current state of the sunroof (e.g., position, tilt, status).
     *
     * @param .google.protobuf.Empty - No input parameters required.
     * @return SunroofStateResponse - The current telemetry data for the sunroof.
     */
    rpc GetSunroofState(.google.protobuf.Empty) returns (SunroofStateResponse) {}
}

מקשרים לספריית הפרוטוקול המתאימה ומגדירים את השירות:

import com.android.sdv.sdvgrpclibrary.SunroofGrpc;
import com.android.sdv.sdvgrpclibrary.SunroofStateResponse; // Assuming this is the generated class
import com.google.protobuf.Empty;
import io.grpc.stub.StreamObserver;

/**
 * Implementation of the Sunroof gRPC service.
 * This class handles the logic for the RPCs defined in your .proto file.
 */
static class SunroofGrpcImpl extends SunroofGrpc.SunroofImplBase {

    @Override
    public void getSunroofState(Empty request, StreamObserver<SunroofStateResponse> responseObserver) {
        // 1. Fetch current sunroof data (e.g., from a Hardware Abstraction Layer)
        int currentPosition = 50; // Example value: 50% open

        // 2. Build the Protobuf response message
        SunroofStateResponse response = SunroofStateResponse.newBuilder()
                .setPercentageOpen(currentPosition)
                .build();

        // 3. Send the response to the client using the observer
        responseObserver.onNext(response);

        // 4. Close the stream to signal that the RPC is finished
        responseObserver.onCompleted();
    }
}

רושמים את שרת ה-gRPC עם פרטי כניסה לערוץ מאובטח ולא מאובטח:

// 1. Define the type signature for the service
UnitType unitType = new UnitType(
    "com.android.testapp.sdvcarmonitor", // sdvPackageName
    "SunroofRpcServer",                  // serviceBundleName
    "Sunroof"                            // typeName (Unit Type)
);

// 2. Register the RPC server with the Gateway
// The gateway creates a mapping between the ServiceUnitName and your implementation.
server = gatewayClient.registerRpcServer(
    "SunroofRpcServerImpl-1",                       // serviceUnitName (Unique instance name)
    unitType,                                       // unitType defined earlier
    "SUNROOF_GRPC_SERVER_VALUE_HOLDER".getBytes(),  // appMetadataValueHolder (Static discovery data)
    1,                                              // appMetadataVersion
    new SunroofGrpcImpl()                           // The actual gRPC service implementation
);

באופן פנימי, ספריית הלקוח יוצרת את אובייקט השרת של gRPC,‏ SdvGatewayClient.java, וגם מטפלת בעדכונים של אישורי הבסיס:

// 1. Initialize credentials (Insecure for dev, TLS for production)
ServerCredentials serverCredentials = InsecureServerCredentials.create();

// 2. Build and start the OkHttp-based gRPC server
final int bindAnyPort = 0;
final Server server = OkHttpServerBuilder
    .forPort(bindAnyPort, serverCredentials)
    .addService(gRpcServerImplementation) // Your SunroofGrpcImpl
    .build()
    .start();

// The assigned port can now be retrieved using server.getPort()
int actualPort = server.getPort();

// 3. Prepare the JNI data structure
// This object mirrors the ASDVGateway_ServiceUnitDefinition_t C struct
JniServiceUnitDefinition definition = new JniServiceUnitDefinition();

// Fill the RPC service definition params (Port, Name, Type, etc.)
definition.setPort(actualPort);
definition.setServiceUnitName("SunroofRpcServerImpl-1");

// 4. Perform the cross-language call
// This jumps from Java -> JNI -> ASDVGateway_Client_registerRpcServer (C API)
mJniClient.nativeRegisterRpcServer(definition);

תהליך הלקוח ב-RPC

דוגמת הקוד הזו מספקת את הגדרת הפרוטוקול של השרת (tpms.proto) שאליו האפליקציה מתחברת כלקוח:

/**
 * The TPMS service provides real-time pressure and temperature
 * data for all tires on the vehicle.
 */
service Tpms {
    /**
     * Returns the full state of all monitored tires.
     */
    rpc GetTpmsState(.google.protobuf.Empty) returns (TpmsStateResponse) {}

    /**
     * A filtered query that returns only the tires
     * below the recommended pressure threshold.
     */
    rpc GetLowTires(.google.protobuf.Empty) returns (LowTiresResponse) {}
}

קישור לספריית הפרוטו המתאימה:

import com.android.sdv.sdvgrpclibrary.TpmsGrpc;
import io.grpc.ManagedChannel;

// --- Inside your Client Application ---

// 1. Request a ManagedChannel from the Gateway for a specific service unit
ManagedChannel managedChannel = gatewayClient.connectToRpcServerByName(
    "",                                     // sdvVmName (empty for local/auto-lookup)
    "android.sdv.samples.cluster",          // packageName
    "ClusterServer",                        // serviceBundleName
    "android-sdv-samples-cluster-cluster"  // serviceUnitName
);

// 2. Use the channel to create a gRPC stub (e.g., for the TPMS service)
TpmsGrpc.TpmsBlockingStub tpmsStub = TpmsGrpc.newBlockingStub(managedChannel);

// 3. Now you can call RPC methods directly
// TpmsStateResponse response = tpmsStub.getTpmsState(Empty.getDefaultInstance());

באופן פנימי, מתבצעת קריאה ל-API של ASDVGateway_Client_findRpcServerByName כדי למצוא את שרת ה-RPC. אם שרת ה-RPC נמצא, הערוץ המנוהל נוצר במצב לא מאובטח או מוגדר לשימוש בהגדרת ה-TLS, בדומה לתהליך של שרת ה-RPC, בהתאם להגדרת זיהוי השירותים. האפליקציה יוצרת את ה-stubs באמצעות האובייקט ManagedChannel וקוראת ל-methods של השרת:

import com.android.sdv.sdvgrpclibrary.TpmsGrpc;
import com.android.sdv.sdvgrpclibrary.TpmsStateResponse;
import com.google.protobuf.Empty;
import io.grpc.stub.MetadataUtils;

// 1. Create a "Blocking Stub" from the existing ManagedChannel.
// We apply an interceptor to attach mandatory metadata (headers)
// required by the SDV Gateway for authorization.
TpmsGrpc.TpmsBlockingStub tpmsStub = TpmsGrpc.newBlockingStub(managedChannel)
    .withInterceptors(MetadataUtils.newAttachHeadersInterceptor(mMetadata));

// 2. Execute the RPC call.
// Because this is a "BlockingStub," the thread will wait here until
// the vehicle service responds or times out.
TpmsStateResponse tpmsStateResponse = tpmsStub.getTpmsState(Empty.getDefaultInstance());

// 3. Extract the domain-specific state object from the Protobuf response.
// 'newState' can now be used to update your UI or application logic.
newState = tpmsStateResponse.getTpmsState();

החלפת רשת ברירת המחדל של התהליך

יכול להיות שתצטרכו לעבור מ-SDV-RPC VLAN כרשת ברירת המחדל של התהליך כדי לפתוח שקעים לחיבורים לאינטרנט. מפעילים את unbindProcessFromSdvRpcNetworkInterface ו-bindProcessToSdvRpcNetworkInterface כדי לבטל את הקישור של התהליך ל-SDV-RPC VLAN ולקשר אותו מחדש. שתי הקריאות פועלות כמתגים גלובליים, ומחליפות את ממשק הרשת שאליו השקעים קשורים בכל השרשורים של התהליך.

// 1. Redirect all socket traffic from this process to the SDV-RPC VLAN.
// This call is required for making RPC calls or hosting RPC services for SDV.
gatewayClient.bindProcessToSdvRpcNetworkInterface();

// --- Process is now communicating over the SDV-RPC interface ---

// 2. Revert the process network binding back to the "default" interface.
// This allows the app to access internet resources again.
gatewayClient.unbindProcessFromSdvRpcNetworkInterface();

יצירת בעל תוכן דיגיטלי ופרסום הודעות

// 1. Define the interface and type for the publication
UnitType unitType = new UnitType(
    "android.sdv.samples.tires.interface", // sdvPackageName
    "TirePressurePublisherInterface",      // serviceBundleName
    "TirePressure"                         // typeName
);

// 2. Configure the Publisher's buffer and message constraints
PublisherUnitMetadata publisherUnitMetadata = new PublisherUnitMetadata(
    1,   // version
    64,  // message size in bytes (fixed size for performance)
    128  // max message count (buffer depth)
);

// 3. Create the Publication instance through the Gateway
Publisher tirePublisher = gatewayClient.createPublication(
    "tire-pressure-service-unit-name",
    unitType,
    publisherUnitMetadata
);

// 4. Prepare and publish a message
// In a real app, you would encode your sensor data into this byte array
byte[] msg = new byte[publisherUnitMetadata.messageSizeBytes];

// ... fill msg with data ...

tirePublisher.publish(msg);

באופן פנימי, ממשקי ה-API של Java createPublication ו-publish מסתמכים על ממשקי ה-API המקוריים של ASDVGateway_Client_createPublication ו-ASDVGateway_Client_readAvailableMessages. מידע מפורט על C API זמין במאמר שימוש ב-SDV Gateway בשירות מקורי של IVI. האובייקט Publisher מספק הקשר לכתיבת הודעות ולניהול מחזור החיים של הפרסום.

יצירת מנוי עם מאזין להתראות

ה-Java API מאפשר להעביר מאזין כפרמטר ל-method של ההרשמה לאתר החדשות, ומחזיר אובייקט Subscription.

  • ‫Listener מקבלת הודעה כשיש נתונים זמינים לאתר החדשות שאליו נרשמתם.

  • ‫Subscription פועל כאובייקט הקשר ואפשר להשתמש בו כדי לקרוא הודעות ולסגור את המינוי.

// 1. Define the Listener to handle incoming data notifications
SubscriptionNotificationListener listener = new SubscriptionNotificationListener() {
    @Override
    public void onSubscriptionNotification(
        Subscription subscription,
        SubscriptionNotificationType notificationType
    ) {
        // Only process if the notification indicates new data is ready
        if (notificationType != SubscriptionNotificationType.DataAvailable) {
            return;
        }

        // Read the message from the subscription buffer
        byte[] content = subscription.readMessage();

        // Note: This callback often runs on a background thread provided by the SDK.
        // If you need to update the UI, use a Handler or View.post().
        processTireData(content);
    }
};

// 2. Subscribe to the publication by its unique name
Subscription tireSubscription = gatewayClient.subscribeToPublicationByName(
    "",                                  // sdvVmName (empty for auto-lookup)
    "android.sdv.samples.dt_publisher",  // packageName
    "SdvGatewayDtPublisher",             // serviceBundleName
    "tire",                              // serviceUnitName
    listener
);

// 3. Read Messages
// You can poll or register callbacks for new messages.
// When polling the message, call this method in a loop.
// When registering callbacks, call this method to get the message payload.
byte[] manualContent = tireSubscription.readMessage();

דוגמת קוד

הפונקציות החוזרות (callbacks) של המאזינים מופעלות בשרשור יחיד שמנוהל על ידי הלקוח, כדי לצמצם את העיבוד בתוך המאזינים ולמנוע עיכובים בקבלת התראות על מינויים אחרים. שכבת ה-Java משתמשת ב-C API לניהול מינויים, לטיפול בהתראות ולאחזור הודעות. כדי לראות הדגמה של השימוש ב-API, אפשר לעיין בדוגמה של אפליקציית Java שמופיעה בקובץ הבינארי בכתובת system/software_defined_vehicle/samples/sdv_gateway/README.md.

ההרשאות הנדרשות

כדי לשלוח קריאה ל-API של לקוח SDV Gateway, לא צריך הרשאות מיוחדות, אבל צריך להחיל את כללי SELinux המתאימים על האפליקציות.

  • לא נדרשות הרשאות למינויים ולפרסומים של מנהרות נתונים.
  • כדי להשתמש ב-SDV RPC, צריך את ההרשאות הבאות:
    • android.permission.INTERNET
    • android.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS

ב-android.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS, צריך גם קובץ רשימת היתרים ב-etc/permissions באותה מחיצה כמו האפליקציה. לדוגמה, ב-SdvCarMonitorTestApp (שם החבילה com.android.testapp.sdvcarmonitor), הקובץ נראה כך:

<?xml version="1.0" encoding="utf-8"?>

<permissions>
    <privapp-permissions package="com.android.testapp.sdvcarmonitor">
        <permission name="android.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS"/>
    </privapp-permissions>
</permissions>

כללי SELinux

כדי להשתמש בממשקי ה-API של SDV Gateway, אפליקציות Java צריכות את אותן הרשאות כמו השירותים המקוריים. כדי להעניק את ההרשאות האלה, משתמשים בפקודת המאקרו הבאה של sdv_gateway_client_domain() SELinux:

sdv_gateway_client_domain(my_oem_sdv_gateway_client_app)

יצרן הציוד המקורי מגדיר את הדומיין my_oem_sdv_gateway_client_app לאפליקציות Java שמורשות להשתמש בשער SDV. השתמשו ב-SDV Gateway רק מאפליקציות מערכת ומאפליקציות עם הרשאות.

מיקומי קוד

מורידים את קוד המקור של SDV Gateway בכתובת system/software_defined_vehicle/sdv_gateway/. אתם יכולים לקבל דוגמאות ל-SDV Gateway בשביל:

  • Client C API: system/software_defined_vehicle/samples/sdv_gateway/NativeSdvGatewayTestApp/
  • ‫Client Java API: system/software_defined_vehicle/samples/sdv_gateway/SdvCarMonitorTestApp/