File: main.cpp

package info (click to toggle)
qt6-remoteobjects 6.8.2-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, trixie
  • size: 3,832 kB
  • sloc: cpp: 20,582; sh: 29; makefile: 23
file content (180 lines) | stat: -rw-r--r-- 7,845 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
// Copyright (C) 2022 The Qt Company Ltd.
// Copyright (C) 2019 Ford Motor Company
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause

#include "rep_heater_source.h"
#include "bleiodevice.h"

#include <QtRemoteObjects/QRemoteObjectNode>
#include <QtBluetooth/QLowEnergyCharacteristicData>
#include <QtBluetooth/QLowEnergyDescriptorData>
#include <QtBluetooth/QLowEnergyServiceData>
#include <QtBluetooth/QLowEnergyAdvertisingData>
#include <QtBluetooth/QLowEnergyController>
#include <QtBluetooth/QLowEnergyAdvertisingParameters>
#include <QtCore/QCoreApplication>
#include <QtCore/QTimer>
#include <QtCore/QLoggingCategory>
#include <QtCore/QCommandLineOption>
#include <QtCore/QCommandLineParser>

using namespace Qt::Literals::StringLiterals;

class Heater : public HeaterSimpleSource
{
    Q_OBJECT
public:
    explicit Heater(QObject* parent = nullptr) : HeaterSimpleSource(parent)
    {
        m_changeTimer.setInterval(std::chrono::seconds{2});
        m_changeTimer.setSingleShot(false);

        QObject::connect(&m_changeTimer, &QTimer::timeout, this, [this]() {
            if (heaterPoweredOn())
                setCurrentTemperature(currentTemperature() + 1);
            else
                setCurrentTemperature(currentTemperature() - 1);
        });

        m_changeTimer.start();
    }

private:
    QTimer m_changeTimer;
};

