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 if (!_serviceable_node->getBoolValue() || !_electrical_node->getBoolValue()) {
296 if (delta_time_sec <= 0.0) {
297 return; // paused, don't bother
300 _raim_node->setDoubleValue(1.0);
301 _indicated_pos = globals->get_aircraft_position();
302 updateBasicData(delta_time_sec);
305 if (_wayptController.get()) {
306 _wayptController->update();
307 SGGeod p(_wayptController->position());
308 _currentWayptNode->setDoubleValue("longitude-deg", p.getLongitudeDeg());
309 _currentWayptNode->setDoubleValue("latitude-deg", p.getLatitudeDeg());
310 _currentWayptNode->setDoubleValue("altitude-ft", p.getElevationFt());
312 _desiredCourse = getLegMagCourse();
323 if (_dataValid && (_mode == "init")) {
324 // will select LEG mode if the route is active
325 routeManagerFlightPlanChanged(NULL);
327 FGRouteMgr* routeMgr = static_cast<FGRouteMgr*>(globals->get_subsystem("route-manager"));
328 if (!routeMgr->isRouteActive()) {
329 // initialise in OBS mode, with waypt set to the nearest airport.
330 // keep in mind at this point, _dataValid is not set
331 auto_ptr<FGPositioned::Filter> f(new FGAirport::HardSurfaceFilter());
332 FGPositionedRef apt = FGPositioned::findClosest(_indicated_pos, 20.0, f.get());
334 selectOBSMode(new flightgear::NavaidWaypoint(apt, NULL));
340 // allow a realistic delay in the future, here
342 } // of init mode check
344 _last_pos = _indicated_pos;
345 _lastPosValid = !(_last_pos == SGGeod());
348 void GPS::routeManagerFlightPlanChanged(SGPropertyNode*)
351 _route->removeDelegate(this);
354 SG_LOG(SG_INSTR, SG_INFO, "GPS saw route-manager flight-plan replaced.");
355 FGRouteMgr* routeMgr = static_cast<FGRouteMgr*>(globals->get_subsystem("route-manager"));
356 _route = routeMgr->flightPlan();
358 _route->addDelegate(this);
361 if (routeMgr->isRouteActive()) {
364 selectOBSMode(_currentWaypt); // revert to OBS on current waypoint
368 void GPS::routeActivated(SGPropertyNode* aNode)
370 bool isActive = aNode->getBoolValue();
372 SG_LOG(SG_INSTR, SG_INFO, "GPS::route activated, switching to LEG mode");
375 // if we've already passed the current waypoint, sequence.
376 if (_dataValid && getWP1FromFlag()) {
377 SG_LOG(SG_INSTR, SG_INFO, "GPS::route activated, FROM wp1, sequencing");
380 } else if (_mode == "leg") {
381 SG_LOG(SG_INSTR, SG_INFO, "GPS::route deactivated, switching to OBS mode");
382 selectOBSMode(_currentWaypt);
386 ///////////////////////////////////////////////////////////////////////////
387 // implement the RNAV interface
388 SGGeod GPS::position()
394 return _indicated_pos;
397 double GPS::trackDeg()
399 return _last_true_track;
402 double GPS::groundSpeedKts()
404 return _last_speed_kts;
407 double GPS::vspeedFPM()
409 return _last_vertical_speed;
412 double GPS::magvarDeg()
414 return _magvar_node->getDoubleValue();
417 double GPS::overflightArmDistanceM()
419 return _config.overflightArmDistanceNm() * SG_NM_TO_METER;
422 double GPS::selectedMagCourse()
424 return _selectedCourse;
427 ///////////////////////////////////////////////////////////////////////////
430 GPS::updateBasicData(double dt)
432 if (!_lastPosValid) {
438 SGGeodesy::inverse(_last_pos, _indicated_pos, _last_true_track, track2_deg, distance_m );
440 double speed_kt = ((distance_m * SG_METER_TO_NM) * ((1 / dt) * 3600.0));
441 double vertical_speed_mpm = ((_indicated_pos.getElevationM() - _last_pos.getElevationM()) * 60 / dt);
442 _last_vertical_speed = vertical_speed_mpm * SG_METER_TO_FEET;
444 speed_kt = fgGetLowPass(_last_speed_kts, speed_kt, dt/10.0);
445 _last_speed_kts = speed_kt;
447 SGGeod g = _indicated_pos;
448 g.setLongitudeDeg(_last_pos.getLongitudeDeg());
449 double northSouthM = SGGeodesy::distanceM(_last_pos, g);
450 northSouthM = copysign(northSouthM, _indicated_pos.getLatitudeDeg() - _last_pos.getLatitudeDeg());
452 double nsMSec = fgGetLowPass(_lastNSVelocity, northSouthM / dt, dt/2.0);
453 _lastNSVelocity = nsMSec;
454 _northSouthVelocity->setDoubleValue(nsMSec);
458 g.setLatitudeDeg(_last_pos.getLatitudeDeg());
459 double eastWestM = SGGeodesy::distanceM(_last_pos, g);
460 eastWestM = copysign(eastWestM, _indicated_pos.getLongitudeDeg() - _last_pos.getLongitudeDeg());
462 double ewMSec = fgGetLowPass(_lastEWVelocity, eastWestM / dt, dt/2.0);
463 _lastEWVelocity = ewMSec;
464 _eastWestVelocity->setDoubleValue(ewMSec);
466 double odometer = _odometer_node->getDoubleValue();
467 _odometer_node->setDoubleValue(odometer + distance_m * SG_METER_TO_NM);
468 odometer = _trip_odometer_node->getDoubleValue();
469 _trip_odometer_node->setDoubleValue(odometer + distance_m * SG_METER_TO_NM);
477 GPS::updateTrackingBug()
479 double tracking_bug = _tracking_bug_node->getDoubleValue();
480 double true_bug_error = tracking_bug - getTrueTrack();
481 double magnetic_bug_error = tracking_bug - getMagTrack();
483 // Get the errors into the (-180,180) range.
484 SG_NORMALIZE_RANGE(true_bug_error, -180.0, 180.0);
485 SG_NORMALIZE_RANGE(magnetic_bug_error, -180.0, 180.0);
487 _true_bug_error_node->setDoubleValue(true_bug_error);
488 _magnetic_bug_error_node->setDoubleValue(magnetic_bug_error);
491 void GPS::endOfFlightPlan()
493 selectOBSMode(_currentWaypt);
496 void GPS::currentWaypointChanged()
502 int index = _route->currentIndex(),
503 count = _route->numLegs();
504 if ((index < 0) || (index >= count)) {
507 // no active leg on the route
512 _prevWaypt = _route->previousLeg()->waypoint();
513 if (_prevWaypt->flag(WPT_DYNAMIC)) {
514 _wp0_position = _indicated_pos;
516 _wp0_position = _prevWaypt->position();
520 _currentWaypt = _route->currentLeg()->waypoint();
521 _desiredCourse = getLegMagCourse();
522 _desiredCourseNode->fireValueChanged();
527 void GPS::waypointsChanged()
529 if (_mode != "leg") {
533 SG_LOG(SG_INSTR, SG_INFO, "GPS route edited while in LEG mode, updating waypoints");
534 currentWaypointChanged();
539 if (_mode != "leg") {
543 selectOBSMode(_currentWaypt);
552 int nextIndex = _route->currentIndex() + 1;
553 if (nextIndex >= _route->numLegs()) {
554 SG_LOG(SG_INSTR, SG_INFO, "sequenced final leg, end of route");
556 selectOBSMode(_currentWaypt);
560 // will callback into currentWaypointChanged
561 _route->setCurrentIndex(nextIndex);
564 void GPS::updateTurn()
566 bool printProgress = false;
568 if (_computeTurnData) {
569 if (_last_speed_kts < 10) {
570 // need valid leg course and sensible ground speed to compute the turn
575 printProgress = true;
578 if (!_anticipateTurn) {
584 // find bearing to turn centre
585 double bearing, az2, distanceM;
586 SGGeodesy::inverse(_indicated_pos, _turnCentre, bearing, az2, distanceM);
587 double progress = computeTurnProgress(bearing);
590 SG_LOG(SG_INSTR, SG_INFO,"turn progress=" << progress);
593 if (!_inTurn && (progress > 0.0)) {
597 if (_inTurn && !_turnSequenced && (progress > 0.5)) {
598 _turnSequenced = true;
599 SG_LOG(SG_INSTR, SG_INFO, "turn passed midpoint, sequencing");
603 if (_inTurn && (progress >= 1.0)) {
608 // drive deviation and desired course
609 double desiredCourse = bearing - copysign(90, _turnAngle);
610 SG_NORMALIZE_RANGE(desiredCourse, 0.0, 360.0);
611 double deviationNm = (distanceM * SG_METER_TO_NM) - _turnRadius;
612 double deviationDeg = desiredCourse - getMagTrack();
613 deviationNm = copysign(deviationNm, deviationDeg);
615 //_wp1_course_deviation_node->setDoubleValue(deviationDeg);
616 //_wp1_course_error_nm_node->setDoubleValue(deviationNm);
617 //_cdiDeflectionNode->setDoubleValue(deviationDeg);
621 void GPS::updateOverflight()
623 if (!_wayptController->isDone()) {
627 if (_mode == "dto") {
628 SG_LOG(SG_INSTR, SG_INFO, "GPS DTO reached destination point");
630 // check for wp1 being on active route - resume leg mode
632 int index = _route->findWayptIndex(_currentWaypt->position());
634 SG_LOG(SG_INSTR, SG_INFO, "GPS DTO, resuming LEG mode at wp:" << index);
636 _route->setCurrentIndex(index);
637 sequence(); // and sequence to the next point
641 if (_mode == "dto") {
642 // if we didn't enter leg mode, drop back to OBS mode
643 // select OBS mode, but keep current waypoint-as is
647 } else if (_mode == "leg") {
648 SG_LOG(SG_INSTR, SG_DEBUG, "GPS doing overflight sequencing");
650 } else if (_mode == "obs") {
651 // nothing to do here, TO/FROM will update but that's fine
654 _computeTurnData = true;
657 void GPS::beginTurn()
660 _turnSequenced = false;
661 SG_LOG(SG_INSTR, SG_INFO, "beginning turn");
667 SG_LOG(SG_INSTR, SG_INFO, "ending turn");
668 _computeTurnData = true;
671 double GPS::computeTurnProgress(double aBearing) const
673 double startBearing = _turnStartBearing + copysign(90, _turnAngle);
674 return (aBearing - startBearing) / _turnAngle;
677 void GPS::computeTurnData()
679 _computeTurnData = false;
680 if ((_mode != "leg") || !_route->nextLeg()) {
681 _anticipateTurn = false;
685 WayptRef next = _route->nextLeg()->waypoint();
686 if (next->flag(WPT_DYNAMIC) || !_config.turnAnticipationEnabled()) {
687 _anticipateTurn = false;
691 _turnStartBearing = _desiredCourse;
692 // compute next leg course
694 boost::tie(crs, dist) = next->courseAndDistanceFrom(_currentWaypt->position());
697 // compute offset bearing
698 _turnAngle = crs - _turnStartBearing;
699 SG_NORMALIZE_RANGE(_turnAngle, -180.0, 180.0);
700 double median = _turnStartBearing + (_turnAngle * 0.5);
701 double offsetBearing = median + copysign(90, _turnAngle);
702 SG_NORMALIZE_RANGE(offsetBearing, 0.0, 360.0);
704 SG_LOG(SG_INSTR, SG_INFO, "GPS computeTurnData: in=" << _turnStartBearing <<
705 ", out=" << crs << "; turnAngle=" << _turnAngle << ", median=" << median
706 << ", offset=" << offsetBearing);
708 SG_LOG(SG_INSTR, SG_INFO, "next leg is now:" << _currentWaypt->ident() << "->" << next->ident());
710 _turnPt = _currentWaypt->position();
711 _anticipateTurn = true;
714 void GPS::updateTurnData()
716 // depends on ground speed, so needs to be updated per-frame
717 _turnRadius = computeTurnRadiusNm(_last_speed_kts);
719 // compute the turn centre, based on the turn radius.
720 // key thing is to understand that we're working a right-angle triangle,
721 // where the right-angle is the point we start the turn. From that point,
722 // one side is the inbound course to the turn pt, and the other is the
723 // perpendicular line, of length 'r', to the turn centre.
724 // the triangle's hypotenuse, which we need to find, is the distance from the
725 // turn pt to the turn center (in the direction of the offset bearing)
726 // note that d - _turnRadius tell us how much we're 'cutting' the corner.
728 double halfTurnAngle = fabs(_turnAngle * 0.5) * SG_DEGREES_TO_RADIANS;
729 double d = _turnRadius / cos(halfTurnAngle);
731 // SG_LOG(SG_INSTR, SG_INFO, "turnRadius=" << _turnRadius << ", d=" << d
732 // << " (cut distance=" << d - _turnRadius << ")");
734 double median = _turnStartBearing + (_turnAngle * 0.5);
735 double offsetBearing = median + copysign(90, _turnAngle);
736 SG_NORMALIZE_RANGE(offsetBearing, 0.0, 360.0);
739 SGGeodesy::direct(_turnPt, offsetBearing, d * SG_NM_TO_METER, _turnCentre, az2);
742 double GPS::computeTurnRadiusNm(double aGroundSpeedKts) const
744 // turn time is seconds to execute a 360 turn.
745 double turnTime = 360.0 / _config.turnRateDegSec();
747 // c is ground distance covered in that time (circumference of the circle)
748 double c = turnTime * (aGroundSpeedKts / 3600.0); // convert knts to nm/sec
750 // divide by 2PI to go from circumference -> radius
751 return c / (2 * M_PI);
754 void GPS::updateRouteData()
756 double totalDistance = _wayptController->distanceToWayptM() * SG_METER_TO_NM;
757 // walk all waypoints from wp2 to route end, and sum
758 // for (int i=_routeMgr->currentIndex()+1; i<_routeMgr->numWaypts(); ++i) {
759 //totalDistance += _routeMgr->get_waypoint(i).get_distance();
762 _routeDistanceNm->setDoubleValue(totalDistance * SG_METER_TO_NM);
763 if (_last_speed_kts > 1.0) {
764 double TTW = ((totalDistance * SG_METER_TO_NM) / _last_speed_kts) * 3600.0;
765 _routeETE->setStringValue(makeTTWString(TTW));
769 void GPS::driveAutopilot()
771 if (!_config.driveAutopilot() || !_defaultGPSMode) {
772 _apDrivingFlag->setBoolValue(false);
776 // compatability feature - allow the route-manager / GPS to drive the
777 // generic autopilot heading hold *in leg mode only*
779 bool drive = _mode == "leg";
780 _apDrivingFlag->setBoolValue(drive);
783 // FIXME: we want to set desired track, not heading, here
784 _apTrueHeading->setDoubleValue(getWP1Bearing());
788 void GPS::wp1Changed()
792 if (_mode == "leg") {
793 _wayptController.reset(WayptController::createForWaypt(this, _currentWaypt));
794 } else if (_mode == "obs") {
795 _wayptController.reset(new OBSController(this, _currentWaypt));
796 } else if (_mode == "dto") {
797 _wayptController.reset(new DirectToController(this, _currentWaypt, _wp0_position));
800 _wayptController->init();
802 if (_mode == "obs") {
803 _legDistanceNm = -1.0;
805 _wayptController->update();
806 _legDistanceNm = _wayptController->distanceToWayptM() * SG_METER_TO_NM;
810 /////////////////////////////////////////////////////////////////////////////
811 // property getter/setters
813 void GPS::setSelectedCourse(double crs)
815 if (_selectedCourse == crs) {
819 _selectedCourse = crs;
820 if ((_mode == "obs") || _config.courseSelectable()) {
821 _desiredCourse = _selectedCourse;
822 _desiredCourseNode->fireValueChanged();
826 double GPS::getLegDistance() const
828 if (!_dataValid || (_mode == "obs")) {
832 return _legDistanceNm;
835 double GPS::getLegCourse() const
837 if (!_dataValid || !_wayptController.get()) {
841 return _wayptController->targetTrackDeg();
844 double GPS::getLegMagCourse() const
850 double m = getLegCourse() - _magvar_node->getDoubleValue();
851 SG_NORMALIZE_RANGE(m, 0.0, 360.0);
855 double GPS::getMagTrack() const
861 double m = getTrueTrack() - _magvar_node->getDoubleValue();
862 SG_NORMALIZE_RANGE(m, 0.0, 360.0);
866 double GPS::getCDIDeflection() const
873 if (_config.cdiDeflectionIsAngular()) {
874 defl = getWP1CourseDeviation();
875 SG_CLAMP_RANGE(defl, -10.0, 10.0); // as in navradio.cxx
877 double fullScale = _config.cdiDeflectionLinearPeg();
878 double normError = getWP1CourseErrorNm() / fullScale;
879 SG_CLAMP_RANGE(normError, -1.0, 1.0);
880 defl = normError * 10.0; // re-scale to navradio limits, i.e [-10.0 .. 10.0]
886 const char* GPS::getWP0Ident() const
888 if (!_dataValid || (_mode != "leg") || (!_prevWaypt)) {
892 return _prevWaypt->ident().c_str();
895 const char* GPS::getWP0Name() const
900 const char* GPS::getWP1Ident() const
902 if ((!_dataValid)||(!_currentWaypt)) {
906 return _currentWaypt->ident().c_str();
909 const char* GPS::getWP1Name() const
914 double GPS::getWP1Distance() const
916 if (!_dataValid || !_wayptController.get()) {
920 return _wayptController->distanceToWayptM() * SG_METER_TO_NM;
923 double GPS::getWP1TTW() const
925 if (!_dataValid || !_wayptController.get()) {
929 return _wayptController->timeToWaypt();
932 const char* GPS::getWP1TTWString() const
934 double t = getWP1TTW();
939 return makeTTWString(t);
942 double GPS::getWP1Bearing() const
944 if (!_dataValid || !_wayptController.get()) {
948 return _wayptController->trueBearingDeg();
951 double GPS::getWP1MagBearing() const
953 if (!_dataValid || !_wayptController.get()) {
957 double magBearing = _wayptController->trueBearingDeg() - _magvar_node->getDoubleValue();
958 SG_NORMALIZE_RANGE(magBearing, 0.0, 360.0);
962 double GPS::getWP1CourseDeviation() const
964 if (!_dataValid || !_wayptController.get()) {
968 return _wayptController->courseDeviationDeg();
971 double GPS::getWP1CourseErrorNm() const
973 if (!_dataValid || !_wayptController.get()) {
977 return _wayptController->xtrackErrorNm();
980 bool GPS::getWP1ToFlag() const
982 if (!_dataValid || !_wayptController.get()) {
986 return _wayptController->toFlag();
989 bool GPS::getWP1FromFlag() const
991 if (!_dataValid || !_wayptController.get()) {
995 return !getWP1ToFlag();
999 double GPS::getScratchDistance() const
1001 if (!_scratchValid) {
1005 return SGGeodesy::distanceNm(_indicated_pos, _scratchPos);
1008 double GPS::getScratchTrueBearing() const
1010 if (!_scratchValid) {
1014 return SGGeodesy::courseDeg(_indicated_pos, _scratchPos);
1017 double GPS::getScratchMagBearing() const
1019 if (!_scratchValid) {
1023 double crs = getScratchTrueBearing() - _magvar_node->getDoubleValue();
1024 SG_NORMALIZE_RANGE(crs, 0.0, 360.0);
1030 /////////////////////////////////////////////////////////////////////////////
1033 void GPS::setCommand(const char* aCmd)
1035 SG_LOG(SG_INSTR, SG_DEBUG, "GPS command:" << aCmd);
1037 if (!strcmp(aCmd, "direct")) {
1039 } else if (!strcmp(aCmd, "obs")) {
1040 selectOBSMode(NULL);
1041 } else if (!strcmp(aCmd, "leg")) {
1044 } else if (!strcmp(aCmd, "load-route-wpt")) {
1045 loadRouteWaypoint();
1046 } else if (!strcmp(aCmd, "nearest")) {
1048 } else if (!strcmp(aCmd, "search")) {
1049 _searchNames = false;
1051 } else if (!strcmp(aCmd, "search-names")) {
1052 _searchNames = true;
1054 } else if (!strcmp(aCmd, "next")) {
1056 } else if (!strcmp(aCmd, "previous")) {
1058 } else if (!strcmp(aCmd, "define-user-wpt")) {
1060 } else if (!strcmp(aCmd, "route-insert-before")) {
1061 int index = _scratchNode->getIntValue("index");
1062 if (index < 0 || (_route->numLegs() == 0)) {
1063 index = _route->numLegs();
1064 } else if (index >= _route->numLegs()) {
1065 SG_LOG(SG_INSTR, SG_WARN, "GPS:route-insert-before, bad index:" << index);
1069 insertWaypointAtIndex(index);
1070 } else if (!strcmp(aCmd, "route-insert-after")) {
1071 int index = _scratchNode->getIntValue("index");
1072 if (index < 0 || (_route->numLegs() == 0)) {
1073 index = _route->numLegs();
1074 } else if (index >= _route->numLegs()) {
1075 SG_LOG(SG_INSTR, SG_WARN, "GPS:route-insert-after, bad index:" << index);
1081 insertWaypointAtIndex(index);
1082 } else if (!strcmp(aCmd, "route-delete")) {
1083 int index = _scratchNode->getIntValue("index");
1085 index = _route->numLegs();
1086 } else if (index >= _route->numLegs()) {
1087 SG_LOG(SG_INSTR, SG_WARN, "GPS:route-delete, bad index:" << index);
1091 removeWaypointAtIndex(index);
1094 SG_LOG(SG_INSTR, SG_WARN, "GPS:unrecognized command:" << aCmd);
1098 void GPS::clearScratch()
1100 _scratchPos = SGGeod::fromDegFt(-9999.0, -9999.0, -9999.0);
1101 _scratchNode->setBoolValue("valid", false);
1103 _scratchNode->setStringValue("type", "");
1104 _scratchNode->setStringValue("query", "");
1108 bool GPS::isScratchPositionValid() const
1110 if ((_scratchPos.getLongitudeDeg() < -9990.0) ||
1111 (_scratchPos.getLatitudeDeg() < -9990.0)) {
1118 void GPS::directTo()
1120 if (!isScratchPositionValid()) {
1125 _wp0_position = _indicated_pos;
1126 _currentWaypt = new BasicWaypt(_scratchPos, _scratchNode->getStringValue("ident"), NULL);
1133 void GPS::selectOBSMode(flightgear::Waypt* waypt)
1136 // initialise from scratch
1137 if (!isScratchPositionValid()) {
1141 waypt = new BasicWaypt(_scratchPos, _scratchNode->getStringValue("ident"), NULL);
1145 _currentWaypt = waypt;
1146 _wp0_position = _indicated_pos;
1150 void GPS::selectLegMode()
1152 if (_mode == "leg") {
1157 SG_LOG(SG_INSTR, SG_WARN, "GPS:selectLegMode: no active route");
1162 // depending on the situation, this will either get over-written
1163 // in routeManagerSequenced or not; either way it does no harm to
1165 _wp0_position = _indicated_pos;
1167 // not really sequenced, but does all the work of updating wp0/1
1168 currentWaypointChanged();
1173 void GPS::loadRouteWaypoint()
1175 _scratchValid = false;
1176 int index = _scratchNode->getIntValue("index", -9999);
1179 if ((index < 0) || (index >= _route->numLegs())) { // no index supplied, use current wp
1180 index = _route->currentIndex();
1183 _searchIsRoute = true;
1184 setScratchFromRouteWaypoint(index);
1187 void GPS::setScratchFromRouteWaypoint(int aIndex)
1189 assert(_searchIsRoute);
1190 if ((aIndex < 0) || (aIndex >= _route->numLegs())) {
1191 SG_LOG(SG_INSTR, SG_WARN, "GPS:setScratchFromRouteWaypoint: route-index out of bounds");
1195 _searchResultIndex = aIndex;
1196 WayptRef wp = _route->legAtIndex(aIndex)->waypoint();
1197 _scratchNode->setStringValue("ident", wp->ident());
1198 _scratchPos = wp->position();
1199 _scratchValid = true;
1200 _scratchNode->setIntValue("index", aIndex);
1203 void GPS::loadNearest()
1205 string sty(_scratchNode->getStringValue("type"));
1206 FGPositioned::Type ty = FGPositioned::typeFromName(sty);
1207 if (ty == FGPositioned::INVALID) {
1208 SG_LOG(SG_INSTR, SG_WARN, "GPS:loadNearest: request type is invalid:" << sty);
1212 auto_ptr<FGPositioned::Filter> f(createFilter(ty));
1213 int limitCount = _scratchNode->getIntValue("max-results", 1);
1214 double cutoffDistance = _scratchNode->getDoubleValue("cutoff-nm", 400.0);
1216 SGGeod searchPos = _indicated_pos;
1217 if (isScratchPositionValid()) {
1218 searchPos = _scratchPos;
1221 clearScratch(); // clear now, regardless of whether we find a match or not
1224 FGPositioned::findClosestN(searchPos, limitCount, cutoffDistance, f.get());
1225 _searchResultIndex = 0;
1226 _searchIsRoute = false;
1228 if (_searchResults.empty()) {
1232 setScratchFromCachedSearchResult();
1235 bool GPS::SearchFilter::pass(FGPositioned* aPos) const
1237 switch (aPos->type()) {
1238 case FGPositioned::AIRPORT:
1239 // heliport and seaport too?
1240 case FGPositioned::VOR:
1241 case FGPositioned::NDB:
1242 case FGPositioned::FIX:
1243 case FGPositioned::TACAN:
1244 case FGPositioned::WAYPOINT:
1251 FGPositioned::Type GPS::SearchFilter::minType() const
1253 return FGPositioned::AIRPORT;
1256 FGPositioned::Type GPS::SearchFilter::maxType() const
1258 return FGPositioned::VOR;
1261 FGPositioned::Filter* GPS::createFilter(FGPositioned::Type aTy)
1263 if (aTy == FGPositioned::AIRPORT) {
1264 return new FGAirport::HardSurfaceFilter();
1267 // if we were passed INVALID, assume it means 'all types interesting to a GPS'
1268 if (aTy == FGPositioned::INVALID) {
1269 return new SearchFilter;
1272 return new FGPositioned::TypeFilter(aTy);
1277 // parse search terms into local members, and exec the first search
1278 string sty(_scratchNode->getStringValue("type"));
1279 _searchType = FGPositioned::typeFromName(sty);
1280 _searchQuery = _scratchNode->getStringValue("query");
1281 if (_searchQuery.empty()) {
1282 SG_LOG(SG_INSTR, SG_WARN, "empty GPS search query");
1287 _searchExact = _scratchNode->getBoolValue("exact", true);
1288 _searchResultIndex = 0;
1289 _searchIsRoute = false;
1291 auto_ptr<FGPositioned::Filter> f(createFilter(_searchType));
1293 _searchResults = FGPositioned::findAllWithName(_searchQuery, f.get(), _searchExact);
1295 _searchResults = FGPositioned::findAllWithIdent(_searchQuery, f.get(), _searchExact);
1298 bool orderByRange = _scratchNode->getBoolValue("order-by-distance", true);
1300 FGPositioned::sortByRange(_searchResults, _indicated_pos);
1303 if (_searchResults.empty()) {
1308 setScratchFromCachedSearchResult();
1311 bool GPS::getScratchHasNext() const
1314 if (_searchIsRoute) {
1315 lastResult = _route->numLegs() - 1;
1317 lastResult = (int) _searchResults.size() - 1;
1320 if (lastResult < 0) { // search array might be empty
1324 return (_searchResultIndex < lastResult);
1327 void GPS::setScratchFromCachedSearchResult()
1329 int index = _searchResultIndex;
1331 if ((index < 0) || (index >= (int) _searchResults.size())) {
1332 SG_LOG(SG_INSTR, SG_WARN, "GPS:setScratchFromCachedSearchResult: index out of bounds:" << index);
1336 setScratchFromPositioned(_searchResults[index], index);
1339 void GPS::setScratchFromPositioned(FGPositioned* aPos, int aIndex)
1344 _scratchPos = aPos->geod();
1345 _scratchNode->setStringValue("name", aPos->name());
1346 _scratchNode->setStringValue("ident", aPos->ident());
1347 _scratchNode->setStringValue("type", FGPositioned::nameForType(aPos->type()));
1350 _scratchNode->setIntValue("index", aIndex);
1353 _scratchValid = true;
1354 _scratchNode->setIntValue("result-count", _searchResults.size());
1356 switch (aPos->type()) {
1357 case FGPositioned::VOR:
1358 _scratchNode->setDoubleValue("frequency-mhz", static_cast<FGNavRecord*>(aPos)->get_freq() / 100.0);
1361 case FGPositioned::NDB:
1362 _scratchNode->setDoubleValue("frequency-khz", static_cast<FGNavRecord*>(aPos)->get_freq() / 100.0);
1365 case FGPositioned::AIRPORT:
1366 addAirportToScratch((FGAirport*)aPos);
1374 // look for being on the route and set?
1377 void GPS::addAirportToScratch(FGAirport* aAirport)
1379 for (unsigned int r=0; r<aAirport->numRunways(); ++r) {
1380 SGPropertyNode* rwyNd = _scratchNode->getChild("runways", r, true);
1381 FGRunway* rwy = aAirport->getRunwayByIndex(r);
1382 // TODO - filter out unsuitable runways in the future
1383 // based on config again
1385 rwyNd->setStringValue("id", rwy->ident().c_str());
1386 rwyNd->setIntValue("length-ft", rwy->lengthFt());
1387 rwyNd->setIntValue("width-ft", rwy->widthFt());
1388 rwyNd->setIntValue("heading-deg", rwy->headingDeg());
1389 // map surface code to a string
1390 // TODO - lighting information
1393 rwyNd->setDoubleValue("ils-frequency-mhz", rwy->ILS()->get_freq() / 100.0);
1395 } // of runways iteration
1398 void GPS::nextResult()
1400 if (!getScratchHasNext()) {
1405 if (_searchIsRoute) {
1406 setScratchFromRouteWaypoint(++_searchResultIndex);
1408 ++_searchResultIndex;
1409 setScratchFromCachedSearchResult();
1413 void GPS::previousResult()
1415 if (_searchResultIndex <= 0) {
1420 --_searchResultIndex;
1422 if (_searchIsRoute) {
1423 setScratchFromRouteWaypoint(_searchResultIndex);
1425 setScratchFromCachedSearchResult();
1429 void GPS::defineWaypoint()
1431 if (!isScratchPositionValid()) {
1432 SG_LOG(SG_INSTR, SG_WARN, "GPS:defineWaypoint: invalid lat/lon");
1436 string ident = _scratchNode->getStringValue("ident");
1437 if (ident.size() < 2) {
1438 SG_LOG(SG_INSTR, SG_WARN, "GPS:defineWaypoint: waypoint identifier must be at least two characters");
1442 // check for duplicate idents
1443 FGPositioned::TypeFilter f(FGPositioned::WAYPOINT);
1444 FGPositionedList dups = FGPositioned::findAllWithIdent(ident, &f);
1445 if (!dups.empty()) {
1446 SG_LOG(SG_INSTR, SG_WARN, "GPS:defineWaypoint: non-unique waypoint identifier, ho-hum");
1449 SG_LOG(SG_INSTR, SG_INFO, "GPS:defineWaypoint: creating waypoint:" << ident);
1450 FGPositionedRef wpt = FGPositioned::createUserWaypoint(ident, _scratchPos);
1451 _searchResults.clear();
1452 _searchResults.push_back(wpt);
1453 setScratchFromPositioned(wpt.get(), -1);
1456 void GPS::insertWaypointAtIndex(int aIndex)
1458 // note we do allow index = routeMgr->size(), that's an append
1459 if ((aIndex < 0) || (aIndex > _route->numLegs())) {
1460 throw sg_range_exception("GPS::insertWaypointAtIndex: index out of bounds");
1463 if (!isScratchPositionValid()) {
1464 SG_LOG(SG_INSTR, SG_WARN, "GPS:insertWaypointAtIndex: invalid lat/lon");
1468 string ident = _scratchNode->getStringValue("ident");
1470 WayptRef wpt = new BasicWaypt(_scratchPos, ident, NULL);
1471 _route->insertWayptAtIndex(wpt, aIndex);
1474 void GPS::removeWaypointAtIndex(int aIndex)
1476 if ((aIndex < 0) || (aIndex >= _route->numLegs())) {
1477 throw sg_range_exception("GPS::removeWaypointAtIndex: index out of bounds");
1480 _route->deleteIndex(aIndex);
1484 #endif // of FG_210_COMPAT
1486 void GPS::tieSGGeod(SGPropertyNode* aNode, SGGeod& aRef,
1487 const char* lonStr, const char* latStr, const char* altStr)
1489 tie(aNode, lonStr, SGRawValueMethods<SGGeod, double>(aRef, &SGGeod::getLongitudeDeg, &SGGeod::setLongitudeDeg));
1490 tie(aNode, latStr, SGRawValueMethods<SGGeod, double>(aRef, &SGGeod::getLatitudeDeg, &SGGeod::setLatitudeDeg));
1493 tie(aNode, altStr, SGRawValueMethods<SGGeod, double>(aRef, &SGGeod::getElevationFt, &SGGeod::setElevationFt));
1497 void GPS::tieSGGeodReadOnly(SGPropertyNode* aNode, SGGeod& aRef,
1498 const char* lonStr, const char* latStr, const char* altStr)
1500 tie(aNode, lonStr, SGRawValueMethods<SGGeod, double>(aRef, &SGGeod::getLongitudeDeg, NULL));
1501 tie(aNode, latStr, SGRawValueMethods<SGGeod, double>(aRef, &SGGeod::getLatitudeDeg, NULL));
1504 tie(aNode, altStr, SGRawValueMethods<SGGeod, double>(aRef, &SGGeod::getElevationFt, NULL));