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>
27 #include <simgear/structure/exception.hxx>
32 ///////////////////////////////////////////////////////////////////
34 void SGGeodProperty::init(SGPropertyNode* base, const char* lonStr, const char* latStr, const char* altStr)
36 _lon = base->getChild(lonStr, 0, true);
37 _lat = base->getChild(latStr, 0, true);
39 _alt = base->getChild(altStr, 0, true);
43 void SGGeodProperty::init(const char* lonStr, const char* latStr, const char* altStr)
45 _lon = fgGetNode(lonStr, true);
46 _lat = fgGetNode(latStr, true);
48 _alt = fgGetNode(altStr, true);
52 void SGGeodProperty::clear()
54 _lon = _lat = _alt = NULL;
57 void SGGeodProperty::operator=(const SGGeod& geod)
59 _lon->setDoubleValue(geod.getLongitudeDeg());
60 _lat->setDoubleValue(geod.getLatitudeDeg());
62 _alt->setDoubleValue(geod.getElevationFt());
66 SGGeod SGGeodProperty::get() const
68 double lon = _lon->getDoubleValue(),
69 lat = _lat->getDoubleValue();
71 return SGGeod::fromDegFt(lon, lat, _alt->getDoubleValue());
73 return SGGeod::fromDeg(lon,lat);
77 static void tieSGGeod(SGPropertyNode* aNode, SGGeod& aRef,
78 const char* lonStr, const char* latStr, const char* altStr)
80 aNode->tie(lonStr, SGRawValueMethods<SGGeod, double>(aRef, &SGGeod::getLongitudeDeg, &SGGeod::setLongitudeDeg));
81 aNode->tie(latStr, SGRawValueMethods<SGGeod, double>(aRef, &SGGeod::getLatitudeDeg, &SGGeod::setLatitudeDeg));
84 aNode->tie(altStr, SGRawValueMethods<SGGeod, double>(aRef, &SGGeod::getElevationFt, &SGGeod::setElevationFt));
88 static void tieSGGeodReadOnly(SGPropertyNode* aNode, SGGeod& aRef,
89 const char* lonStr, const char* latStr, const char* altStr)
91 aNode->tie(lonStr, SGRawValueMethods<SGGeod, double>(aRef, &SGGeod::getLongitudeDeg, NULL));
92 aNode->tie(latStr, SGRawValueMethods<SGGeod, double>(aRef, &SGGeod::getLatitudeDeg, NULL));
95 aNode->tie(altStr, SGRawValueMethods<SGGeod, double>(aRef, &SGGeod::getElevationFt, NULL));
99 static const char* makeTTWString(double TTW)
101 if ((TTW <= 0.0) || (TTW >= 356400.5)) { // 99 hours
105 unsigned int TTW_seconds = (int) (TTW + 0.5);
106 unsigned int TTW_minutes = 0;
107 unsigned int TTW_hours = 0;
108 static char TTW_str[9];
109 TTW_hours = TTW_seconds / 3600;
110 TTW_minutes = (TTW_seconds / 60) % 60;
111 TTW_seconds = TTW_seconds % 60;
112 snprintf(TTW_str, 9, "%02d:%02d:%02d",
113 TTW_hours, TTW_minutes, TTW_seconds);
117 /////////////////////////////////////////////////////////////////////////////
119 class GPSListener : public SGPropertyChangeListener
122 GPSListener(GPS *m) :
126 virtual void valueChanged (SGPropertyNode * prop)
133 if (prop == _gps->_route_current_wp_node) {
134 _gps->routeManagerSequenced();
135 } else if (prop == _gps->_route_active_node) {
136 _gps->routeActivated();
137 } else if (prop == _gps->_ref_navaid_id_node) {
138 _gps->referenceNavaidSet(prop->getStringValue(""));
139 } else if (prop == _gps->_routeEditedSignal) {
141 } else if (prop == _gps->_routeFinishedSignal) {
142 _gps->routeFinished();
148 void setGuard(bool g) {
153 bool _guard; // re-entrancy guard
156 ////////////////////////////////////////////////////////////////////////////
158 * Helper to monitor for Nasal or other code accessing properties we haven't
159 * defined. For the moment we complain about all such activites, since various
160 * users assume all kinds of weird, wonderful and non-existent interfaces.
163 class DeprecatedPropListener : public SGPropertyChangeListener
166 DeprecatedPropListener(SGPropertyNode* gps)
168 _parents.insert(gps);
169 SGPropertyNode* wp = gps->getChild("wp");
171 _parents.insert(wp->getChild("wp", 0));
172 _parents.insert(wp->getChild("wp", 1));
174 std::set<SGPropertyNode*>::iterator it;
175 for (it = _parents.begin(); it != _parents.end(); ++it) {
176 (*it)->addChangeListener(this);
180 virtual void valueChanged (SGPropertyNode * prop)
184 virtual void childAdded (SGPropertyNode * parent, SGPropertyNode * child)
186 if (isDeprecated(parent, child)) {
187 SG_LOG(SG_INSTR, SG_WARN, "GPS: someone accessed a deprecated property:"
188 << child->getPath(true));
192 bool isDeprecated(SGPropertyNode * parent, SGPropertyNode * child) const
194 if (_parents.count(parent) < 1) {
198 // no child exclusions yet
202 std::set<SGPropertyNode*> _parents;
205 ////////////////////////////////////////////////////////////////////////////
206 // configuration helper object
208 GPS::Config::Config() :
209 _enableTurnAnticipation(true),
210 _turnRate(3.0), // degrees-per-second, so 180 degree turn takes 60 seconds
211 _overflightArmDistance(0.5),
212 _waypointAlertTime(30.0),
213 _tuneRadio1ToRefVor(false),
214 _minRunwayLengthFt(0.0),
215 _requireHardSurface(true),
216 _cdiMaxDeflectionNm(-1), // default to angular mode
217 _driveAutopilot(true)
219 _enableTurnAnticipation = false;
220 _extCourseSource = fgGetNode("/instrumentation/nav[0]/radials/selected-deg", true);
223 void GPS::Config::init(SGPropertyNode* aCfgNode)
225 aCfgNode->tie("turn-rate-deg-sec", SGRawValuePointer<double>(&_turnRate));
226 aCfgNode->tie("turn-anticipation", SGRawValuePointer<bool>(&_enableTurnAnticipation));
227 aCfgNode->tie("wpt-alert-time", SGRawValuePointer<double>(&_waypointAlertTime));
228 aCfgNode->tie("tune-nav-radio-to-ref-vor", SGRawValuePointer<bool>(&_tuneRadio1ToRefVor));
229 aCfgNode->tie("min-runway-length-ft", SGRawValuePointer<double>(&_minRunwayLengthFt));
230 aCfgNode->tie("hard-surface-runways-only", SGRawValuePointer<bool>(&_requireHardSurface));
232 aCfgNode->tie("course-source", SGRawValueMethods<GPS::Config, const char*>
233 (*this, &GPS::Config::getCourseSource, &GPS::Config::setCourseSource));
235 aCfgNode->tie("cdi-max-deflection-nm", SGRawValuePointer<double>(&_cdiMaxDeflectionNm));
236 aCfgNode->tie("drive-autopilot", SGRawValuePointer<bool>(&_driveAutopilot));
240 GPS::Config::getCourseSource() const
242 if (!_extCourseSource) {
246 return _extCourseSource->getPath(true);
250 GPS::Config::setCourseSource(const char* aPath)
252 SGPropertyNode* nd = fgGetNode(aPath, false);
254 SG_LOG(SG_INSTR, SG_WARN, "couldn't find course source at:" << aPath);
255 _extCourseSource = NULL;
258 _extCourseSource = nd;
262 GPS::Config::getExternalCourse() const
264 if (!_extCourseSource) {
268 return _extCourseSource->getDoubleValue();
272 GPS::Config::setExternalCourse(double aCourseDeg)
274 if (!_extCourseSource) {
278 _extCourseSource->setDoubleValue(aCourseDeg);
281 ////////////////////////////////////////////////////////////////////////////
283 GPS::GPS ( SGPropertyNode *node) :
284 _selectedCourse(0.0),
286 _lastPosValid(false),
288 _name(node->getStringValue("name", "gps")),
289 _num(node->getIntValue("number", 0)),
290 _computeTurnData(false),
291 _anticipateTurn(false),
303 _routeMgr = (FGRouteMgr*) globals->get_subsystem("route-manager");
307 branch = "/instrumentation/" + _name;
309 SGPropertyNode *node = fgGetNode(branch.c_str(), _num, true );
310 _config.init(node->getChild("config", 0, true));
312 _position.init("/position/longitude-deg", "/position/latitude-deg", "/position/altitude-ft");
313 _magvar_node = fgGetNode("/environment/magnetic-variation-deg", true);
314 _serviceable_node = node->getChild("serviceable", 0, true);
315 _serviceable_node->setBoolValue(true);
316 _electrical_node = fgGetNode("/systems/electrical/outputs/gps", true);
319 node->tie("selected-course-deg", SGRawValueMethods<GPS, double>(*this, &GPS::getSelectedCourse, NULL));
321 _raim_node = node->getChild("raim", 0, true);
323 tieSGGeodReadOnly(node, _indicated_pos, "indicated-longitude-deg",
324 "indicated-latitude-deg", "indicated-altitude-ft");
326 node->tie("indicated-vertical-speed", SGRawValueMethods<GPS, double>
327 (*this, &GPS::getVerticalSpeed, NULL));
328 node->tie("indicated-track-true-deg", SGRawValueMethods<GPS, double>
329 (*this, &GPS::getTrueTrack, NULL));
330 node->tie("indicated-track-magnetic-deg", SGRawValueMethods<GPS, double>
331 (*this, &GPS::getMagTrack, NULL));
332 node->tie("indicated-ground-speed-kt", SGRawValueMethods<GPS, double>
333 (*this, &GPS::getGroundspeedKts, NULL));
335 _odometer_node = node->getChild("odometer", 0, true);
336 _trip_odometer_node = node->getChild("trip-odometer", 0, true);
337 _true_bug_error_node = node->getChild("true-bug-error-deg", 0, true);
338 _magnetic_bug_error_node = node->getChild("magnetic-bug-error-deg", 0, true);
341 node->tie("mode", SGRawValueMethods<GPS, const char*>(*this, &GPS::getMode, NULL));
342 node->tie("command", SGRawValueMethods<GPS, const char*>(*this, &GPS::getCommand, &GPS::setCommand));
344 _scratchNode = node->getChild("scratch", 0, true);
345 tieSGGeod(_scratchNode, _scratchPos, "longitude-deg", "latitude-deg", "altitude-ft");
346 _scratchNode->tie("valid", SGRawValueMethods<GPS, bool>(*this, &GPS::getScratchValid, NULL));
347 _scratchNode->tie("distance-nm", SGRawValueMethods<GPS, double>(*this, &GPS::getScratchDistance, NULL));
348 _scratchNode->tie("true-bearing-deg", SGRawValueMethods<GPS, double>(*this, &GPS::getScratchTrueBearing, NULL));
349 _scratchNode->tie("mag-bearing-deg", SGRawValueMethods<GPS, double>(*this, &GPS::getScratchMagBearing, NULL));
350 _scratchNode->tie("has-next", SGRawValueMethods<GPS, bool>(*this, &GPS::getScratchHasNext, NULL));
351 _scratchValid = false;
353 // waypoint data (including various historical things)
354 SGPropertyNode *wp_node = node->getChild("wp", 0, true);
355 SGPropertyNode *wp0_node = wp_node->getChild("wp", 0, true);
356 SGPropertyNode *wp1_node = wp_node->getChild("wp", 1, true);
358 tieSGGeodReadOnly(wp0_node, _wp0_position, "longitude-deg", "latitude-deg", "altitude-ft");
359 wp0_node->tie("ID", SGRawValueMethods<GPS, const char*>
360 (*this, &GPS::getWP0Ident, NULL));
361 wp0_node->tie("name", SGRawValueMethods<GPS, const char*>
362 (*this, &GPS::getWP0Name, NULL));
364 tieSGGeodReadOnly(wp1_node, _wp1_position, "longitude-deg", "latitude-deg", "altitude-ft");
365 wp1_node->tie("ID", SGRawValueMethods<GPS, const char*>
366 (*this, &GPS::getWP1Ident, NULL));
367 wp1_node->tie("name", SGRawValueMethods<GPS, const char*>
368 (*this, &GPS::getWP1Name, NULL));
370 // for compatability, alias selected course down to wp/wp[1]/desired-course-deg
371 SGPropertyNode* wp1Crs = wp1_node->getChild("desired-course-deg", 0, true);
372 wp1Crs->alias(node->getChild("selected-course-deg"));
374 // _true_wp1_bearing_error_node =
375 // wp1_node->getChild("true-bearing-error-deg", 0, true);
376 // _magnetic_wp1_bearing_error_node =
377 // wp1_node->getChild("magnetic-bearing-error-deg", 0, true);
379 wp1_node->tie("distance-nm", SGRawValueMethods<GPS, double>
380 (*this, &GPS::getWP1Distance, NULL));
381 wp1_node->tie("bearing-true-deg", SGRawValueMethods<GPS, double>
382 (*this, &GPS::getWP1Bearing, NULL));
383 wp1_node->tie("bearing-mag-deg", SGRawValueMethods<GPS, double>
384 (*this, &GPS::getWP1MagBearing, NULL));
385 wp1_node->tie("TTW-sec", SGRawValueMethods<GPS, double>
386 (*this, &GPS::getWP1TTW, NULL));
387 wp1_node->tie("TTW", SGRawValueMethods<GPS, const char*>
388 (*this, &GPS::getWP1TTWString, NULL));
390 wp1_node->tie("course-deviation-deg", SGRawValueMethods<GPS, double>
391 (*this, &GPS::getWP1CourseDeviation, NULL));
392 wp1_node->tie("course-error-nm", SGRawValueMethods<GPS, double>
393 (*this, &GPS::getWP1CourseErrorNm, NULL));
394 wp1_node->tie("to-flag", SGRawValueMethods<GPS, bool>
395 (*this, &GPS::getWP1ToFlag, NULL));
396 wp1_node->tie("from-flag", SGRawValueMethods<GPS, bool>
397 (*this, &GPS::getWP1FromFlag, NULL));
399 _tracking_bug_node = node->getChild("tracking-bug", 0, true);
401 // leg properties (only valid in DTO/LEG modes, not OBS)
402 wp_node->tie("leg-distance-nm", SGRawValueMethods<GPS, double>(*this, &GPS::getLegDistance, NULL));
403 wp_node->tie("leg-true-course-deg", SGRawValueMethods<GPS, double>(*this, &GPS::getLegCourse, NULL));
404 wp_node->tie("leg-mag-course-deg", SGRawValueMethods<GPS, double>(*this, &GPS::getLegMagCourse, NULL));
405 wp_node->tie("alt-dist-ratio", SGRawValueMethods<GPS, double>(*this, &GPS::getAltDistanceRatio, NULL));
408 SGPropertyNode_ptr ref_navaid = node->getChild("ref-navaid", 0, true);
409 _ref_navaid_id_node = ref_navaid->getChild("id", 0, true);
410 _ref_navaid_name_node = ref_navaid->getChild("name", 0, true);
411 _ref_navaid_bearing_node = ref_navaid->getChild("bearing-deg", 0, true);
412 _ref_navaid_frequency_node = ref_navaid->getChild("frequency-mhz", 0, true);
413 _ref_navaid_distance_node = ref_navaid->getChild("distance-nm", 0, true);
414 _ref_navaid_mag_bearing_node = ref_navaid->getChild("mag-bearing-deg", 0, true);
415 _ref_navaid_elapsed = 0.0;
416 _ref_navaid_set = false;
419 // should these move to the route manager?
420 _routeDistanceNm = node->getChild("route-distance-nm", 0, true);
421 _routeETE = node->getChild("ETE", 0, true);
422 _routeEditedSignal = fgGetNode("/autopilot/route-manager/signals/edited", true);
423 _routeFinishedSignal = fgGetNode("/autopilot/route-manager/signals/finished", true);
425 // add listener to various things
426 _listener = new GPSListener(this);
427 _route_current_wp_node = fgGetNode("/autopilot/route-manager/current-wp", true);
428 _route_current_wp_node->addChangeListener(_listener);
429 _route_active_node = fgGetNode("/autopilot/route-manager/active", true);
430 _route_active_node->addChangeListener(_listener);
431 _ref_navaid_id_node->addChangeListener(_listener);
432 _routeEditedSignal->addChangeListener(_listener);
433 _routeFinishedSignal->addChangeListener(_listener);
435 // navradio slaving properties
436 node->tie("cdi-deflection", SGRawValueMethods<GPS,double>
437 (*this, &GPS::getCDIDeflection));
439 SGPropertyNode* toFlag = node->getChild("to-flag", 0, true);
440 toFlag->alias(wp1_node->getChild("to-flag"));
442 SGPropertyNode* fromFlag = node->getChild("from-flag", 0, true);
443 fromFlag->alias(wp1_node->getChild("from-flag"));
446 // autopilot drive properties
447 _apTrueHeading = fgGetNode("/autopilot/settings/true-heading-deg",true);
448 _apTargetAltitudeFt = fgGetNode("/autopilot/settings/target-altitude-ft", true);
449 _apAltitudeLock = fgGetNode("/autopilot/locks/altitude", true);
452 _realismSimpleGps = fgGetNode("/sim/realism/simple-gps", true);
453 if (!_realismSimpleGps->hasValue()) {
454 _realismSimpleGps->setBoolValue(true);
457 // last thing, add the deprecated prop watcher
458 new DeprecatedPropListener(node);
467 _last_speed_kts = 0.0;
468 _last_pos = SGGeod();
469 _lastPosValid = false;
470 _indicated_pos = SGGeod();
471 _last_vertical_speed = 0.0;
472 _last_true_track = 0.0;
474 _raim_node->setDoubleValue(0.0);
475 _indicated_pos = SGGeod();
477 _wp1TrueBearing = 0.0;
478 _wp1_position = SGGeod();
479 _odometer_node->setDoubleValue(0);
480 _trip_odometer_node->setDoubleValue(0);
481 _tracking_bug_node->setDoubleValue(0);
482 _true_bug_error_node->setDoubleValue(0);
483 _magnetic_bug_error_node->setDoubleValue(0);
487 GPS::update (double delta_time_sec)
489 if (!_realismSimpleGps->getBoolValue()) {
490 // If it's off, don't bother.
491 if (!_serviceable_node->getBoolValue() || !_electrical_node->getBoolValue()) {
497 if (delta_time_sec <= 0.0) {
498 return; // paused, don't bother
500 // TODO: Add noise and other errors.
503 // Bias and random error
504 double random_factor = sg_random();
505 double random_error = 1.4;
506 double error_radius = 5.1;
507 double bias_max_radius = 5.1;
508 double random_max_radius = 1.4;
510 bias_length += (random_factor-0.5) * 1.0e-3;
511 if (bias_length <= 0.0) bias_length = 0.0;
512 else if (bias_length >= bias_max_radius) bias_length = bias_max_radius;
513 bias_angle += (random_factor-0.5) * 1.0e-3;
514 if (bias_angle <= 0.0) bias_angle = 0.0;
515 else if (bias_angle >= 360.0) bias_angle = 360.0;
517 double random_length = random_factor * random_max_radius;
518 double random_angle = random_factor * 360.0;
520 double bias_x = bias_length * cos(bias_angle * SG_PI / 180.0);
521 double bias_y = bias_length * sin(bias_angle * SG_PI / 180.0);
522 double random_x = random_length * cos(random_angle * SG_PI / 180.0);
523 double random_y = random_length * sin(random_angle * SG_PI / 180.0);
524 double error_x = bias_x + random_x;
525 double error_y = bias_y + random_y;
526 double error_length = sqrt(error_x*error_x + error_y*error_y);
527 double error_angle = atan(error_y / error_x) * 180.0 / SG_PI;
532 geo_direct_wgs_84 ( altitude_m, latitude_deg,
533 longitude_deg, error_angle,
534 error_length, &lat2, &lon2,
536 //cout << lat2 << " " << lon2 << endl;
537 printf("%f %f \n", bias_length, bias_angle);
538 printf("%3.7f %3.7f \n", lat2, lon2);
539 printf("%f %f \n", error_length, error_angle);
542 _raim_node->setDoubleValue(1.0);
543 _indicated_pos = _position.get();
544 updateBasicData(delta_time_sec);
547 if (_mode == "obs") {
548 _selectedCourse = _config.getExternalCourse();
555 updateReferenceNavaid(delta_time_sec);
560 if (_dataValid && (_mode == "init")) {
561 // allow a realistic delay in the future, here
562 SG_LOG(SG_INSTR, SG_INFO, "GPS initialisation complete");
564 _selectedCourse = _config.getExternalCourse();
566 if (_route_active_node->getBoolValue()) {
567 // GPS init with active route
568 SG_LOG(SG_INSTR, SG_INFO, "GPS init with active route");
571 // initialise in OBS mode, with waypt set to the nearest airport.
572 // keep in mind at this point, _dataValid is not set
574 auto_ptr<FGPositioned::Filter> f(createFilter(FGPositioned::AIRPORT));
575 FGPositionedRef apt = FGPositioned::findClosest(_position.get(), 20.0, f.get());
577 setScratchFromPositioned(apt, 0);
581 } // of init mode check
583 _last_pos = _indicated_pos;
584 _lastPosValid = true;
588 GPS::updateBasicData(double dt)
590 if (!_lastPosValid) {
596 SGGeodesy::inverse(_last_pos, _indicated_pos, _last_true_track, track2_deg, distance_m );
598 double speed_kt = ((distance_m * SG_METER_TO_NM) * ((1 / dt) * 3600.0));
599 double vertical_speed_mpm = ((_indicated_pos.getElevationM() - _last_pos.getElevationM()) * 60 / dt);
600 _last_vertical_speed = vertical_speed_mpm * SG_METER_TO_FEET;
602 speed_kt = fgGetLowPass(_last_speed_kts, speed_kt, dt/20.0);
603 _last_speed_kts = speed_kt;
605 double odometer = _odometer_node->getDoubleValue();
606 _odometer_node->setDoubleValue(odometer + distance_m * SG_METER_TO_NM);
607 odometer = _trip_odometer_node->getDoubleValue();
608 _trip_odometer_node->setDoubleValue(odometer + distance_m * SG_METER_TO_NM);
611 SG_LOG(SG_INSTR, SG_INFO, "GPS setting data valid");
617 GPS::updateTrackingBug()
619 double tracking_bug = _tracking_bug_node->getDoubleValue();
620 double true_bug_error = tracking_bug - getTrueTrack();
621 double magnetic_bug_error = tracking_bug - getMagTrack();
623 // Get the errors into the (-180,180) range.
624 SG_NORMALIZE_RANGE(true_bug_error, -180.0, 180.0);
625 SG_NORMALIZE_RANGE(magnetic_bug_error, -180.0, 180.0);
627 _true_bug_error_node->setDoubleValue(true_bug_error);
628 _magnetic_bug_error_node->setDoubleValue(magnetic_bug_error);
632 GPS::updateWaypoints()
635 SGGeodesy::inverse(_indicated_pos, _wp1_position, _wp1TrueBearing, az2,_wp1DistanceM);
638 void GPS::updateReferenceNavaid(double dt)
640 if (!_ref_navaid_set) {
641 _ref_navaid_elapsed += dt;
642 if (_ref_navaid_elapsed > 5.0) {
643 _ref_navaid_elapsed = 0.0;
645 FGPositioned::TypeFilter vorFilter(FGPositioned::VOR);
646 FGPositionedRef nav = FGPositioned::findClosest(_indicated_pos, 400.0, &vorFilter);
648 SG_LOG(SG_INSTR, SG_INFO, "GPS couldn't find a reference navid");
649 _ref_navaid_id_node->setStringValue("");
650 _ref_navaid_name_node->setStringValue("");
651 _ref_navaid_bearing_node->setDoubleValue(0.0);
652 _ref_navaid_mag_bearing_node->setDoubleValue(0.0);
653 _ref_navaid_distance_node->setDoubleValue(0.0);
654 _ref_navaid_frequency_node->setStringValue("");
655 } else if (nav != _ref_navaid) {
656 SG_LOG(SG_INSTR, SG_INFO, "GPS code selected new ref-navaid:" << nav->ident());
657 _listener->setGuard(true);
658 _ref_navaid_id_node->setStringValue(nav->ident().c_str());
659 _ref_navaid_name_node->setStringValue(nav->name().c_str());
660 FGNavRecord* vor = (FGNavRecord*) nav.ptr();
661 _ref_navaid_frequency_node->setDoubleValue(vor->get_freq() / 100.0);
662 _listener->setGuard(false);
665 // SG_LOG(SG_INSTR, SG_ALERT, "matched existing");
673 double trueCourse, distanceM, az2;
674 SGGeodesy::inverse(_indicated_pos, _ref_navaid->geod(), trueCourse, az2, distanceM);
675 _ref_navaid_distance_node->setDoubleValue(distanceM * SG_METER_TO_NM);
676 _ref_navaid_bearing_node->setDoubleValue(trueCourse);
677 _ref_navaid_mag_bearing_node->setDoubleValue(trueCourse - _magvar_node->getDoubleValue());
681 void GPS::referenceNavaidSet(const std::string& aNavaid)
684 // allow setting an empty string to restore normal nearest-vor selection
685 if (aNavaid.size() > 0) {
686 FGPositioned::TypeFilter vorFilter(FGPositioned::VOR);
687 _ref_navaid = FGPositioned::findClosestWithIdent(aNavaid,
688 _position.get(), &vorFilter);
691 SG_LOG(SG_INSTR, SG_ALERT, "GPS: unknown ref navaid:" << aNavaid);
696 _ref_navaid_set = true;
697 SG_LOG(SG_INSTR, SG_INFO, "GPS code set explict ref-navaid:" << _ref_navaid->ident());
698 _ref_navaid_id_node->setStringValue(_ref_navaid->ident().c_str());
699 _ref_navaid_name_node->setStringValue(_ref_navaid->name().c_str());
700 FGNavRecord* vor = (FGNavRecord*) _ref_navaid.ptr();
701 _ref_navaid_frequency_node->setDoubleValue(vor->get_freq() / 100.0);
704 _ref_navaid_set = false;
705 _ref_navaid_elapsed = 9999.0; // update next tick
709 void GPS::tuneNavRadios()
711 if (!_ref_navaid || !_config.tuneNavRadioToRefVor()) {
715 SGPropertyNode_ptr navRadio1 = fgGetNode("/instrumentation/nav", false);
720 FGNavRecord* vor = (FGNavRecord*) _ref_navaid.ptr();
721 SGPropertyNode_ptr freqs = navRadio1->getChild("frequencies");
722 freqs->setDoubleValue("selected-mhz", vor->get_freq() / 100.0);
725 void GPS::routeActivated()
727 if (_route_active_node->getBoolValue()) {
728 SG_LOG(SG_INSTR, SG_INFO, "GPS::route activated, switching to LEG mode");
731 // if we've already passed the current waypoint, sequence.
732 if (_dataValid && getWP1FromFlag()) {
733 SG_LOG(SG_INSTR, SG_INFO, "GPS::route activated, FROM wp1, sequencing");
734 _routeMgr->sequence();
736 } else if (_mode == "leg") {
737 SG_LOG(SG_INSTR, SG_INFO, "GPS::route deactivated, switching to OBS mode");
742 void GPS::routeManagerSequenced()
744 if (_mode != "leg") {
745 SG_LOG(SG_INSTR, SG_INFO, "GPS ignoring route sequencing, not in LEG mode");
749 int index = _routeMgr->currentWaypoint(),
750 count = _routeMgr->size();
751 if ((index < 0) || (index >= count)) {
752 SG_LOG(SG_INSTR, SG_ALERT, "GPS: malformed route, index=" << index);
756 SG_LOG(SG_INSTR, SG_INFO, "GPS waypoint index is now " << index);
759 SGWayPoint wp0(_routeMgr->get_waypoint(index - 1));
760 _wp0Ident = wp0.get_id();
761 _wp0Name = wp0.get_name();
762 _wp0_position = wp0.get_target();
766 SGWayPoint wp1(_routeMgr->get_waypoint(index));
767 _wp1Ident = wp1.get_id();
768 _wp1Name = wp1.get_name();
769 _wp1_position = wp1.get_target();
771 _selectedCourse = getLegMagCourse();
775 void GPS::routeEdited()
777 if (_mode != "leg") {
781 SG_LOG(SG_INSTR, SG_INFO, "GPS route edited while in LEG mode, updating waypoints");
782 routeManagerSequenced();
785 void GPS::routeFinished()
787 if (_mode != "leg") {
791 SG_LOG(SG_INSTR, SG_INFO, "GPS route finished, reverting to OBS");
793 _wp0_position = _indicated_pos;
797 void GPS::updateTurn()
799 bool printProgress = false;
801 if (_computeTurnData) {
802 if (_last_speed_kts < 60) {
803 // need valid leg course and sensible ground speed to compute the turn
808 printProgress = true;
811 if (!_anticipateTurn) {
817 // find bearing to turn centre
818 double bearing, az2, distanceM;
819 SGGeodesy::inverse(_indicated_pos, _turnCentre, bearing, az2, distanceM);
820 double progress = computeTurnProgress(bearing);
823 SG_LOG(SG_INSTR, SG_INFO,"turn progress=" << progress);
826 if (!_inTurn && (progress > 0.0)) {
830 if (_inTurn && !_turnSequenced && (progress > 0.5)) {
831 _turnSequenced = true;
832 SG_LOG(SG_INSTR, SG_INFO, "turn passed midpoint, sequencing");
833 _routeMgr->sequence();
836 if (_inTurn && (progress >= 1.0)) {
841 // drive deviation and desired course
842 double desiredCourse = bearing - copysign(90, _turnAngle);
843 SG_NORMALIZE_RANGE(desiredCourse, 0.0, 360.0);
844 double deviationNm = (distanceM * SG_METER_TO_NM) - _turnRadius;
845 double deviationDeg = desiredCourse - getMagTrack();
846 deviationNm = copysign(deviationNm, deviationDeg);
848 //_wp1_course_deviation_node->setDoubleValue(deviationDeg);
849 //_wp1_course_error_nm_node->setDoubleValue(deviationNm);
850 //_cdiDeflectionNode->setDoubleValue(deviationDeg);
854 void GPS::updateOverflight()
856 if ((_wp1DistanceM * SG_METER_TO_NM) > _config.overflightArmDistanceNm()) {
860 if (getWP1ToFlag()) {
861 return; // still heading towards the WP
864 if (_mode == "dto") {
865 SG_LOG(SG_INSTR, SG_INFO, "GPS DTO reached destination point");
867 // check for wp1 being on active route - resume leg mode
868 if (_routeMgr->isRouteActive()) {
869 int index = _routeMgr->findWaypoint(_wp1_position);
871 SG_LOG(SG_INSTR, SG_INFO, "GPS DTO, resuming LEG mode at wp:" << index);
873 _routeMgr->jumpToIndex(index);
876 } else if (_mode == "leg") {
877 SG_LOG(SG_INSTR, SG_INFO, "GPS doing overflight sequencing");
878 _routeMgr->sequence();
879 } else if (_mode == "obs") {
880 // nothing to do here, TO/FROM will update but that's fine
883 _computeTurnData = true;
886 void GPS::beginTurn()
889 _turnSequenced = false;
890 SG_LOG(SG_INSTR, SG_INFO, "begining turn");
896 SG_LOG(SG_INSTR, SG_INFO, "ending turn");
897 _computeTurnData = true;
900 double GPS::computeTurnProgress(double aBearing) const
902 double startBearing = _turnStartBearing + copysign(90, _turnAngle);
903 return (aBearing - startBearing) / _turnAngle;
906 void GPS::computeTurnData()
908 _computeTurnData = false;
909 if (_mode != "leg") { // and approach modes in the future
910 _anticipateTurn = false;
914 int curIndex = _routeMgr->currentWaypoint();
915 if ((curIndex + 1) >= _routeMgr->size()) {
916 _anticipateTurn = false;
920 if (!_config.turnAnticipationEnabled()) {
921 _anticipateTurn = false;
925 _turnStartBearing = _selectedCourse;
926 // compute next leg course
927 SGWayPoint wp1(_routeMgr->get_waypoint(curIndex)),
928 wp2(_routeMgr->get_waypoint(curIndex + 1));
930 wp2.CourseAndDistance(wp1, &crs, &dist);
933 // compute offset bearing
934 _turnAngle = crs - _turnStartBearing;
935 SG_NORMALIZE_RANGE(_turnAngle, -180.0, 180.0);
936 double median = _turnStartBearing + (_turnAngle * 0.5);
937 double offsetBearing = median + copysign(90, _turnAngle);
938 SG_NORMALIZE_RANGE(offsetBearing, 0.0, 360.0);
940 SG_LOG(SG_INSTR, SG_INFO, "GPS computeTurnData: in=" << _turnStartBearing <<
941 ", out=" << crs << "; turnAngle=" << _turnAngle << ", median=" << median
942 << ", offset=" << offsetBearing);
944 SG_LOG(SG_INSTR, SG_INFO, "next leg is now:" << wp1.get_id() << "->" << wp2.get_id());
946 _turnPt = _wp1_position;
947 _anticipateTurn = true;
950 void GPS::updateTurnData()
952 // depends on ground speed, so needs to be updated per-frame
953 _turnRadius = computeTurnRadiusNm(_last_speed_kts);
955 // compute the turn centre, based on the turn radius.
956 // key thing is to understand that we're working a right-angle triangle,
957 // where the right-angle is the point we start the turn. From that point,
958 // one side is the inbound course to the turn pt, and the other is the
959 // perpendicular line, of length 'r', to the turn centre.
960 // the triangle's hypotenuse, which we need to find, is the distance from the
961 // turn pt to the turn center (in the direction of the offset bearing)
962 // note that d - _turnRadius tell us how much we're 'cutting' the corner.
964 double halfTurnAngle = fabs(_turnAngle * 0.5) * SG_DEGREES_TO_RADIANS;
965 double d = _turnRadius / cos(halfTurnAngle);
967 // SG_LOG(SG_INSTR, SG_INFO, "turnRadius=" << _turnRadius << ", d=" << d
968 // << " (cut distance=" << d - _turnRadius << ")");
970 double median = _turnStartBearing + (_turnAngle * 0.5);
971 double offsetBearing = median + copysign(90, _turnAngle);
972 SG_NORMALIZE_RANGE(offsetBearing, 0.0, 360.0);
975 SGGeodesy::direct(_turnPt, offsetBearing, d * SG_NM_TO_METER, _turnCentre, az2);
978 double GPS::computeTurnRadiusNm(double aGroundSpeedKts) const
980 // turn time is seconds to execute a 360 turn.
981 double turnTime = 360.0 / _config.turnRateDegSec();
983 // c is ground distance covered in that time (circumference of the circle)
984 double c = turnTime * (aGroundSpeedKts / 3600.0); // convert knts to nm/sec
986 // divide by 2PI to go from circumference -> radius
987 return c / (2 * M_PI);
990 void GPS::updateRouteData()
992 double totalDistance = _wp1DistanceM * SG_METER_TO_NM;
993 // walk all waypoints from wp2 to route end, and sum
994 for (int i=_routeMgr->currentWaypoint()+1; i<_routeMgr->size(); ++i) {
995 totalDistance += _routeMgr->get_waypoint(i).get_distance();
998 _routeDistanceNm->setDoubleValue(totalDistance * SG_METER_TO_NM);
999 if (_last_speed_kts > 1.0) {
1000 double TTW = ((totalDistance * SG_METER_TO_NM) / _last_speed_kts) * 3600.0;
1001 _routeETE->setStringValue(makeTTWString(TTW));
1005 void GPS::driveAutopilot()
1007 if (!_config.driveAutopilot() || !_realismSimpleGps->getBoolValue()) {
1011 // FIXME: we want to set desired track, not heading, here
1012 _apTrueHeading->setDoubleValue(getWP1Bearing());
1015 void GPS::wp1Changed()
1017 // update external HSI/CDI/NavDisplay/PFD/etc
1018 _config.setExternalCourse(getLegMagCourse());
1020 if (!_config.driveAutopilot()) {
1024 double altFt = _wp1_position.getElevationFt();
1025 if (altFt < -9990.0) {
1026 _apTargetAltitudeFt->setDoubleValue(0.0);
1028 _apTargetAltitudeFt->setDoubleValue(altFt);
1032 /////////////////////////////////////////////////////////////////////////////
1033 // property getter/setters
1035 double GPS::getLegDistance() const
1037 if (!_dataValid || (_mode == "obs")) {
1041 return SGGeodesy::distanceNm(_wp0_position, _wp1_position);
1044 double GPS::getLegCourse() const
1050 return SGGeodesy::courseDeg(_wp0_position, _wp1_position);
1053 double GPS::getLegMagCourse() const
1059 double m = getLegCourse() - _magvar_node->getDoubleValue();
1060 SG_NORMALIZE_RANGE(m, 0.0, 360.0);
1064 double GPS::getAltDistanceRatio() const
1066 if (!_dataValid || (_mode == "obs")) {
1070 double dist = SGGeodesy::distanceM(_wp0_position, _wp1_position);
1071 if ( dist <= 0.0 ) {
1075 double alt_difference_m = _wp0_position.getElevationM() - _wp1_position.getElevationM();
1076 return alt_difference_m / dist;
1079 double GPS::getMagTrack() const
1085 double m = getTrueTrack() - _magvar_node->getDoubleValue();
1086 SG_NORMALIZE_RANGE(m, 0.0, 360.0);
1090 double GPS::getCDIDeflection() const
1097 if (_config.cdiDeflectionIsAngular()) {
1098 defl = getWP1CourseDeviation();
1099 SG_CLAMP_RANGE(defl, -10.0, 10.0); // as in navradio.cxx
1101 double fullScale = _config.cdiDeflectionLinearPeg();
1102 double normError = getWP1CourseErrorNm() / fullScale;
1103 SG_CLAMP_RANGE(normError, -1.0, 1.0);
1104 defl = normError * 10.0; // re-scale to navradio limits, i.e [-10.0 .. 10.0]
1110 const char* GPS::getWP0Ident() const
1112 if (!_dataValid || (_mode != "leg")) {
1116 return _wp0Ident.c_str();
1119 const char* GPS::getWP0Name() const
1121 if (!_dataValid || (_mode != "leg")) {
1125 return _wp0Name.c_str();
1128 const char* GPS::getWP1Ident() const
1134 return _wp1Ident.c_str();
1137 const char* GPS::getWP1Name() const
1143 return _wp1Name.c_str();
1146 double GPS::getWP1Distance() const
1152 return _wp1DistanceM * SG_METER_TO_NM;
1155 double GPS::getWP1TTW() const
1161 if (_last_speed_kts < 1.0) {
1165 return (getWP1Distance() / _last_speed_kts) * 3600.0;
1168 const char* GPS::getWP1TTWString() const
1174 return makeTTWString(getWP1TTW());
1177 double GPS::getWP1Bearing() const
1183 return _wp1TrueBearing;
1186 double GPS::getWP1MagBearing() const
1192 return _wp1TrueBearing - _magvar_node->getDoubleValue();
1195 double GPS::getWP1CourseDeviation() const
1201 double dev = getWP1MagBearing() - _selectedCourse;
1202 SG_NORMALIZE_RANGE(dev, -180.0, 180.0);
1204 if (fabs(dev) > 90.0) {
1205 // When the course is away from the waypoint,
1206 // it makes sense to change the sign of the deviation.
1208 SG_NORMALIZE_RANGE(dev, -90.0, 90.0);
1214 double GPS::getWP1CourseErrorNm() const
1220 double radDev = getWP1CourseDeviation() * SG_DEGREES_TO_RADIANS;
1221 double course_error_m = sin(radDev) * _wp1DistanceM;
1222 return course_error_m * SG_METER_TO_NM;
1225 bool GPS::getWP1ToFlag() const
1231 double dev = getWP1MagBearing() - _selectedCourse;
1232 SG_NORMALIZE_RANGE(dev, -180.0, 180.0);
1234 return (fabs(dev) < 90.0);
1237 bool GPS::getWP1FromFlag() const
1243 return !getWP1ToFlag();
1246 double GPS::getScratchDistance() const
1248 if (!_scratchValid) {
1252 return SGGeodesy::distanceNm(_indicated_pos, _scratchPos);
1255 double GPS::getScratchTrueBearing() const
1257 if (!_scratchValid) {
1261 return SGGeodesy::courseDeg(_indicated_pos, _scratchPos);
1264 double GPS::getScratchMagBearing() const
1266 if (!_scratchValid) {
1270 double crs = getScratchTrueBearing() - _magvar_node->getDoubleValue();
1271 SG_NORMALIZE_RANGE(crs, 0.0, 360.0);
1275 /////////////////////////////////////////////////////////////////////////////
1276 // command / scratch / search system
1278 void GPS::setCommand(const char* aCmd)
1280 SG_LOG(SG_INSTR, SG_INFO, "GPS command:" << aCmd);
1282 if (!strcmp(aCmd, "direct")) {
1284 } else if (!strcmp(aCmd, "obs")) {
1286 } else if (!strcmp(aCmd, "leg")) {
1288 } else if (!strcmp(aCmd, "load-route-wpt")) {
1289 loadRouteWaypoint();
1290 } else if (!strcmp(aCmd, "nearest")) {
1292 } else if (!strcmp(aCmd, "search")) {
1293 _searchNames = false;
1295 } else if (!strcmp(aCmd, "search-names")) {
1296 _searchNames = true;
1298 } else if (!strcmp(aCmd, "next")) {
1300 } else if (!strcmp(aCmd, "previous")) {
1302 } else if (!strcmp(aCmd, "define-user-wpt")) {
1304 } else if (!strcmp(aCmd, "route-insert-before")) {
1305 int index = _scratchNode->getIntValue("index");
1306 if (index < 0 || (_routeMgr->size() == 0)) {
1307 index = _routeMgr->size();
1308 } else if (index >= _routeMgr->size()) {
1309 SG_LOG(SG_INSTR, SG_WARN, "GPS:route-insert-before, bad index:" << index);
1313 insertWaypointAtIndex(index);
1314 } else if (!strcmp(aCmd, "route-insert-after")) {
1315 int index = _scratchNode->getIntValue("index");
1316 if (index < 0 || (_routeMgr->size() == 0)) {
1317 index = _routeMgr->size();
1318 } else if (index >= _routeMgr->size()) {
1319 SG_LOG(SG_INSTR, SG_WARN, "GPS:route-insert-after, bad index:" << index);
1325 insertWaypointAtIndex(index);
1326 } else if (!strcmp(aCmd, "route-delete")) {
1327 int index = _scratchNode->getIntValue("index");
1329 index = _routeMgr->size();
1330 } else if (index >= _routeMgr->size()) {
1331 SG_LOG(SG_INSTR, SG_WARN, "GPS:route-delete, bad index:" << index);
1335 removeWaypointAtIndex(index);
1337 SG_LOG(SG_INSTR, SG_WARN, "GPS:unrecognized command:" << aCmd);
1341 void GPS::clearScratch()
1343 _scratchPos = SGGeod::fromDegFt(-9999.0, -9999.0, -9999.0);
1344 _scratchValid = false;
1345 _scratchNode->setStringValue("type", "");
1346 _scratchNode->setStringValue("query", "");
1349 bool GPS::isScratchPositionValid() const
1351 if ((_scratchPos.getLongitudeDeg() < -9990.0) ||
1352 (_scratchPos.getLatitudeDeg() < -9990.0)) {
1359 void GPS::directTo()
1361 if (!isScratchPositionValid()) {
1362 SG_LOG(SG_INSTR, SG_WARN, "invalid DTO lat/lon");
1366 _wp0_position = _indicated_pos;
1367 _wp1Ident = _scratchNode->getStringValue("ident");
1368 _wp1Name = _scratchNode->getStringValue("name");
1369 _wp1_position = _scratchPos;
1372 _selectedCourse = getLegMagCourse();
1378 void GPS::loadRouteWaypoint()
1380 _scratchValid = false;
1381 // if (!_routeMgr->isRouteActive()) {
1382 // SG_LOG(SG_INSTR, SG_WARN, "GPS:loadWaypoint: no active route");
1386 int index = _scratchNode->getIntValue("index", -9999);
1389 if (index == -9999) { // no index supplied, use current wp
1390 index = _routeMgr->currentWaypoint();
1393 _searchIsRoute = true;
1394 setScratchFromRouteWaypoint(index);
1397 void GPS::setScratchFromRouteWaypoint(int aIndex)
1399 assert(_searchIsRoute);
1400 if ((aIndex < 0) || (aIndex >= _routeMgr->size())) {
1401 SG_LOG(SG_INSTR, SG_WARN, "GPS:setScratchFromRouteWaypoint: route-index out of bounds");
1405 _searchResultIndex = aIndex;
1406 SGWayPoint wp(_routeMgr->get_waypoint(aIndex));
1407 _scratchNode->setStringValue("name", wp.get_name());
1408 _scratchNode->setStringValue("ident", wp.get_id());
1409 _scratchPos = wp.get_target();
1410 _scratchValid = true;
1411 _scratchNode->setDoubleValue("course", wp.get_track());
1412 _scratchNode->setIntValue("index", aIndex);
1414 int lastResult = _routeMgr->size() - 1;
1415 _searchHasNext = (_searchResultIndex < lastResult);
1418 void GPS::loadNearest()
1420 string sty(_scratchNode->getStringValue("type"));
1421 FGPositioned::Type ty = FGPositioned::typeFromName(sty);
1422 if (ty == FGPositioned::INVALID) {
1423 SG_LOG(SG_INSTR, SG_WARN, "GPS:loadNearest: request type is invalid:" << sty);
1427 auto_ptr<FGPositioned::Filter> f(createFilter(ty));
1428 int limitCount = _scratchNode->getIntValue("max-results", 1);
1429 double cutoffDistance = _scratchNode->getDoubleValue("cutoff-nm", 400.0);
1431 SGGeod searchPos = _indicated_pos;
1432 if (isScratchPositionValid()) {
1433 searchPos = _scratchPos;
1436 clearScratch(); // clear now, regardless of whether we find a match or not
1439 FGPositioned::findClosestN(searchPos, limitCount, cutoffDistance, f.get());
1440 _searchResultsCached = true;
1441 _searchResultIndex = 0;
1442 _searchIsRoute = false;
1443 _searchHasNext = false;
1445 if (_searchResults.empty()) {
1446 SG_LOG(SG_INSTR, SG_INFO, "GPS:loadNearest: no matches at all");
1450 _searchHasNext = (_searchResults.size() > 1);
1451 setScratchFromCachedSearchResult();
1454 bool GPS::SearchFilter::pass(FGPositioned* aPos) const
1456 switch (aPos->type()) {
1457 case FGPositioned::AIRPORT:
1458 // heliport and seaport too?
1459 case FGPositioned::VOR:
1460 case FGPositioned::NDB:
1461 case FGPositioned::FIX:
1462 case FGPositioned::TACAN:
1463 case FGPositioned::WAYPOINT:
1470 FGPositioned::Type GPS::SearchFilter::minType() const
1472 return FGPositioned::AIRPORT;
1475 FGPositioned::Type GPS::SearchFilter::maxType() const
1477 return FGPositioned::WAYPOINT;
1480 FGPositioned::Filter* GPS::createFilter(FGPositioned::Type aTy)
1482 if (aTy == FGPositioned::AIRPORT) {
1483 return new FGAirport::HardSurfaceFilter(_config.minRunwayLengthFt());
1486 // if we were passed INVALID, assume it means 'all types interesting to a GPS'
1487 if (aTy == FGPositioned::INVALID) {
1488 return new SearchFilter;
1491 return new FGPositioned::TypeFilter(aTy);
1496 // parse search terms into local members, and exec the first search
1497 string sty(_scratchNode->getStringValue("type"));
1498 _searchType = FGPositioned::typeFromName(sty);
1499 _searchQuery = _scratchNode->getStringValue("query");
1500 if (_searchQuery.empty()) {
1501 SG_LOG(SG_INSTR, SG_WARN, "empty GPS search query");
1506 _searchExact = _scratchNode->getBoolValue("exact", true);
1507 _searchOrderByRange = _scratchNode->getBoolValue("order-by-distance", true);
1508 _searchResultIndex = 0;
1509 _searchIsRoute = false;
1510 _searchHasNext = false;
1512 if (_searchExact && _searchOrderByRange) {
1513 // immediate mode search, get all the results now and cache them
1514 auto_ptr<FGPositioned::Filter> f(createFilter(_searchType));
1516 _searchResults = FGPositioned::findAllWithNameSortedByRange(_searchQuery, _indicated_pos, f.get());
1518 _searchResults = FGPositioned::findAllWithIdentSortedByRange(_searchQuery, _indicated_pos, f.get());
1521 _searchResultsCached = true;
1523 if (_searchResults.empty()) {
1528 _searchHasNext = (_searchResults.size() > 1);
1529 setScratchFromCachedSearchResult();
1531 // iterative search, look up result zero
1532 _searchResultsCached = false;
1537 void GPS::performSearch()
1539 auto_ptr<FGPositioned::Filter> f(createFilter(_searchType));
1544 if (_searchOrderByRange) {
1545 r = FGPositioned::findClosestWithPartialName(_indicated_pos, _searchQuery, f.get(), _searchResultIndex, _searchHasNext);
1547 r = FGPositioned::findWithPartialName(_searchQuery, f.get(), _searchResultIndex, _searchHasNext);
1550 if (_searchOrderByRange) {
1551 r = FGPositioned::findClosestWithPartialId(_indicated_pos, _searchQuery, f.get(), _searchResultIndex, _searchHasNext);
1553 r = FGPositioned::findWithPartialId(_searchQuery, f.get(), _searchResultIndex, _searchHasNext);
1561 setScratchFromPositioned(r.get(), _searchResultIndex);
1564 void GPS::setScratchFromCachedSearchResult()
1566 assert(_searchResultsCached);
1567 int index = _searchResultIndex;
1569 if ((index < 0) || (index >= (int) _searchResults.size())) {
1570 SG_LOG(SG_INSTR, SG_WARN, "GPS:setScratchFromCachedSearchResult: index out of bounds:" << index);
1574 setScratchFromPositioned(_searchResults[index], index);
1576 int lastResult = (int) _searchResults.size() - 1;
1577 _searchHasNext = (_searchResultIndex < lastResult);
1580 void GPS::setScratchFromPositioned(FGPositioned* aPos, int aIndex)
1585 _scratchPos = aPos->geod();
1586 _scratchNode->setStringValue("name", aPos->name());
1587 _scratchNode->setStringValue("ident", aPos->ident());
1588 _scratchNode->setStringValue("type", FGPositioned::nameForType(aPos->type()));
1591 _scratchNode->setIntValue("index", aIndex);
1594 _scratchValid = true;
1595 if (_searchResultsCached) {
1596 _scratchNode->setIntValue("result-count", _searchResults.size());
1599 switch (aPos->type()) {
1600 case FGPositioned::VOR:
1601 _scratchNode->setDoubleValue("frequency-mhz", static_cast<FGNavRecord*>(aPos)->get_freq() / 100.0);
1604 case FGPositioned::NDB:
1605 _scratchNode->setDoubleValue("frequency-khz", static_cast<FGNavRecord*>(aPos)->get_freq() / 100.0);
1608 case FGPositioned::AIRPORT:
1609 addAirportToScratch((FGAirport*)aPos);
1617 // look for being on the route and set?
1620 void GPS::addAirportToScratch(FGAirport* aAirport)
1622 for (unsigned int r=0; r<aAirport->numRunways(); ++r) {
1623 SGPropertyNode* rwyNd = _scratchNode->getChild("runways", r, true);
1624 FGRunway* rwy = aAirport->getRunwayByIndex(r);
1625 // TODO - filter out unsuitable runways in the future
1626 // based on config again
1628 rwyNd->setStringValue("id", rwy->ident().c_str());
1629 rwyNd->setIntValue("length-ft", rwy->lengthFt());
1630 rwyNd->setIntValue("width-ft", rwy->widthFt());
1631 rwyNd->setIntValue("heading-deg", rwy->headingDeg());
1632 // map surface code to a string
1633 // TODO - lighting information
1636 rwyNd->setDoubleValue("ils-frequency-mhz", rwy->ILS()->get_freq() / 100.0);
1638 } // of runways iteration
1642 void GPS::selectOBSMode()
1644 if (!isScratchPositionValid()) {
1645 SG_LOG(SG_INSTR, SG_WARN, "invalid OBS lat/lon");
1649 SG_LOG(SG_INSTR, SG_INFO, "GPS switching to OBS mode");
1652 _wp1Ident = _scratchNode->getStringValue("ident");
1653 _wp1Name = _scratchNode->getStringValue("name");
1654 _wp1_position = _scratchPos;
1655 _wp0_position = _indicated_pos;
1659 void GPS::selectLegMode()
1661 if (_mode == "leg") {
1665 if (!_routeMgr->isRouteActive()) {
1666 SG_LOG(SG_INSTR, SG_WARN, "GPS:selectLegMode: no active route");
1670 SG_LOG(SG_INSTR, SG_INFO, "GPS switching to LEG mode");
1673 // depending on the situation, this will either get over-written
1674 // in routeManagerSequenced or not; either way it does no harm to
1676 _wp0_position = _indicated_pos;
1678 // not really sequenced, but does all the work of updating wp0/1
1679 routeManagerSequenced();
1682 void GPS::nextResult()
1684 if (!_searchHasNext) {
1689 if (_searchIsRoute) {
1690 setScratchFromRouteWaypoint(++_searchResultIndex);
1691 } else if (_searchResultsCached) {
1692 ++_searchResultIndex;
1693 setScratchFromCachedSearchResult();
1695 ++_searchResultIndex;
1697 } // of iterative search case
1700 void GPS::previousResult()
1702 if (_searchResultIndex <= 0) {
1707 --_searchResultIndex;
1709 if (_searchIsRoute) {
1710 setScratchFromRouteWaypoint(_searchResultIndex);
1711 } else if (_searchResultsCached) {
1712 setScratchFromCachedSearchResult();
1718 void GPS::defineWaypoint()
1720 if (!isScratchPositionValid()) {
1721 SG_LOG(SG_INSTR, SG_WARN, "GPS:defineWaypoint: invalid lat/lon");
1725 string ident = _scratchNode->getStringValue("ident");
1726 if (ident.size() < 2) {
1727 SG_LOG(SG_INSTR, SG_WARN, "GPS:defineWaypoint: waypoint identifier must be at least two characters");
1731 // check for duplicate idents
1732 FGPositioned::TypeFilter f(FGPositioned::WAYPOINT);
1733 FGPositioned::List dups = FGPositioned::findAllWithIdentSortedByRange(ident, _indicated_pos, &f);
1734 if (!dups.empty()) {
1735 SG_LOG(SG_INSTR, SG_WARN, "GPS:defineWaypoint: non-unique waypoint identifier, ho-hum");
1738 SG_LOG(SG_INSTR, SG_INFO, "GPS:defineWaypoint: creating waypoint:" << ident);
1739 FGPositionedRef wpt = FGPositioned::createUserWaypoint(ident, _scratchPos);
1740 _searchResultsCached = false;
1741 setScratchFromPositioned(wpt.get(), -1);
1744 void GPS::insertWaypointAtIndex(int aIndex)
1746 // note we do allow index = routeMgr->size(), that's an append
1747 if ((aIndex < 0) || (aIndex > _routeMgr->size())) {
1748 throw sg_range_exception("GPS::insertWaypointAtIndex: index out of bounds");
1751 if (!isScratchPositionValid()) {
1752 SG_LOG(SG_INSTR, SG_WARN, "GPS:insertWaypointAtIndex: invalid lat/lon");
1756 string ident = _scratchNode->getStringValue("ident");
1757 string name = _scratchNode->getStringValue("name");
1759 _routeMgr->add_waypoint(SGWayPoint(_scratchPos, ident, name), aIndex);
1762 void GPS::removeWaypointAtIndex(int aIndex)
1764 if ((aIndex < 0) || (aIndex >= _routeMgr->size())) {
1765 throw sg_range_exception("GPS::removeWaypointAtIndex: index out of bounds");
1768 _routeMgr->pop_waypoint(aIndex);