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 "Airports/airport.hxx"
27 #include "Airports/runways.hxx"
28 #include "Autopilot/route_mgr.hxx"
30 #include <simgear/math/sg_random.h>
31 #include <simgear/sg_inlines.h>
32 #include <simgear/math/sg_geodesy.hxx>
33 #include <simgear/structure/exception.hxx>
37 using namespace flightgear;
40 static const char* makeTTWString(double TTW)
42 if ((TTW <= 0.0) || (TTW >= 356400.5)) { // 99 hours
46 unsigned int TTW_seconds = (int) (TTW + 0.5);
47 unsigned int TTW_minutes = 0;
48 unsigned int TTW_hours = 0;
49 static char TTW_str[9];
50 TTW_hours = TTW_seconds / 3600;
51 TTW_minutes = (TTW_seconds / 60) % 60;
52 TTW_seconds = TTW_seconds % 60;
53 snprintf(TTW_str, 9, "%02d:%02d:%02d",
54 TTW_hours, TTW_minutes, TTW_seconds);
58 ////////////////////////////////////////////////////////////////////////////
59 // configuration helper object
61 GPS::Config::Config() :
62 _enableTurnAnticipation(true),
63 _turnRate(3.0), // degrees-per-second, so 180 degree turn takes 60 seconds
64 _overflightArmDistance(1.0),
65 _waypointAlertTime(30.0),
66 _requireHardSurface(true),
67 _cdiMaxDeflectionNm(3.0), // linear mode, 3nm at the peg
68 _driveAutopilot(true),
69 _courseSelectable(false)
71 _enableTurnAnticipation = false;
74 void GPS::Config::bind(GPS* aOwner, SGPropertyNode* aCfg)
76 aOwner->tie(aCfg, "turn-rate-deg-sec", SGRawValuePointer<double>(&_turnRate));
77 aOwner->tie(aCfg, "turn-anticipation", SGRawValuePointer<bool>(&_enableTurnAnticipation));
78 aOwner->tie(aCfg, "wpt-alert-time", SGRawValuePointer<double>(&_waypointAlertTime));
79 aOwner->tie(aCfg, "hard-surface-runways-only", SGRawValuePointer<bool>(&_requireHardSurface));
80 aOwner->tie(aCfg, "cdi-max-deflection-nm", SGRawValuePointer<double>(&_cdiMaxDeflectionNm));
81 aOwner->tie(aCfg, "drive-autopilot", SGRawValuePointer<bool>(&_driveAutopilot));
82 aOwner->tie(aCfg, "course-selectable", SGRawValuePointer<bool>(&_courseSelectable));
85 ////////////////////////////////////////////////////////////////////////////
87 GPS::GPS ( SGPropertyNode *node, bool defaultGPSMode) :
92 _defaultGPSMode(defaultGPSMode),
94 _name(node->getStringValue("name", "gps")),
95 _num(node->getIntValue("number", 0)),
96 _computeTurnData(false),
97 _anticipateTurn(false),
99 _callbackFlightPlanChanged(SGPropertyChangeCallback<GPS>(this,&GPS::routeManagerFlightPlanChanged,
100 fgGetNode("/autopilot/route-manager/signals/flightplan-changed", true))),
101 _callbackRouteActivated(SGPropertyChangeCallback<GPS>(this,&GPS::routeActivated,
102 fgGetNode("/autopilot/route-manager/active", true)))
104 string branch = "/instrumentation/" + _name;
105 _gpsNode = fgGetNode(branch.c_str(), _num, true );
106 _scratchNode = _gpsNode->getChild("scratch", 0, true);
108 SGPropertyNode *wp_node = _gpsNode->getChild("wp", 0, true);
109 _currentWayptNode = wp_node->getChild("wp", 1, true);
112 _searchIsRoute = false;
113 _searchHasNext = false;
114 _searchType = FGPositioned::INVALID;
125 _magvar_node = fgGetNode("/environment/magnetic-variation-deg", true);
126 _serviceable_node = _gpsNode->getChild("serviceable", 0, true);
127 _serviceable_node->setBoolValue(true);
128 _electrical_node = fgGetNode("/systems/electrical/outputs/gps", true);
131 _raim_node = _gpsNode->getChild("raim", 0, true);
132 _odometer_node = _gpsNode->getChild("odometer", 0, true);
133 _trip_odometer_node = _gpsNode->getChild("trip-odometer", 0, true);
134 _true_bug_error_node = _gpsNode->getChild("true-bug-error-deg", 0, true);
135 _magnetic_bug_error_node = _gpsNode->getChild("magnetic-bug-error-deg", 0, true);
136 _eastWestVelocity = _gpsNode->getChild("ew-velocity-msec", 0, true);
137 _northSouthVelocity = _gpsNode->getChild("ns-velocity-msec", 0, true);
140 // for compatability, alias selected course down to wp/wp[1]/desired-course-deg
141 SGPropertyNode* wp1Crs = _currentWayptNode->getChild("desired-course-deg", 0, true);
142 wp1Crs->alias(_gpsNode->getChild("desired-course-deg", 0, true));
144 _tracking_bug_node = _gpsNode->getChild("tracking-bug", 0, true);
147 // should these move to the route manager?
148 _routeDistanceNm = _gpsNode->getChild("route-distance-nm", 0, true);
149 _routeETE = _gpsNode->getChild("ETE", 0, true);
152 // navradio slaving properties
153 SGPropertyNode* toFlag = _gpsNode->getChild("to-flag", 0, true);
154 toFlag->alias(_currentWayptNode->getChild("to-flag"));
156 SGPropertyNode* fromFlag = _gpsNode->getChild("from-flag", 0, true);
157 fromFlag->alias(_currentWayptNode->getChild("from-flag"));
159 // autopilot drive properties
160 _apDrivingFlag = fgGetNode("/autopilot/settings/gps-driving-true-heading", true);
161 _apTrueHeading = fgGetNode("/autopilot/settings/true-heading-deg",true);
175 _config.bind(this, _gpsNode->getChild("config", 0, true));
178 tie(_gpsNode, "selected-course-deg", SGRawValueMethods<GPS, double>
179 (*this, &GPS::getSelectedCourse, &GPS::setSelectedCourse));
181 tie(_gpsNode, "desired-course-deg", SGRawValueMethods<GPS, double>
182 (*this, &GPS::getDesiredCourse, NULL));
183 _desiredCourseNode = _gpsNode->getChild("desired-course-deg", 0, true);
185 tieSGGeodReadOnly(_gpsNode, _indicated_pos, "indicated-longitude-deg",
186 "indicated-latitude-deg", "indicated-altitude-ft");
188 tie(_gpsNode, "indicated-vertical-speed", SGRawValueMethods<GPS, double>
189 (*this, &GPS::getVerticalSpeed, NULL));
190 tie(_gpsNode, "indicated-track-true-deg", SGRawValueMethods<GPS, double>
191 (*this, &GPS::getTrueTrack, NULL));
192 tie(_gpsNode, "indicated-track-magnetic-deg", SGRawValueMethods<GPS, double>
193 (*this, &GPS::getMagTrack, NULL));
194 tie(_gpsNode, "indicated-ground-speed-kt", SGRawValueMethods<GPS, double>
195 (*this, &GPS::getGroundspeedKts, NULL));
198 tie(_gpsNode, "mode", SGRawValueMethods<GPS, const char*>(*this, &GPS::getMode, NULL));
199 tie(_gpsNode, "command", SGRawValueMethods<GPS, const char*>(*this, &GPS::getCommand, &GPS::setCommand));
200 tieSGGeod(_scratchNode, _scratchPos, "longitude-deg", "latitude-deg", "altitude-ft");
203 tie(_scratchNode, "valid", SGRawValueMethods<GPS, bool>(*this, &GPS::getScratchValid, NULL));
204 tie(_scratchNode, "distance-nm", SGRawValueMethods<GPS, double>(*this, &GPS::getScratchDistance, NULL));
205 tie(_scratchNode, "true-bearing-deg", SGRawValueMethods<GPS, double>(*this, &GPS::getScratchTrueBearing, NULL));
206 tie(_scratchNode, "mag-bearing-deg", SGRawValueMethods<GPS, double>(*this, &GPS::getScratchMagBearing, NULL));
207 tie(_scratchNode, "has-next", SGRawValueMethods<GPS, bool>(*this, &GPS::getScratchHasNext, NULL));
208 _scratchValid = false;
210 _scratchNode->setStringValue("type", "");
211 _scratchNode->setStringValue("query", "");
214 SGPropertyNode *wp_node = _gpsNode->getChild("wp", 0, true);
215 SGPropertyNode* wp0_node = wp_node->getChild("wp", 0, true);
216 tieSGGeodReadOnly(wp0_node, _wp0_position, "longitude-deg", "latitude-deg", "altitude-ft");
217 tie(wp0_node, "ID", SGRawValueMethods<GPS, const char*>
218 (*this, &GPS::getWP0Ident, NULL));
221 tie(_currentWayptNode, "ID", SGRawValueMethods<GPS, const char*>
222 (*this, &GPS::getWP1Ident, NULL));
224 tie(_currentWayptNode, "distance-nm", SGRawValueMethods<GPS, double>
225 (*this, &GPS::getWP1Distance, NULL));
226 tie(_currentWayptNode, "bearing-true-deg", SGRawValueMethods<GPS, double>
227 (*this, &GPS::getWP1Bearing, NULL));
228 tie(_currentWayptNode, "bearing-mag-deg", SGRawValueMethods<GPS, double>
229 (*this, &GPS::getWP1MagBearing, NULL));
230 tie(_currentWayptNode, "TTW-sec", SGRawValueMethods<GPS, double>
231 (*this, &GPS::getWP1TTW, NULL));
232 tie(_currentWayptNode, "TTW", SGRawValueMethods<GPS, const char*>
233 (*this, &GPS::getWP1TTWString, NULL));
235 tie(_currentWayptNode, "course-deviation-deg", SGRawValueMethods<GPS, double>
236 (*this, &GPS::getWP1CourseDeviation, NULL));
237 tie(_currentWayptNode, "course-error-nm", SGRawValueMethods<GPS, double>
238 (*this, &GPS::getWP1CourseErrorNm, NULL));
239 tie(_currentWayptNode, "to-flag", SGRawValueMethods<GPS, bool>
240 (*this, &GPS::getWP1ToFlag, NULL));
241 tie(_currentWayptNode, "from-flag", SGRawValueMethods<GPS, bool>
242 (*this, &GPS::getWP1FromFlag, NULL));
244 // leg properties (only valid in DTO/LEG modes, not OBS)
245 tie(wp_node, "leg-distance-nm", SGRawValueMethods<GPS, double>(*this, &GPS::getLegDistance, NULL));
246 tie(wp_node, "leg-true-course-deg", SGRawValueMethods<GPS, double>(*this, &GPS::getLegCourse, NULL));
247 tie(wp_node, "leg-mag-course-deg", SGRawValueMethods<GPS, double>(*this, &GPS::getLegMagCourse, NULL));
249 // navradio slaving properties
250 tie(_gpsNode, "cdi-deflection", SGRawValueMethods<GPS,double>
251 (*this, &GPS::getCDIDeflection));
257 _tiedProperties.Untie();
264 _last_speed_kts = 0.0;
265 _last_pos = SGGeod();
266 _lastPosValid = false;
267 _indicated_pos = SGGeod();
268 _last_vertical_speed = 0.0;
269 _last_true_track = 0.0;
270 _lastEWVelocity = _lastNSVelocity = 0.0;
271 _currentWaypt = _prevWaypt = NULL;
272 _legDistanceNm = -1.0;
274 _raim_node->setDoubleValue(0.0);
275 _indicated_pos = SGGeod();
276 _odometer_node->setDoubleValue(0);
277 _trip_odometer_node->setDoubleValue(0);
278 _tracking_bug_node->setDoubleValue(0);
279 _true_bug_error_node->setDoubleValue(0);
280 _magnetic_bug_error_node->setDoubleValue(0);
281 _northSouthVelocity->setDoubleValue(0.0);
282 _eastWestVelocity->setDoubleValue(0.0);
286 GPS::update (double delta_time_sec)
288 if (!_defaultGPSMode) {
289 // If it's off, don't bother.
290 // check if value is defined, since many aircraft don't define an output
291 // for the GPS, but expect the default one to work.
292 bool elecOn = !_electrical_node->hasValue() || _electrical_node->getBoolValue();
293 if (!_serviceable_node->getBoolValue() || !elecOn) {
299 if (delta_time_sec <= 0.0) {
300 return; // paused, don't bother
303 _raim_node->setDoubleValue(1.0);
304 _indicated_pos = globals->get_aircraft_position();
305 updateBasicData(delta_time_sec);
308 if (_wayptController.get()) {
309 _wayptController->update();
310 SGGeod p(_wayptController->position());
311 _currentWayptNode->setDoubleValue("longitude-deg", p.getLongitudeDeg());
312 _currentWayptNode->setDoubleValue("latitude-deg", p.getLatitudeDeg());
313 _currentWayptNode->setDoubleValue("altitude-ft", p.getElevationFt());
315 _desiredCourse = getLegMagCourse();
326 if (_dataValid && (_mode == "init")) {
327 // will select LEG mode if the route is active
328 routeManagerFlightPlanChanged(NULL);
330 FGRouteMgr* routeMgr = static_cast<FGRouteMgr*>(globals->get_subsystem("route-manager"));
331 if (!routeMgr->isRouteActive()) {
332 // initialise in OBS mode, with waypt set to the nearest airport.
333 // keep in mind at this point, _dataValid is not set
334 auto_ptr<FGPositioned::Filter> f(new FGAirport::HardSurfaceFilter());
335 FGPositionedRef apt = FGPositioned::findClosest(_indicated_pos, 20.0, f.get());
337 selectOBSMode(new flightgear::NavaidWaypoint(apt, NULL));
343 // allow a realistic delay in the future, here
345 } // of init mode check
347 _last_pos = _indicated_pos;
348 _lastPosValid = !(_last_pos == SGGeod());
351 void GPS::routeManagerFlightPlanChanged(SGPropertyNode*)
354 _route->removeDelegate(this);
357 SG_LOG(SG_INSTR, SG_INFO, "GPS saw route-manager flight-plan replaced.");
358 FGRouteMgr* routeMgr = static_cast<FGRouteMgr*>(globals->get_subsystem("route-manager"));
359 _route = routeMgr->flightPlan();
361 _route->addDelegate(this);
364 if (routeMgr->isRouteActive()) {
367 selectOBSMode(_currentWaypt); // revert to OBS on current waypoint
371 void GPS::routeActivated(SGPropertyNode* aNode)
373 bool isActive = aNode->getBoolValue();
375 SG_LOG(SG_INSTR, SG_INFO, "GPS::route activated, switching to LEG mode");
378 // if we've already passed the current waypoint, sequence.
379 if (_dataValid && getWP1FromFlag()) {
380 SG_LOG(SG_INSTR, SG_INFO, "GPS::route activated, FROM wp1, sequencing");
383 } else if (_mode == "leg") {
384 SG_LOG(SG_INSTR, SG_INFO, "GPS::route deactivated, switching to OBS mode");
385 selectOBSMode(_currentWaypt);
389 ///////////////////////////////////////////////////////////////////////////
390 // implement the RNAV interface
391 SGGeod GPS::position()
397 return _indicated_pos;
400 double GPS::trackDeg()
402 return _last_true_track;
405 double GPS::groundSpeedKts()
407 return _last_speed_kts;
410 double GPS::vspeedFPM()
412 return _last_vertical_speed;
415 double GPS::magvarDeg()
417 return _magvar_node->getDoubleValue();
420 double GPS::overflightArmDistanceM()
422 return _config.overflightArmDistanceNm() * SG_NM_TO_METER;
425 double GPS::selectedMagCourse()
427 return _selectedCourse;
430 ///////////////////////////////////////////////////////////////////////////
433 GPS::updateBasicData(double dt)
435 if (!_lastPosValid) {
441 SGGeodesy::inverse(_last_pos, _indicated_pos, _last_true_track, track2_deg, distance_m );
443 double speed_kt = ((distance_m * SG_METER_TO_NM) * ((1 / dt) * 3600.0));
444 double vertical_speed_mpm = ((_indicated_pos.getElevationM() - _last_pos.getElevationM()) * 60 / dt);
445 _last_vertical_speed = vertical_speed_mpm * SG_METER_TO_FEET;
447 speed_kt = fgGetLowPass(_last_speed_kts, speed_kt, dt/10.0);
448 _last_speed_kts = speed_kt;
450 SGGeod g = _indicated_pos;
451 g.setLongitudeDeg(_last_pos.getLongitudeDeg());
452 double northSouthM = SGGeodesy::distanceM(_last_pos, g);
453 northSouthM = copysign(northSouthM, _indicated_pos.getLatitudeDeg() - _last_pos.getLatitudeDeg());
455 double nsMSec = fgGetLowPass(_lastNSVelocity, northSouthM / dt, dt/2.0);
456 _lastNSVelocity = nsMSec;
457 _northSouthVelocity->setDoubleValue(nsMSec);
461 g.setLatitudeDeg(_last_pos.getLatitudeDeg());
462 double eastWestM = SGGeodesy::distanceM(_last_pos, g);
463 eastWestM = copysign(eastWestM, _indicated_pos.getLongitudeDeg() - _last_pos.getLongitudeDeg());
465 double ewMSec = fgGetLowPass(_lastEWVelocity, eastWestM / dt, dt/2.0);
466 _lastEWVelocity = ewMSec;
467 _eastWestVelocity->setDoubleValue(ewMSec);
469 double odometer = _odometer_node->getDoubleValue();
470 _odometer_node->setDoubleValue(odometer + distance_m * SG_METER_TO_NM);
471 odometer = _trip_odometer_node->getDoubleValue();
472 _trip_odometer_node->setDoubleValue(odometer + distance_m * SG_METER_TO_NM);
480 GPS::updateTrackingBug()
482 double tracking_bug = _tracking_bug_node->getDoubleValue();
483 double true_bug_error = tracking_bug - getTrueTrack();
484 double magnetic_bug_error = tracking_bug - getMagTrack();
486 // Get the errors into the (-180,180) range.
487 SG_NORMALIZE_RANGE(true_bug_error, -180.0, 180.0);
488 SG_NORMALIZE_RANGE(magnetic_bug_error, -180.0, 180.0);
490 _true_bug_error_node->setDoubleValue(true_bug_error);
491 _magnetic_bug_error_node->setDoubleValue(magnetic_bug_error);
494 void GPS::endOfFlightPlan()
496 selectOBSMode(_currentWaypt);
499 void GPS::currentWaypointChanged()
505 int index = _route->currentIndex(),
506 count = _route->numLegs();
507 if ((index < 0) || (index >= count)) {
510 // no active leg on the route
515 _prevWaypt = _route->previousLeg()->waypoint();
516 if (_prevWaypt->flag(WPT_DYNAMIC)) {
517 _wp0_position = _indicated_pos;
519 _wp0_position = _prevWaypt->position();
523 _currentWaypt = _route->currentLeg()->waypoint();
524 _desiredCourse = getLegMagCourse();
525 _desiredCourseNode->fireValueChanged();
530 void GPS::waypointsChanged()
532 if (_mode != "leg") {
536 SG_LOG(SG_INSTR, SG_INFO, "GPS route edited while in LEG mode, updating waypoints");
537 currentWaypointChanged();
542 if (_mode != "leg") {
546 selectOBSMode(_currentWaypt);
555 int nextIndex = _route->currentIndex() + 1;
556 if (nextIndex >= _route->numLegs()) {
557 SG_LOG(SG_INSTR, SG_INFO, "sequenced final leg, end of route");
559 selectOBSMode(_currentWaypt);
563 // will callback into currentWaypointChanged
564 _route->setCurrentIndex(nextIndex);
567 void GPS::updateTurn()
569 bool printProgress = false;
571 if (_computeTurnData) {
572 if (_last_speed_kts < 10) {
573 // need valid leg course and sensible ground speed to compute the turn
578 printProgress = true;
581 if (!_anticipateTurn) {
587 // find bearing to turn centre
588 double bearing, az2, distanceM;
589 SGGeodesy::inverse(_indicated_pos, _turnCentre, bearing, az2, distanceM);
590 double progress = computeTurnProgress(bearing);
593 SG_LOG(SG_INSTR, SG_INFO,"turn progress=" << progress);
596 if (!_inTurn && (progress > 0.0)) {
600 if (_inTurn && !_turnSequenced && (progress > 0.5)) {
601 _turnSequenced = true;
602 SG_LOG(SG_INSTR, SG_INFO, "turn passed midpoint, sequencing");
606 if (_inTurn && (progress >= 1.0)) {
611 // drive deviation and desired course
612 double desiredCourse = bearing - copysign(90, _turnAngle);
613 SG_NORMALIZE_RANGE(desiredCourse, 0.0, 360.0);
614 double deviationNm = (distanceM * SG_METER_TO_NM) - _turnRadius;
615 double deviationDeg = desiredCourse - getMagTrack();
616 deviationNm = copysign(deviationNm, deviationDeg);
618 //_wp1_course_deviation_node->setDoubleValue(deviationDeg);
619 //_wp1_course_error_nm_node->setDoubleValue(deviationNm);
620 //_cdiDeflectionNode->setDoubleValue(deviationDeg);
624 void GPS::updateOverflight()
626 if (!_wayptController->isDone()) {
630 if (_mode == "dto") {
631 SG_LOG(SG_INSTR, SG_INFO, "GPS DTO reached destination point");
633 // check for wp1 being on active route - resume leg mode
635 int index = _route->findWayptIndex(_currentWaypt->position());
637 SG_LOG(SG_INSTR, SG_INFO, "GPS DTO, resuming LEG mode at wp:" << index);
639 _route->setCurrentIndex(index);
640 sequence(); // and sequence to the next point
644 if (_mode == "dto") {
645 // if we didn't enter leg mode, drop back to OBS mode
646 // select OBS mode, but keep current waypoint-as is
650 } else if (_mode == "leg") {
651 SG_LOG(SG_INSTR, SG_DEBUG, "GPS doing overflight sequencing");
653 } else if (_mode == "obs") {
654 // nothing to do here, TO/FROM will update but that's fine
657 _computeTurnData = true;
660 void GPS::beginTurn()
663 _turnSequenced = false;
664 SG_LOG(SG_INSTR, SG_INFO, "beginning turn");
670 SG_LOG(SG_INSTR, SG_INFO, "ending turn");
671 _computeTurnData = true;
674 double GPS::computeTurnProgress(double aBearing) const
676 double startBearing = _turnStartBearing + copysign(90, _turnAngle);
677 return (aBearing - startBearing) / _turnAngle;
680 void GPS::computeTurnData()
682 _computeTurnData = false;
683 if ((_mode != "leg") || !_route->nextLeg()) {
684 _anticipateTurn = false;
688 WayptRef next = _route->nextLeg()->waypoint();
689 if (next->flag(WPT_DYNAMIC) || !_config.turnAnticipationEnabled()) {
690 _anticipateTurn = false;
694 _turnStartBearing = _desiredCourse;
695 // compute next leg course
697 boost::tie(crs, dist) = next->courseAndDistanceFrom(_currentWaypt->position());
700 // compute offset bearing
701 _turnAngle = crs - _turnStartBearing;
702 SG_NORMALIZE_RANGE(_turnAngle, -180.0, 180.0);
703 double median = _turnStartBearing + (_turnAngle * 0.5);
704 double offsetBearing = median + copysign(90, _turnAngle);
705 SG_NORMALIZE_RANGE(offsetBearing, 0.0, 360.0);
707 SG_LOG(SG_INSTR, SG_INFO, "GPS computeTurnData: in=" << _turnStartBearing <<
708 ", out=" << crs << "; turnAngle=" << _turnAngle << ", median=" << median
709 << ", offset=" << offsetBearing);
711 SG_LOG(SG_INSTR, SG_INFO, "next leg is now:" << _currentWaypt->ident() << "->" << next->ident());
713 _turnPt = _currentWaypt->position();
714 _anticipateTurn = true;
717 void GPS::updateTurnData()
719 // depends on ground speed, so needs to be updated per-frame
720 _turnRadius = computeTurnRadiusNm(_last_speed_kts);
722 // compute the turn centre, based on the turn radius.
723 // key thing is to understand that we're working a right-angle triangle,
724 // where the right-angle is the point we start the turn. From that point,
725 // one side is the inbound course to the turn pt, and the other is the
726 // perpendicular line, of length 'r', to the turn centre.
727 // the triangle's hypotenuse, which we need to find, is the distance from the
728 // turn pt to the turn center (in the direction of the offset bearing)
729 // note that d - _turnRadius tell us how much we're 'cutting' the corner.
731 double halfTurnAngle = fabs(_turnAngle * 0.5) * SG_DEGREES_TO_RADIANS;
732 double d = _turnRadius / cos(halfTurnAngle);
734 // SG_LOG(SG_INSTR, SG_INFO, "turnRadius=" << _turnRadius << ", d=" << d
735 // << " (cut distance=" << d - _turnRadius << ")");
737 double median = _turnStartBearing + (_turnAngle * 0.5);
738 double offsetBearing = median + copysign(90, _turnAngle);
739 SG_NORMALIZE_RANGE(offsetBearing, 0.0, 360.0);
742 SGGeodesy::direct(_turnPt, offsetBearing, d * SG_NM_TO_METER, _turnCentre, az2);
745 double GPS::computeTurnRadiusNm(double aGroundSpeedKts) const
747 // turn time is seconds to execute a 360 turn.
748 double turnTime = 360.0 / _config.turnRateDegSec();
750 // c is ground distance covered in that time (circumference of the circle)
751 double c = turnTime * (aGroundSpeedKts / 3600.0); // convert knts to nm/sec
753 // divide by 2PI to go from circumference -> radius
754 return c / (2 * M_PI);
757 void GPS::updateRouteData()
759 double totalDistance = _wayptController->distanceToWayptM() * SG_METER_TO_NM;
760 // walk all waypoints from wp2 to route end, and sum
761 // for (int i=_routeMgr->currentIndex()+1; i<_routeMgr->numWaypts(); ++i) {
762 //totalDistance += _routeMgr->get_waypoint(i).get_distance();
765 _routeDistanceNm->setDoubleValue(totalDistance * SG_METER_TO_NM);
766 if (_last_speed_kts > 1.0) {
767 double TTW = ((totalDistance * SG_METER_TO_NM) / _last_speed_kts) * 3600.0;
768 _routeETE->setStringValue(makeTTWString(TTW));
772 void GPS::driveAutopilot()
774 if (!_config.driveAutopilot() || !_defaultGPSMode) {
775 _apDrivingFlag->setBoolValue(false);
779 // compatability feature - allow the route-manager / GPS to drive the
780 // generic autopilot heading hold *in leg mode only*
782 bool drive = _mode == "leg";
783 _apDrivingFlag->setBoolValue(drive);
786 // FIXME: we want to set desired track, not heading, here
787 _apTrueHeading->setDoubleValue(getWP1Bearing());
791 void GPS::wp1Changed()
795 if (_mode == "leg") {
796 _wayptController.reset(WayptController::createForWaypt(this, _currentWaypt));
797 } else if (_mode == "obs") {
798 _wayptController.reset(new OBSController(this, _currentWaypt));
799 } else if (_mode == "dto") {
800 _wayptController.reset(new DirectToController(this, _currentWaypt, _wp0_position));
803 _wayptController->init();
805 if (_mode == "obs") {
806 _legDistanceNm = -1.0;
808 _wayptController->update();
809 _legDistanceNm = _wayptController->distanceToWayptM() * SG_METER_TO_NM;
813 /////////////////////////////////////////////////////////////////////////////
814 // property getter/setters
816 void GPS::setSelectedCourse(double crs)
818 if (_selectedCourse == crs) {
822 _selectedCourse = crs;
823 if ((_mode == "obs") || _config.courseSelectable()) {
824 _desiredCourse = _selectedCourse;
825 _desiredCourseNode->fireValueChanged();
829 double GPS::getLegDistance() const
831 if (!_dataValid || (_mode == "obs")) {
835 return _legDistanceNm;
838 double GPS::getLegCourse() const
840 if (!_dataValid || !_wayptController.get()) {
844 return _wayptController->targetTrackDeg();
847 double GPS::getLegMagCourse() const
853 double m = getLegCourse() - _magvar_node->getDoubleValue();
854 SG_NORMALIZE_RANGE(m, 0.0, 360.0);
858 double GPS::getMagTrack() const
864 double m = getTrueTrack() - _magvar_node->getDoubleValue();
865 SG_NORMALIZE_RANGE(m, 0.0, 360.0);
869 double GPS::getCDIDeflection() const
876 if (_config.cdiDeflectionIsAngular()) {
877 defl = getWP1CourseDeviation();
878 SG_CLAMP_RANGE(defl, -10.0, 10.0); // as in navradio.cxx
880 double fullScale = _config.cdiDeflectionLinearPeg();
881 double normError = getWP1CourseErrorNm() / fullScale;
882 SG_CLAMP_RANGE(normError, -1.0, 1.0);
883 defl = normError * 10.0; // re-scale to navradio limits, i.e [-10.0 .. 10.0]
889 const char* GPS::getWP0Ident() const
891 if (!_dataValid || (_mode != "leg") || (!_prevWaypt)) {
895 return _prevWaypt->ident().c_str();
898 const char* GPS::getWP0Name() const
903 const char* GPS::getWP1Ident() const
905 if ((!_dataValid)||(!_currentWaypt)) {
909 return _currentWaypt->ident().c_str();
912 const char* GPS::getWP1Name() const
917 double GPS::getWP1Distance() const
919 if (!_dataValid || !_wayptController.get()) {
923 return _wayptController->distanceToWayptM() * SG_METER_TO_NM;
926 double GPS::getWP1TTW() const
928 if (!_dataValid || !_wayptController.get()) {
932 return _wayptController->timeToWaypt();
935 const char* GPS::getWP1TTWString() const
937 double t = getWP1TTW();
942 return makeTTWString(t);
945 double GPS::getWP1Bearing() const
947 if (!_dataValid || !_wayptController.get()) {
951 return _wayptController->trueBearingDeg();
954 double GPS::getWP1MagBearing() const
956 if (!_dataValid || !_wayptController.get()) {
960 double magBearing = _wayptController->trueBearingDeg() - _magvar_node->getDoubleValue();
961 SG_NORMALIZE_RANGE(magBearing, 0.0, 360.0);
965 double GPS::getWP1CourseDeviation() const
967 if (!_dataValid || !_wayptController.get()) {
971 return _wayptController->courseDeviationDeg();
974 double GPS::getWP1CourseErrorNm() const
976 if (!_dataValid || !_wayptController.get()) {
980 return _wayptController->xtrackErrorNm();
983 bool GPS::getWP1ToFlag() const
985 if (!_dataValid || !_wayptController.get()) {
989 return _wayptController->toFlag();
992 bool GPS::getWP1FromFlag() const
994 if (!_dataValid || !_wayptController.get()) {
998 return !getWP1ToFlag();
1002 double GPS::getScratchDistance() const
1004 if (!_scratchValid) {
1008 return SGGeodesy::distanceNm(_indicated_pos, _scratchPos);
1011 double GPS::getScratchTrueBearing() const
1013 if (!_scratchValid) {
1017 return SGGeodesy::courseDeg(_indicated_pos, _scratchPos);
1020 double GPS::getScratchMagBearing() const
1022 if (!_scratchValid) {
1026 double crs = getScratchTrueBearing() - _magvar_node->getDoubleValue();
1027 SG_NORMALIZE_RANGE(crs, 0.0, 360.0);
1033 /////////////////////////////////////////////////////////////////////////////
1036 void GPS::setCommand(const char* aCmd)
1038 SG_LOG(SG_INSTR, SG_DEBUG, "GPS command:" << aCmd);
1040 if (!strcmp(aCmd, "direct")) {
1042 } else if (!strcmp(aCmd, "obs")) {
1043 selectOBSMode(NULL);
1044 } else if (!strcmp(aCmd, "leg")) {
1047 } else if (!strcmp(aCmd, "load-route-wpt")) {
1048 loadRouteWaypoint();
1049 } else if (!strcmp(aCmd, "nearest")) {
1051 } else if (!strcmp(aCmd, "search")) {
1052 _searchNames = false;
1054 } else if (!strcmp(aCmd, "search-names")) {
1055 _searchNames = true;
1057 } else if (!strcmp(aCmd, "next")) {
1059 } else if (!strcmp(aCmd, "previous")) {
1061 } else if (!strcmp(aCmd, "define-user-wpt")) {
1063 } else if (!strcmp(aCmd, "route-insert-before")) {
1064 int index = _scratchNode->getIntValue("index");
1065 if (index < 0 || (_route->numLegs() == 0)) {
1066 index = _route->numLegs();
1067 } else if (index >= _route->numLegs()) {
1068 SG_LOG(SG_INSTR, SG_WARN, "GPS:route-insert-before, bad index:" << index);
1072 insertWaypointAtIndex(index);
1073 } else if (!strcmp(aCmd, "route-insert-after")) {
1074 int index = _scratchNode->getIntValue("index");
1075 if (index < 0 || (_route->numLegs() == 0)) {
1076 index = _route->numLegs();
1077 } else if (index >= _route->numLegs()) {
1078 SG_LOG(SG_INSTR, SG_WARN, "GPS:route-insert-after, bad index:" << index);
1084 insertWaypointAtIndex(index);
1085 } else if (!strcmp(aCmd, "route-delete")) {
1086 int index = _scratchNode->getIntValue("index");
1088 index = _route->numLegs();
1089 } else if (index >= _route->numLegs()) {
1090 SG_LOG(SG_INSTR, SG_WARN, "GPS:route-delete, bad index:" << index);
1094 removeWaypointAtIndex(index);
1097 SG_LOG(SG_INSTR, SG_WARN, "GPS:unrecognized command:" << aCmd);
1101 void GPS::clearScratch()
1103 _scratchPos = SGGeod::fromDegFt(-9999.0, -9999.0, -9999.0);
1104 _scratchNode->setBoolValue("valid", false);
1106 _scratchNode->setStringValue("type", "");
1107 _scratchNode->setStringValue("query", "");
1111 bool GPS::isScratchPositionValid() const
1113 if ((_scratchPos.getLongitudeDeg() < -9990.0) ||
1114 (_scratchPos.getLatitudeDeg() < -9990.0)) {
1121 void GPS::directTo()
1123 if (!isScratchPositionValid()) {
1128 _wp0_position = _indicated_pos;
1129 _currentWaypt = new BasicWaypt(_scratchPos, _scratchNode->getStringValue("ident"), NULL);
1136 void GPS::selectOBSMode(flightgear::Waypt* waypt)
1139 // initialise from scratch
1140 if (!isScratchPositionValid()) {
1144 waypt = new BasicWaypt(_scratchPos, _scratchNode->getStringValue("ident"), NULL);
1148 _currentWaypt = waypt;
1149 _wp0_position = _indicated_pos;
1153 void GPS::selectLegMode()
1155 if (_mode == "leg") {
1160 SG_LOG(SG_INSTR, SG_WARN, "GPS:selectLegMode: no active route");
1165 // depending on the situation, this will either get over-written
1166 // in routeManagerSequenced or not; either way it does no harm to
1168 _wp0_position = _indicated_pos;
1170 // not really sequenced, but does all the work of updating wp0/1
1171 currentWaypointChanged();
1176 void GPS::loadRouteWaypoint()
1178 _scratchValid = false;
1179 int index = _scratchNode->getIntValue("index", -9999);
1182 if ((index < 0) || (index >= _route->numLegs())) { // no index supplied, use current wp
1183 index = _route->currentIndex();
1186 _searchIsRoute = true;
1187 setScratchFromRouteWaypoint(index);
1190 void GPS::setScratchFromRouteWaypoint(int aIndex)
1192 assert(_searchIsRoute);
1193 if ((aIndex < 0) || (aIndex >= _route->numLegs())) {
1194 SG_LOG(SG_INSTR, SG_WARN, "GPS:setScratchFromRouteWaypoint: route-index out of bounds");
1198 _searchResultIndex = aIndex;
1199 WayptRef wp = _route->legAtIndex(aIndex)->waypoint();
1200 _scratchNode->setStringValue("ident", wp->ident());
1201 _scratchPos = wp->position();
1202 _scratchValid = true;
1203 _scratchNode->setIntValue("index", aIndex);
1206 void GPS::loadNearest()
1208 string sty(_scratchNode->getStringValue("type"));
1209 FGPositioned::Type ty = FGPositioned::typeFromName(sty);
1210 if (ty == FGPositioned::INVALID) {
1211 SG_LOG(SG_INSTR, SG_WARN, "GPS:loadNearest: request type is invalid:" << sty);
1215 auto_ptr<FGPositioned::Filter> f(createFilter(ty));
1216 int limitCount = _scratchNode->getIntValue("max-results", 1);
1217 double cutoffDistance = _scratchNode->getDoubleValue("cutoff-nm", 400.0);
1219 SGGeod searchPos = _indicated_pos;
1220 if (isScratchPositionValid()) {
1221 searchPos = _scratchPos;
1224 clearScratch(); // clear now, regardless of whether we find a match or not
1227 FGPositioned::findClosestN(searchPos, limitCount, cutoffDistance, f.get());
1228 _searchResultIndex = 0;
1229 _searchIsRoute = false;
1231 if (_searchResults.empty()) {
1235 setScratchFromCachedSearchResult();
1238 bool GPS::SearchFilter::pass(FGPositioned* aPos) const
1240 switch (aPos->type()) {
1241 case FGPositioned::AIRPORT:
1242 // heliport and seaport too?
1243 case FGPositioned::VOR:
1244 case FGPositioned::NDB:
1245 case FGPositioned::FIX:
1246 case FGPositioned::TACAN:
1247 case FGPositioned::WAYPOINT:
1254 FGPositioned::Type GPS::SearchFilter::minType() const
1256 return FGPositioned::AIRPORT;
1259 FGPositioned::Type GPS::SearchFilter::maxType() const
1261 return FGPositioned::VOR;
1264 FGPositioned::Filter* GPS::createFilter(FGPositioned::Type aTy)
1266 if (aTy == FGPositioned::AIRPORT) {
1267 return new FGAirport::HardSurfaceFilter();
1270 // if we were passed INVALID, assume it means 'all types interesting to a GPS'
1271 if (aTy == FGPositioned::INVALID) {
1272 return new SearchFilter;
1275 return new FGPositioned::TypeFilter(aTy);
1280 // parse search terms into local members, and exec the first search
1281 string sty(_scratchNode->getStringValue("type"));
1282 _searchType = FGPositioned::typeFromName(sty);
1283 _searchQuery = _scratchNode->getStringValue("query");
1284 if (_searchQuery.empty()) {
1285 SG_LOG(SG_INSTR, SG_WARN, "empty GPS search query");
1290 _searchExact = _scratchNode->getBoolValue("exact", true);
1291 _searchResultIndex = 0;
1292 _searchIsRoute = false;
1294 auto_ptr<FGPositioned::Filter> f(createFilter(_searchType));
1296 _searchResults = FGPositioned::findAllWithName(_searchQuery, f.get(), _searchExact);
1298 _searchResults = FGPositioned::findAllWithIdent(_searchQuery, f.get(), _searchExact);
1301 bool orderByRange = _scratchNode->getBoolValue("order-by-distance", true);
1303 FGPositioned::sortByRange(_searchResults, _indicated_pos);
1306 if (_searchResults.empty()) {
1311 setScratchFromCachedSearchResult();
1314 bool GPS::getScratchHasNext() const
1317 if (_searchIsRoute) {
1318 lastResult = _route->numLegs() - 1;
1320 lastResult = (int) _searchResults.size() - 1;
1323 if (lastResult < 0) { // search array might be empty
1327 return (_searchResultIndex < lastResult);
1330 void GPS::setScratchFromCachedSearchResult()
1332 int index = _searchResultIndex;
1334 if ((index < 0) || (index >= (int) _searchResults.size())) {
1335 SG_LOG(SG_INSTR, SG_WARN, "GPS:setScratchFromCachedSearchResult: index out of bounds:" << index);
1339 setScratchFromPositioned(_searchResults[index], index);
1342 void GPS::setScratchFromPositioned(FGPositioned* aPos, int aIndex)
1347 _scratchPos = aPos->geod();
1348 _scratchNode->setStringValue("name", aPos->name());
1349 _scratchNode->setStringValue("ident", aPos->ident());
1350 _scratchNode->setStringValue("type", FGPositioned::nameForType(aPos->type()));
1353 _scratchNode->setIntValue("index", aIndex);
1356 _scratchValid = true;
1357 _scratchNode->setIntValue("result-count", _searchResults.size());
1359 switch (aPos->type()) {
1360 case FGPositioned::VOR:
1361 _scratchNode->setDoubleValue("frequency-mhz", static_cast<FGNavRecord*>(aPos)->get_freq() / 100.0);
1364 case FGPositioned::NDB:
1365 _scratchNode->setDoubleValue("frequency-khz", static_cast<FGNavRecord*>(aPos)->get_freq() / 100.0);
1368 case FGPositioned::AIRPORT:
1369 addAirportToScratch((FGAirport*)aPos);
1377 // look for being on the route and set?
1380 void GPS::addAirportToScratch(FGAirport* aAirport)
1382 for (unsigned int r=0; r<aAirport->numRunways(); ++r) {
1383 SGPropertyNode* rwyNd = _scratchNode->getChild("runways", r, true);
1384 FGRunway* rwy = aAirport->getRunwayByIndex(r);
1385 // TODO - filter out unsuitable runways in the future
1386 // based on config again
1388 rwyNd->setStringValue("id", rwy->ident().c_str());
1389 rwyNd->setIntValue("length-ft", rwy->lengthFt());
1390 rwyNd->setIntValue("width-ft", rwy->widthFt());
1391 rwyNd->setIntValue("heading-deg", rwy->headingDeg());
1392 // map surface code to a string
1393 // TODO - lighting information
1396 rwyNd->setDoubleValue("ils-frequency-mhz", rwy->ILS()->get_freq() / 100.0);
1398 } // of runways iteration
1401 void GPS::nextResult()
1403 if (!getScratchHasNext()) {
1408 if (_searchIsRoute) {
1409 setScratchFromRouteWaypoint(++_searchResultIndex);
1411 ++_searchResultIndex;
1412 setScratchFromCachedSearchResult();
1416 void GPS::previousResult()
1418 if (_searchResultIndex <= 0) {
1423 --_searchResultIndex;
1425 if (_searchIsRoute) {
1426 setScratchFromRouteWaypoint(_searchResultIndex);
1428 setScratchFromCachedSearchResult();
1432 void GPS::defineWaypoint()
1434 if (!isScratchPositionValid()) {
1435 SG_LOG(SG_INSTR, SG_WARN, "GPS:defineWaypoint: invalid lat/lon");
1439 string ident = _scratchNode->getStringValue("ident");
1440 if (ident.size() < 2) {
1441 SG_LOG(SG_INSTR, SG_WARN, "GPS:defineWaypoint: waypoint identifier must be at least two characters");
1445 // check for duplicate idents
1446 FGPositioned::TypeFilter f(FGPositioned::WAYPOINT);
1447 FGPositionedList dups = FGPositioned::findAllWithIdent(ident, &f);
1448 if (!dups.empty()) {
1449 SG_LOG(SG_INSTR, SG_WARN, "GPS:defineWaypoint: non-unique waypoint identifier, ho-hum");
1452 SG_LOG(SG_INSTR, SG_INFO, "GPS:defineWaypoint: creating waypoint:" << ident);
1453 FGPositionedRef wpt = FGPositioned::createUserWaypoint(ident, _scratchPos);
1454 _searchResults.clear();
1455 _searchResults.push_back(wpt);
1456 setScratchFromPositioned(wpt.get(), -1);
1459 void GPS::insertWaypointAtIndex(int aIndex)
1461 // note we do allow index = routeMgr->size(), that's an append
1462 if ((aIndex < 0) || (aIndex > _route->numLegs())) {
1463 throw sg_range_exception("GPS::insertWaypointAtIndex: index out of bounds");
1466 if (!isScratchPositionValid()) {
1467 SG_LOG(SG_INSTR, SG_WARN, "GPS:insertWaypointAtIndex: invalid lat/lon");
1471 string ident = _scratchNode->getStringValue("ident");
1473 WayptRef wpt = new BasicWaypt(_scratchPos, ident, NULL);
1474 _route->insertWayptAtIndex(wpt, aIndex);
1477 void GPS::removeWaypointAtIndex(int aIndex)
1479 if ((aIndex < 0) || (aIndex >= _route->numLegs())) {
1480 throw sg_range_exception("GPS::removeWaypointAtIndex: index out of bounds");
1483 _route->deleteIndex(aIndex);
1487 #endif // of FG_210_COMPAT
1489 void GPS::tieSGGeod(SGPropertyNode* aNode, SGGeod& aRef,
1490 const char* lonStr, const char* latStr, const char* altStr)
1492 tie(aNode, lonStr, SGRawValueMethods<SGGeod, double>(aRef, &SGGeod::getLongitudeDeg, &SGGeod::setLongitudeDeg));
1493 tie(aNode, latStr, SGRawValueMethods<SGGeod, double>(aRef, &SGGeod::getLatitudeDeg, &SGGeod::setLatitudeDeg));
1496 tie(aNode, altStr, SGRawValueMethods<SGGeod, double>(aRef, &SGGeod::getElevationFt, &SGGeod::setElevationFt));
1500 void GPS::tieSGGeodReadOnly(SGPropertyNode* aNode, SGGeod& aRef,
1501 const char* lonStr, const char* latStr, const char* altStr)
1503 tie(aNode, lonStr, SGRawValueMethods<SGGeod, double>(aRef, &SGGeod::getLongitudeDeg, NULL));
1504 tie(aNode, latStr, SGRawValueMethods<SGGeod, double>(aRef, &SGGeod::getLatitudeDeg, NULL));
1507 tie(aNode, altStr, SGRawValueMethods<SGGeod, double>(aRef, &SGGeod::getElevationFt, NULL));