7#include <QtCore/QByteArrayView>
26bool Protocol::_baseStationUnsupported()
const
28 const auto& identity = _identity;
30 if (identity.timeModeUnsupported) {
34 return !identity.isM8p && !identity.model.isEmpty();
37 return !profile.rtcmOutput && profile.baseCapabilityKnown;
43 _valsetAckAmbiguous =
false;
46 _setMode({}, channel.
stream());
50 const unsigned requestedBaud = baud;
58 const bool identified = _identify(channel);
63 if (!detection.found) {
68 QString detail = QStringLiteral(
"Unsupported u-blox receiver: hardware version %1")
69 .arg(QString::fromLatin1(
identity.hardware));
70 if (!
identity.protocolVersion.isEmpty()) {
71 detail += QStringLiteral(
", protocol version %1").arg(QString::fromLatin1(
identity.protocolVersion));
76 if (_baseStationUnsupported()) {
78 identity.model.isEmpty() ? QStringLiteral(
"This u-blox receiver") : QString::fromLatin1(
identity.model);
79 channel.
failControl(QStringLiteral(
"%1 cannot run as an RTK base station").arg(model));
82 const unsigned desiredBaud = requestedBaud ? requestedBaud :
Plan::BASE_BAUD;
83 if (!_setUpPort(channel, detection.baud, desiredBaud)) {
87 _setMode({.corrections =
true}, channel.
stream());
89 bool deviceConfigured =
false;
91 deviceConfigured = _configureDevice(channel);
93 deviceConfigured = _configureLegacyDevice(channel);
95 if (!deviceConfigured) {
98 if (!_restartSurveyIn(channel)) {
102 _mode.navigation =
true;
116bool Protocol::_setUpPort(GPSCommandChannel& channel,
unsigned detectedBaud,
unsigned desiredBaud)
118 const bool modern = _identity.protocol27;
129 if (desiredBaud == detectedBaud) {
133 const UBX::Board identifiedBoard = _identity.board;
145 const auto result = _waitForAck(channel, command);
146 const bool acknowledged = result.succeeded();
151 channel.
failControl(QStringLiteral(
"The link cannot run at %1 baud").arg(desiredBaud));
154 if (modern && !acknowledged) {
156 _controller.requireConfigurationReadback(
command.value());
159 if (!_identify(channel)) {
162 if (_identity.board != identifiedBoard || _identity.protocol27 != modern || _controller.lateRejection()) {
165 if (modern && !acknowledged) {
171bool Protocol::_configureDevice(GPSCommandChannel& channel)
175 if (!_runPlan(channel, portsAndNavigation)) {
178 if (!_configureJammingDetection(channel)) {
183 return _runPlan(channel, messageOutput);
186bool Protocol::_configureJammingDetection(GPSCommandChannel& channel)
191 if (probe.succeeded()) {
196 qCWarning(UBXProtocolLog) <<
"CFG-SEC-JAMDET probe unanswered";
203bool Protocol::_configureLegacyDevice(GPSCommandChannel& channel)
210 if (!_sendAcknowledged(channel,
Msg::CFG_NAV5, navigation)) {
214 if (!_setMessageRateAcknowledged(channel, output)) {
221bool Protocol::_restartSurveyIn(GPSCommandChannel& channel)
223 if (!_identity.protocol27) {
224 return _restartLegacySurveyIn(channel);
227 if (
const auto* fixed = std::get_if<GPSBaseStationConfig::Fixed>(&_base.
mode)) {
231 return _activateRTCMOutput(channel) == RTCMActivation::Active;
233 const auto* survey = std::get_if<GPSBaseStationConfig::SurveyIn>(&_base.
mode);
238 if (!_disableTimeMode(channel)) {
241 if (!_waitForSurveyStop(channel)) {
244 return _transactValset(channel,
Plan::surveyIn(*survey)).succeeded();
247bool Protocol::_restartLegacySurveyIn(GPSCommandChannel& channel)
250 (void) _setMessageRate(channel, output);
252 const auto* fixed = std::get_if<GPSBaseStationConfig::Fixed>(&_base.
mode);
253 if (!_disableTimeMode(channel)) {
261 return _activateRTCMOutput(channel) == RTCMActivation::Active;
263 const auto* survey = std::get_if<GPSBaseStationConfig::SurveyIn>(&_base.
mode);
267 if (!_waitForSurveyStop(channel)) {
277bool Protocol::_disableTimeMode(GPSCommandChannel& channel)
279 if (_identity.protocol27) {
283 return _verifyValset(channel,
291 _timeModeReadbackPending =
true;
292 _timeModeReadback.reset();
294 _timeModeReadbackPending =
false;
297 const auto result = channel.
awaitReply([
this] {
298 if (_controller.lateRejection()) {
305 _timeModeReadbackPending =
false;
309bool Protocol::_waitForSurveyStop(GPSCommandChannel& channel)
311 _surveyStopped =
false;
313 while (!_surveyStopped && channel.
nowUs() < deadline) {
322 if (!_surveyStopped) {
323 qCWarning(UBXProtocolLog) <<
"Time mode did not stop";
331Protocol::RTCMActivation Protocol::_activateRTCMOutput(GPSCommandChannel& channel)
333 if (!_identity.protocol27) {
334 return _activateLegacyRTCMOutput(channel);
337 return activated ? RTCMActivation::Active : RTCMActivation::Failed;
340Protocol::RTCMActivation Protocol::_activateLegacyRTCMOutput(GPSCommandChannel& channel)
342 auto& progress = _legacyRTCM;
346 return RTCMActivation::Failed;
353 const auto baseRate = _waitForAck(channel,
Msg::CFG_RATE).outcome;
355 return RTCMActivation::Unanswered;
359 return RTCMActivation::Failed;
364 bool unanswered =
false;
365 for (; progress.next < status.size() + rtcm.size(); ++progress.next) {
369 qCDebug(UBXProtocolLog) <<
"Service budget spent; RTCM activation resumes in the next service";
370 return RTCMActivation::Unanswered;
372 const auto output = progress.next < status.size()
374 : rtcm[progress.next - status.size()];
375 const auto reply = _confirmMessageRate(channel, output.rate);
383 return RTCMActivation::Failed;
389 if (!reply.settled) {
395 const bool active = progress.stationPosition && progress.observations;
397 qCWarning(UBXProtocolLog) <<
"Receiver did not answer a CFG-MSG rate or its poll; later RTCM messages are not"
400 return RTCMActivation::Unanswered;
402 }
else if (!active) {
403 qCWarning(UBXProtocolLog) <<
"Receiver rejected the RTCM station position or every observation message";
406 return active ? RTCMActivation::Active : RTCMActivation::Failed;
411 auto& requests = _requests;
412 if (requests.rtcmActivation) {
413 const auto activation = _activateRTCMOutput(channel);
416 requests.rtcmActivation = activation == RTCMActivation::Unanswered;
417 if (activation == RTCMActivation::Failed) {
418 channel.
failControl(QStringLiteral(
"u-blox receiver did not start RTCM output after the survey-in"));
421 if (
const uint16_t message = std::exchange(requests.disableMessage, 0)) {
422 _disableUnexpectedMessage(channel, message);
426void Protocol::_disableUnexpectedMessage(
GPSCommandChannel& channel, uint16_t message)
428 const uint64_t now = channel.
nowUs();
432 if (!_identity.protocol27) {
433 _lastDisableUs = now;
434 (void) _setMessageRate(channel,
435 {{
static_cast<uint8_t
>(message),
static_cast<uint8_t
>(message >> 8)},
Plan::NO_OUTPUT});
439 [](
const Plan::UnexpectedOutput& entry) {
return entry.
message.
value(); });
441 _lastDisableUs = now;
446bool Protocol::_send(GPSCommandChannel& channel, UBX::MessageId message, std::span<const uint8_t> payload,
447 GPSConfigurationStep step)
455 std::array<uint8_t, UBX::FRAME_OVERHEAD + Plan::VALSET_CAPACITY> buffer{};
461 return channel.
write(frame);
464bool Protocol::_sendAcknowledged(GPSCommandChannel& channel, UBX::MessageId message, std::span<const uint8_t> payload)
469 return _waitForAck(channel, message).succeeded();
472GPSConfigurationEvidence Protocol::_waitForAck(GPSCommandChannel& channel, UBX::MessageId message)
474 auto& controller = _controller;
476 controller.beginAcknowledgement(message.
value());
477 if (valset && controller.configurationReadbackRequired()) {
478 controller.finishAcknowledgement();
482 return _verifyValset(channel,
485 const auto result = channel.
awaitReply([&controller] {
return controller.acknowledgement(); });
486 controller.finishAcknowledgement();
488 _valsetAckAmbiguous =
true;
493bool Protocol::_setMessageRate(GPSCommandChannel& channel, UBX::Plan::MessageRate rate)
499bool Protocol::_setMessageRateAcknowledged(GPSCommandChannel& channel, UBX::Plan::MessageRate rate)
504GPSCommandOutcome Protocol::_setMessageRateReply(GPSCommandChannel& channel, UBX::Plan::MessageRate rate)
506 if (!_setMessageRate(channel, rate)) {
512Protocol::RateConfirmation Protocol::_confirmMessageRate(GPSCommandChannel& channel, UBX::Plan::MessageRate rate)
514 const auto outcome = _setMessageRateReply(channel, rate);
516 return RateConfirmation{outcome,
true};
518 auto& controller = _controller;
523 controller.finishRatePoll();
527 const auto decide = [&controller, expected = rate.
rate] {
528 if (
const auto rates = controller.polledRates()) {
535 const auto result = channel.
awaitReply([&channel, &controller, decide] {
539 const bool settled = controller.ratePollSettled();
540 controller.finishRatePoll();
541 return RateConfirmation{result.outcome, settled};
544bool Protocol::_runPlan(GPSCommandChannel& channel,
const std::vector<UBX::Plan::ValsetBatch>& batches)
546 for (
const auto& batch : batches) {
547 if (!batch.included) {
550 const bool acknowledged = _transactValset(channel, batch).succeeded();
551 if (channel.
failed() || (!acknowledged && batch.policy == NakPolicy::Fail)) {
554 if (!acknowledged && batch.policy == NakPolicy::Warn) {
555 qCWarning(UBXProtocolLog) << batch.warning;
561bool Protocol::_valsetsRefused()
const
563 return _valsetAckAmbiguous && !_controller.configurationReadbackRequired();
566void Protocol::_load(
const UBX::Plan::ValsetBatch& batch)
569 for (
const auto& item : batch.
items) {
570 if (!item.included) {
574 const UBX::MsgOutKey family{{item.key}};
578 (void) _valset.append(item.key, item.value);
583bool Protocol::_writeValset(GPSCommandChannel& channel,
const UBX::Plan::ValsetBatch& batch)
586 const auto payload = _valset.payload();
588 if (payload.empty() || _valsetsRefused()) {
597GPSConfigurationEvidence Protocol::_transactValset(GPSCommandChannel& channel,
const UBX::Plan::ValsetBatch& batch)
599 if (!_writeValset(channel, batch)) {
604 return _awaitValsetAck(channel);
607GPSConfigurationEvidence Protocol::_awaitValsetAck(GPSCommandChannel& channel)
611 _controller.configurationReadbackRequired()) {
620 _valsetAckAmbiguous =
false;
625GPSConfigurationEvidence Protocol::_verifyValset(GPSCommandChannel& channel, GPSConfigurationStep step)
627 auto& controller = _controller;
629 UBX::ConfigurationValueCursor cursor(_valset.entries());
630 GPSConfigurationEvidence result;
631 while (!cursor.empty()) {
632 UBX::ConfigurationValues expected;
633 std::array<uint32_t, UBX::ConfigurationValues::MAX_KEYS> keys{};
635 while (!cursor.empty() && expected.
count < expected.
values.size()) {
636 const auto entry = cursor.next();
645 controller.beginReadback(std::span(keys).first(expected.
count));
646 if (!_send(channel,
Msg::CFG_VALGET, std::span(request).first(4 + expected.
count *
sizeof(uint32_t)), step)) {
647 controller.finishReadback();
650 result = channel.
awaitReply([&controller, &expected] {
651 if (controller.lateRejection() || controller.readbackRejected()) {
654 if (!controller.readbackReady()) {
660 controller.finishReadback();
670constexpr auto MON_VER_POLL = [] {
671 std::array<uint8_t, FRAME_OVERHEAD>
frame{};
676QLatin1StringView signature(
const GPSFrame& frame)
679 return QLatin1StringView(
"UBX frames");
681 const std::string_view text =
frame.text();
686 return sentence &&
sentence->hasValidChecksum() ? QLatin1StringView(
"$PUBX sentences") : QLatin1StringView();
705 .type = GPSType::ublox,
706 .logCategory = &UBXProtocolLog,
710 .signature = &signature,
@ Stop
The receiver answered but is not usable, so no other rate is tried.
std::function< GPSCommandOutcome(const GPSFrame &frame)> GPSFrameMatcher
Resolves the outstanding command from each dispatched frame, after the family decoded it; Pending kee...
@ Cancelled
A stop was requested; not a receiver or link fault.
std::unique_ptr< GPSFamilyProtocol > gpsCreateProtocol()
The create of a family whose protocol is default-constructed: .create = &gpsCreateProtocol<Protocol>.
@ UBX
u-blox 0xB5 0x62 frames with a valid Fletcher checksum.
@ ASCIILine
Printable lines up to CR/LF, without the terminator; the decoder checks checksums.
@ RTCM3
0xD3 frames with a valid CRC-24Q.
#define QGC_LOGGING_CATEGORY(name, categoryStr)
void beginCommand(GPSConfigurationStep step)
GPSBaudDetection detectBaud(std::span< const unsigned > candidates, unsigned baud, GPSBaudProbeFunction probe)
GPSReceiveUpdates receiveCycle(std::chrono::milliseconds timeout)
GPSDeadline operationDeadline() const
bool setBaudrate(unsigned baudrate)
GPSDeadline commandDeadline() const
Deadline of the current command attempt, set by beginCommand().
void failControl(GPSProtocolError failure=GPSProtocolError::Protocol)
GPSDeadlineScope deadlineScope(std::chrono::milliseconds timeout)
bool receiveUntil(std::function< bool()> done, std::chrono::milliseconds duration)
const GPSConfigurationEvidence & currentCommand() const
GPSConfigurationEvidence completeCommand(GPSCommandOutcome outcome)
Retires the current attempt and reports it; repeated completion returns the retained evidence unchang...
GPSStreamDemux & stream()
bool write(QByteArrayView bytes)
GPSConfigurationEvidence awaitReply(GPSReplyPoll reply)
Decodes received traffic until reply resolves the current command, its deadline expires,...
GPSProtocolError error() const
void failNoAnswer(std::span< const unsigned > rates)
GPSConfigurationEvidence transact(GPSConfigurationStep step, QByteArrayView bytes)
void finishCommand(GPSCommandOutcome outcome)
bool probe(GPSCommandChannel &channel) override
The MON-VER poll Protocol::configure() identifies receivers with, under the same label and timeout.
void serviceStreaming(GPSCommandChannel &channel) override
RTCM activation after survey-in and disabling unexpected output, as decoding requested.
QString identity() const override
Model and firmware reported during configuration; empty when unknown.
bool configure(GPSCommandChannel &channel, GPSConfig config, unsigned &baud) override
constexpr bool write(std::span< uint8_t > bytes, std::size_t offset, T value)
Encode an unaligned little-endian scalar. Insufficient space leaves the destination unchanged.
std::optional< Sentence > sentence(std::string_view text)
std::optional< Frame > frame(std::string_view text)
QList< Port > ports(const QList< Function > &functions)
Every port any function can run on, in port id order.
GPSCommandSequence::Command command(QByteArrayView body, GPSTextMatcher reply, std::chrono::milliseconds timeout)
body labelled by its text, framed as a sentence, and completed by reply within timeout.
constexpr auto TMODE_MODE
constexpr MessageId CFG_VALSET
constexpr MessageId NAV_SVIN
constexpr MessageId CFG_VALGET
constexpr MessageId CFG_RATE
constexpr MessageId MON_VER
constexpr MessageId CFG_MSG
constexpr MessageId CFG_NAV5
constexpr MessageId CFG_TMODE3
constexpr MessageId CFG_PRT
ValsetBatch rtcmOutput(bool compactObservations)
Base output at 1 Hz: station position, observations in the selected MSM format and GLONASS biases.
constexpr uint8_t NO_OUTPUT
constexpr MessageRate LEGACY_SURVEY_STATUS
ValsetBatch fixedBase(const GPSBaseStationConfig::Fixed &fixed)
constexpr CfgRate LEGACY_BASE_RATE
ValsetBatch jammingDetection()
Probes CFG-SEC-JAMDET, which F9 HPG 1.50+, F9 L1L5 and X20 have instead of CFG-ITFM.
std::array< MessageRate, 5 > legacyMessageOutput()
NAV-PVT, status, satellite and MON-HW (antenna and jamming) rates during the survey.
ValsetBatch disableRTCMOutput()
Stops RTCM output, including observations a previous session left in the other MSM format.
constexpr std::chrono::milliseconds CONFIG_TIMEOUT
Acknowledgement timeout of one configuration command.
ValsetBatch interferenceMonitor()
Enables the interference monitor of firmware without CFG-SEC-JAMDET.
constexpr std::chrono::milliseconds LEGACY_REPLY_TIMEOUT
The u-blox 8 protocol has CFG commands acknowledged within one second.
constexpr std::array< UnexpectedOutput, 3 > UNEXPECTED_OUTPUT
constexpr std::chrono::milliseconds IDENTITY_TIMEOUT
Slow factory NMEA output can delay a MON-VER response by over a second.
constexpr std::chrono::milliseconds SURVEY_STOP_TIMEOUT
ValsetBatch uart1Baudrate(uint32_t baudrate)
constexpr uint16_t LEGACY_PORT_UART1
constexpr std::chrono::milliseconds SURVEY_STOP_POLL
std::vector< ValsetBatch > portsAndNavigation(const ReceiverProfile &profile)
Protocol 27+ configuration before jamming detection: ports, navigation, odometer and RTK.
std::array< MessageRate, 10 > legacyDisableRTCMOutput()
Written without waiting for acknowledgements.
constexpr CfgRate LEGACY_SURVEY_RATE
5 Hz, UTC-aligned.
CfgTmode3 legacySurveyIn(const GPSBaseStationConfig::SurveyIn &survey)
NakPolicy
What a batch that is rejected, unanswered or not written means for configuration.
std::vector< ValsetBatch > messageOutput(const ReceiverProfile &profile)
Protocol 27+ configuration after jamming detection: message output and receiver-specific extras.
ValsetBatch uart1Protocols()
Protocol 27+ port setup at the detected baud rate: UBX only on UART1, 8N1.
constexpr CfgNav5 LEGACY_NAVIGATION
Updates only the dynamic model and the fix mode (3D only).
constexpr unsigned BASE_BAUD
The link rate a base is moved to when no rate is selected.
std::array< uint8_t, 2 *WIRE_SIZE< CfgPrt > > legacyPorts(uint32_t baudrate)
std::array< RTCMOutput, 6 > legacyRTCMOutput(bool compactObservations)
ValsetBatch disableTimeMode()
CfgTmode3 legacyFixedBase(const GPSBaseStationConfig::Fixed &fixed)
ValsetBatch surveyIn(const GPSBaseStationConfig::SurveyIn &survey)
constexpr uint16_t LEGACY_PORT_USB
constexpr std::array BAUD_RATES
Probing order of the automatic baud detection.
constexpr std::chrono::microseconds DISABLE_MESSAGE_INTERVAL
An unwanted message is disabled at most this often; some cannot be disabled.
ValsetBatch disableMessage(MsgOutKey key)
Disables unexpected output; the reply is not awaited.
constexpr std::chrono::milliseconds BAUD_PROBE_DRAIN
Traffic the baud probe drains before polling MON-VER.
std::array< MessageRate, 2 > legacyBaseStatus()
Survey status and satellite rates for the 1 Hz base; rejections are ignored.
u-blox receivers over UBX: CFG-VALSET configuration from protocol 27, CFG-MSG and CFG-TMODE3 before i...
constexpr ReceiverProfile receiverProfile(Board board)
const GPSReceiverFamily FAMILY
constexpr std::span< const uint8_t > encodeFrame(MessageId message, std::span< const uint8_t > payload, std::span< uint8_t > out)
Writes the frame of payload to the front of out.
QByteArray messageName(MessageId message)
The name of message, such as "UBX-CFG-VALSET", or its class and id in hex when it has none.
constexpr std::array< uint8_t, SIZE< T > > encode(const T &value)
bool compactObservations
MSM4 instead of MSM7 observations: about a third less correction bandwidth, without Doppler.
The receiver configuration requested for one configure() attempt.
GPSBaseStationConfig base
GPSCommandOutcome outcome
std::chrono::milliseconds timeout
static GPSDeadline after(uint64_t nowUs, std::chrono::microseconds timeout)
A negative timeout is already due at nowUs.
std::chrono::milliseconds remaining(uint64_t nowUs) const
Rounded up to whole milliseconds and capped at INT32_MAX milliseconds.
std::array< ConfigurationValue, MAX_KEYS > values
static constexpr size_t MAX_KEYS
One poll reads at most this many keys.
constexpr uint16_t value() const
constexpr CfgKey< uint8_t > port(MsgOutPort port) const
std::chrono::milliseconds timeout
std::vector< ValsetItem > items