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>
32 #include <simgear/scene/util/OsgMath.hxx>
36 using namespace flightgear;
38 ///////////////////////////////////////////////////////////////////
40 void SGGeodProperty::init(SGPropertyNode* base, const char* lonStr, const char* latStr, const char* altStr)
42 _lon = base->getChild(lonStr, 0, true);
43 _lat = base->getChild(latStr, 0, true);
45 _alt = base->getChild(altStr, 0, true);
49 void SGGeodProperty::init(const char* lonStr, const char* latStr, const char* altStr)
51 _lon = fgGetNode(lonStr, true);
52 _lat = fgGetNode(latStr, true);
54 _alt = fgGetNode(altStr, true);
58 void SGGeodProperty::clear()
60 _lon = _lat = _alt = NULL;
63 void SGGeodProperty::operator=(const SGGeod& geod)
65 _lon->setDoubleValue(geod.getLongitudeDeg());
66 _lat->setDoubleValue(geod.getLatitudeDeg());
68 _alt->setDoubleValue(geod.getElevationFt());
72 SGGeod SGGeodProperty::get() const
74 double lon = _lon->getDoubleValue(),
75 lat = _lat->getDoubleValue();
77 if (osg::isNaN(lon) || osg::isNaN(lat)) {
78 SG_LOG(SG_INSTR, SG_WARN, "read NaN for lon/lat:" << _lon->getPath()
79 << ", " << _lat->getPath());
84 return SGGeod::fromDegFt(lon, lat, _alt->getDoubleValue());
86 return SGGeod::fromDeg(lon,lat);
90 static const char* makeTTWString(double TTW)
92 if ((TTW <= 0.0) || (TTW >= 356400.5)) { // 99 hours
96 unsigned int TTW_seconds = (int) (TTW + 0.5);
97 unsigned int TTW_minutes = 0;
98 unsigned int TTW_hours = 0;
99 static char TTW_str[9];
100 TTW_hours = TTW_seconds / 3600;
101 TTW_minutes = (TTW_seconds / 60) % 60;
102 TTW_seconds = TTW_seconds % 60;
103 snprintf(TTW_str, 9, "%02d:%02d:%02d",
104 TTW_hours, TTW_minutes, TTW_seconds);
108 /////////////////////////////////////////////////////////////////////////////
110 class GPSListener : public SGPropertyChangeListener
113 GPSListener(GPS *m) :
117 virtual void valueChanged (SGPropertyNode * prop)
124 if (prop == _gps->_route_current_wp_node) {
125 _gps->routeManagerSequenced();
126 } else if (prop == _gps->_route_active_node) {
127 _gps->routeActivated();
128 } else if (prop == _gps->_ref_navaid_id_node) {
129 _gps->referenceNavaidSet(prop->getStringValue(""));
130 } else if (prop == _gps->_routeEditedSignal) {
132 } else if (prop == _gps->_routeFinishedSignal) {
133 _gps->routeFinished();
139 void setGuard(bool g) {
144 bool _guard; // re-entrancy guard
147 ////////////////////////////////////////////////////////////////////////////
149 * Helper to monitor for Nasal or other code accessing properties we haven't
150 * defined. For the moment we complain about all such activites, since various
151 * users assume all kinds of weird, wonderful and non-existent interfaces.
154 class DeprecatedPropListener : public SGPropertyChangeListener
157 DeprecatedPropListener(SGPropertyNode* gps)
159 _parents.insert(gps);
160 SGPropertyNode* wp = gps->getChild("wp", 0, true);
162 _parents.insert(wp->getChild("wp", 0, true));
163 _parents.insert(wp->getChild("wp", 1, true));
165 std::set<SGPropertyNode*>::iterator it;
166 for (it = _parents.begin(); it != _parents.end(); ++it) {
167 (*it)->addChangeListener(this);
171 virtual void valueChanged (SGPropertyNode * prop)
175 virtual void childAdded (SGPropertyNode * parent, SGPropertyNode * child)
177 if (isDeprecated(parent, child)) {
178 SG_LOG(SG_INSTR, SG_WARN, "GPS: someone accessed a deprecated property:"
179 << child->getPath(true));
183 bool isDeprecated(SGPropertyNode * parent, SGPropertyNode * child) const
185 if (_parents.count(parent) < 1) {
189 // no child exclusions yet
193 std::set<SGPropertyNode*> _parents;
196 ////////////////////////////////////////////////////////////////////////////
197 // configuration helper object
199 GPS::Config::Config() :
200 _enableTurnAnticipation(true),
201 _turnRate(3.0), // degrees-per-second, so 180 degree turn takes 60 seconds
202 _overflightArmDistance(1.0),
203 _waypointAlertTime(30.0),
204 _minRunwayLengthFt(0.0),
205 _requireHardSurface(true),
206 _cdiMaxDeflectionNm(3.0), // linear mode, 3nm at the peg
207 _driveAutopilot(true),
208 _courseSelectable(false)
210 _enableTurnAnticipation = false;
213 void GPS::Config::bind(GPS* aOwner, SGPropertyNode* aCfg)
215 aOwner->tie(aCfg, "turn-rate-deg-sec", SGRawValuePointer<double>(&_turnRate));
216 aOwner->tie(aCfg, "turn-anticipation", SGRawValuePointer<bool>(&_enableTurnAnticipation));
217 aOwner->tie(aCfg, "wpt-alert-time", SGRawValuePointer<double>(&_waypointAlertTime));
218 aOwner->tie(aCfg, "min-runway-length-ft", SGRawValuePointer<double>(&_minRunwayLengthFt));
219 aOwner->tie(aCfg, "hard-surface-runways-only", SGRawValuePointer<bool>(&_requireHardSurface));
220 aOwner->tie(aCfg, "cdi-max-deflection-nm", SGRawValuePointer<double>(&_cdiMaxDeflectionNm));
221 aOwner->tie(aCfg, "drive-autopilot", SGRawValuePointer<bool>(&_driveAutopilot));
222 aOwner->tie(aCfg, "course-selectable", SGRawValuePointer<bool>(&_courseSelectable));
225 ////////////////////////////////////////////////////////////////////////////
227 GPS::GPS ( SGPropertyNode *node) :
228 _selectedCourse(0.0),
231 _lastPosValid(false),
233 _name(node->getStringValue("name", "gps")),
234 _num(node->getIntValue("number", 0)),
235 _searchResultIndex(0),
237 _searchIsRoute(false),
238 _searchHasNext(false),
240 _computeTurnData(false),
241 _anticipateTurn(false),
244 string branch = "/instrumentation/" + _name;
245 _gpsNode = fgGetNode(branch.c_str(), _num, true );
246 _scratchNode = _gpsNode->getChild("scratch", 0, true);
248 SGPropertyNode *wp_node = _gpsNode->getChild("wp", 0, true);
249 _currentWayptNode = wp_node->getChild("wp", 1, true);
259 _routeMgr = (FGRouteMgr*) globals->get_subsystem("route-manager");
262 _position.init("/position/longitude-deg", "/position/latitude-deg", "/position/altitude-ft");
263 _magvar_node = fgGetNode("/environment/magnetic-variation-deg", true);
264 _serviceable_node = _gpsNode->getChild("serviceable", 0, true);
265 _serviceable_node->setBoolValue(true);
266 _electrical_node = fgGetNode("/systems/electrical/outputs/gps", true);
269 _raim_node = _gpsNode->getChild("raim", 0, true);
270 _odometer_node = _gpsNode->getChild("odometer", 0, true);
271 _trip_odometer_node = _gpsNode->getChild("trip-odometer", 0, true);
272 _true_bug_error_node = _gpsNode->getChild("true-bug-error-deg", 0, true);
273 _magnetic_bug_error_node = _gpsNode->getChild("magnetic-bug-error-deg", 0, true);
274 _eastWestVelocity = _gpsNode->getChild("ew-velocity-msec", 0, true);
275 _northSouthVelocity = _gpsNode->getChild("ns-velocity-msec", 0, true);
278 // for compatability, alias selected course down to wp/wp[1]/desired-course-deg
279 SGPropertyNode* wp1Crs = _currentWayptNode->getChild("desired-course-deg", 0, true);
280 wp1Crs->alias(_gpsNode->getChild("desired-course-deg", 0, true));
282 _tracking_bug_node = _gpsNode->getChild("tracking-bug", 0, true);
285 SGPropertyNode_ptr ref_navaid = _gpsNode->getChild("ref-navaid", 0, true);
286 _ref_navaid_id_node = ref_navaid->getChild("id", 0, true);
287 _ref_navaid_name_node = ref_navaid->getChild("name", 0, true);
288 _ref_navaid_bearing_node = ref_navaid->getChild("bearing-deg", 0, true);
289 _ref_navaid_frequency_node = ref_navaid->getChild("frequency-mhz", 0, true);
290 _ref_navaid_distance_node = ref_navaid->getChild("distance-nm", 0, true);
291 _ref_navaid_mag_bearing_node = ref_navaid->getChild("mag-bearing-deg", 0, true);
292 _ref_navaid_elapsed = 0.0;
293 _ref_navaid_set = false;
296 // should these move to the route manager?
297 _routeDistanceNm = _gpsNode->getChild("route-distance-nm", 0, true);
298 _routeETE = _gpsNode->getChild("ETE", 0, true);
299 _routeEditedSignal = fgGetNode("/autopilot/route-manager/signals/edited", true);
300 _routeFinishedSignal = fgGetNode("/autopilot/route-manager/signals/finished", true);
302 // add listener to various things
303 _listener = new GPSListener(this);
304 _route_current_wp_node = fgGetNode("/autopilot/route-manager/current-wp", true);
305 _route_current_wp_node->addChangeListener(_listener);
306 _route_active_node = fgGetNode("/autopilot/route-manager/active", true);
307 _route_active_node->addChangeListener(_listener);
308 _ref_navaid_id_node->addChangeListener(_listener);
309 _routeEditedSignal->addChangeListener(_listener);
310 _routeFinishedSignal->addChangeListener(_listener);
312 // navradio slaving properties
313 SGPropertyNode* toFlag = _gpsNode->getChild("to-flag", 0, true);
314 toFlag->alias(_currentWayptNode->getChild("to-flag"));
316 SGPropertyNode* fromFlag = _gpsNode->getChild("from-flag", 0, true);
317 fromFlag->alias(_currentWayptNode->getChild("from-flag"));
319 // autopilot drive properties
320 _apDrivingFlag = fgGetNode("/autopilot/settings/gps-driving-true-heading", true);
321 _apTrueHeading = fgGetNode("/autopilot/settings/true-heading-deg",true);
322 _apTargetAltitudeFt = fgGetNode("/autopilot/settings/target-altitude-ft", true);
323 _apAltitudeLock = fgGetNode("/autopilot/locks/altitude", true);
326 _realismSimpleGps = fgGetNode("/sim/realism/simple-gps", true);
327 if (!_realismSimpleGps->hasValue()) {
328 _realismSimpleGps->setBoolValue(true);
331 // last thing, add the deprecated prop watcher
332 new DeprecatedPropListener(_gpsNode);
340 _config.bind(this, _gpsNode->getChild("config", 0, true));
343 tie(_gpsNode, "selected-course-deg", SGRawValueMethods<GPS, double>
344 (*this, &GPS::getSelectedCourse, &GPS::setSelectedCourse));
346 tie(_gpsNode, "desired-course-deg", SGRawValueMethods<GPS, double>
347 (*this, &GPS::getDesiredCourse, NULL));
348 _desiredCourseNode = _gpsNode->getChild("desired-course-deg", 0, true);
350 tieSGGeodReadOnly(_gpsNode, _indicated_pos, "indicated-longitude-deg",
351 "indicated-latitude-deg", "indicated-altitude-ft");
353 tie(_gpsNode, "indicated-vertical-speed", SGRawValueMethods<GPS, double>
354 (*this, &GPS::getVerticalSpeed, NULL));
355 tie(_gpsNode, "indicated-track-true-deg", SGRawValueMethods<GPS, double>
356 (*this, &GPS::getTrueTrack, NULL));
357 tie(_gpsNode, "indicated-track-magnetic-deg", SGRawValueMethods<GPS, double>
358 (*this, &GPS::getMagTrack, NULL));
359 tie(_gpsNode, "indicated-ground-speed-kt", SGRawValueMethods<GPS, double>
360 (*this, &GPS::getGroundspeedKts, NULL));
363 tie(_gpsNode, "mode", SGRawValueMethods<GPS, const char*>(*this, &GPS::getMode, NULL));
364 tie(_gpsNode, "command", SGRawValueMethods<GPS, const char*>(*this, &GPS::getCommand, &GPS::setCommand));
366 tieSGGeod(_scratchNode, _scratchPos, "longitude-deg", "latitude-deg", "altitude-ft");
367 tie(_scratchNode, "valid", SGRawValueMethods<GPS, bool>(*this, &GPS::getScratchValid, NULL));
368 tie(_scratchNode, "distance-nm", SGRawValueMethods<GPS, double>(*this, &GPS::getScratchDistance, NULL));
369 tie(_scratchNode, "true-bearing-deg", SGRawValueMethods<GPS, double>(*this, &GPS::getScratchTrueBearing, NULL));
370 tie(_scratchNode, "mag-bearing-deg", SGRawValueMethods<GPS, double>(*this, &GPS::getScratchMagBearing, NULL));
371 tie(_scratchNode, "has-next", SGRawValueMethods<GPS, bool>(*this, &GPS::getScratchHasNext, NULL));
372 _scratchValid = false;
375 SGPropertyNode *wp_node = _gpsNode->getChild("wp", 0, true);
376 SGPropertyNode* wp0_node = wp_node->getChild("wp", 0, true);
378 tieSGGeodReadOnly(wp0_node, _wp0_position, "longitude-deg", "latitude-deg", "altitude-ft");
379 tie(_currentWayptNode, "ID", SGRawValueMethods<GPS, const char*>
380 (*this, &GPS::getWP1Ident, NULL));
382 tie(_currentWayptNode, "distance-nm", SGRawValueMethods<GPS, double>
383 (*this, &GPS::getWP1Distance, NULL));
384 tie(_currentWayptNode, "bearing-true-deg", SGRawValueMethods<GPS, double>
385 (*this, &GPS::getWP1Bearing, NULL));
386 tie(_currentWayptNode, "bearing-mag-deg", SGRawValueMethods<GPS, double>
387 (*this, &GPS::getWP1MagBearing, NULL));
388 tie(_currentWayptNode, "TTW-sec", SGRawValueMethods<GPS, double>
389 (*this, &GPS::getWP1TTW, NULL));
390 tie(_currentWayptNode, "TTW", SGRawValueMethods<GPS, const char*>
391 (*this, &GPS::getWP1TTWString, NULL));
393 tie(_currentWayptNode, "course-deviation-deg", SGRawValueMethods<GPS, double>
394 (*this, &GPS::getWP1CourseDeviation, NULL));
395 tie(_currentWayptNode, "course-error-nm", SGRawValueMethods<GPS, double>
396 (*this, &GPS::getWP1CourseErrorNm, NULL));
397 tie(_currentWayptNode, "to-flag", SGRawValueMethods<GPS, bool>
398 (*this, &GPS::getWP1ToFlag, NULL));
399 tie(_currentWayptNode, "from-flag", SGRawValueMethods<GPS, bool>
400 (*this, &GPS::getWP1FromFlag, NULL));
402 // leg properties (only valid in DTO/LEG modes, not OBS)
403 tie(wp_node, "leg-distance-nm", SGRawValueMethods<GPS, double>(*this, &GPS::getLegDistance, NULL));
404 tie(wp_node, "leg-true-course-deg", SGRawValueMethods<GPS, double>(*this, &GPS::getLegCourse, NULL));
405 tie(wp_node, "leg-mag-course-deg", SGRawValueMethods<GPS, double>(*this, &GPS::getLegMagCourse, NULL));
407 // navradio slaving properties
408 tie(_gpsNode, "cdi-deflection", SGRawValueMethods<GPS,double>
409 (*this, &GPS::getCDIDeflection));
415 _tiedProperties.Untie();
422 _last_speed_kts = 0.0;
423 _last_pos = SGGeod();
424 _lastPosValid = false;
425 _indicated_pos = SGGeod();
426 _last_vertical_speed = 0.0;
427 _last_true_track = 0.0;
428 _lastEWVelocity = _lastNSVelocity = 0.0;
429 _currentWaypt = _prevWaypt = NULL;
430 _legDistanceNm = -1.0;
432 _raim_node->setDoubleValue(0.0);
433 _indicated_pos = SGGeod();
434 _odometer_node->setDoubleValue(0);
435 _trip_odometer_node->setDoubleValue(0);
436 _tracking_bug_node->setDoubleValue(0);
437 _true_bug_error_node->setDoubleValue(0);
438 _magnetic_bug_error_node->setDoubleValue(0);
439 _northSouthVelocity->setDoubleValue(0.0);
440 _eastWestVelocity->setDoubleValue(0.0);
444 GPS::update (double delta_time_sec)
446 if (!_realismSimpleGps->getBoolValue()) {
447 // If it's off, don't bother.
448 if (!_serviceable_node->getBoolValue() || !_electrical_node->getBoolValue()) {
454 if (delta_time_sec <= 0.0) {
455 return; // paused, don't bother
458 _raim_node->setDoubleValue(1.0);
459 _indicated_pos = _position.get();
460 updateBasicData(delta_time_sec);
463 if (_wayptController.get()) {
464 _wayptController->update();
465 SGGeod p(_wayptController->position());
466 _currentWayptNode->setDoubleValue("longitude-deg", p.getLongitudeDeg());
467 _currentWayptNode->setDoubleValue("latitude-deg", p.getLatitudeDeg());
468 _currentWayptNode->setDoubleValue("altitude-ft", p.getElevationFt());
470 _desiredCourse = getLegMagCourse();
478 updateReferenceNavaid(delta_time_sec);
482 if (_dataValid && (_mode == "init")) {
483 // allow a realistic delay in the future, here
484 SG_LOG(SG_INSTR, SG_INFO, "GPS initialisation complete");
486 if (_route_active_node->getBoolValue()) {
487 // GPS init with active route
488 SG_LOG(SG_INSTR, SG_INFO, "GPS init with active route");
491 // initialise in OBS mode, with waypt set to the nearest airport.
492 // keep in mind at this point, _dataValid is not set
494 auto_ptr<FGPositioned::Filter> f(createFilter(FGPositioned::AIRPORT));
495 FGPositionedRef apt = FGPositioned::findClosest(_position.get(), 20.0, f.get());
497 setScratchFromPositioned(apt, 0);
501 } // of init mode check
503 _last_pos = _indicated_pos;
504 _lastPosValid = !(_last_pos == SGGeod());
507 ///////////////////////////////////////////////////////////////////////////
508 // implement the RNAV interface
509 SGGeod GPS::position()
515 return _indicated_pos;
518 double GPS::trackDeg()
520 return _last_true_track;
523 double GPS::groundSpeedKts()
525 return _last_speed_kts;
528 double GPS::vspeedFPM()
530 return _last_vertical_speed;
533 double GPS::magvarDeg()
535 return _magvar_node->getDoubleValue();
538 double GPS::overflightArmDistanceM()
540 return _config.overflightArmDistanceNm() * SG_NM_TO_METER;
543 double GPS::selectedMagCourse()
545 return _selectedCourse;
548 ///////////////////////////////////////////////////////////////////////////
551 GPS::updateBasicData(double dt)
553 if (!_lastPosValid) {
559 SGGeodesy::inverse(_last_pos, _indicated_pos, _last_true_track, track2_deg, distance_m );
561 double speed_kt = ((distance_m * SG_METER_TO_NM) * ((1 / dt) * 3600.0));
562 double vertical_speed_mpm = ((_indicated_pos.getElevationM() - _last_pos.getElevationM()) * 60 / dt);
563 _last_vertical_speed = vertical_speed_mpm * SG_METER_TO_FEET;
565 speed_kt = fgGetLowPass(_last_speed_kts, speed_kt, dt/10.0);
566 _last_speed_kts = speed_kt;
568 SGGeod g = _indicated_pos;
569 g.setLongitudeDeg(_last_pos.getLongitudeDeg());
570 double northSouthM = SGGeodesy::distanceM(_last_pos, g);
571 northSouthM = copysign(northSouthM, _indicated_pos.getLatitudeDeg() - _last_pos.getLatitudeDeg());
573 double nsMSec = fgGetLowPass(_lastNSVelocity, northSouthM / dt, dt/2.0);
574 _lastNSVelocity = nsMSec;
575 _northSouthVelocity->setDoubleValue(nsMSec);
579 g.setLatitudeDeg(_last_pos.getLatitudeDeg());
580 double eastWestM = SGGeodesy::distanceM(_last_pos, g);
581 eastWestM = copysign(eastWestM, _indicated_pos.getLongitudeDeg() - _last_pos.getLongitudeDeg());
583 double ewMSec = fgGetLowPass(_lastEWVelocity, eastWestM / dt, dt/2.0);
584 _lastEWVelocity = ewMSec;
585 _eastWestVelocity->setDoubleValue(ewMSec);
587 double odometer = _odometer_node->getDoubleValue();
588 _odometer_node->setDoubleValue(odometer + distance_m * SG_METER_TO_NM);
589 odometer = _trip_odometer_node->getDoubleValue();
590 _trip_odometer_node->setDoubleValue(odometer + distance_m * SG_METER_TO_NM);
593 SG_LOG(SG_INSTR, SG_INFO, "GPS setting data valid");
599 GPS::updateTrackingBug()
601 double tracking_bug = _tracking_bug_node->getDoubleValue();
602 double true_bug_error = tracking_bug - getTrueTrack();
603 double magnetic_bug_error = tracking_bug - getMagTrack();
605 // Get the errors into the (-180,180) range.
606 SG_NORMALIZE_RANGE(true_bug_error, -180.0, 180.0);
607 SG_NORMALIZE_RANGE(magnetic_bug_error, -180.0, 180.0);
609 _true_bug_error_node->setDoubleValue(true_bug_error);
610 _magnetic_bug_error_node->setDoubleValue(magnetic_bug_error);
613 void GPS::updateReferenceNavaid(double dt)
615 if (!_ref_navaid_set) {
616 _ref_navaid_elapsed += dt;
617 if (_ref_navaid_elapsed > 5.0) {
619 FGPositioned::TypeFilter vorFilter(FGPositioned::VOR);
620 FGPositionedRef nav = FGPositioned::findClosest(_indicated_pos, 400.0, &vorFilter);
622 SG_LOG(SG_INSTR, SG_INFO, "GPS couldn't find a reference navaid");
623 _ref_navaid_id_node->setStringValue("");
624 _ref_navaid_name_node->setStringValue("");
625 _ref_navaid_bearing_node->setDoubleValue(0.0);
626 _ref_navaid_mag_bearing_node->setDoubleValue(0.0);
627 _ref_navaid_distance_node->setDoubleValue(0.0);
628 _ref_navaid_frequency_node->setStringValue("");
629 } else if (nav != _ref_navaid) {
630 SG_LOG(SG_INSTR, SG_INFO, "GPS code selected new ref-navaid:" << nav->ident());
631 _listener->setGuard(true);
632 _ref_navaid_id_node->setStringValue(nav->ident().c_str());
633 _ref_navaid_name_node->setStringValue(nav->name().c_str());
634 FGNavRecord* vor = (FGNavRecord*) nav.ptr();
635 _ref_navaid_frequency_node->setDoubleValue(vor->get_freq() / 100.0);
636 _listener->setGuard(false);
638 // SG_LOG(SG_INSTR, SG_ALERT, "matched existing");
642 // reset elapsed time (do not do that before updating the properties above, since their
643 // listeners may request another update (_ref_navaid_elapsed = 9999), which results in
644 // excessive load (FGPositioned::findClosest called in every update loop...)
645 _ref_navaid_elapsed = 0.0;
650 double trueCourse, distanceM, az2;
651 SGGeodesy::inverse(_indicated_pos, _ref_navaid->geod(), trueCourse, az2, distanceM);
652 _ref_navaid_distance_node->setDoubleValue(distanceM * SG_METER_TO_NM);
653 _ref_navaid_bearing_node->setDoubleValue(trueCourse);
654 _ref_navaid_mag_bearing_node->setDoubleValue(trueCourse - _magvar_node->getDoubleValue());
658 void GPS::referenceNavaidSet(const std::string& aNavaid)
661 // allow setting an empty string to restore normal nearest-vor selection
662 if (aNavaid.size() > 0) {
663 FGPositioned::TypeFilter vorFilter(FGPositioned::VOR);
664 _ref_navaid = FGPositioned::findClosestWithIdent(aNavaid,
665 _position.get(), &vorFilter);
668 SG_LOG(SG_INSTR, SG_ALERT, "GPS: unknown ref navaid:" << aNavaid);
673 _ref_navaid_set = true;
674 SG_LOG(SG_INSTR, SG_INFO, "GPS code set explict ref-navaid:" << _ref_navaid->ident());
675 _ref_navaid_id_node->setStringValue(_ref_navaid->ident().c_str());
676 _ref_navaid_name_node->setStringValue(_ref_navaid->name().c_str());
677 FGNavRecord* vor = (FGNavRecord*) _ref_navaid.ptr();
678 _ref_navaid_frequency_node->setDoubleValue(vor->get_freq() / 100.0);
680 _ref_navaid_set = false;
681 _ref_navaid_elapsed = 9999.0; // update next tick
685 void GPS::routeActivated()
687 if (_route_active_node->getBoolValue()) {
688 SG_LOG(SG_INSTR, SG_INFO, "GPS::route activated, switching to LEG mode");
691 // if we've already passed the current waypoint, sequence.
692 if (_dataValid && getWP1FromFlag()) {
693 SG_LOG(SG_INSTR, SG_INFO, "GPS::route activated, FROM wp1, sequencing");
694 _routeMgr->sequence();
696 } else if (_mode == "leg") {
697 SG_LOG(SG_INSTR, SG_INFO, "GPS::route deactivated, switching to OBS mode");
698 // select OBS mode, but keep current waypoint-as is
704 void GPS::routeManagerSequenced()
706 if (_mode != "leg") {
707 SG_LOG(SG_INSTR, SG_INFO, "GPS ignoring route sequencing, not in LEG mode");
711 int index = _routeMgr->currentIndex(),
712 count = _routeMgr->numWaypts();
713 if ((index < 0) || (index >= count)) {
716 SG_LOG(SG_INSTR, SG_ALERT, "GPS: malformed route, index=" << index);
720 SG_LOG(SG_INSTR, SG_INFO, "GPS waypoint index is now " << index);
723 _prevWaypt = _routeMgr->previousWaypt();
724 if (_prevWaypt->flag(WPT_DYNAMIC)) {
725 _wp0_position = _indicated_pos;
727 _wp0_position = _prevWaypt->position();
731 _currentWaypt = _routeMgr->currentWaypt();
733 _desiredCourse = getLegMagCourse();
734 _desiredCourseNode->fireValueChanged();
738 void GPS::routeEdited()
740 if (_mode != "leg") {
744 SG_LOG(SG_INSTR, SG_INFO, "GPS route edited while in LEG mode, updating waypoints");
745 routeManagerSequenced();
748 void GPS::routeFinished()
750 if (_mode != "leg") {
754 SG_LOG(SG_INSTR, SG_INFO, "GPS route finished, reverting to OBS");
755 // select OBS mode, but keep current waypoint-as is
760 void GPS::updateTurn()
762 bool printProgress = false;
764 if (_computeTurnData) {
765 if (_last_speed_kts < 60) {
766 // need valid leg course and sensible ground speed to compute the turn
771 printProgress = true;
774 if (!_anticipateTurn) {
780 // find bearing to turn centre
781 double bearing, az2, distanceM;
782 SGGeodesy::inverse(_indicated_pos, _turnCentre, bearing, az2, distanceM);
783 double progress = computeTurnProgress(bearing);
786 SG_LOG(SG_INSTR, SG_INFO,"turn progress=" << progress);
789 if (!_inTurn && (progress > 0.0)) {
793 if (_inTurn && !_turnSequenced && (progress > 0.5)) {
794 _turnSequenced = true;
795 SG_LOG(SG_INSTR, SG_INFO, "turn passed midpoint, sequencing");
796 _routeMgr->sequence();
799 if (_inTurn && (progress >= 1.0)) {
804 // drive deviation and desired course
805 double desiredCourse = bearing - copysign(90, _turnAngle);
806 SG_NORMALIZE_RANGE(desiredCourse, 0.0, 360.0);
807 double deviationNm = (distanceM * SG_METER_TO_NM) - _turnRadius;
808 double deviationDeg = desiredCourse - getMagTrack();
809 deviationNm = copysign(deviationNm, deviationDeg);
811 //_wp1_course_deviation_node->setDoubleValue(deviationDeg);
812 //_wp1_course_error_nm_node->setDoubleValue(deviationNm);
813 //_cdiDeflectionNode->setDoubleValue(deviationDeg);
817 void GPS::updateOverflight()
819 if (!_wayptController->isDone()) {
823 if (_mode == "dto") {
824 SG_LOG(SG_INSTR, SG_INFO, "GPS DTO reached destination point");
826 // check for wp1 being on active route - resume leg mode
827 if (_routeMgr->isRouteActive()) {
828 int index = _routeMgr->findWayptIndex(_currentWaypt->position());
830 SG_LOG(SG_INSTR, SG_INFO, "GPS DTO, resuming LEG mode at wp:" << index);
832 _routeMgr->jumpToIndex(index);
836 if (_mode == "dto") {
837 // if we didn't enter leg mode, drop back to OBS mode
838 // select OBS mode, but keep current waypoint-as is
842 } else if (_mode == "leg") {
843 SG_LOG(SG_INSTR, SG_INFO, "GPS doing overflight sequencing");
844 _routeMgr->sequence();
845 } else if (_mode == "obs") {
846 // nothing to do here, TO/FROM will update but that's fine
849 _computeTurnData = true;
852 void GPS::beginTurn()
855 _turnSequenced = false;
856 SG_LOG(SG_INSTR, SG_INFO, "begining turn");
862 SG_LOG(SG_INSTR, SG_INFO, "ending turn");
863 _computeTurnData = true;
866 double GPS::computeTurnProgress(double aBearing) const
868 double startBearing = _turnStartBearing + copysign(90, _turnAngle);
869 return (aBearing - startBearing) / _turnAngle;
872 void GPS::computeTurnData()
874 _computeTurnData = false;
875 if (_mode != "leg") { // and approach modes in the future
876 _anticipateTurn = false;
880 WayptRef next = _routeMgr->nextWaypt();
881 if (!next || next->flag(WPT_DYNAMIC)) {
882 _anticipateTurn = false;
886 if (!_config.turnAnticipationEnabled()) {
887 _anticipateTurn = false;
891 _turnStartBearing = _desiredCourse;
892 // compute next leg course
894 boost::tie(crs, dist) = next->courseAndDistanceFrom(_currentWaypt->position());
897 // compute offset bearing
898 _turnAngle = crs - _turnStartBearing;
899 SG_NORMALIZE_RANGE(_turnAngle, -180.0, 180.0);
900 double median = _turnStartBearing + (_turnAngle * 0.5);
901 double offsetBearing = median + copysign(90, _turnAngle);
902 SG_NORMALIZE_RANGE(offsetBearing, 0.0, 360.0);
904 SG_LOG(SG_INSTR, SG_INFO, "GPS computeTurnData: in=" << _turnStartBearing <<
905 ", out=" << crs << "; turnAngle=" << _turnAngle << ", median=" << median
906 << ", offset=" << offsetBearing);
908 SG_LOG(SG_INSTR, SG_INFO, "next leg is now:" << _currentWaypt->ident() << "->" << next->ident());
910 _turnPt = _currentWaypt->position();
911 _anticipateTurn = true;
914 void GPS::updateTurnData()
916 // depends on ground speed, so needs to be updated per-frame
917 _turnRadius = computeTurnRadiusNm(_last_speed_kts);
919 // compute the turn centre, based on the turn radius.
920 // key thing is to understand that we're working a right-angle triangle,
921 // where the right-angle is the point we start the turn. From that point,
922 // one side is the inbound course to the turn pt, and the other is the
923 // perpendicular line, of length 'r', to the turn centre.
924 // the triangle's hypotenuse, which we need to find, is the distance from the
925 // turn pt to the turn center (in the direction of the offset bearing)
926 // note that d - _turnRadius tell us how much we're 'cutting' the corner.
928 double halfTurnAngle = fabs(_turnAngle * 0.5) * SG_DEGREES_TO_RADIANS;
929 double d = _turnRadius / cos(halfTurnAngle);
931 // SG_LOG(SG_INSTR, SG_INFO, "turnRadius=" << _turnRadius << ", d=" << d
932 // << " (cut distance=" << d - _turnRadius << ")");
934 double median = _turnStartBearing + (_turnAngle * 0.5);
935 double offsetBearing = median + copysign(90, _turnAngle);
936 SG_NORMALIZE_RANGE(offsetBearing, 0.0, 360.0);
939 SGGeodesy::direct(_turnPt, offsetBearing, d * SG_NM_TO_METER, _turnCentre, az2);
942 double GPS::computeTurnRadiusNm(double aGroundSpeedKts) const
944 // turn time is seconds to execute a 360 turn.
945 double turnTime = 360.0 / _config.turnRateDegSec();
947 // c is ground distance covered in that time (circumference of the circle)
948 double c = turnTime * (aGroundSpeedKts / 3600.0); // convert knts to nm/sec
950 // divide by 2PI to go from circumference -> radius
951 return c / (2 * M_PI);
954 void GPS::updateRouteData()
956 double totalDistance = _wayptController->distanceToWayptM() * SG_METER_TO_NM;
957 // walk all waypoints from wp2 to route end, and sum
958 for (int i=_routeMgr->currentIndex()+1; i<_routeMgr->numWaypts(); ++i) {
959 //totalDistance += _routeMgr->get_waypoint(i).get_distance();
962 _routeDistanceNm->setDoubleValue(totalDistance * SG_METER_TO_NM);
963 if (_last_speed_kts > 1.0) {
964 double TTW = ((totalDistance * SG_METER_TO_NM) / _last_speed_kts) * 3600.0;
965 _routeETE->setStringValue(makeTTWString(TTW));
969 void GPS::driveAutopilot()
971 if (!_config.driveAutopilot() || !_realismSimpleGps->getBoolValue()) {
972 _apDrivingFlag->setBoolValue(false);
976 // compatability feature - allow the route-manager / GPS to drive the
977 // generic autopilot heading hold *in leg mode only*
979 bool drive = _mode == "leg";
980 _apDrivingFlag->setBoolValue(drive);
983 // FIXME: we want to set desired track, not heading, here
984 _apTrueHeading->setDoubleValue(getWP1Bearing());
988 void GPS::wp1Changed()
992 if (_mode == "leg") {
993 _wayptController.reset(WayptController::createForWaypt(this, _currentWaypt));
994 } else if (_mode == "obs") {
995 _wayptController.reset(new OBSController(this, _currentWaypt));
996 } else if (_mode == "dto") {
997 _wayptController.reset(new DirectToController(this, _currentWaypt, _wp0_position));
1000 _wayptController->init();
1002 if (_mode == "obs") {
1003 _legDistanceNm = -1.0;
1005 _wayptController->update();
1006 _legDistanceNm = _wayptController->distanceToWayptM() * SG_METER_TO_NM;
1009 if (!_config.driveAutopilot()) {
1013 RouteRestriction ar = _currentWaypt->altitudeRestriction();
1014 double restrictAlt = _currentWaypt->altitudeFt();
1015 double alt = _indicated_pos.getElevationFt();
1016 if ((ar == RESTRICT_AT) ||
1017 ((ar == RESTRICT_ABOVE) && (alt < restrictAlt)) ||
1018 ((ar == RESTRICT_BELOW) && (alt > restrictAlt)))
1020 SG_LOG(SG_AUTOPILOT, SG_INFO, "current waypt has altitude set, setting on AP");
1021 _apTargetAltitudeFt->setDoubleValue(restrictAlt);
1025 /////////////////////////////////////////////////////////////////////////////
1026 // property getter/setters
1028 void GPS::setSelectedCourse(double crs)
1030 if (_selectedCourse == crs) {
1034 _selectedCourse = crs;
1035 if ((_mode == "obs") || _config.courseSelectable()) {
1036 _desiredCourse = _selectedCourse;
1037 _desiredCourseNode->fireValueChanged();
1041 double GPS::getLegDistance() const
1043 if (!_dataValid || (_mode == "obs")) {
1047 return _legDistanceNm;
1050 double GPS::getLegCourse() const
1052 if (!_dataValid || !_wayptController.get()) {
1056 return _wayptController->targetTrackDeg();
1059 double GPS::getLegMagCourse() const
1065 double m = getLegCourse() - _magvar_node->getDoubleValue();
1066 SG_NORMALIZE_RANGE(m, 0.0, 360.0);
1070 double GPS::getMagTrack() const
1076 double m = getTrueTrack() - _magvar_node->getDoubleValue();
1077 SG_NORMALIZE_RANGE(m, 0.0, 360.0);
1081 double GPS::getCDIDeflection() const
1088 if (_config.cdiDeflectionIsAngular()) {
1089 defl = getWP1CourseDeviation();
1090 SG_CLAMP_RANGE(defl, -10.0, 10.0); // as in navradio.cxx
1092 double fullScale = _config.cdiDeflectionLinearPeg();
1093 double normError = getWP1CourseErrorNm() / fullScale;
1094 SG_CLAMP_RANGE(normError, -1.0, 1.0);
1095 defl = normError * 10.0; // re-scale to navradio limits, i.e [-10.0 .. 10.0]
1101 const char* GPS::getWP0Ident() const
1103 if (!_dataValid || (_mode != "leg") || (!_prevWaypt)) {
1107 return _prevWaypt->ident().c_str();
1110 const char* GPS::getWP0Name() const
1115 const char* GPS::getWP1Ident() const
1117 if ((!_dataValid)||(!_currentWaypt)) {
1121 return _currentWaypt->ident().c_str();
1124 const char* GPS::getWP1Name() const
1129 double GPS::getWP1Distance() const
1131 if (!_dataValid || !_wayptController.get()) {
1135 return _wayptController->distanceToWayptM() * SG_METER_TO_NM;
1138 double GPS::getWP1TTW() const
1140 if (!_dataValid || !_wayptController.get()) {
1144 return _wayptController->timeToWaypt();
1147 const char* GPS::getWP1TTWString() const
1149 double t = getWP1TTW();
1154 return makeTTWString(t);
1157 double GPS::getWP1Bearing() const
1159 if (!_dataValid || !_wayptController.get()) {
1163 return _wayptController->trueBearingDeg();
1166 double GPS::getWP1MagBearing() const
1168 if (!_dataValid || !_wayptController.get()) {
1172 double magBearing = _wayptController->trueBearingDeg() - _magvar_node->getDoubleValue();
1173 SG_NORMALIZE_RANGE(magBearing, 0.0, 360.0);
1177 double GPS::getWP1CourseDeviation() const
1179 if (!_dataValid || !_wayptController.get()) {
1183 return _wayptController->courseDeviationDeg();
1186 double GPS::getWP1CourseErrorNm() const
1188 if (!_dataValid || !_wayptController.get()) {
1192 return _wayptController->xtrackErrorNm();
1195 bool GPS::getWP1ToFlag() const
1197 if (!_dataValid || !_wayptController.get()) {
1201 return _wayptController->toFlag();
1204 bool GPS::getWP1FromFlag() const
1206 if (!_dataValid || !_wayptController.get()) {
1210 return !getWP1ToFlag();
1213 double GPS::getScratchDistance() const
1215 if (!_scratchValid) {
1219 return SGGeodesy::distanceNm(_indicated_pos, _scratchPos);
1222 double GPS::getScratchTrueBearing() const
1224 if (!_scratchValid) {
1228 return SGGeodesy::courseDeg(_indicated_pos, _scratchPos);
1231 double GPS::getScratchMagBearing() const
1233 if (!_scratchValid) {
1237 double crs = getScratchTrueBearing() - _magvar_node->getDoubleValue();
1238 SG_NORMALIZE_RANGE(crs, 0.0, 360.0);
1242 /////////////////////////////////////////////////////////////////////////////
1243 // command / scratch / search system
1245 void GPS::setCommand(const char* aCmd)
1247 SG_LOG(SG_INSTR, SG_INFO, "GPS command:" << aCmd);
1249 if (!strcmp(aCmd, "direct")) {
1251 } else if (!strcmp(aCmd, "obs")) {
1253 } else if (!strcmp(aCmd, "leg")) {
1255 } else if (!strcmp(aCmd, "load-route-wpt")) {
1256 loadRouteWaypoint();
1257 } else if (!strcmp(aCmd, "nearest")) {
1259 } else if (!strcmp(aCmd, "search")) {
1260 _searchNames = false;
1262 } else if (!strcmp(aCmd, "search-names")) {
1263 _searchNames = true;
1265 } else if (!strcmp(aCmd, "next")) {
1267 } else if (!strcmp(aCmd, "previous")) {
1269 } else if (!strcmp(aCmd, "define-user-wpt")) {
1271 } else if (!strcmp(aCmd, "route-insert-before")) {
1272 int index = _scratchNode->getIntValue("index");
1273 if (index < 0 || (_routeMgr->numWaypts() == 0)) {
1274 index = _routeMgr->numWaypts();
1275 } else if (index >= _routeMgr->numWaypts()) {
1276 SG_LOG(SG_INSTR, SG_WARN, "GPS:route-insert-before, bad index:" << index);
1280 insertWaypointAtIndex(index);
1281 } else if (!strcmp(aCmd, "route-insert-after")) {
1282 int index = _scratchNode->getIntValue("index");
1283 if (index < 0 || (_routeMgr->numWaypts() == 0)) {
1284 index = _routeMgr->numWaypts();
1285 } else if (index >= _routeMgr->numWaypts()) {
1286 SG_LOG(SG_INSTR, SG_WARN, "GPS:route-insert-after, bad index:" << index);
1292 insertWaypointAtIndex(index);
1293 } else if (!strcmp(aCmd, "route-delete")) {
1294 int index = _scratchNode->getIntValue("index");
1296 index = _routeMgr->numWaypts();
1297 } else if (index >= _routeMgr->numWaypts()) {
1298 SG_LOG(SG_INSTR, SG_WARN, "GPS:route-delete, bad index:" << index);
1302 removeWaypointAtIndex(index);
1304 SG_LOG(SG_INSTR, SG_WARN, "GPS:unrecognized command:" << aCmd);
1308 void GPS::clearScratch()
1310 _scratchPos = SGGeod::fromDegFt(-9999.0, -9999.0, -9999.0);
1311 _scratchValid = false;
1312 _scratchNode->setStringValue("type", "");
1313 _scratchNode->setStringValue("query", "");
1316 bool GPS::isScratchPositionValid() const
1318 if ((_scratchPos.getLongitudeDeg() < -9990.0) ||
1319 (_scratchPos.getLatitudeDeg() < -9990.0)) {
1326 void GPS::directTo()
1328 if (!isScratchPositionValid()) {
1333 _wp0_position = _indicated_pos;
1334 _currentWaypt = new BasicWaypt(_scratchPos, _scratchNode->getStringValue("ident"), NULL);
1341 void GPS::loadRouteWaypoint()
1343 _scratchValid = false;
1344 // if (!_routeMgr->isRouteActive()) {
1345 // SG_LOG(SG_INSTR, SG_WARN, "GPS:loadWaypoint: no active route");
1349 int index = _scratchNode->getIntValue("index", -9999);
1352 if ((index < 0) || (index >= _routeMgr->numWaypts())) { // no index supplied, use current wp
1353 index = _routeMgr->currentIndex();
1356 _searchIsRoute = true;
1357 setScratchFromRouteWaypoint(index);
1360 void GPS::setScratchFromRouteWaypoint(int aIndex)
1362 assert(_searchIsRoute);
1363 if ((aIndex < 0) || (aIndex >= _routeMgr->numWaypts())) {
1364 SG_LOG(SG_INSTR, SG_WARN, "GPS:setScratchFromRouteWaypoint: route-index out of bounds");
1368 _searchResultIndex = aIndex;
1369 WayptRef wp = _routeMgr->wayptAtIndex(aIndex);
1370 _scratchNode->setStringValue("ident", wp->ident());
1371 _scratchPos = wp->position();
1372 _scratchValid = true;
1373 _scratchNode->setIntValue("index", aIndex);
1376 void GPS::loadNearest()
1378 string sty(_scratchNode->getStringValue("type"));
1379 FGPositioned::Type ty = FGPositioned::typeFromName(sty);
1380 if (ty == FGPositioned::INVALID) {
1381 SG_LOG(SG_INSTR, SG_WARN, "GPS:loadNearest: request type is invalid:" << sty);
1385 auto_ptr<FGPositioned::Filter> f(createFilter(ty));
1386 int limitCount = _scratchNode->getIntValue("max-results", 1);
1387 double cutoffDistance = _scratchNode->getDoubleValue("cutoff-nm", 400.0);
1389 SGGeod searchPos = _indicated_pos;
1390 if (isScratchPositionValid()) {
1391 searchPos = _scratchPos;
1394 clearScratch(); // clear now, regardless of whether we find a match or not
1397 FGPositioned::findClosestN(searchPos, limitCount, cutoffDistance, f.get());
1398 _searchResultIndex = 0;
1399 _searchIsRoute = false;
1401 if (_searchResults.empty()) {
1402 SG_LOG(SG_INSTR, SG_INFO, "GPS:loadNearest: no matches at all");
1406 setScratchFromCachedSearchResult();
1409 bool GPS::SearchFilter::pass(FGPositioned* aPos) const
1411 switch (aPos->type()) {
1412 case FGPositioned::AIRPORT:
1413 // heliport and seaport too?
1414 case FGPositioned::VOR:
1415 case FGPositioned::NDB:
1416 case FGPositioned::FIX:
1417 case FGPositioned::TACAN:
1418 case FGPositioned::WAYPOINT:
1425 FGPositioned::Type GPS::SearchFilter::minType() const
1427 return FGPositioned::AIRPORT;
1430 FGPositioned::Type GPS::SearchFilter::maxType() const
1432 return FGPositioned::WAYPOINT;
1435 FGPositioned::Filter* GPS::createFilter(FGPositioned::Type aTy)
1437 if (aTy == FGPositioned::AIRPORT) {
1438 return new FGAirport::HardSurfaceFilter(_config.minRunwayLengthFt());
1441 // if we were passed INVALID, assume it means 'all types interesting to a GPS'
1442 if (aTy == FGPositioned::INVALID) {
1443 return new SearchFilter;
1446 return new FGPositioned::TypeFilter(aTy);
1451 // parse search terms into local members, and exec the first search
1452 string sty(_scratchNode->getStringValue("type"));
1453 _searchType = FGPositioned::typeFromName(sty);
1454 _searchQuery = _scratchNode->getStringValue("query");
1455 if (_searchQuery.empty()) {
1456 SG_LOG(SG_INSTR, SG_WARN, "empty GPS search query");
1461 _searchExact = _scratchNode->getBoolValue("exact", true);
1462 _searchResultIndex = 0;
1463 _searchIsRoute = false;
1465 auto_ptr<FGPositioned::Filter> f(createFilter(_searchType));
1467 _searchResults = FGPositioned::findAllWithName(_searchQuery, f.get(), _searchExact);
1469 _searchResults = FGPositioned::findAllWithIdent(_searchQuery, f.get(), _searchExact);
1472 bool orderByRange = _scratchNode->getBoolValue("order-by-distance", true);
1474 FGPositioned::sortByRange(_searchResults, _indicated_pos);
1477 if (_searchResults.empty()) {
1482 setScratchFromCachedSearchResult();
1485 bool GPS::getScratchHasNext() const
1488 if (_searchIsRoute) {
1489 lastResult = _routeMgr->numWaypts() - 1;
1491 lastResult = (int) _searchResults.size() - 1;
1494 if (lastResult < 0) { // search array might be empty
1498 return (_searchResultIndex < lastResult);
1501 void GPS::setScratchFromCachedSearchResult()
1503 int index = _searchResultIndex;
1505 if ((index < 0) || (index >= (int) _searchResults.size())) {
1506 SG_LOG(SG_INSTR, SG_WARN, "GPS:setScratchFromCachedSearchResult: index out of bounds:" << index);
1510 setScratchFromPositioned(_searchResults[index], index);
1513 void GPS::setScratchFromPositioned(FGPositioned* aPos, int aIndex)
1518 _scratchPos = aPos->geod();
1519 _scratchNode->setStringValue("name", aPos->name());
1520 _scratchNode->setStringValue("ident", aPos->ident());
1521 _scratchNode->setStringValue("type", FGPositioned::nameForType(aPos->type()));
1524 _scratchNode->setIntValue("index", aIndex);
1527 _scratchValid = true;
1528 _scratchNode->setIntValue("result-count", _searchResults.size());
1530 switch (aPos->type()) {
1531 case FGPositioned::VOR:
1532 _scratchNode->setDoubleValue("frequency-mhz", static_cast<FGNavRecord*>(aPos)->get_freq() / 100.0);
1535 case FGPositioned::NDB:
1536 _scratchNode->setDoubleValue("frequency-khz", static_cast<FGNavRecord*>(aPos)->get_freq() / 100.0);
1539 case FGPositioned::AIRPORT:
1540 addAirportToScratch((FGAirport*)aPos);
1548 // look for being on the route and set?
1551 void GPS::addAirportToScratch(FGAirport* aAirport)
1553 for (unsigned int r=0; r<aAirport->numRunways(); ++r) {
1554 SGPropertyNode* rwyNd = _scratchNode->getChild("runways", r, true);
1555 FGRunway* rwy = aAirport->getRunwayByIndex(r);
1556 // TODO - filter out unsuitable runways in the future
1557 // based on config again
1559 rwyNd->setStringValue("id", rwy->ident().c_str());
1560 rwyNd->setIntValue("length-ft", rwy->lengthFt());
1561 rwyNd->setIntValue("width-ft", rwy->widthFt());
1562 rwyNd->setIntValue("heading-deg", rwy->headingDeg());
1563 // map surface code to a string
1564 // TODO - lighting information
1567 rwyNd->setDoubleValue("ils-frequency-mhz", rwy->ILS()->get_freq() / 100.0);
1569 } // of runways iteration
1573 void GPS::selectOBSMode()
1575 if (!isScratchPositionValid()) {
1579 SG_LOG(SG_INSTR, SG_INFO, "GPS switching to OBS mode");
1582 _currentWaypt = new BasicWaypt(_scratchPos, _scratchNode->getStringValue("ident"), NULL);
1583 _wp0_position = _indicated_pos;
1587 void GPS::selectLegMode()
1589 if (_mode == "leg") {
1593 if (!_routeMgr->isRouteActive()) {
1594 SG_LOG(SG_INSTR, SG_WARN, "GPS:selectLegMode: no active route");
1598 SG_LOG(SG_INSTR, SG_INFO, "GPS switching to LEG mode");
1601 // depending on the situation, this will either get over-written
1602 // in routeManagerSequenced or not; either way it does no harm to
1604 _wp0_position = _indicated_pos;
1606 // not really sequenced, but does all the work of updating wp0/1
1607 routeManagerSequenced();
1610 void GPS::nextResult()
1612 if (!getScratchHasNext()) {
1617 if (_searchIsRoute) {
1618 setScratchFromRouteWaypoint(++_searchResultIndex);
1620 ++_searchResultIndex;
1621 setScratchFromCachedSearchResult();
1625 void GPS::previousResult()
1627 if (_searchResultIndex <= 0) {
1632 --_searchResultIndex;
1634 if (_searchIsRoute) {
1635 setScratchFromRouteWaypoint(_searchResultIndex);
1637 setScratchFromCachedSearchResult();
1641 void GPS::defineWaypoint()
1643 if (!isScratchPositionValid()) {
1644 SG_LOG(SG_INSTR, SG_WARN, "GPS:defineWaypoint: invalid lat/lon");
1648 string ident = _scratchNode->getStringValue("ident");
1649 if (ident.size() < 2) {
1650 SG_LOG(SG_INSTR, SG_WARN, "GPS:defineWaypoint: waypoint identifier must be at least two characters");
1654 // check for duplicate idents
1655 FGPositioned::TypeFilter f(FGPositioned::WAYPOINT);
1656 FGPositioned::List dups = FGPositioned::findAllWithIdent(ident, &f);
1657 if (!dups.empty()) {
1658 SG_LOG(SG_INSTR, SG_WARN, "GPS:defineWaypoint: non-unique waypoint identifier, ho-hum");
1661 SG_LOG(SG_INSTR, SG_INFO, "GPS:defineWaypoint: creating waypoint:" << ident);
1662 FGPositionedRef wpt = FGPositioned::createUserWaypoint(ident, _scratchPos);
1663 _searchResults.clear();
1664 _searchResults.push_back(wpt);
1665 setScratchFromPositioned(wpt.get(), -1);
1668 void GPS::insertWaypointAtIndex(int aIndex)
1670 // note we do allow index = routeMgr->size(), that's an append
1671 if ((aIndex < 0) || (aIndex > _routeMgr->numWaypts())) {
1672 throw sg_range_exception("GPS::insertWaypointAtIndex: index out of bounds");
1675 if (!isScratchPositionValid()) {
1676 SG_LOG(SG_INSTR, SG_WARN, "GPS:insertWaypointAtIndex: invalid lat/lon");
1680 string ident = _scratchNode->getStringValue("ident");
1682 WayptRef wpt = new BasicWaypt(_scratchPos, ident, NULL);
1683 _routeMgr->insertWayptAtIndex(wpt, aIndex);
1686 void GPS::removeWaypointAtIndex(int aIndex)
1688 if ((aIndex < 0) || (aIndex >= _routeMgr->numWaypts())) {
1689 throw sg_range_exception("GPS::removeWaypointAtIndex: index out of bounds");
1692 _routeMgr->removeWayptAtIndex(aIndex);
1695 void GPS::tieSGGeod(SGPropertyNode* aNode, SGGeod& aRef,
1696 const char* lonStr, const char* latStr, const char* altStr)
1698 tie(aNode, lonStr, SGRawValueMethods<SGGeod, double>(aRef, &SGGeod::getLongitudeDeg, &SGGeod::setLongitudeDeg));
1699 tie(aNode, latStr, SGRawValueMethods<SGGeod, double>(aRef, &SGGeod::getLatitudeDeg, &SGGeod::setLatitudeDeg));
1702 tie(aNode, altStr, SGRawValueMethods<SGGeod, double>(aRef, &SGGeod::getElevationFt, &SGGeod::setElevationFt));
1706 void GPS::tieSGGeodReadOnly(SGPropertyNode* aNode, SGGeod& aRef,
1707 const char* lonStr, const char* latStr, const char* altStr)
1709 tie(aNode, lonStr, SGRawValueMethods<SGGeod, double>(aRef, &SGGeod::getLongitudeDeg, NULL));
1710 tie(aNode, latStr, SGRawValueMethods<SGGeod, double>(aRef, &SGGeod::getLatitudeDeg, NULL));
1713 tie(aNode, altStr, SGRawValueMethods<SGGeod, double>(aRef, &SGGeod::getElevationFt, NULL));