1 // gps.cxx - distance-measuring equipment.
2 // Written by David Megginson, started 2003.
4 // This file is in the Public Domain and comes with no warranty.
12 #include <boost/tuple/tuple.hpp>
19 #include "Main/fg_props.hxx"
20 #include "Main/globals.hxx" // for get_subsystem
21 #include "Main/util.hxx" // for fgLowPass
22 #include "Navaids/positioned.hxx"
23 #include <Navaids/waypoint.hxx>
24 #include "Navaids/navrecord.hxx"
25 #include "Navaids/FlightPlan.hxx"
26 #include <Navaids/routePath.hxx>
28 #include "Airports/airport.hxx"
29 #include "Airports/runways.hxx"
30 #include "Autopilot/route_mgr.hxx"
32 #include <simgear/math/sg_random.h>
33 #include <simgear/sg_inlines.h>
34 #include <simgear/math/sg_geodesy.hxx>
35 #include <simgear/structure/exception.hxx>
39 using namespace flightgear;
42 static const char* makeTTWString(double TTW)
44 if ((TTW <= 0.0) || (TTW >= 356400.5)) { // 99 hours
48 unsigned int TTW_seconds = (int) (TTW + 0.5);
49 unsigned int TTW_minutes = 0;
50 unsigned int TTW_hours = 0;
51 static char TTW_str[9];
52 TTW_hours = TTW_seconds / 3600;
53 TTW_minutes = (TTW_seconds / 60) % 60;
54 TTW_seconds = TTW_seconds % 60;
55 snprintf(TTW_str, 9, "%02d:%02d:%02d",
56 TTW_hours, TTW_minutes, TTW_seconds);
60 ////////////////////////////////////////////////////////////////////////////
61 // configuration helper object
63 GPS::Config::Config() :
64 _enableTurnAnticipation(true),
65 _turnRate(3.0), // degrees-per-second, so 180 degree turn takes 60 seconds
66 _overflightDistance(0.0),
67 _overflightArmDistance(1.0),
68 _overflightArmAngle(90.0),
69 _waypointAlertTime(30.0),
70 _requireHardSurface(true),
71 _cdiMaxDeflectionNm(3.0), // linear mode, 3nm at the peg
72 _driveAutopilot(true),
73 _courseSelectable(false)
75 _enableTurnAnticipation = false;
78 void GPS::Config::bind(GPS* aOwner, SGPropertyNode* aCfg)
80 aOwner->tie(aCfg, "turn-rate-deg-sec", SGRawValuePointer<double>(&_turnRate));
81 aOwner->tie(aCfg, "turn-anticipation", SGRawValuePointer<bool>(&_enableTurnAnticipation));
82 aOwner->tie(aCfg, "wpt-alert-time", SGRawValuePointer<double>(&_waypointAlertTime));
83 aOwner->tie(aCfg, "hard-surface-runways-only", SGRawValuePointer<bool>(&_requireHardSurface));
84 aOwner->tie(aCfg, "cdi-max-deflection-nm", SGRawValuePointer<double>(&_cdiMaxDeflectionNm));
85 aOwner->tie(aCfg, "drive-autopilot", SGRawValuePointer<bool>(&_driveAutopilot));
86 aOwner->tie(aCfg, "course-selectable", SGRawValuePointer<bool>(&_courseSelectable));
87 aOwner->tie(aCfg, "over-flight-distance-nm", SGRawValuePointer<double>(&_overflightDistance));
88 aOwner->tie(aCfg, "over-flight-arm-distance-nm", SGRawValuePointer<double>(&_overflightArmDistance));
89 aOwner->tie(aCfg, "over-flight-arm-angle-deg", SGRawValuePointer<double>(&_overflightArmAngle));
92 ////////////////////////////////////////////////////////////////////////////
94 GPS::GPS ( SGPropertyNode *node, bool defaultGPSMode) :
99 _defaultGPSMode(defaultGPSMode),
101 _name(node->getStringValue("name", "gps")),
102 _num(node->getIntValue("number", 0)),
103 _computeTurnData(false),
104 _anticipateTurn(false),
106 _callbackFlightPlanChanged(SGPropertyChangeCallback<GPS>(this,&GPS::routeManagerFlightPlanChanged,
107 fgGetNode("/autopilot/route-manager/signals/flightplan-changed", true))),
108 _callbackRouteActivated(SGPropertyChangeCallback<GPS>(this,&GPS::routeActivated,
109 fgGetNode("/autopilot/route-manager/active", true)))
111 string branch = "/instrumentation/" + _name;
112 _gpsNode = fgGetNode(branch.c_str(), _num, true );
113 _scratchNode = _gpsNode->getChild("scratch", 0, true);
115 SGPropertyNode *wp_node = _gpsNode->getChild("wp", 0, true);
116 _currentWayptNode = wp_node->getChild("wp", 1, true);
119 _searchIsRoute = false;
120 _searchHasNext = false;
121 _searchType = FGPositioned::INVALID;
132 _magvar_node = fgGetNode("/environment/magnetic-variation-deg", true);
133 _serviceable_node = _gpsNode->getChild("serviceable", 0, true);
134 _serviceable_node->setBoolValue(true);
135 _electrical_node = fgGetNode("/systems/electrical/outputs/gps", true);
138 _raim_node = _gpsNode->getChild("raim", 0, true);
139 _odometer_node = _gpsNode->getChild("odometer", 0, true);
140 _trip_odometer_node = _gpsNode->getChild("trip-odometer", 0, true);
141 _true_bug_error_node = _gpsNode->getChild("true-bug-error-deg", 0, true);
142 _magnetic_bug_error_node = _gpsNode->getChild("magnetic-bug-error-deg", 0, true);
143 _eastWestVelocity = _gpsNode->getChild("ew-velocity-msec", 0, true);
144 _northSouthVelocity = _gpsNode->getChild("ns-velocity-msec", 0, true);
147 // for compatibility, alias selected course down to wp/wp[1]/desired-course-deg
148 SGPropertyNode* wp1Crs = _currentWayptNode->getChild("desired-course-deg", 0, true);
149 wp1Crs->alias(_gpsNode->getChild("desired-course-deg", 0, true));
151 _tracking_bug_node = _gpsNode->getChild("tracking-bug", 0, true);
154 // should these move to the route manager?
155 _routeDistanceNm = _gpsNode->getChild("route-distance-nm", 0, true);
156 _routeETE = _gpsNode->getChild("ETE", 0, true);
159 // navradio slaving properties
160 SGPropertyNode* toFlag = _gpsNode->getChild("to-flag", 0, true);
161 toFlag->alias(_currentWayptNode->getChild("to-flag"));
163 SGPropertyNode* fromFlag = _gpsNode->getChild("from-flag", 0, true);
164 fromFlag->alias(_currentWayptNode->getChild("from-flag"));
166 // autopilot drive properties
167 _apDrivingFlag = fgGetNode("/autopilot/settings/gps-driving-true-heading", true);
168 _apTrueHeading = fgGetNode("/autopilot/settings/true-heading-deg",true);
183 _config.bind(this, _gpsNode->getChild("config", 0, true));
186 tie(_gpsNode, "selected-course-deg", SGRawValueMethods<GPS, double>
187 (*this, &GPS::getSelectedCourse, &GPS::setSelectedCourse));
189 tie(_gpsNode, "desired-course-deg", SGRawValueMethods<GPS, double>
190 (*this, &GPS::getDesiredCourse, NULL));
191 _desiredCourseNode = _gpsNode->getChild("desired-course-deg", 0, true);
193 tieSGGeodReadOnly(_gpsNode, _indicated_pos, "indicated-longitude-deg",
194 "indicated-latitude-deg", "indicated-altitude-ft");
196 tie(_gpsNode, "indicated-vertical-speed", SGRawValueMethods<GPS, double>
197 (*this, &GPS::getVerticalSpeed, NULL));
198 tie(_gpsNode, "indicated-track-true-deg", SGRawValueMethods<GPS, double>
199 (*this, &GPS::getTrueTrack, NULL));
200 tie(_gpsNode, "indicated-track-magnetic-deg", SGRawValueMethods<GPS, double>
201 (*this, &GPS::getMagTrack, NULL));
202 tie(_gpsNode, "indicated-ground-speed-kt", SGRawValueMethods<GPS, double>
203 (*this, &GPS::getGroundspeedKts, NULL));
206 tie(_gpsNode, "mode", SGRawValueMethods<GPS, const char*>(*this, &GPS::getMode, NULL));
207 tie(_gpsNode, "command", SGRawValueMethods<GPS, const char*>(*this, &GPS::getCommand, &GPS::setCommand));
208 tieSGGeod(_scratchNode, _scratchPos, "longitude-deg", "latitude-deg", "altitude-ft");
211 tie(_scratchNode, "valid", SGRawValueMethods<GPS, bool>(*this, &GPS::getScratchValid, NULL));
212 tie(_scratchNode, "distance-nm", SGRawValueMethods<GPS, double>(*this, &GPS::getScratchDistance, NULL));
213 tie(_scratchNode, "true-bearing-deg", SGRawValueMethods<GPS, double>(*this, &GPS::getScratchTrueBearing, NULL));
214 tie(_scratchNode, "mag-bearing-deg", SGRawValueMethods<GPS, double>(*this, &GPS::getScratchMagBearing, NULL));
215 tie(_scratchNode, "has-next", SGRawValueMethods<GPS, bool>(*this, &GPS::getScratchHasNext, NULL));
216 _scratchValid = false;
218 _scratchNode->setStringValue("type", "");
219 _scratchNode->setStringValue("query", "");
222 SGPropertyNode *wp_node = _gpsNode->getChild("wp", 0, true);
223 SGPropertyNode* wp0_node = wp_node->getChild("wp", 0, true);
224 tieSGGeodReadOnly(wp0_node, _wp0_position, "longitude-deg", "latitude-deg", "altitude-ft");
225 tie(wp0_node, "ID", SGRawValueMethods<GPS, const char*>
226 (*this, &GPS::getWP0Ident, NULL));
227 tie(wp0_node, "name", SGRawValueMethods<GPS, const char*>
228 (*this, &GPS::getWP0Name, NULL));
230 tie(_currentWayptNode, "valid", SGRawValueMethods<GPS, bool>
231 (*this, &GPS::getWP1IValid, NULL));
233 tie(_currentWayptNode, "ID", SGRawValueMethods<GPS, const char*>
234 (*this, &GPS::getWP1Ident, NULL));
235 tie(_currentWayptNode, "name", SGRawValueMethods<GPS, const char*>
236 (*this, &GPS::getWP1Name, NULL));
238 tie(_currentWayptNode, "distance-nm", SGRawValueMethods<GPS, double>
239 (*this, &GPS::getWP1Distance, NULL));
240 tie(_currentWayptNode, "bearing-true-deg", SGRawValueMethods<GPS, double>
241 (*this, &GPS::getWP1Bearing, NULL));
242 tie(_currentWayptNode, "bearing-mag-deg", SGRawValueMethods<GPS, double>
243 (*this, &GPS::getWP1MagBearing, NULL));
244 tie(_currentWayptNode, "TTW-sec", SGRawValueMethods<GPS, double>
245 (*this, &GPS::getWP1TTW, NULL));
246 tie(_currentWayptNode, "TTW", SGRawValueMethods<GPS, const char*>
247 (*this, &GPS::getWP1TTWString, NULL));
249 tie(_currentWayptNode, "course-deviation-deg", SGRawValueMethods<GPS, double>
250 (*this, &GPS::getWP1CourseDeviation, NULL));
251 tie(_currentWayptNode, "course-error-nm", SGRawValueMethods<GPS, double>
252 (*this, &GPS::getWP1CourseErrorNm, NULL));
253 tie(_currentWayptNode, "to-flag", SGRawValueMethods<GPS, bool>
254 (*this, &GPS::getWP1ToFlag, NULL));
255 tie(_currentWayptNode, "from-flag", SGRawValueMethods<GPS, bool>
256 (*this, &GPS::getWP1FromFlag, NULL));
258 // leg properties (only valid in DTO/LEG modes, not OBS)
259 tie(wp_node, "leg-distance-nm", SGRawValueMethods<GPS, double>(*this, &GPS::getLegDistance, NULL));
260 tie(wp_node, "leg-true-course-deg", SGRawValueMethods<GPS, double>(*this, &GPS::getLegCourse, NULL));
261 tie(wp_node, "leg-mag-course-deg", SGRawValueMethods<GPS, double>(*this, &GPS::getLegMagCourse, NULL));
263 // navradio slaving properties
264 tie(_gpsNode, "cdi-deflection", SGRawValueMethods<GPS,double>
265 (*this, &GPS::getCDIDeflection));
271 _tiedProperties.Untie();
278 _last_speed_kts = 0.0;
279 _last_pos = SGGeod();
280 _lastPosValid = false;
281 _indicated_pos = SGGeod();
282 _last_vertical_speed = 0.0;
283 _last_true_track = 0.0;
284 _lastEWVelocity = _lastNSVelocity = 0.0;
285 _currentWaypt = _prevWaypt = NULL;
286 _legDistanceNm = -1.0;
288 _raim_node->setDoubleValue(0.0);
289 _indicated_pos = SGGeod();
290 _odometer_node->setDoubleValue(0);
291 _trip_odometer_node->setDoubleValue(0);
292 _tracking_bug_node->setDoubleValue(0);
293 _true_bug_error_node->setDoubleValue(0);
294 _magnetic_bug_error_node->setDoubleValue(0);
295 _northSouthVelocity->setDoubleValue(0.0);
296 _eastWestVelocity->setDoubleValue(0.0);
300 GPS::update (double delta_time_sec)
302 if (!_defaultGPSMode) {
303 // If it's off, don't bother.
304 // check if value is defined, since many aircraft don't define an output
305 // for the GPS, but expect the default one to work.
306 bool elecOn = !_electrical_node->hasValue() || _electrical_node->getBoolValue();
307 if (!_serviceable_node->getBoolValue() || !elecOn) {
313 if (delta_time_sec <= 0.0) {
314 return; // paused, don't bother
317 _raim_node->setDoubleValue(1.0);
318 _indicated_pos = globals->get_aircraft_position();
319 updateBasicData(delta_time_sec);
322 if (_wayptController.get()) {
323 _wayptController->update();
324 SGGeod p(_wayptController->position());
325 _currentWayptNode->setDoubleValue("longitude-deg", p.getLongitudeDeg());
326 _currentWayptNode->setDoubleValue("latitude-deg", p.getLatitudeDeg());
327 _currentWayptNode->setDoubleValue("altitude-ft", p.getElevationFt());
329 _desiredCourse = getLegMagCourse();
340 if (_dataValid && (_mode == "init")) {
341 // will select LEG mode if the route is active
342 routeManagerFlightPlanChanged(NULL);
344 FGRouteMgr* routeMgr = static_cast<FGRouteMgr*>(globals->get_subsystem("route-manager"));
345 if (!routeMgr->isRouteActive()) {
346 // initialise in OBS mode, with waypt set to the nearest airport.
347 // keep in mind at this point, _dataValid is not set
348 auto_ptr<FGPositioned::Filter> f(new FGAirport::HardSurfaceFilter());
349 FGPositionedRef apt = FGPositioned::findClosest(_indicated_pos, 20.0, f.get());
351 selectOBSMode(new flightgear::NavaidWaypoint(apt, NULL));
361 // allow a realistic delay in the future, here
363 } // of init mode check
365 _last_pos = _indicated_pos;
366 _lastPosValid = !(_last_pos == SGGeod());
369 void GPS::routeManagerFlightPlanChanged(SGPropertyNode*)
372 _route->removeDelegate(this);
375 SG_LOG(SG_INSTR, SG_INFO, "GPS saw route-manager flight-plan replaced.");
376 FGRouteMgr* routeMgr = static_cast<FGRouteMgr*>(globals->get_subsystem("route-manager"));
377 _route = routeMgr->flightPlan();
379 _route->addDelegate(this);
382 if (routeMgr->isRouteActive()) {
385 selectOBSMode(_currentWaypt); // revert to OBS on current waypoint
389 void GPS::routeActivated(SGPropertyNode* aNode)
391 bool isActive = aNode->getBoolValue();
393 SG_LOG(SG_INSTR, SG_INFO, "GPS::route activated, switching to LEG mode");
396 // if we've already passed the current waypoint, sequence.
397 if (_dataValid && getWP1FromFlag()) {
398 SG_LOG(SG_INSTR, SG_INFO, "GPS::route activated, FROM wp1, sequencing");
401 } else if (_mode == "leg") {
402 SG_LOG(SG_INSTR, SG_INFO, "GPS::route deactivated, switching to OBS mode");
403 selectOBSMode(_currentWaypt);
407 ///////////////////////////////////////////////////////////////////////////
408 // implement the RNAV interface
409 SGGeod GPS::position()
415 return _indicated_pos;
418 double GPS::trackDeg()
420 return _last_true_track;
423 double GPS::groundSpeedKts()
425 return _last_speed_kts;
428 double GPS::vspeedFPM()
430 return _last_vertical_speed;
433 double GPS::magvarDeg()
435 return _magvar_node->getDoubleValue();
438 double GPS::overflightDistanceM()
440 return _config.overflightDistanceNm() * SG_NM_TO_METER;
443 double GPS::overflightArmDistanceM()
445 return _config.overflightArmDistanceNm() * SG_NM_TO_METER;
448 double GPS::overflightArmAngleDeg()
450 return _config.overflightArmAngleDeg();
453 double GPS::selectedMagCourse()
455 return _selectedCourse;
458 SGGeod GPS::previousLegWaypointPosition(bool& isValid)
460 FlightPlan::Leg* leg = _route->previousLeg();
462 Waypt* waypt = leg->waypoint();
465 return waypt->position();
471 ///////////////////////////////////////////////////////////////////////////
474 GPS::updateBasicData(double dt)
476 if (!_lastPosValid) {
482 SGGeodesy::inverse(_last_pos, _indicated_pos, _last_true_track, track2_deg, distance_m );
484 double speed_kt = ((distance_m * SG_METER_TO_NM) * ((1 / dt) * 3600.0));
485 double vertical_speed_mpm = ((_indicated_pos.getElevationM() - _last_pos.getElevationM()) * 60 / dt);
486 _last_vertical_speed = vertical_speed_mpm * SG_METER_TO_FEET;
488 speed_kt = fgGetLowPass(_last_speed_kts, speed_kt, dt/10.0);
489 _last_speed_kts = speed_kt;
491 SGGeod g = _indicated_pos;
492 g.setLongitudeDeg(_last_pos.getLongitudeDeg());
493 double northSouthM = dist(SGVec3d::fromGeod(_last_pos), SGVec3d::fromGeod(g));
494 northSouthM = copysign(northSouthM, _indicated_pos.getLatitudeDeg() - _last_pos.getLatitudeDeg());
496 double nsMSec = fgGetLowPass(_lastNSVelocity, northSouthM / dt, dt/2.0);
497 _lastNSVelocity = nsMSec;
498 _northSouthVelocity->setDoubleValue(nsMSec);
501 g.setLatitudeDeg(_last_pos.getLatitudeDeg());
502 double eastWestM = dist(SGVec3d::fromGeod(_last_pos), SGVec3d::fromGeod(g));
503 eastWestM = copysign(eastWestM, _indicated_pos.getLongitudeDeg() - _last_pos.getLongitudeDeg());
505 double ewMSec = fgGetLowPass(_lastEWVelocity, eastWestM / dt, dt/2.0);
506 _lastEWVelocity = ewMSec;
507 _eastWestVelocity->setDoubleValue(ewMSec);
509 double odometer = _odometer_node->getDoubleValue();
510 _odometer_node->setDoubleValue(odometer + distance_m * SG_METER_TO_NM);
511 odometer = _trip_odometer_node->getDoubleValue();
512 _trip_odometer_node->setDoubleValue(odometer + distance_m * SG_METER_TO_NM);
520 GPS::updateTrackingBug()
522 double tracking_bug = _tracking_bug_node->getDoubleValue();
523 double true_bug_error = tracking_bug - getTrueTrack();
524 double magnetic_bug_error = tracking_bug - getMagTrack();
526 // Get the errors into the (-180,180) range.
527 SG_NORMALIZE_RANGE(true_bug_error, -180.0, 180.0);
528 SG_NORMALIZE_RANGE(magnetic_bug_error, -180.0, 180.0);
530 _true_bug_error_node->setDoubleValue(true_bug_error);
531 _magnetic_bug_error_node->setDoubleValue(magnetic_bug_error);
534 void GPS::endOfFlightPlan()
536 selectOBSMode(_currentWaypt);
539 void GPS::currentWaypointChanged()
545 int index = _route->currentIndex(),
546 count = _route->numLegs();
547 if ((index < 0) || (index >= count)) {
550 // no active leg on the route
555 _prevWaypt = _route->previousLeg()->waypoint();
556 if (_prevWaypt->flag(WPT_DYNAMIC)) {
557 _wp0_position = _indicated_pos;
559 _wp0_position = _prevWaypt->position();
563 _currentWaypt = _route->currentLeg()->waypoint();
564 _desiredCourse = getLegMagCourse();
565 _desiredCourseNode->fireValueChanged();
570 void GPS::waypointsChanged()
572 if (_mode != "leg") {
576 SG_LOG(SG_INSTR, SG_INFO, "GPS route edited while in LEG mode, updating waypoints");
577 currentWaypointChanged();
582 if (_mode != "leg") {
586 selectOBSMode(_currentWaypt);
595 int nextIndex = _route->currentIndex() + 1;
596 if (nextIndex >= _route->numLegs()) {
597 SG_LOG(SG_INSTR, SG_INFO, "sequenced final leg, end of route");
599 selectOBSMode(_currentWaypt);
603 // will callback into currentWaypointChanged
604 _route->setCurrentIndex(nextIndex);
607 void GPS::updateTurn()
609 bool printProgress = false;
611 if (_computeTurnData) {
612 if (_last_speed_kts < 10) {
613 // need valid leg course and sensible ground speed to compute the turn
618 printProgress = true;
621 if (!_anticipateTurn) {
627 // find bearing to turn centre
628 double bearing, az2, distanceM;
629 SGGeodesy::inverse(_indicated_pos, _turnCentre, bearing, az2, distanceM);
630 double progress = computeTurnProgress(bearing);
633 SG_LOG(SG_INSTR, SG_INFO,"turn progress=" << progress);
636 if (!_inTurn && (progress > 0.0)) {
640 if (_inTurn && !_turnSequenced && (progress > 0.5)) {
641 _turnSequenced = true;
642 SG_LOG(SG_INSTR, SG_INFO, "turn passed midpoint, sequencing");
646 if (_inTurn && (progress >= 1.0)) {
651 // drive deviation and desired course
652 double desiredCourse = bearing - copysign(90, _turnAngle);
653 SG_NORMALIZE_RANGE(desiredCourse, 0.0, 360.0);
654 double deviationNm = (distanceM * SG_METER_TO_NM) - _turnRadius;
655 double deviationDeg = desiredCourse - getMagTrack();
656 deviationNm = copysign(deviationNm, deviationDeg);
658 //_wp1_course_deviation_node->setDoubleValue(deviationDeg);
659 //_wp1_course_error_nm_node->setDoubleValue(deviationNm);
660 //_cdiDeflectionNode->setDoubleValue(deviationDeg);
664 void GPS::updateOverflight()
666 if (!_wayptController->isDone()) {
670 if (_mode == "dto") {
671 SG_LOG(SG_INSTR, SG_INFO, "GPS DTO reached destination point");
673 // check for wp1 being on active route - resume leg mode
675 int index = _route->findWayptIndex(_currentWaypt->position());
677 SG_LOG(SG_INSTR, SG_INFO, "GPS DTO, resuming LEG mode at wp:" << index);
679 _route->setCurrentIndex(index);
680 sequence(); // and sequence to the next point
684 if (_mode == "dto") {
685 // if we didn't enter leg mode, drop back to OBS mode
686 // select OBS mode, but keep current waypoint-as is
690 } else if (_mode == "leg") {
691 SG_LOG(SG_INSTR, SG_DEBUG, "GPS doing overflight sequencing");
693 } else if (_mode == "obs") {
694 // nothing to do here, TO/FROM will update but that's fine
696 _computeTurnData = true;
699 void GPS::beginTurn()
702 _turnSequenced = false;
703 SG_LOG(SG_INSTR, SG_INFO, "beginning turn");
709 SG_LOG(SG_INSTR, SG_INFO, "ending turn");
710 _computeTurnData = true;
713 double GPS::computeTurnProgress(double aBearing) const
715 double startBearing = _turnStartBearing + copysign(90, _turnAngle);
716 return (aBearing - startBearing) / _turnAngle;
719 void GPS::computeTurnData()
721 _computeTurnData = false;
722 if ((_mode != "leg") || !_route->nextLeg()) {
723 _anticipateTurn = false;
727 WayptRef next = _route->nextLeg()->waypoint();
728 if (next->flag(WPT_DYNAMIC) ||
729 !_config.turnAnticipationEnabled() ||
730 next->flag(WPT_OVERFLIGHT))
732 _anticipateTurn = false;
736 _turnStartBearing = _desiredCourse;
737 // compute next leg course
738 RoutePath path(_route);
739 double crs = path.trackForIndex(_route->currentIndex() + 1);
741 // compute offset bearing
742 _turnAngle = crs - _turnStartBearing;
743 SG_NORMALIZE_RANGE(_turnAngle, -180.0, 180.0);
744 double median = _turnStartBearing + (_turnAngle * 0.5);
745 double offsetBearing = median + copysign(90, _turnAngle);
746 SG_NORMALIZE_RANGE(offsetBearing, 0.0, 360.0);
748 SG_LOG(SG_INSTR, SG_INFO, "GPS computeTurnData: in=" << _turnStartBearing <<
749 ", out=" << crs << "; turnAngle=" << _turnAngle << ", median=" << median
750 << ", offset=" << offsetBearing);
752 SG_LOG(SG_INSTR, SG_INFO, "next leg is now:" << _currentWaypt->ident() << "->" << next->ident());
754 _turnPt = _currentWaypt->position();
755 _anticipateTurn = true;
758 void GPS::updateTurnData()
760 // depends on ground speed, so needs to be updated per-frame
761 _turnRadius = computeTurnRadiusNm(_last_speed_kts);
763 // compute the turn centre, based on the turn radius.
764 // key thing is to understand that we're working a right-angle triangle,
765 // where the right-angle is the point we start the turn. From that point,
766 // one side is the inbound course to the turn pt, and the other is the
767 // perpendicular line, of length 'r', to the turn centre.
768 // the triangle's hypotenuse, which we need to find, is the distance from the
769 // turn pt to the turn center (in the direction of the offset bearing)
770 // note that d - _turnRadius tell us how much we're 'cutting' the corner.
772 double halfTurnAngle = fabs(_turnAngle * 0.5) * SG_DEGREES_TO_RADIANS;
773 double d = _turnRadius / cos(halfTurnAngle);
775 // SG_LOG(SG_INSTR, SG_INFO, "turnRadius=" << _turnRadius << ", d=" << d
776 // << " (cut distance=" << d - _turnRadius << ")");
778 double median = _turnStartBearing + (_turnAngle * 0.5);
779 double offsetBearing = median + copysign(90, _turnAngle);
780 SG_NORMALIZE_RANGE(offsetBearing, 0.0, 360.0);
783 SGGeodesy::direct(_turnPt, offsetBearing, d * SG_NM_TO_METER, _turnCentre, az2);
786 double GPS::computeTurnRadiusNm(double aGroundSpeedKts) const
788 // turn time is seconds to execute a 360 turn.
789 double turnTime = 360.0 / _config.turnRateDegSec();
791 // c is ground distance covered in that time (circumference of the circle)
792 double c = turnTime * (aGroundSpeedKts / 3600.0); // convert knts to nm/sec
794 // divide by 2PI to go from circumference -> radius
795 return c / (2 * M_PI);
798 void GPS::updateRouteData()
800 double totalDistance = _wayptController->distanceToWayptM() * SG_METER_TO_NM;
801 // walk all waypoints from wp2 to route end, and sum
802 for (int i=_route->currentIndex()+1; i<_route->numLegs(); ++i) {
803 FlightPlan::Leg* leg = _route->legAtIndex(i);
804 // omit missed-approach waypoints in distance calculation
805 if (leg->waypoint()->flag(WPT_MISS))
808 totalDistance += leg->distanceNm();
811 _routeDistanceNm->setDoubleValue(totalDistance * SG_METER_TO_NM);
812 if (_last_speed_kts > 1.0) {
813 double TTW = ((totalDistance * SG_METER_TO_NM) / _last_speed_kts) * 3600.0;
814 _routeETE->setStringValue(makeTTWString(TTW));
818 void GPS::driveAutopilot()
820 if (!_config.driveAutopilot() || !_defaultGPSMode) {
821 _apDrivingFlag->setBoolValue(false);
825 // compatibility feature - allow the route-manager / GPS to drive the
826 // generic autopilot heading hold *in leg mode only*
828 bool drive = _mode == "leg";
829 _apDrivingFlag->setBoolValue(drive);
832 // FIXME: we want to set desired track, not heading, here
833 _apTrueHeading->setDoubleValue(getWP1Bearing());
837 void GPS::wp1Changed()
841 if (_mode == "leg") {
842 _wayptController.reset(WayptController::createForWaypt(this, _currentWaypt));
843 } else if (_mode == "obs") {
844 _wayptController.reset(new OBSController(this, _currentWaypt));
845 } else if (_mode == "dto") {
846 _wayptController.reset(new DirectToController(this, _currentWaypt, _wp0_position));
849 _wayptController->init();
851 if (_mode == "obs") {
852 _legDistanceNm = -1.0;
854 _wayptController->update();
855 _legDistanceNm = _wayptController->distanceToWayptM() * SG_METER_TO_NM;
859 /////////////////////////////////////////////////////////////////////////////
860 // property getter/setters
862 void GPS::setSelectedCourse(double crs)
864 if (_selectedCourse == crs) {
868 _selectedCourse = crs;
869 if ((_mode == "obs") || _config.courseSelectable()) {
870 _desiredCourse = _selectedCourse;
871 _desiredCourseNode->fireValueChanged();
875 double GPS::getLegDistance() const
877 if (!_dataValid || (_mode == "obs")) {
881 return _legDistanceNm;
884 double GPS::getLegCourse() const
886 if (!_dataValid || !_wayptController.get()) {
890 return _wayptController->targetTrackDeg();
893 double GPS::getLegMagCourse() const
899 double m = getLegCourse() - _magvar_node->getDoubleValue();
900 SG_NORMALIZE_RANGE(m, 0.0, 360.0);
904 double GPS::getMagTrack() const
910 double m = getTrueTrack() - _magvar_node->getDoubleValue();
911 SG_NORMALIZE_RANGE(m, 0.0, 360.0);
915 double GPS::getCDIDeflection() const
922 if (_config.cdiDeflectionIsAngular()) {
923 defl = getWP1CourseDeviation();
924 SG_CLAMP_RANGE(defl, -10.0, 10.0); // as in navradio.cxx
926 double fullScale = _config.cdiDeflectionLinearPeg();
927 double normError = getWP1CourseErrorNm() / fullScale;
928 SG_CLAMP_RANGE(normError, -1.0, 1.0);
929 defl = normError * 10.0; // re-scale to navradio limits, i.e [-10.0 .. 10.0]
935 const char* GPS::getWP0Ident() const
937 if (!_dataValid || (_mode != "leg") || !_prevWaypt) {
941 // work around std::string::c_str() storage lifetime with libc++
942 // real fix is to allow tie-ing with std::string instead of char*
943 static char identBuf[8];
944 strncpy(identBuf, _prevWaypt->ident().c_str(), 8);
949 const char* GPS::getWP0Name() const
951 if (!_dataValid || !_prevWaypt || !_prevWaypt->source()) {
955 return _prevWaypt->source()->name().c_str();
958 bool GPS::getWP1IValid() const
960 return _dataValid && _currentWaypt.get();
963 const char* GPS::getWP1Ident() const
965 if (!_dataValid || !_currentWaypt) {
969 // work around std::string::c_str() storage lifetime with libc++
970 // real fix is to allow tie-ing with std::string instead of char*
971 static char identBuf[8];
972 strncpy(identBuf, _currentWaypt->ident().c_str(), 8);
977 const char* GPS::getWP1Name() const
979 if (!_dataValid || !_currentWaypt || !_currentWaypt->source()) {
983 return _currentWaypt->source()->name().c_str();
986 double GPS::getWP1Distance() const
988 if (!_dataValid || !_wayptController.get()) {
992 return _wayptController->distanceToWayptM() * SG_METER_TO_NM;
995 double GPS::getWP1TTW() const
997 if (!_dataValid || !_wayptController.get()) {
1001 return _wayptController->timeToWaypt();
1004 const char* GPS::getWP1TTWString() const
1006 double t = getWP1TTW();
1011 return makeTTWString(t);
1014 double GPS::getWP1Bearing() const
1016 if (!_dataValid || !_wayptController.get()) {
1020 return _wayptController->trueBearingDeg();
1023 double GPS::getWP1MagBearing() const
1025 if (!_dataValid || !_wayptController.get()) {
1029 double magBearing = _wayptController->trueBearingDeg() - _magvar_node->getDoubleValue();
1030 SG_NORMALIZE_RANGE(magBearing, 0.0, 360.0);
1034 double GPS::getWP1CourseDeviation() const
1036 if (!_dataValid || !_wayptController.get()) {
1040 return _wayptController->courseDeviationDeg();
1043 double GPS::getWP1CourseErrorNm() const
1045 if (!_dataValid || !_wayptController.get()) {
1049 return _wayptController->xtrackErrorNm();
1052 bool GPS::getWP1ToFlag() const
1054 if (!_dataValid || !_wayptController.get()) {
1058 return _wayptController->toFlag();
1061 bool GPS::getWP1FromFlag() const
1063 if (!_dataValid || !_wayptController.get()) {
1067 return !getWP1ToFlag();
1071 double GPS::getScratchDistance() const
1073 if (!_scratchValid) {
1077 return SGGeodesy::distanceNm(_indicated_pos, _scratchPos);
1080 double GPS::getScratchTrueBearing() const
1082 if (!_scratchValid) {
1086 return SGGeodesy::courseDeg(_indicated_pos, _scratchPos);
1089 double GPS::getScratchMagBearing() const
1091 if (!_scratchValid) {
1095 double crs = getScratchTrueBearing() - _magvar_node->getDoubleValue();
1096 SG_NORMALIZE_RANGE(crs, 0.0, 360.0);
1102 /////////////////////////////////////////////////////////////////////////////
1105 void GPS::setCommand(const char* aCmd)
1107 SG_LOG(SG_INSTR, SG_DEBUG, "GPS command:" << aCmd);
1109 if (!strcmp(aCmd, "direct")) {
1111 } else if (!strcmp(aCmd, "obs")) {
1112 selectOBSMode(NULL);
1113 } else if (!strcmp(aCmd, "leg")) {
1116 } else if (!strcmp(aCmd, "load-route-wpt")) {
1117 loadRouteWaypoint();
1118 } else if (!strcmp(aCmd, "nearest")) {
1120 } else if (!strcmp(aCmd, "search")) {
1121 _searchNames = false;
1123 } else if (!strcmp(aCmd, "search-names")) {
1124 _searchNames = true;
1126 } else if (!strcmp(aCmd, "next")) {
1128 } else if (!strcmp(aCmd, "previous")) {
1130 } else if (!strcmp(aCmd, "define-user-wpt")) {
1132 } else if (!strcmp(aCmd, "route-insert-before")) {
1133 int index = _scratchNode->getIntValue("index");
1134 if (index < 0 || (_route->numLegs() == 0)) {
1135 index = _route->numLegs();
1136 } else if (index >= _route->numLegs()) {
1137 SG_LOG(SG_INSTR, SG_WARN, "GPS:route-insert-before, bad index:" << index);
1141 insertWaypointAtIndex(index);
1142 } else if (!strcmp(aCmd, "route-insert-after")) {
1143 int index = _scratchNode->getIntValue("index");
1144 if (index < 0 || (_route->numLegs() == 0)) {
1145 index = _route->numLegs();
1146 } else if (index >= _route->numLegs()) {
1147 SG_LOG(SG_INSTR, SG_WARN, "GPS:route-insert-after, bad index:" << index);
1153 insertWaypointAtIndex(index);
1154 } else if (!strcmp(aCmd, "route-delete")) {
1155 int index = _scratchNode->getIntValue("index");
1157 index = _route->numLegs();
1158 } else if (index >= _route->numLegs()) {
1159 SG_LOG(SG_INSTR, SG_WARN, "GPS:route-delete, bad index:" << index);
1163 removeWaypointAtIndex(index);
1166 SG_LOG(SG_INSTR, SG_WARN, "GPS:unrecognized command:" << aCmd);
1170 void GPS::clearScratch()
1172 _scratchPos = SGGeod::fromDegFt(-9999.0, -9999.0, -9999.0);
1173 _scratchNode->setBoolValue("valid", false);
1175 _scratchNode->setStringValue("type", "");
1176 _scratchNode->setStringValue("query", "");
1180 bool GPS::isScratchPositionValid() const
1182 if ((_scratchPos.getLongitudeDeg() < -9990.0) ||
1183 (_scratchPos.getLatitudeDeg() < -9990.0)) {
1190 FGPositionedRef GPS::positionedFromScratch() const
1192 if (!isScratchPositionValid()) {
1196 std::string ident(_scratchNode->getStringValue("ident"));
1197 return FGPositioned::findClosestWithIdent(ident, _scratchPos);
1200 void GPS::directTo()
1202 if (!isScratchPositionValid()) {
1207 _wp0_position = _indicated_pos;
1209 FGPositionedRef pos = positionedFromScratch();
1211 _currentWaypt = new NavaidWaypoint(pos, NULL);
1213 _currentWaypt = new BasicWaypt(_scratchPos, _scratchNode->getStringValue("ident"), NULL);
1220 void GPS::selectOBSMode(flightgear::Waypt* waypt)
1222 if (!waypt && isScratchPositionValid()) {
1223 FGPositionedRef pos = positionedFromScratch();
1225 waypt = new NavaidWaypoint(pos, NULL);
1227 waypt = new BasicWaypt(_scratchPos, _scratchNode->getStringValue("ident"), NULL);
1233 _wp0_position = _indicated_pos;
1234 _currentWaypt = waypt;
1238 void GPS::selectLegMode()
1240 if (_mode == "leg") {
1245 SG_LOG(SG_INSTR, SG_WARN, "GPS:selectLegMode: no active route");
1251 // depending on the situation, this will either get over-written
1252 // in routeManagerSequenced or not; either way it does no harm to
1254 _wp0_position = _indicated_pos;
1256 // not really sequenced, but does all the work of updating wp0/1
1257 currentWaypointChanged();
1262 void GPS::loadRouteWaypoint()
1264 _scratchValid = false;
1265 int index = _scratchNode->getIntValue("index", -9999);
1268 if ((index < 0) || (index >= _route->numLegs())) { // no index supplied, use current wp
1269 index = _route->currentIndex();
1272 _searchIsRoute = true;
1273 setScratchFromRouteWaypoint(index);
1276 void GPS::setScratchFromRouteWaypoint(int aIndex)
1278 assert(_searchIsRoute);
1279 if ((aIndex < 0) || (aIndex >= _route->numLegs())) {
1280 SG_LOG(SG_INSTR, SG_WARN, "GPS:setScratchFromRouteWaypoint: route-index out of bounds");
1284 _searchResultIndex = aIndex;
1285 WayptRef wp = _route->legAtIndex(aIndex)->waypoint();
1286 _scratchNode->setStringValue("ident", wp->ident());
1287 _scratchPos = wp->position();
1288 _scratchValid = true;
1289 _scratchNode->setIntValue("index", aIndex);
1292 void GPS::loadNearest()
1294 string sty(_scratchNode->getStringValue("type"));
1295 FGPositioned::Type ty = FGPositioned::typeFromName(sty);
1296 if (ty == FGPositioned::INVALID) {
1297 SG_LOG(SG_INSTR, SG_WARN, "GPS:loadNearest: request type is invalid:" << sty);
1301 auto_ptr<FGPositioned::Filter> f(createFilter(ty));
1302 int limitCount = _scratchNode->getIntValue("max-results", 1);
1303 double cutoffDistance = _scratchNode->getDoubleValue("cutoff-nm", 400.0);
1305 SGGeod searchPos = _indicated_pos;
1306 if (isScratchPositionValid()) {
1307 searchPos = _scratchPos;
1310 clearScratch(); // clear now, regardless of whether we find a match or not
1313 FGPositioned::findClosestN(searchPos, limitCount, cutoffDistance, f.get());
1314 _searchResultIndex = 0;
1315 _searchIsRoute = false;
1317 if (_searchResults.empty()) {
1321 setScratchFromCachedSearchResult();
1324 bool GPS::SearchFilter::pass(FGPositioned* aPos) const
1326 switch (aPos->type()) {
1327 case FGPositioned::AIRPORT:
1328 // heliport and seaport too?
1329 case FGPositioned::VOR:
1330 case FGPositioned::NDB:
1331 case FGPositioned::FIX:
1332 case FGPositioned::TACAN:
1333 case FGPositioned::WAYPOINT:
1340 FGPositioned::Type GPS::SearchFilter::minType() const
1342 return FGPositioned::AIRPORT;
1345 FGPositioned::Type GPS::SearchFilter::maxType() const
1347 return FGPositioned::VOR;
1350 FGPositioned::Filter* GPS::createFilter(FGPositioned::Type aTy)
1352 if (aTy == FGPositioned::AIRPORT) {
1353 return new FGAirport::HardSurfaceFilter();
1356 // if we were passed INVALID, assume it means 'all types interesting to a GPS'
1357 if (aTy == FGPositioned::INVALID) {
1358 return new SearchFilter;
1361 return new FGPositioned::TypeFilter(aTy);
1366 // parse search terms into local members, and exec the first search
1367 string sty(_scratchNode->getStringValue("type"));
1368 _searchType = FGPositioned::typeFromName(sty);
1369 _searchQuery = _scratchNode->getStringValue("query");
1370 if (_searchQuery.empty()) {
1371 SG_LOG(SG_INSTR, SG_WARN, "empty GPS search query");
1376 _searchExact = _scratchNode->getBoolValue("exact", true);
1377 _searchResultIndex = 0;
1378 _searchIsRoute = false;
1380 auto_ptr<FGPositioned::Filter> f(createFilter(_searchType));
1382 _searchResults = FGPositioned::findAllWithName(_searchQuery, f.get(), _searchExact);
1384 _searchResults = FGPositioned::findAllWithIdent(_searchQuery, f.get(), _searchExact);
1387 bool orderByRange = _scratchNode->getBoolValue("order-by-distance", true);
1389 FGPositioned::sortByRange(_searchResults, _indicated_pos);
1392 if (_searchResults.empty()) {
1397 setScratchFromCachedSearchResult();
1400 bool GPS::getScratchHasNext() const
1403 if (_searchIsRoute) {
1404 lastResult = _route->numLegs() - 1;
1406 lastResult = (int) _searchResults.size() - 1;
1409 if (lastResult < 0) { // search array might be empty
1413 return (_searchResultIndex < lastResult);
1416 void GPS::setScratchFromCachedSearchResult()
1418 int index = _searchResultIndex;
1420 if ((index < 0) || (index >= (int) _searchResults.size())) {
1421 SG_LOG(SG_INSTR, SG_WARN, "GPS:setScratchFromCachedSearchResult: index out of bounds:" << index);
1425 setScratchFromPositioned(_searchResults[index], index);
1428 void GPS::setScratchFromPositioned(FGPositioned* aPos, int aIndex)
1433 _scratchPos = aPos->geod();
1434 _scratchNode->setStringValue("name", aPos->name());
1435 _scratchNode->setStringValue("ident", aPos->ident());
1436 _scratchNode->setStringValue("type", FGPositioned::nameForType(aPos->type()));
1439 _scratchNode->setIntValue("index", aIndex);
1442 _scratchValid = true;
1443 _scratchNode->setIntValue("result-count", _searchResults.size());
1445 switch (aPos->type()) {
1446 case FGPositioned::VOR:
1447 _scratchNode->setDoubleValue("frequency-mhz", static_cast<FGNavRecord*>(aPos)->get_freq() / 100.0);
1450 case FGPositioned::NDB:
1451 _scratchNode->setDoubleValue("frequency-khz", static_cast<FGNavRecord*>(aPos)->get_freq() / 100.0);
1454 case FGPositioned::AIRPORT:
1455 addAirportToScratch((FGAirport*)aPos);
1463 // look for being on the route and set?
1466 void GPS::addAirportToScratch(FGAirport* aAirport)
1468 for (unsigned int r=0; r<aAirport->numRunways(); ++r) {
1469 SGPropertyNode* rwyNd = _scratchNode->getChild("runways", r, true);
1470 FGRunway* rwy = aAirport->getRunwayByIndex(r);
1471 // TODO - filter out unsuitable runways in the future
1472 // based on config again
1474 rwyNd->setStringValue("id", rwy->ident().c_str());
1475 rwyNd->setIntValue("length-ft", rwy->lengthFt());
1476 rwyNd->setIntValue("width-ft", rwy->widthFt());
1477 rwyNd->setIntValue("heading-deg", rwy->headingDeg());
1478 // map surface code to a string
1479 // TODO - lighting information
1482 rwyNd->setDoubleValue("ils-frequency-mhz", rwy->ILS()->get_freq() / 100.0);
1484 } // of runways iteration
1487 void GPS::nextResult()
1489 if (!getScratchHasNext()) {
1494 if (_searchIsRoute) {
1495 setScratchFromRouteWaypoint(++_searchResultIndex);
1497 ++_searchResultIndex;
1498 setScratchFromCachedSearchResult();
1502 void GPS::previousResult()
1504 if (_searchResultIndex <= 0) {
1509 --_searchResultIndex;
1511 if (_searchIsRoute) {
1512 setScratchFromRouteWaypoint(_searchResultIndex);
1514 setScratchFromCachedSearchResult();
1518 void GPS::defineWaypoint()
1520 if (!isScratchPositionValid()) {
1521 SG_LOG(SG_INSTR, SG_WARN, "GPS:defineWaypoint: invalid lat/lon");
1525 string ident = _scratchNode->getStringValue("ident");
1526 if (ident.size() < 2) {
1527 SG_LOG(SG_INSTR, SG_WARN, "GPS:defineWaypoint: waypoint identifier must be at least two characters");
1531 // check for duplicate idents
1532 FGPositioned::TypeFilter f(FGPositioned::WAYPOINT);
1533 FGPositionedList dups = FGPositioned::findAllWithIdent(ident, &f);
1534 if (!dups.empty()) {
1535 SG_LOG(SG_INSTR, SG_WARN, "GPS:defineWaypoint: non-unique waypoint identifier, ho-hum");
1538 SG_LOG(SG_INSTR, SG_INFO, "GPS:defineWaypoint: creating waypoint:" << ident);
1539 FGPositionedRef wpt = FGPositioned::createUserWaypoint(ident, _scratchPos);
1540 _searchResults.clear();
1541 _searchResults.push_back(wpt);
1542 setScratchFromPositioned(wpt.get(), -1);
1545 void GPS::insertWaypointAtIndex(int aIndex)
1547 // note we do allow index = routeMgr->size(), that's an append
1548 if ((aIndex < 0) || (aIndex > _route->numLegs())) {
1549 throw sg_range_exception("GPS::insertWaypointAtIndex: index out of bounds");
1552 if (!isScratchPositionValid()) {
1553 SG_LOG(SG_INSTR, SG_WARN, "GPS:insertWaypointAtIndex: invalid lat/lon");
1557 string ident = _scratchNode->getStringValue("ident");
1559 WayptRef wpt = new BasicWaypt(_scratchPos, ident, NULL);
1560 _route->insertWayptAtIndex(wpt, aIndex);
1563 void GPS::removeWaypointAtIndex(int aIndex)
1565 if ((aIndex < 0) || (aIndex >= _route->numLegs())) {
1566 throw sg_range_exception("GPS::removeWaypointAtIndex: index out of bounds");
1569 _route->deleteIndex(aIndex);
1573 #endif // of FG_210_COMPAT
1575 void GPS::tieSGGeod(SGPropertyNode* aNode, SGGeod& aRef,
1576 const char* lonStr, const char* latStr, const char* altStr)
1578 tie(aNode, lonStr, SGRawValueMethods<SGGeod, double>(aRef, &SGGeod::getLongitudeDeg, &SGGeod::setLongitudeDeg));
1579 tie(aNode, latStr, SGRawValueMethods<SGGeod, double>(aRef, &SGGeod::getLatitudeDeg, &SGGeod::setLatitudeDeg));
1582 tie(aNode, altStr, SGRawValueMethods<SGGeod, double>(aRef, &SGGeod::getElevationFt, &SGGeod::setElevationFt));
1586 void GPS::tieSGGeodReadOnly(SGPropertyNode* aNode, SGGeod& aRef,
1587 const char* lonStr, const char* latStr, const char* altStr)
1589 tie(aNode, lonStr, SGRawValueMethods<SGGeod, double>(aRef, &SGGeod::getLongitudeDeg, NULL));
1590 tie(aNode, latStr, SGRawValueMethods<SGGeod, double>(aRef, &SGGeod::getLatitudeDeg, NULL));
1593 tie(aNode, altStr, SGRawValueMethods<SGGeod, double>(aRef, &SGGeod::getElevationFt, NULL));