| 1 |
// Copyright (C) 2024 The Qt Company Ltd. |
| 2 |
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GFDL-1.3-no-invariants-only |
| 3 |
|
| 4 |
/*! |
| 5 |
\example vehicle |
| 6 |
\ingroup qtgrpc-examples |
| 7 |
\examplecategory {Networking} |
| 8 |
\meta tag {network,protobuf,grpc,threading} |
| 9 |
\title Vehicle |
| 10 |
|
| 11 |
\brief Manage two threaded connections between a Qt \gRPC client and a C++ \gRPC server. |
| 12 |
|
| 13 |
The example simulates a vehicle dashboard that displays data sent by a \gRPC server. |
| 14 |
\image vehicle.webp "Vehicle example dashboard screenshot" |
| 15 |
|
| 16 |
The example code has the following components: |
| 17 |
\list |
| 18 |
\li \c vehicle_client Qt \gRPC client application that uses the |
| 19 |
\l {qt_add_protobuf}{qt_add_protobuf()} and \l {qt_add_grpc}{qt_add_grpc()} CMake functions |
| 20 |
for message and service Qt code generation. |
| 21 |
\li \c vehicle_server application that calls C++ \gRPC plugin for generating server code and |
| 22 |
implementing simple server logic. |
| 23 |
\endlist |
| 24 |
|
| 25 |
\note you need the C++ \gRPC plugin installed. |
| 26 |
Find details here: \l {Module prerequisites} |
| 27 |
|
| 28 |
Both components use generated messages from the protobuf schemas described in the files |
| 29 |
\c {vehicleservice.proto} and \c {navigationservice.proto}. |
| 30 |
|
| 31 |
Vehicle service: |
| 32 |
\snippet vehicle/proto/vehicleservice.proto Proto types |
| 33 |
|
| 34 |
Navigation service: |
| 35 |
\snippet vehicle/proto/navigationservice.proto Proto types |
| 36 |
|
| 37 |
The \c VehicleManager \l {Singletons in QML#Defining singletons in C++} {C++ singleton} uses |
| 38 |
two \l QThread instances to communicate with the server in parallel. The threads have different |
| 39 |
\gRPC connection types. In this example, there are two types: |
| 40 |
\list |
| 41 |
\li Server streaming RPCs |
| 42 |
For example, the speed stream of the vehicle thread. It uses two callback functions: |
| 43 |
QGrpcServerStream::messageReceived and QGrpcOperation::finished |
| 44 |
\snippet vehicle/vehiclethread.cpp Speed stream |
| 45 |
|
| 46 |
\li Unary RPCs |
| 47 |
The RPC \c getAutonomy operation is a unary RPC. It returns a single response. It is only |
| 48 |
connected to the QGrpcOperation::finished signal. |
| 49 |
\snippet vehicle/vehiclethread.cpp Autonomy call |
| 50 |
\endlist |
| 51 |
|
| 52 |
The client main window interface is defined in the Main.qml file. It uses QML \l Connections |
| 53 |
type in order to connect to the signals of the \c VehicleManager |
| 54 |
\l {Singletons in QML#Defining singletons in C++} {C++ singleton} to custom slots: |
| 55 |
\snippet vehicle/Main.qml Connections |
| 56 |
|
| 57 |
After receiving a response, the client window updates the UI with the received data. This way, |
| 58 |
messages can be received in different threads and be sent to the client UI in a thread-safe way |
| 59 |
thanks to the signals. |
| 60 |
*/ |