Module 12 · Lesson 31 of 114

Method calls and events

Call ara::com methods, interpret future results and errors, and publish and consume event samples with explicit ownership.

  • Beginner to advanced
  • 10 min read
  • 13 min lab
What you will need

Familiarity with generated ara::com proxies and skeletons and basic C++ ownership. The practice exercises use a text editor on Ubuntu 24.04 in WSL2 or a VM.

Your place in the module
By the end you can 4 objectives
  • Trace a request-response method from proxy invocation to future completion.
  • Distinguish a local wait timeout, a communication error, and a service-defined error.
  • Describe how to subscribe, retrieve new samples, and unsubscribe.
  • Trace sample ownership through allocation, publication, and release.
Video coming soonMethod calls and events
The video for this lesson is being recorded. Read the lesson below in the meantime.
Recall first from Proxies, skeletons and the service interface
  • The consumer holds a generated proxy for a service instance, and the provider implements the contract exposed by the generated skeleton.
  • Request/response methods have a reply, fire-and-forget methods have no service reply, and events carry provider-published samples.
  • A field represents a value and can expose a getter, a setter, and a notifier, each with its own identifier when deployed over SOME/IP.
01

Calling a method and collecting its result

5 min read

The proxy and skeleton give an application its interface. This lesson answers how to call methods synchronously or asynchronously and how events deliver samples.

A program that waits for a reply on its only processing thread can delay other work on that thread. Linux exposes the same practical scheduling problem in a different API. A blocking socket receive waits when no message is available. With epoll, a program can wait for readiness across multiple descriptors and then perform the receive separately. The socket behavior is documented in recv(2) and epoll(7). In ara::com, the equivalent decision for a request-response operation is when the application chooses to wait for its future. The generated API supplies the future, and application code decides where a wait belongs.

Consider a sensor service with a method called RunSelfTest. A client passes the requested test mode to the generated proxy method. Communication Management conveys the request to the provider, where the skeleton dispatches it to the service implementation. The implementation completes the operation with its output or a supported error. The client's future represents the eventual outcome of that specific invocation. If the client starts two invocations, it gets two futures. Each future refers to its own call, even if the second operation finishes before the first.

Request and future completionClientProxyProviderInvoke methodReturn futureDispatch requestComplete operationFuture becomes ready1. Client → ProxyInvoke method2. Proxy → ClientReturn future3. Proxy → ProviderDispatch request4. Provider → ProxyComplete operation5. Proxy → ClientFuture becomes ready
A request-response call returns a future whose result belongs to that invocation.

Suppose the interface models two output arguments, passed and faultCount. The generated C++ API groups the outputs in a method-specific output type, conventionally named Output in the generated method type. The proxy returns an ara::core::Future parameterized by that output type. The expression that invokes the method therefore yields a future, and accessing the output members comes after successful completion. If the method has a reply with no output arguments, its completion can be represented by ara::core::Future<void>. A success in that case carries no payload. A modeled fire-and-forget method has no reply and supplies no future for the remote operation's outcome.

For synchronous use, invoke RunSelfTest and immediately retrieve the outcome with GetResult(). The calling thread waits if the future is pending. This is convenient when the next instruction depends on the test result and the thread can afford to wait. The generated call is still future-based. The caller has chosen synchronous behavior by waiting immediately. A small helper that invokes the method and collects the result before returning has the same effect on its caller.

For asynchronous use, store the future and let the caller continue with independent work. Later it can check readiness or wait with a duration using wait_for. Once the result is ready, it can collect it. Retain the future with enough context to interpret the reply when it arrives, such as the test mode or the client operation that requested it. Asynchronous use gives the client control of when it waits. The provider and the communication path still determine when the operation completes.

C++ offers std::future<T> for local asynchronous code. Its get() waits if necessary and retrieves a value or rethrows an exception stored in the shared state. The generated ara::com request-response API uses ara::core::Future, which provides an error-code path in addition to the exception-based access available when exceptions are enabled. A local test using std::future can demonstrate the timing of a wait. The generated proxy declaration determines the actual type used to call the service.

