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(""));
138 } else if (prop == _gps->_routeEditedSignal) {
140 } else if (prop == _gps->_routeFinishedSignal) {
141 _gps->routeFinished();
147 void setGuard(bool g) {
152 bool _guard; // re-entrancy guard
155 ////////////////////////////////////////////////////////////////////////////
157 * Helper to monitor for Nasal or other code accessing properties we haven't
158 * defined. For the moment we complain about all such activites, since various
159 * users assume all kinds of weird, wonderful and non-existent interfaces.
162 class DeprecatedPropListener : public SGPropertyChangeListener
165 DeprecatedPropListener(SGPropertyNode* gps)
167 _parents.insert(gps);
168 SGPropertyNode* wp = gps->getChild("wp");
170 _parents.insert(wp->getChild("wp", 0));
171 _parents.insert(wp->getChild("wp", 1));
173 std::set<SGPropertyNode*>::iterator it;
174 for (it = _parents.begin(); it != _parents.end(); ++it) {
175 (*it)->addChangeListener(this);
179 virtual void valueChanged (SGPropertyNode * prop)
183 virtual void childAdded (SGPropertyNode * parent, SGPropertyNode * child)
185 if (isDeprecated(parent, child)) {
186 SG_LOG(SG_INSTR, SG_WARN, "GPS: someone accessed a deprecated property:"
187 << child->getPath(true));
191 bool isDeprecated(SGPropertyNode * parent, SGPropertyNode * child) const
193 if (_parents.count(parent) < 1) {
197 // no child exclusions yet
201 std::set<SGPropertyNode*> _parents;
204 ////////////////////////////////////////////////////////////////////////////
205 // configuration helper object
207 GPS::Config::Config() :
208 _enableTurnAnticipation(true),
209 _turnRate(3.0), // degrees-per-second, so 180 degree turn takes 60 seconds
210 _overflightArmDistance(0.5),
211 _waypointAlertTime(30.0),
212 _tuneRadio1ToRefVor(false),
213 _minRunwayLengthFt(0.0),
214 _requireHardSurface(true),
215 _cdiMaxDeflectionNm(-1), // default to angular mode
216 _driveAutopilot(true)
218 _enableTurnAnticipation = false;
219 _extCourseSource = fgGetNode("/instrumentation/nav[0]/radials/selected-deg", true);
222 void GPS::Config::init(SGPropertyNode* aCfgNode)
224 aCfgNode->tie("turn-rate-deg-sec", SGRawValuePointer<double>(&_turnRate));
225 aCfgNode->tie("turn-anticipation", SGRawValuePointer<bool>(&_enableTurnAnticipation));
226 aCfgNode->tie("wpt-alert-time", SGRawValuePointer<double>(&_waypointAlertTime));
227 aCfgNode->tie("tune-nav-radio-to-ref-vor", SGRawValuePointer<bool>(&_tuneRadio1ToRefVor));
228 aCfgNode->tie("min-runway-length-ft", SGRawValuePointer<double>(&_minRunwayLengthFt));
229 aCfgNode->tie("hard-surface-runways-only", SGRawValuePointer<bool>(&_requireHardSurface));
231 aCfgNode->tie("course-source", SGRawValueMethods<GPS::Config, const char*>
232 (*this, &GPS::Config::getCourseSource, &GPS::Config::setCourseSource));
234 aCfgNode->tie("cdi-max-deflection-nm", SGRawValuePointer<double>(&_cdiMaxDeflectionNm));
235 aCfgNode->tie("drive-autopilot", SGRawValuePointer<bool>(&_driveAutopilot));
239 GPS::Config::getCourseSource() const
241 if (!_extCourseSource) {
245 return _extCourseSource->getPath(true);
249 GPS::Config::setCourseSource(const char* aPath)
251 SGPropertyNode* nd = fgGetNode(aPath, false);
253 SG_LOG(SG_INSTR, SG_WARN, "couldn't find course source at:" << aPath);
254 _extCourseSource = NULL;
257 _extCourseSource = nd;
261 GPS::Config::getExternalCourse() const
263 if (!_extCourseSource) {
267 return _extCourseSource->getDoubleValue();
271 GPS::Config::setExternalCourse(double aCourseDeg)
273 if (!_extCourseSource) {
277 _extCourseSource->setDoubleValue(aCourseDeg);
280 ////////////////////////////////////////////////////////////////////////////
282 GPS::GPS ( SGPropertyNode *node) :
284 _name(node->getStringValue("name", "gps")),
285 _num(node->getIntValue("number", 0)),
286 _computeTurnData(false),
287 _anticipateTurn(false),
299 _routeMgr = (FGRouteMgr*) globals->get_subsystem("route-manager");
303 branch = "/instrumentation/" + _name;
305 SGPropertyNode *node = fgGetNode(branch.c_str(), _num, true );
306 _config.init(node->getChild("config", 0, true));
308 _position.init("/position/longitude-deg", "/position/latitude-deg", "/position/altitude-ft");
309 _magvar_node = fgGetNode("/environment/magnetic-variation-deg", true);
310 _serviceable_node = node->getChild("serviceable", 0, true);
311 _serviceable_node->setBoolValue(true);
312 _electrical_node = fgGetNode("/systems/electrical/outputs/gps", true);
315 node->tie("selected-course-deg", SGRawValueMethods<GPS, double>(*this, &GPS::getSelectedCourse, NULL));
317 _raim_node = node->getChild("raim", 0, true);
319 tieSGGeodReadOnly(node, _indicated_pos, "indicated-longitude-deg",
320 "indicated-latitude-deg", "indicated-altitude-ft");
322 node->tie("indicated-vertical-speed", SGRawValueMethods<GPS, double>
323 (*this, &GPS::getVerticalSpeed, NULL));
324 node->tie("indicated-track-true-deg", SGRawValueMethods<GPS, double>
325 (*this, &GPS::getTrueTrack, NULL));
326 node->tie("indicated-track-magnetic-deg", SGRawValueMethods<GPS, double>
327 (*this, &GPS::getMagTrack, NULL));
328 node->tie("indicated-ground-speed-kt", SGRawValueMethods<GPS, double>
329 (*this, &GPS::getGroundspeedKts, NULL));
331 _odometer_node = node->getChild("odometer", 0, true);
332 _trip_odometer_node = node->getChild("trip-odometer", 0, true);
333 _true_bug_error_node = node->getChild("true-bug-error-deg", 0, true);
334 _magnetic_bug_error_node = node->getChild("magnetic-bug-error-deg", 0, true);
338 node->tie("mode", SGRawValueMethods<GPS, const char*>(*this, &GPS::getMode, NULL));
339 node->tie("command", SGRawValueMethods<GPS, const char*>(*this, &GPS::getCommand, &GPS::setCommand));
341 _scratchNode = node->getChild("scratch", 0, true);
342 tieSGGeod(_scratchNode, _scratchPos, "longitude-deg", "latitude-deg", "altitude-ft");
343 _scratchNode->tie("valid", SGRawValueMethods<GPS, bool>(*this, &GPS::getScratchValid, NULL));
344 _scratchNode->tie("distance-nm", SGRawValueMethods<GPS, double>(*this, &GPS::getScratchDistance, NULL));
345 _scratchNode->tie("true-bearing-deg", SGRawValueMethods<GPS, double>(*this, &GPS::getScratchTrueBearing, NULL));
346 _scratchNode->tie("mag-bearing-deg", SGRawValueMethods<GPS, double>(*this, &GPS::getScratchMagBearing, NULL));
347 _scratchNode->tie("has-next", SGRawValueMethods<GPS, bool>(*this, &GPS::getScratchHasNext, NULL));
348 _scratchValid = false;
350 // waypoint data (including various historical things)
351 SGPropertyNode *wp_node = node->getChild("wp", 0, true);
352 SGPropertyNode *wp0_node = wp_node->getChild("wp", 0, true);
353 SGPropertyNode *wp1_node = wp_node->getChild("wp", 1, true);
355 tieSGGeodReadOnly(wp0_node, _wp0_position, "longitude-deg", "latitude-deg", "altitude-ft");
356 wp0_node->tie("ID", SGRawValueMethods<GPS, const char*>
357 (*this, &GPS::getWP0Ident, NULL));
358 wp0_node->tie("name", SGRawValueMethods<GPS, const char*>
359 (*this, &GPS::getWP0Name, NULL));
361 tieSGGeodReadOnly(wp1_node, _wp1_position, "longitude-deg", "latitude-deg", "altitude-ft");
362 wp1_node->tie("ID", SGRawValueMethods<GPS, const char*>
363 (*this, &GPS::getWP1Ident, NULL));
364 wp1_node->tie("name", SGRawValueMethods<GPS, const char*>
365 (*this, &GPS::getWP1Name, NULL));
367 // for compatability, alias selected course down to wp/wp[1]/desired-course-deg
368 SGPropertyNode* wp1Crs = wp1_node->getChild("desired-course-deg", 0, true);
369 wp1Crs->alias(node->getChild("selected-course-deg"));
371 // _true_wp1_bearing_error_node =
372 // wp1_node->getChild("true-bearing-error-deg", 0, true);
373 // _magnetic_wp1_bearing_error_node =
374 // wp1_node->getChild("magnetic-bearing-error-deg", 0, true);
376 wp1_node->tie("distance-nm", SGRawValueMethods<GPS, double>
377 (*this, &GPS::getWP1Distance, NULL));
378 wp1_node->tie("bearing-true-deg", SGRawValueMethods<GPS, double>
379 (*this, &GPS::getWP1Bearing, NULL));
380 wp1_node->tie("bearing-mag-deg", SGRawValueMethods<GPS, double>
381 (*this, &GPS::getWP1MagBearing, NULL));
382 wp1_node->tie("TTW-sec", SGRawValueMethods<GPS, double>
383 (*this, &GPS::getWP1TTW, NULL));
384 wp1_node->tie("TTW", SGRawValueMethods<GPS, const char*>
385 (*this, &GPS::getWP1TTWString, NULL));
387 wp1_node->tie("course-deviation-deg", SGRawValueMethods<GPS, double>
388 (*this, &GPS::getWP1CourseDeviation, NULL));
389 wp1_node->tie("course-error-nm", SGRawValueMethods<GPS, double>
390 (*this, &GPS::getWP1CourseErrorNm, NULL));
391 wp1_node->tie("to-flag", SGRawValueMethods<GPS, bool>
392 (*this, &GPS::getWP1ToFlag, NULL));
393 wp1_node->tie("from-flag", SGRawValueMethods<GPS, bool>
394 (*this, &GPS::getWP1FromFlag, NULL));
396 _tracking_bug_node = node->getChild("tracking-bug", 0, true);
398 // leg properties (only valid in DTO/LEG modes, not OBS)
399 wp_node->tie("leg-distance-nm", SGRawValueMethods<GPS, double>(*this, &GPS::getLegDistance, NULL));
400 wp_node->tie("leg-true-course-deg", SGRawValueMethods<GPS, double>(*this, &GPS::getLegCourse, NULL));
401 wp_node->tie("leg-mag-course-deg", SGRawValueMethods<GPS, double>(*this, &GPS::getLegMagCourse, NULL));
402 wp_node->tie("alt-dist-ratio", SGRawValueMethods<GPS, double>(*this, &GPS::getAltDistanceRatio, NULL));
405 SGPropertyNode_ptr ref_navaid = node->getChild("ref-navaid", 0, true);
406 _ref_navaid_id_node = ref_navaid->getChild("id", 0, true);
407 _ref_navaid_name_node = ref_navaid->getChild("name", 0, true);
408 _ref_navaid_bearing_node = ref_navaid->getChild("bearing-deg", 0, true);
409 _ref_navaid_frequency_node = ref_navaid->getChild("frequency-mhz", 0, true);
410 _ref_navaid_distance_node = ref_navaid->getChild("distance-nm", 0, true);
411 _ref_navaid_mag_bearing_node = ref_navaid->getChild("mag-bearing-deg", 0, true);
412 _ref_navaid_elapsed = 0.0;
413 _ref_navaid_set = false;
416 // should these move to the route manager?
417 _routeDistanceNm = node->getChild("route-distance-nm", 0, true);
418 _routeETE = node->getChild("ETE", 0, true);
419 _routeEditedSignal = fgGetNode("/autopilot/route-manager/signals/edited", true);
420 _routeFinishedSignal = fgGetNode("/autopilot/route-manager/signals/finished", true);
422 // add listener to various things
423 _listener = new GPSListener(this);
424 _route_current_wp_node = fgGetNode("/autopilot/route-manager/current-wp", true);
425 _route_current_wp_node->addChangeListener(_listener);
426 _route_active_node = fgGetNode("/autopilot/route-manager/active", true);
427 _route_active_node->addChangeListener(_listener);
428 _ref_navaid_id_node->addChangeListener(_listener);
429 _routeEditedSignal->addChangeListener(_listener);
430 _routeFinishedSignal->addChangeListener(_listener);
432 // navradio slaving properties
433 node->tie("cdi-deflection", SGRawValueMethods<GPS,double>
434 (*this, &GPS::getCDIDeflection));
436 SGPropertyNode* toFlag = node->getChild("to-flag", 0, true);
437 toFlag->alias(wp1_node->getChild("to-flag"));
439 SGPropertyNode* fromFlag = node->getChild("from-flag", 0, true);
440 fromFlag->alias(wp1_node->getChild("from-flag"));
443 // autopilot drive properties
444 _apTrueHeading = fgGetNode("/autopilot/settings/true-heading-deg",true);
445 _apTargetAltitudeFt = fgGetNode("/autopilot/settings/target-altitude-ft", true);
446 _apAltitudeLock = fgGetNode("/autopilot/locks/altitude", true);
449 _realismSimpleGps = fgGetNode("/sim/realism/simple-gps", true);
450 if (!_realismSimpleGps->hasValue()) {
451 _realismSimpleGps->setBoolValue(true);
454 // last thing, add the deprecated prop watcher
455 new DeprecatedPropListener(node);
457 // initialise in OBS mode, with waypt set to the nearest airport.
458 // keep in mind at this point, _last_valid is not set
460 auto_ptr<FGPositioned::Filter> f(createFilter(FGPositioned::AIRPORT));
461 FGPositionedRef apt = FGPositioned::findClosest(_position.get(), 20.0, f.get());
463 setScratchFromPositioned(apt, 0);
472 _last_speed_kts = 0.0;
473 _last_pos = SGGeod();
474 _indicated_pos = SGGeod();
475 _last_vertical_speed = 0.0;
476 _last_true_track = 0.0;
478 _raim_node->setDoubleValue(0.0);
479 _indicated_pos = SGGeod();
481 _wp1TrueBearing = 0.0;
482 _wp1_position = SGGeod();
483 _odometer_node->setDoubleValue(0);
484 _trip_odometer_node->setDoubleValue(0);
485 _tracking_bug_node->setDoubleValue(0);
486 _true_bug_error_node->setDoubleValue(0);
487 _magnetic_bug_error_node->setDoubleValue(0);
491 GPS::update (double delta_time_sec)
493 if (!_realismSimpleGps->getBoolValue()) {
494 // If it's off, don't bother.
495 if (!_serviceable_node->getBoolValue() || !_electrical_node->getBoolValue()) {
501 if (delta_time_sec <= 0.0) {
502 return; // paused, don't bother
504 // TODO: Add noise and other errors.
507 // Bias and random error
508 double random_factor = sg_random();
509 double random_error = 1.4;
510 double error_radius = 5.1;
511 double bias_max_radius = 5.1;
512 double random_max_radius = 1.4;
514 bias_length += (random_factor-0.5) * 1.0e-3;
515 if (bias_length <= 0.0) bias_length = 0.0;
516 else if (bias_length >= bias_max_radius) bias_length = bias_max_radius;
517 bias_angle += (random_factor-0.5) * 1.0e-3;
518 if (bias_angle <= 0.0) bias_angle = 0.0;
519 else if (bias_angle >= 360.0) bias_angle = 360.0;
521 double random_length = random_factor * random_max_radius;
522 double random_angle = random_factor * 360.0;
524 double bias_x = bias_length * cos(bias_angle * SG_PI / 180.0);
525 double bias_y = bias_length * sin(bias_angle * SG_PI / 180.0);
526 double random_x = random_length * cos(random_angle * SG_PI / 180.0);
527 double random_y = random_length * sin(random_angle * SG_PI / 180.0);
528 double error_x = bias_x + random_x;
529 double error_y = bias_y + random_y;
530 double error_length = sqrt(error_x*error_x + error_y*error_y);
531 double error_angle = atan(error_y / error_x) * 180.0 / SG_PI;
536 geo_direct_wgs_84 ( altitude_m, latitude_deg,
537 longitude_deg, error_angle,
538 error_length, &lat2, &lon2,
540 //cout << lat2 << " " << lon2 << endl;
541 printf("%f %f \n", bias_length, bias_angle);
542 printf("%3.7f %3.7f \n", lat2, lon2);
543 printf("%f %f \n", error_length, error_angle);
546 _raim_node->setDoubleValue(1.0);
547 _indicated_pos = _position.get();
550 updateWithValid(delta_time_sec);
554 if (_route_active_node->getBoolValue()) {
555 // GPS init with active route
556 SG_LOG(SG_INSTR, SG_INFO, "GPS init with active route");
557 _listener->setGuard(true);
559 routeManagerSequenced();
560 _listener->setGuard(false);
564 _last_pos = _indicated_pos;
568 GPS::updateWithValid(double dt)
574 if (_mode == "obs") {
575 _selectedCourse = _config.getExternalCourse();
582 updateReferenceNavaid(dt);
588 GPS::updateBasicData(double dt)
592 SGGeodesy::inverse(_last_pos, _indicated_pos, _last_true_track, track2_deg, distance_m );
594 double speed_kt = ((distance_m * SG_METER_TO_NM) * ((1 / dt) * 3600.0));
595 double vertical_speed_mpm = ((_indicated_pos.getElevationM() - _last_pos.getElevationM()) * 60 / dt);
596 _last_vertical_speed = vertical_speed_mpm * SG_METER_TO_FEET;
598 speed_kt = fgGetLowPass(_last_speed_kts, speed_kt, dt/20.0);
599 _last_speed_kts = speed_kt;
601 double odometer = _odometer_node->getDoubleValue();
602 _odometer_node->setDoubleValue(odometer + distance_m * SG_METER_TO_NM);
603 odometer = _trip_odometer_node->getDoubleValue();
604 _trip_odometer_node->setDoubleValue(odometer + distance_m * SG_METER_TO_NM);
608 GPS::updateTrackingBug()
610 double tracking_bug = _tracking_bug_node->getDoubleValue();
611 double true_bug_error = tracking_bug - getTrueTrack();
612 double magnetic_bug_error = tracking_bug - getMagTrack();
614 // Get the errors into the (-180,180) range.
615 SG_NORMALIZE_RANGE(true_bug_error, -180.0, 180.0);
616 SG_NORMALIZE_RANGE(magnetic_bug_error, -180.0, 180.0);
618 _true_bug_error_node->setDoubleValue(true_bug_error);
619 _magnetic_bug_error_node->setDoubleValue(magnetic_bug_error);
623 GPS::updateWaypoints()
626 SGGeodesy::inverse(_indicated_pos, _wp1_position, _wp1TrueBearing, az2,_wp1DistanceM);
629 void GPS::updateReferenceNavaid(double dt)
631 if (!_ref_navaid_set) {
632 _ref_navaid_elapsed += dt;
633 if (_ref_navaid_elapsed > 5.0) {
634 _ref_navaid_elapsed = 0.0;
636 FGPositioned::TypeFilter vorFilter(FGPositioned::VOR);
637 FGPositionedRef nav = FGPositioned::findClosest(_indicated_pos, 400.0, &vorFilter);
639 SG_LOG(SG_INSTR, SG_INFO, "GPS couldn't find a reference navid");
640 _ref_navaid_id_node->setStringValue("");
641 _ref_navaid_name_node->setStringValue("");
642 _ref_navaid_bearing_node->setDoubleValue(0.0);
643 _ref_navaid_mag_bearing_node->setDoubleValue(0.0);
644 _ref_navaid_distance_node->setDoubleValue(0.0);
645 _ref_navaid_frequency_node->setStringValue("");
646 } else if (nav != _ref_navaid) {
647 SG_LOG(SG_INSTR, SG_INFO, "GPS code selected new ref-navaid:" << nav->ident());
648 _listener->setGuard(true);
649 _ref_navaid_id_node->setStringValue(nav->ident().c_str());
650 _ref_navaid_name_node->setStringValue(nav->name().c_str());
651 FGNavRecord* vor = (FGNavRecord*) nav.ptr();
652 _ref_navaid_frequency_node->setDoubleValue(vor->get_freq() / 100.0);
653 _listener->setGuard(false);
656 // SG_LOG(SG_INSTR, SG_ALERT, "matched existing");
664 double trueCourse, distanceM, az2;
665 SGGeodesy::inverse(_indicated_pos, _ref_navaid->geod(), trueCourse, az2, distanceM);
666 _ref_navaid_distance_node->setDoubleValue(distanceM * SG_METER_TO_NM);
667 _ref_navaid_bearing_node->setDoubleValue(trueCourse);
668 _ref_navaid_mag_bearing_node->setDoubleValue(trueCourse - _magvar_node->getDoubleValue());
672 void GPS::referenceNavaidSet(const std::string& aNavaid)
675 // allow setting an empty string to restore normal nearest-vor selection
676 if (aNavaid.size() > 0) {
677 FGPositioned::TypeFilter vorFilter(FGPositioned::VOR);
678 _ref_navaid = FGPositioned::findClosestWithIdent(aNavaid,
679 _position.get(), &vorFilter);
682 SG_LOG(SG_INSTR, SG_ALERT, "GPS: unknown ref navaid:" << aNavaid);
687 _ref_navaid_set = true;
688 SG_LOG(SG_INSTR, SG_INFO, "GPS code set explict ref-navaid:" << _ref_navaid->ident());
689 _ref_navaid_id_node->setStringValue(_ref_navaid->ident().c_str());
690 _ref_navaid_name_node->setStringValue(_ref_navaid->name().c_str());
691 FGNavRecord* vor = (FGNavRecord*) _ref_navaid.ptr();
692 _ref_navaid_frequency_node->setDoubleValue(vor->get_freq() / 100.0);
695 _ref_navaid_set = false;
696 _ref_navaid_elapsed = 9999.0; // update next tick
700 void GPS::tuneNavRadios()
702 if (!_ref_navaid || !_config.tuneNavRadioToRefVor()) {
706 SGPropertyNode_ptr navRadio1 = fgGetNode("/instrumentation/nav", false);
711 FGNavRecord* vor = (FGNavRecord*) _ref_navaid.ptr();
712 SGPropertyNode_ptr freqs = navRadio1->getChild("frequencies");
713 freqs->setDoubleValue("selected-mhz", vor->get_freq() / 100.0);
716 void GPS::routeActivated()
718 if (_route_active_node->getBoolValue()) {
719 SG_LOG(SG_INSTR, SG_INFO, "GPS::route activated, switching to LEG mode");
721 } else if (_mode == "leg") {
722 SG_LOG(SG_INSTR, SG_INFO, "GPS::route deactivated, switching to OBS mode");
727 void GPS::routeManagerSequenced()
729 if (_mode != "leg") {
730 SG_LOG(SG_INSTR, SG_INFO, "GPS ignoring route sequencing, not in LEG mode");
734 int index = _routeMgr->currentWaypoint(),
735 count = _routeMgr->size();
736 if ((index < 1) || (index >= count)) {
737 SG_LOG(SG_INSTR, SG_ALERT, "GPS: malformed route, index=" << index);
741 SG_LOG(SG_INSTR, SG_INFO, "GPS waypoint index is now " << index);
742 SGWayPoint wp0(_routeMgr->get_waypoint(index - 1));
743 SGWayPoint wp1(_routeMgr->get_waypoint(index));
745 _wp0Ident = wp0.get_id();
746 _wp0Name = wp0.get_name();
747 _wp0_position = wp0.get_target();
749 _wp1Ident = wp1.get_id();
750 _wp1Name = wp1.get_name();
751 _wp1_position = wp1.get_target();
753 _selectedCourse = getLegMagCourse();
757 void GPS::routeEdited()
759 if (_mode != "leg") {
763 SG_LOG(SG_INSTR, SG_INFO, "GPS route edited while in LEG mode, updating waypoints");
764 routeManagerSequenced();
767 void GPS::routeFinished()
769 if (_mode != "leg") {
773 SG_LOG(SG_INSTR, SG_INFO, "GPS route finished, reverting to OBS");
775 _wp0_position = _indicated_pos;
779 void GPS::updateTurn()
781 bool printProgress = false;
783 if (_computeTurnData) {
784 if (_last_speed_kts < 60) {
785 // need valid leg course and sensible ground speed to compute the turn
790 printProgress = true;
793 if (!_anticipateTurn) {
799 // find bearing to turn centre
800 double bearing, az2, distanceM;
801 SGGeodesy::inverse(_indicated_pos, _turnCentre, bearing, az2, distanceM);
802 double progress = computeTurnProgress(bearing);
805 SG_LOG(SG_INSTR, SG_INFO,"turn progress=" << progress);
808 if (!_inTurn && (progress > 0.0)) {
812 if (_inTurn && !_turnSequenced && (progress > 0.5)) {
813 _turnSequenced = true;
814 SG_LOG(SG_INSTR, SG_INFO, "turn passed midpoint, sequencing");
815 _routeMgr->sequence();
818 if (_inTurn && (progress >= 1.0)) {
823 // drive deviation and desired course
824 double desiredCourse = bearing - copysign(90, _turnAngle);
825 SG_NORMALIZE_RANGE(desiredCourse, 0.0, 360.0);
826 double deviationNm = (distanceM * SG_METER_TO_NM) - _turnRadius;
827 double deviationDeg = desiredCourse - getMagTrack();
828 deviationNm = copysign(deviationNm, deviationDeg);
830 //_wp1_course_deviation_node->setDoubleValue(deviationDeg);
831 //_wp1_course_error_nm_node->setDoubleValue(deviationNm);
832 //_cdiDeflectionNode->setDoubleValue(deviationDeg);
836 void GPS::updateOverflight()
838 if ((_wp1DistanceM * SG_METER_TO_NM) > _config.overflightArmDistanceNm()) {
842 if (getWP1ToFlag()) {
843 return; // still heading towards the WP
846 if (_mode == "dto") {
847 SG_LOG(SG_INSTR, SG_INFO, "GPS DTO reached destination point");
849 // check for wp1 being on active route - resume leg mode
850 if (_routeMgr->isRouteActive()) {
851 int index = _routeMgr->findWaypoint(_wp1_position);
853 SG_LOG(SG_INSTR, SG_INFO, "GPS DTO, resuming LEG mode at wp:" << index);
855 _routeMgr->jumpToIndex(index);
858 } else if (_mode == "leg") {
859 SG_LOG(SG_INSTR, SG_INFO, "GPS doing overflight sequencing");
860 _routeMgr->sequence();
861 } else if (_mode == "obs") {
862 // nothing to do here, TO/FROM will update but that's fine
865 _computeTurnData = true;
868 void GPS::beginTurn()
871 _turnSequenced = false;
872 SG_LOG(SG_INSTR, SG_INFO, "begining turn");
878 SG_LOG(SG_INSTR, SG_INFO, "ending turn");
879 _computeTurnData = true;
882 double GPS::computeTurnProgress(double aBearing) const
884 double startBearing = _turnStartBearing + copysign(90, _turnAngle);
885 return (aBearing - startBearing) / _turnAngle;
888 void GPS::computeTurnData()
890 _computeTurnData = false;
891 if (_mode != "leg") { // and approach modes in the future
892 _anticipateTurn = false;
896 int curIndex = _routeMgr->currentWaypoint();
897 if ((curIndex + 1) >= _routeMgr->size()) {
898 _anticipateTurn = false;
902 if (!_config.turnAnticipationEnabled()) {
903 _anticipateTurn = false;
907 _turnStartBearing = _selectedCourse;
908 // compute next leg course
909 SGWayPoint wp1(_routeMgr->get_waypoint(curIndex)),
910 wp2(_routeMgr->get_waypoint(curIndex + 1));
912 wp2.CourseAndDistance(wp1, &crs, &dist);
915 // compute offset bearing
916 _turnAngle = crs - _turnStartBearing;
917 SG_NORMALIZE_RANGE(_turnAngle, -180.0, 180.0);
918 double median = _turnStartBearing + (_turnAngle * 0.5);
919 double offsetBearing = median + copysign(90, _turnAngle);
920 SG_NORMALIZE_RANGE(offsetBearing, 0.0, 360.0);
922 SG_LOG(SG_INSTR, SG_INFO, "GPS computeTurnData: in=" << _turnStartBearing <<
923 ", out=" << crs << "; turnAngle=" << _turnAngle << ", median=" << median
924 << ", offset=" << offsetBearing);
926 SG_LOG(SG_INSTR, SG_INFO, "next leg is now:" << wp1.get_id() << "->" << wp2.get_id());
928 _turnPt = _wp1_position;
929 _anticipateTurn = true;
932 void GPS::updateTurnData()
934 // depends on ground speed, so needs to be updated per-frame
935 _turnRadius = computeTurnRadiusNm(_last_speed_kts);
937 // compute the turn centre, based on the turn radius.
938 // key thing is to understand that we're working a right-angle triangle,
939 // where the right-angle is the point we start the turn. From that point,
940 // one side is the inbound course to the turn pt, and the other is the
941 // perpendicular line, of length 'r', to the turn centre.
942 // the triangle's hypotenuse, which we need to find, is the distance from the
943 // turn pt to the turn center (in the direction of the offset bearing)
944 // note that d - _turnRadius tell us how much we're 'cutting' the corner.
946 double halfTurnAngle = fabs(_turnAngle * 0.5) * SG_DEGREES_TO_RADIANS;
947 double d = _turnRadius / cos(halfTurnAngle);
949 // SG_LOG(SG_INSTR, SG_INFO, "turnRadius=" << _turnRadius << ", d=" << d
950 // << " (cut distance=" << d - _turnRadius << ")");
952 double median = _turnStartBearing + (_turnAngle * 0.5);
953 double offsetBearing = median + copysign(90, _turnAngle);
954 SG_NORMALIZE_RANGE(offsetBearing, 0.0, 360.0);
957 SGGeodesy::direct(_turnPt, offsetBearing, d * SG_NM_TO_METER, _turnCentre, az2);
960 double GPS::computeTurnRadiusNm(double aGroundSpeedKts) const
962 // turn time is seconds to execute a 360 turn.
963 double turnTime = 360.0 / _config.turnRateDegSec();
965 // c is ground distance covered in that time (circumference of the circle)
966 double c = turnTime * (aGroundSpeedKts / 3600.0); // convert knts to nm/sec
968 // divide by 2PI to go from circumference -> radius
969 return c / (2 * M_PI);
972 void GPS::updateRouteData()
974 double totalDistance = _wp1DistanceM * SG_METER_TO_NM;
975 // walk all waypoints from wp2 to route end, and sum
976 for (int i=_routeMgr->currentWaypoint()+1; i<_routeMgr->size(); ++i) {
977 totalDistance += _routeMgr->get_waypoint(i).get_distance();
980 _routeDistanceNm->setDoubleValue(totalDistance * SG_METER_TO_NM);
981 if (_last_speed_kts > 1.0) {
982 double TTW = ((totalDistance * SG_METER_TO_NM) / _last_speed_kts) * 3600.0;
983 _routeETE->setStringValue(makeTTWString(TTW));
987 void GPS::driveAutopilot()
989 if (!_config.driveAutopilot() || !_realismSimpleGps->getBoolValue()) {
993 // FIXME: we want to set desired track, not heading, here
994 _apTrueHeading->setDoubleValue(getWP1Bearing());
997 void GPS::wp1Changed()
999 // update external HSI/CDI/NavDisplay/PFD/etc
1000 _config.setExternalCourse(getLegMagCourse());
1002 if (!_config.driveAutopilot()) {
1006 double altFt = _wp1_position.getElevationFt();
1007 if (altFt < -9990.0) {
1008 _apTargetAltitudeFt->setDoubleValue(0.0);
1010 _apTargetAltitudeFt->setDoubleValue(altFt);
1014 /////////////////////////////////////////////////////////////////////////////
1015 // property getter/setters
1017 double GPS::getLegDistance() const
1019 if (!_last_valid || (_mode == "obs")) {
1023 return SGGeodesy::distanceNm(_wp0_position, _wp1_position);
1026 double GPS::getLegCourse() const
1028 if (!_last_valid || (_mode == "obs")) {
1032 return SGGeodesy::courseDeg(_wp0_position, _wp1_position);
1035 double GPS::getLegMagCourse() const
1037 if (!_last_valid || (_mode == "obs")) {
1041 double m = getLegCourse() - _magvar_node->getDoubleValue();
1042 SG_NORMALIZE_RANGE(m, 0.0, 360.0);
1046 double GPS::getAltDistanceRatio() const
1048 if (!_last_valid || (_mode == "obs")) {
1052 double dist = SGGeodesy::distanceM(_wp0_position, _wp1_position);
1053 if ( dist <= 0.0 ) {
1057 double alt_difference_m = _wp0_position.getElevationM() - _wp1_position.getElevationM();
1058 return alt_difference_m / dist;
1061 double GPS::getMagTrack() const
1067 double m = getTrueTrack() - _magvar_node->getDoubleValue();
1068 SG_NORMALIZE_RANGE(m, 0.0, 360.0);
1072 double GPS::getCDIDeflection() const
1079 if (_config.cdiDeflectionIsAngular()) {
1080 defl = getWP1CourseDeviation();
1081 SG_CLAMP_RANGE(defl, -10.0, 10.0); // as in navradio.cxx
1083 double fullScale = _config.cdiDeflectionLinearPeg();
1084 double normError = getWP1CourseErrorNm() / fullScale;
1085 SG_CLAMP_RANGE(normError, -1.0, 1.0);
1086 defl = normError * 10.0; // re-scale to navradio limits, i.e [-10.0 .. 10.0]
1092 const char* GPS::getWP0Ident() const
1094 if (!_last_valid || (_mode != "leg")) {
1098 return _wp0Ident.c_str();
1101 const char* GPS::getWP0Name() const
1103 if (!_last_valid || (_mode != "leg")) {
1107 return _wp0Name.c_str();
1110 const char* GPS::getWP1Ident() const
1116 return _wp1Ident.c_str();
1119 const char* GPS::getWP1Name() const
1125 return _wp1Name.c_str();
1128 double GPS::getWP1Distance() const
1134 return _wp1DistanceM * SG_METER_TO_NM;
1137 double GPS::getWP1TTW() const
1143 if (_last_speed_kts < 1.0) {
1147 return (getWP1Distance() / _last_speed_kts) * 3600.0;
1150 const char* GPS::getWP1TTWString() const
1156 return makeTTWString(getWP1TTW());
1159 double GPS::getWP1Bearing() const
1165 return _wp1TrueBearing;
1168 double GPS::getWP1MagBearing() const
1174 return _wp1TrueBearing - _magvar_node->getDoubleValue();
1177 double GPS::getWP1CourseDeviation() const
1183 double dev = getWP1MagBearing() - _selectedCourse;
1184 SG_NORMALIZE_RANGE(dev, -180.0, 180.0);
1186 if (fabs(dev) > 90.0) {
1187 // When the course is away from the waypoint,
1188 // it makes sense to change the sign of the deviation.
1190 SG_NORMALIZE_RANGE(dev, -90.0, 90.0);
1196 double GPS::getWP1CourseErrorNm() const
1202 double radDev = getWP1CourseDeviation() * SG_DEGREES_TO_RADIANS;
1203 double course_error_m = sin(radDev) * _wp1DistanceM;
1204 return course_error_m * SG_METER_TO_NM;
1207 bool GPS::getWP1ToFlag() const
1213 double dev = getWP1MagBearing() - _selectedCourse;
1214 SG_NORMALIZE_RANGE(dev, -180.0, 180.0);
1216 return (fabs(dev) < 90.0);
1219 bool GPS::getWP1FromFlag() const
1225 return !getWP1ToFlag();
1228 double GPS::getScratchDistance() const
1230 if (!_scratchValid) {
1234 return SGGeodesy::distanceNm(_indicated_pos, _scratchPos);
1237 double GPS::getScratchTrueBearing() const
1239 if (!_scratchValid) {
1243 return SGGeodesy::courseDeg(_indicated_pos, _scratchPos);
1246 double GPS::getScratchMagBearing() const
1248 if (!_scratchValid) {
1252 double crs = getScratchTrueBearing() - _magvar_node->getDoubleValue();
1253 SG_NORMALIZE_RANGE(crs, 0.0, 360.0);
1257 /////////////////////////////////////////////////////////////////////////////
1258 // command / scratch / search system
1260 void GPS::setCommand(const char* aCmd)
1262 SG_LOG(SG_INSTR, SG_INFO, "GPS command:" << aCmd);
1264 if (!strcmp(aCmd, "direct")) {
1266 } else if (!strcmp(aCmd, "obs")) {
1268 } else if (!strcmp(aCmd, "leg")) {
1270 } else if (!strcmp(aCmd, "load-route-wpt")) {
1271 loadRouteWaypoint();
1272 } else if (!strcmp(aCmd, "nearest")) {
1274 } else if (!strcmp(aCmd, "search")) {
1275 _searchNames = false;
1277 } else if (!strcmp(aCmd, "search-names")) {
1278 _searchNames = true;
1280 } else if (!strcmp(aCmd, "next")) {
1282 } else if (!strcmp(aCmd, "previous")) {
1284 } else if (!strcmp(aCmd, "define-user-wpt")) {
1287 SG_LOG(SG_INSTR, SG_WARN, "GPS:unrecognzied command:" << aCmd);
1291 void GPS::clearScratch()
1293 _scratchPos = SGGeod::fromDegFt(-9999.0, -9999.0, -9999.0);
1294 _scratchValid = false;
1295 _scratchNode->setStringValue("type", "");
1296 _scratchNode->setStringValue("query", "");
1299 bool GPS::isScratchPositionValid() const
1301 if ((_scratchPos.getLongitudeDeg() < -9990.0) ||
1302 (_scratchPos.getLatitudeDeg() < -9990.0)) {
1309 void GPS::directTo()
1311 if (!isScratchPositionValid()) {
1312 SG_LOG(SG_INSTR, SG_WARN, "invalid DTO lat/lon");
1316 _wp0_position = _indicated_pos;
1317 _wp1Ident = _scratchNode->getStringValue("ident");
1318 _wp1Name = _scratchNode->getStringValue("name");
1319 _wp1_position = _scratchPos;
1322 _selectedCourse = getLegMagCourse();
1328 void GPS::loadRouteWaypoint()
1330 _scratchValid = false;
1331 // if (!_routeMgr->isRouteActive()) {
1332 // SG_LOG(SG_INSTR, SG_WARN, "GPS:loadWaypoint: no active route");
1336 int index = _scratchNode->getIntValue("index", -9999);
1339 if (index == -9999) { // no index supplied, use current wp
1340 index = _routeMgr->currentWaypoint();
1343 _searchIsRoute = true;
1344 setScratchFromRouteWaypoint(index);
1347 void GPS::setScratchFromRouteWaypoint(int aIndex)
1349 assert(_searchIsRoute);
1350 if ((aIndex < 0) || (aIndex >= _routeMgr->size())) {
1351 SG_LOG(SG_INSTR, SG_WARN, "GPS:setScratchFromRouteWaypoint: route-index out of bounds");
1355 _searchResultIndex = aIndex;
1356 SGWayPoint wp(_routeMgr->get_waypoint(aIndex));
1357 _scratchNode->setStringValue("name", wp.get_name());
1358 _scratchNode->setStringValue("ident", wp.get_id());
1359 _scratchPos = wp.get_target();
1360 _scratchValid = true;
1361 _scratchNode->setDoubleValue("course", wp.get_track());
1362 _scratchNode->setIntValue("index", aIndex);
1364 int lastResult = _routeMgr->size() - 1;
1365 _searchHasNext = (_searchResultIndex < lastResult);
1368 void GPS::loadNearest()
1370 string sty(_scratchNode->getStringValue("type"));
1371 FGPositioned::Type ty = FGPositioned::typeFromName(sty);
1372 if (ty == FGPositioned::INVALID) {
1373 SG_LOG(SG_INSTR, SG_WARN, "GPS:loadNearest: request type is invalid:" << sty);
1377 auto_ptr<FGPositioned::Filter> f(createFilter(ty));
1378 int limitCount = _scratchNode->getIntValue("max-results", 1);
1379 double cutoffDistance = _scratchNode->getDoubleValue("cutoff-nm", 400.0);
1381 clearScratch(); // clear now, regardless of whether we find a match or not
1384 FGPositioned::findClosestN(_indicated_pos, limitCount, cutoffDistance, f.get());
1385 _searchResultsCached = true;
1386 _searchResultIndex = 0;
1387 _searchIsRoute = false;
1388 _searchHasNext = false;
1390 if (_searchResults.empty()) {
1391 SG_LOG(SG_INSTR, SG_INFO, "GPS:loadNearest: no matches at all");
1395 _searchHasNext = (_searchResults.size() > 1);
1396 setScratchFromCachedSearchResult();
1399 bool GPS::SearchFilter::pass(FGPositioned* aPos) const
1401 switch (aPos->type()) {
1402 case FGPositioned::AIRPORT:
1403 // heliport and seaport too?
1404 case FGPositioned::VOR:
1405 case FGPositioned::NDB:
1406 case FGPositioned::FIX:
1407 case FGPositioned::TACAN:
1408 case FGPositioned::WAYPOINT:
1415 FGPositioned::Type GPS::SearchFilter::minType() const
1417 return FGPositioned::AIRPORT;
1420 FGPositioned::Type GPS::SearchFilter::maxType() const
1422 return FGPositioned::WAYPOINT;
1425 FGPositioned::Filter* GPS::createFilter(FGPositioned::Type aTy)
1427 if (aTy == FGPositioned::AIRPORT) {
1428 return new FGAirport::HardSurfaceFilter(_config.minRunwayLengthFt());
1431 // if we were passed INVALID, assume it means 'all types interesting to a GPS'
1432 if (aTy == FGPositioned::INVALID) {
1433 return new SearchFilter;
1436 return new FGPositioned::TypeFilter(aTy);
1441 // parse search terms into local members, and exec the first search
1442 string sty(_scratchNode->getStringValue("type"));
1443 _searchType = FGPositioned::typeFromName(sty);
1444 _searchQuery = _scratchNode->getStringValue("query");
1445 _searchExact = _scratchNode->getBoolValue("exact", true);
1446 _searchOrderByRange = _scratchNode->getBoolValue("order-by-distance", true);
1447 _searchResultIndex = 0;
1448 _searchIsRoute = false;
1449 _searchHasNext = false;
1451 if (_searchExact && _searchOrderByRange) {
1452 // immediate mode search, get all the results now and cache them
1453 auto_ptr<FGPositioned::Filter> f(createFilter(_searchType));
1455 _searchResults = FGPositioned::findAllWithNameSortedByRange(_searchQuery, _indicated_pos, f.get());
1457 _searchResults = FGPositioned::findAllWithIdentSortedByRange(_searchQuery, _indicated_pos, f.get());
1460 _searchResultsCached = true;
1462 if (_searchResults.empty()) {
1467 _searchHasNext = (_searchResults.size() > 1);
1468 setScratchFromCachedSearchResult();
1470 // iterative search, look up result zero
1471 _searchResultsCached = false;
1476 void GPS::performSearch()
1478 auto_ptr<FGPositioned::Filter> f(createFilter(_searchType));
1483 if (_searchOrderByRange) {
1484 r = FGPositioned::findClosestWithPartialName(_indicated_pos, _searchQuery, f.get(), _searchResultIndex, _searchHasNext);
1486 r = FGPositioned::findWithPartialName(_searchQuery, f.get(), _searchResultIndex, _searchHasNext);
1489 if (_searchOrderByRange) {
1490 r = FGPositioned::findClosestWithPartialId(_indicated_pos, _searchQuery, f.get(), _searchResultIndex, _searchHasNext);
1492 r = FGPositioned::findWithPartialId(_searchQuery, f.get(), _searchResultIndex, _searchHasNext);
1500 setScratchFromPositioned(r.get(), _searchResultIndex);
1503 void GPS::setScratchFromCachedSearchResult()
1505 assert(_searchResultsCached);
1506 int index = _searchResultIndex;
1508 if ((index < 0) || (index >= (int) _searchResults.size())) {
1509 SG_LOG(SG_INSTR, SG_WARN, "GPS:setScratchFromCachedSearchResult: index out of bounds:" << index);
1513 setScratchFromPositioned(_searchResults[index], index);
1515 int lastResult = (int) _searchResults.size() - 1;
1516 _searchHasNext = (_searchResultIndex < lastResult);
1519 void GPS::setScratchFromPositioned(FGPositioned* aPos, int aIndex)
1524 _scratchPos = aPos->geod();
1525 _scratchNode->setStringValue("name", aPos->name());
1526 _scratchNode->setStringValue("ident", aPos->ident());
1527 _scratchNode->setStringValue("type", FGPositioned::nameForType(aPos->type()));
1530 _scratchNode->setIntValue("index", aIndex);
1533 _scratchValid = true;
1534 if (_searchResultsCached) {
1535 _scratchNode->setIntValue("result-count", _searchResults.size());
1538 switch (aPos->type()) {
1539 case FGPositioned::VOR:
1540 _scratchNode->setDoubleValue("frequency-mhz", static_cast<FGNavRecord*>(aPos)->get_freq() / 100.0);
1543 case FGPositioned::NDB:
1544 _scratchNode->setDoubleValue("frequency-khz", static_cast<FGNavRecord*>(aPos)->get_freq() / 100.0);
1547 case FGPositioned::AIRPORT:
1548 addAirportToScratch((FGAirport*)aPos);
1556 // look for being on the route and set?
1559 void GPS::addAirportToScratch(FGAirport* aAirport)
1561 for (unsigned int r=0; r<aAirport->numRunways(); ++r) {
1562 SGPropertyNode* rwyNd = _scratchNode->getChild("runways", r, true);
1563 FGRunway* rwy = aAirport->getRunwayByIndex(r);
1564 // TODO - filter out unsuitable runways in the future
1565 // based on config again
1567 rwyNd->setStringValue("id", rwy->ident().c_str());
1568 rwyNd->setIntValue("length-ft", rwy->lengthFt());
1569 rwyNd->setIntValue("width-ft", rwy->widthFt());
1570 rwyNd->setIntValue("heading-deg", rwy->headingDeg());
1571 // map surface code to a string
1572 // TODO - lighting information
1575 rwyNd->setDoubleValue("ils-frequency-mhz", rwy->ILS()->get_freq() / 100.0);
1577 } // of runways iteration
1581 void GPS::selectOBSMode()
1583 if (!isScratchPositionValid()) {
1584 SG_LOG(SG_INSTR, SG_WARN, "invalid OBS lat/lon");
1588 SG_LOG(SG_INSTR, SG_INFO, "GPS switching to OBS mode");
1591 _wp1Ident = _scratchNode->getStringValue("ident");
1592 _wp1Name = _scratchNode->getStringValue("name");
1593 _wp1_position = _scratchPos;
1594 _wp0_position = _indicated_pos;
1598 void GPS::selectLegMode()
1600 if (_mode == "leg") {
1604 if (!_routeMgr->isRouteActive()) {
1605 SG_LOG(SG_INSTR, SG_WARN, "GPS:selectLegMode: no active route");
1609 SG_LOG(SG_INSTR, SG_INFO, "GPS switching to LEG mode");
1612 // not really sequenced, but does all the work of updating wp0/1
1613 routeManagerSequenced();
1616 void GPS::nextResult()
1618 if (!_searchHasNext) {
1623 if (_searchIsRoute) {
1624 setScratchFromRouteWaypoint(++_searchResultIndex);
1625 } else if (_searchResultsCached) {
1626 ++_searchResultIndex;
1627 setScratchFromCachedSearchResult();
1629 ++_searchResultIndex;
1631 } // of iterative search case
1634 void GPS::previousResult()
1636 if (_searchResultIndex <= 0) {
1641 --_searchResultIndex;
1643 if (_searchIsRoute) {
1644 setScratchFromRouteWaypoint(_searchResultIndex);
1645 } else if (_searchResultsCached) {
1646 setScratchFromCachedSearchResult();
1652 void GPS::defineWaypoint()
1654 if (!isScratchPositionValid()) {
1655 SG_LOG(SG_INSTR, SG_WARN, "GPS:defineWaypoint: invalid lat/lon");
1659 string ident = _scratchNode->getStringValue("ident");
1660 if (ident.size() < 2) {
1661 SG_LOG(SG_INSTR, SG_WARN, "GPS:defineWaypoint: waypoint identifier must be at least two characters");
1665 // check for duplicate idents
1666 FGPositioned::TypeFilter f(FGPositioned::WAYPOINT);
1667 FGPositioned::List dups = FGPositioned::findAllWithIdentSortedByRange(ident, _indicated_pos, &f);
1668 if (!dups.empty()) {
1669 SG_LOG(SG_INSTR, SG_WARN, "GPS:defineWaypoint: non-unique waypoint identifier, ho-hum");
1672 SG_LOG(SG_INSTR, SG_INFO, "GPS:defineWaypoint: creating waypoint:" << ident);
1673 FGPositionedRef wpt = FGPositioned::createUserWaypoint(ident, _scratchPos);
1674 _searchResultsCached = false;
1675 setScratchFromPositioned(wpt.get(), -1);