Skip to content

gRPC Client

Requires AMC 2.5.2+.

GrpcClient calls gRPC services from plugin QML without generated code. Your plugin ships a descriptor set with the service and message definitions, and requests and responses are plain JavaScript objects. Unary calls and streams in either direction are supported. Over TLS it can present a client certificate.

Import: import QGroundControl.SecureConnections

The same import gives you GrpcOperation, which call() returns, and LinkState. Secure Connections covers what the HTTPS, gRPC and MQTT clients share: certificates, LinkState, settings changes and plugin removal. This page covers what is specific to gRPC.


Quick start

Write a descriptor set for your .proto files with protoc, the Protocol Buffers compiler:

protoc --include_imports --descriptor_set_out=proto/services.pb -I proto proto/helloworld.proto

Add the file to the plugin archive in build.sh:

zip -r "${OUTPUT_FILE}" plugin.json src/ img/ proto/services.pb

Declare a client in your Data singleton, src/MyPluginData.qml, and call a method. helloworld.Greeter/SayHello, from the gRPC examples, takes {name} and answers {message}.

pragma Singleton

import QtQuick
import QGroundControl.Plugin
import QGroundControl.SecureConnections

Item {
    id: root

    property string greeting: ""
    property alias greeter: greeterClient

    GrpcClient {
        id: greeterClient
        url: "https://dispatch.example.com:8443"
        descriptorSet: Qt.resolvedUrl("../proto/services.pb")
    }

    function sayHello(name) {
        const operation = greeterClient.call("helloworld.Greeter/SayHello", {name: name})
        operation.messageReceived.connect((reply) => {
            root.greeting = reply.message
        })
        operation.finished.connect((statusCode, statusMessage) => {
            if (statusCode !== 0) {
                PluginManager.log("MyPlugin: SayHello failed (" + statusCode + "): " + statusMessage)
            }
        })
    }
}

You can call right away, even from Component.onCompleted: a call made while the client is being set up waits, then goes out.

Declare clients in the Data singleton

A client lives as long as the QML object that declares it. When a client is destroyed, its running calls stop without emitting finished(). The Data singleton stays alive while views open and close.


Descriptor set

descriptorSet points at the file that protoc --descriptor_set_out=<file> --include_imports writes. It holds the services and messages the client can use.

MyPlugin/
├── plugin.json
├── build.sh
├── proto/
│   ├── helloworld.proto    ← source, stays out of the archive
│   ├── route_guide.proto   ← source, stays out of the archive
│   └── services.pb         ← descriptor set, goes into the archive
└── src/
    └── MyPluginData.qml
  • Always pass --include_imports. It adds the files your .proto files import, such as google/protobuf/timestamp.proto. Without them the set cannot be loaded.
  • One descriptor set per client. A client can call every service in its set. Write all the .proto files it needs in one protoc run:

    protoc --include_imports --descriptor_set_out=proto/services.pb \
        -I proto proto/helloworld.proto proto/route_guide.proto
    
  • Local files only. A relative URL resolves against the QML file that declares the client. Qt.resolvedUrl(...) works too.

  • Changing descriptorSet loads the new file at once. It does not reconnect. Running calls keep the definitions they started with.

If the set cannot be loaded, state is ConfigError, errorString says why, and calls finish with FAILED_PRECONDITION (9). Once a set loads, state shows the link again.

errorString Cause
No descriptor set is given. descriptorSet is empty.
Cannot open the descriptor set … The path is wrong, or the file is missing from the plugin archive.
The descriptor set is not a serialized FileDescriptorSet. The file is not a descriptor set.
… conflicts with another file in the descriptor set. A file appears twice, or two files define the same name, for example after joining two descriptor sets. Write the set in one protoc run.
… cannot be built; was the descriptor set written with --include_imports? A file it imports is missing from the set.

GrpcClient

Properties

Property Type Writable Description
url QUrl Yes The server, https://host:port. The port defaults to 443, and a path is ignored. http:// connects without TLS, to port 80 by default. Any other scheme, a missing host, port 0, or a user name or password in the URL gives ConfigError. The server's certificate must name this host: unlike HttpsClient, there is no expectedHostName.
certificateId QString Yes The certificate store entry to connect with. Empty: no client certificate, and the server is checked against the system CAs. Ignored with http://. See Certificates.
metadata QVariantMap Yes Sent with every call. See Metadata.
descriptorSet QUrl Yes The service and message definitions. See Descriptor set.
timeout int Yes Deadline for unary calls, in milliseconds. Default 10000; 0 for none, and a negative value counts as 0. Streams don't use it.
keepaliveInterval int Yes While a stream is open, checks every this many milliseconds that the server still answers. Default 0: off. A value from 1 to 9999 counts as 10000, a negative one as 0. See Detecting a dead connection.
state LinkState No How the link to the server stands. See Link state.
errorString QString No Explains Off and the error states. Empty while Connecting or Connected.

