QGroundControl
Ground Control Station for MAVLink Drones
Loading...
Searching...
No Matches
GPSReceiverConnectionPolicy.cc
Go to the documentation of this file.
2
3#include <utility>
4
5#include <QtCore/QStringList>
6
7#include "GPSReceiverConfig.h"
9#include "RuntimeScheduler.h"
10#ifndef QGC_NO_SERIAL_LINK
11#include "SerialPortManager.h"
12#endif
13
14QGC_LOGGING_CATEGORY(GPSReceiverConnectionPolicyLog, "GPS.Receiver.GPSReceiverConnectionPolicy")
15
17 const GPSReceiverConfiguration& configuration,
18 RuntimeScheduler* scheduler)
19 : _receiver(receiver)
20 , _configuration(configuration)
21 , _scheduler(scheduler)
22{}
23
25{
26 const bool connectionChanged = !previous.sameConnection(_configuration);
27 const bool turnedOn = !previous.autoConnect && _configuration.autoConnect;
28 const bool turnedOff = previous.autoConnect && !_configuration.autoConnect;
29 if (connectionChanged || turnedOff) {
30 _cancelRetries();
31 }
32 if (turnedOn) {
33 _paused = false;
34 _startPending = true;
35 // A saved receiver the user already connected is kept connected from now on.
36 _keepConnected = _owner == Owner::Saved && !connectionChanged;
37 }
38}
39
40void GPSReceiverConnectionPolicy::_cancelRetries()
41{
42 if (_keepConnected) {
43 qCDebug(GPSReceiverConnectionPolicyLog) << "Automatic reconnect cancelled";
44 }
45 // Nothing reconnects any more, so a message about the pending reconnect would be stale.
46 if ((_keepConnected || _retryDeadlineUs) && !_receiver.hasReceiver()) {
47 _receiver.setConnectionError({});
48 }
49 _keepConnected = false;
50 _waitingForPort = false;
51 _autoPort.clear();
52#ifndef QGC_NO_SERIAL_LINK
53 _waitingPorts.clear();
54#endif
55 _retryDeadlineUs.reset();
56 _retryBackoff.reset();
57}
58
60{
61 _cancelRetries();
62 _owner = Owner::None;
63 _startPending = false;
64}
65
66bool GPSReceiverConnectionPolicy::connectConfigured(bool allowPersistentChanges)
67{
68 // A rejected request leaves the current connection's ownership and retries as they are.
69 if (_receiver.hasReceiver()) {
70 _receiver.setConnectionError(tr("Disconnect the current receiver before connecting another."));
71 return false;
72 }
73 reset();
74 _paused = false;
75 if (!_connectConfigured(allowPersistentChanges)) {
76 return false;
77 }
78 _owner = Owner::Saved;
79 return true;
80}
81
83{
84 reset();
85 _paused = true;
86 _receiver.endConnection(true);
87}
88
90{
91 if (_owner == Owner::Saved && _configuration.autoConnect && !std::exchange(_keepConnected, true)) {
92 qCDebug(GPSReceiverConnectionPolicyLog) << "Automatic reconnect armed for the saved receiver";
93 }
94 _waitingForPort = false;
95 _retryDeadlineUs.reset();
96 _retryBackoff.reset();
97}
98
100{
101 if (_owner == Owner::Discovered && _discoveryEnabled()) {
102 if (portRemoved) {
103 // Discovery connects the receiver again when it returns.
104 _owner = Owner::None;
105 _cancelRetries();
107 }
108 _scheduleRetry();
110 }
111 if (_owner == Owner::Saved && _keepConnected) {
112 if (portRemoved) {
113 _waitingForPort = true;
115 }
116 _scheduleRetry();
118 }
119 _owner = Owner::None;
120 _cancelRetries();
122}
123
124void GPSReceiverConnectionPolicy::_scheduleRetry()
125{
126 const auto delay = _retryBackoff.next();
127 qCDebug(GPSReceiverConnectionPolicyLog) << "Retrying the receiver connection in" << delay.count() << "ms";
128 _retryDeadlineUs = _scheduler->nowUs() + static_cast<quint64>(std::chrono::microseconds(delay).count());
129}
130
132{
133 if (!_configuration.autoConnect || _paused || _receiver.hasReceiver()) {
134 return;
135 }
136 if (std::exchange(_startPending, false) && _hasSavedReceiver()) {
137 _owner = Owner::Saved;
138 _keepConnected = true;
139 }
140 if (_keepConnected) {
141 _updateSaved();
142 } else if (_discoveryEnabled()) {
143 _updateDiscovery();
144 }
145}
146
147bool GPSReceiverConnectionPolicy::_hasSavedReceiver() const
148{
149 switch (_configuration.effectiveConnectionType()) {
151 return !_configuration.serialDevice.trimmed().isEmpty();
152 case RTKSettings::Tcp:
153 return !_configuration.tcpHost.trimmed().isEmpty() && _configuration.tcpPort != 0;
154 case RTKSettings::Udp:
155 // UDP only receives, so it cannot carry a configured base.
156 return _configuration.receiverRole != RTKSettings::ConfiguredBase;
157 }
158 return false;
159}
160
161bool GPSReceiverConnectionPolicy::_discoveryEnabled() const
162{
163#ifdef QGC_NO_SERIAL_LINK
164 return false;
165#else
166 // Discovery configures known base receivers, so it never replaces a saved, network or passive receiver.
167 return _configuration.autoConnect && !_paused && _configuration.receiverRole == RTKSettings::ConfiguredBase &&
168 _configuration.effectiveConnectionType() == RTKSettings::Serial &&
169 _configuration.serialDevice.trimmed().isEmpty();
170#endif
171}
172
173void GPSReceiverConnectionPolicy::_updateSaved()
174{
175 if (_configuration.effectiveConnectionType() == RTKSettings::Serial) {
176 const QString device = _configuration.serialDevice.trimmed();
177 if (!_serialDeviceAvailable(device)) {
178 if (!std::exchange(_waitingForPort, true)) {
179 const QString label = _serialDeviceLabel(device);
180 if (label.isEmpty()) {
181 _receiver.setConnectionError(tr("Waiting for the receiver on USB."));
182 } else {
183 //: %1 is a serial device, such as /dev/ttyACM0 or COM3
184 _receiver.setConnectionError(tr("Waiting for the receiver on %1.").arg(label));
185 }
186 }
187 return;
188 }
189 if (std::exchange(_waitingForPort, false)) {
190 // Retry as soon as the receiver returns instead of waiting out the backoff.
191 _attemptSaved();
192 return;
193 }
194 }
195 if (!_retryDeadlineUs || _scheduler->nowUs() >= *_retryDeadlineUs) {
196 _attemptSaved();
197 }
198}
199
200void GPSReceiverConnectionPolicy::_attemptSaved()
201{
202 _retryDeadlineUs.reset();
203 // Flash-save consent is one-use and never passed by automatic attempts.
204 if (!_connectConfigured(false)) {
205 _scheduleRetry();
206 }
207}
208
209bool GPSReceiverConnectionPolicy::_serialDeviceAvailable([[maybe_unused]] const QString& device) const
210{
211#ifdef QGC_NO_SERIAL_LINK
212 return false;
213#else
214 return _receiver.serialPortAvailable(device);
215#endif
216}
217
218QString GPSReceiverConnectionPolicy::_serialDeviceLabel(const QString& device) const
219{
220#ifdef QGC_NO_SERIAL_LINK
221 return device;
222#else
223 return _receiver.serialPortLabel(device);
224#endif
225}
226
227bool GPSReceiverConnectionPolicy::_connectConfigured(bool allowPersistentChanges)
228{
229 const bool configuredBase = _configuration.receiverRole == RTKSettings::ConfiguredBase;
230 const auto type = configuredBase ? gpsReceiverTypeForManufacturer(_configuration.baseReceiverManufacturer)
231 : std::optional(GPSType::passive);
232 if (!type) {
233 _receiver.setConnectionError(tr("Select a receiver type before connecting."));
234 return false;
235 }
236 const auto connection = _configuration.effectiveConnectionType();
237 if (connection == RTKSettings::Tcp) {
238 const QString host = _configuration.tcpHost.trimmed();
239 const uint tcpPort = _configuration.tcpPort;
240 if (host.isEmpty() || tcpPort == 0 || tcpPort > 65535) {
241 _receiver.setConnectionError(tr("Enter the receiver's TCP host and port."));
242 return false;
243 }
244 return _receiver.connectTcp(host, static_cast<quint16>(tcpPort), *type, allowPersistentChanges);
245 }
246 if (connection == RTKSettings::Udp) {
247 const uint udpPort = _configuration.udpPort;
248 if (configuredBase) {
249 _receiver.setConnectionError(
250 tr("A configured base needs a serial or TCP connection. UDP only receives data."));
251 return false;
252 }
253 if (udpPort == 0 || udpPort > 65535) {
254 _receiver.setConnectionError(tr("Enter the UDP port that receives the data."));
255 return false;
256 }
257 return _receiver.connectUdp(static_cast<quint16>(udpPort), *type);
258 }
259#ifndef QGC_NO_SERIAL_LINK
260 const QString device = _configuration.serialDevice.trimmed();
261 if (!_serialDeviceAvailable(device)) {
262 _receiver.setConnectionError(tr("Select an available serial device that is not a bootloader."));
263 return false;
264 }
265 // Zero asks configurable receivers to detect the rate.
266 const auto baud = _configuration.serialBaudRate;
267 if (!gpsValidBaudRate(baud, *type == GPSType::passive)) {
269 return false;
270 }
271 auto claim = _receiver.claimSerialPort(device);
272 if (!claim) {
273 _receiver.setConnectionError(tr("The selected serial device is already in use."));
274 return false;
275 }
276 return _receiver.connectSerial(device, *type, baud, allowPersistentChanges, std::move(claim));
277#else
278 return false;
279#endif
280}
281
282void GPSReceiverConnectionPolicy::_updateDiscovery()
283{
284#ifndef QGC_NO_SERIAL_LINK
285 const QStringList receivers = _receiver.rtkReceiverPorts();
286 // On Android the user allows each USB device by itself, and may never allow the first receiver listed. One
287 // that QGC may not open is passed over while it may open another.
288 QStringList allowed;
289 for (const QString& device : receivers) {
290 if (_receiver.serialPortAllowed(device)) {
291 allowed.append(device);
292 }
293 }
294 if (_owner == Owner::Discovered) {
295 const bool passedOver = !allowed.isEmpty() && !_receiver.serialPortAllowed(_autoPort);
296 if (_serialDeviceAvailable(_autoPort) && !passedOver) {
297 if (!_retryDeadlineUs || _scheduler->nowUs() >= *_retryDeadlineUs) {
298 _connectDiscovered(_autoPort);
299 }
300 return;
301 }
302 // The receiver being retried was unplugged, and discovery finds it again when it returns, or is passed over.
303 _owner = Owner::None;
304 _cancelRetries();
305 }
306 _waitingPorts.removeIf([&receivers](const QString& device) { return !receivers.contains(device); });
307 const QStringList& candidates = allowed.isEmpty() ? receivers : allowed;
308 const quint64 nowUs = _scheduler->nowUs();
309 for (const QString& device : candidates) {
310 if (_waitingPorts.settled(device, nowUs)) {
311 _connectDiscovered(device);
312 return;
313 }
314 }
315#endif
316}
317
318#ifndef QGC_NO_SERIAL_LINK
319void GPSReceiverConnectionPolicy::_connectDiscovered(const QString& device)
320{
321 auto claim = _receiver.claimSerialPort(device);
322 if (!claim) {
323 return;
324 }
325 _owner = Owner::Discovered;
326 _autoPort = device;
327 _waitingPorts.clear();
328 _retryDeadlineUs.reset();
329 // The USB identity only chose the port; the saved manufacturer chooses the family, detecting it when Automatic.
330 const auto type = gpsReceiverTypeForManufacturer(_configuration.baseReceiverManufacturer);
331 if (!type) {
332 _receiver.setConnectionError(tr("Select a receiver type before connecting."));
333 }
334 if (!type || !_receiver.connectSerial(device, *type, 0, false, std::move(claim))) {
335 _scheduleRetry();
336 }
337}
338#endif
QString gpsReceiverConfigErrorText(GPSReceiverConfigError error)
Translated diagnostic; empty for GPSReceiverConfigError::None.
constexpr bool gpsValidBaudRate(uint32_t baudRate, bool passive)
GPSReceiverSessionOutcome
What the policy does after a receiver session ends; the receiver words the message for it.
@ Unplugged
A discovered receiver was unplugged; discovery connects it again when it returns.
@ None
Nothing reconnects; the receiver's own message for the error applies.
@ AutoRetrying
A discovered receiver failed or was lost; discovery retries it.
@ WaitingForPort
The saved receiver was unplugged; it reconnects when its port returns.
@ Retrying
The saved receiver's connection was lost; a retry is scheduled.
std::optional< GPSType > gpsReceiverTypeForManufacturer(int manufacturer)
The family a persisted manufacturer selects, GPSType::automatic for GPS_AUTOMATIC_MANUFACTURER; empty...
GPSTypes::GPSType GPSType
Definition GPSType.h:25
#define QGC_LOGGING_CATEGORY(name, categoryStr)
constexpr Delay next(Delay retryAfter=Delay::zero())
Returns peek(retryAfter) and counts the attempt.
void disconnectConfigured()
Disconnects at the user's request and pauses automatic connection.
GPSReceiverConnectionPolicy(GPSReceiverConnector &receiver, const GPSReceiverConfiguration &configuration, RuntimeScheduler *scheduler)
GPSReceiverSessionOutcome sessionEnded(bool portRemoved)
void reset()
Forgets connection ownership and pending retries, before another connection replaces it.
void update()
Periodic tick: due automatic connections and USB discovery.
void configurationChanged(const GPSReceiverConfiguration &previous)
The receiver's configuration changed from previous.
bool connectConfigured(bool allowPersistentChanges)
Connects the saved receiver at the user's request and resumes automatic connection.
virtual quint64 nowUs() const =0
uint64_t nowUs()
QCameraDevice device(const QString &description)
The attached camera of description description; a null device when none is.
Definition UVCDevices.cc:21
The receiver configuration the application's settings binding supplies as values.
RTKSettings::ReceiverRole receiverRole
Only a configured base is written to by QGroundControl.
bool autoConnect
Keep the saved receiver connected, or discover a configured base on USB when no device is saved.
bool sameConnection(const GPSReceiverConfiguration &other) const
RTKSettings::ConnectionType effectiveConnectionType() const
The connection this configuration uses; builds without serial links connect a serial selection over T...