]> git.mxchange.org Git - flightgear.git/blob - src/Instrumentation/gps.cxx
Merge branch 'ehofman/particle' into next
[flightgear.git] / src / Instrumentation / gps.cxx
1 // gps.cxx - distance-measuring equipment.
2 // Written by David Megginson, started 2003.
3 //
4 // This file is in the Public Domain and comes with no warranty.
5
6 #ifdef HAVE_CONFIG_H
7 #  include <config.h>
8 #endif
9
10 #include "gps.hxx"
11
12 #include <memory>
13 #include <set>
14
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"
23
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>
28
29 using std::auto_ptr;
30 using std::string;
31
32 ///////////////////////////////////////////////////////////////////
33
34 void SGGeodProperty::init(SGPropertyNode* base, const char* lonStr, const char* latStr, const char* altStr)
35 {
36     _lon = base->getChild(lonStr, 0, true);
37     _lat = base->getChild(latStr, 0, true);
38     if (altStr) {
39         _alt = base->getChild(altStr, 0, true);
40     }
41 }
42
43 void SGGeodProperty::init(const char* lonStr, const char* latStr, const char* altStr)
44 {
45     _lon = fgGetNode(lonStr, true);
46     _lat = fgGetNode(latStr, true);
47     if (altStr) {
48         _alt = fgGetNode(altStr, true);
49     }
50 }
51
52 void SGGeodProperty::clear()
53 {
54     _lon = _lat = _alt = NULL;
55 }
56
57 void SGGeodProperty::operator=(const SGGeod& geod)
58 {
59     _lon->setDoubleValue(geod.getLongitudeDeg());
60     _lat->setDoubleValue(geod.getLatitudeDeg());
61     if (_alt) {
62         _alt->setDoubleValue(geod.getElevationFt());
63     }
64 }
65
66 SGGeod SGGeodProperty::get() const
67 {
68     double lon = _lon->getDoubleValue(),
69         lat = _lat->getDoubleValue();
70     if (_alt) {
71         return SGGeod::fromDegFt(lon, lat, _alt->getDoubleValue());
72     } else {
73         return SGGeod::fromDeg(lon,lat);
74     }
75 }
76
77 static const char* makeTTWString(double TTW)
78 {
79   if ((TTW <= 0.0) || (TTW >= 356400.5)) { // 99 hours
80     return "--:--:--";
81   }
82       
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);
92   return TTW_str;
93 }
94
95 /////////////////////////////////////////////////////////////////////////////
96
97 class GPSListener : public SGPropertyChangeListener
98 {
99 public:
100   GPSListener(GPS *m) : 
101     _gps(m),
102     _guard(false) {}
103     
104   virtual void valueChanged (SGPropertyNode * prop)
105   {
106     if (_guard) {
107       return;
108     }
109     
110     _guard = true;
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) {
118       _gps->routeEdited();
119     } else if (prop == _gps->_routeFinishedSignal) {
120       _gps->routeFinished();
121     }
122         
123     _guard = false;
124   }
125   
126   void setGuard(bool g) {
127     _guard = g;
128   }
129 private:
130   GPS* _gps;
131   bool _guard; // re-entrancy guard
132 };
133
134 ////////////////////////////////////////////////////////////////////////////
135 /**
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.
139  */
140  
141 class DeprecatedPropListener : public SGPropertyChangeListener
142 {
143 public:
144   DeprecatedPropListener(SGPropertyNode* gps)
145   {
146     _parents.insert(gps);
147     SGPropertyNode* wp = gps->getChild("wp"); 
148     _parents.insert(wp);
149     _parents.insert(wp->getChild("wp", 0));
150     _parents.insert(wp->getChild("wp", 1));
151     
152     std::set<SGPropertyNode*>::iterator it;
153     for (it = _parents.begin(); it != _parents.end(); ++it) {
154       (*it)->addChangeListener(this);
155     }
156   }
157   
158   virtual void valueChanged (SGPropertyNode * prop)
159   {
160   }
161   
162   virtual void childAdded (SGPropertyNode * parent, SGPropertyNode * child)
163   {
164     if (isDeprecated(parent, child)) {
165       SG_LOG(SG_INSTR, SG_WARN, "GPS: someone accessed a deprecated property:"
166         << child->getPath(true));
167     }
168   }
169 private:
170   bool isDeprecated(SGPropertyNode * parent, SGPropertyNode * child) const 
171   {
172     if (_parents.count(parent) < 1) {
173       return false;
174     }
175     
176     // no child exclusions yet
177     return true;
178   }
179   
180   std::set<SGPropertyNode*> _parents;
181 };
182
183 ////////////////////////////////////////////////////////////////////////////
184 // configuration helper object
185
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)
196 {
197   _enableTurnAnticipation = false;
198 }
199
200 void GPS::Config::bind(GPS* aOwner, SGPropertyNode* aCfg)
201 {
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));
210 }
211
212 ////////////////////////////////////////////////////////////////////////////
213
214 GPS::GPS ( SGPropertyNode *node) : 
215   _selectedCourse(0.0),
216   _dataValid(false),
217   _lastPosValid(false),
218   _mode("init"),
219   _name(node->getStringValue("name", "gps")),
220   _num(node->getIntValue("number", 0)),
221   _computeTurnData(false),
222   _anticipateTurn(false),
223   _inTurn(false)
224 {
225   string branch = "/instrumentation/" + _name;
226   _gpsNode = fgGetNode(branch.c_str(), _num, true );
227   _scratchNode = _gpsNode->getChild("scratch", 0, true);
228 }
229
230 GPS::~GPS ()
231 {
232 }
233
234 void
235 GPS::init ()
236 {
237   _routeMgr = (FGRouteMgr*) globals->get_subsystem("route-manager");
238   assert(_routeMgr);
239   
240   _position.init("/position/longitude-deg", "/position/latitude-deg", "/position/altitude-ft");
241   _magvar_node = fgGetNode("/environment/magnetic-variation-deg", true);
242   _serviceable_node = _gpsNode->getChild("serviceable", 0, true);
243   _serviceable_node->setBoolValue(true);
244   _electrical_node = fgGetNode("/systems/electrical/outputs/gps", true);
245
246 // basic GPS outputs
247   _raim_node = _gpsNode->getChild("raim", 0, true);
248   _odometer_node = _gpsNode->getChild("odometer", 0, true);
249   _trip_odometer_node = _gpsNode->getChild("trip-odometer", 0, true);
250   _true_bug_error_node = _gpsNode->getChild("true-bug-error-deg", 0, true);
251   _magnetic_bug_error_node = _gpsNode->getChild("magnetic-bug-error-deg", 0, true);
252   _eastWestVelocity = _gpsNode->getChild("ew-velocity-msec", 0, true);
253   _northSouthVelocity = _gpsNode->getChild("ns-velocity-msec", 0, true);
254   
255 // waypoints
256   SGPropertyNode *wp_node = _gpsNode->getChild("wp", 0, true);
257   SGPropertyNode *wp1_node = wp_node->getChild("wp", 1, true);
258
259   // for compatability, alias selected course down to wp/wp[1]/desired-course-deg
260   SGPropertyNode* wp1Crs = wp1_node->getChild("desired-course-deg", 0, true);
261   wp1Crs->alias(_gpsNode->getChild("desired-course-deg", 0, true));
262     
263 //    _true_wp1_bearing_error_node =
264 //        wp1_node->getChild("true-bearing-error-deg", 0, true);
265 //    _magnetic_wp1_bearing_error_node =
266   //      wp1_node->getChild("magnetic-bearing-error-deg", 0, true);
267
268   _tracking_bug_node = _gpsNode->getChild("tracking-bug", 0, true);
269          
270 // reference navid
271   SGPropertyNode_ptr ref_navaid = _gpsNode->getChild("ref-navaid", 0, true);
272   _ref_navaid_id_node = ref_navaid->getChild("id", 0, true);
273   _ref_navaid_name_node = ref_navaid->getChild("name", 0, true);
274   _ref_navaid_bearing_node = ref_navaid->getChild("bearing-deg", 0, true);
275   _ref_navaid_frequency_node = ref_navaid->getChild("frequency-mhz", 0, true);
276   _ref_navaid_distance_node = ref_navaid->getChild("distance-nm", 0, true);
277   _ref_navaid_mag_bearing_node = ref_navaid->getChild("mag-bearing-deg", 0, true);
278   _ref_navaid_elapsed = 0.0;
279   _ref_navaid_set = false;
280     
281 // route properties    
282   // should these move to the route manager?
283   _routeDistanceNm = _gpsNode->getChild("route-distance-nm", 0, true);
284   _routeETE = _gpsNode->getChild("ETE", 0, true);
285   _routeEditedSignal = fgGetNode("/autopilot/route-manager/signals/edited", true);
286   _routeFinishedSignal = fgGetNode("/autopilot/route-manager/signals/finished", true);
287   
288 // add listener to various things
289   _listener = new GPSListener(this);
290   _route_current_wp_node = fgGetNode("/autopilot/route-manager/current-wp", true);
291   _route_current_wp_node->addChangeListener(_listener);
292   _route_active_node = fgGetNode("/autopilot/route-manager/active", true);
293   _route_active_node->addChangeListener(_listener);
294   _ref_navaid_id_node->addChangeListener(_listener);
295   _routeEditedSignal->addChangeListener(_listener);
296   _routeFinishedSignal->addChangeListener(_listener);
297   
298 // navradio slaving properties  
299   SGPropertyNode* toFlag = _gpsNode->getChild("to-flag", 0, true);
300   toFlag->alias(wp1_node->getChild("to-flag"));
301   
302   SGPropertyNode* fromFlag = _gpsNode->getChild("from-flag", 0, true);
303   fromFlag->alias(wp1_node->getChild("from-flag"));
304     
305 // autopilot drive properties
306   _apTrueHeading = fgGetNode("/autopilot/settings/true-heading-deg",true);
307   _apTargetAltitudeFt = fgGetNode("/autopilot/settings/target-altitude-ft", true);
308   _apAltitudeLock = fgGetNode("/autopilot/locks/altitude", true);
309   
310 // realism prop[s]
311   _realismSimpleGps = fgGetNode("/sim/realism/simple-gps", true);
312   if (!_realismSimpleGps->hasValue()) {
313     _realismSimpleGps->setBoolValue(true);
314   }
315   
316   // last thing, add the deprecated prop watcher
317   new DeprecatedPropListener(_gpsNode);
318   
319   clearOutput();
320 }
321
322 void
323 GPS::bind()
324 {
325   _config.bind(this, _gpsNode->getChild("config", 0, true));
326 // basic GPS outputs
327   tie(_gpsNode, "selected-course-deg", SGRawValueMethods<GPS, double>
328     (*this, &GPS::getSelectedCourse, &GPS::setSelectedCourse));
329   
330   tie(_gpsNode, "desired-course-deg", SGRawValueMethods<GPS, double>
331     (*this, &GPS::getDesiredCourse, NULL));
332   _desiredCourseNode = _gpsNode->getChild("desired-course-deg");
333     
334   tieSGGeodReadOnly(_gpsNode, _indicated_pos, "indicated-longitude-deg", 
335         "indicated-latitude-deg", "indicated-altitude-ft");
336
337   tie(_gpsNode, "indicated-vertical-speed", SGRawValueMethods<GPS, double>
338     (*this, &GPS::getVerticalSpeed, NULL));
339   tie(_gpsNode, "indicated-track-true-deg", SGRawValueMethods<GPS, double>
340     (*this, &GPS::getTrueTrack, NULL));
341   tie(_gpsNode, "indicated-track-magnetic-deg", SGRawValueMethods<GPS, double>
342     (*this, &GPS::getMagTrack, NULL));
343   tie(_gpsNode, "indicated-ground-speed-kt", SGRawValueMethods<GPS, double>
344     (*this, &GPS::getGroundspeedKts, NULL));
345   
346 // command system    
347   tie(_gpsNode, "mode", SGRawValueMethods<GPS, const char*>(*this, &GPS::getMode, NULL));
348   tie(_gpsNode, "command", SGRawValueMethods<GPS, const char*>(*this, &GPS::getCommand, &GPS::setCommand));
349     
350   tieSGGeod(_scratchNode, _scratchPos, "longitude-deg", "latitude-deg", "altitude-ft");
351   tie(_scratchNode, "valid", SGRawValueMethods<GPS, bool>(*this, &GPS::getScratchValid, NULL));
352   tie(_scratchNode, "distance-nm", SGRawValueMethods<GPS, double>(*this, &GPS::getScratchDistance, NULL));
353   tie(_scratchNode, "true-bearing-deg", SGRawValueMethods<GPS, double>(*this, &GPS::getScratchTrueBearing, NULL));
354   tie(_scratchNode, "mag-bearing-deg", SGRawValueMethods<GPS, double>(*this, &GPS::getScratchMagBearing, NULL));
355   tie(_scratchNode, "has-next", SGRawValueMethods<GPS, bool>(*this, &GPS::getScratchHasNext, NULL));
356   _scratchValid = false;
357   
358 // waypoint data (including various historical things)
359   SGPropertyNode *wp_node = _gpsNode->getChild("wp", 0, true);
360   SGPropertyNode *wp0_node = wp_node->getChild("wp", 0, true);
361   SGPropertyNode *wp1_node = wp_node->getChild("wp", 1, true);
362
363   tieSGGeodReadOnly(wp0_node, _wp0_position, "longitude-deg", "latitude-deg", "altitude-ft");
364   tie(wp0_node, "ID", SGRawValueMethods<GPS, const char*>
365     (*this, &GPS::getWP0Ident, NULL));
366   tie(wp0_node, "name", SGRawValueMethods<GPS, const char*>
367     (*this, &GPS::getWP0Name, NULL));
368     
369   tieSGGeodReadOnly(wp1_node, _wp1_position, "longitude-deg", "latitude-deg", "altitude-ft");
370   tie(wp1_node, "ID", SGRawValueMethods<GPS, const char*>
371     (*this, &GPS::getWP1Ident, NULL));
372   tie(wp1_node, "name", SGRawValueMethods<GPS, const char*>
373     (*this, &GPS::getWP1Name, NULL));
374   
375   tie(wp1_node, "distance-nm", SGRawValueMethods<GPS, double>
376     (*this, &GPS::getWP1Distance, NULL));
377   tie(wp1_node, "bearing-true-deg", SGRawValueMethods<GPS, double>
378     (*this, &GPS::getWP1Bearing, NULL));
379   tie(wp1_node, "bearing-mag-deg", SGRawValueMethods<GPS, double>
380     (*this, &GPS::getWP1MagBearing, NULL));
381   tie(wp1_node, "TTW-sec", SGRawValueMethods<GPS, double>
382     (*this, &GPS::getWP1TTW, NULL));
383   tie(wp1_node, "TTW", SGRawValueMethods<GPS, const char*>
384     (*this, &GPS::getWP1TTWString, NULL));
385   
386   tie(wp1_node, "course-deviation-deg", SGRawValueMethods<GPS, double>
387     (*this, &GPS::getWP1CourseDeviation, NULL));
388   tie(wp1_node, "course-error-nm", SGRawValueMethods<GPS, double>
389     (*this, &GPS::getWP1CourseErrorNm, NULL));
390   tie(wp1_node, "to-flag", SGRawValueMethods<GPS, bool>
391     (*this, &GPS::getWP1ToFlag, NULL));
392   tie(wp1_node, "from-flag", SGRawValueMethods<GPS, bool>
393     (*this, &GPS::getWP1FromFlag, NULL));
394
395 // leg properties (only valid in DTO/LEG modes, not OBS)
396   tie(wp_node, "leg-distance-nm", SGRawValueMethods<GPS, double>(*this, &GPS::getLegDistance, NULL));
397   tie(wp_node, "leg-true-course-deg", SGRawValueMethods<GPS, double>(*this, &GPS::getLegCourse, NULL));
398   tie(wp_node, "leg-mag-course-deg", SGRawValueMethods<GPS, double>(*this, &GPS::getLegMagCourse, NULL));
399   tie(wp_node, "alt-dist-ratio", SGRawValueMethods<GPS, double>(*this, &GPS::getAltDistanceRatio, NULL));
400
401 // navradio slaving properties  
402   tie(_gpsNode, "cdi-deflection", SGRawValueMethods<GPS,double>
403     (*this, &GPS::getCDIDeflection));
404 }
405
406 void
407 GPS::unbind()
408 {
409   for (unsigned int t=0; t<_tiedNodes.size(); ++t) {
410     _tiedNodes[t]->untie();
411   }
412   _tiedNodes.clear();
413 }
414
415 void
416 GPS::clearOutput()
417 {
418   _dataValid = false;
419   _last_speed_kts = 0.0;
420   _last_pos = SGGeod();
421   _lastPosValid = false;
422   _indicated_pos = SGGeod();
423   _last_vertical_speed = 0.0;
424   _last_true_track = 0.0;
425   _lastEWVelocity = _lastNSVelocity = 0.0;
426   
427   _raim_node->setDoubleValue(0.0);
428   _indicated_pos = SGGeod();
429   _wp1DistanceM = 0.0;
430   _wp1TrueBearing = 0.0;
431   _wp1_position = SGGeod();
432   _odometer_node->setDoubleValue(0);
433   _trip_odometer_node->setDoubleValue(0);
434   _tracking_bug_node->setDoubleValue(0);
435   _true_bug_error_node->setDoubleValue(0);
436   _magnetic_bug_error_node->setDoubleValue(0);
437   _northSouthVelocity->setDoubleValue(0.0);
438   _eastWestVelocity->setDoubleValue(0.0);
439 }
440
441 void
442 GPS::update (double delta_time_sec)
443 {
444   if (!_realismSimpleGps->getBoolValue()) {
445     // If it's off, don't bother.
446     if (!_serviceable_node->getBoolValue() || !_electrical_node->getBoolValue()) {
447       clearOutput();
448       return;
449     }
450   }
451   
452   if (delta_time_sec <= 0.0) {
453     return; // paused, don't bother
454   }    
455     // TODO: Add noise and other errors.
456 /*
457
458     // Bias and random error
459     double random_factor = sg_random();
460     double random_error = 1.4;
461     double error_radius = 5.1;
462     double bias_max_radius = 5.1;
463     double random_max_radius = 1.4;
464
465     bias_length += (random_factor-0.5) * 1.0e-3;
466     if (bias_length <= 0.0) bias_length = 0.0;
467     else if (bias_length >= bias_max_radius) bias_length = bias_max_radius;
468     bias_angle  += (random_factor-0.5) * 1.0e-3;
469     if (bias_angle <= 0.0) bias_angle = 0.0;
470     else if (bias_angle >= 360.0) bias_angle = 360.0;
471
472     double random_length = random_factor * random_max_radius;
473     double random_angle = random_factor * 360.0;
474
475     double bias_x = bias_length * cos(bias_angle * SG_PI / 180.0);
476     double bias_y = bias_length * sin(bias_angle * SG_PI / 180.0);
477     double random_x = random_length * cos(random_angle * SG_PI / 180.0);
478     double random_y = random_length * sin(random_angle * SG_PI / 180.0);
479     double error_x = bias_x + random_x;
480     double error_y = bias_y + random_y;
481     double error_length = sqrt(error_x*error_x + error_y*error_y);
482     double error_angle = atan(error_y / error_x) * 180.0 / SG_PI;
483
484     double lat2;
485     double lon2;
486     double az2;
487     geo_direct_wgs_84 ( altitude_m, latitude_deg,
488                         longitude_deg, error_angle,
489                         error_length, &lat2, &lon2,
490                         &az2 );
491     //cout << lat2 << " " << lon2 << endl;
492     printf("%f %f \n", bias_length, bias_angle);
493     printf("%3.7f %3.7f \n", lat2, lon2);
494     printf("%f %f \n", error_length, error_angle);
495
496 */
497   _raim_node->setDoubleValue(1.0);
498   _indicated_pos = _position.get();
499   updateBasicData(delta_time_sec);
500
501   if (_dataValid) {
502     if (_mode != "obs") {
503       updateTurn();
504     }
505       
506     updateWaypoints();
507     updateTrackingBug();
508     updateReferenceNavaid(delta_time_sec);
509     updateRouteData();
510     driveAutopilot();
511   }
512   
513   if (_dataValid && (_mode == "init")) {
514     // allow a realistic delay in the future, here
515     SG_LOG(SG_INSTR, SG_INFO, "GPS initialisation complete");
516         
517     if (_route_active_node->getBoolValue()) {
518       // GPS init with active route
519       SG_LOG(SG_INSTR, SG_INFO, "GPS init with active route");
520       selectLegMode();
521     } else {
522       // initialise in OBS mode, with waypt set to the nearest airport.
523       // keep in mind at this point, _dataValid is not set
524     
525       auto_ptr<FGPositioned::Filter> f(createFilter(FGPositioned::AIRPORT));
526       FGPositionedRef apt = FGPositioned::findClosest(_position.get(), 20.0, f.get());
527       if (apt) {
528         setScratchFromPositioned(apt, 0);
529         selectOBSMode();
530       }
531     }
532   } // of init mode check
533   
534   _last_pos = _indicated_pos;
535   _lastPosValid = true;
536 }
537
538 void
539 GPS::updateBasicData(double dt)
540 {
541   if (!_lastPosValid) {
542     return;
543   }
544   
545   double distance_m;
546   double track2_deg;
547   SGGeodesy::inverse(_last_pos, _indicated_pos, _last_true_track, track2_deg, distance_m );
548     
549   double speed_kt = ((distance_m * SG_METER_TO_NM) * ((1 / dt) * 3600.0));
550   double vertical_speed_mpm = ((_indicated_pos.getElevationM() - _last_pos.getElevationM()) * 60 / dt);
551   _last_vertical_speed = vertical_speed_mpm * SG_METER_TO_FEET;
552   
553   speed_kt = fgGetLowPass(_last_speed_kts, speed_kt, dt/10.0);
554   _last_speed_kts = speed_kt;
555   
556   SGGeod g = _indicated_pos;
557   g.setLongitudeDeg(_last_pos.getLongitudeDeg());
558   double northSouthM = SGGeodesy::distanceM(_last_pos, g);
559   northSouthM = copysign(northSouthM, _indicated_pos.getLatitudeDeg() - _last_pos.getLatitudeDeg());
560   
561   double nsMSec = fgGetLowPass(_lastNSVelocity, northSouthM / dt, dt/2.0);
562   _lastNSVelocity = nsMSec;
563   _northSouthVelocity->setDoubleValue(nsMSec);
564
565
566   g = _indicated_pos;
567   g.setLatitudeDeg(_last_pos.getLatitudeDeg());
568   double eastWestM = SGGeodesy::distanceM(_last_pos, g);
569   eastWestM = copysign(eastWestM, _indicated_pos.getLongitudeDeg() - _last_pos.getLongitudeDeg());
570   
571   double ewMSec = fgGetLowPass(_lastEWVelocity, eastWestM / dt, dt/2.0);
572   _lastEWVelocity = ewMSec;
573   _eastWestVelocity->setDoubleValue(ewMSec);
574   
575   double odometer = _odometer_node->getDoubleValue();
576   _odometer_node->setDoubleValue(odometer + distance_m * SG_METER_TO_NM);
577   odometer = _trip_odometer_node->getDoubleValue();
578   _trip_odometer_node->setDoubleValue(odometer + distance_m * SG_METER_TO_NM);
579   
580   if (!_dataValid) {
581     SG_LOG(SG_INSTR, SG_INFO, "GPS setting data valid");
582     _dataValid = true;
583   }
584 }
585
586 void
587 GPS::updateTrackingBug()
588 {
589   double tracking_bug = _tracking_bug_node->getDoubleValue();
590   double true_bug_error = tracking_bug - getTrueTrack();
591   double magnetic_bug_error = tracking_bug - getMagTrack();
592
593   // Get the errors into the (-180,180) range.
594   SG_NORMALIZE_RANGE(true_bug_error, -180.0, 180.0);
595   SG_NORMALIZE_RANGE(magnetic_bug_error, -180.0, 180.0);
596
597   _true_bug_error_node->setDoubleValue(true_bug_error);
598   _magnetic_bug_error_node->setDoubleValue(magnetic_bug_error);
599 }
600
601 void
602 GPS::updateWaypoints()
603 {  
604   double az2;
605   SGGeodesy::inverse(_indicated_pos, _wp1_position, _wp1TrueBearing, az2,_wp1DistanceM);
606 }
607
608 void GPS::updateReferenceNavaid(double dt)
609 {
610   if (!_ref_navaid_set) {
611     _ref_navaid_elapsed += dt;
612     if (_ref_navaid_elapsed > 5.0) {
613       _ref_navaid_elapsed = 0.0;
614
615       FGPositioned::TypeFilter vorFilter(FGPositioned::VOR);
616       FGPositionedRef nav = FGPositioned::findClosest(_indicated_pos, 400.0, &vorFilter);
617       if (!nav) {
618         SG_LOG(SG_INSTR, SG_INFO, "GPS couldn't find a reference navid");
619         _ref_navaid_id_node->setStringValue("");
620         _ref_navaid_name_node->setStringValue("");
621         _ref_navaid_bearing_node->setDoubleValue(0.0);
622         _ref_navaid_mag_bearing_node->setDoubleValue(0.0);
623         _ref_navaid_distance_node->setDoubleValue(0.0);
624         _ref_navaid_frequency_node->setStringValue("");
625       } else if (nav != _ref_navaid) {
626         SG_LOG(SG_INSTR, SG_INFO, "GPS code selected new ref-navaid:" << nav->ident());
627         _listener->setGuard(true);
628         _ref_navaid_id_node->setStringValue(nav->ident().c_str());
629         _ref_navaid_name_node->setStringValue(nav->name().c_str());
630         FGNavRecord* vor = (FGNavRecord*) nav.ptr();
631         _ref_navaid_frequency_node->setDoubleValue(vor->get_freq() / 100.0);
632         _listener->setGuard(false);
633       } else {
634         // SG_LOG(SG_INSTR, SG_ALERT, "matched existing");
635       }
636       
637       _ref_navaid = nav;
638     }
639   }
640   
641   if (_ref_navaid) {
642     double trueCourse, distanceM, az2;
643     SGGeodesy::inverse(_indicated_pos, _ref_navaid->geod(), trueCourse, az2, distanceM);
644     _ref_navaid_distance_node->setDoubleValue(distanceM * SG_METER_TO_NM);
645     _ref_navaid_bearing_node->setDoubleValue(trueCourse);
646     _ref_navaid_mag_bearing_node->setDoubleValue(trueCourse - _magvar_node->getDoubleValue());
647   }
648 }
649
650 void GPS::referenceNavaidSet(const std::string& aNavaid)
651 {
652   _ref_navaid = NULL;
653   // allow setting an empty string to restore normal nearest-vor selection
654   if (aNavaid.size() > 0) {
655     FGPositioned::TypeFilter vorFilter(FGPositioned::VOR);
656     _ref_navaid = FGPositioned::findClosestWithIdent(aNavaid, 
657       _position.get(), &vorFilter);
658     
659     if (!_ref_navaid) {
660       SG_LOG(SG_INSTR, SG_ALERT, "GPS: unknown ref navaid:" << aNavaid);
661     }
662   }
663
664   if (_ref_navaid) {
665     _ref_navaid_set = true;
666     SG_LOG(SG_INSTR, SG_INFO, "GPS code set explict ref-navaid:" << _ref_navaid->ident());
667     _ref_navaid_id_node->setStringValue(_ref_navaid->ident().c_str());
668     _ref_navaid_name_node->setStringValue(_ref_navaid->name().c_str());
669     FGNavRecord* vor = (FGNavRecord*) _ref_navaid.ptr();
670     _ref_navaid_frequency_node->setDoubleValue(vor->get_freq() / 100.0);
671   } else {
672     _ref_navaid_set = false;
673     _ref_navaid_elapsed = 9999.0; // update next tick
674   }
675 }
676
677 void GPS::routeActivated()
678 {
679   if (_route_active_node->getBoolValue()) {
680     SG_LOG(SG_INSTR, SG_INFO, "GPS::route activated, switching to LEG mode");
681     selectLegMode();
682     
683     // if we've already passed the current waypoint, sequence.
684     if (_dataValid && getWP1FromFlag()) {
685       SG_LOG(SG_INSTR, SG_INFO, "GPS::route activated, FROM wp1, sequencing");
686       _routeMgr->sequence();
687     }
688   } else if (_mode == "leg") {
689     SG_LOG(SG_INSTR, SG_INFO, "GPS::route deactivated, switching to OBS mode");
690     selectOBSMode();
691   }
692 }
693
694 void GPS::routeManagerSequenced()
695 {
696   if (_mode != "leg") {
697     SG_LOG(SG_INSTR, SG_INFO, "GPS ignoring route sequencing, not in LEG mode");
698     return;
699   }
700   
701   int index = _routeMgr->currentWaypoint(),
702     count = _routeMgr->size();
703   if ((index < 0) || (index >= count)) {
704     SG_LOG(SG_INSTR, SG_ALERT, "GPS: malformed route, index=" << index);
705     return;
706   }
707   
708   SG_LOG(SG_INSTR, SG_INFO, "GPS waypoint index is now " << index);
709   
710   if (index > 0) {
711     SGWayPoint wp0(_routeMgr->get_waypoint(index - 1));
712     _wp0Ident = wp0.get_id();
713     _wp0Name = wp0.get_name();
714     _wp0_position = wp0.get_target();
715
716   }
717   
718   SGWayPoint wp1(_routeMgr->get_waypoint(index));
719   _wp1Ident = wp1.get_id();
720   _wp1Name = wp1.get_name();
721   _wp1_position = wp1.get_target();
722
723   _desiredCourse = getLegMagCourse();
724   _desiredCourseNode->fireValueChanged();
725   wp1Changed();
726 }
727
728 void GPS::routeEdited()
729 {
730   if (_mode != "leg") {
731     return;
732   }
733   
734   SG_LOG(SG_INSTR, SG_INFO, "GPS route edited while in LEG mode, updating waypoints");
735   routeManagerSequenced();
736 }
737
738 void GPS::routeFinished()
739 {
740   if (_mode != "leg") {
741     return;
742   }
743   
744   SG_LOG(SG_INSTR, SG_INFO, "GPS route finished, reverting to OBS");
745   _mode = "obs";
746   _wp0_position = _indicated_pos;
747   wp1Changed();
748 }
749
750 void GPS::updateTurn()
751 {
752   bool printProgress = false;
753   
754   if (_computeTurnData) {
755     if (_last_speed_kts < 60) {
756       // need valid leg course and sensible ground speed to compute the turn
757       return;
758     }
759     
760     computeTurnData();
761     printProgress = true;
762   }
763   
764   if (!_anticipateTurn) {
765     updateOverflight();
766     return;
767   }
768
769   updateTurnData();
770   // find bearing to turn centre
771   double bearing, az2, distanceM;
772   SGGeodesy::inverse(_indicated_pos, _turnCentre, bearing, az2, distanceM);
773   double progress = computeTurnProgress(bearing);
774   
775   if (printProgress) {
776     SG_LOG(SG_INSTR, SG_INFO,"turn progress=" << progress);
777   }
778   
779   if (!_inTurn && (progress > 0.0)) {
780     beginTurn();
781   }
782   
783   if (_inTurn && !_turnSequenced && (progress > 0.5)) {
784     _turnSequenced = true;
785      SG_LOG(SG_INSTR, SG_INFO, "turn passed midpoint, sequencing");
786      _routeMgr->sequence();
787   }
788   
789   if (_inTurn && (progress >= 1.0)) {
790     endTurn();
791   }
792   
793   if (_inTurn) {
794     // drive deviation and desired course
795     double desiredCourse = bearing - copysign(90, _turnAngle);
796     SG_NORMALIZE_RANGE(desiredCourse, 0.0, 360.0);
797     double deviationNm = (distanceM * SG_METER_TO_NM) - _turnRadius;
798     double deviationDeg = desiredCourse - getMagTrack();
799     deviationNm = copysign(deviationNm, deviationDeg);
800     // FXIME
801     //_wp1_course_deviation_node->setDoubleValue(deviationDeg);
802     //_wp1_course_error_nm_node->setDoubleValue(deviationNm);
803     //_cdiDeflectionNode->setDoubleValue(deviationDeg);
804   }
805 }
806
807 void GPS::updateOverflight()
808 {
809   if ((_wp1DistanceM * SG_METER_TO_NM) > _config.overflightArmDistanceNm()) {
810     return;
811   }
812   
813   if (getWP1ToFlag()) {
814     return; // still heading towards the WP
815   }
816   
817   if (_mode == "dto") {
818     SG_LOG(SG_INSTR, SG_INFO, "GPS DTO reached destination point");
819     
820     // check for wp1 being on active route - resume leg mode
821     if (_routeMgr->isRouteActive()) {
822       int index = _routeMgr->findWaypoint(_wp1_position);
823       if (index >= 0) {
824         SG_LOG(SG_INSTR, SG_INFO, "GPS DTO, resuming LEG mode at wp:" << index);
825         _mode = "leg";
826         _routeMgr->jumpToIndex(index);
827       }
828     }
829   } else if (_mode == "leg") {
830     SG_LOG(SG_INSTR, SG_INFO, "GPS doing overflight sequencing");
831     _routeMgr->sequence();
832   } else if (_mode == "obs") {
833     // nothing to do here, TO/FROM will update but that's fine
834   }
835   
836   _computeTurnData = true;
837 }
838
839 void GPS::beginTurn()
840 {
841   _inTurn = true;
842   _turnSequenced = false;
843   SG_LOG(SG_INSTR, SG_INFO, "begining turn");
844 }
845
846 void GPS::endTurn()
847 {
848   _inTurn = false;
849   SG_LOG(SG_INSTR, SG_INFO, "ending turn");
850   _computeTurnData = true;
851 }
852
853 double GPS::computeTurnProgress(double aBearing) const
854 {
855   double startBearing = _turnStartBearing + copysign(90, _turnAngle);
856   return (aBearing - startBearing) / _turnAngle;
857 }
858
859 void GPS::computeTurnData()
860 {
861   _computeTurnData = false;
862   if (_mode != "leg") { // and approach modes in the future
863     _anticipateTurn = false;
864     return;
865   }
866   
867   int curIndex = _routeMgr->currentWaypoint();
868   if ((curIndex + 1) >= _routeMgr->size()) {
869     _anticipateTurn = false;
870     return;
871   }
872   
873   if (!_config.turnAnticipationEnabled()) {
874     _anticipateTurn = false;
875     return;
876   }
877   
878   _turnStartBearing = _desiredCourse;
879 // compute next leg course
880   SGWayPoint wp1(_routeMgr->get_waypoint(curIndex)),
881     wp2(_routeMgr->get_waypoint(curIndex + 1));
882   double crs, dist;
883   wp2.CourseAndDistance(wp1, &crs, &dist);
884   
885
886 // compute offset bearing
887   _turnAngle = crs - _turnStartBearing;
888   SG_NORMALIZE_RANGE(_turnAngle, -180.0, 180.0);
889   double median = _turnStartBearing + (_turnAngle * 0.5);
890   double offsetBearing = median + copysign(90, _turnAngle);
891   SG_NORMALIZE_RANGE(offsetBearing, 0.0, 360.0);
892   
893   SG_LOG(SG_INSTR, SG_INFO, "GPS computeTurnData: in=" << _turnStartBearing <<
894     ", out=" << crs << "; turnAngle=" << _turnAngle << ", median=" << median 
895     << ", offset=" << offsetBearing);
896
897   SG_LOG(SG_INSTR, SG_INFO, "next leg is now:" << wp1.get_id() << "->" << wp2.get_id());
898
899   _turnPt = _wp1_position;
900   _anticipateTurn = true;
901 }
902
903 void GPS::updateTurnData()
904 {
905   // depends on ground speed, so needs to be updated per-frame
906   _turnRadius = computeTurnRadiusNm(_last_speed_kts);
907   
908   // compute the turn centre, based on the turn radius.
909   // key thing is to understand that we're working a right-angle triangle,
910   // where the right-angle is the point we start the turn. From that point,
911   // one side is the inbound course to the turn pt, and the other is the
912   // perpendicular line, of length 'r', to the turn centre.
913   // the triangle's hypotenuse, which we need to find, is the distance from the
914   // turn pt to the turn center (in the direction of the offset bearing)
915   // note that d - _turnRadius tell us how much we're 'cutting' the corner.
916   
917   double halfTurnAngle = fabs(_turnAngle * 0.5) * SG_DEGREES_TO_RADIANS;
918   double d = _turnRadius / cos(halfTurnAngle);
919   
920  // SG_LOG(SG_INSTR, SG_INFO, "turnRadius=" << _turnRadius << ", d=" << d
921  //   << " (cut distance=" << d - _turnRadius << ")");
922   
923   double median = _turnStartBearing + (_turnAngle * 0.5);
924   double offsetBearing = median + copysign(90, _turnAngle);
925   SG_NORMALIZE_RANGE(offsetBearing, 0.0, 360.0);
926   
927   double az2;
928   SGGeodesy::direct(_turnPt, offsetBearing, d * SG_NM_TO_METER, _turnCentre, az2); 
929 }
930
931 double GPS::computeTurnRadiusNm(double aGroundSpeedKts) const
932 {
933         // turn time is seconds to execute a 360 turn. 
934   double turnTime = 360.0 / _config.turnRateDegSec();
935   
936   // c is ground distance covered in that time (circumference of the circle)
937         double c = turnTime * (aGroundSpeedKts / 3600.0); // convert knts to nm/sec
938   
939   // divide by 2PI to go from circumference -> radius
940         return c / (2 * M_PI);
941 }
942
943 void GPS::updateRouteData()
944 {
945   double totalDistance = _wp1DistanceM * SG_METER_TO_NM;
946   // walk all waypoints from wp2 to route end, and sum
947   for (int i=_routeMgr->currentWaypoint()+1; i<_routeMgr->size(); ++i) {
948     totalDistance += _routeMgr->get_waypoint(i).get_distance();
949   }
950   
951   _routeDistanceNm->setDoubleValue(totalDistance * SG_METER_TO_NM);
952   if (_last_speed_kts > 1.0) {
953     double TTW = ((totalDistance * SG_METER_TO_NM) / _last_speed_kts) * 3600.0;
954     _routeETE->setStringValue(makeTTWString(TTW));    
955   }
956 }
957
958 void GPS::driveAutopilot()
959 {
960   if (!_config.driveAutopilot() || !_realismSimpleGps->getBoolValue()) {
961     return;
962   }
963  
964   // compatability feature - allow the route-manager / GPS to drive the
965   // generic autopilot heading hold *in leg mode only* 
966   if (_mode == "leg") {
967     // FIXME: we want to set desired track, not heading, here
968     _apTrueHeading->setDoubleValue(getWP1Bearing());
969   }
970 }
971
972 void GPS::wp1Changed()
973 {
974   if (!_config.driveAutopilot()) {
975     return;
976   }
977   
978   double altFt = _wp1_position.getElevationFt();
979   if (altFt > -9990.0) {
980     _apTargetAltitudeFt->setDoubleValue(altFt);
981   }
982 }
983
984 /////////////////////////////////////////////////////////////////////////////
985 // property getter/setters
986
987 void GPS::setSelectedCourse(double crs)
988 {
989   if (_selectedCourse == crs) {
990     return;
991   }
992   
993   _selectedCourse = crs;
994   if ((_mode == "obs") || _config.courseSelectable()) {
995     _desiredCourse = _selectedCourse;
996     _desiredCourseNode->fireValueChanged();
997   }
998 }
999
1000 double GPS::getLegDistance() const
1001 {
1002   if (!_dataValid || (_mode == "obs")) {
1003     return -1;
1004   }
1005   
1006   return SGGeodesy::distanceNm(_wp0_position, _wp1_position);
1007 }
1008
1009 double GPS::getLegCourse() const
1010 {
1011   if (!_dataValid) {
1012     return -9999.0;
1013   }
1014   
1015   return SGGeodesy::courseDeg(_wp0_position, _wp1_position);
1016 }
1017
1018 double GPS::getLegMagCourse() const
1019 {
1020   if (!_dataValid) {
1021     return 0.0;
1022   }
1023   
1024   double m = getLegCourse() - _magvar_node->getDoubleValue();
1025   SG_NORMALIZE_RANGE(m, 0.0, 360.0);
1026   return m;
1027 }
1028
1029 double GPS::getAltDistanceRatio() const
1030 {
1031   if (!_dataValid || (_mode == "obs")) {
1032     return 0.0;
1033   }
1034   
1035   double dist = SGGeodesy::distanceM(_wp0_position, _wp1_position);
1036   if ( dist <= 0.0 ) {
1037     return 0.0;
1038   }
1039   
1040   double alt_difference_m = _wp0_position.getElevationM() - _wp1_position.getElevationM();
1041   return alt_difference_m / dist;
1042 }
1043
1044 double GPS::getMagTrack() const
1045 {
1046   if (!_dataValid) {
1047     return 0.0;
1048   }
1049   
1050   double m = getTrueTrack() - _magvar_node->getDoubleValue();
1051   SG_NORMALIZE_RANGE(m, 0.0, 360.0);
1052   return m;
1053 }
1054
1055 double GPS::getCDIDeflection() const
1056 {
1057   if (!_dataValid) {
1058     return 0.0;
1059   }
1060   
1061   double defl;
1062   if (_config.cdiDeflectionIsAngular()) {
1063     defl = getWP1CourseDeviation();
1064     SG_CLAMP_RANGE(defl, -10.0, 10.0); // as in navradio.cxx
1065   } else {
1066     double fullScale = _config.cdiDeflectionLinearPeg();
1067     double normError = getWP1CourseErrorNm() / fullScale;
1068     SG_CLAMP_RANGE(normError, -1.0, 1.0);
1069     defl = normError * 10.0; // re-scale to navradio limits, i.e [-10.0 .. 10.0]
1070   }
1071   
1072   return defl;
1073 }
1074
1075 const char* GPS::getWP0Ident() const
1076 {
1077   if (!_dataValid || (_mode != "leg")) {
1078     return "";
1079   }
1080   
1081   return _wp0Ident.c_str();
1082 }
1083
1084 const char* GPS::getWP0Name() const
1085 {
1086   if (!_dataValid || (_mode != "leg")) {
1087     return "";
1088   }
1089   
1090   return _wp0Name.c_str();
1091 }
1092
1093 const char* GPS::getWP1Ident() const
1094 {
1095   if (!_dataValid) {
1096     return "";
1097   }
1098   
1099   return _wp1Ident.c_str();
1100 }
1101
1102 const char* GPS::getWP1Name() const
1103 {
1104   if (!_dataValid) {
1105     return "";
1106   }
1107
1108   return _wp1Name.c_str();
1109 }
1110
1111 double GPS::getWP1Distance() const
1112 {
1113   if (!_dataValid) {
1114     return -1.0;
1115   }
1116   
1117   return _wp1DistanceM * SG_METER_TO_NM;
1118 }
1119
1120 double GPS::getWP1TTW() const
1121 {
1122   if (!_dataValid) {
1123     return -1.0;
1124   }
1125   
1126   if (_last_speed_kts < 1.0) {
1127     return -1.0;
1128   }
1129   
1130   return (getWP1Distance() / _last_speed_kts) * 3600.0;
1131 }
1132
1133 const char* GPS::getWP1TTWString() const
1134 {
1135   if (!_dataValid) {
1136     return "";
1137   }
1138   
1139   return makeTTWString(getWP1TTW());
1140 }
1141
1142 double GPS::getWP1Bearing() const
1143 {
1144   if (!_dataValid) {
1145     return -9999.0;
1146   }
1147   
1148   return _wp1TrueBearing;
1149 }
1150
1151 double GPS::getWP1MagBearing() const
1152 {
1153   if (!_dataValid) {
1154     return -9999.0;
1155   }
1156
1157   double magBearing = _wp1TrueBearing - _magvar_node->getDoubleValue();
1158   SG_NORMALIZE_RANGE(magBearing, 0.0, 360.0);
1159   return magBearing;
1160 }
1161
1162 double GPS::getWP1CourseDeviation() const
1163 {
1164   if (!_dataValid) {
1165     return 0.0;
1166   }
1167   
1168   double dev = getWP1MagBearing() - _desiredCourse;
1169   SG_NORMALIZE_RANGE(dev, -180.0, 180.0);
1170   
1171   if (fabs(dev) > 90.0) {
1172     // When the course is away from the waypoint, 
1173     // it makes sense to change the sign of the deviation.
1174     dev *= -1.0;
1175     SG_NORMALIZE_RANGE(dev, -90.0, 90.0);
1176   }
1177   
1178   return dev;
1179 }
1180
1181 double GPS::getWP1CourseErrorNm() const
1182 {
1183   if (!_dataValid) {
1184     return 0.0;
1185   }
1186   
1187   double radDev = getWP1CourseDeviation() * SG_DEGREES_TO_RADIANS;
1188   double course_error_m = sin(radDev) * _wp1DistanceM;
1189   return course_error_m * SG_METER_TO_NM;
1190 }
1191
1192 bool GPS::getWP1ToFlag() const
1193 {
1194   if (!_dataValid) {
1195     return false;
1196   }
1197   
1198   double dev = getWP1MagBearing() - _desiredCourse;
1199   SG_NORMALIZE_RANGE(dev, -180.0, 180.0);
1200
1201   return (fabs(dev) < 90.0);
1202 }
1203
1204 bool GPS::getWP1FromFlag() const
1205 {
1206   if (!_dataValid) {
1207     return false;
1208   }
1209   
1210   return !getWP1ToFlag();
1211 }
1212
1213 double GPS::getScratchDistance() const
1214 {
1215   if (!_scratchValid) {
1216     return 0.0;
1217   }
1218   
1219   return SGGeodesy::distanceNm(_indicated_pos, _scratchPos);
1220 }
1221
1222 double GPS::getScratchTrueBearing() const
1223 {
1224   if (!_scratchValid) {
1225     return 0.0;
1226   }
1227
1228   return SGGeodesy::courseDeg(_indicated_pos, _scratchPos);
1229 }
1230
1231 double GPS::getScratchMagBearing() const
1232 {
1233   if (!_scratchValid) {
1234     return 0.0;
1235   }
1236   
1237   double crs = getScratchTrueBearing() - _magvar_node->getDoubleValue();
1238   SG_NORMALIZE_RANGE(crs, 0.0, 360.0);
1239   return crs;
1240 }
1241
1242 /////////////////////////////////////////////////////////////////////////////
1243 // command / scratch / search system
1244
1245 void GPS::setCommand(const char* aCmd)
1246 {
1247   SG_LOG(SG_INSTR, SG_INFO, "GPS command:" << aCmd);
1248   
1249   if (!strcmp(aCmd, "direct")) {
1250     directTo();
1251   } else if (!strcmp(aCmd, "obs")) {
1252     selectOBSMode();
1253   } else if (!strcmp(aCmd, "leg")) {
1254     selectLegMode();
1255   } else if (!strcmp(aCmd, "load-route-wpt")) {
1256     loadRouteWaypoint();
1257   } else if (!strcmp(aCmd, "nearest")) {
1258     loadNearest();
1259   } else if (!strcmp(aCmd, "search")) {
1260     _searchNames = false;
1261     search();
1262   } else if (!strcmp(aCmd, "search-names")) {
1263     _searchNames = true;
1264     search();
1265   } else if (!strcmp(aCmd, "next")) {
1266     nextResult();
1267   } else if (!strcmp(aCmd, "previous")) {
1268     previousResult();
1269   } else if (!strcmp(aCmd, "define-user-wpt")) {
1270     defineWaypoint();
1271   } else if (!strcmp(aCmd, "route-insert-before")) {
1272     int index = _scratchNode->getIntValue("index");
1273     if (index < 0 || (_routeMgr->size() == 0)) {
1274       index = _routeMgr->size();
1275     } else if (index >= _routeMgr->size()) {
1276       SG_LOG(SG_INSTR, SG_WARN, "GPS:route-insert-before, bad index:" << index);
1277       return;
1278     }
1279     
1280     insertWaypointAtIndex(index);
1281   } else if (!strcmp(aCmd, "route-insert-after")) {
1282     int index = _scratchNode->getIntValue("index");
1283     if (index < 0 || (_routeMgr->size() == 0)) {
1284       index = _routeMgr->size();
1285     } else if (index >= _routeMgr->size()) {
1286       SG_LOG(SG_INSTR, SG_WARN, "GPS:route-insert-after, bad index:" << index);
1287       return;
1288     } else {
1289       ++index; 
1290     }
1291   
1292     insertWaypointAtIndex(index);
1293   } else if (!strcmp(aCmd, "route-delete")) {
1294     int index = _scratchNode->getIntValue("index");
1295     if (index < 0) {
1296       index = _routeMgr->size();
1297     } else if (index >= _routeMgr->size()) {
1298       SG_LOG(SG_INSTR, SG_WARN, "GPS:route-delete, bad index:" << index);
1299       return;
1300     }
1301     
1302     removeWaypointAtIndex(index);
1303   } else {
1304     SG_LOG(SG_INSTR, SG_WARN, "GPS:unrecognized command:" << aCmd);
1305   }
1306 }
1307
1308 void GPS::clearScratch()
1309 {
1310   _scratchPos = SGGeod::fromDegFt(-9999.0, -9999.0, -9999.0);
1311   _scratchValid = false;  
1312   _scratchNode->setStringValue("type", "");
1313   _scratchNode->setStringValue("query", "");
1314 }
1315
1316 bool GPS::isScratchPositionValid() const
1317 {
1318   if ((_scratchPos.getLongitudeDeg() < -9990.0) ||
1319       (_scratchPos.getLatitudeDeg() < -9990.0)) {
1320    return false;   
1321   }
1322   
1323   return true;
1324 }
1325
1326 void GPS::directTo()
1327 {
1328   _wp0_position = _indicated_pos;
1329   
1330   if (isScratchPositionValid()) {
1331     _wp1Ident = _scratchNode->getStringValue("ident");
1332     _wp1Name = _scratchNode->getStringValue("name");
1333     _wp1_position = _scratchPos;
1334   }
1335   
1336   _mode = "dto";
1337   _desiredCourse = getLegMagCourse();
1338   _desiredCourseNode->fireValueChanged();
1339   clearScratch();
1340   wp1Changed();
1341 }
1342
1343 void GPS::loadRouteWaypoint()
1344 {
1345   _scratchValid = false;
1346 //  if (!_routeMgr->isRouteActive()) {
1347 //    SG_LOG(SG_INSTR, SG_WARN, "GPS:loadWaypoint: no active route");
1348 //    return;
1349 //  }
1350   
1351   int index = _scratchNode->getIntValue("index", -9999);
1352   clearScratch();
1353   
1354   if ((index < 0) || (index >= _routeMgr->size())) { // no index supplied, use current wp
1355     index = _routeMgr->currentWaypoint();
1356   }
1357   
1358   _searchIsRoute = true;
1359   setScratchFromRouteWaypoint(index);
1360 }
1361
1362 void GPS::setScratchFromRouteWaypoint(int aIndex)
1363 {
1364   assert(_searchIsRoute);
1365   if ((aIndex < 0) || (aIndex >= _routeMgr->size())) {
1366     SG_LOG(SG_INSTR, SG_WARN, "GPS:setScratchFromRouteWaypoint: route-index out of bounds");
1367     return;
1368   }
1369   
1370   _searchResultIndex = aIndex;
1371   SGWayPoint wp(_routeMgr->get_waypoint(aIndex));
1372   _scratchNode->setStringValue("name", wp.get_name());
1373   _scratchNode->setStringValue("ident", wp.get_id());
1374   _scratchPos = wp.get_target();
1375   _scratchValid = true;
1376   _scratchNode->setDoubleValue("course", wp.get_track());
1377   _scratchNode->setIntValue("index", aIndex);
1378   
1379   int lastResult = _routeMgr->size() - 1;
1380   _searchHasNext = (_searchResultIndex < lastResult);
1381 }
1382
1383 void GPS::loadNearest()
1384 {
1385   string sty(_scratchNode->getStringValue("type"));
1386   FGPositioned::Type ty = FGPositioned::typeFromName(sty);
1387   if (ty == FGPositioned::INVALID) {
1388     SG_LOG(SG_INSTR, SG_WARN, "GPS:loadNearest: request type is invalid:" << sty);
1389     return;
1390   }
1391   
1392   auto_ptr<FGPositioned::Filter> f(createFilter(ty));
1393   int limitCount = _scratchNode->getIntValue("max-results", 1);
1394   double cutoffDistance = _scratchNode->getDoubleValue("cutoff-nm", 400.0);
1395   
1396   SGGeod searchPos = _indicated_pos;
1397   if (isScratchPositionValid()) {
1398     searchPos = _scratchPos;
1399   }
1400   
1401   clearScratch(); // clear now, regardless of whether we find a match or not
1402     
1403   _searchResults = 
1404     FGPositioned::findClosestN(searchPos, limitCount, cutoffDistance, f.get());
1405   _searchResultsCached = true;
1406   _searchResultIndex = 0;
1407   _searchIsRoute = false;
1408   _searchHasNext = false;
1409   
1410   if (_searchResults.empty()) {
1411     SG_LOG(SG_INSTR, SG_INFO, "GPS:loadNearest: no matches at all");
1412     return;
1413   }
1414   
1415   _searchHasNext = (_searchResults.size() > 1);
1416   setScratchFromCachedSearchResult();
1417 }
1418
1419 bool GPS::SearchFilter::pass(FGPositioned* aPos) const
1420 {
1421   switch (aPos->type()) {
1422   case FGPositioned::AIRPORT:
1423   // heliport and seaport too?
1424   case FGPositioned::VOR:
1425   case FGPositioned::NDB:
1426   case FGPositioned::FIX:
1427   case FGPositioned::TACAN:
1428   case FGPositioned::WAYPOINT:
1429     return true;
1430   default:
1431     return false;
1432   }
1433 }
1434
1435 FGPositioned::Type GPS::SearchFilter::minType() const
1436 {
1437   return FGPositioned::AIRPORT;
1438 }
1439
1440 FGPositioned::Type GPS::SearchFilter::maxType() const
1441 {
1442   return FGPositioned::WAYPOINT;
1443 }
1444
1445 FGPositioned::Filter* GPS::createFilter(FGPositioned::Type aTy)
1446 {
1447   if (aTy == FGPositioned::AIRPORT) {
1448     return new FGAirport::HardSurfaceFilter(_config.minRunwayLengthFt());
1449   }
1450   
1451   // if we were passed INVALID, assume it means 'all types interesting to a GPS'
1452   if (aTy == FGPositioned::INVALID) {
1453     return new SearchFilter;
1454   }
1455   
1456   return new FGPositioned::TypeFilter(aTy);
1457 }
1458
1459 void GPS::search()
1460 {
1461   // parse search terms into local members, and exec the first search
1462   string sty(_scratchNode->getStringValue("type"));
1463   _searchType = FGPositioned::typeFromName(sty);
1464   _searchQuery = _scratchNode->getStringValue("query");
1465   if (_searchQuery.empty()) {
1466     SG_LOG(SG_INSTR, SG_WARN, "empty GPS search query");
1467     clearScratch();
1468     return;
1469   }
1470   
1471   _searchExact = _scratchNode->getBoolValue("exact", true);
1472   _searchOrderByRange = _scratchNode->getBoolValue("order-by-distance", true);
1473   _searchResultIndex = 0;
1474   _searchIsRoute = false;
1475   _searchHasNext = false;
1476   
1477   if (_searchExact && _searchOrderByRange) {
1478     // immediate mode search, get all the results now and cache them
1479     auto_ptr<FGPositioned::Filter> f(createFilter(_searchType));
1480     if (_searchNames) {
1481       _searchResults = FGPositioned::findAllWithNameSortedByRange(_searchQuery, _indicated_pos, f.get());
1482     } else {
1483       _searchResults = FGPositioned::findAllWithIdentSortedByRange(_searchQuery, _indicated_pos, f.get());
1484     }
1485     
1486     _searchResultsCached = true;
1487     
1488     if (_searchResults.empty()) {
1489       clearScratch();
1490       return;
1491     }
1492     
1493     _searchHasNext = (_searchResults.size() > 1);
1494     setScratchFromCachedSearchResult();
1495   } else {
1496     // iterative search, look up result zero
1497     _searchResultsCached = false;
1498     performSearch();
1499   }
1500 }
1501
1502 void GPS::performSearch()
1503 {
1504   auto_ptr<FGPositioned::Filter> f(createFilter(_searchType));
1505   clearScratch();
1506   
1507   FGPositionedRef r;
1508   if (_searchNames) {
1509     if (_searchOrderByRange) {
1510       r = FGPositioned::findClosestWithPartialName(_indicated_pos, _searchQuery, f.get(), _searchResultIndex, _searchHasNext);
1511     } else {
1512       r = FGPositioned::findWithPartialName(_searchQuery, f.get(), _searchResultIndex, _searchHasNext);
1513     }
1514   } else {
1515     if (_searchOrderByRange) {
1516       r = FGPositioned::findClosestWithPartialId(_indicated_pos, _searchQuery, f.get(), _searchResultIndex, _searchHasNext);
1517     } else {
1518       r = FGPositioned::findWithPartialId(_searchQuery, f.get(), _searchResultIndex, _searchHasNext);
1519     }
1520   }
1521   
1522   if (!r) {
1523     return;
1524   }
1525   
1526   setScratchFromPositioned(r.get(), _searchResultIndex);
1527 }
1528
1529 void GPS::setScratchFromCachedSearchResult()
1530 {
1531   assert(_searchResultsCached);
1532   int index = _searchResultIndex;
1533   
1534   if ((index < 0) || (index >= (int) _searchResults.size())) {
1535     SG_LOG(SG_INSTR, SG_WARN, "GPS:setScratchFromCachedSearchResult: index out of bounds:" << index);
1536     return;
1537   }
1538   
1539   setScratchFromPositioned(_searchResults[index], index);
1540   
1541   int lastResult = (int) _searchResults.size() - 1;
1542   _searchHasNext = (_searchResultIndex < lastResult);
1543 }
1544
1545 void GPS::setScratchFromPositioned(FGPositioned* aPos, int aIndex)
1546 {
1547   clearScratch();
1548   assert(aPos);
1549
1550   _scratchPos = aPos->geod();
1551   _scratchNode->setStringValue("name", aPos->name());
1552   _scratchNode->setStringValue("ident", aPos->ident());
1553   _scratchNode->setStringValue("type", FGPositioned::nameForType(aPos->type()));
1554     
1555   if (aIndex >= 0) {
1556     _scratchNode->setIntValue("index", aIndex);
1557   }
1558   
1559   _scratchValid = true;
1560   if (_searchResultsCached) {
1561     _scratchNode->setIntValue("result-count", _searchResults.size());
1562   }
1563   
1564   switch (aPos->type()) {
1565   case FGPositioned::VOR:
1566     _scratchNode->setDoubleValue("frequency-mhz", static_cast<FGNavRecord*>(aPos)->get_freq() / 100.0);
1567     break;
1568   
1569   case FGPositioned::NDB:
1570     _scratchNode->setDoubleValue("frequency-khz", static_cast<FGNavRecord*>(aPos)->get_freq() / 100.0);
1571     break;
1572   
1573   case FGPositioned::AIRPORT:
1574     addAirportToScratch((FGAirport*)aPos);
1575     break;
1576   
1577   default:
1578       // no-op
1579       break;
1580   }
1581   
1582   // look for being on the route and set?
1583 }
1584
1585 void GPS::addAirportToScratch(FGAirport* aAirport)
1586 {
1587   for (unsigned int r=0; r<aAirport->numRunways(); ++r) {
1588     SGPropertyNode* rwyNd = _scratchNode->getChild("runways", r, true);
1589     FGRunway* rwy = aAirport->getRunwayByIndex(r);
1590     // TODO - filter out unsuitable runways in the future
1591     // based on config again
1592     
1593     rwyNd->setStringValue("id", rwy->ident().c_str());
1594     rwyNd->setIntValue("length-ft", rwy->lengthFt());
1595     rwyNd->setIntValue("width-ft", rwy->widthFt());
1596     rwyNd->setIntValue("heading-deg", rwy->headingDeg());
1597     // map surface code to a string
1598     // TODO - lighting information
1599     
1600     if (rwy->ILS()) {
1601       rwyNd->setDoubleValue("ils-frequency-mhz", rwy->ILS()->get_freq() / 100.0);
1602     }
1603   } // of runways iteration
1604 }
1605
1606
1607 void GPS::selectOBSMode()
1608 {
1609   if (isScratchPositionValid()) {
1610     _wp1Ident = _scratchNode->getStringValue("ident");
1611     _wp1Name = _scratchNode->getStringValue("name");
1612     _wp1_position = _scratchPos;
1613   }
1614   
1615   SG_LOG(SG_INSTR, SG_INFO, "GPS switching to OBS mode");
1616   _mode = "obs";
1617   _wp0_position = _indicated_pos;
1618   wp1Changed();
1619 }
1620
1621 void GPS::selectLegMode()
1622 {
1623   if (_mode == "leg") {
1624     return;
1625   }
1626   
1627   if (!_routeMgr->isRouteActive()) {
1628     SG_LOG(SG_INSTR, SG_WARN, "GPS:selectLegMode: no active route");
1629     return;
1630   }
1631
1632   SG_LOG(SG_INSTR, SG_INFO, "GPS switching to LEG mode");
1633   _mode = "leg";
1634   
1635   // depending on the situation, this will either get over-written 
1636   // in routeManagerSequenced or not; either way it does no harm to
1637   // set it here.
1638   _wp0_position = _indicated_pos;
1639
1640   // not really sequenced, but does all the work of updating wp0/1
1641   routeManagerSequenced();
1642 }
1643
1644 void GPS::nextResult()
1645 {
1646   if (!_searchHasNext) {
1647     return;
1648   }
1649   
1650   clearScratch();
1651   if (_searchIsRoute) {
1652     setScratchFromRouteWaypoint(++_searchResultIndex);
1653   } else if (_searchResultsCached) {
1654     ++_searchResultIndex;
1655     setScratchFromCachedSearchResult();
1656   } else {
1657     ++_searchResultIndex;
1658     performSearch();
1659   } // of iterative search case
1660 }
1661
1662 void GPS::previousResult()
1663 {
1664   if (_searchResultIndex <= 0) {
1665     return;
1666   }
1667   
1668   clearScratch();
1669   --_searchResultIndex;
1670   
1671   if (_searchIsRoute) {
1672     setScratchFromRouteWaypoint(_searchResultIndex);
1673   } else if (_searchResultsCached) {
1674     setScratchFromCachedSearchResult();
1675   } else {
1676     performSearch();
1677   }
1678 }
1679
1680 void GPS::defineWaypoint()
1681 {
1682   if (!isScratchPositionValid()) {
1683     SG_LOG(SG_INSTR, SG_WARN, "GPS:defineWaypoint: invalid lat/lon");
1684     return;
1685   }
1686   
1687   string ident = _scratchNode->getStringValue("ident");
1688   if (ident.size() < 2) {
1689     SG_LOG(SG_INSTR, SG_WARN, "GPS:defineWaypoint: waypoint identifier must be at least two characters");
1690     return;
1691   }
1692     
1693 // check for duplicate idents
1694   FGPositioned::TypeFilter f(FGPositioned::WAYPOINT);
1695   FGPositioned::List dups = FGPositioned::findAllWithIdentSortedByRange(ident, _indicated_pos, &f);
1696   if (!dups.empty()) {
1697     SG_LOG(SG_INSTR, SG_WARN, "GPS:defineWaypoint: non-unique waypoint identifier, ho-hum");
1698   }
1699   
1700   SG_LOG(SG_INSTR, SG_INFO, "GPS:defineWaypoint: creating waypoint:" << ident);
1701   FGPositionedRef wpt = FGPositioned::createUserWaypoint(ident, _scratchPos);
1702   _searchResultsCached = false;
1703   setScratchFromPositioned(wpt.get(), -1);
1704 }
1705
1706 void GPS::insertWaypointAtIndex(int aIndex)
1707 {
1708   // note we do allow index = routeMgr->size(), that's an append
1709   if ((aIndex < 0) || (aIndex > _routeMgr->size())) {
1710     throw sg_range_exception("GPS::insertWaypointAtIndex: index out of bounds");
1711   }
1712   
1713   if (!isScratchPositionValid()) {
1714     SG_LOG(SG_INSTR, SG_WARN, "GPS:insertWaypointAtIndex: invalid lat/lon");
1715     return;
1716   }
1717   
1718   string ident = _scratchNode->getStringValue("ident");
1719   string name = _scratchNode->getStringValue("name");
1720   
1721   _routeMgr->add_waypoint(SGWayPoint(_scratchPos, ident, name), aIndex);
1722 }
1723
1724 void GPS::removeWaypointAtIndex(int aIndex)
1725 {
1726   if ((aIndex < 0) || (aIndex >= _routeMgr->size())) {
1727     throw sg_range_exception("GPS::removeWaypointAtIndex: index out of bounds");
1728   }
1729   
1730   _routeMgr->pop_waypoint(aIndex);
1731 }
1732
1733 void GPS::tieSGGeod(SGPropertyNode* aNode, SGGeod& aRef, 
1734   const char* lonStr, const char* latStr, const char* altStr)
1735 {
1736   tie(aNode, lonStr, SGRawValueMethods<SGGeod, double>(aRef, &SGGeod::getLongitudeDeg, &SGGeod::setLongitudeDeg));
1737   tie(aNode, latStr, SGRawValueMethods<SGGeod, double>(aRef, &SGGeod::getLatitudeDeg, &SGGeod::setLatitudeDeg));
1738   
1739   if (altStr) {
1740     tie(aNode, altStr, SGRawValueMethods<SGGeod, double>(aRef, &SGGeod::getElevationFt, &SGGeod::setElevationFt));
1741   }
1742 }
1743
1744 void GPS::tieSGGeodReadOnly(SGPropertyNode* aNode, SGGeod& aRef, 
1745   const char* lonStr, const char* latStr, const char* altStr)
1746 {
1747   tie(aNode, lonStr, SGRawValueMethods<SGGeod, double>(aRef, &SGGeod::getLongitudeDeg, NULL));
1748   tie(aNode, latStr, SGRawValueMethods<SGGeod, double>(aRef, &SGGeod::getLatitudeDeg, NULL));
1749   
1750   if (altStr) {
1751     tie(aNode, altStr, SGRawValueMethods<SGGeod, double>(aRef, &SGGeod::getElevationFt, NULL));
1752   }
1753 }
1754
1755 // end of gps.cxx