Changing url or certificateId sets the client up again: running calls finish with CANCELLED (1), and calls made meanwhile wait for the new setup. The other properties never reconnect.

Methods

Method Parameters Returns Description
call(method, request, options) QString, QVariant, QVariantMap GrpcOperation* Calls a unary method or opens a stream. request and options are optional. See Calling a method.

Signals

Signal Emitted when
stateChanged() state changed. errorString already explains the new state.
errorStringChanged() errorString changed.
configurationChanged() url or certificateId changed. There is no urlChanged(); use onConfigurationChanged.
metadataChanged() metadata changed.
descriptorSetChanged() descriptorSet changed.
timeoutChanged() timeout changed.
keepaliveIntervalChanged() keepaliveInterval changed.

Calling a method

const operation = client.call(method, request, options)
Argument Description
method The gRPC path package.Service/Method, e.g. "helloworld.Greeter/SayHello". A leading / is allowed.
request The request message as a JavaScript object. Left out, undefined or null sends the empty message. For a method that takes a stream of requests, this is the first one. See Messages as JavaScript objects.
options Settings for this call only, below.

call() always returns a GrpcOperation. A call that cannot go out does not throw: it finishes with a status code after call() has returned, so connect to the operation's signals right after the call.

Option Default Description
timeout Unary call: the client's timeout. Stream: none. Deadline in milliseconds. 0 for none.
idleTimeout Off For a stream of responses: ends the stream when no message arrives for this many milliseconds, then checks the connection. 0 turns it off; methods with a single response ignore it. See Detecting a dead connection.

Both take a number of milliseconds, 0 or more. A negative or non-numeric value, or any other option name, makes the call finish with INVALID_ARGUMENT (3).

Unary calls and streams

call() handles every kind of method; the method's definition in the descriptor set decides which.

  • Unary call: messageReceived(message) fires once with the response, then finished(0, …). A failed call emits only finished().
  • Server stream, such as routeguide.RouteGuide/ListFeatures: messageReceived(message) fires for every message. finished() follows when the server ends the stream, the stream fails, its deadline passes, or you call cancel().
  • Client stream, such as routeguide.RouteGuide/RecordRoute: request goes out at once as the first message, and send() adds more. Call closeSend() when you are done; the server then answers once, like a unary call. See the route recording example.
  • Bidirectional stream, such as routeguide.RouteGuide/RouteChat: you send() and the server answers in any order, each answer a messageReceived(message). closeSend() tells the server you are done; finished() follows when the server ends the stream.

A stream of requests always starts with a message: Qt GRPC sends one when it opens the stream. Leaving request out sends the empty message first, so pass the real first message to call() if your server reads it. Messages you send() before the connection is ready wait and go out in order.

Deadlines

  • A unary call's deadline is the client's timeout (10 s by default), unless the call passes its own.
  • A stream has a deadline only when its call passes timeout. The stream then ends after that time, even while messages are still flowing.
  • The clock starts with call(), so it also covers waiting for the client's setup (checking url, loading the client certificate, which may prompt for the keychain) and a stalled TLS handshake.
  • A call that runs out of time finishes with DEADLINE_EXCEEDED (4). One that was still waiting for the setup leaves state as it is.

Detecting a dead connection

Qt GRPC, which AMC uses, sends no HTTP/2 pings. If the network fails silently, the connection still looks open, and a stream that waits for its next message can wait indefinitely. Two settings catch this:

  • keepaliveInterval on the client: while a stream is open, AMC checks the connection every keepaliveInterval milliseconds. Use it for streams that only send when something changes. A dead connection is noticed within about two intervals.
  • idleTimeout on a call: when the stream receives no message for idleTimeout milliseconds, AMC cancels it with UNAVAILABLE (14), sets the state to Unreachable, and checks the connection, giving the server idleTimeout, but at least 10 s, to answer. Use it when the server sends at a steady rate, such as a heartbeat, and set it well above that rate.

A check calls grpc.health.v1.Health/Check on the same connection, without your metadata. Any answer counts, also an error such as UNIMPLEMENTED or UNAUTHENTICATED, so the server need not offer the health service. One check runs at a time.

