swift
Loading...
Searching...
No Matches
simulatorxplane.cpp
1// SPDX-FileCopyrightText: Copyright (C) 2013 swift Project Community / Contributors
2// SPDX-License-Identifier: GPL-3.0-or-later OR LicenseRef-swift-pilot-client-1
3
4#include "simulatorxplane.h"
5
6#include <cmath>
7
8#include <QColor>
9#include <QDBusServiceWatcher>
10#include <QElapsedTimer>
11#include <QPointer>
12#include <QString>
13#include <QTimer>
14#include <QtGlobal>
15
16#include "dbus/dbus.h"
17#include "qcompilerdetection.h"
18
19#include "config/buildconfig.h"
33#include "misc/dbusserver.h"
35#include "misc/geo/latitude.h"
36#include "misc/geo/longitude.h"
37#include "misc/iterator.h"
38#include "misc/logmessage.h"
41#include "misc/pq/angle.h"
42#include "misc/pq/frequency.h"
43#include "misc/pq/length.h"
44#include "misc/pq/pressure.h"
45#include "misc/pq/speed.h"
46#include "misc/pq/temperature.h"
47#include "misc/setbuilder.h"
49#include "misc/simulation/settings/xswiftbussettingsqtfree.inc"
52#include "misc/verify.h"
59
60using namespace swift::config;
61using namespace swift::misc;
62using namespace swift::misc::aviation;
63using namespace swift::misc::network;
64using namespace swift::misc::physical_quantities;
65using namespace swift::misc::geo;
66using namespace swift::misc::simulation;
67using namespace swift::misc::simulation::settings;
68using namespace swift::misc::weather;
69using namespace swift::core;
70
71namespace
72{
73 const QString &xswiftbusServiceName()
74 {
75 static const QString name("org.swift-project.xswiftbus");
76 return name;
77 }
78 const QString &commitHash()
79 {
80 static const QString hash(XSWIFTBUS_COMMIT);
81 return hash;
82 }
83} // namespace
84
85namespace swift::simplugin::xplane
86{
88 IRemoteAircraftProvider *remoteAircraftProvider, IClientProvider *clientProvider,
90 : CSimulatorPluginCommon(info, ownAircraftProvider, remoteAircraftProvider, clientProvider, parent)
91 {
92 m_watcher = new QDBusServiceWatcher(this);
93 m_watcher->setWatchMode(QDBusServiceWatcher::WatchForUnregistration);
94 m_watcher->addWatchedService(xswiftbusServiceName());
95 m_watcher->setObjectName("QDBusServiceWatcher");
97 &CSimulatorXPlane::onDBusServiceUnregistered, Qt::QueuedConnection);
98
99 m_fastTimer.setObjectName(this->objectName().append(":m_fastTimer"));
100 m_slowTimer.setObjectName(this->objectName().append(":m_slowTimer"));
101 m_pendingAddedTimer.setObjectName(this->objectName().append(":m_pendingAddedTimer"));
102 connect(&m_fastTimer, &QTimer::timeout, this, &CSimulatorXPlane::fastTimerTimeout);
103 connect(&m_slowTimer, &QTimer::timeout, this, &CSimulatorXPlane::slowTimerTimeout);
104 connect(&m_pendingAddedTimer, &QTimer::timeout, this, &CSimulatorXPlane::addNextPendingAircraft);
105 m_fastTimer.start(100);
106 m_slowTimer.start(1000);
107 m_pendingAddedTimer.start(5000);
108
109 this->setDefaultModel({ "Jets A320_a A320_a_Austrian_Airlines A320_a_Austrian_Airlines",
111 CAircraftIcaoCode("A320", "L2J") });
112 this->resetXPlaneData();
113 }
114
116
118 {
119 if (!this->isConnected())
120 {
121 return;
122 }
123
124 // will call disconnect from
125 CSimulatorPluginCommon::unload();
126 delete m_watcher;
127 m_watcher = nullptr;
128 }
129
131 {
132 return QStringLiteral("Add-time: %1ms/%2ms").arg(m_statsAddCurrentTimeMs).arg(m_statsAddMaxTimeMs);
133 }
134
136 {
137 m_statsAddMaxTimeMs = -1;
138 m_statsAddCurrentTimeMs = -1;
139 }
140
142 {
143 if (callsign.isEmpty() || !m_xplaneAircraftObjects.contains(callsign))
144 {
145 return {};
146 }
148 this->getInterpolationSetupConsolidated(callsign, false);
149 return m_xplaneAircraftObjects[callsign].getInterpolationMessages(setup.getInterpolatorMode());
150 }
151
153 const CAircraftParts &parts)
154 {
156 {
157 return false;
158 }
159 if (!m_trafficProxy)
160 {
161 return false;
162 }
163 if (!m_xplaneAircraftObjects.contains(callsign))
164 {
165 return false;
166 }
167
168 int u = 0;
169 if (!situation.isNull())
170 {
171 PlanesPositions planesPositions;
172 planesPositions.push_back(situation);
173 m_trafficProxy->setPlanesPositions(planesPositions);
174 u++;
175 }
176
177 if (!parts.isNull())
178 {
179 PlanesSurfaces surfaces;
180 surfaces.push_back(callsign, parts);
181 m_trafficProxy->setPlanesSurfaces(surfaces);
182 u++;
183 }
184 return u > 0;
185 }
186
187 bool CSimulatorXPlane::handleProbeValue(const CElevationPlane &plane, const CCallsign &callsign, bool waterFlag,
188 const QString &hint, bool ignoreOutsideRange)
189 {
190 // XPlane specific checks for T778
191 // https://discordapp.com/channels/539048679160676382/577213275184562176/696780159969132626
192 if (!plane.hasMSLGeodeticHeight())
193 {
194 return false;
195 }
196 if (isSuspiciousTerrainValue(plane))
197 {
198 // ignore values up to +- 1.0meters, those most likely mean no scenery
199 const CLength distance = this->getDistanceToOwnAircraft(plane);
200 if (ignoreOutsideRange && distance > maxTerrainRequestDistance())
201 {
202 return false;
203 }
204
205 static const CLength threshold = maxTerrainRequestDistance() * 0.50;
206 if (distance > threshold)
207 {
208 // we expect scenery to be loaded within threshold range
209 // outside that range we assue a suspicous value "represents no scenery"
210 // of course this can be wrong, but in that case we would geth those values
211 // once we get inside range
212 this->setMinTerrainProbeDistance(distance);
213 CLogMessage(this).debug(
214 u"Suspicous XPlane probe [%1] value %2 for '%3' ignored, distance: %4 min.disance: %5 water: %6")
215 << hint << plane.getAltitude().valueRoundedAsString(CLengthUnit::m(), 4) << callsign.asString()
216 << distance.valueRoundedAsString(CLengthUnit::NM(), 2)
217 << m_minSuspicousTerrainProbe.valueRoundedAsString(CLengthUnit::NM(), 2) << boolToYesNo(waterFlag);
218 return false;
219 }
220 }
221 return true;
222 }
223
225 bool isWater)
226 {
227 static const QString hint("probe callback");
228 if (!this->handleProbeValue(plane, callsign, isWater, hint, false))
229 {
230 this->removePendingElevationRequest(callsign);
231 return;
232 }
233 CSimulatorPluginCommon::callbackReceivedRequestedElevation(plane, callsign, isWater);
234 }
235
237 {
238 if (connected && !this->isShuttingDownOrDisconnected())
239 {
240 m_serviceProxy->resetFrameTotals();
241 }
242 m_serviceProxy->setFlightNetworkConnected(connected);
243 CSimulatorPluginCommon::setFlightNetworkConnected(connected);
244 }
245
247 {
248 m_serviceProxy->setOwnCallsign(callsign.asString());
249 CSimulatorPluginCommon::setOwnCallsign(callsign);
250 }
251
252 bool CSimulatorXPlane::isSuspiciousTerrainValue(const CElevationPlane &elevation)
253 {
254 if (!elevation.hasMSLGeodeticHeight())
255 {
256 return true;
257 }
258 const double valueFt = qAbs(elevation.getAltitudeValue(CLengthUnit::ft()));
259 return valueFt < 1.0;
260 }
261
262 const CLength &CSimulatorXPlane::maxTerrainRequestDistance()
263 {
264 static const CLength d(70.0, CLengthUnit::NM());
265 return d;
266 }
267
269 {
270 m_aircraftAddedFailed.clear();
271 CSimulatorPluginCommon::clearAllRemoteAircraftData();
272 m_minSuspicousTerrainProbe.setNull();
273 }
274
276 {
278 {
279 return false;
280 }
281 if (reference.isNull())
282 {
283 return false;
284 }
285
286 // avoid requests for NON exising aircraft (based on LINUX crashes)
287 if (callsign.isEmpty())
288 {
289 return false;
290 }
291 if (!this->isAircraftInRange(callsign))
292 {
293 return false;
294 }
295
296 const CLength d = this->getDistanceToOwnAircraft(reference);
297 if (!d.isNull() && d > maxTerrainRequestDistance())
298 {
299 // no request, too far away
300 return false;
301 }
302
303 CCoordinateGeodetic pos(reference);
304 if (!pos.hasMSLGeodeticHeight())
305 {
306 // testing showed: height has an influence on the returned result
307 // - the most accurate value seems to be returned if the height is close to the elevation
308 // - in normal scenarios there is no much difference of the results if 0 is used
309 // - in Lukla (9200ft MSL) the difference between 0 and 9200 is around 1ft
310 // - in the LOWW scenario using 50000ft MSL results in around 3ft too low elevation
311 static const CAltitude alt(0, CAltitude::MeanSeaLevel, CLengthUnit::ft());
312 pos.setGeodeticHeight(alt);
313 }
314
315 using namespace std::placeholders;
316 auto callback = [this](auto &&plane, auto &&callsign, auto &&isWater) {
317 callbackReceivedRequestedElevation(std::forward<decltype(plane)>(plane),
318 std::forward<decltype(callsign)>(callsign),
319 std::forward<decltype(isWater)>(isWater));
320 };
321
322 // Request
323 m_trafficProxy->getElevationAtPosition(callsign, pos.latitude().value(CAngleUnit::deg()),
325 pos.geodeticHeight().value(CLengthUnit::m()), callback);
326 emit this->requestedElevation(callsign);
327 return true;
328 }
329
330 // convert xplane squawk mode to swift squawk mode
331 CTransponder::TransponderMode xpdrMode(int xplaneMode, bool ident)
332 {
333 if (ident)
334 {
336 }
337 if (xplaneMode == 0 || xplaneMode == 1)
338 {
340 }
341 return CTransponder::ModeC;
342 }
343
344 // convert swift squawk mode to xplane squawk mode
345 int xpdrMode(CTransponder::TransponderMode mode) { return mode == CTransponder::StateStandby ? 1 : 2; }
346
347 void CSimulatorXPlane::fastTimerTimeout()
348 {
349 if (!this->isShuttingDownOrDisconnected())
350 {
351 m_fastTimerCalls++;
352
353 m_serviceProxy->getOwnAircraftSituationDataAsync(&m_xplaneData);
354 m_serviceProxy->getOwnAircraftVelocityDataAsync(&m_xplaneData);
355 m_serviceProxy->getOwnAircraftCom1DataAsync(&m_xplaneData);
356 m_serviceProxy->getOwnAircraftCom2DataAsync(&m_xplaneData);
357 m_serviceProxy->getOwnAircraftXpdrAsync(&m_xplaneData);
358 m_serviceProxy->getAllWheelsOnGroundAsync(&m_xplaneData.onGroundAll);
359 m_serviceProxy->getHeightAglMAsync(&m_xplaneData.heightAglM);
360 m_serviceProxy->getPressureAltitudeFtAsync(&m_xplaneData.pressureAltitudeFt);
361
362 CAircraftSituation situation;
363 situation.setPosition({ m_xplaneData.latitudeDeg, m_xplaneData.longitudeDeg, 0 });
364 const CAltitude altitude { m_xplaneData.altitudeM, CAltitude::MeanSeaLevel, CLengthUnit::m() };
365 const CPressure seaLevelPressure({ m_xplaneData.seaLevelPressureInHg, CPressureUnit::inHg() });
366 const CAltitude pressureAltitude(altitude.toPressureAltitude(seaLevelPressure));
367 if (std::isnan(m_xplaneData.pressureAltitudeFt))
368 {
369 m_altitudeDelta = {};
370 situation.setAltitude(altitude);
371 situation.setPressureAltitude(pressureAltitude);
372 }
373 else
374 {
375 const CAltitude pressureAltitudeXP12(m_xplaneData.pressureAltitudeFt, CAltitude::MeanSeaLevel,
377 m_altitudeDelta = pressureAltitude - pressureAltitudeXP12;
378
379 situation.setAltitude({ altitude - m_altitudeDelta, CAltitude::MeanSeaLevel });
380 situation.setPressureAltitude(pressureAltitudeXP12);
381 }
382 situation.setHeading({ m_xplaneData.trueHeadingDeg, CHeading::True, CAngleUnit::deg() });
383 situation.setPitch({ m_xplaneData.pitchDeg, CAngleUnit::deg() });
384 situation.setBank({ m_xplaneData.rollDeg, CAngleUnit::deg() });
385 situation.setGroundSpeed({ m_xplaneData.groundspeedMs, CSpeedUnit::m_s() });
386 const CAltitude elevation { m_xplaneData.altitudeM - m_xplaneData.heightAglM, CAltitude::MeanSeaLevel,
387 CLengthUnit::m() };
389 situation.setVelocity({ m_xplaneData.localXVelocityMs, m_xplaneData.localYVelocityMs,
390 m_xplaneData.localZVelocityMs, CSpeedUnit::m_s(), m_xplaneData.pitchRadPerSec,
391 m_xplaneData.rollRadPerSec, m_xplaneData.headingRadPerSec, CAngleUnit::rad(),
392 CTimeUnit::s() });
393
394 // Updates
395 // Do not update ICAO codes, as this overrides reverse lookups
396 // updateOwnIcaoCodes(m_xplaneData.aircraftIcaoCode, CAirlineIcaoCode());
398
399 // defaults
400 CSimulatedAircraft myAircraft(getOwnAircraft());
401 CComSystem com1(myAircraft.getCom1System()); // set defaults
402 CComSystem com2(myAircraft.getCom2System());
403 CTransponder transponder(myAircraft.getTransponder());
404
405 // updates
406 com1.setFrequencyActive(CFrequency(m_xplaneData.com1ActiveKhz, CFrequencyUnit::kHz()));
407 com1.setFrequencyStandby(CFrequency(m_xplaneData.com1StandbyKhz, CFrequencyUnit::kHz()));
408 const int v1 = qRound(m_xplaneData.com1Volume * 100);
409 com1.setVolumeReceive(v1);
410 com1.setReceiveEnabled(m_xplaneData.isCom1Receiving);
411 com1.setTransmitEnabled(m_xplaneData.isCom1Transmitting);
412 const bool changedCom1 = myAircraft.getCom1System() != com1;
413
414 com2.setFrequencyActive(CFrequency(m_xplaneData.com2ActiveKhz, CFrequencyUnit::kHz()));
415 com2.setFrequencyStandby(CFrequency(m_xplaneData.com2StandbyKhz, CFrequencyUnit::kHz()));
416 const int v2 = qRound(m_xplaneData.com2Volume * 100);
417 com2.setVolumeReceive(v2);
418 com2.setReceiveEnabled(m_xplaneData.isCom2Receiving);
419 com2.setTransmitEnabled(m_xplaneData.isCom2Transmitting);
420 const bool changedCom2 = myAircraft.getCom2System() != com2;
421
422 transponder = CTransponder::getStandardTransponder(m_xplaneData.xpdrCode,
423 xpdrMode(m_xplaneData.xpdrMode, m_xplaneData.xpdrIdent));
424 const bool changedXpr = (myAircraft.getTransponder() != transponder);
425
426 if (changedCom1 || changedCom2 || changedXpr)
427 {
428 this->updateCockpit(com1, com2, transponder, identifier());
429 }
430 }
431 }
432
433 void CSimulatorXPlane::slowTimerTimeout()
434 {
435 if (!this->isShuttingDownOrDisconnected())
436 {
437 m_slowTimerCalls++;
438
439 // own aircraft data
440 m_serviceProxy->getOwnAircraftModelDataAsync(&m_xplaneData);
441 m_serviceProxy->getOwnAircraftLightsAsync(&m_xplaneData);
442 m_serviceProxy->getOwnAircraftPartsAsync(&m_xplaneData);
443
444 CAircraftEngineList engines;
445 for (int engineNumber = 0; engineNumber < m_xplaneData.enginesN1Percentage.size(); ++engineNumber)
446 {
447 // Engine number start counting at 1
448 // We consider the engine running when N1 is bigger than 5 %
449 const CAircraftEngine engine { engineNumber + 1,
450 m_xplaneData.enginesN1Percentage.at(engineNumber) > 5.0,
451 static_cast<int>(m_xplaneData.enginesN1Percentage.at(engineNumber)) };
452 engines.push_back(engine);
453 }
454
455 const CAircraftLights lights(m_xplaneData.strobeLightsOn, m_xplaneData.landingLightsOn,
456 m_xplaneData.taxiLightsOn, m_xplaneData.beaconLightsOn,
457 m_xplaneData.navLightsOn, false);
458
459 const CAircraftParts parts { lights,
460 m_xplaneData.gearDeployRatio > 0,
461 qRound(m_xplaneData.flapsDeployRatio * 100.0),
462 m_xplaneData.speedBrakeRatio > 0.5,
463 engines,
464 m_xplaneData.onGroundAll };
465
466 this->updateOwnParts(parts);
467
468 CCallsignSet invalid;
469 for (CXPlaneMPAircraft &xplaneAircraft : m_xplaneAircraftObjects)
470 {
471 // Update remote aircraft to have the latest transponder modes, codes etc.
472 const CCallsign cs = xplaneAircraft.getCallsign();
473 const CSimulatedAircraft simulatedAircraft = this->getAircraftInRangeForCallsign(cs);
474 if (!simulatedAircraft.hasCallsign())
475 {
476 // removed in provider
477 if (!cs.isEmpty())
478 {
479 invalid.insert(cs);
480 }
481 continue;
482 }
483 xplaneAircraft.setSimulatedAircraft(simulatedAircraft);
484 }
485
486 // remove the invalid ones
487 int i = 0;
488 if (this->isTestMode())
489 {
490 invalid.clear();
491 } // skip this in test mode
492 for (const CCallsign &cs : invalid)
493 {
494 this->triggerRemoveAircraft(cs, ++i * 100);
495 }
496
497 // KB: IMHO those data are pretty useless for XPlane
498 // no need to request them all the times
499 if ((m_slowTimerCalls % 3u) == 0u)
500 {
501 this->requestRemoteAircraftDataFromXPlane();
502 }
503
504 // FPS
505 // reading FPS resets average, so we only monitor over some time
506 if ((m_slowTimerCalls % 5u) == 0u)
507 {
508 constexpr double warningMiles = 1;
509 constexpr double disconnectMiles = 2;
510 const double previousMiles = m_trackMilesShort;
511
512 m_serviceProxy->getFrameStats(&m_averageFps, &m_simTimeRatio, &m_trackMilesShort, &m_minutesLate);
513
514 if (previousMiles < disconnectMiles && m_trackMilesShort >= disconnectMiles)
515 {
517 }
518 else if (previousMiles < warningMiles && m_trackMilesShort >= warningMiles)
519 {
521 }
522 }
523 }
524 }
525
526 bool CSimulatorXPlane::isConnected() const { return m_serviceProxy && m_trafficProxy; }
527
529 {
530 if (this->isConnected())
531 {
532 return true;
533 }
534 const QString dBusServerAddress = m_xSwiftBusServerSettings.getThreadLocal().getDBusServerAddressQt();
535
536 if (CDBusServer::isSessionOrSystemAddress(dBusServerAddress))
537 {
538 m_dBusConnection = QDBusConnection::sessionBus();
539 m_dbusMode = Session;
540 }
541 else if (CDBusServer::isQtDBusAddress(dBusServerAddress))
542 {
543 m_dBusConnection = QDBusConnection::connectToPeer(dBusServerAddress, "xswiftbus");
544 if (!m_dBusConnection.isConnected())
545 {
546 return false;
547 }
548 m_dbusMode = P2P;
549 }
550
551 m_serviceProxy = new CXSwiftBusServiceProxy(m_dBusConnection, this);
552 m_trafficProxy = new CXSwiftBusTrafficProxy(m_dBusConnection, this);
553
554 // hook up disconnected slot of connection
555 bool s = m_dBusConnection.connect(QString(), DBUS_PATH_LOCAL, DBUS_INTERFACE_LOCAL, "Disconnected", this,
556 SLOT(onDBusServiceUnregistered()));
557 Q_ASSERT(s);
558 if (!m_serviceProxy->isValid() || !m_trafficProxy->isValid())
559 {
560 this->disconnectFrom();
561 return false;
562 }
563
564 emitOwnAircraftModelChanged(m_serviceProxy->getAircraftModelPath(), m_serviceProxy->getAircraftModelFilename(),
565 m_serviceProxy->getAircraftLivery(), m_serviceProxy->getAircraftIcaoCode(),
566 m_serviceProxy->getAircraftModelString(), m_serviceProxy->getAircraftName(),
567 m_serviceProxy->getAircraftDescription());
568 QString xplaneVersion = QStringLiteral("%1.%2")
569 .arg(m_serviceProxy->getXPlaneVersionMajor())
570 .arg(m_serviceProxy->getXPlaneVersionMinor());
571 setSimulatorDetails("X-Plane", {}, xplaneVersion);
573 &CSimulatorXPlane::emitOwnAircraftModelChanged);
574 connect(m_trafficProxy, &CXSwiftBusTrafficProxy::simFrame, this, &CSimulatorXPlane::updateRemoteAircraft);
576 &CSimulatorXPlane::onRemoteAircraftAdded);
578 &CSimulatorXPlane::onRemoteAircraftAddingFailed);
579 if (m_watcher)
580 {
581 m_watcher->setConnection(m_dBusConnection);
582 }
583 m_trafficProxy->removeAllPlanes();
584
585 // send the settings
586 this->sendXSwiftBusSettings();
587
588 // load CSL
589 this->loadCslPackages();
590
591 // finish
594
595 return true;
596 }
597
599 {
600 if (!this->isConnected())
601 {
602 return true;
603 } // avoid emit if already disconnected
604 this->disconnectFromDBus();
605 if (m_watcher)
606 {
607 m_watcher->setConnection(m_dBusConnection);
608 }
609 delete m_serviceProxy;
610 delete m_trafficProxy;
611 m_serviceProxy = nullptr;
612 m_trafficProxy = nullptr;
613 m_fastTimerCalls = 0;
614 m_slowTimerCalls = 0;
615
617 return true;
618 }
619
620 void CSimulatorXPlane::onDBusServiceUnregistered()
621 {
622 if (!m_serviceProxy)
623 {
624 return;
625 }
626 CLogMessage(this).info(u"XPlane xSwiftBus service unregistered");
627
628 if (m_dbusMode == P2P)
629 {
630 QDBusConnection::disconnectFromPeer(m_dBusConnection.name());
631 }
632 m_dBusConnection = QDBusConnection { "default" };
633 if (m_watcher)
634 {
635 m_watcher->setConnection(m_dBusConnection);
636 }
637 delete m_serviceProxy;
638 delete m_trafficProxy;
639 m_serviceProxy = nullptr;
640 m_trafficProxy = nullptr;
642 }
643
644 void CSimulatorXPlane::emitOwnAircraftModelChanged(const QString &path, const QString &filename,
645 const QString &livery, const QString &icao,
646 const QString &modelString, const QString &name,
647 const QString &description)
648 {
649 CAircraftModel model(modelString, CAircraftModel::TypeOwnSimulatorModel, CSimulatorInfo::XPLANE, name,
650 description, icao);
651 if (!livery.isEmpty())
652 {
653 model.setModelString(model.getModelString() + " " + livery);
654 }
655 model.setFileName(path + "/" + filename);
656
658 }
659
661 {
662 // No assert here, as status message may come in because of network problems
664 {
665 return;
666 }
667
668 // avoid infinite recursion in case this function is called due to a message caused by this very function
669 static bool isInFunction = false;
670 if (isInFunction)
671 {
672 return;
673 }
674 isInFunction = true;
675
676 std::vector<int> msgBoxValues = m_xSwiftBusServerSettings.getThreadLocal().getMessageBoxValuesVector();
677 QColor color = msgBoxValues[9];
678 /* switch (message.getSeverity())
679 {
680 case CStatusMessage::SeverityDebug: color = "teal"; break;
681 case CStatusMessage::SeverityInfo: color = "cyan"; break;
682 case CStatusMessage::SeverityWarning: color = "orange"; break;
683 case CStatusMessage::SeverityError: color = "red"; break;
684 } */
685
686 m_serviceProxy->addTextMessage("swift: " + message.getMessage(), color.redF(), color.greenF(), color.blueF());
687 isInFunction = false;
688 }
689
691 {
692 // avoid issues during shutdown
694 {
695 return;
696 }
697
698 std::vector<int> msgBoxValues = m_xSwiftBusServerSettings.getThreadLocal().getMessageBoxValuesVector();
699 QColor color;
700 if (message.isServerMessage())
701 {
702 color = msgBoxValues[8];
703 }
704 else if (message.isSupervisorMessage())
705 {
706 color = msgBoxValues[10];
707 }
708 else if (message.isPrivateMessage())
709 {
710 color = msgBoxValues[7];
711 }
712 else
713 {
714 color = msgBoxValues[6];
715 }
716
717 m_serviceProxy->addTextMessage(message.getSenderCallsign().toQString() + ": " + message.getMessage(),
718 color.redF(), color.greenF(), color.blueF());
719 }
720
722 {
723 return m_xplaneAircraftObjects.contains(callsign);
724 }
725
727 const CIdentifier &originator)
728 {
729 if (originator == this->identifier())
730 {
731 return false;
732 }
734 {
735 return false;
736 } // could happen during shutdown
737
738 auto com1 = CComSystem::getCom1System({ m_xplaneData.com1ActiveKhz, CFrequencyUnit::kHz() },
739 { m_xplaneData.com1StandbyKhz, CFrequencyUnit::kHz() });
740 auto com2 = CComSystem::getCom2System({ m_xplaneData.com2ActiveKhz, CFrequencyUnit::kHz() },
741 { m_xplaneData.com2StandbyKhz, CFrequencyUnit::kHz() });
742 auto xpdr = CTransponder::getStandardTransponder(m_xplaneData.xpdrCode,
743 xpdrMode(m_xplaneData.xpdrMode, m_xplaneData.xpdrIdent));
744 if (aircraft.hasChangedCockpitData(com1, com2, xpdr))
745 {
746 m_xplaneData.com1ActiveKhz =
748 m_xplaneData.com1StandbyKhz =
750 m_xplaneData.com2ActiveKhz =
752 m_xplaneData.com2StandbyKhz =
754 m_xplaneData.xpdrCode = aircraft.getTransponderCode();
755 m_xplaneData.xpdrMode = xpdrMode(aircraft.getTransponderMode());
756 m_serviceProxy->setCom1ActiveKhz(m_xplaneData.com1ActiveKhz);
757 m_serviceProxy->setCom1StandbyKhz(m_xplaneData.com1StandbyKhz);
758 m_serviceProxy->setCom2ActiveKhz(m_xplaneData.com2ActiveKhz);
759 m_serviceProxy->setCom2StandbyKhz(m_xplaneData.com2StandbyKhz);
760 m_serviceProxy->setTransponderCode(m_xplaneData.xpdrCode);
761 m_serviceProxy->setTransponderMode(m_xplaneData.xpdrMode);
762
763 m_serviceProxy
764 ->cancelAllPendingAsyncCalls(); // in case there is already a reply with some old data incoming
765 return true;
766 }
767 return false;
768 }
769
771 {
772 if (originator == this->identifier())
773 {
774 return false;
775 }
777 {
778 return false;
779 } // could happen during shutdown
780
782 Q_UNUSED(selcal)
783 return false;
784 }
785
786 void CSimulatorXPlane::loadCslPackages()
787 {
788 // An ad-hoc type for keeping track of packages as they are discovered.
789 // A model is a member of a package if the model path starts with the package path.
790 // A trailing separator is appended only for checking if a model path starts with this path.
791 struct Prefix
792 {
793 Prefix(const QString &p) : s(p + '/') {}
794 QString parent() const
795 {
797 }
798 bool isPrefixOf(const QString &o) const { return o.startsWith(s); }
799 QString s;
800 };
801
802 // Heterogeneous comparison so a package can be found by binary search
803 // (e.g. std::lower_bound) using a model path as the search key.
804 struct PrefixComparator
805 {
806 bool operator()(const Prefix &a, const QString &b) const
807 {
808 return QStringView(a.s) < QStringView(b).left(a.s.size());
809 }
810 bool operator()(const QString &a, const Prefix &b) const
811 {
812 return QStringView(a).left(b.s.size()) < QStringView(b.s);
813 }
814 };
815
816 // The list of packages discovered so far.
817 QList<Prefix> packages;
818
819 Q_ASSERT(this->isConnected());
820 const CAircraftModelList models = this->getModelSet();
821
822 // Find the CSL packages for all models in the list
823 for (const auto &model : models)
824 {
825 const QString &modelFile = model.getFileName();
826 if (modelFile.isEmpty() || !QFile::exists(modelFile))
827 {
828 continue;
829 }
830
831 // Check if this model's package was already found
832 auto it = std::lower_bound(packages.begin(), packages.end(), modelFile, PrefixComparator());
833 if (it != packages.end() && it->isPrefixOf(modelFile))
834 {
835 continue;
836 }
837
838 // This model's package was not already found, so find it and add it to the list
839 QString package = findCslPackage(modelFile);
840 if (package.isEmpty())
841 {
842 continue;
843 }
844 packages.insert(it, package);
845 }
846
847 // comment KB 2019-06
848 // a package is one xsb_aircraft.txt file BB has 9, X-CSL has 76
849 CSetBuilder<QString> superpackages;
850 for (const Prefix &package : std::as_const(packages))
851 {
852 superpackages.insert(package.parent());
853 }
854 QStringList superpackagesList = superpackages;
855
857 for (const QString &package : superpackagesList)
858 {
859 if (CDirectoryUtils::isSameOrSubDirectoryOf(package, simDir))
860 {
861 const QString message = m_trafficProxy->loadPlanesPackage(package);
862 if (!message.isEmpty())
863 {
864 CLogMessage(this).validationError(u"CSL package '%1' xpmp error: %2") << package << message;
865 }
866 }
867 else
868 {
869 CLogMessage(this).validationError(
870 u"CSL package '%1' can not be loaded as it is outside the X-Plane installation directory")
871 << package;
872 }
873 }
874 }
875
876 QString CSimulatorXPlane::findCslPackage(const QString &modelFile)
877 {
879 const QFileInfo info(modelFile);
880 QDir dir = info.isDir() ? QDir(modelFile) : info.dir();
881 do
882 {
883 if (dir.exists(QStringLiteral("xsb_aircraft.txt")))
884 {
885 return dir.path();
886 }
887 }
888 while (dir.cdUp());
889 CLogMessage(this).warning(u"Failed to find CSL package for %1") << modelFile;
890 return {};
891 }
892
894 {
895 // avoid issue in rapid shutdown
897 {
898 return false;
899 }
900
901 // entry checks
902 Q_ASSERT_X(CThreadUtils::isInThisThread(this), Q_FUNC_INFO, "thread");
903 Q_ASSERT_X(!newRemoteAircraft.getCallsign().isEmpty(), Q_FUNC_INFO, "empty callsign");
904 Q_ASSERT_X(newRemoteAircraft.hasModelString(), Q_FUNC_INFO, "missing model string");
905
906 // crosscheck if still a valid aircraft
907 // it can happen that aircraft has been removed, timed out ...
908 if (!this->isAircraftInRangeOrTestMode(newRemoteAircraft.getCallsign()))
909 {
910 // next cycle will be called by callbacks or timer
911 CLogMessage(this).warning(u"Aircraft '%1' no longer in range, will not add")
912 << newRemoteAircraft.getCallsign();
913 return false;
914 }
915
916 if (this->canAddAircraft())
917 {
918 // no aircraft pending, add
919 this->logAddingAircraftModel(newRemoteAircraft);
920 const qint64 now = QDateTime::currentMSecsSinceEpoch();
921 m_addingInProgressAircraft.insert(newRemoteAircraft.getCallsign(), now);
922 const QString callsign = newRemoteAircraft.getCallsign().asString();
923 CAircraftModel aircraftModel = newRemoteAircraft.getModel();
924
925 // some more validation
926 if (aircraftModel.getCallsign() != newRemoteAircraft.getCallsign())
927 {
928 CLogMessage(this).warning(u"Model for '%1' has no callsign, maybe using a default model") << callsign;
929 aircraftModel.setCallsign(callsign); // fix callsign to avoid follow up issues
930
931 // we could disable the aircraft?
932 }
933
934 const QString livery = aircraftModel.getLivery().getCombinedCode();
935 m_trafficProxy->addPlane(callsign, aircraftModel.getModelString(),
936 newRemoteAircraft.getAircraftIcaoCode().getDesignator(),
937 newRemoteAircraft.getAirlineIcaoCode().getDesignator(), livery);
938 PlanesPositions pos;
939 pos.push_back(newRemoteAircraft.getSituation());
940 m_trafficProxy->setPlanesPositions(pos);
941
942 PlanesSurfaces surfaces;
943 surfaces.push_back(newRemoteAircraft.getCallsign(), newRemoteAircraft.getParts());
944 m_trafficProxy->setPlanesSurfaces(surfaces);
945 }
946 else
947 {
948 // add in queue
949 m_pendingToBeAddedAircraft.replaceOrAdd(newRemoteAircraft);
950 }
951 return true;
952 }
953
955 {
956 // avoid issue in rapid shutdown
958 {
959 return false;
960 }
961
962 // only remove from sim
963 Q_ASSERT_X(CThreadUtils::isInThisThread(this), Q_FUNC_INFO, "wrong thread");
964 if (callsign.isEmpty())
965 {
966 return false;
967 } // can happen if an object is not an aircraft
968
969 // really remove from simulator
970 if (!this->isTestMode() && !m_xplaneAircraftObjects.contains(callsign) &&
971 !m_pendingToBeAddedAircraft.containsCallsign(callsign) && !m_addingInProgressAircraft.contains(callsign))
972 {
973 // not existing aircraft
974 return false;
975 }
976
977 // mark in provider
978 const bool updated = this->updateAircraftRendered(callsign, false);
979 if (updated)
980 {
981 if (m_xplaneAircraftObjects.contains(callsign))
982 {
983 const CXPlaneMPAircraft &xplaneAircraft = m_xplaneAircraftObjects[callsign];
984 CSimulatedAircraft aircraft(xplaneAircraft.getAircraft());
985 aircraft.setRendered(false);
986 emit this->aircraftRenderingChanged(aircraft);
987 }
988 else if (m_pendingToBeAddedAircraft.containsCallsign(callsign))
989 {
990 CSimulatedAircraft aircraft = m_pendingToBeAddedAircraft.findFirstByCallsign(callsign);
991 aircraft.setRendered(false);
992 emit this->aircraftRenderingChanged(aircraft);
993 }
994 }
995
996 // if adding in progress, postpone
997 if (m_addingInProgressAircraft.contains(callsign))
998 {
999 // we are just about to add that aircraft
1000 QPointer<CSimulatorXPlane> myself(this);
1001 QTimer::singleShot(TimeoutAdding, this, [=, this] {
1002 if (!myself)
1003 {
1004 return;
1005 }
1006 m_addingInProgressAircraft.remove(callsign); // remove as "in progress"
1007 this->physicallyRemoveRemoteAircraft(callsign); // and remove from sim. if it was added in the mean time
1008 });
1009 return false; // do nothing right now
1010 }
1011
1012 m_trafficProxy->removePlane(callsign.asString());
1013 m_xplaneAircraftObjects.remove(callsign);
1014 m_pendingToBeAddedAircraft.removeByCallsign(callsign);
1015
1016 // bye
1017 return CSimulatorPluginCommon::physicallyRemoveRemoteAircraft(callsign);
1018 }
1019
1021 {
1022 if (this->isShuttingDownOrDisconnected())
1023 {
1024 return 0;
1025 }
1026 m_pendingToBeAddedAircraft.clear();
1027 m_addingInProgressAircraft.clear();
1028 return CSimulatorPluginCommon::physicallyRemoveAllRemoteAircraft();
1029 }
1030
1032 {
1034 return this->getAircraftInRange().findByRendered(true).getCallsigns(); // just a poor workaround
1035 }
1036
1038 {
1039 if (!m_trafficProxy || !m_trafficProxy->isValid())
1040 {
1041 return false;
1042 }
1043 m_trafficProxy->setFollowedAircraft(callsign.toQString());
1044 return true;
1045 }
1046
1047 void CSimulatorXPlane::updateRemoteAircraft()
1048 {
1049 Q_ASSERT_X(CThreadUtils::isInThisThread(this), Q_FUNC_INFO, "thread");
1050
1051 const int remoteAircraftNo = this->getAircraftInRangeCount();
1052 if (remoteAircraftNo < 1)
1053 {
1054 return;
1055 }
1056
1057 // values used for position and parts
1059 const qint64 currentTimestamp = QDateTime::currentMSecsSinceEpoch();
1060
1061 // interpolation for all remote aircraft
1062 PlanesPositions planesPositions;
1063 PlanesSurfaces planesSurfaces;
1064 PlanesTransponders planesTransponders;
1065
1066 uint32_t aircraftNumber = 0;
1067 const bool updateAllAircraft = this->isUpdateAllRemoteAircraft(currentTimestamp);
1068 const CCallsignSet callsignsInRange = this->getAircraftInRangeCallsigns();
1069 for (const CXPlaneMPAircraft &xplaneAircraft : std::as_const(m_xplaneAircraftObjects))
1070 {
1071 const CCallsign callsign(xplaneAircraft.getCallsign());
1072 const bool hasCallsign = !callsign.isEmpty();
1073 if (!hasCallsign)
1074 {
1075 // does not make sense to continue here
1076 SWIFT_VERIFY_X(false, Q_FUNC_INFO, "missing callsign");
1077 continue;
1078 }
1079
1080 // skip no longer in range
1081 if (!callsignsInRange.contains(callsign))
1082 {
1083 continue;
1084 }
1085
1086 planesTransponders.callsigns.push_back(callsign.asString());
1087 planesTransponders.codes.push_back(xplaneAircraft.getAircraft().getTransponderCode());
1088 CTransponder::TransponderMode transponderMode = xplaneAircraft.getAircraft().getTransponderMode();
1089 planesTransponders.idents.push_back(transponderMode == CTransponder::StateIdent);
1090 planesTransponders.modeCs.push_back(transponderMode == CTransponder::ModeC);
1091
1092 // setup
1094 this->getInterpolationSetupConsolidated(callsign, updateAllAircraft);
1095
1096 // interpolated situation/parts
1097 const CInterpolationResult result =
1098 xplaneAircraft.getInterpolation(currentTimestamp, setup, aircraftNumber++);
1100 {
1101 CAircraftSituation interpolatedSituation(result);
1102
1103 // adjust altitude to compensate for XP12 temperature effect
1104 const CLength relativeAltitude =
1105 interpolatedSituation.geodeticHeight() - getOwnAircraftPosition().geodeticHeight();
1106 const double altitudeDeltaWeight =
1107 2 - qBound(3000.0, relativeAltitude.abs().value(CLengthUnit::ft()), 6000.0) / 3000;
1108 const CLength alt = interpolatedSituation.getAltitude() +
1109 m_altitudeDelta * altitudeDeltaWeight *
1110 (1 - interpolatedSituation.getOnGroundInfo().getGroundFactor());
1111 interpolatedSituation.setAltitude({ alt, interpolatedSituation.getAltitude().getReferenceDatum() });
1112
1113 // update situation
1114 if (updateAllAircraft || !this->isEqualLastSent(interpolatedSituation))
1115 {
1116 this->rememberLastSent(interpolatedSituation);
1117 planesPositions.push_back(interpolatedSituation);
1118 }
1119 }
1120 else
1121 {
1122 CLogMessage(this).warning(
1123 this->getInvalidSituationLogMessage(callsign, result.getInterpolationStatus()));
1124 }
1125
1126 const CAircraftParts parts(result);
1127 if (result.getPartsStatus().isSupportingParts() || parts.getPartsDetails() == CAircraftParts::GuessedParts)
1128 {
1129 if (updateAllAircraft || !this->isEqualLastSent(parts, callsign))
1130 {
1131 this->rememberLastSent(parts, callsign);
1132 planesSurfaces.push_back(xplaneAircraft.getCallsign(), parts);
1133 }
1134 }
1135
1136 } // all callsigns
1137
1138 if (!planesTransponders.isEmpty())
1139 {
1140 m_trafficProxy->setPlanesTransponders(planesTransponders);
1141 }
1142
1143 if (!planesPositions.isEmpty())
1144 {
1146 {
1147 SWIFT_VERIFY_X(planesPositions.hasSameSizes(), Q_FUNC_INFO, "Mismatching sizes");
1148 }
1149 m_trafficProxy->setPlanesPositions(planesPositions);
1150 }
1151
1152 if (!planesSurfaces.isEmpty())
1153 {
1154 m_trafficProxy->setPlanesSurfaces(planesSurfaces);
1155 }
1156
1157 // stats
1158 this->finishUpdateRemoteAircraftAndSetStatistics(currentTimestamp);
1159 }
1160
1161 void CSimulatorXPlane::requestRemoteAircraftDataFromXPlane()
1162 {
1163 if (this->isShuttingDownOrDisconnected())
1164 {
1165 return;
1166 }
1167
1168 // It is not required to request all elevations and CGs, but only for aircraft "near ground relevant"
1169 // - we could use the elevation cache and CG cache to decide if we need to request
1170 // - if an aircraft is on ground but not moving, we do not need to request elevation if we already have it (it
1171 // will not change
1172 CCallsignSet callsigns = m_xplaneAircraftObjects.getAllCallsigns();
1173 const CCallsignSet remove = this->getLastSentCanLikelySkipNearGroundInterpolation().getCallsigns();
1174 callsigns.remove(remove);
1175 if (!callsigns.isEmpty())
1176 {
1177 this->requestRemoteAircraftDataFromXPlane(callsigns);
1178 }
1179 }
1180
1181 void CSimulatorXPlane::requestRemoteAircraftDataFromXPlane(const CCallsignSet &callsigns)
1182 {
1183 if (callsigns.isEmpty())
1184 {
1185 return;
1186 }
1187 if (!m_trafficProxy || this->isShuttingDown())
1188 {
1189 return;
1190 }
1191 const QStringList csStrings = callsigns.getCallsignStrings();
1192 QPointer<CSimulatorXPlane> myself(this);
1193 m_trafficProxy->getRemoteAircraftData(
1194 csStrings, [=, this](const QStringList &callsigns, const QDoubleList &latitudesDeg,
1195 const QDoubleList &longitudesDeg, const QDoubleList &elevationsMeters,
1196 const QBoolList &waterFlags, const QDoubleList &verticalOffsetsMeters) {
1197 if (!myself)
1198 {
1199 return;
1200 }
1201 this->updateRemoteAircraftFromSimulator(callsigns, latitudesDeg, longitudesDeg, elevationsMeters,
1202 waterFlags, verticalOffsetsMeters);
1203 });
1204 }
1205
1206 void CSimulatorXPlane::triggerRequestRemoteAircraftDataFromXPlane(const CCallsignSet &callsigns)
1207 {
1208 if (callsigns.isEmpty())
1209 {
1210 return;
1211 }
1212 QPointer<CSimulatorXPlane> myself(this);
1213 QTimer::singleShot(0, this, [=, this] {
1214 if (!myself)
1215 {
1216 return;
1217 }
1218 this->requestRemoteAircraftDataFromXPlane(callsigns);
1219 });
1220 }
1221
1222 void CSimulatorXPlane::updateRemoteAircraftFromSimulator(
1223 const QStringList &callsigns, const QDoubleList &latitudesDeg, const QDoubleList &longitudesDeg,
1224 const QDoubleList &elevationsMeters, const QBoolList &waterFlags, const QDoubleList &verticalOffsetsMeters)
1225 {
1226 const int size = callsigns.size();
1227
1228 // we skip if we are not near ground
1230 {
1231 Q_ASSERT_X(elevationsMeters.size() == size, Q_FUNC_INFO, "Wrong elevations");
1232 Q_ASSERT_X(waterFlags.size() == size, Q_FUNC_INFO, "Wrong waterFlags");
1233 Q_ASSERT_X(latitudesDeg.size() == size, Q_FUNC_INFO, "Wrong latitudesDeg");
1234 Q_ASSERT_X(longitudesDeg.size() == size, Q_FUNC_INFO, "Wrong longitudesDeg");
1235 Q_ASSERT_X(verticalOffsetsMeters.size() == size, Q_FUNC_INFO, "Wrong CG");
1236 }
1237
1238 const CCallsignSet logCallsigns = this->getLogCallsigns();
1239 static const QString hint("remote acft.");
1240 for (int i = 0; i < size; i++)
1241 {
1242 const bool emptyCs = callsigns[i].isEmpty();
1243 SWIFT_VERIFY_X(!emptyCs, Q_FUNC_INFO, "Need callsign");
1244 if (emptyCs)
1245 {
1246 continue;
1247 }
1248
1249 const CCallsign cs(callsigns[i]);
1250 if (!m_xplaneAircraftObjects.contains(cs))
1251 {
1252 continue;
1253 }
1254 const CXPlaneMPAircraft xpAircraft = m_xplaneAircraftObjects[cs];
1255 SWIFT_VERIFY_X(xpAircraft.hasCallsign(), Q_FUNC_INFO, "Need callsign");
1256 if (!xpAircraft.hasCallsign())
1257 {
1258 continue;
1259 }
1260
1261 CElevationPlane elevation = CElevationPlane::null();
1262 if (!std::isnan(elevationsMeters[i]))
1263 {
1264 const CAltitude elevationAlt = CAltitude(elevationsMeters[i], CLengthUnit::m(), CLengthUnit::ft());
1265 elevation = CElevationPlane(CLatitude(latitudesDeg[i], CAngleUnit::deg()),
1266 CLongitude(longitudesDeg[i], CAngleUnit::deg()), elevationAlt,
1268 }
1269
1270 const double cgValue = verticalOffsetsMeters[i]; // XP offset is swift CG
1271 CLength cg = std::isnan(cgValue) ? CLength::null() : CLength(cgValue, CLengthUnit::m(), CLengthUnit::ft());
1272 cg = fixSimulatorCg(cg, xpAircraft.getAircraftModel());
1273
1274 // if we knew "on ground" here we could set it as parameter of rememberElevationAndSimulatorCG
1275 // with T778 we do NOT use this function for elevation here if "isSuspicious"
1276 const bool waterFlag = waterFlags[i];
1277 const bool useElevation = this->handleProbeValue(elevation, cs, waterFlag, hint, true);
1278 this->rememberElevationAndSimulatorCG(cs, xpAircraft.getAircraftModel(), false,
1279 useElevation ? elevation : CElevationPlane::null(), cg);
1280
1281 // loopback
1282 if (logCallsigns.contains(cs))
1283 {
1284 this->addLoopbackSituation(cs, elevation, cg);
1285 }
1286 }
1287 }
1288
1289 CLength CSimulatorXPlane::fixSimulatorCg(const CLength &cg, const CAircraftModel &model)
1290 {
1292 // For XCSL null means no offset => 0
1293 // so not to override it with some DB value in X mode, we set it to "0"
1295 {
1296 return { 0.0, CLengthUnit::ft() };
1297 }
1298 return cg;
1299 }
1300
1301 void CSimulatorXPlane::disconnectFromDBus()
1302 {
1303 if (m_dBusConnection.isConnected())
1304 {
1305 if (m_trafficProxy)
1306 {
1307 m_trafficProxy->cleanup();
1308 }
1309
1310 if (m_dbusMode == P2P)
1311 {
1312 QDBusConnection::disconnectFromPeer(m_dBusConnection.name());
1313 }
1314 else
1315 {
1316 QDBusConnection::disconnectFromBus(m_dBusConnection.name());
1317 }
1318 }
1319 m_dBusConnection = QDBusConnection { "default" };
1320 }
1321
1322 bool CSimulatorXPlane::sendXSwiftBusSettings()
1323 {
1324 if (this->isShuttingDownOrDisconnected())
1325 {
1326 return false;
1327 }
1328 if (!m_serviceProxy)
1329 {
1330 return false;
1331 }
1332 CXSwiftBusSettings s = m_xSwiftBusServerSettings.get();
1334 m_serviceProxy->setSettingsJson(s.toXSwiftBusJsonStringQt());
1335 CLogMessage(this).info(u"Send settings: %1") << s.toQString(true);
1336 return true;
1337 }
1338
1339 CXSwiftBusSettings CSimulatorXPlane::receiveXSwiftBusSettings(bool &ok)
1340 {
1341 ok = false;
1342 CXSwiftBusSettings s;
1343
1344 if (this->isShuttingDownOrDisconnected())
1345 {
1346 return s;
1347 }
1348 if (!m_serviceProxy)
1349 {
1350 return s;
1351 }
1352
1353 const QString json = m_serviceProxy->getSettingsJson();
1354 s.parseXSwiftBusStringQt(json);
1355 ok = true;
1356 return s;
1357 }
1358
1359 void CSimulatorXPlane::onXSwiftBusSettingsChanged()
1360 {
1361 bool ok {};
1362 const CXSwiftBusSettings xPlaneSide = this->receiveXSwiftBusSettings(ok);
1363 if (ok)
1364 {
1365 // we only send if DBus did not change
1366 // DBus changes would require a restart
1367 const CXSwiftBusSettings swiftSide = m_xSwiftBusServerSettings.get();
1368 if (xPlaneSide.getDBusServerAddressQt() == swiftSide.getDBusServerAddressQt())
1369 {
1370 this->sendXSwiftBusSettings();
1371 }
1372 }
1373 }
1374
1375 void CSimulatorXPlane::setMinTerrainProbeDistance(const CLength &distance)
1376 {
1377 if (distance.isNull())
1378 {
1379 return;
1380 }
1381 if (m_minSuspicousTerrainProbe.isNull() || distance < m_minSuspicousTerrainProbe)
1382 {
1383 m_minSuspicousTerrainProbe = distance;
1384 }
1385 }
1386
1387 void CSimulatorXPlane::onRemoteAircraftAdded(const QString &callsign)
1388 {
1389 SWIFT_VERIFY_X(!callsign.isEmpty(), Q_FUNC_INFO, "Need callsign");
1390 if (callsign.isEmpty())
1391 {
1392 return;
1393 }
1394 const CCallsign cs(callsign);
1395 CSimulatedAircraft addedRemoteAircraft = this->getAircraftInRangeForCallsign(cs);
1396
1397 // statistics
1398 bool wasPending = false;
1399 if (m_addingInProgressAircraft.contains(cs))
1400 {
1401 wasPending = true;
1402 const qint64 wasStartedMs = m_addingInProgressAircraft.value(cs);
1403 const qint64 deltaTimeMs = QDateTime::currentMSecsSinceEpoch() - wasStartedMs;
1404 m_statsAddCurrentTimeMs = deltaTimeMs;
1405 m_statsAddMaxTimeMs = std::max(deltaTimeMs, m_statsAddMaxTimeMs);
1406 m_addingInProgressAircraft.remove(cs);
1407 }
1408
1409 if (!addedRemoteAircraft.hasCallsign())
1410 {
1411 CLogMessage(this).warning(u"Aircraft '%1' no longer in range, will be removed") << callsign;
1412 this->triggerRemoveAircraft(cs, TimeoutAdding);
1413 return;
1414 }
1415
1416 CLogMessage(this).info(u"Added aircraft '%1'") << callsign;
1417 if (!wasPending)
1418 {
1419 // timeout?
1420 // slow adding?
1421 CLogMessage(this).warning(u"Added callsign '%1' was not in progress anymore. Timeout?") << callsign;
1422 }
1423
1424 const bool rendered = true;
1425 addedRemoteAircraft.setRendered(rendered);
1426 this->updateAircraftRendered(cs, rendered);
1427 this->triggerRequestRemoteAircraftDataFromXPlane(cs);
1428 this->triggerAddNextPendingAircraft();
1429
1430 Q_ASSERT_X(addedRemoteAircraft.hasCallsign(), Q_FUNC_INFO,
1431 "No callsign"); // already checked above, MUST never happen
1432 Q_ASSERT_X(addedRemoteAircraft.getCallsign() == cs, Q_FUNC_INFO,
1433 "No callsign"); // already checked above, MUST never happen
1434 m_xplaneAircraftObjects.insert(cs, CXPlaneMPAircraft(addedRemoteAircraft, this, &m_interpolationLogger));
1435 emit this->aircraftRenderingChanged(addedRemoteAircraft);
1436 }
1437
1438 void CSimulatorXPlane::onRemoteAircraftAddingFailed(const QString &callsign)
1439 {
1440 SWIFT_VERIFY_X(!callsign.isEmpty(), Q_FUNC_INFO, "Need callsign");
1441 if (callsign.isEmpty())
1442 {
1443 return;
1444 }
1445 const CCallsign cs(callsign);
1446 CSimulatedAircraft failedRemoteAircraft = this->getAircraftInRangeForCallsign(cs);
1447
1448 if (failedRemoteAircraft.hasCallsign())
1449 {
1450 CLogMessage(this).warning(u"Adding aircraft failed: '%1'") << callsign;
1451 failedRemoteAircraft.setRendered(false);
1452 }
1453 else
1454 {
1455 CLogMessage(this).warning(u"Adding '%1' failed, but aircraft no longer in range, will be removed")
1456 << callsign;
1457 }
1458
1459 const bool wasPending = (static_cast<int>(m_addingInProgressAircraft.remove(cs)) > 0);
1460 Q_UNUSED(wasPending)
1461
1462 if (failedRemoteAircraft.hasCallsign() && !m_aircraftAddedFailed.containsCallsign(cs))
1463 {
1464 m_aircraftAddedFailed.push_back(failedRemoteAircraft);
1465 m_pendingToBeAddedAircraft.replaceOrAdd(failedRemoteAircraft); // try a second time
1466 }
1467 this->triggerAddNextPendingAircraft();
1468 }
1469
1470 void CSimulatorXPlane::addNextPendingAircraft()
1471 {
1472 if (m_pendingToBeAddedAircraft.isEmpty())
1473 {
1474 return;
1475 } // no more pending
1476
1477 // housekeeping
1478 this->detectTimeoutAdding();
1479
1480 // check if can add
1481 if (!this->canAddAircraft())
1482 {
1483 return;
1484 }
1485
1486 // next add cycle
1487 const CSimulatedAircraft newRemoteAircraft = m_pendingToBeAddedAircraft.front();
1488 m_pendingToBeAddedAircraft.pop_front();
1489 CLogMessage(this).info(u"Adding next pending aircraft '%1', pending %2, in progress %3")
1490 << newRemoteAircraft.getCallsignAsString() << m_pendingToBeAddedAircraft.size()
1491 << m_addingInProgressAircraft.size();
1492 this->physicallyAddRemoteAircraft(newRemoteAircraft);
1493 }
1494
1495 void CSimulatorXPlane::triggerAddNextPendingAircraft()
1496 {
1497 QPointer<CSimulatorXPlane> myself(this);
1498 QTimer::singleShot(100, this, [=, this] {
1499 if (!myself || !sApp || sApp->isShuttingDown())
1500 {
1501 return;
1502 }
1503 this->addNextPendingAircraft();
1504 });
1505 }
1506
1507 int CSimulatorXPlane::detectTimeoutAdding()
1508 {
1509 if (m_addingInProgressAircraft.isEmpty())
1510 {
1511 return 0;
1512 }
1513 const qint64 timeout = QDateTime::currentMSecsSinceEpoch() + TimeoutAdding;
1514 CCallsignSet timeoutCallsigns;
1515 const QList<CCallsign> addingCallsigns = m_addingInProgressAircraft.keys();
1516 for (const CCallsign &cs : addingCallsigns)
1517 {
1518 if (m_addingInProgressAircraft.value(cs) < timeout)
1519 {
1520 continue;
1521 }
1522 timeoutCallsigns.push_back(cs);
1523 }
1524
1525 for (const CCallsign &cs : std::as_const(timeoutCallsigns))
1526 {
1527 m_addingInProgressAircraft.remove(cs);
1528 CLogMessage(this).warning(u"Adding for '%1' timed out") << cs.asString();
1529 }
1530
1531 return timeoutCallsigns.size();
1532 }
1533
1534 void CSimulatorXPlane::triggerRemoveAircraft(const CCallsign &callsign, qint64 deferMs)
1535 {
1536 QPointer<CSimulatorXPlane> myself(this);
1537 QTimer::singleShot(deferMs, this, [=, this] {
1538 if (!myself)
1539 {
1540 return;
1541 }
1542 this->physicallyRemoveRemoteAircraft(callsign);
1543 });
1544 }
1545
1546 QPair<qint64, qint64> CSimulatorXPlane::minMaxTimestampsAddInProgress() const
1547 {
1548 static const QPair<qint64, qint64> empty(-1, -1);
1549 if (m_addingInProgressAircraft.isEmpty())
1550 {
1551 return empty;
1552 }
1553 const QList<qint64> ts = m_addingInProgressAircraft.values();
1554 const auto mm = std::minmax_element(ts.constBegin(), ts.constEnd());
1555 return { *mm.first, *mm.second };
1556 }
1557
1558 bool CSimulatorXPlane::canAddAircraft() const
1559 {
1560 if (m_addingInProgressAircraft.isEmpty())
1561 {
1562 return true;
1563 }
1564
1565 // check
1566 const qint64 now = QDateTime::currentMSecsSinceEpoch();
1567 const QPair<qint64, qint64> tsMM = this->minMaxTimestampsAddInProgress();
1568 const qint64 deltaLatest = now - tsMM.second;
1569 const bool canAdd = (deltaLatest > TimeoutAdding);
1570 return canAdd;
1571 }
1572
1574 IOwnAircraftProvider *ownAircraftProvider,
1575 IRemoteAircraftProvider *remoteAircraftProvider,
1576 IClientProvider *clientProvider)
1577 {
1578 return new CSimulatorXPlane(info, ownAircraftProvider, remoteAircraftProvider, clientProvider, this);
1579 }
1580
1582 {
1583 constexpr int QueryInterval = 5 * 1000; // 5 seconds
1584 m_timer.setInterval(QueryInterval);
1585 m_timer.setObjectName(this->objectName().append(":m_timer"));
1586 connect(&m_timer, &QTimer::timeout, this, &CSimulatorXPlaneListener::checkConnection);
1587 }
1588
1589 void CSimulatorXPlaneListener::startImpl() { m_timer.start(); }
1590
1591 void CSimulatorXPlaneListener::stopImpl() { m_timer.stop(); }
1592
1594 {
1595 if (!m_timer.isActive())
1596 {
1597 return;
1598 }
1599 if (this->isShuttingDown())
1600 {
1601 return;
1602 }
1603
1604 m_timer.start(); // restart because we will check just now
1606 QTimer::singleShot(0, this, [=, this] {
1607 if (!myself)
1608 {
1609 return;
1610 }
1611 checkConnection();
1612 });
1613 }
1614
1615 void CSimulatorXPlaneListener::checkConnection()
1616 {
1617 if (this->isShuttingDown())
1618 {
1619 return;
1620 }
1621 Q_ASSERT_X(!CThreadUtils::thisIsMainThread(), Q_FUNC_INFO, "Expect to run in background");
1622 QElapsedTimer t;
1623 t.start();
1624
1625 QString via;
1626 m_dBusServerAddress = m_xSwiftBusServerSettings.getThreadLocal().getDBusServerAddressQt();
1627 if (CDBusServer::isSessionOrSystemAddress(m_dBusServerAddress))
1628 {
1629 checkConnectionViaSessionBus();
1630 via = "SessionBus";
1631 }
1632 else if (CDBusServer::isQtDBusAddress(m_dBusServerAddress))
1633 {
1634 checkConnectionViaPeer(m_dBusServerAddress);
1635 via = "P2P";
1636 }
1637
1638 CLogMessage(this).debug(u"Checked sim. 'XPLANE' via '%1' connection in %2ms") << via << t.elapsed();
1639 }
1640
1641 void CSimulatorXPlaneListener::checkConnectionViaSessionBus()
1642 {
1643 m_DBusConnection = QDBusConnection::sessionBus();
1644 if (!m_DBusConnection.isConnected())
1645 {
1646 QDBusConnection::disconnectFromBus(m_DBusConnection.name());
1647 return;
1648 }
1649 checkConnectionCommon(); // bus
1650 QDBusConnection::disconnectFromBus(m_DBusConnection.name());
1651 }
1652
1653 void CSimulatorXPlaneListener::checkConnectionViaPeer(const QString &address)
1654 {
1655 m_DBusConnection = QDBusConnection::connectToPeer(address, "xswiftbus");
1656 if (!m_DBusConnection.isConnected())
1657 {
1658 // This is required to cleanup the connection in QtDBus
1659 QDBusConnection::disconnectFromPeer(m_DBusConnection.name());
1660 return;
1661 }
1662 checkConnectionCommon(); // peer
1663 QDBusConnection::disconnectFromPeer(m_DBusConnection.name());
1664 }
1665
1666 void CSimulatorXPlaneListener::checkConnectionCommon()
1667 {
1668 CXSwiftBusServiceProxy service(m_DBusConnection);
1669 CXSwiftBusTrafficProxy traffic(m_DBusConnection);
1670
1671 const bool result = service.isValid() && traffic.isValid();
1672 if (!result)
1673 {
1674 return;
1675 }
1676
1677 const QString swiftVersion = CBuildConfig::getVersionString();
1678 const QString xswiftbusVersion = service.getVersionNumber();
1679 const QString xswiftbusCommitHash = service.getCommitHash();
1680 if (xswiftbusVersion.isEmpty())
1681 {
1682 CLogMessage(this).warning(u"Could not determine which version of xswiftbus is running. Mismatched versions "
1683 u"might cause instability.");
1684 }
1685 else if (commitHash() != xswiftbusCommitHash)
1686 {
1687 CLogMessage(this).error(u"You are using an incorrect version of xswiftbus. The version of xswiftbus (%1) "
1688 u"should match the version of swift (%2). Consider upgrading!")
1689 << xswiftbusVersion << swiftVersion;
1690 }
1691
1692 if (!traffic.initialize())
1693 {
1694 CLogMessage(this).error(
1695 u"Connection to xswiftbus successful, but could not initialize xswiftbus. Check X-Plane Log.txt.");
1696 return;
1697 }
1698
1699 const MultiplayerAcquireInfo info = traffic.acquireMultiplayerPlanes();
1700 if (!info.hasAcquired)
1701 {
1702 const QString owner =
1703 info.owner.trimmed().isEmpty() ? QStringLiteral("unknown plugin") : info.owner.trimmed();
1704 CLogMessage(this).error(
1705 u"Connection to xswiftbus successful, but could not acquire multiplayer planes. '%1' has acquired them "
1706 u"already. Disable '%2' or remove it if not required and reload xswiftbus.")
1707 << owner << owner.toLower();
1708 return;
1709 }
1710
1712 }
1713
1714 void CSimulatorXPlaneListener::serviceRegistered(const QString &serviceName)
1715 {
1716 if (serviceName == xswiftbusServiceName())
1717 {
1719 }
1720 QDBusConnection::disconnectFromBus(m_DBusConnection.name());
1721 }
1722
1723 void CSimulatorXPlaneListener::onXSwiftBusServerSettingChanged()
1724 {
1725 const CXSwiftBusSettings s = m_xSwiftBusServerSettings.get();
1726 if (m_dBusServerAddress != s.getDBusServerAddressQt())
1727 {
1728 this->stop();
1729 this->start();
1730 m_dBusServerAddress = s.getDBusServerAddressQt();
1731 }
1732 }
1733} // namespace swift::simplugin::xplane
SWIFT_CORE_EXPORT swift::core::CApplication * sApp
Single instance of application object.
static CAngleUnit rad()
Radians.
Definition units.h:268
static CAngleUnit deg()
Degrees.
Definition units.h:276
static CFrequencyUnit kHz()
Kilohertz.
Definition units.h:371
static const QString & getVersionString()
Version as QVersionNumber.
static bool isLocalDeveloperDebugBuild()
Local build for developers.
bool isShuttingDown() const
Is application shutting down?
Interface to a simulator.
Definition simulator.h:59
double m_simTimeRatio
ratio of simulation time to real time, due to low FPS (X-Plane)
Definition simulator.h:566
bool addLoopbackSituation(const swift::misc::aviation::CAircraftSituation &situation)
Add a loopback situation if logging is enabled.
bool isEqualLastSent(const swift::misc::aviation::CAircraftSituation &compare) const
Equal to last sent situation.
bool updateOwnSituationAndGroundElevation(const swift::misc::aviation::CAircraftSituation &situation)
Update own aircraft position and if suitable use it to update ground elevation.
bool isUpdateAllRemoteAircraft(qint64 currentTimestamp=-1) const
Do update all remote aircraft?
virtual bool isShuttingDown() const
Is overall (swift) application shutting down.
Definition simulator.h:214
void requestedElevation(const swift::misc::aviation::CCallsign &callsign)
Requested elevation, call pending.
bool m_updateRemoteAircraftInProgress
currently updating remote aircraft
Definition simulator.h:559
void rememberElevationAndSimulatorCG(const swift::misc::aviation::CCallsign &callsign, const swift::misc::simulation::CAircraftModel &model, bool likelyOnGroundElevation, const swift::misc::geo::CElevationPlane &elevation, const swift::misc::physical_quantities::CLength &simulatorCG)
Set elevation and CG in the providers and for auto publishing.
double m_trackMilesShort
difference between real and reported groundspeed, multiplied by time
Definition simulator.h:567
double m_minutesLate
difference between real and reported groundspeed, integrated over time
Definition simulator.h:568
bool isAircraftInRangeOrTestMode(const swift::misc::aviation::CCallsign &callsign) const
Test version aware version of isAircraftInRange.
void finishUpdateRemoteAircraftAndSetStatistics(qint64 startTime, bool limited=false)
Update stats and flags.
void insufficientFrameRateDetected(bool fatal)
Frame rate has fallen too far below the threshold to maintain consistent sim rate.
void reverseLookupAndUpdateOwnAircraftModel(const swift::misc::simulation::CAircraftModel &model)
Set own model.
swift::misc::aviation::CAircraftSituationList getLastSentCanLikelySkipNearGroundInterpolation() const
Last sent situations.
bool isTestMode() const
Test mode? (driver can skip code parts etc., driver dependent).
Definition simulator.h:183
swift::misc::simulation::CAircraftModelList getModelSet() const
Get the model set.
void emitSimulatorCombinedStatus(SimulatorStatus oldStatus=Unspecified)
Emit the combined status.
void logAddingAircraftModel(const swift::misc::simulation::CSimulatedAircraft &aircraft) const
Unified qeeing aircraft message.
swift::misc::simulation::CInterpolationAndRenderingSetupPerCallsign getInterpolationSetupConsolidated(const swift::misc::aviation::CCallsign &callsign, bool forceFullUpdate) const
Consolidate setup with other data like from swift::misc::simulation::IRemoteAircraftProvider.
swift::misc::simulation::settings::CSpecializedSimulatorSettings getSimulatorSettings() const
Settings for current simulator.
Definition simulator.h:162
swift::misc::simulation::CInterpolationLogger m_interpolationLogger
log.interpolation
Definition simulator.h:582
void aircraftRenderingChanged(const swift::misc::simulation::CSimulatedAircraft &aircraft)
Aircraft rendering changed.
virtual bool isShuttingDownOrDisconnected() const
Shutting down or disconnected?
Definition simulator.h:217
virtual void initSimulatorInternals()
Init the internals info from the simulator.
QString getInvalidSituationLogMessage(const swift::misc::aviation::CCallsign &callsign, const swift::misc::simulation::CInterpolationStatus &status, const QString &details={}) const
Info about invalid situation.
void rememberLastSent(const swift::misc::aviation::CAircraftSituation &sent)
Remember as last sent.
void simulatorStarted(const swift::misc::simulation::CSimulatorPluginInfo &info)
Emitted when the listener discovers the simulator running.
const swift::misc::simulation::CSimulatorPluginInfo & getPluginInfo() const
Corresponding info.
Definition simulator.h:641
ISimulatorListener(const swift::misc::simulation::CSimulatorPluginInfo &info)
Constructor.
virtual bool isShuttingDown() const
Overall (swift) application shutting down.
void start()
Start listening for the simulator to start.
void stop()
Stops listening.
const T & getThreadLocal() const
Read the current value.
Definition valuecache.h:403
size_type size() const
Returns number of elements in the collection.
Definition collection.h:191
void remove(const T &object)
Efficient remove using the find and erase of the implementation container. Typically O(log n).
Definition collection.h:316
iterator insert(const_iterator hint, const T &value)
For compatibility with std::inserter.
Definition collection.h:205
bool isEmpty() const
Synonym for empty.
Definition collection.h:197
iterator push_back(const T &value)
Synonym for insert.
Definition collection.h:244
void clear()
Removes all elements in the collection.
Definition collection.h:200
static bool isSessionOrSystemAddress(const QString &address)
True if address is session or system bus address.
static bool isQtDBusAddress(const QString &address)
True if a valid Qt DBus address, e.g. "unix:tmpdir=/tmp", "tcp:host=127.0.0.1,port=45000".
static bool isSameOrSubDirectoryOf(const QString &testDir, const QString &parentDir)
Is "testDir" a subdirectory (possibly nested) of "parentDir" or the same directory.
const CIdentifier & identifier() const
Get identifier.
Value object encapsulating information identifying a component of a modular distributed swift process...
Definition identifier.h:29
Class for emitting a log message.
Definition logmessage.h:27
Derived & debug()
Set the severity to debug.
Derived & warning(const char16_t(&format)[N])
Set the severity to warning, providing a format string.
Derived & info(const char16_t(&format)[N])
Set the severity to info, providing a format string.
bool contains(const T &object) const
Return true if there is an element equal to given object. Uses the most efficient implementation avai...
Definition range.h:109
void push_back(const T &value)
Appends an element at the end of the sequence.
Definition sequence.h:308
void insert(const T &value)
Add an element to the set. Runs in amortized constant time.
Definition setbuilder.h:29
Streamable status message, e.g.
QString getMessage() const
Message.
Status messages, e.g. from Core -> GUI.
static bool thisIsMainThread()
Is the current thread the application thread?
static bool isInThisThread(const QObject *toBeTested)
Is the current thread the object's thread?
Value object for ICAO classification.
const QString & getDesignator() const
Get ICAO designator, e.g. "B737".
Value object encapsulating information of aircraft's parts.
bool isNull() const
NULL parts object?
PartsDetails getPartsDetails() const
Get parts details.
Value object encapsulating information of an aircraft's situation.
void setPressureAltitude(const CAltitude &altitude)
Set pressure altitude.
void setGroundSpeed(const physical_quantities::CSpeed &groundspeed)
Set ground speed.
bool setGroundElevation(const aviation::CAltitude &altitude, GndElevationInfo info, bool transferred=false)
Elevation of the ground directly beneath at the given situation.
void setBank(const physical_quantities::CAngle &bank)
Set bank (angle).
void setHeading(const CHeading &heading)
Set heading.
@ FromProvider
from swift::misc::simulation::ISimulationEnvironmentProvider
void setAltitude(const CAltitude &altitude)
Set altitude.
void setPitch(const physical_quantities::CAngle &pitch)
Set pitch.
void setVelocity(const CAircraftVelocity &velocity)
Set 6DOF velocity.
void setPosition(const geo::CCoordinateGeodetic &position)
Set position.
const QString & getDesignator() const
Get airline, e.g. "DLH".
Altitude as used in aviation, can be AGL or MSL altitude.
Definition altitude.h:52
@ PressureAltitude
Altitude above the standard datum plane.
Definition altitude.h:82
CAltitude toPressureAltitude(const physical_quantities::CPressure &seaLevelPressure) const
Returns the altitude converted to pressure altitude. Requires the current barometric pressure at MSL.
Definition altitude.cpp:164
Value object encapsulating information of a callsign.
Definition callsign.h:30
const QString & asString() const
Get callsign (normalized).
Definition callsign.h:96
bool isEmpty() const
Is empty?
Definition callsign.h:63
Value object for a set of callsigns.
Definition callsignset.h:26
QStringList getCallsignStrings(bool sorted=false) const
The callsign strings.
static CComSystem getCom1System(double activeFrequencyMHz, double standbyFrequencyMHz=-1)
COM1 unit.
Definition comsystem.cpp:70
static CComSystem getCom2System(double activeFrequencyMHz, double standbyFrequencyMHz=-1)
COM2 unit.
Definition comsystem.cpp:84
const QString & getCombinedCode() const
Combined code.
Definition livery.h:71
swift::misc::physical_quantities::CFrequency getFrequencyStandby() const
Standby frequency.
Definition modulator.cpp:36
swift::misc::physical_quantities::CFrequency getFrequencyActive() const
Active frequency.
Definition modulator.cpp:30
Value object for SELCAL.
Definition selcal.h:31
static CTransponder getStandardTransponder(qint32 transponderCode, TransponderMode mode)
Transponder unit.
@ StateStandby
not a real mode, more a state
Definition transponder.h:33
@ StateIdent
not a real mode, more a state
Definition transponder.h:39
swift::misc::aviation::CCallsignSet getCallsigns() const
All callsigns.
void setGeodeticHeight(const aviation::CAltitude &height)
Set height (ellipsoidal or geodetic height).
const aviation::CAltitude & geodeticHeight() const
Height, ellipsoidal or geodetic height (used in GPS).
Plane of same elevation, can be a single point or larger area (e.g. airport).
static const physical_quantities::CLength & singlePointRadius()
Radius for single point.
double getAltitudeValue(const physical_quantities::CLengthUnit &unit) const
Altitude (synonym for geodetic height).
const aviation::CAltitude & getAltitude() const
Altitude (synonym for geodetic height).
static const CElevationPlane & null()
NULL plane.
Geodetic coordinate, a position in 3D space relative to the reference geoid.
bool hasMSLGeodeticHeight() const
Geodetic height not null and aviation::CAltitude::MeanSeaLevel.
virtual bool isNull() const
Is null, means vector x, y, z == 0.
QString toQString(bool i18n=false) const
Cast as QString.
Definition mixinstring.h:74
Value object encapsulating information of a text message.
Definition textmessage.h:31
bool isPrivateMessage() const
Is private message?
const QString & getMessage() const
Get message.
Definition textmessage.h:78
bool isServerMessage() const
Initial message of server?
bool isSupervisorMessage() const
Supervisor message?
const aviation::CCallsign & getSenderCallsign() const
Get callsign (from).
Definition textmessage.h:54
Direct in memory access to client (network client) data.
Physical unit length (length).
Definition length.h:18
static CLengthUnit m()
Meter m.
Definition units.h:140
static CLengthUnit NM()
Nautical miles NM.
Definition units.h:148
static CLengthUnit ft()
Foot ft.
Definition units.h:157
double value(MU unit) const
Value in given unit.
QString valueRoundedAsString(MU unit, int digits=-1) const
Rounded value in given unit.
static CPressureUnit inHg()
Inch of mercury at 0°C.
Definition units.h:618
static CSpeedUnit m_s()
Meter/second m/s.
Definition units.h:808
static CTimeUnit s()
Second s.
Definition units.h:938
Aircraft model (used by another pilot, my models on disk).
const aviation::CCallsign & getCallsign() const
Corresponding callsign if applicable.
@ TypeModelMatchingDefaultModel
a default model assigned by model matching
@ TypeOwnSimulatorModel
represents own simulator model (AI model, model on disk)
void setCallsign(const aviation::CCallsign &callsign)
Corresponding callsign if applicable.
const CDistributor & getDistributor() const
Get distributor.
const aviation::CLivery & getLivery() const
Get livery.
const QString & getModelString() const
Model key, either queried or loaded from simulator model.
static const QString & xplaneXcsl()
Hardcoded keys for standard models.
bool matchesKeyOrAlias(const QString &keyOrAlias) const
Matches key or alias.
Value object for interpolator and rendering per callsign.
const CInterpolationStatus & getInterpolationStatus() const
Get status.
const CPartsStatus & getPartsStatus() const
Get status.
bool hasValidSituation() const
Is the corresponding position valid?
bool updateOwnParts(const aviation::CAircraftParts &parts)
Update own parts.
swift::misc::physical_quantities::CLength getDistanceToOwnAircraft(const swift::misc::geo::ICoordinateGeodetic &position) const
Distance to own aircraft.
bool updateCockpit(const swift::misc::simulation::CSimulatedAircraft &aircraft, const swift::misc::CIdentifier &originator)
Update cockpit, but only send signals when applicable.
swift::misc::geo::CCoordinateGeodetic getOwnAircraftPosition() const
Own aircraft's position.
CSimulatedAircraft getOwnAircraft() const
Own aircraft.
bool isSupportingParts() const
Supporting parts.
Definition partsstatus.h:26
aviation::CCallsignSet getAircraftInRangeCallsigns() const
Unique callsigns for aircraft in range.
bool isAircraftInRange(const aviation::CCallsign &callsign) const
Is aircraft in range?
CSimulatedAircraftList getAircraftInRange() const
All remote aircraft.
int getAircraftInRangeCount() const
Count remote aircraft.
CSimulatedAircraft getAircraftInRangeForCallsign(const aviation::CCallsign &callsign) const
Aircraft for callsign.
bool updateAircraftRendered(const aviation::CCallsign &callsign, bool rendered)
Set aircraft rendered.
Comprehensive information of an aircraft.
bool hasModelString() const
Has model string?
aviation::CTransponder::TransponderMode getTransponderMode() const
Get transponder mode.
const aviation::CComSystem & getCom2System() const
Get COM2 system.
const aviation::CComSystem & getCom1System() const
Get COM1 system.
const aviation::CCallsign & getCallsign() const
Get callsign.
qint32 getTransponderCode() const
Get transponder code.
bool hasCallsign() const
Callsign not empty, no further checks.
const aviation::CAircraftIcaoCode & getAircraftIcaoCode() const
Get aircraft ICAO info.
const aviation::CAircraftParts & getParts() const
Get aircraft parts.
bool hasChangedCockpitData(const aviation::CComSystem &com1, const aviation::CComSystem &com2, const aviation::CTransponder &transponder) const
Changed cockpit data?
const aviation::CAircraftSituation & getSituation() const
Get situation.
const simulation::CAircraftModel & getModel() const
Get model (model used for mapping).
QString getCallsignAsString() const
Get callsign.
const aviation::CAirlineIcaoCode & getAirlineIcaoCode() const
Airline ICAO code if any.
Q_REQUIRED_RESULT CSimulatedAircraftList findByRendered(bool rendered) const
Rendered / not rendered aircraft.
aviation::CCallsignSet getLogCallsigns() const
All callsigns marked to be logged.
Direct threadsafe in memory access to own aircraft.
Direct thread safe in memory access to remote aircraft.
void setSimulatorDetails(const QString &name, const QString &details, const QString &version)
Set version and simulator details from running simulator.
void removePendingElevationRequest(const aviation::CCallsign &cs)
Remove pending timestamp.
void setDefaultModel(const CAircraftModel &defaultModel)
Default model.
const QString & getSimulatorDirectoryOrDefault() const
Simulator directory or default path.
void parseXSwiftBusStringQt(const QString &json)
Load and parse config file.
CSimulatorPluginCommon(const swift::misc::simulation::CSimulatorPluginInfo &info, swift::misc::simulation::IOwnAircraftProvider *ownAircraftProvider, swift::misc::simulation::IRemoteAircraftProvider *renderedAircraftProvider, swift::misc::network::IClientProvider *clientProvider, QObject *parent=nullptr)
Constructor.
swift::core::ISimulator * create(const swift::misc::simulation::CSimulatorPluginInfo &info, swift::misc::simulation::IOwnAircraftProvider *ownAircraftProvider, swift::misc::simulation::IRemoteAircraftProvider *remoteAircraftProvider, swift::misc::network::IClientProvider *clientProvider)
Create a new instance of a driver.
int physicallyRemoveAllRemoteAircraft()
Remove all remote aircraft and their data via ISimulator::clearAllRemoteAircraftData.
bool followAircraft(const swift::misc::aviation::CCallsign &callsign)
Follow aircraft.
bool isConnected() const
Are we connected to the simulator?
bool requestElevation(const swift::misc::geo::ICoordinateGeodetic &reference, const swift::misc::aviation::CCallsign &callsign)
Request elevation, there is no guarantee the requested elevation will be available in the provider.
CSimulatorXPlane(const swift::misc::simulation::CSimulatorPluginInfo &info, swift::misc::simulation::IOwnAircraftProvider *ownAircraftProvider, swift::misc::simulation::IRemoteAircraftProvider *remoteAircraftProvider, swift::misc::network::IClientProvider *clientProvider, QObject *parent=nullptr)
Constructor.
bool testSendSituationAndParts(const swift::misc::aviation::CCallsign &callsign, const swift::misc::aviation::CAircraftSituation &situation, const swift::misc::aviation::CAircraftParts &parts)
Send situation/parts for testing.
void resetAircraftStatistics()
Reset the statistics.
bool updateOwnSimulatorSelcal(const swift::misc::aviation::CSelcal &selcal, const swift::misc::CIdentifier &originator)
Update own aircraft cockpit (usually from context).
void clearAllRemoteAircraftData()
Clear all aircraft related data, but do not physically remove the aircraft.
bool isPhysicallyRenderedAircraft(const swift::misc::aviation::CCallsign &callsign) const
Is the aircraft rendered (displayed in simulator)? This shall only return true if the aircraft is rea...
void setOwnCallsign(const swift::misc::aviation::CCallsign &callsign)
Own callsign has changed.
bool updateOwnSimulatorCockpit(const swift::misc::simulation::CSimulatedAircraft &aircraft, const swift::misc::CIdentifier &originator)
Update own aircraft cockpit (usually from context).
swift::misc::aviation::CCallsignSet physicallyRenderedAircraft() const
Physically rendered (displayed in simulator) This shall only return aircraft handled in the simulator...
swift::misc::CStatusMessageList getInterpolationMessages(const swift::misc::aviation::CCallsign &callsign) const
Interpolation messages for callsign.
void setFlightNetworkConnected(bool connected)
Flight network has been connected.
bool physicallyAddRemoteAircraft(const swift::misc::simulation::CSimulatedAircraft &newRemoteAircraft)
Add new remote aircraft physically to the simulator.
bool physicallyRemoveRemoteAircraft(const swift::misc::aviation::CCallsign &callsign)
Remove remote aircraft from simulator.
QString getStatisticsSimulatorSpecific() const
Allows to print out simulator specific statistics.
void callbackReceivedRequestedElevation(const swift::misc::geo::CElevationPlane &plane, const swift::misc::aviation::CCallsign &callsign, bool isWater)
A requested elevation has been received.
void displayStatusMessage(const swift::misc::CStatusMessage &message) const
Display a status message in the simulator.
bool disconnectFrom()
Disconnect from simulator.
void displayTextMessage(const swift::misc::network::CTextMessage &message) const
Display a text message.
CSimulatorXPlaneListener(const swift::misc::simulation::CSimulatorPluginInfo &info)
Constructor.
void checkImpl()
Plugin specific implementation to check.
void startImpl()
Plugin specific implementation to start listener.
void stopImpl()
Plugin specific implementation to stop listener.
Class representing a X-Plane multiplayer aircraft.
const swift::misc::simulation::CSimulatedAircraft & getAircraft() const
Simulated aircraft (as added).
Proxy object connected to a real XSwiftBus::CService object via DBus.
void aircraftModelChanged(const QString &path, const QString &filename, const QString &livery, const QString &icao, const QString &modelString, const QString &name, const QString &description)
Own aircraft model changed.
Proxy object connected to a real XSwiftBus::CTraffic object via DBus.
void remoteAircraftAddingFailed(const QString &callsign)
Remote aircraft adding failed.
void remoteAircraftAdded(const QString &callsign)
Remote aircraft successfully added.
Backend services of the swift project, like dealing with the network or the simulators.
Definition actionbind.cpp:7
Free functions in swift::misc.
SWIFT_MISC_EXPORT const QString & boolToYesNo(bool v)
Bool to yes/no.
float blueF() const const
float greenF() const const
float redF() const const
qint64 currentMSecsSinceEpoch()
QDBusConnection connectToPeer(const QString &address, const QString &name)
void disconnectFromBus(const QString &name)
void disconnectFromPeer(const QString &name)
QString name() const const
QDBusConnection sessionBus()
void serviceUnregistered(const QString &serviceName)
void setConnection(const QDBusConnection &connection)
bool cdUp()
bool exists() const const
QString path() const const
qint64 elapsed() const const
bool exists() const const
QList< T >::iterator begin()
QList< T >::const_iterator constBegin() const const
QList< T >::const_iterator constEnd() const const
QList< T >::iterator end()
QList< T >::iterator insert(QList< T >::const_iterator before, QList< T >::parameter_type value)
bool isEmpty() const const
qsizetype size() const const
QObject(QObject *parent)
QMetaObject::Connection connect(const QObject *sender, PointerToMemberFunction signal, Functor functor)
QObject * parent() const const
QString arg(Args &&... args) const const
bool isEmpty() const const
QString left(qsizetype n) &&
QString section(QChar sep, qsizetype start, qsizetype end, QString::SectionFlags flags) const const
qsizetype size() const const
bool startsWith(QChar c, Qt::CaseSensitivity cs) const const
QString toLower() const const
QueuedConnection
void timeout()
void push_back(const swift::misc::aviation::CAircraftSituation &situation)
Push back the latest situation.
void push_back(const swift::misc::aviation::CCallsign &callsign, const swift::misc::aviation::CAircraftParts &parts)
Push back the latest parts.
#define SWIFT_VERIFY_X(COND, WHERE, WHAT)
A weaker kind of assert.
Definition verify.h:26