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.
15 #include "Main/fg_props.hxx"
16 #include "Main/globals.hxx" // for get_subsystem
17 #include "Main/util.hxx" // for fgLowPass
18 #include "Navaids/positioned.hxx"
19 #include "Navaids/navrecord.hxx"
20 #include "Airports/simple.hxx"
21 #include "Airports/runways.hxx"
22 #include "Autopilot/route_mgr.hxx"
24 #include <simgear/math/sg_random.h>
25 #include <simgear/sg_inlines.h>
26 #include <simgear/math/sg_geodesy.hxx>
31 ///////////////////////////////////////////////////////////////////
33 void SGGeodProperty::init(SGPropertyNode* base, const char* lonStr, const char* latStr, const char* altStr)
35 _lon = base->getChild(lonStr, 0, true);
36 _lat = base->getChild(latStr, 0, true);
38 _alt = base->getChild(altStr, 0, true);
42 void SGGeodProperty::init(const char* lonStr, const char* latStr, const char* altStr)
44 _lon = fgGetNode(lonStr, true);
45 _lat = fgGetNode(latStr, true);
47 _alt = fgGetNode(altStr, true);
51 void SGGeodProperty::clear()
53 _lon = _lat = _alt = NULL;
56 void SGGeodProperty::operator=(const SGGeod& geod)
58 _lon->setDoubleValue(geod.getLongitudeDeg());
59 _lat->setDoubleValue(geod.getLatitudeDeg());
61 _alt->setDoubleValue(geod.getElevationFt());
65 SGGeod SGGeodProperty::get() const
67 double lon = _lon->getDoubleValue(),
68 lat = _lat->getDoubleValue();
70 return SGGeod::fromDegFt(lon, lat, _alt->getDoubleValue());
72 return SGGeod::fromDeg(lon,lat);
76 static void tieSGGeod(SGPropertyNode* aNode, SGGeod& aRef,
77 const char* lonStr, const char* latStr, const char* altStr)
79 aNode->tie(lonStr, SGRawValueMethods<SGGeod, double>(aRef, &SGGeod::getLongitudeDeg, &SGGeod::setLongitudeDeg));
80 aNode->tie(latStr, SGRawValueMethods<SGGeod, double>(aRef, &SGGeod::getLatitudeDeg, &SGGeod::setLatitudeDeg));
83 aNode->tie(altStr, SGRawValueMethods<SGGeod, double>(aRef, &SGGeod::getElevationFt, &SGGeod::setElevationFt));
87 static void tieSGGeodReadOnly(SGPropertyNode* aNode, SGGeod& aRef,
88 const char* lonStr, const char* latStr, const char* altStr)
90 aNode->tie(lonStr, SGRawValueMethods<SGGeod, double>(aRef, &SGGeod::getLongitudeDeg, NULL));
91 aNode->tie(latStr, SGRawValueMethods<SGGeod, double>(aRef, &SGGeod::getLatitudeDeg, NULL));
94 aNode->tie(altStr, SGRawValueMethods<SGGeod, double>(aRef, &SGGeod::getElevationFt, NULL));
98 static const char* makeTTWString(double TTW)
100 if ((TTW <= 0.0) || (TTW >= 356400.5)) { // 99 hours
104 unsigned int TTW_seconds = (int) (TTW + 0.5);
105 unsigned int TTW_minutes = 0;
106 unsigned int TTW_hours = 0;
107 static char TTW_str[9];
108 TTW_hours = TTW_seconds / 3600;
109 TTW_minutes = (TTW_seconds / 60) % 60;
110 TTW_seconds = TTW_seconds % 60;
111 snprintf(TTW_str, 9, "%02d:%02d:%02d",
112 TTW_hours, TTW_minutes, TTW_seconds);
116 /////////////////////////////////////////////////////////////////////////////
118 class GPSListener : public SGPropertyChangeListener
121 GPSListener(GPS *m) :
125 virtual void valueChanged (SGPropertyNode * prop)
132 if (prop == _gps->_route_current_wp_node) {
133 _gps->routeManagerSequenced();
134 } else if (prop == _gps->_route_active_node) {
135 _gps->routeActivated();
136 } else if (prop == _gps->_ref_navaid_id_node) {
137 _gps->referenceNavaidSet(prop->getStringValue(""));
143 void setGuard(bool g) {
148 bool _guard; // re-entrancy guard
151 ////////////////////////////////////////////////////////////////////////////
153 * Helper to monitor for Nasal or other code accessing properties we haven't
154 * defined. For the moment we complain about all such activites, since various
155 * users assume all kinds of weird, wonderful and non-existent interfaces.
158 class DeprecatedPropListener : public SGPropertyChangeListener
161 DeprecatedPropListener(SGPropertyNode* gps)
163 _parents.insert(gps);
164 SGPropertyNode* wp = gps->getChild("wp");
166 _parents.insert(wp->getChild("wp", 0));
167 _parents.insert(wp->getChild("wp", 1));
169 std::set<SGPropertyNode*>::iterator it;
170 for (it = _parents.begin(); it != _parents.end(); ++it) {
171 (*it)->addChangeListener(this);
175 virtual void valueChanged (SGPropertyNode * prop)
179 virtual void childAdded (SGPropertyNode * parent, SGPropertyNode * child)
181 if (isDeprecated(parent, child)) {
182 SG_LOG(SG_INSTR, SG_WARN, "GPS: someone accessed a deprecated property:"
183 << child->getPath(true));
187 bool isDeprecated(SGPropertyNode * parent, SGPropertyNode * child) const
189 if (_parents.count(parent) < 1) {
193 // no child exclusions yet
197 std::set<SGPropertyNode*> _parents;
200 ////////////////////////////////////////////////////////////////////////////
201 // configuration helper object
203 GPS::Config::Config() :
204 _enableTurnAnticipation(true),
205 _turnRate(3.0), // degrees-per-second, so 180 degree turn takes 60 seconds
206 _overflightArmDistance(0.5),
207 _waypointAlertTime(30.0),
208 _tuneRadio1ToRefVor(false),
209 _minRunwayLengthFt(0.0),
210 _requireHardSurface(true),
211 _cdiMaxDeflectionNm(-1), // default to angular mode
212 _driveAutopilot(true)
214 _enableTurnAnticipation = false;
215 _extCourseSource = fgGetNode("/instrumentation/nav[0]/radials/selected-deg", true);
218 void GPS::Config::init(SGPropertyNode* aCfgNode)
220 aCfgNode->tie("turn-rate-deg-sec", SGRawValuePointer<double>(&_turnRate));
221 aCfgNode->tie("turn-anticipation", SGRawValuePointer<bool>(&_enableTurnAnticipation));
222 aCfgNode->tie("wpt-alert-time", SGRawValuePointer<double>(&_waypointAlertTime));
223 aCfgNode->tie("tune-nav-radio-to-ref-vor", SGRawValuePointer<bool>(&_tuneRadio1ToRefVor));
224 aCfgNode->tie("min-runway-length-ft", SGRawValuePointer<double>(&_minRunwayLengthFt));
225 aCfgNode->tie("hard-surface-runways-only", SGRawValuePointer<bool>(&_requireHardSurface));
227 aCfgNode->tie("course-source", SGRawValueMethods<GPS::Config, const char*>
228 (*this, &GPS::Config::getCourseSource, &GPS::Config::setCourseSource));
230 aCfgNode->tie("cdi-max-deflection-nm", SGRawValuePointer<double>(&_cdiMaxDeflectionNm));
231 aCfgNode->tie("drive-autopilot", SGRawValuePointer<bool>(&_driveAutopilot));
235 GPS::Config::getCourseSource() const
237 if (!_extCourseSource) {
241 return _extCourseSource->getPath(true);
245 GPS::Config::setCourseSource(const char* aPath)
247 SGPropertyNode* nd = fgGetNode(aPath, false);
249 SG_LOG(SG_INSTR, SG_WARN, "couldn't find course source at:" << aPath);
250 _extCourseSource = NULL;
253 _extCourseSource = nd;
257 GPS::Config::getExternalCourse() const
259 if (!_extCourseSource) {
263 return _extCourseSource->getDoubleValue();
267 GPS::Config::setExternalCourse(double aCourseDeg)
269 if (!_extCourseSource) {
273 _extCourseSource->setDoubleValue(aCourseDeg);
276 ////////////////////////////////////////////////////////////////////////////
278 GPS::GPS ( SGPropertyNode *node) :
280 _name(node->getStringValue("name", "gps")),
281 _num(node->getIntValue("number", 0)),
282 _computeTurnData(false),
283 _anticipateTurn(false),
295 _routeMgr = (FGRouteMgr*) globals->get_subsystem("route-manager");
299 branch = "/instrumentation/" + _name;
301 SGPropertyNode *node = fgGetNode(branch.c_str(), _num, true );
302 _config.init(node->getChild("config", 0, true));
304 _position.init("/position/longitude-deg", "/position/latitude-deg", "/position/altitude-ft");
305 _magvar_node = fgGetNode("/environment/magnetic-variation-deg", true);
306 _serviceable_node = node->getChild("serviceable", 0, true);
307 _serviceable_node->setBoolValue(true);
308 _electrical_node = fgGetNode("/systems/electrical/outputs/gps", true);
311 node->tie("selected-course-deg", SGRawValueMethods<GPS, double>(*this, &GPS::getSelectedCourse, NULL));
313 _raim_node = node->getChild("raim", 0, true);
315 tieSGGeodReadOnly(node, _indicated_pos, "indicated-longitude-deg",
316 "indicated-latitude-deg", "indicated-altitude-ft");
318 node->tie("indicated-vertical-speed", SGRawValueMethods<GPS, double>
319 (*this, &GPS::getVerticalSpeed, NULL));
320 node->tie("indicated-track-true-deg", SGRawValueMethods<GPS, double>
321 (*this, &GPS::getTrueTrack, NULL));
322 node->tie("indicated-track-magnetic-deg", SGRawValueMethods<GPS, double>
323 (*this, &GPS::getMagTrack, NULL));
324 node->tie("indicated-ground-speed-kt", SGRawValueMethods<GPS, double>
325 (*this, &GPS::getGroundspeedKts, NULL));
327 _odometer_node = node->getChild("odometer", 0, true);
328 _trip_odometer_node = node->getChild("trip-odometer", 0, true);
329 _true_bug_error_node = node->getChild("true-bug-error-deg", 0, true);
330 _magnetic_bug_error_node = node->getChild("magnetic-bug-error-deg", 0, true);
334 node->tie("mode", SGRawValueMethods<GPS, const char*>(*this, &GPS::getMode, NULL));
335 node->tie("command", SGRawValueMethods<GPS, const char*>(*this, &GPS::getCommand, &GPS::setCommand));
337 _scratchNode = node->getChild("scratch", 0, true);
338 tieSGGeod(_scratchNode, _scratchPos, "longitude-deg", "latitude-deg", "altitude-ft");
339 _scratchNode->tie("valid", SGRawValueMethods<GPS, bool>(*this, &GPS::getScratchValid, NULL));
340 _scratchNode->tie("distance-nm", SGRawValueMethods<GPS, double>(*this, &GPS::getScratchDistance, NULL));
341 _scratchNode->tie("true-bearing-deg", SGRawValueMethods<GPS, double>(*this, &GPS::getScratchTrueBearing, NULL));
342 _scratchNode->tie("mag-bearing-deg", SGRawValueMethods<GPS, double>(*this, &GPS::getScratchMagBearing, NULL));
343 _scratchNode->tie("has-next", SGRawValueMethods<GPS, bool>(*this, &GPS::getScratchHasNext, NULL));
344 _scratchValid = false;
346 // waypoint data (including various historical things)
347 SGPropertyNode *wp_node = node->getChild("wp", 0, true);
348 SGPropertyNode *wp0_node = wp_node->getChild("wp", 0, true);
349 SGPropertyNode *wp1_node = wp_node->getChild("wp", 1, true);
351 tieSGGeodReadOnly(wp0_node, _wp0_position, "longitude-deg", "latitude-deg", "altitude-ft");
352 wp0_node->tie("ID", SGRawValueMethods<GPS, const char*>
353 (*this, &GPS::getWP0Ident, NULL));
354 wp0_node->tie("name", SGRawValueMethods<GPS, const char*>
355 (*this, &GPS::getWP0Name, NULL));
357 tieSGGeodReadOnly(wp1_node, _wp1_position, "longitude-deg", "latitude-deg", "altitude-ft");
358 wp1_node->tie("ID", SGRawValueMethods<GPS, const char*>
359 (*this, &GPS::getWP1Ident, NULL));
360 wp1_node->tie("name", SGRawValueMethods<GPS, const char*>
361 (*this, &GPS::getWP1Name, NULL));
363 // for compatability, alias selected course down to wp/wp[1]/desired-course-deg
364 SGPropertyNode* wp1Crs = wp1_node->getChild("desired-course-deg", 0, true);
365 wp1Crs->alias(node->getChild("selected-course-deg"));
367 // _true_wp1_bearing_error_node =
368 // wp1_node->getChild("true-bearing-error-deg", 0, true);
369 // _magnetic_wp1_bearing_error_node =
370 // wp1_node->getChild("magnetic-bearing-error-deg", 0, true);
372 wp1_node->tie("distance-nm", SGRawValueMethods<GPS, double>
373 (*this, &GPS::getWP1Distance, NULL));
374 wp1_node->tie("bearing-true-deg", SGRawValueMethods<GPS, double>
375 (*this, &GPS::getWP1Bearing, NULL));
376 wp1_node->tie("bearing-mag-deg", SGRawValueMethods<GPS, double>
377 (*this, &GPS::getWP1MagBearing, NULL));
378 wp1_node->tie("TTW-sec", SGRawValueMethods<GPS, double>
379 (*this, &GPS::getWP1TTW, NULL));
380 wp1_node->tie("TTW", SGRawValueMethods<GPS, const char*>
381 (*this, &GPS::getWP1TTWString, NULL));
383 wp1_node->tie("course-deviation-deg", SGRawValueMethods<GPS, double>
384 (*this, &GPS::getWP1CourseDeviation, NULL));
385 wp1_node->tie("course-error-nm", SGRawValueMethods<GPS, double>
386 (*this, &GPS::getWP1CourseErrorNm, NULL));
387 wp1_node->tie("to-flag", SGRawValueMethods<GPS, bool>
388 (*this, &GPS::getWP1ToFlag, NULL));
389 wp1_node->tie("from-flag", SGRawValueMethods<GPS, bool>
390 (*this, &GPS::getWP1FromFlag, NULL));
392 _tracking_bug_node = node->getChild("tracking-bug", 0, true);
394 // leg properties (only valid in DTO/LEG modes, not OBS)
395 wp_node->tie("leg-distance-nm", SGRawValueMethods<GPS, double>(*this, &GPS::getLegDistance, NULL));
396 wp_node->tie("leg-true-course-deg", SGRawValueMethods<GPS, double>(*this, &GPS::getLegCourse, NULL));
397 wp_node->tie("leg-mag-course-deg", SGRawValueMethods<GPS, double>(*this, &GPS::getLegMagCourse, NULL));
398 wp_node->tie("alt-dist-ratio", SGRawValueMethods<GPS, double>(*this, &GPS::getAltDistanceRatio, NULL));
401 SGPropertyNode_ptr ref_navaid = node->getChild("ref-navaid", 0, true);
402 _ref_navaid_id_node = ref_navaid->getChild("id", 0, true);
403 _ref_navaid_name_node = ref_navaid->getChild("name", 0, true);
404 _ref_navaid_bearing_node = ref_navaid->getChild("bearing-deg", 0, true);
405 _ref_navaid_frequency_node = ref_navaid->getChild("frequency-mhz", 0, true);
406 _ref_navaid_distance_node = ref_navaid->getChild("distance-nm", 0, true);
407 _ref_navaid_mag_bearing_node = ref_navaid->getChild("mag-bearing-deg", 0, true);
408 _ref_navaid_elapsed = 0.0;
409 _ref_navaid_set = false;
412 // should these move to the route manager?
413 _routeDistanceNm = node->getChild("route-distance-nm", 0, true);
414 _routeETE = node->getChild("ETE", 0, true);
416 // disable auto-sequencing in the route manager; we'll deal with it
417 // ourselves using turn anticipation
418 SGPropertyNode_ptr autoSeq = fgGetNode("/autopilot/route-manager/auto-sequence", true);
419 autoSeq->setBoolValue(false);
421 // add listener to various things
422 _listener = new GPSListener(this);
423 _route_current_wp_node = fgGetNode("/autopilot/route-manager/current-wp", true);
424 _route_current_wp_node->addChangeListener(_listener);
425 _route_active_node = fgGetNode("/autopilot/route-manager/active", true);
426 _route_active_node->addChangeListener(_listener);
427 _ref_navaid_id_node->addChangeListener(_listener);
429 // navradio slaving properties
430 node->tie("cdi-deflection", SGRawValueMethods<GPS,double>
431 (*this, &GPS::getCDIDeflection));
433 SGPropertyNode* toFlag = node->getChild("to-flag", 0, true);
434 toFlag->alias(wp1_node->getChild("to-flag"));
436 // autopilot drive properties
437 _apTrueHeading = fgGetNode("/autopilot/settings/true-heading-deg",true);
438 _apTargetAltitudeFt = fgGetNode("/autopilot/settings/target-altitude-ft", true);
439 _apAltitudeLock = fgGetNode("/autopilot/locks/altitude", true);
442 _realismSimpleGps = fgGetNode("/sim/realism/simple-gps", true);
443 if (!_realismSimpleGps->hasValue()) {
444 _realismSimpleGps->setBoolValue(true);
447 // last thing, add the deprecated prop watcher
448 new DeprecatedPropListener(node);
450 // initialise in OBS mode, with waypt set to the nearest airport.
451 // keep in mind at this point, _last_valid is not set
453 auto_ptr<FGPositioned::Filter> f(createFilter(FGPositioned::AIRPORT));
454 FGPositionedRef apt = FGPositioned::findClosest(_position.get(), 20.0, f.get());
456 setScratchFromPositioned(apt, 0);
465 _last_speed_kts = 0.0;
466 _last_pos = SGGeod();
467 _indicated_pos = SGGeod();
468 _last_vertical_speed = 0.0;
469 _last_true_track = 0.0;
471 _raim_node->setDoubleValue(0.0);
472 _indicated_pos = SGGeod();
474 _wp1TrueBearing = 0.0;
475 _wp1_position = SGGeod();
476 _odometer_node->setDoubleValue(0);
477 _trip_odometer_node->setDoubleValue(0);
478 _tracking_bug_node->setDoubleValue(0);
479 _true_bug_error_node->setDoubleValue(0);
480 _magnetic_bug_error_node->setDoubleValue(0);
484 GPS::update (double delta_time_sec)
486 if (!_realismSimpleGps->getBoolValue()) {
487 // If it's off, don't bother.
488 if (!_serviceable_node->getBoolValue() || !_electrical_node->getBoolValue()) {
494 if (delta_time_sec <= 0.0) {
495 return; // paused, don't bother
497 // TODO: Add noise and other errors.
500 // Bias and random error
501 double random_factor = sg_random();
502 double random_error = 1.4;
503 double error_radius = 5.1;
504 double bias_max_radius = 5.1;
505 double random_max_radius = 1.4;
507 bias_length += (random_factor-0.5) * 1.0e-3;
508 if (bias_length <= 0.0) bias_length = 0.0;
509 else if (bias_length >= bias_max_radius) bias_length = bias_max_radius;
510 bias_angle += (random_factor-0.5) * 1.0e-3;
511 if (bias_angle <= 0.0) bias_angle = 0.0;
512 else if (bias_angle >= 360.0) bias_angle = 360.0;
514 double random_length = random_factor * random_max_radius;
515 double random_angle = random_factor * 360.0;
517 double bias_x = bias_length * cos(bias_angle * SG_PI / 180.0);
518 double bias_y = bias_length * sin(bias_angle * SG_PI / 180.0);
519 double random_x = random_length * cos(random_angle * SG_PI / 180.0);
520 double random_y = random_length * sin(random_angle * SG_PI / 180.0);
521 double error_x = bias_x + random_x;
522 double error_y = bias_y + random_y;
523 double error_length = sqrt(error_x*error_x + error_y*error_y);
524 double error_angle = atan(error_y / error_x) * 180.0 / SG_PI;
529 geo_direct_wgs_84 ( altitude_m, latitude_deg,
530 longitude_deg, error_angle,
531 error_length, &lat2, &lon2,
533 //cout << lat2 << " " << lon2 << endl;
534 printf("%f %f \n", bias_length, bias_angle);
535 printf("%3.7f %3.7f \n", lat2, lon2);
536 printf("%f %f \n", error_length, error_angle);
539 _raim_node->setDoubleValue(1.0);
540 _indicated_pos = _position.get();
543 updateWithValid(delta_time_sec);
547 if (_route_active_node->getBoolValue()) {
548 // GPS init with active route
549 SG_LOG(SG_INSTR, SG_INFO, "GPS init with active route");
550 _listener->setGuard(true);
552 routeManagerSequenced();
553 _listener->setGuard(false);
557 _last_pos = _indicated_pos;
561 GPS::updateWithValid(double dt)
567 if (_mode == "obs") {
568 _selectedCourse = _config.getExternalCourse();
575 updateReferenceNavaid(dt);
581 GPS::updateBasicData(double dt)
585 SGGeodesy::inverse(_last_pos, _indicated_pos, _last_true_track, track2_deg, distance_m );
587 double speed_kt = ((distance_m * SG_METER_TO_NM) * ((1 / dt) * 3600.0));
588 double vertical_speed_mpm = ((_indicated_pos.getElevationM() - _last_pos.getElevationM()) * 60 / dt);
589 _last_vertical_speed = vertical_speed_mpm * SG_METER_TO_FEET;
591 speed_kt = fgGetLowPass(_last_speed_kts, speed_kt, dt/20.0);
592 _last_speed_kts = speed_kt;
594 double odometer = _odometer_node->getDoubleValue();
595 _odometer_node->setDoubleValue(odometer + distance_m * SG_METER_TO_NM);
596 odometer = _trip_odometer_node->getDoubleValue();
597 _trip_odometer_node->setDoubleValue(odometer + distance_m * SG_METER_TO_NM);
601 GPS::updateTrackingBug()
603 double tracking_bug = _tracking_bug_node->getDoubleValue();
604 double true_bug_error = tracking_bug - getTrueTrack();
605 double magnetic_bug_error = tracking_bug - getMagTrack();
607 // Get the errors into the (-180,180) range.
608 SG_NORMALIZE_RANGE(true_bug_error, -180.0, 180.0);
609 SG_NORMALIZE_RANGE(magnetic_bug_error, -180.0, 180.0);
611 _true_bug_error_node->setDoubleValue(true_bug_error);
612 _magnetic_bug_error_node->setDoubleValue(magnetic_bug_error);
616 GPS::updateWaypoints()
619 SGGeodesy::inverse(_indicated_pos, _wp1_position, _wp1TrueBearing, az2,_wp1DistanceM);
622 void GPS::updateReferenceNavaid(double dt)
624 if (!_ref_navaid_set) {
625 _ref_navaid_elapsed += dt;
626 if (_ref_navaid_elapsed > 5.0) {
627 _ref_navaid_elapsed = 0.0;
629 FGPositioned::TypeFilter vorFilter(FGPositioned::VOR);
630 FGPositionedRef nav = FGPositioned::findClosest(_indicated_pos, 400.0, &vorFilter);
632 SG_LOG(SG_INSTR, SG_INFO, "GPS couldn't find a reference navid");
633 _ref_navaid_id_node->setStringValue("");
634 _ref_navaid_name_node->setStringValue("");
635 _ref_navaid_bearing_node->setDoubleValue(0.0);
636 _ref_navaid_mag_bearing_node->setDoubleValue(0.0);
637 _ref_navaid_distance_node->setDoubleValue(0.0);
638 _ref_navaid_frequency_node->setStringValue("");
639 } else if (nav != _ref_navaid) {
640 SG_LOG(SG_INSTR, SG_INFO, "GPS code selected new ref-navaid:" << nav->ident());
641 _listener->setGuard(true);
642 _ref_navaid_id_node->setStringValue(nav->ident().c_str());
643 _ref_navaid_name_node->setStringValue(nav->name().c_str());
644 FGNavRecord* vor = (FGNavRecord*) nav.ptr();
645 _ref_navaid_frequency_node->setDoubleValue(vor->get_freq() / 100.0);
646 _listener->setGuard(false);
649 // SG_LOG(SG_INSTR, SG_ALERT, "matched existing");
657 double trueCourse, distanceM, az2;
658 SGGeodesy::inverse(_indicated_pos, _ref_navaid->geod(), trueCourse, az2, distanceM);
659 _ref_navaid_distance_node->setDoubleValue(distanceM * SG_METER_TO_NM);
660 _ref_navaid_bearing_node->setDoubleValue(trueCourse);
661 _ref_navaid_mag_bearing_node->setDoubleValue(trueCourse - _magvar_node->getDoubleValue());
665 void GPS::referenceNavaidSet(const std::string& aNavaid)
668 // allow setting an empty string to restore normal nearest-vor selection
669 if (aNavaid.size() > 0) {
670 FGPositioned::TypeFilter vorFilter(FGPositioned::VOR);
671 _ref_navaid = FGPositioned::findClosestWithIdent(aNavaid,
672 _position.get(), &vorFilter);
675 SG_LOG(SG_INSTR, SG_ALERT, "GPS: unknown ref navaid:" << aNavaid);
680 _ref_navaid_set = true;
681 SG_LOG(SG_INSTR, SG_INFO, "GPS code set explict ref-navaid:" << _ref_navaid->ident());
682 _ref_navaid_id_node->setStringValue(_ref_navaid->ident().c_str());
683 _ref_navaid_name_node->setStringValue(_ref_navaid->name().c_str());
684 FGNavRecord* vor = (FGNavRecord*) _ref_navaid.ptr();
685 _ref_navaid_frequency_node->setDoubleValue(vor->get_freq() / 100.0);
688 _ref_navaid_set = false;
689 _ref_navaid_elapsed = 9999.0; // update next tick
693 void GPS::tuneNavRadios()
695 if (!_ref_navaid || !_config.tuneNavRadioToRefVor()) {
699 SGPropertyNode_ptr navRadio1 = fgGetNode("/instrumentation/nav", false);
704 FGNavRecord* vor = (FGNavRecord*) _ref_navaid.ptr();
705 SGPropertyNode_ptr freqs = navRadio1->getChild("frequencies");
706 freqs->setDoubleValue("selected-mhz", vor->get_freq() / 100.0);
709 void GPS::routeActivated()
711 if (_route_active_node->getBoolValue()) {
712 SG_LOG(SG_INSTR, SG_INFO, "GPS::route activated, switching to LEG mode");
714 } else if (_mode == "leg") {
715 SG_LOG(SG_INSTR, SG_INFO, "GPS::route deactivated, switching to OBS mode");
720 void GPS::routeManagerSequenced()
722 if (_mode != "leg") {
723 SG_LOG(SG_INSTR, SG_INFO, "GPS ignoring route sequencing, not in LEG mode");
727 int index = _routeMgr->currentWaypoint(),
728 count = _routeMgr->size();
729 if ((index < 1) || (index >= count)) {
730 SG_LOG(SG_INSTR, SG_ALERT, "GPS: malformed route, index=" << index);
734 SG_LOG(SG_INSTR, SG_INFO, "GPS waypoint index is now " << index);
735 SGWayPoint wp0(_routeMgr->get_waypoint(index - 1));
736 SGWayPoint wp1(_routeMgr->get_waypoint(index));
738 _wp0Ident = wp0.get_id();
739 _wp0Name = wp0.get_name();
740 _wp0_position = wp0.get_target();
742 _wp1Ident = wp1.get_id();
743 _wp1Name = wp1.get_name();
744 _wp1_position = wp1.get_target();
746 _selectedCourse = getLegMagCourse();
750 void GPS::updateTurn()
752 bool printProgress = false;
754 if (_computeTurnData) {
755 if (_last_speed_kts < 60) {
756 // need valid leg course and sensible ground speed to compute the turn
761 printProgress = true;
764 if (!_anticipateTurn) {
770 // find bearing to turn centre
771 double bearing, az2, distanceM;
772 SGGeodesy::inverse(_indicated_pos, _turnCentre, bearing, az2, distanceM);
773 double progress = computeTurnProgress(bearing);
776 SG_LOG(SG_INSTR, SG_INFO,"turn progress=" << progress);
779 if (!_inTurn && (progress > 0.0)) {
783 if (_inTurn && !_turnSequenced && (progress > 0.5)) {
784 _turnSequenced = true;
785 SG_LOG(SG_INSTR, SG_INFO, "turn passed midpoint, sequencing");
786 _routeMgr->sequence();
789 if (_inTurn && (progress >= 1.0)) {
794 // drive deviation and desired course
795 double desiredCourse = bearing - copysign(90, _turnAngle);
796 SG_NORMALIZE_RANGE(desiredCourse, 0.0, 360.0);
797 double deviationNm = (distanceM * SG_METER_TO_NM) - _turnRadius;
798 double deviationDeg = desiredCourse - getMagTrack();
799 deviationNm = copysign(deviationNm, deviationDeg);
801 //_wp1_course_deviation_node->setDoubleValue(deviationDeg);
802 //_wp1_course_error_nm_node->setDoubleValue(deviationNm);
803 //_cdiDeflectionNode->setDoubleValue(deviationDeg);
807 void GPS::updateOverflight()
809 if ((_wp1DistanceM * SG_METER_TO_NM) > _config.overflightArmDistanceNm()) {
813 if (getWP1ToFlag()) {
814 return; // still heading towards the WP
817 if (_mode == "dto") {
818 SG_LOG(SG_INSTR, SG_INFO, "GPS DTO reached destination point");
820 // check for wp1 being on active route - resume leg mode
821 if (_routeMgr->isRouteActive()) {
822 int index = _routeMgr->findWaypoint(_wp1_position);
824 SG_LOG(SG_INSTR, SG_INFO, "GPS DTO, resuming LEG mode at wp:" << index);
826 _routeMgr->jumpToIndex(index);
829 } else if (_mode == "leg") {
830 SG_LOG(SG_INSTR, SG_INFO, "GPS doing overflight sequencing");
831 _routeMgr->sequence();
832 } else if (_mode == "obs") {
833 // nothing to do here, TO/FROM will update but that's fine
836 _computeTurnData = true;
839 void GPS::beginTurn()
842 _turnSequenced = false;
843 SG_LOG(SG_INSTR, SG_INFO, "begining turn");
849 SG_LOG(SG_INSTR, SG_INFO, "ending turn");
850 _computeTurnData = true;
853 double GPS::computeTurnProgress(double aBearing) const
855 double startBearing = _turnStartBearing + copysign(90, _turnAngle);
856 return (aBearing - startBearing) / _turnAngle;
859 void GPS::computeTurnData()
861 _computeTurnData = false;
862 if (_mode != "leg") { // and approach modes in the future
863 _anticipateTurn = false;
867 int curIndex = _routeMgr->currentWaypoint();
868 if ((curIndex + 1) >= _routeMgr->size()) {
869 _anticipateTurn = false;
873 if (!_config.turnAnticipationEnabled()) {
874 _anticipateTurn = false;
878 _turnStartBearing = _selectedCourse;
879 // compute next leg course
880 SGWayPoint wp1(_routeMgr->get_waypoint(curIndex)),
881 wp2(_routeMgr->get_waypoint(curIndex + 1));
883 wp2.CourseAndDistance(wp1, &crs, &dist);
886 // compute offset bearing
887 _turnAngle = crs - _turnStartBearing;
888 SG_NORMALIZE_RANGE(_turnAngle, -180.0, 180.0);
889 double median = _turnStartBearing + (_turnAngle * 0.5);
890 double offsetBearing = median + copysign(90, _turnAngle);
891 SG_NORMALIZE_RANGE(offsetBearing, 0.0, 360.0);
893 SG_LOG(SG_INSTR, SG_INFO, "GPS computeTurnData: in=" << _turnStartBearing <<
894 ", out=" << crs << "; turnAngle=" << _turnAngle << ", median=" << median
895 << ", offset=" << offsetBearing);
897 SG_LOG(SG_INSTR, SG_INFO, "next leg is now:" << wp1.get_id() << "->" << wp2.get_id());
899 _turnPt = _wp1_position;
900 _anticipateTurn = true;
903 void GPS::updateTurnData()
905 // depends on ground speed, so needs to be updated per-frame
906 _turnRadius = computeTurnRadiusNm(_last_speed_kts);
908 // compute the turn centre, based on the turn radius.
909 // key thing is to understand that we're working a right-angle triangle,
910 // where the right-angle is the point we start the turn. From that point,
911 // one side is the inbound course to the turn pt, and the other is the
912 // perpendicular line, of length 'r', to the turn centre.
913 // the triangle's hypotenuse, which we need to find, is the distance from the
914 // turn pt to the turn center (in the direction of the offset bearing)
915 // note that d - _turnRadius tell us how much we're 'cutting' the corner.
917 double halfTurnAngle = fabs(_turnAngle * 0.5) * SG_DEGREES_TO_RADIANS;
918 double d = _turnRadius / cos(halfTurnAngle);
920 // SG_LOG(SG_INSTR, SG_INFO, "turnRadius=" << _turnRadius << ", d=" << d
921 // << " (cut distance=" << d - _turnRadius << ")");
923 double median = _turnStartBearing + (_turnAngle * 0.5);
924 double offsetBearing = median + copysign(90, _turnAngle);
925 SG_NORMALIZE_RANGE(offsetBearing, 0.0, 360.0);
928 SGGeodesy::direct(_turnPt, offsetBearing, d * SG_NM_TO_METER, _turnCentre, az2);
931 double GPS::computeTurnRadiusNm(double aGroundSpeedKts) const
933 // turn time is seconds to execute a 360 turn.
934 double turnTime = 360.0 / _config.turnRateDegSec();
936 // c is ground distance covered in that time (circumference of the circle)
937 double c = turnTime * (aGroundSpeedKts / 3600.0); // convert knts to nm/sec
939 // divide by 2PI to go from circumference -> radius
940 return c / (2 * M_PI);
943 void GPS::updateRouteData()
945 double totalDistance = _wp1DistanceM * SG_METER_TO_NM;
946 // walk all waypoints from wp2 to route end, and sum
947 for (int i=_routeMgr->currentWaypoint()+1; i<_routeMgr->size(); ++i) {
948 totalDistance += _routeMgr->get_waypoint(i).get_distance();
951 _routeDistanceNm->setDoubleValue(totalDistance * SG_METER_TO_NM);
952 if (_last_speed_kts > 1.0) {
953 double TTW = ((totalDistance * SG_METER_TO_NM) / _last_speed_kts) * 3600.0;
954 _routeETE->setStringValue(makeTTWString(TTW));
958 void GPS::driveAutopilot()
960 if (!_config.driveAutopilot() || !_realismSimpleGps->getBoolValue()) {
964 // FIXME: we want to set desired track, not heading, here
965 _apTrueHeading->setDoubleValue(getWP1Bearing());
968 void GPS::wp1Changed()
970 // update external HSI/CDI/NavDisplay/PFD/etc
971 _config.setExternalCourse(getLegMagCourse());
973 if (!_config.driveAutopilot()) {
977 double altFt = _wp1_position.getElevationFt();
978 if (altFt < -9990.0) {
979 _apTargetAltitudeFt->setDoubleValue(0.0);
980 _apAltitudeLock->setBoolValue(false);
982 _apTargetAltitudeFt->setDoubleValue(altFt);
983 _apAltitudeLock->setBoolValue(true);
987 /////////////////////////////////////////////////////////////////////////////
988 // property getter/setters
990 double GPS::getLegDistance() const
992 if (!_last_valid || (_mode == "obs")) {
996 return SGGeodesy::distanceNm(_wp0_position, _wp1_position);
999 double GPS::getLegCourse() const
1001 if (!_last_valid || (_mode == "obs")) {
1005 return SGGeodesy::courseDeg(_wp0_position, _wp1_position);
1008 double GPS::getLegMagCourse() const
1010 if (!_last_valid || (_mode == "obs")) {
1014 double m = getLegCourse() - _magvar_node->getDoubleValue();
1015 SG_NORMALIZE_RANGE(m, 0.0, 360.0);
1019 double GPS::getAltDistanceRatio() const
1021 if (!_last_valid || (_mode == "obs")) {
1025 double dist = SGGeodesy::distanceM(_wp0_position, _wp1_position);
1026 if ( dist <= 0.0 ) {
1030 double alt_difference_m = _wp0_position.getElevationM() - _wp1_position.getElevationM();
1031 return alt_difference_m / dist;
1034 double GPS::getMagTrack() const
1040 double m = getTrueTrack() - _magvar_node->getDoubleValue();
1041 SG_NORMALIZE_RANGE(m, 0.0, 360.0);
1045 double GPS::getCDIDeflection() const
1052 if (_config.cdiDeflectionIsAngular()) {
1053 defl = getWP1CourseDeviation();
1054 SG_CLAMP_RANGE(defl, -10.0, 10.0); // as in navradio.cxx
1056 double fullScale = _config.cdiDeflectionLinearPeg();
1057 double normError = getWP1CourseErrorNm() / fullScale;
1058 SG_CLAMP_RANGE(normError, -1.0, 1.0);
1059 defl = normError * 10.0; // re-scale to navradio limits, i.e [-10.0 .. 10.0]
1065 const char* GPS::getWP0Ident() const
1067 if (!_last_valid || (_mode != "leg")) {
1071 return _wp0Ident.c_str();
1074 const char* GPS::getWP0Name() const
1076 if (!_last_valid || (_mode != "leg")) {
1080 return _wp0Name.c_str();
1083 const char* GPS::getWP1Ident() const
1089 return _wp1Ident.c_str();
1092 const char* GPS::getWP1Name() const
1098 return _wp1Name.c_str();
1101 double GPS::getWP1Distance() const
1107 return _wp1DistanceM * SG_METER_TO_NM;
1110 double GPS::getWP1TTW() const
1116 if (_last_speed_kts < 1.0) {
1120 return (getWP1Distance() / _last_speed_kts) * 3600.0;
1123 const char* GPS::getWP1TTWString() const
1129 return makeTTWString(getWP1TTW());
1132 double GPS::getWP1Bearing() const
1138 return _wp1TrueBearing;
1141 double GPS::getWP1MagBearing() const
1147 return _wp1TrueBearing - _magvar_node->getDoubleValue();
1150 double GPS::getWP1CourseDeviation() const
1156 double dev = getWP1MagBearing() - _selectedCourse;
1157 SG_NORMALIZE_RANGE(dev, -180.0, 180.0);
1159 if (fabs(dev) > 90.0) {
1160 // When the course is away from the waypoint,
1161 // it makes sense to change the sign of the deviation.
1163 SG_NORMALIZE_RANGE(dev, -90.0, 90.0);
1169 double GPS::getWP1CourseErrorNm() const
1175 double radDev = getWP1CourseDeviation() * SG_DEGREES_TO_RADIANS;
1176 double course_error_m = sin(radDev) * _wp1DistanceM;
1177 return course_error_m * SG_METER_TO_NM;
1180 bool GPS::getWP1ToFlag() const
1186 double dev = getWP1MagBearing() - _selectedCourse;
1187 SG_NORMALIZE_RANGE(dev, -180.0, 180.0);
1189 return (fabs(dev) < 90.0);
1192 bool GPS::getWP1FromFlag() const
1198 return !getWP1ToFlag();
1201 double GPS::getScratchDistance() const
1203 if (!_scratchValid) {
1207 return SGGeodesy::distanceNm(_indicated_pos, _scratchPos);
1210 double GPS::getScratchTrueBearing() const
1212 if (!_scratchValid) {
1216 return SGGeodesy::courseDeg(_indicated_pos, _scratchPos);
1219 double GPS::getScratchMagBearing() const
1221 if (!_scratchValid) {
1225 double crs = getScratchTrueBearing() - _magvar_node->getDoubleValue();
1226 SG_NORMALIZE_RANGE(crs, 0.0, 360.0);
1230 /////////////////////////////////////////////////////////////////////////////
1231 // command / scratch / search system
1233 void GPS::setCommand(const char* aCmd)
1235 SG_LOG(SG_INSTR, SG_INFO, "GPS command:" << aCmd);
1237 if (!strcmp(aCmd, "direct")) {
1239 } else if (!strcmp(aCmd, "obs")) {
1241 } else if (!strcmp(aCmd, "leg")) {
1243 } else if (!strcmp(aCmd, "load-route-wpt")) {
1244 loadRouteWaypoint();
1245 } else if (!strcmp(aCmd, "nearest")) {
1247 } else if (!strcmp(aCmd, "search")) {
1248 _searchNames = false;
1250 } else if (!strcmp(aCmd, "search-names")) {
1251 _searchNames = true;
1253 } else if (!strcmp(aCmd, "next")) {
1255 } else if (!strcmp(aCmd, "previous")) {
1257 } else if (!strcmp(aCmd, "define-user-wpt")) {
1260 SG_LOG(SG_INSTR, SG_WARN, "GPS:unrecognzied command:" << aCmd);
1264 void GPS::clearScratch()
1266 _scratchPos = SGGeod::fromDegFt(-9999.0, -9999.0, -9999.0);
1267 _scratchValid = false;
1268 _scratchNode->setStringValue("type", "");
1269 _scratchNode->setStringValue("query", "");
1272 bool GPS::isScratchPositionValid() const
1274 if ((_scratchPos.getLongitudeDeg() < -9990.0) ||
1275 (_scratchPos.getLatitudeDeg() < -9990.0)) {
1282 void GPS::directTo()
1284 if (!isScratchPositionValid()) {
1285 SG_LOG(SG_INSTR, SG_WARN, "invalid DTO lat/lon");
1289 _wp0_position = _indicated_pos;
1290 _wp1Ident = _scratchNode->getStringValue("ident");
1291 _wp1Name = _scratchNode->getStringValue("name");
1292 _wp1_position = _scratchPos;
1295 _selectedCourse = getLegMagCourse();
1301 void GPS::loadRouteWaypoint()
1303 _scratchValid = false;
1304 // if (!_routeMgr->isRouteActive()) {
1305 // SG_LOG(SG_INSTR, SG_WARN, "GPS:loadWaypoint: no active route");
1309 int index = _scratchNode->getIntValue("index", -9999);
1312 if (index == -9999) { // no index supplied, use current wp
1313 index = _routeMgr->currentWaypoint();
1316 _searchIsRoute = true;
1317 setScratchFromRouteWaypoint(index);
1320 void GPS::setScratchFromRouteWaypoint(int aIndex)
1322 assert(_searchIsRoute);
1323 if ((aIndex < 0) || (aIndex >= _routeMgr->size())) {
1324 SG_LOG(SG_INSTR, SG_WARN, "GPS:setScratchFromRouteWaypoint: route-index out of bounds");
1328 _searchResultIndex = aIndex;
1329 SGWayPoint wp(_routeMgr->get_waypoint(aIndex));
1330 _scratchNode->setStringValue("name", wp.get_name());
1331 _scratchNode->setStringValue("ident", wp.get_id());
1332 _scratchPos = wp.get_target();
1333 _scratchValid = true;
1334 _scratchNode->setDoubleValue("course", wp.get_track());
1335 _scratchNode->setIntValue("index", aIndex);
1337 int lastResult = _routeMgr->size() - 1;
1338 _searchHasNext = (_searchResultIndex < lastResult);
1341 void GPS::loadNearest()
1343 string sty(_scratchNode->getStringValue("type"));
1344 FGPositioned::Type ty = FGPositioned::typeFromName(sty);
1345 if (ty == FGPositioned::INVALID) {
1346 SG_LOG(SG_INSTR, SG_WARN, "GPS:loadNearest: request type is invalid:" << sty);
1350 auto_ptr<FGPositioned::Filter> f(createFilter(ty));
1351 int limitCount = _scratchNode->getIntValue("max-results", 1);
1352 double cutoffDistance = _scratchNode->getDoubleValue("cutoff-nm", 400.0);
1354 clearScratch(); // clear now, regardless of whether we find a match or not
1357 FGPositioned::findClosestN(_indicated_pos, limitCount, cutoffDistance, f.get());
1358 _searchResultsCached = true;
1359 _searchResultIndex = 0;
1360 _searchIsRoute = false;
1361 _searchHasNext = false;
1363 if (_searchResults.empty()) {
1364 SG_LOG(SG_INSTR, SG_INFO, "GPS:loadNearest: no matches at all");
1368 _searchHasNext = (_searchResults.size() > 1);
1369 setScratchFromCachedSearchResult();
1372 bool GPS::SearchFilter::pass(FGPositioned* aPos) const
1374 switch (aPos->type()) {
1375 case FGPositioned::AIRPORT:
1376 // heliport and seaport too?
1377 case FGPositioned::VOR:
1378 case FGPositioned::NDB:
1379 case FGPositioned::FIX:
1380 case FGPositioned::TACAN:
1381 case FGPositioned::WAYPOINT:
1388 FGPositioned::Type GPS::SearchFilter::minType() const
1390 return FGPositioned::AIRPORT;
1393 FGPositioned::Type GPS::SearchFilter::maxType() const
1395 return FGPositioned::WAYPOINT;
1398 FGPositioned::Filter* GPS::createFilter(FGPositioned::Type aTy)
1400 if (aTy == FGPositioned::AIRPORT) {
1401 return new FGAirport::HardSurfaceFilter(_config.minRunwayLengthFt());
1404 // if we were passed INVALID, assume it means 'all types interesting to a GPS'
1405 if (aTy == FGPositioned::INVALID) {
1406 return new SearchFilter;
1409 return new FGPositioned::TypeFilter(aTy);
1414 // parse search terms into local members, and exec the first search
1415 string sty(_scratchNode->getStringValue("type"));
1416 _searchType = FGPositioned::typeFromName(sty);
1417 _searchQuery = _scratchNode->getStringValue("query");
1418 _searchExact = _scratchNode->getBoolValue("exact", true);
1419 _searchOrderByRange = _scratchNode->getBoolValue("order-by-distance", true);
1420 _searchResultIndex = 0;
1421 _searchIsRoute = false;
1422 _searchHasNext = false;
1424 if (_searchExact && _searchOrderByRange) {
1425 // immediate mode search, get all the results now and cache them
1426 auto_ptr<FGPositioned::Filter> f(createFilter(_searchType));
1428 _searchResults = FGPositioned::findAllWithNameSortedByRange(_searchQuery, _indicated_pos, f.get());
1430 _searchResults = FGPositioned::findAllWithIdentSortedByRange(_searchQuery, _indicated_pos, f.get());
1433 _searchResultsCached = true;
1435 if (_searchResults.empty()) {
1440 _searchHasNext = (_searchResults.size() > 1);
1441 setScratchFromCachedSearchResult();
1443 // iterative search, look up result zero
1444 _searchResultsCached = false;
1449 void GPS::performSearch()
1451 auto_ptr<FGPositioned::Filter> f(createFilter(_searchType));
1456 if (_searchOrderByRange) {
1457 r = FGPositioned::findClosestWithPartialName(_indicated_pos, _searchQuery, f.get(), _searchResultIndex, _searchHasNext);
1459 r = FGPositioned::findWithPartialName(_searchQuery, f.get(), _searchResultIndex, _searchHasNext);
1462 if (_searchOrderByRange) {
1463 r = FGPositioned::findClosestWithPartialId(_indicated_pos, _searchQuery, f.get(), _searchResultIndex, _searchHasNext);
1465 r = FGPositioned::findWithPartialId(_searchQuery, f.get(), _searchResultIndex, _searchHasNext);
1473 setScratchFromPositioned(r.get(), _searchResultIndex);
1476 void GPS::setScratchFromCachedSearchResult()
1478 assert(_searchResultsCached);
1479 int index = _searchResultIndex;
1481 if ((index < 0) || (index >= (int) _searchResults.size())) {
1482 SG_LOG(SG_INSTR, SG_WARN, "GPS:setScratchFromCachedSearchResult: index out of bounds:" << index);
1486 setScratchFromPositioned(_searchResults[index], index);
1488 int lastResult = (int) _searchResults.size() - 1;
1489 _searchHasNext = (_searchResultIndex < lastResult);
1492 void GPS::setScratchFromPositioned(FGPositioned* aPos, int aIndex)
1497 _scratchPos = aPos->geod();
1498 _scratchNode->setStringValue("name", aPos->name());
1499 _scratchNode->setStringValue("ident", aPos->ident());
1500 _scratchNode->setStringValue("type", FGPositioned::nameForType(aPos->type()));
1503 _scratchNode->setIntValue("index", aIndex);
1506 _scratchValid = true;
1507 if (_searchResultsCached) {
1508 _scratchNode->setIntValue("result-count", _searchResults.size());
1511 switch (aPos->type()) {
1512 case FGPositioned::VOR:
1513 _scratchNode->setDoubleValue("frequency-mhz", static_cast<FGNavRecord*>(aPos)->get_freq() / 100.0);
1516 case FGPositioned::NDB:
1517 _scratchNode->setDoubleValue("frequency-khz", static_cast<FGNavRecord*>(aPos)->get_freq() / 100.0);
1520 case FGPositioned::AIRPORT:
1521 addAirportToScratch((FGAirport*)aPos);
1529 // look for being on the route and set?
1532 void GPS::addAirportToScratch(FGAirport* aAirport)
1534 for (unsigned int r=0; r<aAirport->numRunways(); ++r) {
1535 SGPropertyNode* rwyNd = _scratchNode->getChild("runways", r, true);
1536 FGRunway* rwy = aAirport->getRunwayByIndex(r);
1537 // TODO - filter out unsuitable runways in the future
1538 // based on config again
1540 rwyNd->setStringValue("id", rwy->ident().c_str());
1541 rwyNd->setIntValue("length-ft", rwy->lengthFt());
1542 rwyNd->setIntValue("width-ft", rwy->widthFt());
1543 rwyNd->setIntValue("heading-deg", rwy->headingDeg());
1544 // map surface code to a string
1545 // TODO - lighting information
1548 rwyNd->setDoubleValue("ils-frequency-mhz", rwy->ILS()->get_freq() / 100.0);
1550 } // of runways iteration
1554 void GPS::selectOBSMode()
1556 if (!isScratchPositionValid()) {
1557 SG_LOG(SG_INSTR, SG_WARN, "invalid OBS lat/lon");
1561 SG_LOG(SG_INSTR, SG_INFO, "GPS switching to OBS mode");
1564 _wp1Ident = _scratchNode->getStringValue("ident");
1565 _wp1Name = _scratchNode->getStringValue("name");
1566 _wp1_position = _scratchPos;
1567 _wp0_position = _indicated_pos;
1571 void GPS::selectLegMode()
1573 if (_mode == "leg") {
1577 if (!_routeMgr->isRouteActive()) {
1578 SG_LOG(SG_INSTR, SG_WARN, "GPS:selectLegMode: no active route");
1582 SG_LOG(SG_INSTR, SG_INFO, "GPS switching to LEG mode");
1585 // not really sequenced, but does all the work of updating wp0/1
1586 routeManagerSequenced();
1589 void GPS::nextResult()
1591 if (!_searchHasNext) {
1596 if (_searchIsRoute) {
1597 setScratchFromRouteWaypoint(++_searchResultIndex);
1598 } else if (_searchResultsCached) {
1599 ++_searchResultIndex;
1600 setScratchFromCachedSearchResult();
1602 ++_searchResultIndex;
1604 } // of iterative search case
1607 void GPS::previousResult()
1609 if (_searchResultIndex <= 0) {
1614 --_searchResultIndex;
1616 if (_searchIsRoute) {
1617 setScratchFromRouteWaypoint(_searchResultIndex);
1618 } else if (_searchResultsCached) {
1619 setScratchFromCachedSearchResult();
1625 void GPS::defineWaypoint()
1627 if (!isScratchPositionValid()) {
1628 SG_LOG(SG_INSTR, SG_WARN, "GPS:defineWaypoint: invalid lat/lon");
1632 string ident = _scratchNode->getStringValue("ident");
1633 if (ident.size() < 2) {
1634 SG_LOG(SG_INSTR, SG_WARN, "GPS:defineWaypoint: waypoint identifier must be at least two characters");
1638 // check for duplicate idents
1639 FGPositioned::TypeFilter f(FGPositioned::WAYPOINT);
1640 FGPositioned::List dups = FGPositioned::findAllWithIdentSortedByRange(ident, _indicated_pos, &f);
1641 if (!dups.empty()) {
1642 SG_LOG(SG_INSTR, SG_WARN, "GPS:defineWaypoint: non-unique waypoint identifier, ho-hum");
1645 SG_LOG(SG_INSTR, SG_INFO, "GPS:defineWaypoint: creating waypoint:" << ident);
1646 FGPositionedRef wpt = FGPositioned::createUserWaypoint(ident, _scratchPos);
1647 _searchResultsCached = false;
1648 setScratchFromPositioned(wpt.get(), -1);