When a check goes unanswered, AMC closes the connection and opens a new one. Every running call on the client finishes with UNAVAILABLE (14), and the state becomes Unreachable with errorString "The server did not answer within … ms." Open your streams again in finished(); they go out on the new connection, as the streaming example does. When the check is answered, only the stream that went quiet has ended.


GrpcOperation

call() returns a GrpcOperation. You cannot create one, and it has no properties.

Methods

Method Description
cancel() Ends the operation; finished() then reports CANCELLED (1). Does nothing once the operation has finished.
send(message) Sends one more request to a method that takes a stream of them. Returns false, and AMC's log says why, if the method takes a single request, after closeSend() or finished(), if the operation never started, or if AMC refuses the message, for example a NaN or an unknown field. A refused message does not end the stream.
closeSend() Tells the server that no more requests follow. Responses still arrive until finished(). Does nothing for a method that takes a single request, a second time, or after finished().

Signals

Signal Description
messageReceived(message) A response, as a JavaScript object. Once for a method with a single response, such as a unary call or a client stream, once per message for a stream of responses.
finished(statusCode, statusMessage) The operation is over. statusCode is the gRPC status code, 0 for OK. statusMessage explains it.

Lifetime

  • Every operation finishes exactly once, also when it could not start. The one exception: when the client is destroyed, its operations stop without finished().
  • finished() never fires before call() returns.
  • AMC owns the operation and deletes it soon after finished(), so you need not keep a reference for the call to run. If you keep one to cancel() later, set it to null in finished().
  • statusMessage is meant for people and may be translated. Decide on statusCode.

Messages as JavaScript objects

Requests and responses follow protobuf's standard JSON mapping:

Protobuf JavaScript
message Object. Field names are lowerCamelCase: work_order_id becomes workOrderId.
int32, uint32, sint32, fixed32, sfixed32 Number.
int64, uint64, sint64, fixed64, sfixed64 String in responses. String or number in requests; a string keeps values above 2^53 exact.
float, double Number. NaN and the infinities are the strings "NaN", "Infinity" and "-Infinity".
bool Boolean.
string String.
bytes Base64 string.
enum The value's name in responses, or its number if the descriptor set does not know it. Name or number in requests.
repeated Array. An array in a response has the array methods, but Array.isArray() returns false for it.
map<K, V> Object. Keys are strings.

Requests

  • Field names may also be written as in the .proto file, e.g. work_order_id.
  • A field the message does not have makes the call finish with INVALID_ARGUMENT (3), so a typo does not go unnoticed.
  • Leave a field out to send no value.

Responses

  • Every field is present. A field the server did not set holds its default: 0, "", false, [], {}, or the enum's zero value.
  • Message fields, optional fields and oneof members are the exception: they are missing when not set. Check them before reading inside them, e.g. if (feature.location).
  • Fields that are not in your descriptor set are dropped.

Well-known types

The google.protobuf well-known types have their own JSON forms, at any depth and also as a whole request or response. Your descriptor set must contain them; --include_imports takes care of that.

Type JavaScript Example
Timestamp RFC 3339 string. Responses are in UTC. "2026-10-27T09:30:00Z". Send new Date().toISOString(); read with new Date(value).
Duration Seconds with an s suffix "1.5s"
Empty Empty object {}
StringValue, Int32Value, BoolValue and the other wrappers The wrapped value. Int64Value and UInt64Value as strings. "text", 42, true
Struct Object {"color": "red"}
Value Any JSON value 3, "text", null
ListValue Array [1, "two"]
FieldMask Comma-separated paths in lowerCamelCase "name,location.latitude"
Any Object with an @type URL and the packed message's fields {"@type": "type.googleapis.com/routeguide.Point", "latitude": 1, "longitude": 2}

An Any can only hold a message type that is in the descriptor set.

Values AMC refuses

NaN, infinities and undefined make the call fail

A request that contains NaN, Infinity, -Infinity, undefined, or a value with no JSON form, such as a QML object or a Fact, finishes with INVALID_ARGUMENT (3), at any depth. The message names the field:

routeguide.Rectangle.lo.latitude is NaN, infinite, undefined or not a JSON value; leave a field out to send no value.

JSON has no form for these values. They would become null, which protobuf reads as "not set", so an unknown position would reach the server as 0. AMC refuses the request instead. A message given to send() is refused the same way, but send() returns false and the stream carries on.

  • Telemetry that is not known yet is often NaN, for example the vehicle.fuel values. Check with isNaN(), and leave the field out instead.
  • Pass a Fact's value or rawValue, not the Fact.
  • To send NaN or an infinity on purpose, use the strings "NaN", "Infinity" or "-Infinity".
  • null is allowed and means "not set". In a list, though, it makes the call finish with INVALID_ARGUMENT (3), unless the list holds google.protobuf.Values.

