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 const char* makeTTWString(double TTW)
79 if ((TTW <= 0.0) || (TTW >= 356400.5)) { // 99 hours
83 unsigned int TTW_seconds = (int) (TTW + 0.5);
84 unsigned int TTW_minutes = 0;
85 unsigned int TTW_hours = 0;
86 static char TTW_str[9];
87 TTW_hours = TTW_seconds / 3600;
88 TTW_minutes = (TTW_seconds / 60) % 60;
89 TTW_seconds = TTW_seconds % 60;
90 snprintf(TTW_str, 9, "%02d:%02d:%02d",
91 TTW_hours, TTW_minutes, TTW_seconds);
95 /////////////////////////////////////////////////////////////////////////////
97 class GPSListener : public SGPropertyChangeListener
100 GPSListener(GPS *m) :
104 virtual void valueChanged (SGPropertyNode * prop)
111 if (prop == _gps->_route_current_wp_node) {
112 _gps->routeManagerSequenced();
113 } else if (prop == _gps->_route_active_node) {
114 _gps->routeActivated();
115 } else if (prop == _gps->_ref_navaid_id_node) {
116 _gps->referenceNavaidSet(prop->getStringValue(""));
117 } else if (prop == _gps->_routeEditedSignal) {
119 } else if (prop == _gps->_routeFinishedSignal) {
120 _gps->routeFinished();
126 void setGuard(bool g) {
131 bool _guard; // re-entrancy guard
134 ////////////////////////////////////////////////////////////////////////////
136 * Helper to monitor for Nasal or other code accessing properties we haven't
137 * defined. For the moment we complain about all such activites, since various
138 * users assume all kinds of weird, wonderful and non-existent interfaces.
141 class DeprecatedPropListener : public SGPropertyChangeListener
144 DeprecatedPropListener(SGPropertyNode* gps)
146 _parents.insert(gps);
147 SGPropertyNode* wp = gps->getChild("wp");
149 _parents.insert(wp->getChild("wp", 0));
150 _parents.insert(wp->getChild("wp", 1));
152 std::set<SGPropertyNode*>::iterator it;
153 for (it = _parents.begin(); it != _parents.end(); ++it) {
154 (*it)->addChangeListener(this);
158 virtual void valueChanged (SGPropertyNode * prop)
162 virtual void childAdded (SGPropertyNode * parent, SGPropertyNode * child)
164 if (isDeprecated(parent, child)) {
165 SG_LOG(SG_INSTR, SG_WARN, "GPS: someone accessed a deprecated property:"
166 << child->getPath(true));
170 bool isDeprecated(SGPropertyNode * parent, SGPropertyNode * child) const
172 if (_parents.count(parent) < 1) {
176 // no child exclusions yet
180 std::set<SGPropertyNode*> _parents;
183 ////////////////////////////////////////////////////////////////////////////
184 // configuration helper object
186 GPS::Config::Config() :
187 _enableTurnAnticipation(true),
188 _turnRate(3.0), // degrees-per-second, so 180 degree turn takes 60 seconds
189 _overflightArmDistance(1.0),
190 _waypointAlertTime(30.0),
191 _minRunwayLengthFt(0.0),
192 _requireHardSurface(true),
193 _cdiMaxDeflectionNm(3.0), // linear mode, 3nm at the peg
194 _driveAutopilot(true),
195 _courseSelectable(false)
197 _enableTurnAnticipation = false;
200 void GPS::Config::bind(GPS* aOwner, SGPropertyNode* aCfg)
202 aOwner->tie(aCfg, "turn-rate-deg-sec", SGRawValuePointer<double>(&_turnRate));
203 aOwner->tie(aCfg, "turn-anticipation", SGRawValuePointer<bool>(&_enableTurnAnticipation));
204 aOwner->tie(aCfg, "wpt-alert-time", SGRawValuePointer<double>(&_waypointAlertTime));
205 aOwner->tie(aCfg, "min-runway-length-ft", SGRawValuePointer<double>(&_minRunwayLengthFt));
206 aOwner->tie(aCfg, "hard-surface-runways-only", SGRawValuePointer<bool>(&_requireHardSurface));
207 aOwner->tie(aCfg, "cdi-max-deflection-nm", SGRawValuePointer<double>(&_cdiMaxDeflectionNm));
208 aOwner->tie(aCfg, "drive-autopilot", SGRawValuePointer<bool>(&_driveAutopilot));
209 aOwner->tie(aCfg, "course-selectable", SGRawValuePointer<bool>(&_courseSelectable));
212 ////////////////////////////////////////////////////////////////////////////
214 GPS::GPS ( SGPropertyNode *node) :
215 _selectedCourse(0.0),
217 _lastPosValid(false),
219 _name(node->getStringValue("name", "gps")),
220 _num(node->getIntValue("number", 0)),
221 _computeTurnData(false),
222 _anticipateTurn(false),
226 string branch = "/instrumentation/" + _name;
227 _gpsNode = fgGetNode(branch.c_str(), _num, true );
228 _scratchNode = _gpsNode->getChild("scratch", 0, true);
238 _routeMgr = (FGRouteMgr*) globals->get_subsystem("route-manager");
241 _position.init("/position/longitude-deg", "/position/latitude-deg", "/position/altitude-ft");
242 _magvar_node = fgGetNode("/environment/magnetic-variation-deg", true);
243 _serviceable_node = _gpsNode->getChild("serviceable", 0, true);
244 _serviceable_node->setBoolValue(true);
245 _electrical_node = fgGetNode("/systems/electrical/outputs/gps", true);
248 _raim_node = _gpsNode->getChild("raim", 0, true);
249 _odometer_node = _gpsNode->getChild("odometer", 0, true);
250 _trip_odometer_node = _gpsNode->getChild("trip-odometer", 0, true);
251 _true_bug_error_node = _gpsNode->getChild("true-bug-error-deg", 0, true);
252 _magnetic_bug_error_node = _gpsNode->getChild("magnetic-bug-error-deg", 0, true);
253 _eastWestVelocity = _gpsNode->getChild("ew-velocity-msec", 0, true);
254 _northSouthVelocity = _gpsNode->getChild("ns-velocity-msec", 0, true);
257 SGPropertyNode *wp_node = _gpsNode->getChild("wp", 0, true);
258 SGPropertyNode *wp1_node = wp_node->getChild("wp", 1, true);
260 // for compatability, alias selected course down to wp/wp[1]/desired-course-deg
261 SGPropertyNode* wp1Crs = wp1_node->getChild("desired-course-deg", 0, true);
262 wp1Crs->alias(_gpsNode->getChild("desired-course-deg", 0, true));
264 // _true_wp1_bearing_error_node =
265 // wp1_node->getChild("true-bearing-error-deg", 0, true);
266 // _magnetic_wp1_bearing_error_node =
267 // wp1_node->getChild("magnetic-bearing-error-deg", 0, true);
269 _tracking_bug_node = _gpsNode->getChild("tracking-bug", 0, true);
272 SGPropertyNode_ptr ref_navaid = _gpsNode->getChild("ref-navaid", 0, true);
273 _ref_navaid_id_node = ref_navaid->getChild("id", 0, true);
274 _ref_navaid_name_node = ref_navaid->getChild("name", 0, true);
275 _ref_navaid_bearing_node = ref_navaid->getChild("bearing-deg", 0, true);
276 _ref_navaid_frequency_node = ref_navaid->getChild("frequency-mhz", 0, true);
277 _ref_navaid_distance_node = ref_navaid->getChild("distance-nm", 0, true);
278 _ref_navaid_mag_bearing_node = ref_navaid->getChild("mag-bearing-deg", 0, true);
279 _ref_navaid_elapsed = 0.0;
280 _ref_navaid_set = false;
283 // should these move to the route manager?
284 _routeDistanceNm = _gpsNode->getChild("route-distance-nm", 0, true);
285 _routeETE = _gpsNode->getChild("ETE", 0, true);
286 _routeEditedSignal = fgGetNode("/autopilot/route-manager/signals/edited", true);
287 _routeFinishedSignal = fgGetNode("/autopilot/route-manager/signals/finished", true);
289 // add listener to various things
290 _listener = new GPSListener(this);
291 _route_current_wp_node = fgGetNode("/autopilot/route-manager/current-wp", true);
292 _route_current_wp_node->addChangeListener(_listener);
293 _route_active_node = fgGetNode("/autopilot/route-manager/active", true);
294 _route_active_node->addChangeListener(_listener);
295 _ref_navaid_id_node->addChangeListener(_listener);
296 _routeEditedSignal->addChangeListener(_listener);
297 _routeFinishedSignal->addChangeListener(_listener);
299 // navradio slaving properties
300 SGPropertyNode* toFlag = _gpsNode->getChild("to-flag", 0, true);
301 toFlag->alias(wp1_node->getChild("to-flag"));
303 SGPropertyNode* fromFlag = _gpsNode->getChild("from-flag", 0, true);
304 fromFlag->alias(wp1_node->getChild("from-flag"));
306 // autopilot drive properties
307 _apDrivingFlag = fgGetNode("/autopilot/settings/gps-driving-true-heading", true);
308 _apTrueHeading = fgGetNode("/autopilot/settings/true-heading-deg",true);
309 _apTargetAltitudeFt = fgGetNode("/autopilot/settings/target-altitude-ft", true);
310 _apAltitudeLock = fgGetNode("/autopilot/locks/altitude", true);
313 _realismSimpleGps = fgGetNode("/sim/realism/simple-gps", true);
314 if (!_realismSimpleGps->hasValue()) {
315 _realismSimpleGps->setBoolValue(true);
318 // last thing, add the deprecated prop watcher
319 new DeprecatedPropListener(_gpsNode);
327 _config.bind(this, _gpsNode->getChild("config", 0, true));
329 tie(_gpsNode, "selected-course-deg", SGRawValueMethods<GPS, double>
330 (*this, &GPS::getSelectedCourse, &GPS::setSelectedCourse));
332 tie(_gpsNode, "desired-course-deg", SGRawValueMethods<GPS, double>
333 (*this, &GPS::getDesiredCourse, NULL));
334 _desiredCourseNode = _gpsNode->getChild("desired-course-deg");
336 tieSGGeodReadOnly(_gpsNode, _indicated_pos, "indicated-longitude-deg",
337 "indicated-latitude-deg", "indicated-altitude-ft");
339 tie(_gpsNode, "indicated-vertical-speed", SGRawValueMethods<GPS, double>
340 (*this, &GPS::getVerticalSpeed, NULL));
341 tie(_gpsNode, "indicated-track-true-deg", SGRawValueMethods<GPS, double>
342 (*this, &GPS::getTrueTrack, NULL));
343 tie(_gpsNode, "indicated-track-magnetic-deg", SGRawValueMethods<GPS, double>
344 (*this, &GPS::getMagTrack, NULL));
345 tie(_gpsNode, "indicated-ground-speed-kt", SGRawValueMethods<GPS, double>
346 (*this, &GPS::getGroundspeedKts, NULL));
349 tie(_gpsNode, "mode", SGRawValueMethods<GPS, const char*>(*this, &GPS::getMode, NULL));
350 tie(_gpsNode, "command", SGRawValueMethods<GPS, const char*>(*this, &GPS::getCommand, &GPS::setCommand));
352 tieSGGeod(_scratchNode, _scratchPos, "longitude-deg", "latitude-deg", "altitude-ft");
353 tie(_scratchNode, "valid", SGRawValueMethods<GPS, bool>(*this, &GPS::getScratchValid, NULL));
354 tie(_scratchNode, "distance-nm", SGRawValueMethods<GPS, double>(*this, &GPS::getScratchDistance, NULL));
355 tie(_scratchNode, "true-bearing-deg", SGRawValueMethods<GPS, double>(*this, &GPS::getScratchTrueBearing, NULL));
356 tie(_scratchNode, "mag-bearing-deg", SGRawValueMethods<GPS, double>(*this, &GPS::getScratchMagBearing, NULL));
357 tie(_scratchNode, "has-next", SGRawValueMethods<GPS, bool>(*this, &GPS::getScratchHasNext, NULL));
358 _scratchValid = false;
360 // waypoint data (including various historical things)
361 SGPropertyNode *wp_node = _gpsNode->getChild("wp", 0, true);
362 SGPropertyNode *wp0_node = wp_node->getChild("wp", 0, true);
363 SGPropertyNode *wp1_node = wp_node->getChild("wp", 1, true);
365 tieSGGeodReadOnly(wp0_node, _wp0_position, "longitude-deg", "latitude-deg", "altitude-ft");
366 tie(wp0_node, "ID", SGRawValueMethods<GPS, const char*>
367 (*this, &GPS::getWP0Ident, NULL));
368 tie(wp0_node, "name", SGRawValueMethods<GPS, const char*>
369 (*this, &GPS::getWP0Name, NULL));
371 tieSGGeodReadOnly(wp1_node, _wp1_position, "longitude-deg", "latitude-deg", "altitude-ft");
372 tie(wp1_node, "ID", SGRawValueMethods<GPS, const char*>
373 (*this, &GPS::getWP1Ident, NULL));
374 tie(wp1_node, "name", SGRawValueMethods<GPS, const char*>
375 (*this, &GPS::getWP1Name, NULL));
377 tie(wp1_node, "distance-nm", SGRawValueMethods<GPS, double>
378 (*this, &GPS::getWP1Distance, NULL));
379 tie(wp1_node, "bearing-true-deg", SGRawValueMethods<GPS, double>
380 (*this, &GPS::getWP1Bearing, NULL));
381 tie(wp1_node, "bearing-mag-deg", SGRawValueMethods<GPS, double>
382 (*this, &GPS::getWP1MagBearing, NULL));
383 tie(wp1_node, "TTW-sec", SGRawValueMethods<GPS, double>
384 (*this, &GPS::getWP1TTW, NULL));
385 tie(wp1_node, "TTW", SGRawValueMethods<GPS, const char*>
386 (*this, &GPS::getWP1TTWString, NULL));
388 tie(wp1_node, "course-deviation-deg", SGRawValueMethods<GPS, double>
389 (*this, &GPS::getWP1CourseDeviation, NULL));
390 tie(wp1_node, "course-error-nm", SGRawValueMethods<GPS, double>
391 (*this, &GPS::getWP1CourseErrorNm, NULL));
392 tie(wp1_node, "to-flag", SGRawValueMethods<GPS, bool>
393 (*this, &GPS::getWP1ToFlag, NULL));
394 tie(wp1_node, "from-flag", SGRawValueMethods<GPS, bool>
395 (*this, &GPS::getWP1FromFlag, NULL));
397 // leg properties (only valid in DTO/LEG modes, not OBS)
398 tie(wp_node, "leg-distance-nm", SGRawValueMethods<GPS, double>(*this, &GPS::getLegDistance, NULL));
399 tie(wp_node, "leg-true-course-deg", SGRawValueMethods<GPS, double>(*this, &GPS::getLegCourse, NULL));
400 tie(wp_node, "leg-mag-course-deg", SGRawValueMethods<GPS, double>(*this, &GPS::getLegMagCourse, NULL));
401 tie(wp_node, "alt-dist-ratio", SGRawValueMethods<GPS, double>(*this, &GPS::getAltDistanceRatio, NULL));
403 // navradio slaving properties
404 tie(_gpsNode, "cdi-deflection", SGRawValueMethods<GPS,double>
405 (*this, &GPS::getCDIDeflection));
411 for (unsigned int t=0; t<_tiedNodes.size(); ++t) {
412 _tiedNodes[t]->untie();
421 _last_speed_kts = 0.0;
422 _last_pos = SGGeod();
423 _lastPosValid = false;
424 _indicated_pos = SGGeod();
425 _last_vertical_speed = 0.0;
426 _last_true_track = 0.0;
427 _lastEWVelocity = _lastNSVelocity = 0.0;
429 _raim_node->setDoubleValue(0.0);
430 _indicated_pos = SGGeod();
432 _wp1TrueBearing = 0.0;
433 _wp1_position = SGGeod();
434 _odometer_node->setDoubleValue(0);
435 _trip_odometer_node->setDoubleValue(0);
436 _tracking_bug_node->setDoubleValue(0);
437 _true_bug_error_node->setDoubleValue(0);
438 _magnetic_bug_error_node->setDoubleValue(0);
439 _northSouthVelocity->setDoubleValue(0.0);
440 _eastWestVelocity->setDoubleValue(0.0);
444 GPS::update (double delta_time_sec)
446 if (!_realismSimpleGps->getBoolValue()) {
447 // If it's off, don't bother.
448 if (!_serviceable_node->getBoolValue() || !_electrical_node->getBoolValue()) {
454 if (delta_time_sec <= 0.0) {
455 return; // paused, don't bother
457 // TODO: Add noise and other errors.
460 // Bias and random error
461 double random_factor = sg_random();
462 double random_error = 1.4;
463 double error_radius = 5.1;
464 double bias_max_radius = 5.1;
465 double random_max_radius = 1.4;
467 bias_length += (random_factor-0.5) * 1.0e-3;
468 if (bias_length <= 0.0) bias_length = 0.0;
469 else if (bias_length >= bias_max_radius) bias_length = bias_max_radius;
470 bias_angle += (random_factor-0.5) * 1.0e-3;
471 if (bias_angle <= 0.0) bias_angle = 0.0;
472 else if (bias_angle >= 360.0) bias_angle = 360.0;
474 double random_length = random_factor * random_max_radius;
475 double random_angle = random_factor * 360.0;
477 double bias_x = bias_length * cos(bias_angle * SG_PI / 180.0);
478 double bias_y = bias_length * sin(bias_angle * SG_PI / 180.0);
479 double random_x = random_length * cos(random_angle * SG_PI / 180.0);
480 double random_y = random_length * sin(random_angle * SG_PI / 180.0);
481 double error_x = bias_x + random_x;
482 double error_y = bias_y + random_y;
483 double error_length = sqrt(error_x*error_x + error_y*error_y);
484 double error_angle = atan(error_y / error_x) * 180.0 / SG_PI;
489 geo_direct_wgs_84 ( altitude_m, latitude_deg,
490 longitude_deg, error_angle,
491 error_length, &lat2, &lon2,
493 //cout << lat2 << " " << lon2 << endl;
494 printf("%f %f \n", bias_length, bias_angle);
495 printf("%3.7f %3.7f \n", lat2, lon2);
496 printf("%f %f \n", error_length, error_angle);
499 _raim_node->setDoubleValue(1.0);
500 _indicated_pos = _position.get();
501 updateBasicData(delta_time_sec);
504 if (_mode != "obs") {
510 updateReferenceNavaid(delta_time_sec);
515 if (_dataValid && (_mode == "init")) {
516 // allow a realistic delay in the future, here
517 SG_LOG(SG_INSTR, SG_INFO, "GPS initialisation complete");
519 if (_route_active_node->getBoolValue()) {
520 // GPS init with active route
521 SG_LOG(SG_INSTR, SG_INFO, "GPS init with active route");
524 // initialise in OBS mode, with waypt set to the nearest airport.
525 // keep in mind at this point, _dataValid is not set
527 auto_ptr<FGPositioned::Filter> f(createFilter(FGPositioned::AIRPORT));
528 FGPositionedRef apt = FGPositioned::findClosest(_position.get(), 20.0, f.get());
530 setScratchFromPositioned(apt, 0);
534 } // of init mode check
536 _last_pos = _indicated_pos;
537 _lastPosValid = true;
541 GPS::updateBasicData(double dt)
543 if (!_lastPosValid) {
549 SGGeodesy::inverse(_last_pos, _indicated_pos, _last_true_track, track2_deg, distance_m );
551 double speed_kt = ((distance_m * SG_METER_TO_NM) * ((1 / dt) * 3600.0));
552 double vertical_speed_mpm = ((_indicated_pos.getElevationM() - _last_pos.getElevationM()) * 60 / dt);
553 _last_vertical_speed = vertical_speed_mpm * SG_METER_TO_FEET;
555 speed_kt = fgGetLowPass(_last_speed_kts, speed_kt, dt/10.0);
556 _last_speed_kts = speed_kt;
558 SGGeod g = _indicated_pos;
559 g.setLongitudeDeg(_last_pos.getLongitudeDeg());
560 double northSouthM = SGGeodesy::distanceM(_last_pos, g);
561 northSouthM = copysign(northSouthM, _indicated_pos.getLatitudeDeg() - _last_pos.getLatitudeDeg());
563 double nsMSec = fgGetLowPass(_lastNSVelocity, northSouthM / dt, dt/2.0);
564 _lastNSVelocity = nsMSec;
565 _northSouthVelocity->setDoubleValue(nsMSec);
569 g.setLatitudeDeg(_last_pos.getLatitudeDeg());
570 double eastWestM = SGGeodesy::distanceM(_last_pos, g);
571 eastWestM = copysign(eastWestM, _indicated_pos.getLongitudeDeg() - _last_pos.getLongitudeDeg());
573 double ewMSec = fgGetLowPass(_lastEWVelocity, eastWestM / dt, dt/2.0);
574 _lastEWVelocity = ewMSec;
575 _eastWestVelocity->setDoubleValue(ewMSec);
577 double odometer = _odometer_node->getDoubleValue();
578 _odometer_node->setDoubleValue(odometer + distance_m * SG_METER_TO_NM);
579 odometer = _trip_odometer_node->getDoubleValue();
580 _trip_odometer_node->setDoubleValue(odometer + distance_m * SG_METER_TO_NM);
583 SG_LOG(SG_INSTR, SG_INFO, "GPS setting data valid");
589 GPS::updateTrackingBug()
591 double tracking_bug = _tracking_bug_node->getDoubleValue();
592 double true_bug_error = tracking_bug - getTrueTrack();
593 double magnetic_bug_error = tracking_bug - getMagTrack();
595 // Get the errors into the (-180,180) range.
596 SG_NORMALIZE_RANGE(true_bug_error, -180.0, 180.0);
597 SG_NORMALIZE_RANGE(magnetic_bug_error, -180.0, 180.0);
599 _true_bug_error_node->setDoubleValue(true_bug_error);
600 _magnetic_bug_error_node->setDoubleValue(magnetic_bug_error);
604 GPS::updateWaypoints()
607 SGGeodesy::inverse(_indicated_pos, _wp1_position, _wp1TrueBearing, az2,_wp1DistanceM);
610 void GPS::updateReferenceNavaid(double dt)
612 if (!_ref_navaid_set) {
613 _ref_navaid_elapsed += dt;
614 if (_ref_navaid_elapsed > 5.0) {
615 _ref_navaid_elapsed = 0.0;
617 FGPositioned::TypeFilter vorFilter(FGPositioned::VOR);
618 FGPositionedRef nav = FGPositioned::findClosest(_indicated_pos, 400.0, &vorFilter);
620 SG_LOG(SG_INSTR, SG_INFO, "GPS couldn't find a reference navid");
621 _ref_navaid_id_node->setStringValue("");
622 _ref_navaid_name_node->setStringValue("");
623 _ref_navaid_bearing_node->setDoubleValue(0.0);
624 _ref_navaid_mag_bearing_node->setDoubleValue(0.0);
625 _ref_navaid_distance_node->setDoubleValue(0.0);
626 _ref_navaid_frequency_node->setStringValue("");
627 } else if (nav != _ref_navaid) {
628 SG_LOG(SG_INSTR, SG_INFO, "GPS code selected new ref-navaid:" << nav->ident());
629 _listener->setGuard(true);
630 _ref_navaid_id_node->setStringValue(nav->ident().c_str());
631 _ref_navaid_name_node->setStringValue(nav->name().c_str());
632 FGNavRecord* vor = (FGNavRecord*) nav.ptr();
633 _ref_navaid_frequency_node->setDoubleValue(vor->get_freq() / 100.0);
634 _listener->setGuard(false);
636 // SG_LOG(SG_INSTR, SG_ALERT, "matched existing");
644 double trueCourse, distanceM, az2;
645 SGGeodesy::inverse(_indicated_pos, _ref_navaid->geod(), trueCourse, az2, distanceM);
646 _ref_navaid_distance_node->setDoubleValue(distanceM * SG_METER_TO_NM);
647 _ref_navaid_bearing_node->setDoubleValue(trueCourse);
648 _ref_navaid_mag_bearing_node->setDoubleValue(trueCourse - _magvar_node->getDoubleValue());
652 void GPS::referenceNavaidSet(const std::string& aNavaid)
655 // allow setting an empty string to restore normal nearest-vor selection
656 if (aNavaid.size() > 0) {
657 FGPositioned::TypeFilter vorFilter(FGPositioned::VOR);
658 _ref_navaid = FGPositioned::findClosestWithIdent(aNavaid,
659 _position.get(), &vorFilter);
662 SG_LOG(SG_INSTR, SG_ALERT, "GPS: unknown ref navaid:" << aNavaid);
667 _ref_navaid_set = true;
668 SG_LOG(SG_INSTR, SG_INFO, "GPS code set explict ref-navaid:" << _ref_navaid->ident());
669 _ref_navaid_id_node->setStringValue(_ref_navaid->ident().c_str());
670 _ref_navaid_name_node->setStringValue(_ref_navaid->name().c_str());
671 FGNavRecord* vor = (FGNavRecord*) _ref_navaid.ptr();
672 _ref_navaid_frequency_node->setDoubleValue(vor->get_freq() / 100.0);
674 _ref_navaid_set = false;
675 _ref_navaid_elapsed = 9999.0; // update next tick
679 void GPS::routeActivated()
681 if (_route_active_node->getBoolValue()) {
682 SG_LOG(SG_INSTR, SG_INFO, "GPS::route activated, switching to LEG mode");
685 // if we've already passed the current waypoint, sequence.
686 if (_dataValid && getWP1FromFlag()) {
687 SG_LOG(SG_INSTR, SG_INFO, "GPS::route activated, FROM wp1, sequencing");
688 _routeMgr->sequence();
690 } else if (_mode == "leg") {
691 SG_LOG(SG_INSTR, SG_INFO, "GPS::route deactivated, switching to OBS mode");
696 void GPS::routeManagerSequenced()
698 if (_mode != "leg") {
699 SG_LOG(SG_INSTR, SG_INFO, "GPS ignoring route sequencing, not in LEG mode");
703 int index = _routeMgr->currentWaypoint(),
704 count = _routeMgr->size();
705 if ((index < 0) || (index >= count)) {
706 SG_LOG(SG_INSTR, SG_ALERT, "GPS: malformed route, index=" << index);
710 SG_LOG(SG_INSTR, SG_INFO, "GPS waypoint index is now " << index);
713 SGWayPoint wp0(_routeMgr->get_waypoint(index - 1));
714 _wp0Ident = wp0.get_id();
715 _wp0Name = wp0.get_name();
716 _wp0_position = wp0.get_target();
720 SGWayPoint wp1(_routeMgr->get_waypoint(index));
721 _wp1Ident = wp1.get_id();
722 _wp1Name = wp1.get_name();
723 _wp1_position = wp1.get_target();
725 _desiredCourse = getLegMagCourse();
726 _desiredCourseNode->fireValueChanged();
730 void GPS::routeEdited()
732 if (_mode != "leg") {
736 SG_LOG(SG_INSTR, SG_INFO, "GPS route edited while in LEG mode, updating waypoints");
737 routeManagerSequenced();
740 void GPS::routeFinished()
742 if (_mode != "leg") {
746 SG_LOG(SG_INSTR, SG_INFO, "GPS route finished, reverting to OBS");
748 _wp0_position = _indicated_pos;
752 void GPS::updateTurn()
754 bool printProgress = false;
756 if (_computeTurnData) {
757 if (_last_speed_kts < 60) {
758 // need valid leg course and sensible ground speed to compute the turn
763 printProgress = true;
766 if (!_anticipateTurn) {
772 // find bearing to turn centre
773 double bearing, az2, distanceM;
774 SGGeodesy::inverse(_indicated_pos, _turnCentre, bearing, az2, distanceM);
775 double progress = computeTurnProgress(bearing);
778 SG_LOG(SG_INSTR, SG_INFO,"turn progress=" << progress);
781 if (!_inTurn && (progress > 0.0)) {
785 if (_inTurn && !_turnSequenced && (progress > 0.5)) {
786 _turnSequenced = true;
787 SG_LOG(SG_INSTR, SG_INFO, "turn passed midpoint, sequencing");
788 _routeMgr->sequence();
791 if (_inTurn && (progress >= 1.0)) {
796 // drive deviation and desired course
797 double desiredCourse = bearing - copysign(90, _turnAngle);
798 SG_NORMALIZE_RANGE(desiredCourse, 0.0, 360.0);
799 double deviationNm = (distanceM * SG_METER_TO_NM) - _turnRadius;
800 double deviationDeg = desiredCourse - getMagTrack();
801 deviationNm = copysign(deviationNm, deviationDeg);
803 //_wp1_course_deviation_node->setDoubleValue(deviationDeg);
804 //_wp1_course_error_nm_node->setDoubleValue(deviationNm);
805 //_cdiDeflectionNode->setDoubleValue(deviationDeg);
809 void GPS::updateOverflight()
811 if ((_wp1DistanceM * SG_METER_TO_NM) > _config.overflightArmDistanceNm()) {
815 if (getWP1ToFlag()) {
816 return; // still heading towards the WP
819 if (_mode == "dto") {
820 SG_LOG(SG_INSTR, SG_INFO, "GPS DTO reached destination point");
822 // check for wp1 being on active route - resume leg mode
823 if (_routeMgr->isRouteActive()) {
824 int index = _routeMgr->findWaypoint(_wp1_position);
826 SG_LOG(SG_INSTR, SG_INFO, "GPS DTO, resuming LEG mode at wp:" << index);
828 _routeMgr->jumpToIndex(index);
831 } else if (_mode == "leg") {
832 SG_LOG(SG_INSTR, SG_INFO, "GPS doing overflight sequencing");
833 _routeMgr->sequence();
834 } else if (_mode == "obs") {
835 // nothing to do here, TO/FROM will update but that's fine
838 _computeTurnData = true;
841 void GPS::beginTurn()
844 _turnSequenced = false;
845 SG_LOG(SG_INSTR, SG_INFO, "begining turn");
851 SG_LOG(SG_INSTR, SG_INFO, "ending turn");
852 _computeTurnData = true;
855 double GPS::computeTurnProgress(double aBearing) const
857 double startBearing = _turnStartBearing + copysign(90, _turnAngle);
858 return (aBearing - startBearing) / _turnAngle;
861 void GPS::computeTurnData()
863 _computeTurnData = false;
864 if (_mode != "leg") { // and approach modes in the future
865 _anticipateTurn = false;
869 int curIndex = _routeMgr->currentWaypoint();
870 if ((curIndex + 1) >= _routeMgr->size()) {
871 _anticipateTurn = false;
875 if (!_config.turnAnticipationEnabled()) {
876 _anticipateTurn = false;
880 _turnStartBearing = _desiredCourse;
881 // compute next leg course
882 SGWayPoint wp1(_routeMgr->get_waypoint(curIndex)),
883 wp2(_routeMgr->get_waypoint(curIndex + 1));
885 wp2.CourseAndDistance(wp1, &crs, &dist);
888 // compute offset bearing
889 _turnAngle = crs - _turnStartBearing;
890 SG_NORMALIZE_RANGE(_turnAngle, -180.0, 180.0);
891 double median = _turnStartBearing + (_turnAngle * 0.5);
892 double offsetBearing = median + copysign(90, _turnAngle);
893 SG_NORMALIZE_RANGE(offsetBearing, 0.0, 360.0);
895 SG_LOG(SG_INSTR, SG_INFO, "GPS computeTurnData: in=" << _turnStartBearing <<
896 ", out=" << crs << "; turnAngle=" << _turnAngle << ", median=" << median
897 << ", offset=" << offsetBearing);
899 SG_LOG(SG_INSTR, SG_INFO, "next leg is now:" << wp1.get_id() << "->" << wp2.get_id());
901 _turnPt = _wp1_position;
902 _anticipateTurn = true;
905 void GPS::updateTurnData()
907 // depends on ground speed, so needs to be updated per-frame
908 _turnRadius = computeTurnRadiusNm(_last_speed_kts);
910 // compute the turn centre, based on the turn radius.
911 // key thing is to understand that we're working a right-angle triangle,
912 // where the right-angle is the point we start the turn. From that point,
913 // one side is the inbound course to the turn pt, and the other is the
914 // perpendicular line, of length 'r', to the turn centre.
915 // the triangle's hypotenuse, which we need to find, is the distance from the
916 // turn pt to the turn center (in the direction of the offset bearing)
917 // note that d - _turnRadius tell us how much we're 'cutting' the corner.
919 double halfTurnAngle = fabs(_turnAngle * 0.5) * SG_DEGREES_TO_RADIANS;
920 double d = _turnRadius / cos(halfTurnAngle);
922 // SG_LOG(SG_INSTR, SG_INFO, "turnRadius=" << _turnRadius << ", d=" << d
923 // << " (cut distance=" << d - _turnRadius << ")");
925 double median = _turnStartBearing + (_turnAngle * 0.5);
926 double offsetBearing = median + copysign(90, _turnAngle);
927 SG_NORMALIZE_RANGE(offsetBearing, 0.0, 360.0);
930 SGGeodesy::direct(_turnPt, offsetBearing, d * SG_NM_TO_METER, _turnCentre, az2);
933 double GPS::computeTurnRadiusNm(double aGroundSpeedKts) const
935 // turn time is seconds to execute a 360 turn.
936 double turnTime = 360.0 / _config.turnRateDegSec();
938 // c is ground distance covered in that time (circumference of the circle)
939 double c = turnTime * (aGroundSpeedKts / 3600.0); // convert knts to nm/sec
941 // divide by 2PI to go from circumference -> radius
942 return c / (2 * M_PI);
945 void GPS::updateRouteData()
947 double totalDistance = _wp1DistanceM * SG_METER_TO_NM;
948 // walk all waypoints from wp2 to route end, and sum
949 for (int i=_routeMgr->currentWaypoint()+1; i<_routeMgr->size(); ++i) {
950 totalDistance += _routeMgr->get_waypoint(i).get_distance();
953 _routeDistanceNm->setDoubleValue(totalDistance * SG_METER_TO_NM);
954 if (_last_speed_kts > 1.0) {
955 double TTW = ((totalDistance * SG_METER_TO_NM) / _last_speed_kts) * 3600.0;
956 _routeETE->setStringValue(makeTTWString(TTW));
960 void GPS::driveAutopilot()
962 if (!_config.driveAutopilot() || !_realismSimpleGps->getBoolValue()) {
963 _apDrivingFlag->setBoolValue(false);
967 // compatability feature - allow the route-manager / GPS to drive the
968 // generic autopilot heading hold *in leg mode only*
970 bool drive = _mode == "leg";
971 _apDrivingFlag->setBoolValue(drive);
974 // FIXME: we want to set desired track, not heading, here
975 _apTrueHeading->setDoubleValue(getWP1Bearing());
979 void GPS::wp1Changed()
981 if (!_config.driveAutopilot()) {
985 double altFt = _wp1_position.getElevationFt();
986 if (altFt > -9990.0) {
987 _apTargetAltitudeFt->setDoubleValue(altFt);
991 /////////////////////////////////////////////////////////////////////////////
992 // property getter/setters
994 void GPS::setSelectedCourse(double crs)
996 if (_selectedCourse == crs) {
1000 _selectedCourse = crs;
1001 if ((_mode == "obs") || _config.courseSelectable()) {
1002 _desiredCourse = _selectedCourse;
1003 _desiredCourseNode->fireValueChanged();
1007 double GPS::getLegDistance() const
1009 if (!_dataValid || (_mode == "obs")) {
1013 return SGGeodesy::distanceNm(_wp0_position, _wp1_position);
1016 double GPS::getLegCourse() const
1022 return SGGeodesy::courseDeg(_wp0_position, _wp1_position);
1025 double GPS::getLegMagCourse() const
1031 double m = getLegCourse() - _magvar_node->getDoubleValue();
1032 SG_NORMALIZE_RANGE(m, 0.0, 360.0);
1036 double GPS::getAltDistanceRatio() const
1038 if (!_dataValid || (_mode == "obs")) {
1042 double dist = SGGeodesy::distanceM(_wp0_position, _wp1_position);
1043 if ( dist <= 0.0 ) {
1047 double alt_difference_m = _wp0_position.getElevationM() - _wp1_position.getElevationM();
1048 return alt_difference_m / dist;
1051 double GPS::getMagTrack() const
1057 double m = getTrueTrack() - _magvar_node->getDoubleValue();
1058 SG_NORMALIZE_RANGE(m, 0.0, 360.0);
1062 double GPS::getCDIDeflection() const
1069 if (_config.cdiDeflectionIsAngular()) {
1070 defl = getWP1CourseDeviation();
1071 SG_CLAMP_RANGE(defl, -10.0, 10.0); // as in navradio.cxx
1073 double fullScale = _config.cdiDeflectionLinearPeg();
1074 double normError = getWP1CourseErrorNm() / fullScale;
1075 SG_CLAMP_RANGE(normError, -1.0, 1.0);
1076 defl = normError * 10.0; // re-scale to navradio limits, i.e [-10.0 .. 10.0]
1082 const char* GPS::getWP0Ident() const
1084 if (!_dataValid || (_mode != "leg")) {
1088 return _wp0Ident.c_str();
1091 const char* GPS::getWP0Name() const
1093 if (!_dataValid || (_mode != "leg")) {
1097 return _wp0Name.c_str();
1100 const char* GPS::getWP1Ident() const
1106 return _wp1Ident.c_str();
1109 const char* GPS::getWP1Name() const
1115 return _wp1Name.c_str();
1118 double GPS::getWP1Distance() const
1124 return _wp1DistanceM * SG_METER_TO_NM;
1127 double GPS::getWP1TTW() const
1133 if (_last_speed_kts < 1.0) {
1137 return (getWP1Distance() / _last_speed_kts) * 3600.0;
1140 const char* GPS::getWP1TTWString() const
1146 return makeTTWString(getWP1TTW());
1149 double GPS::getWP1Bearing() const
1155 return _wp1TrueBearing;
1158 double GPS::getWP1MagBearing() const
1164 double magBearing = _wp1TrueBearing - _magvar_node->getDoubleValue();
1165 SG_NORMALIZE_RANGE(magBearing, 0.0, 360.0);
1169 double GPS::getWP1CourseDeviation() const
1175 double dev = getWP1MagBearing() - _desiredCourse;
1176 SG_NORMALIZE_RANGE(dev, -180.0, 180.0);
1178 if (fabs(dev) > 90.0) {
1179 // When the course is away from the waypoint,
1180 // it makes sense to change the sign of the deviation.
1182 SG_NORMALIZE_RANGE(dev, -90.0, 90.0);
1188 double GPS::getWP1CourseErrorNm() const
1194 double radDev = getWP1CourseDeviation() * SG_DEGREES_TO_RADIANS;
1195 double course_error_m = sin(radDev) * _wp1DistanceM;
1196 return course_error_m * SG_METER_TO_NM;
1199 bool GPS::getWP1ToFlag() const
1205 double dev = getWP1MagBearing() - _desiredCourse;
1206 SG_NORMALIZE_RANGE(dev, -180.0, 180.0);
1208 return (fabs(dev) < 90.0);
1211 bool GPS::getWP1FromFlag() const
1217 return !getWP1ToFlag();
1220 double GPS::getScratchDistance() const
1222 if (!_scratchValid) {
1226 return SGGeodesy::distanceNm(_indicated_pos, _scratchPos);
1229 double GPS::getScratchTrueBearing() const
1231 if (!_scratchValid) {
1235 return SGGeodesy::courseDeg(_indicated_pos, _scratchPos);
1238 double GPS::getScratchMagBearing() const
1240 if (!_scratchValid) {
1244 double crs = getScratchTrueBearing() - _magvar_node->getDoubleValue();
1245 SG_NORMALIZE_RANGE(crs, 0.0, 360.0);
1249 /////////////////////////////////////////////////////////////////////////////
1250 // command / scratch / search system
1252 void GPS::setCommand(const char* aCmd)
1254 SG_LOG(SG_INSTR, SG_INFO, "GPS command:" << aCmd);
1256 if (!strcmp(aCmd, "direct")) {
1258 } else if (!strcmp(aCmd, "obs")) {
1260 } else if (!strcmp(aCmd, "leg")) {
1262 } else if (!strcmp(aCmd, "load-route-wpt")) {
1263 loadRouteWaypoint();
1264 } else if (!strcmp(aCmd, "nearest")) {
1266 } else if (!strcmp(aCmd, "search")) {
1267 _searchNames = false;
1269 } else if (!strcmp(aCmd, "search-names")) {
1270 _searchNames = true;
1272 } else if (!strcmp(aCmd, "next")) {
1274 } else if (!strcmp(aCmd, "previous")) {
1276 } else if (!strcmp(aCmd, "define-user-wpt")) {
1278 } else if (!strcmp(aCmd, "route-insert-before")) {
1279 int index = _scratchNode->getIntValue("index");
1280 if (index < 0 || (_routeMgr->size() == 0)) {
1281 index = _routeMgr->size();
1282 } else if (index >= _routeMgr->size()) {
1283 SG_LOG(SG_INSTR, SG_WARN, "GPS:route-insert-before, bad index:" << index);
1287 insertWaypointAtIndex(index);
1288 } else if (!strcmp(aCmd, "route-insert-after")) {
1289 int index = _scratchNode->getIntValue("index");
1290 if (index < 0 || (_routeMgr->size() == 0)) {
1291 index = _routeMgr->size();
1292 } else if (index >= _routeMgr->size()) {
1293 SG_LOG(SG_INSTR, SG_WARN, "GPS:route-insert-after, bad index:" << index);
1299 insertWaypointAtIndex(index);
1300 } else if (!strcmp(aCmd, "route-delete")) {
1301 int index = _scratchNode->getIntValue("index");
1303 index = _routeMgr->size();
1304 } else if (index >= _routeMgr->size()) {
1305 SG_LOG(SG_INSTR, SG_WARN, "GPS:route-delete, bad index:" << index);
1309 removeWaypointAtIndex(index);
1311 SG_LOG(SG_INSTR, SG_WARN, "GPS:unrecognized command:" << aCmd);
1315 void GPS::clearScratch()
1317 _scratchPos = SGGeod::fromDegFt(-9999.0, -9999.0, -9999.0);
1318 _scratchValid = false;
1319 _scratchNode->setStringValue("type", "");
1320 _scratchNode->setStringValue("query", "");
1323 bool GPS::isScratchPositionValid() const
1325 if ((_scratchPos.getLongitudeDeg() < -9990.0) ||
1326 (_scratchPos.getLatitudeDeg() < -9990.0)) {
1333 void GPS::directTo()
1335 _wp0_position = _indicated_pos;
1337 if (isScratchPositionValid()) {
1338 _wp1Ident = _scratchNode->getStringValue("ident");
1339 _wp1Name = _scratchNode->getStringValue("name");
1340 _wp1_position = _scratchPos;
1344 _desiredCourse = getLegMagCourse();
1345 _desiredCourseNode->fireValueChanged();
1350 void GPS::loadRouteWaypoint()
1352 _scratchValid = false;
1353 // if (!_routeMgr->isRouteActive()) {
1354 // SG_LOG(SG_INSTR, SG_WARN, "GPS:loadWaypoint: no active route");
1358 int index = _scratchNode->getIntValue("index", -9999);
1361 if ((index < 0) || (index >= _routeMgr->size())) { // no index supplied, use current wp
1362 index = _routeMgr->currentWaypoint();
1365 _searchIsRoute = true;
1366 setScratchFromRouteWaypoint(index);
1369 void GPS::setScratchFromRouteWaypoint(int aIndex)
1371 assert(_searchIsRoute);
1372 if ((aIndex < 0) || (aIndex >= _routeMgr->size())) {
1373 SG_LOG(SG_INSTR, SG_WARN, "GPS:setScratchFromRouteWaypoint: route-index out of bounds");
1377 _searchResultIndex = aIndex;
1378 SGWayPoint wp(_routeMgr->get_waypoint(aIndex));
1379 _scratchNode->setStringValue("name", wp.get_name());
1380 _scratchNode->setStringValue("ident", wp.get_id());
1381 _scratchPos = wp.get_target();
1382 _scratchValid = true;
1383 _scratchNode->setDoubleValue("course", wp.get_track());
1384 _scratchNode->setIntValue("index", aIndex);
1386 int lastResult = _routeMgr->size() - 1;
1387 _searchHasNext = (_searchResultIndex < lastResult);
1390 void GPS::loadNearest()
1392 string sty(_scratchNode->getStringValue("type"));
1393 FGPositioned::Type ty = FGPositioned::typeFromName(sty);
1394 if (ty == FGPositioned::INVALID) {
1395 SG_LOG(SG_INSTR, SG_WARN, "GPS:loadNearest: request type is invalid:" << sty);
1399 auto_ptr<FGPositioned::Filter> f(createFilter(ty));
1400 int limitCount = _scratchNode->getIntValue("max-results", 1);
1401 double cutoffDistance = _scratchNode->getDoubleValue("cutoff-nm", 400.0);
1403 SGGeod searchPos = _indicated_pos;
1404 if (isScratchPositionValid()) {
1405 searchPos = _scratchPos;
1408 clearScratch(); // clear now, regardless of whether we find a match or not
1411 FGPositioned::findClosestN(searchPos, limitCount, cutoffDistance, f.get());
1412 _searchResultsCached = true;
1413 _searchResultIndex = 0;
1414 _searchIsRoute = false;
1415 _searchHasNext = false;
1417 if (_searchResults.empty()) {
1418 SG_LOG(SG_INSTR, SG_INFO, "GPS:loadNearest: no matches at all");
1422 _searchHasNext = (_searchResults.size() > 1);
1423 setScratchFromCachedSearchResult();
1426 bool GPS::SearchFilter::pass(FGPositioned* aPos) const
1428 switch (aPos->type()) {
1429 case FGPositioned::AIRPORT:
1430 // heliport and seaport too?
1431 case FGPositioned::VOR:
1432 case FGPositioned::NDB:
1433 case FGPositioned::FIX:
1434 case FGPositioned::TACAN:
1435 case FGPositioned::WAYPOINT:
1442 FGPositioned::Type GPS::SearchFilter::minType() const
1444 return FGPositioned::AIRPORT;
1447 FGPositioned::Type GPS::SearchFilter::maxType() const
1449 return FGPositioned::WAYPOINT;
1452 FGPositioned::Filter* GPS::createFilter(FGPositioned::Type aTy)
1454 if (aTy == FGPositioned::AIRPORT) {
1455 return new FGAirport::HardSurfaceFilter(_config.minRunwayLengthFt());
1458 // if we were passed INVALID, assume it means 'all types interesting to a GPS'
1459 if (aTy == FGPositioned::INVALID) {
1460 return new SearchFilter;
1463 return new FGPositioned::TypeFilter(aTy);
1468 // parse search terms into local members, and exec the first search
1469 string sty(_scratchNode->getStringValue("type"));
1470 _searchType = FGPositioned::typeFromName(sty);
1471 _searchQuery = _scratchNode->getStringValue("query");
1472 if (_searchQuery.empty()) {
1473 SG_LOG(SG_INSTR, SG_WARN, "empty GPS search query");
1478 _searchExact = _scratchNode->getBoolValue("exact", true);
1479 _searchOrderByRange = _scratchNode->getBoolValue("order-by-distance", true);
1480 _searchResultIndex = 0;
1481 _searchIsRoute = false;
1482 _searchHasNext = false;
1484 if (_searchExact && _searchOrderByRange) {
1485 // immediate mode search, get all the results now and cache them
1486 auto_ptr<FGPositioned::Filter> f(createFilter(_searchType));
1488 _searchResults = FGPositioned::findAllWithNameSortedByRange(_searchQuery, _indicated_pos, f.get());
1490 _searchResults = FGPositioned::findAllWithIdentSortedByRange(_searchQuery, _indicated_pos, f.get());
1493 _searchResultsCached = true;
1495 if (_searchResults.empty()) {
1500 _searchHasNext = (_searchResults.size() > 1);
1501 setScratchFromCachedSearchResult();
1503 // iterative search, look up result zero
1504 _searchResultsCached = false;
1509 void GPS::performSearch()
1511 auto_ptr<FGPositioned::Filter> f(createFilter(_searchType));
1516 if (_searchOrderByRange) {
1517 r = FGPositioned::findClosestWithPartialName(_indicated_pos, _searchQuery, f.get(), _searchResultIndex, _searchHasNext);
1519 r = FGPositioned::findWithPartialName(_searchQuery, f.get(), _searchResultIndex, _searchHasNext);
1522 if (_searchOrderByRange) {
1523 r = FGPositioned::findClosestWithPartialId(_indicated_pos, _searchQuery, f.get(), _searchResultIndex, _searchHasNext);
1525 r = FGPositioned::findWithPartialId(_searchQuery, f.get(), _searchResultIndex, _searchHasNext);
1533 setScratchFromPositioned(r.get(), _searchResultIndex);
1536 void GPS::setScratchFromCachedSearchResult()
1538 assert(_searchResultsCached);
1539 int index = _searchResultIndex;
1541 if ((index < 0) || (index >= (int) _searchResults.size())) {
1542 SG_LOG(SG_INSTR, SG_WARN, "GPS:setScratchFromCachedSearchResult: index out of bounds:" << index);
1546 setScratchFromPositioned(_searchResults[index], index);
1548 int lastResult = (int) _searchResults.size() - 1;
1549 _searchHasNext = (_searchResultIndex < lastResult);
1552 void GPS::setScratchFromPositioned(FGPositioned* aPos, int aIndex)
1557 _scratchPos = aPos->geod();
1558 _scratchNode->setStringValue("name", aPos->name());
1559 _scratchNode->setStringValue("ident", aPos->ident());
1560 _scratchNode->setStringValue("type", FGPositioned::nameForType(aPos->type()));
1563 _scratchNode->setIntValue("index", aIndex);
1566 _scratchValid = true;
1567 if (_searchResultsCached) {
1568 _scratchNode->setIntValue("result-count", _searchResults.size());
1571 switch (aPos->type()) {
1572 case FGPositioned::VOR:
1573 _scratchNode->setDoubleValue("frequency-mhz", static_cast<FGNavRecord*>(aPos)->get_freq() / 100.0);
1576 case FGPositioned::NDB:
1577 _scratchNode->setDoubleValue("frequency-khz", static_cast<FGNavRecord*>(aPos)->get_freq() / 100.0);
1580 case FGPositioned::AIRPORT:
1581 addAirportToScratch((FGAirport*)aPos);
1589 // look for being on the route and set?
1592 void GPS::addAirportToScratch(FGAirport* aAirport)
1594 for (unsigned int r=0; r<aAirport->numRunways(); ++r) {
1595 SGPropertyNode* rwyNd = _scratchNode->getChild("runways", r, true);
1596 FGRunway* rwy = aAirport->getRunwayByIndex(r);
1597 // TODO - filter out unsuitable runways in the future
1598 // based on config again
1600 rwyNd->setStringValue("id", rwy->ident().c_str());
1601 rwyNd->setIntValue("length-ft", rwy->lengthFt());
1602 rwyNd->setIntValue("width-ft", rwy->widthFt());
1603 rwyNd->setIntValue("heading-deg", rwy->headingDeg());
1604 // map surface code to a string
1605 // TODO - lighting information
1608 rwyNd->setDoubleValue("ils-frequency-mhz", rwy->ILS()->get_freq() / 100.0);
1610 } // of runways iteration
1614 void GPS::selectOBSMode()
1616 if (isScratchPositionValid()) {
1617 _wp1Ident = _scratchNode->getStringValue("ident");
1618 _wp1Name = _scratchNode->getStringValue("name");
1619 _wp1_position = _scratchPos;
1622 SG_LOG(SG_INSTR, SG_INFO, "GPS switching to OBS mode");
1624 _wp0_position = _indicated_pos;
1628 void GPS::selectLegMode()
1630 if (_mode == "leg") {
1634 if (!_routeMgr->isRouteActive()) {
1635 SG_LOG(SG_INSTR, SG_WARN, "GPS:selectLegMode: no active route");
1639 SG_LOG(SG_INSTR, SG_INFO, "GPS switching to LEG mode");
1642 // depending on the situation, this will either get over-written
1643 // in routeManagerSequenced or not; either way it does no harm to
1645 _wp0_position = _indicated_pos;
1647 // not really sequenced, but does all the work of updating wp0/1
1648 routeManagerSequenced();
1651 void GPS::nextResult()
1653 if (!_searchHasNext) {
1658 if (_searchIsRoute) {
1659 setScratchFromRouteWaypoint(++_searchResultIndex);
1660 } else if (_searchResultsCached) {
1661 ++_searchResultIndex;
1662 setScratchFromCachedSearchResult();
1664 ++_searchResultIndex;
1666 } // of iterative search case
1669 void GPS::previousResult()
1671 if (_searchResultIndex <= 0) {
1676 --_searchResultIndex;
1678 if (_searchIsRoute) {
1679 setScratchFromRouteWaypoint(_searchResultIndex);
1680 } else if (_searchResultsCached) {
1681 setScratchFromCachedSearchResult();
1687 void GPS::defineWaypoint()
1689 if (!isScratchPositionValid()) {
1690 SG_LOG(SG_INSTR, SG_WARN, "GPS:defineWaypoint: invalid lat/lon");
1694 string ident = _scratchNode->getStringValue("ident");
1695 if (ident.size() < 2) {
1696 SG_LOG(SG_INSTR, SG_WARN, "GPS:defineWaypoint: waypoint identifier must be at least two characters");
1700 // check for duplicate idents
1701 FGPositioned::TypeFilter f(FGPositioned::WAYPOINT);
1702 FGPositioned::List dups = FGPositioned::findAllWithIdentSortedByRange(ident, _indicated_pos, &f);
1703 if (!dups.empty()) {
1704 SG_LOG(SG_INSTR, SG_WARN, "GPS:defineWaypoint: non-unique waypoint identifier, ho-hum");
1707 SG_LOG(SG_INSTR, SG_INFO, "GPS:defineWaypoint: creating waypoint:" << ident);
1708 FGPositionedRef wpt = FGPositioned::createUserWaypoint(ident, _scratchPos);
1709 _searchResultsCached = false;
1710 setScratchFromPositioned(wpt.get(), -1);
1713 void GPS::insertWaypointAtIndex(int aIndex)
1715 // note we do allow index = routeMgr->size(), that's an append
1716 if ((aIndex < 0) || (aIndex > _routeMgr->size())) {
1717 throw sg_range_exception("GPS::insertWaypointAtIndex: index out of bounds");
1720 if (!isScratchPositionValid()) {
1721 SG_LOG(SG_INSTR, SG_WARN, "GPS:insertWaypointAtIndex: invalid lat/lon");
1725 string ident = _scratchNode->getStringValue("ident");
1726 string name = _scratchNode->getStringValue("name");
1728 _routeMgr->add_waypoint(SGWayPoint(_scratchPos, ident, name), aIndex);
1731 void GPS::removeWaypointAtIndex(int aIndex)
1733 if ((aIndex < 0) || (aIndex >= _routeMgr->size())) {
1734 throw sg_range_exception("GPS::removeWaypointAtIndex: index out of bounds");
1737 _routeMgr->pop_waypoint(aIndex);
1740 void GPS::tieSGGeod(SGPropertyNode* aNode, SGGeod& aRef,
1741 const char* lonStr, const char* latStr, const char* altStr)
1743 tie(aNode, lonStr, SGRawValueMethods<SGGeod, double>(aRef, &SGGeod::getLongitudeDeg, &SGGeod::setLongitudeDeg));
1744 tie(aNode, latStr, SGRawValueMethods<SGGeod, double>(aRef, &SGGeod::getLatitudeDeg, &SGGeod::setLatitudeDeg));
1747 tie(aNode, altStr, SGRawValueMethods<SGGeod, double>(aRef, &SGGeod::getElevationFt, &SGGeod::setElevationFt));
1751 void GPS::tieSGGeodReadOnly(SGPropertyNode* aNode, SGGeod& aRef,
1752 const char* lonStr, const char* latStr, const char* altStr)
1754 tie(aNode, lonStr, SGRawValueMethods<SGGeod, double>(aRef, &SGGeod::getLongitudeDeg, NULL));
1755 tie(aNode, latStr, SGRawValueMethods<SGGeod, double>(aRef, &SGGeod::getLatitudeDeg, NULL));
1758 tie(aNode, altStr, SGRawValueMethods<SGGeod, double>(aRef, &SGGeod::getElevationFt, NULL));