]> git.mxchange.org Git - flightgear.git/blob - src/Instrumentation/navradio.cxx
GPS data validity clean-up; it was a mess, now it's more robust. Thanks to Dave Luff...
[flightgear.git] / src / Instrumentation / navradio.cxx
1 // navradio.cxx -- class to manage a nav radio instance
2 //
3 // Written by Curtis Olson, started April 2000.
4 //
5 // Copyright (C) 2000 - 2002  Curtis L. Olson - http://www.flightgear.org/~curt
6 //
7 // This program is free software; you can redistribute it and/or
8 // modify it under the terms of the GNU General Public License as
9 // published by the Free Software Foundation; either version 2 of the
10 // License, or (at your option) any later version.
11 //
12 // This program is distributed in the hope that it will be useful, but
13 // WITHOUT ANY WARRANTY; without even the implied warranty of
14 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15 // General Public License for more details.
16 //
17 // You should have received a copy of the GNU General Public License
18 // along with this program; if not, write to the Free Software
19 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
20 //
21 // $Id$
22
23
24 #ifdef HAVE_CONFIG_H
25 #  include <config.h>
26 #endif
27
28 #include "navradio.hxx"
29
30 #include <sstream>
31
32 #include <simgear/sg_inlines.h>
33 #include <simgear/timing/sg_time.hxx>
34 #include <simgear/math/vector.hxx>
35 #include <simgear/math/sg_random.h>
36 #include <simgear/misc/sg_path.hxx>
37 #include <simgear/math/sg_geodesy.hxx>
38 #include <simgear/structure/exception.hxx>
39 #include <simgear/math/interpolater.hxx>
40
41 #include <Navaids/navrecord.hxx>
42
43 #include <Airports/runways.hxx>
44 #include <Navaids/navlist.hxx>
45 #include <Main/util.hxx>
46
47
48 using std::string;
49
50 // General-purpose sawtooth function.  Graph looks like this:
51 //         /\                                    .
52 //       \/
53 // Odd symmetry, inversion symmetry about the origin.
54 // Unit slope at the origin.
55 // Max 1, min -1, period 4.
56 // Two zero-crossings per period, one with + slope, one with - slope.
57 // Useful for false localizer courses.
58 static double sawtooth(double xx)
59 {
60   return 4.0 * fabs(xx/4.0 + 0.25 - floor(xx/4.0 + 0.75)) - 1.0;
61 }
62
63 // Calculate a unit vector in the horizontal tangent plane
64 // starting at the given "tail" of the vector and going off 
65 // with the given heading.
66 static SGVec3d tangentVector(const SGGeod& tail, const SGVec3d& tail_xyz, 
67           const double heading)
68 {
69 // The fudge factor here is presumably intended to improve
70 // numerical stability.  I don't know if it is necessary.
71 // It gets divided out later.
72   double fudge(100.0);
73   SGGeod head;
74   double az2; // ignored
75   SGGeodesy::direct(tail, heading, fudge, head, az2);
76   head.setElevationM(tail.getElevationM());
77   SGVec3d head_xyz = SGVec3d::fromGeod(head);
78   return (head_xyz - tail_xyz) * (1.0/fudge);
79 }
80
81 // Constructor
82 FGNavRadio::FGNavRadio(SGPropertyNode *node) :
83     lon_node(fgGetNode("/position/longitude-deg", true)),
84     lat_node(fgGetNode("/position/latitude-deg", true)),
85     alt_node(fgGetNode("/position/altitude-ft", true)),
86     is_valid_node(NULL),
87     power_btn_node(NULL),
88     freq_node(NULL),
89     alt_freq_node(NULL),
90     sel_radial_node(NULL),
91     vol_btn_node(NULL),
92     ident_btn_node(NULL),
93     audio_btn_node(NULL),
94     backcourse_node(NULL),
95     nav_serviceable_node(NULL),
96     cdi_serviceable_node(NULL),
97     gs_serviceable_node(NULL),
98     tofrom_serviceable_node(NULL),
99     fmt_freq_node(NULL),
100     fmt_alt_freq_node(NULL),
101     heading_node(NULL),
102     radial_node(NULL),
103     recip_radial_node(NULL),
104     target_radial_true_node(NULL),
105     target_auto_hdg_node(NULL),
106     time_to_intercept(NULL),
107     to_flag_node(NULL),
108     from_flag_node(NULL),
109     inrange_node(NULL),
110     signal_quality_norm_node(NULL),
111     cdi_deflection_node(NULL),
112     cdi_deflection_norm_node(NULL),
113     cdi_xtrack_error_node(NULL),
114     cdi_xtrack_hdg_err_node(NULL),
115     has_gs_node(NULL),
116     loc_node(NULL),
117     loc_dist_node(NULL),
118     gs_deflection_node(NULL),
119     gs_deflection_deg_node(NULL),
120     gs_deflection_norm_node(NULL),
121     gs_rate_of_climb_node(NULL),
122     gs_dist_node(NULL),
123     nav_id_node(NULL),
124     id_c1_node(NULL),
125     id_c2_node(NULL),
126     id_c3_node(NULL),
127     id_c4_node(NULL),
128     nav_slaved_to_gps_node(NULL),
129     gps_cdi_deflection_node(NULL),
130     gps_to_flag_node(NULL),
131     gps_from_flag_node(NULL),
132     gps_has_gs_node(NULL),
133     gps_xtrack_error_nm_node(NULL),
134     play_count(0),
135     last_time(0),
136     target_radial(0.0),
137     horiz_vel(0.0),
138     last_x(0.0),
139     last_loc_dist(0.0),
140     last_xtrack_error(0.0),
141     _localizerWidth(5.0),
142     _name(node->getStringValue("name", "nav")),
143     _num(node->getIntValue("number", 0)),
144     _time_before_search_sec(-1.0)
145 {
146     SGPath path( globals->get_fg_root() );
147     SGPath term = path;
148     term.append( "Navaids/range.term" );
149     SGPath low = path;
150     low.append( "Navaids/range.low" );
151     SGPath high = path;
152     high.append( "Navaids/range.high" );
153
154     term_tbl = new SGInterpTable( term.str() );
155     low_tbl = new SGInterpTable( low.str() );
156     high_tbl = new SGInterpTable( high.str() );
157 }
158
159
160 // Destructor
161 FGNavRadio::~FGNavRadio() 
162 {
163     delete term_tbl;
164     delete low_tbl;
165     delete high_tbl;
166 }
167
168
169 void
170 FGNavRadio::init ()
171 {
172     morse.init();
173
174     string branch;
175     branch = "/instrumentation/" + _name;
176
177     SGPropertyNode *node = fgGetNode(branch.c_str(), _num, true );
178
179     bus_power_node = 
180         fgGetNode(("/systems/electrical/outputs/" + _name).c_str(), true);
181
182     // inputs
183     is_valid_node = node->getChild("data-is-valid", 0, true);
184     power_btn_node = node->getChild("power-btn", 0, true);
185     power_btn_node->setBoolValue( true );
186     vol_btn_node = node->getChild("volume", 0, true);
187     ident_btn_node = node->getChild("ident", 0, true);
188     ident_btn_node->setBoolValue( true );
189     audio_btn_node = node->getChild("audio-btn", 0, true);
190     audio_btn_node->setBoolValue( true );
191     backcourse_node = node->getChild("back-course-btn", 0, true);
192     backcourse_node->setBoolValue( false );
193     nav_serviceable_node = node->getChild("serviceable", 0, true);
194     cdi_serviceable_node = (node->getChild("cdi", 0, true))
195         ->getChild("serviceable", 0, true);
196     gs_serviceable_node = (node->getChild("gs", 0, true))
197         ->getChild("serviceable");
198     tofrom_serviceable_node = (node->getChild("to-from", 0, true))
199         ->getChild("serviceable", 0, true);
200
201     // frequencies
202     SGPropertyNode *subnode = node->getChild("frequencies", 0, true);
203     freq_node = subnode->getChild("selected-mhz", 0, true);
204     alt_freq_node = subnode->getChild("standby-mhz", 0, true);
205     fmt_freq_node = subnode->getChild("selected-mhz-fmt", 0, true);
206     fmt_alt_freq_node = subnode->getChild("standby-mhz-fmt", 0, true);
207
208     // radials
209     subnode = node->getChild("radials", 0, true);
210     sel_radial_node = subnode->getChild("selected-deg", 0, true);
211     radial_node = subnode->getChild("actual-deg", 0, true);
212     recip_radial_node = subnode->getChild("reciprocal-radial-deg", 0, true);
213     target_radial_true_node = subnode->getChild("target-radial-deg", 0, true);
214     target_auto_hdg_node = subnode->getChild("target-auto-hdg-deg", 0, true);
215
216     // outputs
217     heading_node = node->getChild("heading-deg", 0, true);
218     time_to_intercept = node->getChild("time-to-intercept-sec", 0, true);
219     to_flag_node = node->getChild("to-flag", 0, true);
220     from_flag_node = node->getChild("from-flag", 0, true);
221     inrange_node = node->getChild("in-range", 0, true);
222     signal_quality_norm_node = node->getChild("signal-quality-norm", 0, true);
223     cdi_deflection_node = node->getChild("heading-needle-deflection", 0, true);
224     cdi_deflection_norm_node = node->getChild("heading-needle-deflection-norm", 0, true);
225     cdi_xtrack_error_node = node->getChild("crosstrack-error-m", 0, true);
226     cdi_xtrack_hdg_err_node
227         = node->getChild("crosstrack-heading-error-deg", 0, true);
228     has_gs_node = node->getChild("has-gs", 0, true);
229     loc_node = node->getChild("nav-loc", 0, true);
230     loc_dist_node = node->getChild("nav-distance", 0, true);
231     gs_deflection_node = node->getChild("gs-needle-deflection", 0, true);
232     gs_deflection_deg_node = node->getChild("gs-needle-deflection-deg", 0, true);
233     gs_deflection_norm_node = node->getChild("gs-needle-deflection-norm", 0, true);
234     gs_rate_of_climb_node = node->getChild("gs-rate-of-climb", 0, true);
235     gs_dist_node = node->getChild("gs-distance", 0, true);
236     nav_id_node = node->getChild("nav-id", 0, true);
237     id_c1_node = node->getChild("nav-id_asc1", 0, true);
238     id_c2_node = node->getChild("nav-id_asc2", 0, true);
239     id_c3_node = node->getChild("nav-id_asc3", 0, true);
240     id_c4_node = node->getChild("nav-id_asc4", 0, true);
241
242     // gps slaving support
243     nav_slaved_to_gps_node = node->getChild("slaved-to-gps", 0, true);
244     gps_cdi_deflection_node = fgGetNode("/instrumentation/gps/cdi-deflection", true);
245     gps_to_flag_node = fgGetNode("/instrumentation/gps/to-flag", true);
246     gps_from_flag_node = fgGetNode("/instrumentation/gps/from-flag", true);
247     gps_has_gs_node = fgGetNode("/instrumentation/gps/has-gs", true);
248     gps_course_node = fgGetNode("/instrumentation/gps/selected-course-deg", true);
249     gps_xtrack_error_nm_node = fgGetNode("/instrumentation/gps/wp/wp[1]/course-error-nm", true);
250     _magvarNode = fgGetNode("/environment/magnetic-variation-deg", true);
251     
252     std::ostringstream temp;
253     temp << _name << "nav-ident" << _num;
254     nav_fx_name = temp.str();
255     temp << _name << "dme-ident" << _num;
256     dme_fx_name = temp.str();
257 }
258
259 void
260 FGNavRadio::bind ()
261 {
262     std::ostringstream temp;
263     string branch;
264     temp << _num;
265     branch = "/instrumentation/" + _name + "[" + temp.str() + "]";
266 }
267
268
269 void
270 FGNavRadio::unbind ()
271 {
272     std::ostringstream temp;
273     string branch;
274     temp << _num;
275     branch = "/instrumentation/" + _name + "[" + temp.str() + "]";
276 }
277
278
279 // model standard VOR/DME/TACAN service volumes as per AIM 1-1-8
280 double FGNavRadio::adjustNavRange( double stationElev, double aircraftElev,
281                                  double nominalRange )
282 {
283     // extend out actual usable range to be 1.3x the published safe range
284     const double usability_factor = 1.3;
285
286     // assumptions we model the standard service volume, plus
287     // ... rather than specifying a cylinder, we model a cone that
288     // contains the cylinder.  Then we put an upside down cone on top
289     // to model diminishing returns at too-high altitudes.
290
291     // altitude difference
292     double alt = ( aircraftElev * SG_METER_TO_FEET - stationElev );
293     // cout << "aircraft elev = " << aircraftElev * SG_METER_TO_FEET
294     //      << " station elev = " << stationElev << endl;
295
296     if ( nominalRange < 25.0 + SG_EPSILON ) {
297         // Standard Terminal Service Volume
298         return term_tbl->interpolate( alt ) * usability_factor;
299     } else if ( nominalRange < 50.0 + SG_EPSILON ) {
300         // Standard Low Altitude Service Volume
301         // table is based on range of 40, scale to actual range
302         return low_tbl->interpolate( alt ) * nominalRange / 40.0
303             * usability_factor;
304     } else {
305         // Standard High Altitude Service Volume
306         // table is based on range of 130, scale to actual range
307         return high_tbl->interpolate( alt ) * nominalRange / 130.0
308             * usability_factor;
309     }
310 }
311
312
313 // model standard ILS service volumes as per AIM 1-1-9
314 double FGNavRadio::adjustILSRange( double stationElev, double aircraftElev,
315                                  double offsetDegrees, double distance )
316 {
317     // assumptions we model the standard service volume, plus
318
319     // altitude difference
320     // double alt = ( aircraftElev * SG_METER_TO_FEET - stationElev );
321 //     double offset = fabs( offsetDegrees );
322
323 //     if ( offset < 10 ) {
324 //      return FG_ILS_DEFAULT_RANGE;
325 //     } else if ( offset < 35 ) {
326 //      return 10 + (35 - offset) * (FG_ILS_DEFAULT_RANGE - 10) / 25;
327 //     } else if ( offset < 45 ) {
328 //      return (45 - offset);
329 //     } else if ( offset > 170 ) {
330 //         return FG_ILS_DEFAULT_RANGE;
331 //     } else if ( offset > 145 ) {
332 //      return 10 + (offset - 145) * (FG_ILS_DEFAULT_RANGE - 10) / 25;
333 //     } else if ( offset > 135 ) {
334 //         return (offset - 135);
335 //     } else {
336 //      return 0;
337 //     }
338     return FG_LOC_DEFAULT_RANGE;
339 }
340
341
342 //////////////////////////////////////////////////////////////////////////
343 // Update the various nav values based on position and valid tuned in navs
344 //////////////////////////////////////////////////////////////////////////
345 void 
346 FGNavRadio::update(double dt) 
347 {
348   if (dt <= 0.0) {
349     return; // paused
350   }
351     
352   // Create "formatted" versions of the nav frequencies for
353   // instrument displays.
354   char tmp[16];
355   sprintf( tmp, "%.2f", freq_node->getDoubleValue() );
356   fmt_freq_node->setStringValue(tmp);
357   sprintf( tmp, "%.2f", alt_freq_node->getDoubleValue() );
358   fmt_alt_freq_node->setStringValue(tmp);
359
360   if (power_btn_node->getBoolValue() 
361       && (bus_power_node->getDoubleValue() > 1.0)
362       && nav_serviceable_node->getBoolValue() )
363   {   
364     if (nav_slaved_to_gps_node->getBoolValue()) {
365       updateGPSSlaved();
366     } else {
367       updateReceiver(dt);
368     }
369     
370     updateCDI(dt);
371   } else {
372     clearOutputs();
373   }
374   
375   updateAudio();
376 }
377
378 void FGNavRadio::clearOutputs()
379 {
380   inrange_node->setBoolValue( false );
381   cdi_deflection_node->setDoubleValue( 0.0 );
382   cdi_deflection_norm_node->setDoubleValue( 0.0 );
383   cdi_xtrack_error_node->setDoubleValue( 0.0 );
384   cdi_xtrack_hdg_err_node->setDoubleValue( 0.0 );
385   time_to_intercept->setDoubleValue( 0.0 );
386   gs_deflection_node->setDoubleValue( 0.0 );
387   gs_deflection_deg_node->setDoubleValue(0.0);
388   gs_deflection_norm_node->setDoubleValue(0.0);
389   
390   to_flag_node->setBoolValue( false );
391   from_flag_node->setBoolValue( false );
392 }
393
394 void FGNavRadio::updateReceiver(double dt)
395 {
396   // Do a nav station search only once a second to reduce
397   // unnecessary work. (Also, make sure to do this before caching
398   // any values!)
399   _time_before_search_sec -= dt;
400   if ( _time_before_search_sec < 0 ) {
401    search();
402   }
403
404   if (!_navaid) {
405     _cdiDeflection = 0.0;
406     _cdiCrossTrackErrorM = 0.0;
407     _toFlag = _fromFlag = false;
408     _gsNeedleDeflection = 0.0;
409     _gsNeedleDeflectionNorm = 0.0;
410     inrange_node->setBoolValue(false);
411     return;
412   }
413
414   SGGeod pos = SGGeod::fromDegFt(lon_node->getDoubleValue(),
415                                lat_node->getDoubleValue(),
416                                alt_node->getDoubleValue());
417                                
418   double nav_elev = _navaid->get_elev_ft();
419   SGVec3d aircraft = SGVec3d::fromGeod(pos);
420   double loc_dist = dist(aircraft, _navaid->cart());
421   loc_dist_node->setDoubleValue( loc_dist );
422   bool is_loc = loc_node->getBoolValue();
423   double signal_quality_norm = signal_quality_norm_node->getDoubleValue();
424   
425   double az2, s;
426   //////////////////////////////////////////////////////////
427         // compute forward and reverse wgs84 headings to localizer
428   //////////////////////////////////////////////////////////
429   double hdg;
430   SGGeodesy::inverse(pos, _navaid->geod(), hdg, az2, s);
431   heading_node->setDoubleValue(hdg);
432   double radial = az2 - twist;
433   double recip = radial + 180.0;
434   SG_NORMALIZE_RANGE(recip, 0.0, 360.0);
435   radial_node->setDoubleValue( radial );
436   recip_radial_node->setDoubleValue( recip );
437   
438   //////////////////////////////////////////////////////////
439   // compute the target/selected radial in "true" heading
440   //////////////////////////////////////////////////////////
441   if (!is_loc) {
442     target_radial = sel_radial_node->getDoubleValue();
443   }
444   
445   // VORs need twist (mag-var) added; ILS/LOCs don't but we set twist to 0.0
446   double trtrue = target_radial + twist;
447   SG_NORMALIZE_RANGE(trtrue, 0.0, 360.0);
448   target_radial_true_node->setDoubleValue( trtrue );
449
450   //////////////////////////////////////////////////////////
451   // adjust reception range for altitude
452   // FIXME: make sure we are using the navdata range now that
453   //        it is valid in the data file
454   //////////////////////////////////////////////////////////
455         if ( is_loc ) {
456             double offset = radial - target_radial;
457       SG_NORMALIZE_RANGE(offset, -180.0, 180.0);
458             effective_range
459                 = adjustILSRange( nav_elev, pos.getElevationM(), offset,
460                                   loc_dist * SG_METER_TO_NM );
461         } else {
462             effective_range
463                 = adjustNavRange( nav_elev, pos.getElevationM(), _navaid->get_range() );
464         }
465
466   double effective_range_m = effective_range * SG_NM_TO_METER;
467
468   //////////////////////////////////////////////////////////
469   // compute signal quality
470   // 100% within effective_range
471   // decreases 1/x^2 further out
472   //////////////////////////////////////////////////////////  
473   double last_signal_quality_norm = signal_quality_norm;
474
475   if ( loc_dist < effective_range_m ) {
476     signal_quality_norm = 1.0;
477   } else {
478     double range_exceed_norm = loc_dist/effective_range_m;
479     signal_quality_norm = 1/(range_exceed_norm*range_exceed_norm);
480   }
481
482   signal_quality_norm = fgGetLowPass( last_signal_quality_norm, 
483            signal_quality_norm, dt );
484   
485   signal_quality_norm_node->setDoubleValue( signal_quality_norm );
486   bool inrange = signal_quality_norm > 0.2;
487   inrange_node->setBoolValue( inrange );
488   
489   //////////////////////////////////////////////////////////
490   // compute to/from flag status
491   //////////////////////////////////////////////////////////
492   if (inrange) {
493     if (is_loc) {
494       _toFlag = true;
495     } else {
496       double offset = fabs(radial - target_radial);
497       _toFlag = (offset > 90.0 && offset < 270.0);
498     }
499     _fromFlag = !_toFlag;
500   } else {
501     _toFlag = _fromFlag = false;
502   }
503   
504   // CDI deflection
505   double r = target_radial - radial;
506   SG_NORMALIZE_RANGE(r, -180.0, 180.0);
507   
508   if ( is_loc ) {
509     // The factor of 30.0 gives a period of 120 which gives us 3 cycles and six 
510     // zeros i.e. six courses: one front course, one back course, and four 
511     // false courses. Three of the six are reverse sensing.
512     _cdiDeflection = 30.0 * sawtooth(r / 30.0);
513     const double VOR_FULL_ARC = 20.0; // VOR is -10 .. 10 degree swing
514     _cdiDeflection *= VOR_FULL_ARC / _localizerWidth; // increased localiser sensitivity
515   } else {
516     // handle the TO side of the VOR
517     if (fabs(r) > 90.0) {
518       r = ( r<0.0 ? -r-180.0 : -r+180.0 );
519     }
520     _cdiDeflection = r;
521   } // of non-localiser case
522   
523   SG_CLAMP_RANGE(_cdiDeflection, -10.0, 10.0 );
524   _cdiDeflection *= signal_quality_norm;
525   
526   // cross-track error (in metres)
527   _cdiCrossTrackErrorM = loc_dist * sin(r * SGD_DEGREES_TO_RADIANS);
528   
529   updateGlideSlope(dt, aircraft, signal_quality_norm);
530   
531   last_loc_dist = loc_dist;
532 }
533
534 void FGNavRadio::updateGlideSlope(double dt, const SGVec3d& aircraft, double signal_quality_norm)
535 {
536   _gsNeedleDeflection = 0.0;
537   if (!_gs || !inrange_node->getBoolValue()) {
538     gs_dist_node->setDoubleValue( 0.0 );
539     return;
540   }
541   
542   double gsDist = dist(aircraft, _gsCart);
543   gs_dist_node->setDoubleValue(gsDist);
544   if (gsDist > (_gs->get_range() * SG_NM_TO_METER)) {
545     return;
546   }
547   
548   SGVec3d pos = aircraft - _gsCart; // relative vector from gs antenna to aircraft
549   // The positive GS axis points along the runway in the landing direction,
550   // toward the far end, not toward the approach area, so we need a - sign here:
551   double dot_h = -dot(pos, _gsAxis);
552   double dot_v = dot(pos, _gsVertical);
553   double angle = atan2(dot_v, dot_h) * SGD_RADIANS_TO_DEGREES;
554   double deflectionAngle = target_gs - angle;
555     
556   // Construct false glideslopes.  The scale factor of 1.5 
557   // in the sawtooth gives a period of 6 degrees.
558   // There will be zeros at 3, 6r, 9, 12r et cetera
559   // where "r" indicates reverse sensing.
560   // This is is consistent with conventional pilot lore
561   // e.g. http://www.allstar.fiu.edu/aerojava/ILS.htm
562   // but inconsistent with
563   // http://www.freepatentsonline.com/3757338.html
564   //
565   // It may be that some of each exist.
566   if (deflectionAngle < 0) {
567     deflectionAngle = 1.5 * sawtooth(deflectionAngle / 1.5);
568   } else {
569     // no false GS below the true GS
570   }
571   
572   _gsNeedleDeflection = deflectionAngle * 5.0;
573   _gsNeedleDeflection *= signal_quality_norm;
574   
575   SG_CLAMP_RANGE(deflectionAngle, -0.7, 0.7);
576   _gsNeedleDeflectionNorm = (deflectionAngle / 0.7) * signal_quality_norm;
577   
578   //////////////////////////////////////////////////////////
579   // Calculate desired rate of climb for intercepting the GS
580   //////////////////////////////////////////////////////////
581   double gs_diff = target_gs - angle;
582   // convert desired vertical path angle into a climb rate
583   double des_angle = angle - 10 * gs_diff;
584
585   // estimate horizontal speed towards ILS in meters per minute
586   double elapsedDistance = last_x - gsDist;
587   last_x = gsDist;
588       
589   double new_vel = ( elapsedDistance / dt );
590   horiz_vel = 0.75 * horiz_vel + 0.25 * new_vel;
591
592   gs_rate_of_climb_node
593       ->setDoubleValue( -sin( des_angle * SGD_DEGREES_TO_RADIANS )
594                         * horiz_vel * SG_METER_TO_FEET );
595 }
596
597 void FGNavRadio::updateGPSSlaved()
598 {
599   has_gs_node->setBoolValue(gps_has_gs_node->getBoolValue());
600  
601   _toFlag = gps_to_flag_node->getBoolValue();
602   _fromFlag = gps_from_flag_node->getBoolValue();
603
604   bool gpsValid = (_toFlag | _fromFlag);
605   inrange_node->setBoolValue(gpsValid);
606   if (!gpsValid) {
607     signal_quality_norm_node->setDoubleValue(0.0);
608     _cdiDeflection = 0.0;
609     _cdiCrossTrackErrorM = 0.0;
610     _gsNeedleDeflection = 0.0;
611     return;
612   }
613   
614   // this is unfortunate, but panel instruments use this value to decide
615   // if the navradio output is valid.
616   signal_quality_norm_node->setDoubleValue(1.0);
617   
618   _cdiDeflection =  gps_cdi_deflection_node->getDoubleValue();
619   // clmap to some range (+/- 10 degrees) as the regular deflection
620   SG_CLAMP_RANGE(_cdiDeflection, -10.0, 10.0 );
621   
622   _cdiCrossTrackErrorM = gps_xtrack_error_nm_node->getDoubleValue() * SG_NM_TO_METER;
623   _gsNeedleDeflection = 0.0; // FIXME, supply this
624   
625   double trtrue = gps_course_node->getDoubleValue() + _magvarNode->getDoubleValue();
626   SG_NORMALIZE_RANGE(trtrue, 0.0, 360.0);
627   target_radial_true_node->setDoubleValue( trtrue );
628 }
629
630 void FGNavRadio::updateCDI(double dt)
631 {
632   bool cdi_serviceable = cdi_serviceable_node->getBoolValue();
633   bool inrange = inrange_node->getBoolValue();
634                                
635   if (tofrom_serviceable_node->getBoolValue()) {
636     to_flag_node->setBoolValue(_toFlag);
637     from_flag_node->setBoolValue(_fromFlag);
638   } else {
639     to_flag_node->setBoolValue(false);
640     from_flag_node->setBoolValue(false);
641   }
642   
643   if (!cdi_serviceable) {
644     _cdiDeflection = 0.0;
645     _cdiCrossTrackErrorM = 0.0;
646   }
647   
648   cdi_deflection_node->setDoubleValue(_cdiDeflection);
649   cdi_deflection_norm_node->setDoubleValue(_cdiDeflection * 0.1);
650   cdi_xtrack_error_node->setDoubleValue(_cdiCrossTrackErrorM);
651
652   //////////////////////////////////////////////////////////
653   // compute an approximate ground track heading error
654   //////////////////////////////////////////////////////////
655   double hdg_error = 0.0;
656   if ( inrange && cdi_serviceable ) {
657     double vn = fgGetDouble( "/velocities/speed-north-fps" );
658     double ve = fgGetDouble( "/velocities/speed-east-fps" );
659     double gnd_trk_true = atan2( ve, vn ) * SGD_RADIANS_TO_DEGREES;
660     if ( gnd_trk_true < 0.0 ) { gnd_trk_true += 360.0; }
661
662     SGPropertyNode *true_hdg
663         = fgGetNode("/orientation/heading-deg", true);
664     hdg_error = gnd_trk_true - true_hdg->getDoubleValue();
665
666     // cout << "ground track = " << gnd_trk_true
667     //      << " orientation = " << true_hdg->getDoubleValue() << endl;
668   }
669   cdi_xtrack_hdg_err_node->setDoubleValue( hdg_error );
670
671   //////////////////////////////////////////////////////////
672   // Calculate a suggested target heading to smoothly intercept
673   // a nav/ils radial.
674   //////////////////////////////////////////////////////////
675
676   // Now that we have cross track heading adjustment built in,
677   // we shouldn't need to overdrive the heading angle within 8km
678   // of the station.
679   //
680   // The cdi deflection should be +/-10 for a full range of deflection
681   // so multiplying this by 3 gives us +/- 30 degrees heading
682   // compensation.
683   double adjustment = _cdiDeflection * 3.0;
684   SG_CLAMP_RANGE( adjustment, -30.0, 30.0 );
685
686   // determine the target heading to fly to intercept the
687   // tgt_radial = target radial (true) + cdi offset adjustmest -
688   // xtrack heading error adjustment
689   double nta_hdg;
690   double trtrue = target_radial_true_node->getDoubleValue();
691   if ( loc_node->getBoolValue() && backcourse_node->getBoolValue() ) {
692       // tuned to a localizer and backcourse mode activated
693       trtrue += 180.0;   // reverse the target localizer heading
694       SG_NORMALIZE_RANGE(trtrue, 0.0, 360.0);
695       nta_hdg = trtrue - adjustment - hdg_error;
696   } else {
697       nta_hdg = trtrue + adjustment - hdg_error;
698   }
699
700   SG_NORMALIZE_RANGE(nta_hdg, 0.0, 360.0);
701   target_auto_hdg_node->setDoubleValue( nta_hdg );
702
703   //////////////////////////////////////////////////////////
704   // compute the time to intercept selected radial (based on
705   // current and last cross track errors and dt
706   //////////////////////////////////////////////////////////
707   double t = 0.0;
708   if ( inrange && cdi_serviceable ) {
709     double xrate_ms = (last_xtrack_error - _cdiCrossTrackErrorM) / dt;
710     if ( fabs(xrate_ms) > 0.00001 ) {
711         t = _cdiCrossTrackErrorM / xrate_ms;
712     } else {
713         t = 9999.9;
714     }
715   }
716   time_to_intercept->setDoubleValue( t );
717
718   if (!gs_serviceable_node->getBoolValue() ) {
719     _gsNeedleDeflection = 0.0;
720     _gsNeedleDeflectionNorm = 0.0;
721   }
722   gs_deflection_node->setDoubleValue(_gsNeedleDeflection);
723   gs_deflection_deg_node->setDoubleValue(_gsNeedleDeflectionNorm * 0.7);
724   gs_deflection_norm_node->setDoubleValue(_gsNeedleDeflectionNorm);
725   
726   last_xtrack_error = _cdiCrossTrackErrorM;
727 }
728
729 void FGNavRadio::updateAudio()
730 {
731   if (!_navaid || !inrange_node->getBoolValue() || !nav_serviceable_node->getBoolValue()) {
732     return;
733   }
734   
735         // play station ident via audio system if on + ident,
736         // otherwise turn it off
737         if (!power_btn_node->getBoolValue()
738       || !(bus_power_node->getDoubleValue() > 1.0)
739       || !ident_btn_node->getBoolValue()
740       || !audio_btn_node->getBoolValue() ) {
741     globals->get_soundmgr()->stop( nav_fx_name );
742     globals->get_soundmgr()->stop( dme_fx_name );
743     return;
744   }
745
746   SGSoundSample *sound = globals->get_soundmgr()->find( nav_fx_name );
747   double vol = vol_btn_node->getDoubleValue();
748   SG_CLAMP_RANGE(vol, 0.0, 1.0);
749   
750   if ( sound != NULL ) {
751     sound->set_volume( vol );
752   } else {
753     SG_LOG( SG_COCKPIT, SG_ALERT, "Can't find nav-vor-ident sound" );
754   }
755   
756   sound = globals->get_soundmgr()->find( dme_fx_name );
757   if ( sound != NULL ) {
758     sound->set_volume( vol );
759   } else {
760     SG_LOG( SG_COCKPIT, SG_ALERT, "Can't find nav-dme-ident sound" );
761   }
762
763   if ( last_time < globals->get_time_params()->get_cur_time() - 30 ) {
764                 last_time = globals->get_time_params()->get_cur_time();
765                 play_count = 0;
766   }
767   
768   if ( play_count < 4 ) {
769                 // play VOR ident
770                 if ( !globals->get_soundmgr()->is_playing(nav_fx_name) ) {
771                     globals->get_soundmgr()->play_once( nav_fx_name );
772                     ++play_count;
773     }
774   } else if ( play_count < 5 &&  has_dme) {
775                 // play DME ident
776                 if ( !globals->get_soundmgr()->is_playing(nav_fx_name) &&
777                      !globals->get_soundmgr()->is_playing(dme_fx_name) ) {
778                     globals->get_soundmgr()->play_once( dme_fx_name );
779                     ++play_count;
780                 }
781   }
782 }
783
784 FGNavRecord* FGNavRadio::findPrimaryNavaid(const SGGeod& aPos, double aFreqMHz)
785 {
786   FGNavRecord* nav = globals->get_navlist()->findByFreq(aFreqMHz, aPos);
787   if (nav) {
788     return nav;
789   }
790   
791   return globals->get_loclist()->findByFreq(aFreqMHz, aPos);
792 }
793
794 // Update current nav/adf radio stations based on current postition
795 void FGNavRadio::search() 
796 {
797   _time_before_search_sec = 1.0;
798   SGGeod pos = SGGeod::fromDegFt(lon_node->getDoubleValue(),
799     lat_node->getDoubleValue(), alt_node->getDoubleValue());
800   double freq = freq_node->getDoubleValue();
801   
802   FGNavRecord* nav = findPrimaryNavaid(pos, freq);
803   if (nav == _navaid) {
804     return; // found the same as last search, we're done
805   }
806   
807   _navaid = nav;
808   char identBuffer[5] = "    ";
809   if (nav) {
810     FGNavRecord* dme = globals->get_dmelist()->findByFreq(freq, pos);
811     has_dme = (dme != NULL);
812     
813     nav_id_node->setStringValue(nav->get_ident());
814     strncpy(identBuffer, nav->ident().c_str(), 5);
815     
816     effective_range = adjustNavRange(nav->get_elev_ft(), pos.getElevationM(), nav->get_range());
817     loc_node->setBoolValue(nav->type() != FGPositioned::VOR);
818     twist = nav->get_multiuse();
819
820     if (nav->type() == FGPositioned::VOR) {
821       target_radial = sel_radial_node->getDoubleValue();
822       _gs = NULL;
823     } else { // ILS or LOC
824       _gs = globals->get_gslist()->findByFreq(freq, pos);
825       _localizerWidth = localizerWidth(nav);
826       has_gs_node->setBoolValue(_gs != NULL);
827       twist = 0.0;
828             effective_range = nav->get_range();
829       
830       target_radial = nav->get_multiuse();
831       SG_NORMALIZE_RANGE(target_radial, 0.0, 360.0);
832       
833       if (_gs) {
834         int tmp = (int)(_gs->get_multiuse() / 1000.0);
835         target_gs = (double)tmp / 100.0;
836         
837         // GS axis unit tangent vector
838         // (along the runway)
839         _gsCart = _gs->cart();
840         _gsAxis = tangentVector(_gs->geod(), _gsCart, target_radial);
841
842         // GS baseline unit tangent vector
843         // (perpendicular to the runay along the ground)
844         SGVec3d baseline = tangentVector(_gs->geod(), _gsCart, target_radial + 90.0);
845         _gsVertical = cross(baseline, _gsAxis);
846       } // of have glideslope
847     } // of found LOC or ILS
848     
849     audioNavidChanged();
850   } else { // found nothing
851     _gs = NULL;
852     nav_id_node->setStringValue("");
853     has_dme = false;
854     globals->get_soundmgr()->remove( nav_fx_name );
855     globals->get_soundmgr()->remove( dme_fx_name );
856   }
857
858   is_valid_node->setBoolValue(nav != NULL);
859   id_c1_node->setIntValue( (int)identBuffer[0] );
860   id_c2_node->setIntValue( (int)identBuffer[1] );
861   id_c3_node->setIntValue( (int)identBuffer[2] );
862   id_c4_node->setIntValue( (int)identBuffer[3] );
863 }
864
865 double FGNavRadio::localizerWidth(FGNavRecord* aLOC)
866 {
867   FGRunway* rwy = aLOC->runway();
868   assert(rwy);
869   
870   SGVec3d thresholdCart(SGVec3d::fromGeod(rwy->threshold()));
871   double axisLength = dist(aLOC->cart(), thresholdCart);
872   double landingLength = dist(thresholdCart, SGVec3d::fromGeod(rwy->end()));
873   
874 // Reference: http://dcaa.slv.dk:8000/icaodocs/
875 // ICAO standard width at threshold is 210 m = 689 feet = approx 700 feet.
876 // ICAO 3.1.1 half course = DDM = 0.0775
877 // ICAO 3.1.3.7.1 Sensitivity 0.00145 DDM/m at threshold
878 //  implies peg-to-peg of 214 m ... we will stick with 210.
879 // ICAO 3.1.3.7.1 "Course sector angle shall not exceed 6 degrees."
880               
881 // Very short runway:  less than 1200 m (4000 ft) landing length:
882   if (landingLength < 1200.0) {
883 // ICAO fudges localizer sensitivity for very short runways.
884 // This produces a non-monotonic sensitivity-versus length relation.
885     axisLength += 1050.0;
886   }
887
888 // Example: very short: San Diego   KMYF (Montgomery Field) ILS RWY 28R
889 // Example: short:      Tom's River KMJX (Robert J. Miller) ILS RWY 6
890 // Example: very long:  Denver      KDEN (Denver)           ILS RWY 16R
891   double raw_width = 210.0 / axisLength * SGD_RADIANS_TO_DEGREES;
892   return raw_width < 6.0? raw_width : 6.0;
893 }
894
895 void FGNavRadio::audioNavidChanged()
896 {
897   if ( globals->get_soundmgr()->exists(nav_fx_name)) {
898                 globals->get_soundmgr()->remove(nav_fx_name);
899   }
900   
901   try {
902     string trans_ident(_navaid->get_trans_ident());
903     SGSoundSample* sound = morse.make_ident(trans_ident, LO_FREQUENCY);
904     sound->set_volume( 0.3 );
905     if (!globals->get_soundmgr()->add( sound, nav_fx_name )) {
906       SG_LOG(SG_COCKPIT, SG_WARN, "Failed to add v1-vor-ident sound");
907     }
908
909           if ( globals->get_soundmgr()->exists( dme_fx_name ) ) {
910       globals->get_soundmgr()->remove( dme_fx_name );
911     }
912      
913     sound = morse.make_ident( trans_ident, HI_FREQUENCY );
914     sound->set_volume( 0.3 );
915     globals->get_soundmgr()->add( sound, dme_fx_name );
916
917           int offset = (int)(sg_random() * 30.0);
918           play_count = offset / 4;
919     last_time = globals->get_time_params()->get_cur_time() - offset;
920   } catch (sg_io_exception& e) {
921     SG_LOG(SG_GENERAL, SG_ALERT, e.getFormattedMessage());
922   }
923 }