Metadata

metadata holds the headers sent with every call. A call takes metadata as it is when call() runs; changing it later affects only later calls and does not reconnect.

GrpcClient {
    id: dispatchClient
    url: "https://dispatch.example.com:8443"
    descriptorSet: Qt.resolvedUrl("../proto/services.pb")
    metadata: ({"authorization": "Bearer " + root.accessToken, "x-roles": ["viewer", "dispatcher"]})
}
  • Put an object literal in parentheses, as above. Without them, QML reads {…} as a block of code.
  • A list gives one name several values.
  • Names are sent in lower case and may contain only ASCII letters, digits, -, _ and .. Values must be printable ASCII.
  • Reserved names are refused: names starting with grpc- or qtgrpc-, and content-type, te and user-agent. So is binary metadata, whose names end in -bin.

While metadata breaks one of these rules, every call finishes with INVALID_ARGUMENT (3), and statusMessage names the entry.


Status codes

finished() reports the standard gRPC status codes. Most come from the server and are passed on unchanged. These also come from AMC or from the connection:

Code Name When
0 OK The call succeeded, or the server ended the stream normally.
1 CANCELLED You called cancel(), url or certificateId changed while the call ran, or its certificate entry was deleted.
3 INVALID_ARGUMENT An unknown option or a bad option value, invalid metadata, or a request that does not fit its message type or holds a value AMC refuses.
4 DEADLINE_EXCEEDED The call's deadline passed.
9 FAILED_PRECONDITION No descriptor set is loaded, or there is no connection because url is empty or unusable or the certificate entry was deleted.
12 UNIMPLEMENTED The descriptor set has no such service or method, or method is not a package.Service/Method path.
13 INTERNAL A response could not be read or does not match the descriptor set, or the reply is not valid gRPC.
14 UNAVAILABLE The server cannot be reached, the TLS handshake failed, a stream's idleTimeout passed, a check of the connection went unanswered, the client certificate cannot be used, or the call could not be started.

UNAUTHENTICATED (16) and PERMISSION_DENIED (7) come from the server and set the state to AuthError.


state is a LinkState value. The client connects as soon as it is set up, but only your calls tell state how the link stands:

State For a GrpcClient
Off url is empty.
Connecting The client is being set up, or no call has been answered since.
Connected The server answered the last call with a status not listed below, or a stream delivered a message.
Unreachable A call ended with UNAVAILABLE (14): the server could not be reached or reported itself unavailable, a stream's idleTimeout passed, or a check of the connection went unanswered. Also DEADLINE_EXCEEDED (4) on a call that went out: a unary call, or a stream that had no message yet.
TlsError The TLS handshake failed, or the client certificate cannot be loaded or is not valid now.
AuthError A call failed with UNAUTHENTICATED (16) or PERMISSION_DENIED (7).
ConfigError url is malformed or contains credentials, the certificate entry was deleted, or the descriptor set cannot be loaded.
  • Don't wait for Connected before the first call. Only a call gets the state there. Call whenever the state is not Off or ConfigError.
  • The latest answer counts. After an error, the next call the server answers sets the state back to Connected.
  • Some outcomes leave the state as it is: your own cancel(), and calls refused before they go out, such as for bad options, metadata or requests.
  • errorString is meant for people and may be translated. Use state in code.

To show the state, with the client exposed from the Data singleton as in the quick start:

import QtQuick
import QGroundControl.Controls
import QGroundControl.Plugin
import QGroundControl.SecureConnections

QGCLabel {
    text: {
        switch (MyPluginData.greeter.state) {
        case LinkState.Connected:
            return qsTr("Connected")
        case LinkState.Connecting:
            return qsTr("Connecting…")
        default:
            return MyPluginData.greeter.errorString
        }
    }
}

Connection changes

Secure Connections describes these for all three clients. For a GrpcClient:

Event Running calls Calls waiting for the setup Calls made afterwards
url or certificateId changes CANCELLED (1) Go out on the new connection Wait for the new setup
The certificate entry is deleted CANCELLED (1) FAILED_PRECONDITION (9) FAILED_PRECONDITION (9) until certificateId changes
The client certificate cannot be used None are running UNAVAILABLE (14) UNAVAILABLE (14). The first call a minute or more later loads the certificate again and waits for it. After a refused keychain prompt, calls fail until another client has loaded the entry, or url or certificateId changes.

Example: stream features into a model

routeguide.RouteGuide/ListFeatures, from the gRPC route guide example, streams the features inside a rectangle. Coordinates are degrees × 10^7. route_guide.proto must be in the descriptor set, as in Descriptor set.

