Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
qnmeapositioninfosource.cpp
Go to the documentation of this file.
1// Copyright (C) 2016 Jolla Ltd.
2// Copyright (C) 2016 The Qt Company Ltd.
3// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
4// Qt-Security score:significant reason:default
8
9#include <QIODevice>
10#include <QBasicTimer>
11#include <QTimerEvent>
12#include <QTimer>
13#include <array>
14#include <QDebug>
15#include <QtCore/QtNumeric>
16#include <QtCore/QDateTime>
17#include <QtCore/QTimeZone>
18
19#include <algorithm>
20
21QT_BEGIN_NAMESPACE
22
23#define USE_POSITION_NMEA_PIMPL 0
24
26class QGeoPositionInfoPrivateNmea : public QGeoPositionInfoPrivate
27{
28public:
29 virtual ~QGeoPositionInfoPrivateNmea();
30
31 QList<QByteArray> nmeaSentences;
32};
33
34
35QGeoPositionInfoPrivateNmea::~QGeoPositionInfoPrivateNmea()
36{
37
38}
39#else
40typedef QGeoPositionInfoPrivate QGeoPositionInfoPrivateNmea;
41#endif
42
43static bool propagateCoordinate(QGeoPositionInfo &dst, const QGeoPositionInfo &src, bool force = true)
44{
45 bool updated = false;
46 QGeoCoordinate c = dst.coordinate();
47 const QGeoCoordinate & srcCoordinate = src.coordinate();
48 if (qIsFinite(src.coordinate().latitude())
49 && (!qIsFinite(dst.coordinate().latitude()) || force)) {
50 updated |= (c.latitude() != srcCoordinate.latitude());
51 c.setLatitude(src.coordinate().latitude());
52 }
53 if (qIsFinite(src.coordinate().longitude())
54 && (!qIsFinite(dst.coordinate().longitude()) || force)) {
55 updated |= (c.longitude() != srcCoordinate.longitude());
56 c.setLongitude(src.coordinate().longitude());
57 }
58 if (qIsFinite(src.coordinate().altitude())
59 && (!qIsFinite(dst.coordinate().altitude()) || force)) {
60 updated |= (c.altitude() != srcCoordinate.altitude())
61 || (c.altitudeType() != srcCoordinate.altitudeType());
62 c.setAltitude(src.coordinate().altitude());
63 c.setAltitudeType(srcCoordinate.altitudeType());
64 }
65 dst.setCoordinate(c);
66 return updated;
67}
68
69static bool propagateDate(QGeoPositionInfo &dst, const QGeoPositionInfo &src)
70{
71 if (!dst.timestamp().date().isValid() && src.timestamp().isValid()) { // time was supposed to be set/the same already. Date can be overwritten.
72 dst.setTimestamp(src.timestamp());
73 return true;
74 }
75 return false;
76}
77
78static bool propagateAttributes(QGeoPositionInfo &dst, const QGeoPositionInfo &src, bool force = true)
79{
80 bool updated = false;
81 static constexpr std::array<QGeoPositionInfo::Attribute, 6> attrs {
82 { QGeoPositionInfo::GroundSpeed
83 ,QGeoPositionInfo::HorizontalAccuracy
84 ,QGeoPositionInfo::VerticalAccuracy
85 ,QGeoPositionInfo::Direction
86 ,QGeoPositionInfo::VerticalSpeed
87 ,QGeoPositionInfo::MagneticVariation} };
88 for (const auto a: attrs) {
89 if (src.hasAttribute(a) && (!dst.hasAttribute(a) || force)) {
90 updated |= (dst.attribute(a) != src.attribute(a));
91 dst.setAttribute(a, src.attribute(a));
92 }
93 }
94
95 return updated;
96}
97
98// returns false if src does not contain any additional or different data than dst,
99// true otherwise.
100static bool mergePositions(QGeoPositionInfo &dst, const QGeoPositionInfo &src, QByteArray nmeaSentence)
101{
102 bool updated = false;
103
104 updated |= propagateCoordinate(dst, src);
105 updated |= propagateDate(dst, src);
106 updated |= propagateAttributes(dst, src);
107
109 QGeoPositionInfoPrivateNmea *dstPimpl = static_cast<QGeoPositionInfoPrivateNmea *>(QGeoPositionInfoPrivate::get(dst));
110 dstPimpl->nmeaSentences.append(nmeaSentence);
111#else
112 Q_UNUSED(nmeaSentence);
113#endif
114 return updated;
115}
116
117static qint64 msecsTo(const QDateTime &from, const QDateTime &to)
118{
119 if (!from.time().isValid() || !to.time().isValid())
120 return 0;
121
122 if (!from.date().isValid() || !to.date().isValid()) // use only time
123 return from.time().msecsTo(to.time());
124
125 return from.msecsTo(to);
126}
127
129 = default;
130
132 : QNmeaReader(sourcePrivate), m_update(*new QGeoPositionInfoPrivateNmea)
133{
134 // An env var controlling the number of milliseconds to use to withold
135 // an update and wait for additional data to combine.
136 // The update will be pushed earlier than this if a newer update will be received.
137 // The update will be withold longer than this amount of time if additional
138 // valid data will keep arriving within this time frame.
139 bool ok = false;
140 int pushDelay = qEnvironmentVariableIntValue("QT_NMEA_PUSH_DELAY", &ok);
141 if (ok)
142 pushDelay = std::clamp(pushDelay, -1, 1000);
143 else
144 pushDelay = 20;
145
146 if (pushDelay >= 0) {
147 m_timer.setSingleShot(true);
148 m_timer.setInterval(pushDelay);
149 m_timer.connect(&m_timer, &QTimer::timeout, &m_timer, [this]() {
150 this->notifyNewUpdate();
151 });
152 }
153 m_pushDelay = pushDelay;
154}
155
156QNmeaRealTimeReader::~QNmeaRealTimeReader()
157 = default;
158
160{
161 while (m_proxy->m_device->canReadLine()) {
162 const QTime infoTime = m_update.timestamp().time(); // if update has been set, time must be valid.
163 const QDate infoDate = m_update.timestamp().date(); // this one might not be valid, as some sentences do not contain it
164
165 QGeoPositionInfoPrivateNmea *pimpl = new QGeoPositionInfoPrivateNmea;
166 QGeoPositionInfo pos(*pimpl);
167
168 char buf[1024];
169 qint64 size = m_proxy->m_device->readLine(buf, sizeof(buf));
170 if (size <= 0)
171 continue;
172
173 const bool oldFix = m_hasFix;
174 bool hasFix;
175 const bool parsed = m_proxy->parsePosInfoFromNmeaData(
176 QByteArrayView{buf, static_cast<qsizetype>(size)}, &pos, &hasFix);
177
178 if (!parsed) {
179 // got garbage, don't stop the timer
180 continue;
181 }
182
183 m_hasFix |= hasFix;
184 m_updateParsed = true;
185
186 // Date may or may not be valid, as some packets do not have date.
187 // If date isn't valid, match is performed on time only.
188 // Hence, make sure that packet blocks are generated with
189 // the sentences containing the full timestamp (e.g., GPRMC) *first* !
190 if (infoTime.isValid()) {
191 if (pos.timestamp().time().isValid()) {
192 const bool newerTime = infoTime < pos.timestamp().time();
193 const bool newerDate = (infoDate.isValid() // if time is valid but one date or both are not,
194 && pos.timestamp().date().isValid()
195 && infoDate < pos.timestamp().date());
196 if (newerTime || newerDate) {
197 // Effectively read data for different update, that is also newer,
198 // so flush retained update, and copy the new pos into m_update
199 const QDate updateDate = m_update.timestamp().date();
200 const QDate lastPushedDate = m_lastPushedTS.date();
201 const bool newerTimestampSinceLastPushed = m_update.timestamp() > m_lastPushedTS;
202 const bool invalidDate = !(updateDate.isValid() && lastPushedDate.isValid());
203 const bool newerTimeSinceLastPushed = m_update.timestamp().time() > m_lastPushedTS.time();
204 if ( newerTimestampSinceLastPushed || (invalidDate && newerTimeSinceLastPushed)) {
205 m_proxy->notifyNewUpdate(&m_update, oldFix);
206 m_lastPushedTS = m_update.timestamp();
207 }
208 m_timer.stop();
209 // next update data
210 propagateAttributes(pos, m_update, false);
211 m_update = pos;
212 m_hasFix = hasFix;
213 } else {
214 if (infoTime == pos.timestamp().time())
215 // timestamps match -- merge into m_update
216 if (mergePositions(m_update, pos, QByteArray(buf, size))) {
217 // Reset the timer only if new info has been received.
218 // Else the source might be keep repeating outdated info until
219 // new info become available.
220 m_timer.stop();
221 }
222 // else discard out of order outdated info.
223 }
224 } else {
225 // no timestamp available in parsed update-- merge into m_update
226 if (mergePositions(m_update, pos, QByteArray(buf, size)))
227 m_timer.stop();
228 }
229 } else {
230 // there was no info with valid TS. Overwrite with whatever is parsed.
232 pimpl->nmeaSentences.append(QByteArray(buf, size));
233#endif
234 propagateAttributes(pos, m_update);
235 m_update = pos;
236 m_timer.stop();
237 }
238 }
239
240 if (m_updateParsed) {
241 if (m_pushDelay < 0)
243 else
244 m_timer.start();
245 }
246}
247
249{
250 const bool newerTime = m_update.timestamp().time() > m_lastPushedTS.time();
251 const bool newerDate = (m_update.timestamp().date().isValid()
252 && m_lastPushedTS.date().isValid()
253 && m_update.timestamp().date() > m_lastPushedTS.date());
254 if (newerTime || newerDate) {
255 m_proxy->notifyNewUpdate(&m_update, m_hasFix);
256 m_lastPushedTS = m_update.timestamp();
257 }
258 m_timer.stop();
259}
260
261
262//============================================================
263
264QNmeaSimulatedReader::QNmeaSimulatedReader(QNmeaPositionInfoSourcePrivate *sourcePrivate)
265 : QNmeaReader(sourcePrivate),
266 m_currTimerId(-1),
267 m_hasValidDateTime(false)
268{
269}
270
272{
273 if (m_currTimerId > 0)
274 killTimer(m_currTimerId);
275}
276
278{
279 if (m_currTimerId > 0) // we are already reading
280 return;
281
282 if (!m_hasValidDateTime) { // first update
283 Q_ASSERT(m_proxy->m_device && (m_proxy->m_device->openMode() & QIODevice::ReadOnly));
284
285 if (!setFirstDateTime()) {
286 //m_proxy->notifyReachedEndOfFile();
287 qWarning("QNmeaPositionInfoSource: cannot find NMEA sentence with valid date & time");
288 return;
289 }
290
291 m_hasValidDateTime = true;
292 simulatePendingUpdate();
293
294 } else {
295 // previously read to EOF, but now new data has arrived
296 processNextSentence();
297 }
298}
299
300static int processSentence(QGeoPositionInfo &info,
301 QByteArray &m_nextLine,
303 QQueue<QPendingGeoPositionInfo> &m_pendingUpdates,
304 bool &hasFix)
305{
306 int timeToNextUpdate = -1;
307 QDateTime prevTs;
308 if (!m_pendingUpdates.isEmpty())
309 prevTs = m_pendingUpdates.head().info.timestamp();
310
311 // find the next update with a valid time (as long as the time is valid,
312 // we can calculate when the update should be emitted)
313 while (!m_nextLine.isEmpty() || (m_proxy->m_device && m_proxy->m_device->bytesAvailable() > 0)) {
314 char static_buf[1024];
315 char *buf = static_buf;
316 QByteArray nextLine;
317 qint64 size = 0;
318 if (!m_nextLine.isEmpty()) {
319 // Read something in the previous call, but TS was later.
320 size = m_nextLine.size();
321 nextLine = m_nextLine;
322 m_nextLine.clear();
323 buf = nextLine.data();
324 } else {
325 size = m_proxy->m_device->readLine(buf, sizeof(static_buf));
326 }
327
328 if (size <= 0)
329 continue;
330
331 const QTime infoTime = info.timestamp().time(); // if info has been set, time must be valid.
332 const QDate infoDate = info.timestamp().date(); // this one might not be valid, as some sentences do not contain it
333
334 /*
335 Packets containing time information are GGA, RMC, ZDA, GLL:
336
337 GGA : GPS fix data - only time
338 GLL : geographic latitude and longitude - only time
339 RMC : recommended minimum FPOS/transit data - date and time
340 ZDA : only timestamp - date and time
341
342 QLocationUtils is currently also capable of parsing VTG and GSA sentences:
343
344 VTG: containing Track made good and ground speed
345 GSA: overall satellite data, w. accuracies (ends up into PositionInfo)
346
347 Since these sentences contain no timestamp, their content will be merged with the content
348 from any prior sentence that had timestamp info, if any is available.
349 */
350
351 QGeoPositionInfoPrivateNmea *pimpl = new QGeoPositionInfoPrivateNmea;
352 QGeoPositionInfo pos(*pimpl);
353 if (m_proxy->parsePosInfoFromNmeaData(
354 QByteArrayView{buf, static_cast<qsizetype>(size)}, &pos, &hasFix)) {
355 // Date may or may not be valid, as some packets do not have date.
356 // If date isn't valid, match is performed on time only.
357 // Hence, make sure that packet blocks are generated with
358 // the sentences containing the full timestamp (e.g., GPRMC) *first* !
359 if (infoTime.isValid()) {
360 if (pos.timestamp().time().isValid()) {
361 const bool newerTime = infoTime < pos.timestamp().time();
362 const bool newerDate = (infoDate.isValid() // if time is valid but one date or both are not,
363 && pos.timestamp().date().isValid()
364 && infoDate < pos.timestamp().date());
365 if (newerTime || newerDate) {
366 // Effectively read data for different update, that is also newer, so copy buf into m_nextLine
367 m_nextLine = QByteArray(buf, size);
368 break;
369 } else {
370 if (infoTime == pos.timestamp().time())
371 // timestamps match -- merge into info
372 mergePositions(info, pos, QByteArray(buf, size));
373 // else discard out of order outdated info.
374 }
375 } else {
376 // no timestamp available -- merge into info
377 mergePositions(info, pos, QByteArray(buf, size));
378 }
379 } else {
380 // there was no info with valid TS. Overwrite with whatever is parsed.
382 pimpl->nmeaSentences.append(QByteArray(buf, size));
383#endif
384 info = pos;
385 }
386
387 if (prevTs.time().isValid()) {
388 timeToNextUpdate = msecsTo(prevTs, info.timestamp());
389 if (timeToNextUpdate < 0) // Somehow parsing expired packets, reset info
390 info = QGeoPositionInfo(*new QGeoPositionInfoPrivateNmea);
391 }
392 }
393 }
394
395 return timeToNextUpdate;
396}
397
398bool QNmeaSimulatedReader::setFirstDateTime()
399{
400 // find the first update with valid date and time
401 QGeoPositionInfo info(*new QGeoPositionInfoPrivateNmea);
402 bool hasFix = false;
403 processSentence(info, m_nextLine, m_proxy, m_pendingUpdates, hasFix);
404
405 if (info.timestamp().time().isValid()) { // NMEA may have sentences with only time and no date. These would generate invalid positions
407 pending.info = info;
408 pending.hasFix = hasFix;
409 m_pendingUpdates.enqueue(pending);
410 return true;
411 }
412 return false;
413}
414
415void QNmeaSimulatedReader::simulatePendingUpdate()
416{
417 if (!m_pendingUpdates.isEmpty()) {
418 // will be dequeued in processNextSentence()
419 QPendingGeoPositionInfo &pending = m_pendingUpdates.head();
420 m_proxy->notifyNewUpdate(&pending.info, pending.hasFix);
421 }
422
423 processNextSentence();
424}
425
426void QNmeaSimulatedReader::timerEvent(QTimerEvent *event)
427{
428 killTimer(event->timerId());
429 m_currTimerId = -1;
430 simulatePendingUpdate();
431}
432
433void QNmeaSimulatedReader::processNextSentence()
434{
435 QGeoPositionInfo info(*new QGeoPositionInfoPrivateNmea);
436 bool hasFix = false;
437
438 int timeToNextUpdate = processSentence(info, m_nextLine, m_proxy, m_pendingUpdates, hasFix);
439 if (timeToNextUpdate < 0)
440 return;
441
442 m_pendingUpdates.dequeue();
443
445 pending.info = info;
446 pending.hasFix = hasFix;
447 m_pendingUpdates.enqueue(pending);
448 m_currTimerId = startTimer(timeToNextUpdate);
449}
450
451
452//============================================================
453
454
455QNmeaPositionInfoSourcePrivate::QNmeaPositionInfoSourcePrivate(QNmeaPositionInfoSource *parent, QNmeaPositionInfoSource::UpdateMode updateMode)
456 : QObject(parent),
457 m_updateMode(updateMode),
458 m_device(0),
459 m_invokedStart(false),
460 m_positionError(QGeoPositionInfoSource::UnknownSourceError),
462 m_source(parent),
463 m_nmeaReader(0),
464 m_updateTimer(0),
465 m_requestTimer(0),
466 m_horizontalAccuracy(qQNaN()),
467 m_verticalAccuracy(qQNaN()),
468 m_noUpdateLastInterval(false),
469 m_updateTimeoutSent(false),
470 m_connectedReadyRead(false)
471{
472}
473
475{
476 delete m_nmeaReader;
477 delete m_updateTimer;
478}
479
480bool QNmeaPositionInfoSourcePrivate::openSourceDevice()
481{
482 if (!m_device) {
483 qWarning("QNmeaPositionInfoSource: no QIODevice data source, call setDevice() first");
484 return false;
485 }
486
487 if (!m_device->isOpen() && !m_device->open(QIODevice::ReadOnly)) {
488 qWarning("QNmeaPositionInfoSource: cannot open QIODevice data source");
489 return false;
490 }
491
492 connect(m_device, SIGNAL(aboutToClose()), SLOT(sourceDataClosed()));
493 connect(m_device, SIGNAL(readChannelFinished()), SLOT(sourceDataClosed()));
494 connect(m_device, SIGNAL(destroyed()), SLOT(sourceDataClosed()));
495
496 return true;
497}
498
499void QNmeaPositionInfoSourcePrivate::sourceDataClosed()
500{
501 if (m_nmeaReader && m_device && m_device->bytesAvailable())
502 m_nmeaReader->readAvailableData();
503}
504
506{
507 if (m_nmeaReader)
508 m_nmeaReader->readAvailableData();
509}
510
511bool QNmeaPositionInfoSourcePrivate::initialize()
512{
513 if (m_nmeaReader)
514 return true;
515
516 if (!openSourceDevice())
517 return false;
518
519 if (m_updateMode == QNmeaPositionInfoSource::RealTimeMode)
520 m_nmeaReader = new QNmeaRealTimeReader(this);
521 else
522 m_nmeaReader = new QNmeaSimulatedReader(this);
523
524 return true;
525}
526
527void QNmeaPositionInfoSourcePrivate::prepareSourceDevice()
528{
529 // some data may already be available
530 if (m_updateMode == QNmeaPositionInfoSource::SimulationMode) {
531 if (m_nmeaReader && m_device->bytesAvailable())
532 m_nmeaReader->readAvailableData();
533 }
534
535 if (!m_connectedReadyRead) {
536 connect(m_device, SIGNAL(readyRead()), SLOT(readyRead()));
537 m_connectedReadyRead = true;
538 }
539}
540
542 QGeoPositionInfo *posInfo, bool *hasFix)
543{
544 return m_source->parsePosInfoFromNmeaData(data, posInfo, hasFix);
545}
546
548{
549 if (m_invokedStart)
550 return;
551
552 m_positionError = QGeoPositionInfoSource::NoError;
553
554 m_invokedStart = true;
555 m_pendingUpdate = QGeoPositionInfo();
556 m_noUpdateLastInterval = false;
557
558 bool initialized = initialize();
559 if (!initialized) {
560 m_source->setError(QGeoPositionInfoSource::AccessError);
561 return;
562 }
563
564 if (m_updateMode == QNmeaPositionInfoSource::RealTimeMode) {
565 // skip over any buffered data - we only want the newest data.
566 // Don't do this in requestUpdate. In that case bufferedData is good to have/use.
567 if (m_device->bytesAvailable()) {
568 if (m_device->isSequential())
569 m_device->readAll();
570 else
571 m_device->seek(m_device->bytesAvailable());
572 }
573 }
574
575 if (m_updateTimer)
576 m_updateTimer->stop();
577
578 if (m_source->updateInterval() > 0) {
579 if (!m_updateTimer)
580 m_updateTimer = new QBasicTimer;
581 m_updateTimer->start(m_source->updateInterval(), this);
582 }
583
584 if (initialized)
585 prepareSourceDevice();
586}
587
589{
590 m_invokedStart = false;
591 if (m_updateTimer)
592 m_updateTimer->stop();
593 m_pendingUpdate = QGeoPositionInfo();
594 m_noUpdateLastInterval = false;
595}
596
598{
599 if (m_requestTimer && m_requestTimer->isActive())
600 return;
601
602 m_positionError = QGeoPositionInfoSource::NoError;
603
604 if (msec <= 0 || msec < m_source->minimumUpdateInterval()) {
605 m_source->setError(QGeoPositionInfoSource::UpdateTimeoutError);
606 return;
607 }
608
609 if (!m_requestTimer) {
610 m_requestTimer = new QTimer(this);
611 connect(m_requestTimer, SIGNAL(timeout()), SLOT(updateRequestTimeout()));
612 }
613
614 bool initialized = initialize();
615 if (!initialized) {
616 m_source->setError(QGeoPositionInfoSource::UpdateTimeoutError);
617 return;
618 }
619
620 m_requestTimer->start(msec);
621 prepareSourceDevice();
622}
623
624void QNmeaPositionInfoSourcePrivate::updateRequestTimeout()
625{
626 m_requestTimer->stop();
627 m_source->setError(QGeoPositionInfoSource::UpdateTimeoutError);
628}
629
630void QNmeaPositionInfoSourcePrivate::notifyNewUpdate(QGeoPositionInfo *update, bool hasFix)
631{
632 // include <QDebug> before uncommenting
633 //qDebug() << "QNmeaPositionInfoSourcePrivate::notifyNewUpdate()" << update->timestamp() << hasFix << m_invokedStart << (m_requestTimer && m_requestTimer->isActive());
634
635 QDate date = update->timestamp().date();
636 if (date.isValid()) {
637 m_currentDate = date;
638 } else {
639 // some sentence have time but no date
640 QTime time = update->timestamp().time();
641 if (time.isValid() && m_currentDate.isValid())
642 update->setTimestamp(QDateTime(m_currentDate, time, QTimeZone::UTC));
643 }
644
645 // Some attributes are sent in separate NMEA sentences. Save and restore the accuracy
646 // measurements.
647 if (update->hasAttribute(QGeoPositionInfo::HorizontalAccuracy))
648 m_horizontalAccuracy = update->attribute(QGeoPositionInfo::HorizontalAccuracy);
649 else if (!qIsNaN(m_horizontalAccuracy))
650 update->setAttribute(QGeoPositionInfo::HorizontalAccuracy, m_horizontalAccuracy);
651
652 if (update->hasAttribute(QGeoPositionInfo::VerticalAccuracy))
653 m_verticalAccuracy = update->attribute(QGeoPositionInfo::VerticalAccuracy);
654 else if (!qIsNaN(m_verticalAccuracy))
655 update->setAttribute(QGeoPositionInfo::VerticalAccuracy, m_verticalAccuracy);
656
657 if (hasFix && update->isValid()) {
658 if (m_requestTimer && m_requestTimer->isActive()) { // User called requestUpdate()
659 m_requestTimer->stop();
660 emitUpdated(*update);
661 } else if (m_invokedStart) { // user called startUpdates()
662 if (m_updateTimer && m_updateTimer->isActive()) { // update interval > 0
663 // for periodic updates, only want the most recent update
664 m_pendingUpdate = *update; // Set what to send in timerEvent()
665 if (m_noUpdateLastInterval) {
666 // if the update was invalid when timerEvent was last called, a valid update
667 // should be sent ASAP
668 emitPendingUpdate();
669 m_noUpdateLastInterval = false;
670 }
671 } else { // update interval <= 0
672 emitUpdated(*update);
673 }
674 }
675 m_lastUpdate = *update; // Set in any case, if update is valid. Used in lastKnownPosition().
676 }
677}
678
680{
681 emitPendingUpdate();
682}
683
684void QNmeaPositionInfoSourcePrivate::emitPendingUpdate()
685{
686 if (m_pendingUpdate.isValid()) {
687 m_updateTimeoutSent = false;
688 m_noUpdateLastInterval = false;
689 emitUpdated(m_pendingUpdate);
690 m_pendingUpdate = QGeoPositionInfo();
691 } else { // invalid update
692 if (m_noUpdateLastInterval && !m_updateTimeoutSent) {
693 m_updateTimeoutSent = true;
694 m_pendingUpdate = QGeoPositionInfo(); // Invalid already, but clear just in case.
695 m_source->setError(QGeoPositionInfoSource::UpdateTimeoutError);
696 }
697 m_noUpdateLastInterval = true;
698 }
699}
700
701void QNmeaPositionInfoSourcePrivate::emitUpdated(const QGeoPositionInfo &update)
702{
703 // check for duplication already done in QNmeaRealTimeReader::notifyNewUpdate
704 // and QNmeaRealTimeReader::readAvailableData
705 m_lastUpdate = update;
706 emit m_source->positionUpdated(update);
707}
708
709//=========================================================
710
711/*!
712 \class QNmeaPositionInfoSource
713 \inmodule QtPositioning
714 \ingroup QtPositioning-positioning
715 \since 5.2
716
717 \brief The QNmeaPositionInfoSource class provides positional information using a NMEA data source.
718
719 NMEA is a commonly used protocol for the specification of one's global
720 position at a certain point in time. The QNmeaPositionInfoSource class reads NMEA
721 data and uses it to provide positional data in the form of
722 QGeoPositionInfo objects.
723
724 A QNmeaPositionInfoSource instance operates in either \l {RealTimeMode} or
725 \l {SimulationMode}. These modes allow NMEA data to be read from either a
726 live source of positional data, or replayed for simulation purposes from
727 previously recorded NMEA data.
728
729 The source of NMEA data is set with setDevice().
730
731 Use startUpdates() to start receiving regular position updates and stopUpdates() to stop these
732 updates. If you only require updates occasionally, you can call requestUpdate() to request a
733 single update.
734
735 In both cases the position information is received via the positionUpdated() signal and the
736 last known position can be accessed with lastKnownPosition().
737
738 QNmeaPositionInfoSource supports reporting the accuracy of the horizontal and vertical position.
739 To enable position accuracy reporting an estimate of the User Equivalent Range Error associated
740 with the NMEA source must be set with setUserEquivalentRangeError().
741
742 \target nmea-altitude-type
743 \section1 Altitude type
744
745 The GGA sentence reports the altitude above Mean Sea Level (MSL). It also
746 reports the geoid separation, which is the difference between the MSL
747 and the WGS84 reference ellipsoid. This allows to calculate the altitude
748 above the WGS84 ellipsoid.
749
750 By default, QNmeaPositionInfoSource reports the MSL altitude, and sets the
751 \l {QGeoCoordinate::}{altitudeType()} of the reported coordinates to
752 \l {QGeoCoordinate::AltitudeType}{AltitudeType::Unknown} to preserve
753 backwards compatibility with previous Qt versions.
754
755 Since Qt 6.13, use setPreferredAltitudeType() to select the altitude type.
756 If the preferred altitude type is set to
757 \l {QGeoCoordinate::AltitudeType}{AltitudeType::WGS84}, and the GGA
758 sentence contains the geoid separation, the altitude above the WGS84
759 ellipsoid is reported, and the altitude type is set to
760 \l {QGeoCoordinate::AltitudeType}{AltitudeType::WGS84}. If the geoid
761 separation is not available, the MSL altitude is reported, and the
762 altitude type is set to
763 \l {QGeoCoordinate::AltitudeType}{AltitudeType::MSL}.
764*/
765
766
767/*!
768 \enum QNmeaPositionInfoSource::UpdateMode
769 Defines the available update modes.
770
771 \value RealTimeMode Positional data is read and distributed from the data source as it becomes available. Use this mode if you are using a live source of positional data (for example, a GPS hardware device).
772 \value SimulationMode The data and time information in the NMEA source data is used to provide positional updates at the rate at which the data was originally recorded. Use this mode if the data source contains previously recorded NMEA data and you want to replay the data for simulation purposes.
773*/
774
775
776/*!
777 Constructs a QNmeaPositionInfoSource instance with the given \a parent
778 and \a updateMode.
779*/
780QNmeaPositionInfoSource::QNmeaPositionInfoSource(UpdateMode updateMode, QObject *parent)
781 : QGeoPositionInfoSource(parent),
782 d(new QNmeaPositionInfoSourcePrivate(this, updateMode))
783{
784}
785
786/*!
787 Destroys the position source.
788*/
789QNmeaPositionInfoSource::~QNmeaPositionInfoSource()
790{
791 delete d;
792}
793
794/*!
795 Sets the User Equivalent Range Error (UERE) to \a uere. The UERE is used in calculating an
796 estimate of the accuracy of the position information reported by the position info source. The
797 UERE should be set to a value appropriate for the GPS device which generated the NMEA stream.
798
799 The true UERE value is calculated from multiple error sources including errors introduced by
800 the satellites and signal propogation delays through the atmosphere as well as errors
801 introduced by the receiving GPS equipment. For details on GPS accuracy see
802 \l {https://web.archive.org/web/20161212144906if_/http://edu-observatory.org/gps/gps_accuracy.html} {Sam J. Wormley, GPS Errors & Estimating Your Reveiver's Accuracy}.
803
804 A typical value for UERE is approximately 5.1.
805
806 \since 5.3
807
808 \sa userEquivalentRangeError()
809*/
810void QNmeaPositionInfoSource::setUserEquivalentRangeError(double uere)
811{
812 d->m_userEquivalentRangeError = uere;
813}
814
815/*!
816 Returns the current User Equivalent Range Error (UERE). The UERE is used in calculating an
817 estimate of the accuracy of the position information reported by the position info source. The
818 default value is NaN which means no accuracy information will be provided.
819
820 \since 5.3
821
822 \sa setUserEquivalentRangeError()
823*/
824double QNmeaPositionInfoSource::userEquivalentRangeError() const
825{
826 return d->m_userEquivalentRangeError;
827}
828
829/*!
830 Parses an NMEA sentence string into a QGeoPositionInfo.
831
832 The default implementation will parse standard NMEA sentences.
833 This method should be reimplemented in a subclass whenever the need to deal with non-standard
834 NMEA sentences arises.
835
836 The parser reads \a size bytes from \a data and uses that information to setup \a posInfo and
837 \a hasFix. If \a hasFix is set to false then \a posInfo may contain only the time or the date
838 and the time.
839
840 Returns true if the sentence was successfully parsed, otherwise returns false and should not
841 modifiy \a posInfo or \a hasFix.
842*/
843
844#if QT_DEPRECATED_SINCE(7, 0)
845bool QNmeaPositionInfoSource::parsePosInfoFromNmeaData(const char *data, int size,
846 QGeoPositionInfo *posInfo, bool *hasFix)
847{
848#if QT_VERSION < QT_VERSION_CHECK(7, 0, 0)
849 return QLocationUtils::getPosInfoFromNmea(QByteArrayView{data, size}, posInfo,
850 d->m_userEquivalentRangeError,
851 preferredAltitudeType(), hasFix);
852#else
853 return parsePosInfoFromNmeaData(QByteArrayView{data, size}, posInfo, hasFix);
854#endif
855}
856#endif // QT_DEPRECATED_SINCE(7, 0)
857
858bool QNmeaPositionInfoSource::parsePosInfoFromNmeaData(QByteArrayView data,
859 QGeoPositionInfo *posInfo, bool *hasFix)
860{
861#if QT_VERSION < QT_VERSION_CHECK(7, 0, 0)
862 return parsePosInfoFromNmeaData(data.data(), static_cast<int>(data.size()),
863 posInfo, hasFix);
864#else
865 return QLocationUtils::getPosInfoFromNmea(data, posInfo,
866 d->m_userEquivalentRangeError,
867 preferredAltitudeType(), hasFix);
868#endif
869}
870
871
872/*!
873 Returns the update mode.
874*/
875QNmeaPositionInfoSource::UpdateMode QNmeaPositionInfoSource::updateMode() const
876{
877 return d->m_updateMode;
878}
879
880/*!
881 Sets the NMEA data source to \a device. If the device is not open, it
882 will be opened in \l{QIODeviceBase::}{ReadOnly} mode.
883
884 The source device can only be set once and must be set before calling
885 \l startUpdates() or \l requestUpdate().
886
887 \note The \a device must emit \l {QIODevice::readyRead()} for the
888 source to be notified when data is available for reading.
889 \l QNmeaPositionInfoSource does not assume the ownership of the device,
890 and hence does not deallocate it upon destruction.
891*/
892void QNmeaPositionInfoSource::setDevice(QIODevice *device)
893{
894 if (device != d->m_device) {
895 if (!d->m_device)
896 d->m_device = device;
897 else
898 qWarning("QNmeaPositionInfoSource: source device has already been set");
899 }
900}
901
902/*!
903 Returns the NMEA data source.
904*/
905QIODevice *QNmeaPositionInfoSource::device() const
906{
907 return d->m_device;
908}
909
910/*!
911 \reimp
912*/
913void QNmeaPositionInfoSource::setUpdateInterval(int msec)
914{
915 int interval = msec;
916 if (interval != 0)
917 interval = qMax(msec, minimumUpdateInterval());
918 QGeoPositionInfoSource::setUpdateInterval(interval);
919 if (d->m_invokedStart) {
920 d->stopUpdates();
921 d->startUpdates();
922 }
923}
924
925/*!
926 \reimp
927*/
928void QNmeaPositionInfoSource::startUpdates()
929{
930 d->startUpdates();
931}
932
933/*!
934 \reimp
935*/
936void QNmeaPositionInfoSource::stopUpdates()
937{
938 d->stopUpdates();
939}
940
941/*!
942 \reimp
943*/
944void QNmeaPositionInfoSource::requestUpdate(int msec)
945{
946 d->requestUpdate(msec == 0 ? 60000 * 5 : msec); // 5min default timeout
947}
948
949/*!
950 \reimp
951*/
952QGeoPositionInfo QNmeaPositionInfoSource::lastKnownPosition(bool) const
953{
954 // the bool value does not matter since we only use satellite positioning
955 return d->m_lastUpdate;
956}
957
958/*!
959 \reimp
960*/
961QGeoPositionInfoSource::PositioningMethods QNmeaPositionInfoSource::supportedPositioningMethods() const
962{
963 return SatellitePositioningMethods;
964}
965
966/*!
967 \reimp
968*/
969int QNmeaPositionInfoSource::minimumUpdateInterval() const
970{
971 return 2; // Some chips are capable of over 100 updates per seconds.
972}
973
974/*!
975 \reimp
976*/
977QGeoPositionInfoSource::Error QNmeaPositionInfoSource::error() const
978{
979 return d->m_positionError;
980}
981
982void QNmeaPositionInfoSource::setError(QGeoPositionInfoSource::Error positionError)
983{
984 d->m_positionError = positionError;
985 if (d->m_positionError != QGeoPositionInfoSource::NoError)
986 emit QGeoPositionInfoSource::errorOccurred(positionError);
987}
988
989QT_END_NAMESPACE
990
991#include "moc_qnmeapositioninfosource_p.cpp"
992#include "moc_qnmeapositioninfosource.cpp"
void notifyNewUpdate(QGeoPositionInfo *update, bool fixStatus)
bool parsePosInfoFromNmeaData(QByteArrayView data, QGeoPositionInfo *posInfo, bool *hasFix)
void timerEvent(QTimerEvent *event) override
This event handler can be reimplemented in a subclass to receive timer events for the object.
QNmeaReader(QNmeaPositionInfoSourcePrivate *sourcePrivate)
virtual void readAvailableData()=0
virtual ~QNmeaReader()
QNmeaRealTimeReader(QNmeaPositionInfoSourcePrivate *sourcePrivate)
void timerEvent(QTimerEvent *event) override
This event handler can be reimplemented in a subclass to receive timer events for the object.
#define USE_POSITION_NMEA_PIMPL
static bool propagateCoordinate(QGeoPositionInfo &dst, const QGeoPositionInfo &src, bool force=true)
static int processSentence(QGeoPositionInfo &info, QByteArray &m_nextLine, QNmeaPositionInfoSourcePrivate *m_proxy, QQueue< QPendingGeoPositionInfo > &m_pendingUpdates, bool &hasFix)
static bool propagateAttributes(QGeoPositionInfo &dst, const QGeoPositionInfo &src, bool force=true)
static qint64 msecsTo(const QDateTime &from, const QDateTime &to)
static bool propagateDate(QGeoPositionInfo &dst, const QGeoPositionInfo &src)
static bool mergePositions(QGeoPositionInfo &dst, const QGeoPositionInfo &src, QByteArray nmeaSentence)