GetResult() yields an ara::core::Result whose successful value holds the generated output. Check HasValue() before reading Value(). When the result carries an error, inspect Error() for the ara::core::ErrorCode. Interpret the code together with its error domain because different domains can reuse the same numeric value. A communication error can indicate that the request could not be completed through the communication path. A service-defined error, when modeled for that method, can report that the provider rejected the requested test mode. On an exception-enabled build, get() can raise the exception associated with an error code. An exception handler then implements the corresponding failure policy.

A valid output with passed set to false is another possible outcome. In this example, it means the provider completed the self-test and reported a failed test through the output data. The client can display the returned fault count. If the provider rejected the test mode, the client instead handles the service error. If communication failed, the client handles the communication error. Keeping these cases distinct lets the application report what it actually knows about the operation.

A wait timeout is a decision point for the client. It can keep the future and check later, or apply its own policy for a result that arrives too late to use. The wait itself does not cancel the request. This matters when an operation changes provider state. Issuing a second request after the first wait expires can execute the operation again, so the method's contract must guide any retry.

02

Subscribing and retrieving event samples

4 min read

Suppose the same service publishes TemperatureUpdated. Its event type describes one measurement, for example a temperature and its acquisition timestamp. Each published value is a . The provider decides when to publish. It might publish after each measurement or when a measurement satisfies an application condition. A subscriber receives the values the provider publishes while its subscription is active and the communication path can deliver them. The subscription establishes ongoing interest. There is no separate request for each temperature measurement.

On the generated proxy, call Subscribe(maxSampleCount) on the event. The argument sets the maximum number of samples the application may hold at once for that event. Check the result of the subscription call and use GetSubscriptionState() when the application needs to know whether the subscription is active. A successful Subscribe call can precede establishment of the subscription. An application that displays a live reading can keep its reading marked as unavailable until it has actually received a sample. An active subscription can exist while the provider is between publications.

The proxy event's SetReceiveHandler registers a handler that Communication Management can invoke when new samples are available. In R24-11 SetReceiveHandler returns void and is noexcept, so there is no result to check. In an application that uses this notification path, register the handler before subscribing so that the application is ready to react when data arrives. The handler takes no sample argument. Inside the receive path, call GetNewSamples with a callable that accepts each newly retrieved sample handle. The application can also call GetNewSamples when it chooses to check for available data, for example when integrating event consumption into a periodic task.

Event notification and retrievalSubscriberProxy eventProviderSubscribeEstablishsubscriptionPublish samplesNotify availabilityGetNewSamplesDeliver samplehandlesUnsubscribe1. Subscriber → Proxy eventSubscribe2. Proxy event → ProviderEstablish subscription3. Provider → Proxy eventPublish samples4. Proxy event → SubscriberNotify availability5. Subscriber → Proxy eventGetNewSamples6. Proxy event → SubscriberDeliver sample handles7. Subscriber → Proxy eventUnsubscribe
A subscription establishes interest, a notification signals availability, and GetNewSamples supplies the data.

GetNewSamples can invoke the callable several times during one call. Its optional maximum limits how many samples that call can deliver. This per-call limit lets the application bound the number of sample callbacks it handles in one processing cycle. Check the returned result. On success, the value reports how many new samples were delivered to the callable during that call. Zero is a valid count. A reported error needs its own handling. The count describes local retrieval and should be interpreted within that scope.

To see why the notification and the retrieval are separate, suppose the provider publishes several readings while the subscriber is busy. When the subscriber processes the notification, more than one reading may already be available. One invocation of GetNewSamples may deliver several readings. If the application asks for a limited number and reaches that limit, it can schedule another retrieval when it wants to continue processing available data. Use the sample's timestamp when reasoning about measurement time, since the time the receive handler runs depends on when the subscriber gets to process the data.

The callable receives an ara::com::SamplePtr to the event data for read access. Dereference the handle while it owns the sample. For a display, the callable can read the temperature and timestamp, update application state with those values, and let the handle go out of scope. If later processing needs the entire sample, move the handle into storage owned by that processing code. A reference taken from the handle is usable only while some owner keeps the sample alive.

