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);
119 _magvar_node = fgGetNode("/environment/magnetic-variation-deg", true);
120 _serviceable_node = _gpsNode->getChild("serviceable", 0, true);
121 _serviceable_node->setBoolValue(true);
122 _electrical_node = fgGetNode("/systems/electrical/outputs/gps", true);
125 _raim_node = _gpsNode->getChild("raim", 0, true);
126 _odometer_node = _gpsNode->getChild("odometer", 0, true);
127 _trip_odometer_node = _gpsNode->getChild("trip-odometer", 0, true);
128 _true_bug_error_node = _gpsNode->getChild("true-bug-error-deg", 0, true);
129 _magnetic_bug_error_node = _gpsNode->getChild("magnetic-bug-error-deg", 0, true);
130 _eastWestVelocity = _gpsNode->getChild("ew-velocity-msec", 0, true);
131 _northSouthVelocity = _gpsNode->getChild("ns-velocity-msec", 0, true);
134 // for compatability, alias selected course down to wp/wp[1]/desired-course-deg
135 SGPropertyNode* wp1Crs = _currentWayptNode->getChild("desired-course-deg", 0, true);
136 wp1Crs->alias(_gpsNode->getChild("desired-course-deg", 0, true));
138 _tracking_bug_node = _gpsNode->getChild("tracking-bug", 0, true);
141 // should these move to the route manager?
142 _routeDistanceNm = _gpsNode->getChild("route-distance-nm", 0, true);
143 _routeETE = _gpsNode->getChild("ETE", 0, true);
146 // navradio slaving properties
147 SGPropertyNode* toFlag = _gpsNode->getChild("to-flag", 0, true);
148 toFlag->alias(_currentWayptNode->getChild("to-flag"));
150 SGPropertyNode* fromFlag = _gpsNode->getChild("from-flag", 0, true);
151 fromFlag->alias(_currentWayptNode->getChild("from-flag"));
153 // autopilot drive properties
154 _apDrivingFlag = fgGetNode("/autopilot/settings/gps-driving-true-heading", true);
155 _apTrueHeading = fgGetNode("/autopilot/settings/true-heading-deg",true);
169 _config.bind(this, _gpsNode->getChild("config", 0, true));
172 tie(_gpsNode, "selected-course-deg", SGRawValueMethods<GPS, double>
173 (*this, &GPS::getSelectedCourse, &GPS::setSelectedCourse));
175 tie(_gpsNode, "desired-course-deg", SGRawValueMethods<GPS, double>
176 (*this, &GPS::getDesiredCourse, NULL));
177 _desiredCourseNode = _gpsNode->getChild("desired-course-deg", 0, true);
179 tieSGGeodReadOnly(_gpsNode, _indicated_pos, "indicated-longitude-deg",
180 "indicated-latitude-deg", "indicated-altitude-ft");
182 tie(_gpsNode, "indicated-vertical-speed", SGRawValueMethods<GPS, double>
183 (*this, &GPS::getVerticalSpeed, NULL));
184 tie(_gpsNode, "indicated-track-true-deg", SGRawValueMethods<GPS, double>
185 (*this, &GPS::getTrueTrack, NULL));
186 tie(_gpsNode, "indicated-track-magnetic-deg", SGRawValueMethods<GPS, double>
187 (*this, &GPS::getMagTrack, NULL));
188 tie(_gpsNode, "indicated-ground-speed-kt", SGRawValueMethods<GPS, double>
189 (*this, &GPS::getGroundspeedKts, NULL));
192 tie(_gpsNode, "mode", SGRawValueMethods<GPS, const char*>(*this, &GPS::getMode, NULL));
193 tie(_gpsNode, "command", SGRawValueMethods<GPS, const char*>(*this, &GPS::getCommand, &GPS::setCommand));
194 tieSGGeod(_scratchNode, _scratchPos, "longitude-deg", "latitude-deg", "altitude-ft");
196 SGPropertyNode *wp_node = _gpsNode->getChild("wp", 0, true);
197 SGPropertyNode* wp0_node = wp_node->getChild("wp", 0, true);
198 tieSGGeodReadOnly(wp0_node, _wp0_position, "longitude-deg", "latitude-deg", "altitude-ft");
199 tie(wp0_node, "ID", SGRawValueMethods<GPS, const char*>
200 (*this, &GPS::getWP0Ident, NULL));
203 tie(_currentWayptNode, "ID", SGRawValueMethods<GPS, const char*>
204 (*this, &GPS::getWP1Ident, NULL));
206 tie(_currentWayptNode, "distance-nm", SGRawValueMethods<GPS, double>
207 (*this, &GPS::getWP1Distance, NULL));
208 tie(_currentWayptNode, "bearing-true-deg", SGRawValueMethods<GPS, double>
209 (*this, &GPS::getWP1Bearing, NULL));
210 tie(_currentWayptNode, "bearing-mag-deg", SGRawValueMethods<GPS, double>
211 (*this, &GPS::getWP1MagBearing, NULL));
212 tie(_currentWayptNode, "TTW-sec", SGRawValueMethods<GPS, double>
213 (*this, &GPS::getWP1TTW, NULL));
214 tie(_currentWayptNode, "TTW", SGRawValueMethods<GPS, const char*>
215 (*this, &GPS::getWP1TTWString, NULL));
217 tie(_currentWayptNode, "course-deviation-deg", SGRawValueMethods<GPS, double>
218 (*this, &GPS::getWP1CourseDeviation, NULL));
219 tie(_currentWayptNode, "course-error-nm", SGRawValueMethods<GPS, double>
220 (*this, &GPS::getWP1CourseErrorNm, NULL));
221 tie(_currentWayptNode, "to-flag", SGRawValueMethods<GPS, bool>
222 (*this, &GPS::getWP1ToFlag, NULL));
223 tie(_currentWayptNode, "from-flag", SGRawValueMethods<GPS, bool>
224 (*this, &GPS::getWP1FromFlag, NULL));
226 // leg properties (only valid in DTO/LEG modes, not OBS)
227 tie(wp_node, "leg-distance-nm", SGRawValueMethods<GPS, double>(*this, &GPS::getLegDistance, NULL));
228 tie(wp_node, "leg-true-course-deg", SGRawValueMethods<GPS, double>(*this, &GPS::getLegCourse, NULL));
229 tie(wp_node, "leg-mag-course-deg", SGRawValueMethods<GPS, double>(*this, &GPS::getLegMagCourse, NULL));
231 // navradio slaving properties
232 tie(_gpsNode, "cdi-deflection", SGRawValueMethods<GPS,double>
233 (*this, &GPS::getCDIDeflection));
239 _tiedProperties.Untie();
246 _last_speed_kts = 0.0;
247 _last_pos = SGGeod();
248 _lastPosValid = false;
249 _indicated_pos = SGGeod();
250 _last_vertical_speed = 0.0;
251 _last_true_track = 0.0;
252 _lastEWVelocity = _lastNSVelocity = 0.0;
253 _currentWaypt = _prevWaypt = NULL;
254 _legDistanceNm = -1.0;
256 _raim_node->setDoubleValue(0.0);
257 _indicated_pos = SGGeod();
258 _odometer_node->setDoubleValue(0);
259 _trip_odometer_node->setDoubleValue(0);
260 _tracking_bug_node->setDoubleValue(0);
261 _true_bug_error_node->setDoubleValue(0);
262 _magnetic_bug_error_node->setDoubleValue(0);
263 _northSouthVelocity->setDoubleValue(0.0);
264 _eastWestVelocity->setDoubleValue(0.0);
268 GPS::update (double delta_time_sec)
270 if (!_defaultGPSMode) {
271 // If it's off, don't bother.
272 if (!_serviceable_node->getBoolValue() || !_electrical_node->getBoolValue()) {
278 if (delta_time_sec <= 0.0) {
279 return; // paused, don't bother
282 _raim_node->setDoubleValue(1.0);
283 _indicated_pos = globals->get_aircraft_position();
284 updateBasicData(delta_time_sec);
287 if (_wayptController.get()) {
288 _wayptController->update();
289 SGGeod p(_wayptController->position());
290 _currentWayptNode->setDoubleValue("longitude-deg", p.getLongitudeDeg());
291 _currentWayptNode->setDoubleValue("latitude-deg", p.getLatitudeDeg());
292 _currentWayptNode->setDoubleValue("altitude-ft", p.getElevationFt());
294 _desiredCourse = getLegMagCourse();
305 if (_dataValid && (_mode == "init")) {
306 // will select LEG mode if the route is active
307 routeManagerFlightPlanChanged(NULL);
309 FGRouteMgr* routeMgr = static_cast<FGRouteMgr*>(globals->get_subsystem("route-manager"));
310 if (!routeMgr->isRouteActive()) {
311 // initialise in OBS mode, with waypt set to the nearest airport.
312 // keep in mind at this point, _dataValid is not set
313 auto_ptr<FGPositioned::Filter> f(new FGAirport::HardSurfaceFilter());
314 FGPositionedRef apt = FGPositioned::findClosest(_indicated_pos, 20.0, f.get());
316 selectOBSMode(new flightgear::NavaidWaypoint(apt, NULL));
322 // allow a realistic delay in the future, here
324 } // of init mode check
326 _last_pos = _indicated_pos;
327 _lastPosValid = !(_last_pos == SGGeod());
330 void GPS::routeManagerFlightPlanChanged(SGPropertyNode*)
333 _route->removeDelegate(this);
336 SG_LOG(SG_INSTR, SG_INFO, "GPS saw route-manager flight-plan replaced.");
337 FGRouteMgr* routeMgr = static_cast<FGRouteMgr*>(globals->get_subsystem("route-manager"));
338 _route = routeMgr->flightPlan();
340 _route->addDelegate(this);
343 if (routeMgr->isRouteActive()) {
346 selectOBSMode(_currentWaypt); // revert to OBS on current waypoint
350 void GPS::routeActivated(SGPropertyNode* aNode)
352 bool isActive = aNode->getBoolValue();
354 SG_LOG(SG_INSTR, SG_INFO, "GPS::route activated, switching to LEG mode");
357 // if we've already passed the current waypoint, sequence.
358 if (_dataValid && getWP1FromFlag()) {
359 SG_LOG(SG_INSTR, SG_INFO, "GPS::route activated, FROM wp1, sequencing");
362 } else if (_mode == "leg") {
363 SG_LOG(SG_INSTR, SG_INFO, "GPS::route deactivated, switching to OBS mode");
364 selectOBSMode(_currentWaypt);
368 ///////////////////////////////////////////////////////////////////////////
369 // implement the RNAV interface
370 SGGeod GPS::position()
376 return _indicated_pos;
379 double GPS::trackDeg()
381 return _last_true_track;
384 double GPS::groundSpeedKts()
386 return _last_speed_kts;
389 double GPS::vspeedFPM()
391 return _last_vertical_speed;
394 double GPS::magvarDeg()
396 return _magvar_node->getDoubleValue();
399 double GPS::overflightArmDistanceM()
401 return _config.overflightArmDistanceNm() * SG_NM_TO_METER;
404 double GPS::selectedMagCourse()
406 return _selectedCourse;
409 ///////////////////////////////////////////////////////////////////////////
412 GPS::updateBasicData(double dt)
414 if (!_lastPosValid) {
420 SGGeodesy::inverse(_last_pos, _indicated_pos, _last_true_track, track2_deg, distance_m );
422 double speed_kt = ((distance_m * SG_METER_TO_NM) * ((1 / dt) * 3600.0));
423 double vertical_speed_mpm = ((_indicated_pos.getElevationM() - _last_pos.getElevationM()) * 60 / dt);
424 _last_vertical_speed = vertical_speed_mpm * SG_METER_TO_FEET;
426 speed_kt = fgGetLowPass(_last_speed_kts, speed_kt, dt/10.0);
427 _last_speed_kts = speed_kt;
429 SGGeod g = _indicated_pos;
430 g.setLongitudeDeg(_last_pos.getLongitudeDeg());
431 double northSouthM = SGGeodesy::distanceM(_last_pos, g);
432 northSouthM = copysign(northSouthM, _indicated_pos.getLatitudeDeg() - _last_pos.getLatitudeDeg());
434 double nsMSec = fgGetLowPass(_lastNSVelocity, northSouthM / dt, dt/2.0);
435 _lastNSVelocity = nsMSec;
436 _northSouthVelocity->setDoubleValue(nsMSec);
440 g.setLatitudeDeg(_last_pos.getLatitudeDeg());
441 double eastWestM = SGGeodesy::distanceM(_last_pos, g);
442 eastWestM = copysign(eastWestM, _indicated_pos.getLongitudeDeg() - _last_pos.getLongitudeDeg());
444 double ewMSec = fgGetLowPass(_lastEWVelocity, eastWestM / dt, dt/2.0);
445 _lastEWVelocity = ewMSec;
446 _eastWestVelocity->setDoubleValue(ewMSec);
448 double odometer = _odometer_node->getDoubleValue();
449 _odometer_node->setDoubleValue(odometer + distance_m * SG_METER_TO_NM);
450 odometer = _trip_odometer_node->getDoubleValue();
451 _trip_odometer_node->setDoubleValue(odometer + distance_m * SG_METER_TO_NM);
459 GPS::updateTrackingBug()
461 double tracking_bug = _tracking_bug_node->getDoubleValue();
462 double true_bug_error = tracking_bug - getTrueTrack();
463 double magnetic_bug_error = tracking_bug - getMagTrack();
465 // Get the errors into the (-180,180) range.
466 SG_NORMALIZE_RANGE(true_bug_error, -180.0, 180.0);
467 SG_NORMALIZE_RANGE(magnetic_bug_error, -180.0, 180.0);
469 _true_bug_error_node->setDoubleValue(true_bug_error);
470 _magnetic_bug_error_node->setDoubleValue(magnetic_bug_error);
473 void GPS::endOfFlightPlan()
475 selectOBSMode(_currentWaypt);
478 void GPS::currentWaypointChanged()
484 int index = _route->currentIndex(),
485 count = _route->numLegs();
486 if ((index < 0) || (index >= count)) {
489 // no active leg on the route
494 _prevWaypt = _route->previousLeg()->waypoint();
495 if (_prevWaypt->flag(WPT_DYNAMIC)) {
496 _wp0_position = _indicated_pos;
498 _wp0_position = _prevWaypt->position();
502 _currentWaypt = _route->currentLeg()->waypoint();
503 _desiredCourse = getLegMagCourse();
504 _desiredCourseNode->fireValueChanged();
509 void GPS::waypointsChanged()
511 if (_mode != "leg") {
515 SG_LOG(SG_INSTR, SG_INFO, "GPS route edited while in LEG mode, updating waypoints");
516 currentWaypointChanged();
521 if (_mode != "leg") {
525 selectOBSMode(_currentWaypt);
534 int nextIndex = _route->currentIndex() + 1;
535 if (nextIndex >= _route->numLegs()) {
536 SG_LOG(SG_INSTR, SG_INFO, "sequenced final leg, end of route");
538 selectOBSMode(_currentWaypt);
542 // will callback into currentWaypointChanged
543 _route->setCurrentIndex(nextIndex);
546 void GPS::updateTurn()
548 bool printProgress = false;
550 if (_computeTurnData) {
551 if (_last_speed_kts < 10) {
552 // need valid leg course and sensible ground speed to compute the turn
557 printProgress = true;
560 if (!_anticipateTurn) {
566 // find bearing to turn centre
567 double bearing, az2, distanceM;
568 SGGeodesy::inverse(_indicated_pos, _turnCentre, bearing, az2, distanceM);
569 double progress = computeTurnProgress(bearing);
572 SG_LOG(SG_INSTR, SG_INFO,"turn progress=" << progress);
575 if (!_inTurn && (progress > 0.0)) {
579 if (_inTurn && !_turnSequenced && (progress > 0.5)) {
580 _turnSequenced = true;
581 SG_LOG(SG_INSTR, SG_INFO, "turn passed midpoint, sequencing");
585 if (_inTurn && (progress >= 1.0)) {
590 // drive deviation and desired course
591 double desiredCourse = bearing - copysign(90, _turnAngle);
592 SG_NORMALIZE_RANGE(desiredCourse, 0.0, 360.0);
593 double deviationNm = (distanceM * SG_METER_TO_NM) - _turnRadius;
594 double deviationDeg = desiredCourse - getMagTrack();
595 deviationNm = copysign(deviationNm, deviationDeg);
597 //_wp1_course_deviation_node->setDoubleValue(deviationDeg);
598 //_wp1_course_error_nm_node->setDoubleValue(deviationNm);
599 //_cdiDeflectionNode->setDoubleValue(deviationDeg);
603 void GPS::updateOverflight()
605 if (!_wayptController->isDone()) {
609 if (_mode == "dto") {
610 SG_LOG(SG_INSTR, SG_INFO, "GPS DTO reached destination point");
612 // check for wp1 being on active route - resume leg mode
614 int index = _route->findWayptIndex(_currentWaypt->position());
616 SG_LOG(SG_INSTR, SG_INFO, "GPS DTO, resuming LEG mode at wp:" << index);
618 _route->setCurrentIndex(index);
619 sequence(); // and sequence to the next point
623 if (_mode == "dto") {
624 // if we didn't enter leg mode, drop back to OBS mode
625 // select OBS mode, but keep current waypoint-as is
629 } else if (_mode == "leg") {
630 SG_LOG(SG_INSTR, SG_DEBUG, "GPS doing overflight sequencing");
632 } else if (_mode == "obs") {
633 // nothing to do here, TO/FROM will update but that's fine
636 _computeTurnData = true;
639 void GPS::beginTurn()
642 _turnSequenced = false;
643 SG_LOG(SG_INSTR, SG_INFO, "beginning turn");
649 SG_LOG(SG_INSTR, SG_INFO, "ending turn");
650 _computeTurnData = true;
653 double GPS::computeTurnProgress(double aBearing) const
655 double startBearing = _turnStartBearing + copysign(90, _turnAngle);
656 return (aBearing - startBearing) / _turnAngle;
659 void GPS::computeTurnData()
661 _computeTurnData = false;
662 if ((_mode != "leg") || !_route->nextLeg()) {
663 _anticipateTurn = false;
667 WayptRef next = _route->nextLeg()->waypoint();
668 if (next->flag(WPT_DYNAMIC) || !_config.turnAnticipationEnabled()) {
669 _anticipateTurn = false;
673 _turnStartBearing = _desiredCourse;
674 // compute next leg course
676 boost::tie(crs, dist) = next->courseAndDistanceFrom(_currentWaypt->position());
679 // compute offset bearing
680 _turnAngle = crs - _turnStartBearing;
681 SG_NORMALIZE_RANGE(_turnAngle, -180.0, 180.0);
682 double median = _turnStartBearing + (_turnAngle * 0.5);
683 double offsetBearing = median + copysign(90, _turnAngle);
684 SG_NORMALIZE_RANGE(offsetBearing, 0.0, 360.0);
686 SG_LOG(SG_INSTR, SG_INFO, "GPS computeTurnData: in=" << _turnStartBearing <<
687 ", out=" << crs << "; turnAngle=" << _turnAngle << ", median=" << median
688 << ", offset=" << offsetBearing);
690 SG_LOG(SG_INSTR, SG_INFO, "next leg is now:" << _currentWaypt->ident() << "->" << next->ident());
692 _turnPt = _currentWaypt->position();
693 _anticipateTurn = true;
696 void GPS::updateTurnData()
698 // depends on ground speed, so needs to be updated per-frame
699 _turnRadius = computeTurnRadiusNm(_last_speed_kts);
701 // compute the turn centre, based on the turn radius.
702 // key thing is to understand that we're working a right-angle triangle,
703 // where the right-angle is the point we start the turn. From that point,
704 // one side is the inbound course to the turn pt, and the other is the
705 // perpendicular line, of length 'r', to the turn centre.
706 // the triangle's hypotenuse, which we need to find, is the distance from the
707 // turn pt to the turn center (in the direction of the offset bearing)
708 // note that d - _turnRadius tell us how much we're 'cutting' the corner.
710 double halfTurnAngle = fabs(_turnAngle * 0.5) * SG_DEGREES_TO_RADIANS;
711 double d = _turnRadius / cos(halfTurnAngle);
713 // SG_LOG(SG_INSTR, SG_INFO, "turnRadius=" << _turnRadius << ", d=" << d
714 // << " (cut distance=" << d - _turnRadius << ")");
716 double median = _turnStartBearing + (_turnAngle * 0.5);
717 double offsetBearing = median + copysign(90, _turnAngle);
718 SG_NORMALIZE_RANGE(offsetBearing, 0.0, 360.0);
721 SGGeodesy::direct(_turnPt, offsetBearing, d * SG_NM_TO_METER, _turnCentre, az2);
724 double GPS::computeTurnRadiusNm(double aGroundSpeedKts) const
726 // turn time is seconds to execute a 360 turn.
727 double turnTime = 360.0 / _config.turnRateDegSec();
729 // c is ground distance covered in that time (circumference of the circle)
730 double c = turnTime * (aGroundSpeedKts / 3600.0); // convert knts to nm/sec
732 // divide by 2PI to go from circumference -> radius
733 return c / (2 * M_PI);
736 void GPS::updateRouteData()
738 double totalDistance = _wayptController->distanceToWayptM() * SG_METER_TO_NM;
739 // walk all waypoints from wp2 to route end, and sum
740 // for (int i=_routeMgr->currentIndex()+1; i<_routeMgr->numWaypts(); ++i) {
741 //totalDistance += _routeMgr->get_waypoint(i).get_distance();
744 _routeDistanceNm->setDoubleValue(totalDistance * SG_METER_TO_NM);
745 if (_last_speed_kts > 1.0) {
746 double TTW = ((totalDistance * SG_METER_TO_NM) / _last_speed_kts) * 3600.0;
747 _routeETE->setStringValue(makeTTWString(TTW));
751 void GPS::driveAutopilot()
753 if (!_config.driveAutopilot() || !_defaultGPSMode) {
754 _apDrivingFlag->setBoolValue(false);
758 // compatability feature - allow the route-manager / GPS to drive the
759 // generic autopilot heading hold *in leg mode only*
761 bool drive = _mode == "leg";
762 _apDrivingFlag->setBoolValue(drive);
765 // FIXME: we want to set desired track, not heading, here
766 _apTrueHeading->setDoubleValue(getWP1Bearing());
770 void GPS::wp1Changed()
774 if (_mode == "leg") {
775 _wayptController.reset(WayptController::createForWaypt(this, _currentWaypt));
776 } else if (_mode == "obs") {
777 _wayptController.reset(new OBSController(this, _currentWaypt));
778 } else if (_mode == "dto") {
779 _wayptController.reset(new DirectToController(this, _currentWaypt, _wp0_position));
782 _wayptController->init();
784 if (_mode == "obs") {
785 _legDistanceNm = -1.0;
787 _wayptController->update();
788 _legDistanceNm = _wayptController->distanceToWayptM() * SG_METER_TO_NM;
792 /////////////////////////////////////////////////////////////////////////////
793 // property getter/setters
795 void GPS::setSelectedCourse(double crs)
797 if (_selectedCourse == crs) {
801 _selectedCourse = crs;
802 if ((_mode == "obs") || _config.courseSelectable()) {
803 _desiredCourse = _selectedCourse;
804 _desiredCourseNode->fireValueChanged();
808 double GPS::getLegDistance() const
810 if (!_dataValid || (_mode == "obs")) {
814 return _legDistanceNm;
817 double GPS::getLegCourse() const
819 if (!_dataValid || !_wayptController.get()) {
823 return _wayptController->targetTrackDeg();
826 double GPS::getLegMagCourse() const
832 double m = getLegCourse() - _magvar_node->getDoubleValue();
833 SG_NORMALIZE_RANGE(m, 0.0, 360.0);
837 double GPS::getMagTrack() const
843 double m = getTrueTrack() - _magvar_node->getDoubleValue();
844 SG_NORMALIZE_RANGE(m, 0.0, 360.0);
848 double GPS::getCDIDeflection() const
855 if (_config.cdiDeflectionIsAngular()) {
856 defl = getWP1CourseDeviation();
857 SG_CLAMP_RANGE(defl, -10.0, 10.0); // as in navradio.cxx
859 double fullScale = _config.cdiDeflectionLinearPeg();
860 double normError = getWP1CourseErrorNm() / fullScale;
861 SG_CLAMP_RANGE(normError, -1.0, 1.0);
862 defl = normError * 10.0; // re-scale to navradio limits, i.e [-10.0 .. 10.0]
868 const char* GPS::getWP0Ident() const
870 if (!_dataValid || (_mode != "leg") || (!_prevWaypt)) {
874 return _prevWaypt->ident().c_str();
877 const char* GPS::getWP0Name() const
882 const char* GPS::getWP1Ident() const
884 if ((!_dataValid)||(!_currentWaypt)) {
888 return _currentWaypt->ident().c_str();
891 const char* GPS::getWP1Name() const
896 double GPS::getWP1Distance() const
898 if (!_dataValid || !_wayptController.get()) {
902 return _wayptController->distanceToWayptM() * SG_METER_TO_NM;
905 double GPS::getWP1TTW() const
907 if (!_dataValid || !_wayptController.get()) {
911 return _wayptController->timeToWaypt();
914 const char* GPS::getWP1TTWString() const
916 double t = getWP1TTW();
921 return makeTTWString(t);
924 double GPS::getWP1Bearing() const
926 if (!_dataValid || !_wayptController.get()) {
930 return _wayptController->trueBearingDeg();
933 double GPS::getWP1MagBearing() const
935 if (!_dataValid || !_wayptController.get()) {
939 double magBearing = _wayptController->trueBearingDeg() - _magvar_node->getDoubleValue();
940 SG_NORMALIZE_RANGE(magBearing, 0.0, 360.0);
944 double GPS::getWP1CourseDeviation() const
946 if (!_dataValid || !_wayptController.get()) {
950 return _wayptController->courseDeviationDeg();
953 double GPS::getWP1CourseErrorNm() const
955 if (!_dataValid || !_wayptController.get()) {
959 return _wayptController->xtrackErrorNm();
962 bool GPS::getWP1ToFlag() const
964 if (!_dataValid || !_wayptController.get()) {
968 return _wayptController->toFlag();
971 bool GPS::getWP1FromFlag() const
973 if (!_dataValid || !_wayptController.get()) {
977 return !getWP1ToFlag();
980 /////////////////////////////////////////////////////////////////////////////
983 void GPS::setCommand(const char* aCmd)
985 SG_LOG(SG_INSTR, SG_DEBUG, "GPS command:" << aCmd);
987 if (!strcmp(aCmd, "direct")) {
989 } else if (!strcmp(aCmd, "obs")) {
991 } else if (!strcmp(aCmd, "leg")) {
994 SG_LOG(SG_INSTR, SG_WARN, "GPS:unrecognized command:" << aCmd);
998 void GPS::clearScratch()
1000 _scratchPos = SGGeod::fromDegFt(-9999.0, -9999.0, -9999.0);
1001 _scratchNode->setBoolValue("valid", false);
1004 bool GPS::isScratchPositionValid() const
1006 if ((_scratchPos.getLongitudeDeg() < -9990.0) ||
1007 (_scratchPos.getLatitudeDeg() < -9990.0)) {
1014 void GPS::directTo()
1016 if (!isScratchPositionValid()) {
1021 _wp0_position = _indicated_pos;
1022 _currentWaypt = new BasicWaypt(_scratchPos, _scratchNode->getStringValue("ident"), NULL);
1029 void GPS::selectOBSMode(flightgear::Waypt* waypt)
1032 // initialise from scratch
1033 if (!isScratchPositionValid()) {
1037 waypt = new BasicWaypt(_scratchPos, _scratchNode->getStringValue("ident"), NULL);
1041 _currentWaypt = waypt;
1042 _wp0_position = _indicated_pos;
1046 void GPS::selectLegMode()
1048 if (_mode == "leg") {
1053 SG_LOG(SG_INSTR, SG_WARN, "GPS:selectLegMode: no active route");
1058 // depending on the situation, this will either get over-written
1059 // in routeManagerSequenced or not; either way it does no harm to
1061 _wp0_position = _indicated_pos;
1063 // not really sequenced, but does all the work of updating wp0/1
1064 currentWaypointChanged();
1067 void GPS::tieSGGeod(SGPropertyNode* aNode, SGGeod& aRef,
1068 const char* lonStr, const char* latStr, const char* altStr)
1070 tie(aNode, lonStr, SGRawValueMethods<SGGeod, double>(aRef, &SGGeod::getLongitudeDeg, &SGGeod::setLongitudeDeg));
1071 tie(aNode, latStr, SGRawValueMethods<SGGeod, double>(aRef, &SGGeod::getLatitudeDeg, &SGGeod::setLatitudeDeg));
1074 tie(aNode, altStr, SGRawValueMethods<SGGeod, double>(aRef, &SGGeod::getElevationFt, &SGGeod::setElevationFt));
1078 void GPS::tieSGGeodReadOnly(SGPropertyNode* aNode, SGGeod& aRef,
1079 const char* lonStr, const char* latStr, const char* altStr)
1081 tie(aNode, lonStr, SGRawValueMethods<SGGeod, double>(aRef, &SGGeod::getLongitudeDeg, NULL));
1082 tie(aNode, latStr, SGRawValueMethods<SGGeod, double>(aRef, &SGGeod::getLatitudeDeg, NULL));
1085 tie(aNode, altStr, SGRawValueMethods<SGGeod, double>(aRef, &SGGeod::getElevationFt, NULL));