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>
18 #include "Main/fg_props.hxx"
19 #include "Main/globals.hxx" // for get_subsystem
20 #include "Main/util.hxx" // for fgLowPass
21 #include "Navaids/positioned.hxx"
22 #include <Navaids/waypoint.hxx>
23 #include "Navaids/navrecord.hxx"
24 #include "Airports/simple.hxx"
25 #include "Airports/runways.hxx"
26 #include "Autopilot/route_mgr.hxx"
28 #include <simgear/math/sg_random.h>
29 #include <simgear/sg_inlines.h>
30 #include <simgear/math/sg_geodesy.hxx>
31 #include <simgear/structure/exception.hxx>
35 using namespace flightgear;
37 ///////////////////////////////////////////////////////////////////
39 void SGGeodProperty::init(SGPropertyNode* base, const char* lonStr, const char* latStr, const char* altStr)
41 _lon = base->getChild(lonStr, 0, true);
42 _lat = base->getChild(latStr, 0, true);
44 _alt = base->getChild(altStr, 0, true);
48 void SGGeodProperty::init(const char* lonStr, const char* latStr, const char* altStr)
50 _lon = fgGetNode(lonStr, true);
51 _lat = fgGetNode(latStr, true);
53 _alt = fgGetNode(altStr, true);
57 void SGGeodProperty::clear()
59 _lon = _lat = _alt = NULL;
62 void SGGeodProperty::operator=(const SGGeod& geod)
64 _lon->setDoubleValue(geod.getLongitudeDeg());
65 _lat->setDoubleValue(geod.getLatitudeDeg());
67 _alt->setDoubleValue(geod.getElevationFt());
71 SGGeod SGGeodProperty::get() const
73 double lon = _lon->getDoubleValue(),
74 lat = _lat->getDoubleValue();
76 if (SGMisc<double>::isNaN(lon) || SGMisc<double>::isNaN(lat)) {
77 SG_LOG(SG_INSTR, SG_WARN, "read NaN for lon/lat:" << _lon->getPath()
78 << ", " << _lat->getPath());
83 return SGGeod::fromDegFt(lon, lat, _alt->getDoubleValue());
85 return SGGeod::fromDeg(lon,lat);
89 static const char* makeTTWString(double TTW)
91 if ((TTW <= 0.0) || (TTW >= 356400.5)) { // 99 hours
95 unsigned int TTW_seconds = (int) (TTW + 0.5);
96 unsigned int TTW_minutes = 0;
97 unsigned int TTW_hours = 0;
98 static char TTW_str[9];
99 TTW_hours = TTW_seconds / 3600;
100 TTW_minutes = (TTW_seconds / 60) % 60;
101 TTW_seconds = TTW_seconds % 60;
102 snprintf(TTW_str, 9, "%02d:%02d:%02d",
103 TTW_hours, TTW_minutes, TTW_seconds);
107 /////////////////////////////////////////////////////////////////////////////
109 class GPSListener : public SGPropertyChangeListener
112 GPSListener(GPS *m) :
116 virtual void valueChanged (SGPropertyNode * prop)
123 if (prop == _gps->_route_current_wp_node) {
124 _gps->routeManagerSequenced();
125 } else if (prop == _gps->_route_active_node) {
126 _gps->routeActivated();
127 } else if (prop == _gps->_ref_navaid_id_node) {
128 _gps->referenceNavaidSet(prop->getStringValue(""));
129 } else if (prop == _gps->_routeEditedSignal) {
131 } else if (prop == _gps->_routeFinishedSignal) {
132 _gps->routeFinished();
138 void setGuard(bool g) {
143 bool _guard; // re-entrancy guard
146 ////////////////////////////////////////////////////////////////////////////
148 * Helper to monitor for Nasal or other code accessing properties we haven't
149 * defined. For the moment we complain about all such activites, since various
150 * users assume all kinds of weird, wonderful and non-existent interfaces.
153 class DeprecatedPropListener : public SGPropertyChangeListener
156 DeprecatedPropListener(SGPropertyNode* gps)
158 _parents.insert(gps);
159 SGPropertyNode* wp = gps->getChild("wp", 0, true);
161 _parents.insert(wp->getChild("wp", 0, true));
162 _parents.insert(wp->getChild("wp", 1, true));
164 std::set<SGPropertyNode*>::iterator it;
165 for (it = _parents.begin(); it != _parents.end(); ++it) {
166 (*it)->addChangeListener(this);
170 virtual void valueChanged (SGPropertyNode * prop)
174 virtual void childAdded (SGPropertyNode * parent, SGPropertyNode * child)
176 if (isDeprecated(parent, child)) {
177 SG_LOG(SG_INSTR, SG_WARN, "GPS: someone accessed a deprecated property:"
178 << child->getPath(true));
182 bool isDeprecated(SGPropertyNode * parent, SGPropertyNode * child) const
184 if (_parents.count(parent) < 1) {
188 // no child exclusions yet
192 std::set<SGPropertyNode*> _parents;
195 ////////////////////////////////////////////////////////////////////////////
196 // configuration helper object
198 GPS::Config::Config() :
199 _enableTurnAnticipation(true),
200 _turnRate(3.0), // degrees-per-second, so 180 degree turn takes 60 seconds
201 _overflightArmDistance(1.0),
202 _waypointAlertTime(30.0),
203 _requireHardSurface(true),
204 _cdiMaxDeflectionNm(3.0), // linear mode, 3nm at the peg
205 _driveAutopilot(true),
206 _courseSelectable(false)
208 _enableTurnAnticipation = false;
211 void GPS::Config::bind(GPS* aOwner, SGPropertyNode* aCfg)
213 aOwner->tie(aCfg, "turn-rate-deg-sec", SGRawValuePointer<double>(&_turnRate));
214 aOwner->tie(aCfg, "turn-anticipation", SGRawValuePointer<bool>(&_enableTurnAnticipation));
215 aOwner->tie(aCfg, "wpt-alert-time", SGRawValuePointer<double>(&_waypointAlertTime));
216 aOwner->tie(aCfg, "hard-surface-runways-only", SGRawValuePointer<bool>(&_requireHardSurface));
217 aOwner->tie(aCfg, "cdi-max-deflection-nm", SGRawValuePointer<double>(&_cdiMaxDeflectionNm));
218 aOwner->tie(aCfg, "drive-autopilot", SGRawValuePointer<bool>(&_driveAutopilot));
219 aOwner->tie(aCfg, "course-selectable", SGRawValuePointer<bool>(&_courseSelectable));
222 ////////////////////////////////////////////////////////////////////////////
224 GPS::GPS ( SGPropertyNode *node) :
225 _selectedCourse(0.0),
228 _lastPosValid(false),
230 _name(node->getStringValue("name", "gps")),
231 _num(node->getIntValue("number", 0)),
232 _searchResultIndex(0),
234 _searchIsRoute(false),
235 _searchHasNext(false),
237 _computeTurnData(false),
238 _anticipateTurn(false),
241 string branch = "/instrumentation/" + _name;
242 _gpsNode = fgGetNode(branch.c_str(), _num, true );
243 _scratchNode = _gpsNode->getChild("scratch", 0, true);
245 SGPropertyNode *wp_node = _gpsNode->getChild("wp", 0, true);
246 _currentWayptNode = wp_node->getChild("wp", 1, true);
256 _routeMgr = (FGRouteMgr*) globals->get_subsystem("route-manager");
259 _position.init("/position/longitude-deg", "/position/latitude-deg", "/position/altitude-ft");
260 _magvar_node = fgGetNode("/environment/magnetic-variation-deg", true);
261 _serviceable_node = _gpsNode->getChild("serviceable", 0, true);
262 _serviceable_node->setBoolValue(true);
263 _electrical_node = fgGetNode("/systems/electrical/outputs/gps", true);
266 _raim_node = _gpsNode->getChild("raim", 0, true);
267 _odometer_node = _gpsNode->getChild("odometer", 0, true);
268 _trip_odometer_node = _gpsNode->getChild("trip-odometer", 0, true);
269 _true_bug_error_node = _gpsNode->getChild("true-bug-error-deg", 0, true);
270 _magnetic_bug_error_node = _gpsNode->getChild("magnetic-bug-error-deg", 0, true);
271 _eastWestVelocity = _gpsNode->getChild("ew-velocity-msec", 0, true);
272 _northSouthVelocity = _gpsNode->getChild("ns-velocity-msec", 0, true);
275 // for compatability, alias selected course down to wp/wp[1]/desired-course-deg
276 SGPropertyNode* wp1Crs = _currentWayptNode->getChild("desired-course-deg", 0, true);
277 wp1Crs->alias(_gpsNode->getChild("desired-course-deg", 0, true));
279 _tracking_bug_node = _gpsNode->getChild("tracking-bug", 0, true);
282 SGPropertyNode_ptr ref_navaid = _gpsNode->getChild("ref-navaid", 0, true);
283 _ref_navaid_id_node = ref_navaid->getChild("id", 0, true);
284 _ref_navaid_name_node = ref_navaid->getChild("name", 0, true);
285 _ref_navaid_bearing_node = ref_navaid->getChild("bearing-deg", 0, true);
286 _ref_navaid_frequency_node = ref_navaid->getChild("frequency-mhz", 0, true);
287 _ref_navaid_distance_node = ref_navaid->getChild("distance-nm", 0, true);
288 _ref_navaid_mag_bearing_node = ref_navaid->getChild("mag-bearing-deg", 0, true);
289 _ref_navaid_elapsed = 0.0;
290 _ref_navaid_set = false;
293 // should these move to the route manager?
294 _routeDistanceNm = _gpsNode->getChild("route-distance-nm", 0, true);
295 _routeETE = _gpsNode->getChild("ETE", 0, true);
296 _routeEditedSignal = fgGetNode("/autopilot/route-manager/signals/edited", true);
297 _routeFinishedSignal = fgGetNode("/autopilot/route-manager/signals/finished", true);
299 // add listener to various things
300 _listener = new GPSListener(this);
301 _route_current_wp_node = fgGetNode("/autopilot/route-manager/current-wp", true);
302 _route_current_wp_node->addChangeListener(_listener);
303 _route_active_node = fgGetNode("/autopilot/route-manager/active", true);
304 _route_active_node->addChangeListener(_listener);
305 _ref_navaid_id_node->addChangeListener(_listener);
306 _routeEditedSignal->addChangeListener(_listener);
307 _routeFinishedSignal->addChangeListener(_listener);
309 // navradio slaving properties
310 SGPropertyNode* toFlag = _gpsNode->getChild("to-flag", 0, true);
311 toFlag->alias(_currentWayptNode->getChild("to-flag"));
313 SGPropertyNode* fromFlag = _gpsNode->getChild("from-flag", 0, true);
314 fromFlag->alias(_currentWayptNode->getChild("from-flag"));
316 // autopilot drive properties
317 _apDrivingFlag = fgGetNode("/autopilot/settings/gps-driving-true-heading", true);
318 _apTrueHeading = fgGetNode("/autopilot/settings/true-heading-deg",true);
319 _apTargetAltitudeFt = fgGetNode("/autopilot/settings/target-altitude-ft", true);
320 _apAltitudeLock = fgGetNode("/autopilot/locks/altitude", true);
323 _realismSimpleGps = fgGetNode("/sim/realism/simple-gps", true);
324 if (!_realismSimpleGps->hasValue()) {
325 _realismSimpleGps->setBoolValue(true);
328 // last thing, add the deprecated prop watcher
329 new DeprecatedPropListener(_gpsNode);
341 _config.bind(this, _gpsNode->getChild("config", 0, true));
344 tie(_gpsNode, "selected-course-deg", SGRawValueMethods<GPS, double>
345 (*this, &GPS::getSelectedCourse, &GPS::setSelectedCourse));
347 tie(_gpsNode, "desired-course-deg", SGRawValueMethods<GPS, double>
348 (*this, &GPS::getDesiredCourse, NULL));
349 _desiredCourseNode = _gpsNode->getChild("desired-course-deg", 0, true);
351 tieSGGeodReadOnly(_gpsNode, _indicated_pos, "indicated-longitude-deg",
352 "indicated-latitude-deg", "indicated-altitude-ft");
354 tie(_gpsNode, "indicated-vertical-speed", SGRawValueMethods<GPS, double>
355 (*this, &GPS::getVerticalSpeed, NULL));
356 tie(_gpsNode, "indicated-track-true-deg", SGRawValueMethods<GPS, double>
357 (*this, &GPS::getTrueTrack, NULL));
358 tie(_gpsNode, "indicated-track-magnetic-deg", SGRawValueMethods<GPS, double>
359 (*this, &GPS::getMagTrack, NULL));
360 tie(_gpsNode, "indicated-ground-speed-kt", SGRawValueMethods<GPS, double>
361 (*this, &GPS::getGroundspeedKts, NULL));
364 tie(_gpsNode, "mode", SGRawValueMethods<GPS, const char*>(*this, &GPS::getMode, NULL));
365 tie(_gpsNode, "command", SGRawValueMethods<GPS, const char*>(*this, &GPS::getCommand, &GPS::setCommand));
367 tieSGGeod(_scratchNode, _scratchPos, "longitude-deg", "latitude-deg", "altitude-ft");
368 tie(_scratchNode, "valid", SGRawValueMethods<GPS, bool>(*this, &GPS::getScratchValid, NULL));
369 tie(_scratchNode, "distance-nm", SGRawValueMethods<GPS, double>(*this, &GPS::getScratchDistance, NULL));
370 tie(_scratchNode, "true-bearing-deg", SGRawValueMethods<GPS, double>(*this, &GPS::getScratchTrueBearing, NULL));
371 tie(_scratchNode, "mag-bearing-deg", SGRawValueMethods<GPS, double>(*this, &GPS::getScratchMagBearing, NULL));
372 tie(_scratchNode, "has-next", SGRawValueMethods<GPS, bool>(*this, &GPS::getScratchHasNext, NULL));
373 _scratchValid = false;
376 SGPropertyNode *wp_node = _gpsNode->getChild("wp", 0, true);
377 SGPropertyNode* wp0_node = wp_node->getChild("wp", 0, true);
379 tieSGGeodReadOnly(wp0_node, _wp0_position, "longitude-deg", "latitude-deg", "altitude-ft");
380 tie(_currentWayptNode, "ID", SGRawValueMethods<GPS, const char*>
381 (*this, &GPS::getWP1Ident, NULL));
383 tie(_currentWayptNode, "distance-nm", SGRawValueMethods<GPS, double>
384 (*this, &GPS::getWP1Distance, NULL));
385 tie(_currentWayptNode, "bearing-true-deg", SGRawValueMethods<GPS, double>
386 (*this, &GPS::getWP1Bearing, NULL));
387 tie(_currentWayptNode, "bearing-mag-deg", SGRawValueMethods<GPS, double>
388 (*this, &GPS::getWP1MagBearing, NULL));
389 tie(_currentWayptNode, "TTW-sec", SGRawValueMethods<GPS, double>
390 (*this, &GPS::getWP1TTW, NULL));
391 tie(_currentWayptNode, "TTW", SGRawValueMethods<GPS, const char*>
392 (*this, &GPS::getWP1TTWString, NULL));
394 tie(_currentWayptNode, "course-deviation-deg", SGRawValueMethods<GPS, double>
395 (*this, &GPS::getWP1CourseDeviation, NULL));
396 tie(_currentWayptNode, "course-error-nm", SGRawValueMethods<GPS, double>
397 (*this, &GPS::getWP1CourseErrorNm, NULL));
398 tie(_currentWayptNode, "to-flag", SGRawValueMethods<GPS, bool>
399 (*this, &GPS::getWP1ToFlag, NULL));
400 tie(_currentWayptNode, "from-flag", SGRawValueMethods<GPS, bool>
401 (*this, &GPS::getWP1FromFlag, NULL));
403 // leg properties (only valid in DTO/LEG modes, not OBS)
404 tie(wp_node, "leg-distance-nm", SGRawValueMethods<GPS, double>(*this, &GPS::getLegDistance, NULL));
405 tie(wp_node, "leg-true-course-deg", SGRawValueMethods<GPS, double>(*this, &GPS::getLegCourse, NULL));
406 tie(wp_node, "leg-mag-course-deg", SGRawValueMethods<GPS, double>(*this, &GPS::getLegMagCourse, NULL));
408 // navradio slaving properties
409 tie(_gpsNode, "cdi-deflection", SGRawValueMethods<GPS,double>
410 (*this, &GPS::getCDIDeflection));
416 _tiedProperties.Untie();
423 _last_speed_kts = 0.0;
424 _last_pos = SGGeod();
425 _lastPosValid = false;
426 _indicated_pos = SGGeod();
427 _last_vertical_speed = 0.0;
428 _last_true_track = 0.0;
429 _lastEWVelocity = _lastNSVelocity = 0.0;
430 _currentWaypt = _prevWaypt = NULL;
431 _legDistanceNm = -1.0;
433 _raim_node->setDoubleValue(0.0);
434 _indicated_pos = SGGeod();
435 _odometer_node->setDoubleValue(0);
436 _trip_odometer_node->setDoubleValue(0);
437 _tracking_bug_node->setDoubleValue(0);
438 _true_bug_error_node->setDoubleValue(0);
439 _magnetic_bug_error_node->setDoubleValue(0);
440 _northSouthVelocity->setDoubleValue(0.0);
441 _eastWestVelocity->setDoubleValue(0.0);
445 GPS::update (double delta_time_sec)
447 if (!_realismSimpleGps->getBoolValue()) {
448 // If it's off, don't bother.
449 if (!_serviceable_node->getBoolValue() || !_electrical_node->getBoolValue()) {
455 if (delta_time_sec <= 0.0) {
456 return; // paused, don't bother
459 _raim_node->setDoubleValue(1.0);
460 _indicated_pos = _position.get();
461 updateBasicData(delta_time_sec);
464 if (_wayptController.get()) {
465 _wayptController->update();
466 SGGeod p(_wayptController->position());
467 _currentWayptNode->setDoubleValue("longitude-deg", p.getLongitudeDeg());
468 _currentWayptNode->setDoubleValue("latitude-deg", p.getLatitudeDeg());
469 _currentWayptNode->setDoubleValue("altitude-ft", p.getElevationFt());
471 _desiredCourse = getLegMagCourse();
479 updateReferenceNavaid(delta_time_sec);
483 if (_dataValid && (_mode == "init")) {
485 if (_route_active_node->getBoolValue()) {
486 // GPS init with active route
487 SG_LOG(SG_INSTR, SG_INFO, "GPS init with active route");
490 // initialise in OBS mode, with waypt set to the nearest airport.
491 // keep in mind at this point, _dataValid is not set
493 auto_ptr<FGPositioned::Filter> f(createFilter(FGPositioned::AIRPORT));
494 FGPositionedRef apt = FGPositioned::findClosest(_position.get(), 20.0, f.get());
496 setScratchFromPositioned(apt, 0);
503 // allow a realistic delay in the future, here
504 SG_LOG(SG_INSTR, SG_INFO, "GPS initialisation complete");
506 } // of init mode check
508 _last_pos = _indicated_pos;
509 _lastPosValid = !(_last_pos == SGGeod());
512 ///////////////////////////////////////////////////////////////////////////
513 // implement the RNAV interface
514 SGGeod GPS::position()
520 return _indicated_pos;
523 double GPS::trackDeg()
525 return _last_true_track;
528 double GPS::groundSpeedKts()
530 return _last_speed_kts;
533 double GPS::vspeedFPM()
535 return _last_vertical_speed;
538 double GPS::magvarDeg()
540 return _magvar_node->getDoubleValue();
543 double GPS::overflightArmDistanceM()
545 return _config.overflightArmDistanceNm() * SG_NM_TO_METER;
548 double GPS::selectedMagCourse()
550 return _selectedCourse;
553 ///////////////////////////////////////////////////////////////////////////
556 GPS::updateBasicData(double dt)
558 if (!_lastPosValid) {
564 SGGeodesy::inverse(_last_pos, _indicated_pos, _last_true_track, track2_deg, distance_m );
566 double speed_kt = ((distance_m * SG_METER_TO_NM) * ((1 / dt) * 3600.0));
567 double vertical_speed_mpm = ((_indicated_pos.getElevationM() - _last_pos.getElevationM()) * 60 / dt);
568 _last_vertical_speed = vertical_speed_mpm * SG_METER_TO_FEET;
570 speed_kt = fgGetLowPass(_last_speed_kts, speed_kt, dt/10.0);
571 _last_speed_kts = speed_kt;
573 SGGeod g = _indicated_pos;
574 g.setLongitudeDeg(_last_pos.getLongitudeDeg());
575 double northSouthM = SGGeodesy::distanceM(_last_pos, g);
576 northSouthM = copysign(northSouthM, _indicated_pos.getLatitudeDeg() - _last_pos.getLatitudeDeg());
578 double nsMSec = fgGetLowPass(_lastNSVelocity, northSouthM / dt, dt/2.0);
579 _lastNSVelocity = nsMSec;
580 _northSouthVelocity->setDoubleValue(nsMSec);
584 g.setLatitudeDeg(_last_pos.getLatitudeDeg());
585 double eastWestM = SGGeodesy::distanceM(_last_pos, g);
586 eastWestM = copysign(eastWestM, _indicated_pos.getLongitudeDeg() - _last_pos.getLongitudeDeg());
588 double ewMSec = fgGetLowPass(_lastEWVelocity, eastWestM / dt, dt/2.0);
589 _lastEWVelocity = ewMSec;
590 _eastWestVelocity->setDoubleValue(ewMSec);
592 double odometer = _odometer_node->getDoubleValue();
593 _odometer_node->setDoubleValue(odometer + distance_m * SG_METER_TO_NM);
594 odometer = _trip_odometer_node->getDoubleValue();
595 _trip_odometer_node->setDoubleValue(odometer + distance_m * SG_METER_TO_NM);
598 SG_LOG(SG_INSTR, SG_INFO, "GPS setting data valid");
604 GPS::updateTrackingBug()
606 double tracking_bug = _tracking_bug_node->getDoubleValue();
607 double true_bug_error = tracking_bug - getTrueTrack();
608 double magnetic_bug_error = tracking_bug - getMagTrack();
610 // Get the errors into the (-180,180) range.
611 SG_NORMALIZE_RANGE(true_bug_error, -180.0, 180.0);
612 SG_NORMALIZE_RANGE(magnetic_bug_error, -180.0, 180.0);
614 _true_bug_error_node->setDoubleValue(true_bug_error);
615 _magnetic_bug_error_node->setDoubleValue(magnetic_bug_error);
618 void GPS::updateReferenceNavaid(double dt)
620 if (!_ref_navaid_set) {
621 _ref_navaid_elapsed += dt;
622 if (_ref_navaid_elapsed > 5.0) {
624 FGPositioned::TypeFilter vorFilter(FGPositioned::VOR);
625 FGPositionedRef nav = FGPositioned::findClosest(_indicated_pos, 400.0, &vorFilter);
627 SG_LOG(SG_INSTR, SG_INFO, "GPS couldn't find a reference navaid");
628 _ref_navaid_id_node->setStringValue("");
629 _ref_navaid_name_node->setStringValue("");
630 _ref_navaid_bearing_node->setDoubleValue(0.0);
631 _ref_navaid_mag_bearing_node->setDoubleValue(0.0);
632 _ref_navaid_distance_node->setDoubleValue(0.0);
633 _ref_navaid_frequency_node->setStringValue("");
634 } else if (nav != _ref_navaid) {
635 SG_LOG(SG_INSTR, SG_INFO, "GPS code selected new ref-navaid:" << nav->ident());
636 _listener->setGuard(true);
637 _ref_navaid_id_node->setStringValue(nav->ident().c_str());
638 _ref_navaid_name_node->setStringValue(nav->name().c_str());
639 FGNavRecord* vor = (FGNavRecord*) nav.ptr();
640 _ref_navaid_frequency_node->setDoubleValue(vor->get_freq() / 100.0);
641 _listener->setGuard(false);
643 // SG_LOG(SG_INSTR, SG_ALERT, "matched existing");
647 // reset elapsed time (do not do that before updating the properties above, since their
648 // listeners may request another update (_ref_navaid_elapsed = 9999), which results in
649 // excessive load (FGPositioned::findClosest called in every update loop...)
650 _ref_navaid_elapsed = 0.0;
655 double trueCourse, distanceM, az2;
656 SGGeodesy::inverse(_indicated_pos, _ref_navaid->geod(), trueCourse, az2, distanceM);
657 _ref_navaid_distance_node->setDoubleValue(distanceM * SG_METER_TO_NM);
658 _ref_navaid_bearing_node->setDoubleValue(trueCourse);
659 _ref_navaid_mag_bearing_node->setDoubleValue(trueCourse - _magvar_node->getDoubleValue());
663 void GPS::referenceNavaidSet(const std::string& aNavaid)
666 // allow setting an empty string to restore normal nearest-vor selection
667 if (aNavaid.size() > 0) {
668 FGPositioned::TypeFilter vorFilter(FGPositioned::VOR);
669 _ref_navaid = FGPositioned::findClosestWithIdent(aNavaid,
670 _position.get(), &vorFilter);
673 SG_LOG(SG_INSTR, SG_ALERT, "GPS: unknown ref navaid:" << aNavaid);
678 _ref_navaid_set = true;
679 SG_LOG(SG_INSTR, SG_INFO, "GPS code set explicit ref-navaid:" << _ref_navaid->ident());
680 _ref_navaid_id_node->setStringValue(_ref_navaid->ident().c_str());
681 _ref_navaid_name_node->setStringValue(_ref_navaid->name().c_str());
682 FGNavRecord* vor = (FGNavRecord*) _ref_navaid.ptr();
683 _ref_navaid_frequency_node->setDoubleValue(vor->get_freq() / 100.0);
685 _ref_navaid_set = false;
686 _ref_navaid_elapsed = 9999.0; // update next tick
690 void GPS::routeActivated()
692 if (_route_active_node->getBoolValue()) {
693 SG_LOG(SG_INSTR, SG_INFO, "GPS::route activated, switching to LEG mode");
696 // if we've already passed the current waypoint, sequence.
697 if (_dataValid && getWP1FromFlag()) {
698 SG_LOG(SG_INSTR, SG_INFO, "GPS::route activated, FROM wp1, sequencing");
699 _routeMgr->sequence();
701 } else if (_mode == "leg") {
702 SG_LOG(SG_INSTR, SG_INFO, "GPS::route deactivated, switching to OBS mode");
703 // select OBS mode, but keep current waypoint-as is
709 void GPS::routeManagerSequenced()
711 if (_mode != "leg") {
712 SG_LOG(SG_INSTR, SG_INFO, "GPS ignoring route sequencing, not in LEG mode");
716 int index = _routeMgr->currentIndex(),
717 count = _routeMgr->numWaypts();
718 if ((index < 0) || (index >= count)) {
721 SG_LOG(SG_INSTR, SG_ALERT, "GPS: malformed route, index=" << index);
725 SG_LOG(SG_INSTR, SG_INFO, "GPS waypoint index is now " << index);
728 _prevWaypt = _routeMgr->wayptAtIndex(index - 1);
729 if (_prevWaypt->flag(WPT_DYNAMIC)) {
730 _wp0_position = _indicated_pos;
732 _wp0_position = _prevWaypt->position();
736 _currentWaypt = _routeMgr->currentWaypt();
738 _desiredCourse = getLegMagCourse();
739 _desiredCourseNode->fireValueChanged();
743 void GPS::routeEdited()
745 if (_mode != "leg") {
749 SG_LOG(SG_INSTR, SG_INFO, "GPS route edited while in LEG mode, updating waypoints");
750 routeManagerSequenced();
753 void GPS::routeFinished()
755 if (_mode != "leg") {
759 SG_LOG(SG_INSTR, SG_INFO, "GPS route finished, reverting to OBS");
760 // select OBS mode, but keep current waypoint-as is
765 void GPS::updateTurn()
767 bool printProgress = false;
769 if (_computeTurnData) {
770 if (_last_speed_kts < 60) {
771 // need valid leg course and sensible ground speed to compute the turn
776 printProgress = true;
779 if (!_anticipateTurn) {
785 // find bearing to turn centre
786 double bearing, az2, distanceM;
787 SGGeodesy::inverse(_indicated_pos, _turnCentre, bearing, az2, distanceM);
788 double progress = computeTurnProgress(bearing);
791 SG_LOG(SG_INSTR, SG_INFO,"turn progress=" << progress);
794 if (!_inTurn && (progress > 0.0)) {
798 if (_inTurn && !_turnSequenced && (progress > 0.5)) {
799 _turnSequenced = true;
800 SG_LOG(SG_INSTR, SG_INFO, "turn passed midpoint, sequencing");
801 _routeMgr->sequence();
804 if (_inTurn && (progress >= 1.0)) {
809 // drive deviation and desired course
810 double desiredCourse = bearing - copysign(90, _turnAngle);
811 SG_NORMALIZE_RANGE(desiredCourse, 0.0, 360.0);
812 double deviationNm = (distanceM * SG_METER_TO_NM) - _turnRadius;
813 double deviationDeg = desiredCourse - getMagTrack();
814 deviationNm = copysign(deviationNm, deviationDeg);
816 //_wp1_course_deviation_node->setDoubleValue(deviationDeg);
817 //_wp1_course_error_nm_node->setDoubleValue(deviationNm);
818 //_cdiDeflectionNode->setDoubleValue(deviationDeg);
822 void GPS::updateOverflight()
824 if (!_wayptController->isDone()) {
828 if (_mode == "dto") {
829 SG_LOG(SG_INSTR, SG_INFO, "GPS DTO reached destination point");
831 // check for wp1 being on active route - resume leg mode
832 if (_routeMgr->isRouteActive()) {
833 int index = _routeMgr->flightPlan()->findWayptIndex(_currentWaypt->position());
835 SG_LOG(SG_INSTR, SG_INFO, "GPS DTO, resuming LEG mode at wp:" << index);
837 _routeMgr->jumpToIndex(index);
841 if (_mode == "dto") {
842 // if we didn't enter leg mode, drop back to OBS mode
843 // select OBS mode, but keep current waypoint-as is
847 } else if (_mode == "leg") {
848 SG_LOG(SG_INSTR, SG_INFO, "GPS doing overflight sequencing");
849 _routeMgr->sequence();
850 } else if (_mode == "obs") {
851 // nothing to do here, TO/FROM will update but that's fine
854 _computeTurnData = true;
857 void GPS::beginTurn()
860 _turnSequenced = false;
861 SG_LOG(SG_INSTR, SG_INFO, "beginning turn");
867 SG_LOG(SG_INSTR, SG_INFO, "ending turn");
868 _computeTurnData = true;
871 double GPS::computeTurnProgress(double aBearing) const
873 double startBearing = _turnStartBearing + copysign(90, _turnAngle);
874 return (aBearing - startBearing) / _turnAngle;
877 void GPS::computeTurnData()
879 _computeTurnData = false;
880 if (_mode != "leg") { // and approach modes in the future
881 _anticipateTurn = false;
885 WayptRef next = _routeMgr->wayptAtIndex(_routeMgr->currentIndex() + 1);
886 if (!next || next->flag(WPT_DYNAMIC)) {
887 _anticipateTurn = false;
891 if (!_config.turnAnticipationEnabled()) {
892 _anticipateTurn = false;
896 _turnStartBearing = _desiredCourse;
897 // compute next leg course
899 boost::tie(crs, dist) = next->courseAndDistanceFrom(_currentWaypt->position());
902 // compute offset bearing
903 _turnAngle = crs - _turnStartBearing;
904 SG_NORMALIZE_RANGE(_turnAngle, -180.0, 180.0);
905 double median = _turnStartBearing + (_turnAngle * 0.5);
906 double offsetBearing = median + copysign(90, _turnAngle);
907 SG_NORMALIZE_RANGE(offsetBearing, 0.0, 360.0);
909 SG_LOG(SG_INSTR, SG_INFO, "GPS computeTurnData: in=" << _turnStartBearing <<
910 ", out=" << crs << "; turnAngle=" << _turnAngle << ", median=" << median
911 << ", offset=" << offsetBearing);
913 SG_LOG(SG_INSTR, SG_INFO, "next leg is now:" << _currentWaypt->ident() << "->" << next->ident());
915 _turnPt = _currentWaypt->position();
916 _anticipateTurn = true;
919 void GPS::updateTurnData()
921 // depends on ground speed, so needs to be updated per-frame
922 _turnRadius = computeTurnRadiusNm(_last_speed_kts);
924 // compute the turn centre, based on the turn radius.
925 // key thing is to understand that we're working a right-angle triangle,
926 // where the right-angle is the point we start the turn. From that point,
927 // one side is the inbound course to the turn pt, and the other is the
928 // perpendicular line, of length 'r', to the turn centre.
929 // the triangle's hypotenuse, which we need to find, is the distance from the
930 // turn pt to the turn center (in the direction of the offset bearing)
931 // note that d - _turnRadius tell us how much we're 'cutting' the corner.
933 double halfTurnAngle = fabs(_turnAngle * 0.5) * SG_DEGREES_TO_RADIANS;
934 double d = _turnRadius / cos(halfTurnAngle);
936 // SG_LOG(SG_INSTR, SG_INFO, "turnRadius=" << _turnRadius << ", d=" << d
937 // << " (cut distance=" << d - _turnRadius << ")");
939 double median = _turnStartBearing + (_turnAngle * 0.5);
940 double offsetBearing = median + copysign(90, _turnAngle);
941 SG_NORMALIZE_RANGE(offsetBearing, 0.0, 360.0);
944 SGGeodesy::direct(_turnPt, offsetBearing, d * SG_NM_TO_METER, _turnCentre, az2);
947 double GPS::computeTurnRadiusNm(double aGroundSpeedKts) const
949 // turn time is seconds to execute a 360 turn.
950 double turnTime = 360.0 / _config.turnRateDegSec();
952 // c is ground distance covered in that time (circumference of the circle)
953 double c = turnTime * (aGroundSpeedKts / 3600.0); // convert knts to nm/sec
955 // divide by 2PI to go from circumference -> radius
956 return c / (2 * M_PI);
959 void GPS::updateRouteData()
961 double totalDistance = _wayptController->distanceToWayptM() * SG_METER_TO_NM;
962 // walk all waypoints from wp2 to route end, and sum
963 for (int i=_routeMgr->currentIndex()+1; i<_routeMgr->numWaypts(); ++i) {
964 //totalDistance += _routeMgr->get_waypoint(i).get_distance();
967 _routeDistanceNm->setDoubleValue(totalDistance * SG_METER_TO_NM);
968 if (_last_speed_kts > 1.0) {
969 double TTW = ((totalDistance * SG_METER_TO_NM) / _last_speed_kts) * 3600.0;
970 _routeETE->setStringValue(makeTTWString(TTW));
974 void GPS::driveAutopilot()
976 if (!_config.driveAutopilot() || !_realismSimpleGps->getBoolValue()) {
977 _apDrivingFlag->setBoolValue(false);
981 // compatability feature - allow the route-manager / GPS to drive the
982 // generic autopilot heading hold *in leg mode only*
984 bool drive = _mode == "leg";
985 _apDrivingFlag->setBoolValue(drive);
988 // FIXME: we want to set desired track, not heading, here
989 _apTrueHeading->setDoubleValue(getWP1Bearing());
993 void GPS::wp1Changed()
997 if (_mode == "leg") {
998 _wayptController.reset(WayptController::createForWaypt(this, _currentWaypt));
999 } else if (_mode == "obs") {
1000 _wayptController.reset(new OBSController(this, _currentWaypt));
1001 } else if (_mode == "dto") {
1002 _wayptController.reset(new DirectToController(this, _currentWaypt, _wp0_position));
1005 _wayptController->init();
1007 if (_mode == "obs") {
1008 _legDistanceNm = -1.0;
1010 _wayptController->update();
1011 _legDistanceNm = _wayptController->distanceToWayptM() * SG_METER_TO_NM;
1014 if (!_config.driveAutopilot()) {
1018 RouteRestriction ar = _currentWaypt->altitudeRestriction();
1019 double restrictAlt = _currentWaypt->altitudeFt();
1020 double alt = _indicated_pos.getElevationFt();
1021 if ((ar == RESTRICT_AT) ||
1022 ((ar == RESTRICT_ABOVE) && (alt < restrictAlt)) ||
1023 ((ar == RESTRICT_BELOW) && (alt > restrictAlt)))
1025 SG_LOG(SG_AUTOPILOT, SG_INFO, "current waypt has altitude set, setting on AP");
1026 _apTargetAltitudeFt->setDoubleValue(restrictAlt);
1030 /////////////////////////////////////////////////////////////////////////////
1031 // property getter/setters
1033 void GPS::setSelectedCourse(double crs)
1035 if (_selectedCourse == crs) {
1039 _selectedCourse = crs;
1040 if ((_mode == "obs") || _config.courseSelectable()) {
1041 _desiredCourse = _selectedCourse;
1042 _desiredCourseNode->fireValueChanged();
1046 double GPS::getLegDistance() const
1048 if (!_dataValid || (_mode == "obs")) {
1052 return _legDistanceNm;
1055 double GPS::getLegCourse() const
1057 if (!_dataValid || !_wayptController.get()) {
1061 return _wayptController->targetTrackDeg();
1064 double GPS::getLegMagCourse() const
1070 double m = getLegCourse() - _magvar_node->getDoubleValue();
1071 SG_NORMALIZE_RANGE(m, 0.0, 360.0);
1075 double GPS::getMagTrack() const
1081 double m = getTrueTrack() - _magvar_node->getDoubleValue();
1082 SG_NORMALIZE_RANGE(m, 0.0, 360.0);
1086 double GPS::getCDIDeflection() const
1093 if (_config.cdiDeflectionIsAngular()) {
1094 defl = getWP1CourseDeviation();
1095 SG_CLAMP_RANGE(defl, -10.0, 10.0); // as in navradio.cxx
1097 double fullScale = _config.cdiDeflectionLinearPeg();
1098 double normError = getWP1CourseErrorNm() / fullScale;
1099 SG_CLAMP_RANGE(normError, -1.0, 1.0);
1100 defl = normError * 10.0; // re-scale to navradio limits, i.e [-10.0 .. 10.0]
1106 const char* GPS::getWP0Ident() const
1108 if (!_dataValid || (_mode != "leg") || (!_prevWaypt)) {
1112 return _prevWaypt->ident().c_str();
1115 const char* GPS::getWP0Name() const
1120 const char* GPS::getWP1Ident() const
1122 if ((!_dataValid)||(!_currentWaypt)) {
1126 return _currentWaypt->ident().c_str();
1129 const char* GPS::getWP1Name() const
1134 double GPS::getWP1Distance() const
1136 if (!_dataValid || !_wayptController.get()) {
1140 return _wayptController->distanceToWayptM() * SG_METER_TO_NM;
1143 double GPS::getWP1TTW() const
1145 if (!_dataValid || !_wayptController.get()) {
1149 return _wayptController->timeToWaypt();
1152 const char* GPS::getWP1TTWString() const
1154 double t = getWP1TTW();
1159 return makeTTWString(t);
1162 double GPS::getWP1Bearing() const
1164 if (!_dataValid || !_wayptController.get()) {
1168 return _wayptController->trueBearingDeg();
1171 double GPS::getWP1MagBearing() const
1173 if (!_dataValid || !_wayptController.get()) {
1177 double magBearing = _wayptController->trueBearingDeg() - _magvar_node->getDoubleValue();
1178 SG_NORMALIZE_RANGE(magBearing, 0.0, 360.0);
1182 double GPS::getWP1CourseDeviation() const
1184 if (!_dataValid || !_wayptController.get()) {
1188 return _wayptController->courseDeviationDeg();
1191 double GPS::getWP1CourseErrorNm() const
1193 if (!_dataValid || !_wayptController.get()) {
1197 return _wayptController->xtrackErrorNm();
1200 bool GPS::getWP1ToFlag() const
1202 if (!_dataValid || !_wayptController.get()) {
1206 return _wayptController->toFlag();
1209 bool GPS::getWP1FromFlag() const
1211 if (!_dataValid || !_wayptController.get()) {
1215 return !getWP1ToFlag();
1218 double GPS::getScratchDistance() const
1220 if (!_scratchValid) {
1224 return SGGeodesy::distanceNm(_indicated_pos, _scratchPos);
1227 double GPS::getScratchTrueBearing() const
1229 if (!_scratchValid) {
1233 return SGGeodesy::courseDeg(_indicated_pos, _scratchPos);
1236 double GPS::getScratchMagBearing() const
1238 if (!_scratchValid) {
1242 double crs = getScratchTrueBearing() - _magvar_node->getDoubleValue();
1243 SG_NORMALIZE_RANGE(crs, 0.0, 360.0);
1247 /////////////////////////////////////////////////////////////////////////////
1248 // command / scratch / search system
1250 void GPS::setCommand(const char* aCmd)
1252 SG_LOG(SG_INSTR, SG_INFO, "GPS command:" << aCmd);
1254 if (!strcmp(aCmd, "direct")) {
1256 } else if (!strcmp(aCmd, "obs")) {
1258 } else if (!strcmp(aCmd, "leg")) {
1260 } else if (!strcmp(aCmd, "load-route-wpt")) {
1261 loadRouteWaypoint();
1262 } else if (!strcmp(aCmd, "nearest")) {
1264 } else if (!strcmp(aCmd, "search")) {
1265 _searchNames = false;
1267 } else if (!strcmp(aCmd, "search-names")) {
1268 _searchNames = true;
1270 } else if (!strcmp(aCmd, "next")) {
1272 } else if (!strcmp(aCmd, "previous")) {
1274 } else if (!strcmp(aCmd, "define-user-wpt")) {
1276 } else if (!strcmp(aCmd, "route-insert-before")) {
1277 int index = _scratchNode->getIntValue("index");
1278 if (index < 0 || (_routeMgr->numWaypts() == 0)) {
1279 index = _routeMgr->numWaypts();
1280 } else if (index >= _routeMgr->numWaypts()) {
1281 SG_LOG(SG_INSTR, SG_WARN, "GPS:route-insert-before, bad index:" << index);
1285 insertWaypointAtIndex(index);
1286 } else if (!strcmp(aCmd, "route-insert-after")) {
1287 int index = _scratchNode->getIntValue("index");
1288 if (index < 0 || (_routeMgr->numWaypts() == 0)) {
1289 index = _routeMgr->numWaypts();
1290 } else if (index >= _routeMgr->numWaypts()) {
1291 SG_LOG(SG_INSTR, SG_WARN, "GPS:route-insert-after, bad index:" << index);
1297 insertWaypointAtIndex(index);
1298 } else if (!strcmp(aCmd, "route-delete")) {
1299 int index = _scratchNode->getIntValue("index");
1301 index = _routeMgr->numWaypts();
1302 } else if (index >= _routeMgr->numWaypts()) {
1303 SG_LOG(SG_INSTR, SG_WARN, "GPS:route-delete, bad index:" << index);
1307 removeWaypointAtIndex(index);
1309 SG_LOG(SG_INSTR, SG_WARN, "GPS:unrecognized command:" << aCmd);
1313 void GPS::clearScratch()
1315 _scratchPos = SGGeod::fromDegFt(-9999.0, -9999.0, -9999.0);
1316 _scratchValid = false;
1317 _scratchNode->setStringValue("type", "");
1318 _scratchNode->setStringValue("query", "");
1321 bool GPS::isScratchPositionValid() const
1323 if ((_scratchPos.getLongitudeDeg() < -9990.0) ||
1324 (_scratchPos.getLatitudeDeg() < -9990.0)) {
1331 void GPS::directTo()
1333 if (!isScratchPositionValid()) {
1338 _wp0_position = _indicated_pos;
1339 _currentWaypt = new BasicWaypt(_scratchPos, _scratchNode->getStringValue("ident"), NULL);
1346 void GPS::loadRouteWaypoint()
1348 _scratchValid = false;
1349 // if (!_routeMgr->isRouteActive()) {
1350 // SG_LOG(SG_INSTR, SG_WARN, "GPS:loadWaypoint: no active route");
1354 int index = _scratchNode->getIntValue("index", -9999);
1357 if ((index < 0) || (index >= _routeMgr->numWaypts())) { // no index supplied, use current wp
1358 index = _routeMgr->currentIndex();
1361 _searchIsRoute = true;
1362 setScratchFromRouteWaypoint(index);
1365 void GPS::setScratchFromRouteWaypoint(int aIndex)
1367 assert(_searchIsRoute);
1368 if ((aIndex < 0) || (aIndex >= _routeMgr->numWaypts())) {
1369 SG_LOG(SG_INSTR, SG_WARN, "GPS:setScratchFromRouteWaypoint: route-index out of bounds");
1373 _searchResultIndex = aIndex;
1374 WayptRef wp = _routeMgr->wayptAtIndex(aIndex);
1375 _scratchNode->setStringValue("ident", wp->ident());
1376 _scratchPos = wp->position();
1377 _scratchValid = true;
1378 _scratchNode->setIntValue("index", aIndex);
1381 void GPS::loadNearest()
1383 string sty(_scratchNode->getStringValue("type"));
1384 FGPositioned::Type ty = FGPositioned::typeFromName(sty);
1385 if (ty == FGPositioned::INVALID) {
1386 SG_LOG(SG_INSTR, SG_WARN, "GPS:loadNearest: request type is invalid:" << sty);
1390 auto_ptr<FGPositioned::Filter> f(createFilter(ty));
1391 int limitCount = _scratchNode->getIntValue("max-results", 1);
1392 double cutoffDistance = _scratchNode->getDoubleValue("cutoff-nm", 400.0);
1394 SGGeod searchPos = _indicated_pos;
1395 if (isScratchPositionValid()) {
1396 searchPos = _scratchPos;
1399 clearScratch(); // clear now, regardless of whether we find a match or not
1402 FGPositioned::findClosestN(searchPos, limitCount, cutoffDistance, f.get());
1403 _searchResultIndex = 0;
1404 _searchIsRoute = false;
1406 if (_searchResults.empty()) {
1407 SG_LOG(SG_INSTR, SG_INFO, "GPS:loadNearest: no matches at all");
1411 setScratchFromCachedSearchResult();
1414 bool GPS::SearchFilter::pass(FGPositioned* aPos) const
1416 switch (aPos->type()) {
1417 case FGPositioned::AIRPORT:
1418 // heliport and seaport too?
1419 case FGPositioned::VOR:
1420 case FGPositioned::NDB:
1421 case FGPositioned::FIX:
1422 case FGPositioned::TACAN:
1423 case FGPositioned::WAYPOINT:
1430 FGPositioned::Type GPS::SearchFilter::minType() const
1432 return FGPositioned::AIRPORT;
1435 FGPositioned::Type GPS::SearchFilter::maxType() const
1437 return FGPositioned::VOR;
1440 FGPositioned::Filter* GPS::createFilter(FGPositioned::Type aTy)
1442 if (aTy == FGPositioned::AIRPORT) {
1443 return new FGAirport::HardSurfaceFilter();
1446 // if we were passed INVALID, assume it means 'all types interesting to a GPS'
1447 if (aTy == FGPositioned::INVALID) {
1448 return new SearchFilter;
1451 return new FGPositioned::TypeFilter(aTy);
1456 // parse search terms into local members, and exec the first search
1457 string sty(_scratchNode->getStringValue("type"));
1458 _searchType = FGPositioned::typeFromName(sty);
1459 _searchQuery = _scratchNode->getStringValue("query");
1460 if (_searchQuery.empty()) {
1461 SG_LOG(SG_INSTR, SG_WARN, "empty GPS search query");
1466 _searchExact = _scratchNode->getBoolValue("exact", true);
1467 _searchResultIndex = 0;
1468 _searchIsRoute = false;
1470 auto_ptr<FGPositioned::Filter> f(createFilter(_searchType));
1472 _searchResults = FGPositioned::findAllWithName(_searchQuery, f.get(), _searchExact);
1474 _searchResults = FGPositioned::findAllWithIdent(_searchQuery, f.get(), _searchExact);
1477 bool orderByRange = _scratchNode->getBoolValue("order-by-distance", true);
1479 FGPositioned::sortByRange(_searchResults, _indicated_pos);
1482 if (_searchResults.empty()) {
1487 setScratchFromCachedSearchResult();
1490 bool GPS::getScratchHasNext() const
1493 if (_searchIsRoute) {
1494 lastResult = _routeMgr->numWaypts() - 1;
1496 lastResult = (int) _searchResults.size() - 1;
1499 if (lastResult < 0) { // search array might be empty
1503 return (_searchResultIndex < lastResult);
1506 void GPS::setScratchFromCachedSearchResult()
1508 int index = _searchResultIndex;
1510 if ((index < 0) || (index >= (int) _searchResults.size())) {
1511 SG_LOG(SG_INSTR, SG_WARN, "GPS:setScratchFromCachedSearchResult: index out of bounds:" << index);
1515 setScratchFromPositioned(_searchResults[index], index);
1518 void GPS::setScratchFromPositioned(FGPositioned* aPos, int aIndex)
1523 _scratchPos = aPos->geod();
1524 _scratchNode->setStringValue("name", aPos->name());
1525 _scratchNode->setStringValue("ident", aPos->ident());
1526 _scratchNode->setStringValue("type", FGPositioned::nameForType(aPos->type()));
1529 _scratchNode->setIntValue("index", aIndex);
1532 _scratchValid = true;
1533 _scratchNode->setIntValue("result-count", _searchResults.size());
1535 switch (aPos->type()) {
1536 case FGPositioned::VOR:
1537 _scratchNode->setDoubleValue("frequency-mhz", static_cast<FGNavRecord*>(aPos)->get_freq() / 100.0);
1540 case FGPositioned::NDB:
1541 _scratchNode->setDoubleValue("frequency-khz", static_cast<FGNavRecord*>(aPos)->get_freq() / 100.0);
1544 case FGPositioned::AIRPORT:
1545 addAirportToScratch((FGAirport*)aPos);
1553 // look for being on the route and set?
1556 void GPS::addAirportToScratch(FGAirport* aAirport)
1558 for (unsigned int r=0; r<aAirport->numRunways(); ++r) {
1559 SGPropertyNode* rwyNd = _scratchNode->getChild("runways", r, true);
1560 FGRunway* rwy = aAirport->getRunwayByIndex(r);
1561 // TODO - filter out unsuitable runways in the future
1562 // based on config again
1564 rwyNd->setStringValue("id", rwy->ident().c_str());
1565 rwyNd->setIntValue("length-ft", rwy->lengthFt());
1566 rwyNd->setIntValue("width-ft", rwy->widthFt());
1567 rwyNd->setIntValue("heading-deg", rwy->headingDeg());
1568 // map surface code to a string
1569 // TODO - lighting information
1572 rwyNd->setDoubleValue("ils-frequency-mhz", rwy->ILS()->get_freq() / 100.0);
1574 } // of runways iteration
1578 void GPS::selectOBSMode()
1580 if (!isScratchPositionValid()) {
1584 SG_LOG(SG_INSTR, SG_INFO, "GPS switching to OBS mode");
1587 _currentWaypt = new BasicWaypt(_scratchPos, _scratchNode->getStringValue("ident"), NULL);
1588 _wp0_position = _indicated_pos;
1592 void GPS::selectLegMode()
1594 if (_mode == "leg") {
1598 if (!_routeMgr->isRouteActive()) {
1599 SG_LOG(SG_INSTR, SG_WARN, "GPS:selectLegMode: no active route");
1603 SG_LOG(SG_INSTR, SG_INFO, "GPS switching to LEG mode");
1606 // depending on the situation, this will either get over-written
1607 // in routeManagerSequenced or not; either way it does no harm to
1609 _wp0_position = _indicated_pos;
1611 // not really sequenced, but does all the work of updating wp0/1
1612 routeManagerSequenced();
1615 void GPS::nextResult()
1617 if (!getScratchHasNext()) {
1622 if (_searchIsRoute) {
1623 setScratchFromRouteWaypoint(++_searchResultIndex);
1625 ++_searchResultIndex;
1626 setScratchFromCachedSearchResult();
1630 void GPS::previousResult()
1632 if (_searchResultIndex <= 0) {
1637 --_searchResultIndex;
1639 if (_searchIsRoute) {
1640 setScratchFromRouteWaypoint(_searchResultIndex);
1642 setScratchFromCachedSearchResult();
1646 void GPS::defineWaypoint()
1648 if (!isScratchPositionValid()) {
1649 SG_LOG(SG_INSTR, SG_WARN, "GPS:defineWaypoint: invalid lat/lon");
1653 string ident = _scratchNode->getStringValue("ident");
1654 if (ident.size() < 2) {
1655 SG_LOG(SG_INSTR, SG_WARN, "GPS:defineWaypoint: waypoint identifier must be at least two characters");
1659 // check for duplicate idents
1660 FGPositioned::TypeFilter f(FGPositioned::WAYPOINT);
1661 FGPositioned::List dups = FGPositioned::findAllWithIdent(ident, &f);
1662 if (!dups.empty()) {
1663 SG_LOG(SG_INSTR, SG_WARN, "GPS:defineWaypoint: non-unique waypoint identifier, ho-hum");
1666 SG_LOG(SG_INSTR, SG_INFO, "GPS:defineWaypoint: creating waypoint:" << ident);
1667 FGPositionedRef wpt = FGPositioned::createUserWaypoint(ident, _scratchPos);
1668 _searchResults.clear();
1669 _searchResults.push_back(wpt);
1670 setScratchFromPositioned(wpt.get(), -1);
1673 void GPS::insertWaypointAtIndex(int aIndex)
1675 // note we do allow index = routeMgr->size(), that's an append
1676 if ((aIndex < 0) || (aIndex > _routeMgr->numWaypts())) {
1677 throw sg_range_exception("GPS::insertWaypointAtIndex: index out of bounds");
1680 if (!isScratchPositionValid()) {
1681 SG_LOG(SG_INSTR, SG_WARN, "GPS:insertWaypointAtIndex: invalid lat/lon");
1685 string ident = _scratchNode->getStringValue("ident");
1687 WayptRef wpt = new BasicWaypt(_scratchPos, ident, NULL);
1688 _routeMgr->flightPlan()->insertWayptAtIndex(wpt, aIndex);
1691 void GPS::removeWaypointAtIndex(int aIndex)
1693 if ((aIndex < 0) || (aIndex >= _routeMgr->numWaypts())) {
1694 throw sg_range_exception("GPS::removeWaypointAtIndex: index out of bounds");
1697 _routeMgr->removeLegAtIndex(aIndex);
1700 void GPS::tieSGGeod(SGPropertyNode* aNode, SGGeod& aRef,
1701 const char* lonStr, const char* latStr, const char* altStr)
1703 tie(aNode, lonStr, SGRawValueMethods<SGGeod, double>(aRef, &SGGeod::getLongitudeDeg, &SGGeod::setLongitudeDeg));
1704 tie(aNode, latStr, SGRawValueMethods<SGGeod, double>(aRef, &SGGeod::getLatitudeDeg, &SGGeod::setLatitudeDeg));
1707 tie(aNode, altStr, SGRawValueMethods<SGGeod, double>(aRef, &SGGeod::getElevationFt, &SGGeod::setElevationFt));
1711 void GPS::tieSGGeodReadOnly(SGPropertyNode* aNode, SGGeod& aRef,
1712 const char* lonStr, const char* latStr, const char* altStr)
1714 tie(aNode, lonStr, SGRawValueMethods<SGGeod, double>(aRef, &SGGeod::getLongitudeDeg, NULL));
1715 tie(aNode, latStr, SGRawValueMethods<SGGeod, double>(aRef, &SGGeod::getLatitudeDeg, NULL));
1718 tie(aNode, altStr, SGRawValueMethods<SGGeod, double>(aRef, &SGGeod::getElevationFt, NULL));