When the client no longer needs updates, call Unsubscribe() on the proxy event. If it is dismantling the receive path, remove the registered handler with UnsetReceiveHandler() and coordinate teardown with any application work already in progress. Release any retained sample handles when the application finishes using them. Ending the subscription stops the client's interest in future deliveries. Work the client has already scheduled still needs to finish or be discarded by the application.

03

Allocating and releasing samples

3 min read

On the provider side, a generated skeleton event offers Allocate() for obtaining middleware-managed storage for a sample. In R24-11 Allocate() returns the writable handle directly, and a failure to allocate is reported as a violation rather than through a returned error. Earlier releases declared a Result here, so check the generated header of your release. AUTOSAR distinguishes the writable allocation handle, ara::com::SampleAllocateePtr, from the subscriber's read-access ara::com::SamplePtr. Using the writable handle, fill in the temperature, timestamp, and any other fields of the sample directly. Then pass the handle to the event's Send overload by moving it with std::move. The Send overload returns an ara::core::Result<void> in R24-11, so check it and follow the event's error policy.

Sample ownership during publicationAllocatewritablesampleFill sampleMove intoSendReceiveread handleRead dataReleasehandleAllocatewritablesampleFill sampleMove intoSendReceiveread handleRead dataReleasehandle
The provider fills allocated storage, and the subscriber releases its receive handle after use.
Going deeperSample pools and ownership

Communication Management can manage reusable sample storage in pools. A pool makes sample lifetime relevant to capacity. Space occupied by a live sample is unavailable for reuse until the relevant ownership ends and the implementation can reclaim the storage. On the provider, allocation can fail (in R24-11 as a violation), so a producer should know its policy for an unavailable slot before trying to fill or send a sample. On the subscriber, retaining handles uses the application's simultaneous sample allowance. If the application reaches that allowance, it must release a handle before it can take ownership of another sample.

Moving a handle transfers ownership of the existing sample. The payload remains in its storage during that C++ move. On the provider, filling the allocated sample directly avoids first building a separate full payload and then copying it into the allocated object. Once ownership has been passed to Send, the provider must stop using that sample through the original handle or through references obtained from it. On the subscriber, moving the receive handle into a worker's storage similarly avoids copying the payload into a second application object. When the worker finishes, destruction or release of the handle gives the implementation the opportunity to reuse the receive storage.

A worker that saves every handle can eventually hold all the samples allowed by the subscription. For a client that only needs to display the latest numeric reading, extracting the few fields it needs and releasing the handle promptly can be cheaper than retaining the whole sample. For processing that needs the complete payload, keep ownership for the duration of that work and account for those retained handles in the subscription budget.

The copies avoided by handle moves are application-level payload copies. Whether the binding can share storage between processes, or must serialize and reconstruct the sample for transport, depends on the deployment and the implementation. A provider allocation and a subscriber handle therefore describe ownership on their respective sides. They give the application a way to manage sample lifetime even when the transport uses separate storage.

For practice, use the subscription trace to follow a notification through retrieval and release. Fields and choosing the right element follows by asking how a service should represent a value that clients may need to read directly and observe as it changes.

Key takeaways

  • A generated request-response proxy method returns an ara::core::Future for its result, and the caller decides when to wait.
  • GetResult exposes success or an error code without requiring the exception-based get path.
  • A receive notification indicates sample availability, and GetNewSamples delivers the available samples to the application.
  • Retained receive sample handles occupy storage until released.
Reflect
  1. Explain to a colleague, in two sentences: trace a request-response method from proxy invocation to future completion.
  2. Which objective are you least sure about? Re-read that section, then do its exercise in the practice pack.
  3. What surprised you when you ran the commands yourself?
On a real board

Repeat the key commands on your Raspberry Pi or lab board over SSH or the serial console. Note anything that behaves differently from your PC, such as missing tools, a BusyBox shell or a read-only filesystem.

References and further reading

Find your next step

↑ ↓ to move · Enter to open · Esc to close