This Data singleton fills a ListModel, checks the connection every 30 s while the stream is open, opens the stream again 5 s after it fails with UNAVAILABLE, and stops on request:

pragma Singleton

import QtQuick
import QGroundControl.Plugin
import QGroundControl.SecureConnections

Item {
    id: root

    property alias features: featureModel
    property var featureStream: null

    ListModel { id: featureModel }

    GrpcClient {
        id: routeGuide
        url: "https://dispatch.example.com:8443"
        descriptorSet: Qt.resolvedUrl("../proto/services.pb")
        keepaliveInterval: 30000
    }

    Timer {
        id: reopenTimer
        interval: 5000
        onTriggered: root.listFeatures()
    }

    function listFeatures() {
        if (root.featureStream) {
            return
        }
        featureModel.clear()
        const area = {
            lo: {latitude: 400000000, longitude: -750000000},
            hi: {latitude: 420000000, longitude: -730000000}
        }
        const stream = routeGuide.call("routeguide.RouteGuide/ListFeatures", area)
        root.featureStream = stream
        stream.messageReceived.connect((feature) => {
            if (feature.location) {
                featureModel.append({
                    name: feature.name,
                    latitude: feature.location.latitude / 1e7,
                    longitude: feature.location.longitude / 1e7
                })
            }
        })
        stream.finished.connect((statusCode, statusMessage) => {
            root.featureStream = null
            if (statusCode === 14) {
                // UNAVAILABLE: no connection, or the connection stopped answering
                reopenTimer.start()
            } else if (statusCode !== 0 && statusCode !== 1) {
                PluginManager.log("MyPlugin: ListFeatures failed (" + statusCode + "): " + statusMessage)
            }
        })
    }

    function stopFeatures() {
        reopenTimer.stop()
        if (root.featureStream) {
            root.featureStream.cancel()
        }
    }
}

MyPluginData.features can serve as the model of a MapItemView.


Example: look up the vehicle's position

routeguide.RouteGuide/GetFeature is a unary method that takes a point. Add this to the same singleton, together with import QGroundControl:

property string featureHere: ""

function lookUpVehiclePosition() {
    const vehicle = QGroundControl.multiVehicleManager.activeVehicle
    if (!vehicle || !vehicle.vehicleCoordinateValid) {
        return
    }
    const point = {
        latitude: Math.round(vehicle.latitude * 1e7),
        longitude: Math.round(vehicle.longitude * 1e7)
    }
    const operation = routeGuide.call("routeguide.RouteGuide/GetFeature", point)
    operation.messageReceived.connect((feature) => {
        root.featureHere = feature.name
    })
}

Until the vehicle has a position, vehicle.latitude is NaN, which AMC would refuse.


Example: record the vehicle's route

routeguide.RouteGuide/RecordRoute is a client stream: it takes any number of points and answers once, with a summary, after the last one. Add this to the same singleton, which needs import QGroundControl for the vehicle. It sends the vehicle's position every second until you stop it:

property var routeRecording: null

Timer {
    id: recordTimer
    interval: 1000
    repeat: true
    onTriggered: {
        const point = root.vehiclePoint()
        if (point && root.routeRecording) {
            root.routeRecording.send(point)
        }
    }
}

function vehiclePoint() {
    const vehicle = QGroundControl.multiVehicleManager.activeVehicle
    if (!vehicle || !vehicle.vehicleCoordinateValid) {
        return null
    }
    return {
        latitude: Math.round(vehicle.latitude * 1e7),
        longitude: Math.round(vehicle.longitude * 1e7)
    }
}

function startRecording() {
    const point = root.vehiclePoint()
    if (root.routeRecording || !point) {
        return
    }
    // The first point goes out with the call; send() adds the rest.
    const recording = routeGuide.call("routeguide.RouteGuide/RecordRoute", point)
    root.routeRecording = recording
    recording.messageReceived.connect((summary) => {
        PluginManager.log("MyPlugin: recorded " + summary.pointCount + " points over " + summary.distance + " m")
    })
    recording.finished.connect((statusCode, statusMessage) => {
        recordTimer.stop()
        root.routeRecording = null
        if (statusCode !== 0) {
            PluginManager.log("MyPlugin: RecordRoute failed (" + statusCode + "): " + statusMessage)
        }
    })
    recordTimer.start()
}

function stopRecording() {
    recordTimer.stop()
    if (root.routeRecording) {
        root.routeRecording.closeSend()
    }
}

stopRecording() only ends the requests. routeRecording stays set until the summary has arrived and finished() fires.