int main(int argc, char *argv[])
{
    QCoreApplication app(argc, argv);

    QCommandLineParser parser;
    parser.addHelpOption();
    QCommandLineOption verboseOption("verbose", "Verbose mode");
    parser.addOption(verboseOption);
    parser.process(app);
    if (parser.isSet(verboseOption)) {
        QLoggingCategory::setFilterRules("qt.remoteobjects* = true"_L1);
        QLoggingCategory::setFilterRules("qt.bluetooth* = true"_L1);
    }

    // The model that will be used as the source object
    std::unique_ptr<Heater> heater = std::make_unique<Heater>();
    std::unique_ptr<QLowEnergyController> bleController;
    std::unique_ptr<QRemoteObjectHost> hostNode;
    std::unique_ptr<BLEIoDevice> ioDevice;

    // Setup BLE server. The two-way communication consists of a GATT service
    // which has two characteristics. The characteristics form the two-way communication
    // between client/server. The characteristic notifications are enabled so that each
    // side (client/server) gets notified if the other has written data.
    QLowEnergyCharacteristicData rxCharData;
    rxCharData.setUuid(BLEIoDevice::CLIENT_TX_SERVER_RX_CHAR_UUID);
    // Allow the remote end (client) to write to this characteristic
    rxCharData.setProperties(QLowEnergyCharacteristic::Write);

    QLowEnergyCharacteristicData txCharData;
    txCharData.setUuid(BLEIoDevice::CLIENT_RX_SERVER_TX_CHAR_UUID);
    // Allow the remote end (client) to read characteristic's data and subscribe to value changes
    const QLowEnergyDescriptorData clientConfig(
                QBluetoothUuid::DescriptorType::ClientCharacteristicConfiguration,
                QLowEnergyCharacteristic::CCCDDisable);
    txCharData.addDescriptor(clientConfig);
    txCharData.setProperties(QLowEnergyCharacteristic::Read | QLowEnergyCharacteristic::Notify);

    // Set up the service, its characteristics, and advertisement data
    QLowEnergyServiceData sppServiceData;
    sppServiceData.setType(QLowEnergyServiceData::ServiceTypePrimary);
    sppServiceData.setUuid(BLEIoDevice::SERVICE_UUID);
    sppServiceData.addCharacteristic(txCharData);
    sppServiceData.addCharacteristic(rxCharData);

    QLowEnergyAdvertisingData sppAdvertisingData;
    sppAdvertisingData.setDiscoverability(QLowEnergyAdvertisingData::DiscoverabilityGeneral);
    sppAdvertisingData.setIncludePowerLevel(true);
    // The device name that is broadcasted in the advertisement. Note that this is not supported
    // on Android where the device's name is used instead
    sppAdvertisingData.setLocalName("QtRO peripheral"_L1);

    bleController.reset(QLowEnergyController::createPeripheral());

    // Add the service to the BT LE controller and start advertising so that clients
    // can discover this server. When the client disconnects the advertisement is
    // resumed so that next clients can find the server
    std::unique_ptr<QLowEnergyService> sppService;
    auto startAdvertising = [&bleController, sppAdvertisingData, sppServiceData, &sppService]
    {
        sppService.reset(bleController->addService(sppServiceData));
        if (sppService) {
            bleController->startAdvertising(QLowEnergyAdvertisingParameters(),
                                           sppAdvertisingData, sppAdvertisingData);
        }
    };

    QObject::connect(bleController.get(), &QLowEnergyController::disconnected, [&]() {
        // Upon disconnection the underlying BLE service used by the ioDevice becomes
        // obsolete. Free up the resources, resume advertising and wait for a new client
        hostNode.reset(nullptr);
        ioDevice.reset(nullptr);
        startAdvertising();
    });

    auto errorHandler = [&](QLowEnergyController::Error errorCode)
    {
        // Exit server in cases we won't try to recover
        qWarning().noquote().nospace() << errorCode << " error: " << bleController->errorString();
        if (errorCode != QLowEnergyController::RemoteHostClosedError) {
            qWarning("BLE server quitting due to the error.");
            QCoreApplication::quit();
        }
    };
    // Use queued connection in case the advertising fails before we even enter
    // the event loop / exec(), in which case the quit() does nothing
    QObject::connect(bleController.get(), &QLowEnergyController::errorOccurred,
                     &app, errorHandler, Qt::QueuedConnection);

    // Start initial advertising
    startAdvertising();

    // Now we are advertising, next:
    // 1) Wait for a client to discover the service and get connected
    // 2) Wait for client to indicate it is fully ready
    // 3) Create RO sourcenode and BLE IO device
    QMetaObject::Connection readConnection;
    QObject::connect(bleController.get(), &QLowEnergyController::connected, [&]() {
        Q_ASSERT(!hostNode);
        Q_ASSERT(!ioDevice);
        readConnection = QObject::connect(sppService.get(),
                                          &QLowEnergyService::characteristicChanged,
                                          bleController.get(),
                                          [&](const QLowEnergyCharacteristic &info,
                                              const QByteArray &value) {
            // Wait for the client to signal it is ready
            if (info.uuid() != BLEIoDevice::CLIENT_TX_SERVER_RX_CHAR_UUID
                    || value != BLEIoDevice::CLIENT_READY_SIGNAL) {
                return;
            }

            QObject::disconnect(readConnection);
            readConnection = {};

            // We have a client that is connected and has indicated it is ready;
            // Create the hostnode and the associated BLE IO device and enable
            // remote access
            hostNode = std::make_unique<QRemoteObjectHost>();
            hostNode->setHostUrl(u"ble://qt_ro_ble"_s,
                                 QRemoteObjectHost::AllowExternalRegistration);
            hostNode->enableRemoting(heater.get());

            ioDevice = std::make_unique<BLEIoDevice>(sppService.get(),
                           BLEIoDevice::CLIENT_TX_SERVER_RX_CHAR_UUID,
                           BLEIoDevice::CLIENT_RX_SERVER_TX_CHAR_UUID);
            QObject::connect(ioDevice.get(), &BLEIoDevice::closing, bleController.get(),
                             &QLowEnergyController::disconnectFromDevice);
            hostNode->addHostSideConnection(ioDevice.get());
        });
    });

    return QCoreApplication::exec();
}

#include "main.moc"