1 // navradio.cxx -- class to manage a nav radio instance
3 // Written by Curtis Olson, started April 2000.
5 // Copyright (C) 2000 - 2002 Curtis L. Olson - http://www.flightgear.org/~curt
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.
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.
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.
28 #include "navradio.hxx"
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>
41 #include <Navaids/navrecord.hxx>
43 #include <Airports/runways.hxx>
44 #include <Navaids/navlist.hxx>
45 #include <Main/util.hxx>
50 // General-purpose sawtooth function. Graph looks like this:
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)
60 return 4.0 * fabs(xx/4.0 + 0.25 - floor(xx/4.0 + 0.75)) - 1.0;
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,
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.
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);
81 // Create a "serviceable" node with a default value of "true"
82 SGPropertyNode_ptr createServiceableProp(SGPropertyNode* aParent, const char* aName)
84 SGPropertyNode_ptr n = (aParent->getChild(aName, 0, true)->getChild("serviceable", 0, true));
85 simgear::props::Type typ = n->getType();
86 if ((typ == simgear::props::NONE) || (typ == simgear::props::UNSPECIFIED)) {
87 n->setBoolValue(true);
93 FGNavRadio::FGNavRadio(SGPropertyNode *node) :
94 lon_node(fgGetNode("/position/longitude-deg", true)),
95 lat_node(fgGetNode("/position/latitude-deg", true)),
96 alt_node(fgGetNode("/position/altitude-ft", true)),
101 sel_radial_node(NULL),
103 ident_btn_node(NULL),
104 audio_btn_node(NULL),
105 backcourse_node(NULL),
106 nav_serviceable_node(NULL),
107 cdi_serviceable_node(NULL),
108 gs_serviceable_node(NULL),
109 tofrom_serviceable_node(NULL),
110 dme_serviceable_node(NULL),
112 fmt_alt_freq_node(NULL),
115 recip_radial_node(NULL),
116 target_radial_true_node(NULL),
117 target_auto_hdg_node(NULL),
118 time_to_intercept(NULL),
120 from_flag_node(NULL),
122 signal_quality_norm_node(NULL),
123 cdi_deflection_node(NULL),
124 cdi_deflection_norm_node(NULL),
125 cdi_xtrack_error_node(NULL),
126 cdi_xtrack_hdg_err_node(NULL),
130 gs_deflection_node(NULL),
131 gs_deflection_deg_node(NULL),
132 gs_deflection_norm_node(NULL),
133 gs_rate_of_climb_node(NULL),
135 gs_inrange_node(NULL),
141 nav_slaved_to_gps_node(NULL),
142 gps_cdi_deflection_node(NULL),
143 gps_to_flag_node(NULL),
144 gps_from_flag_node(NULL),
145 gps_has_gs_node(NULL),
146 gps_xtrack_error_nm_node(NULL),
153 last_xtrack_error(0.0),
155 _localizerWidth(5.0),
156 _name(node->getStringValue("name", "nav")),
157 _num(node->getIntValue("number", 0)),
158 _time_before_search_sec(-1.0),
159 _falseCoursesEnabled(true)
161 SGPath path( globals->get_fg_root() );
163 term.append( "Navaids/range.term" );
165 low.append( "Navaids/range.low" );
167 high.append( "Navaids/range.high" );
169 term_tbl = new SGInterpTable( term.str() );
170 low_tbl = new SGInterpTable( low.str() );
171 high_tbl = new SGInterpTable( high.str() );
176 FGNavRadio::~FGNavRadio()
190 branch = "/instrumentation/" + _name;
192 SGPropertyNode *node = fgGetNode(branch.c_str(), _num, true );
195 fgGetNode(("/systems/electrical/outputs/" + _name).c_str(), true);
198 is_valid_node = node->getChild("data-is-valid", 0, true);
199 power_btn_node = node->getChild("power-btn", 0, true);
200 power_btn_node->setBoolValue( true );
201 vol_btn_node = node->getChild("volume", 0, true);
202 ident_btn_node = node->getChild("ident", 0, true);
203 ident_btn_node->setBoolValue( true );
204 audio_btn_node = node->getChild("audio-btn", 0, true);
205 audio_btn_node->setBoolValue( true );
206 backcourse_node = node->getChild("back-course-btn", 0, true);
207 backcourse_node->setBoolValue( false );
209 nav_serviceable_node = node->getChild("serviceable", 0, true);
210 cdi_serviceable_node = createServiceableProp(node, "cdi");
211 gs_serviceable_node = createServiceableProp(node, "gs");
212 tofrom_serviceable_node = createServiceableProp(node, "to-from");
213 dme_serviceable_node = createServiceableProp(node, "dme");
215 globals->get_props()->tie("sim/realism/false-radio-courses-enabled",
216 SGRawValuePointer<bool>(&_falseCoursesEnabled));
219 SGPropertyNode *subnode = node->getChild("frequencies", 0, true);
220 freq_node = subnode->getChild("selected-mhz", 0, true);
221 alt_freq_node = subnode->getChild("standby-mhz", 0, true);
222 fmt_freq_node = subnode->getChild("selected-mhz-fmt", 0, true);
223 fmt_alt_freq_node = subnode->getChild("standby-mhz-fmt", 0, true);
226 subnode = node->getChild("radials", 0, true);
227 sel_radial_node = subnode->getChild("selected-deg", 0, true);
228 radial_node = subnode->getChild("actual-deg", 0, true);
229 recip_radial_node = subnode->getChild("reciprocal-radial-deg", 0, true);
230 target_radial_true_node = subnode->getChild("target-radial-deg", 0, true);
231 target_auto_hdg_node = subnode->getChild("target-auto-hdg-deg", 0, true);
234 heading_node = node->getChild("heading-deg", 0, true);
235 time_to_intercept = node->getChild("time-to-intercept-sec", 0, true);
236 to_flag_node = node->getChild("to-flag", 0, true);
237 from_flag_node = node->getChild("from-flag", 0, true);
238 inrange_node = node->getChild("in-range", 0, true);
239 signal_quality_norm_node = node->getChild("signal-quality-norm", 0, true);
240 cdi_deflection_node = node->getChild("heading-needle-deflection", 0, true);
241 cdi_deflection_norm_node = node->getChild("heading-needle-deflection-norm", 0, true);
242 cdi_xtrack_error_node = node->getChild("crosstrack-error-m", 0, true);
243 cdi_xtrack_hdg_err_node
244 = node->getChild("crosstrack-heading-error-deg", 0, true);
245 has_gs_node = node->getChild("has-gs", 0, true);
246 loc_node = node->getChild("nav-loc", 0, true);
247 loc_dist_node = node->getChild("nav-distance", 0, true);
248 gs_deflection_node = node->getChild("gs-needle-deflection", 0, true);
249 gs_deflection_deg_node = node->getChild("gs-needle-deflection-deg", 0, true);
250 gs_deflection_norm_node = node->getChild("gs-needle-deflection-norm", 0, true);
251 gs_rate_of_climb_node = node->getChild("gs-rate-of-climb", 0, true);
252 gs_dist_node = node->getChild("gs-distance", 0, true);
253 gs_inrange_node = node->getChild("gs-in-range", 0, true);
255 nav_id_node = node->getChild("nav-id", 0, true);
256 id_c1_node = node->getChild("nav-id_asc1", 0, true);
257 id_c2_node = node->getChild("nav-id_asc2", 0, true);
258 id_c3_node = node->getChild("nav-id_asc3", 0, true);
259 id_c4_node = node->getChild("nav-id_asc4", 0, true);
261 node->tie("dme-in-range", SGRawValuePointer<bool>(&_dmeInRange));
263 // gps slaving support
264 nav_slaved_to_gps_node = node->getChild("slaved-to-gps", 0, true);
265 gps_cdi_deflection_node = fgGetNode("/instrumentation/gps/cdi-deflection", true);
266 gps_to_flag_node = fgGetNode("/instrumentation/gps/to-flag", true);
267 gps_from_flag_node = fgGetNode("/instrumentation/gps/from-flag", true);
268 gps_has_gs_node = fgGetNode("/instrumentation/gps/has-gs", true);
269 gps_course_node = fgGetNode("/instrumentation/gps/selected-course-deg", true);
270 gps_xtrack_error_nm_node = fgGetNode("/instrumentation/gps/wp/wp[1]/course-error-nm", true);
271 _magvarNode = fgGetNode("/environment/magnetic-variation-deg", true);
273 std::ostringstream temp;
274 temp << _name << "nav-ident" << _num;
275 nav_fx_name = temp.str();
276 temp << _name << "dme-ident" << _num;
277 dme_fx_name = temp.str();
288 FGNavRadio::unbind ()
293 // model standard VOR/DME/TACAN service volumes as per AIM 1-1-8
294 double FGNavRadio::adjustNavRange( double stationElev, double aircraftElev,
295 double nominalRange )
297 if (nominalRange <= 0.0) {
298 nominalRange = FG_NAV_DEFAULT_RANGE;
301 // extend out actual usable range to be 1.3x the published safe range
302 const double usability_factor = 1.3;
304 // assumptions we model the standard service volume, plus
305 // ... rather than specifying a cylinder, we model a cone that
306 // contains the cylinder. Then we put an upside down cone on top
307 // to model diminishing returns at too-high altitudes.
309 // altitude difference
310 double alt = ( aircraftElev * SG_METER_TO_FEET - stationElev );
311 // cout << "aircraft elev = " << aircraftElev * SG_METER_TO_FEET
312 // << " station elev = " << stationElev << endl;
314 if ( nominalRange < 25.0 + SG_EPSILON ) {
315 // Standard Terminal Service Volume
316 return term_tbl->interpolate( alt ) * usability_factor;
317 } else if ( nominalRange < 50.0 + SG_EPSILON ) {
318 // Standard Low Altitude Service Volume
319 // table is based on range of 40, scale to actual range
320 return low_tbl->interpolate( alt ) * nominalRange / 40.0
323 // Standard High Altitude Service Volume
324 // table is based on range of 130, scale to actual range
325 return high_tbl->interpolate( alt ) * nominalRange / 130.0
331 // model standard ILS service volumes as per AIM 1-1-9
332 double FGNavRadio::adjustILSRange( double stationElev, double aircraftElev,
333 double offsetDegrees, double distance )
335 // assumptions we model the standard service volume, plus
337 // altitude difference
338 // double alt = ( aircraftElev * SG_METER_TO_FEET - stationElev );
339 // double offset = fabs( offsetDegrees );
341 // if ( offset < 10 ) {
342 // return FG_ILS_DEFAULT_RANGE;
343 // } else if ( offset < 35 ) {
344 // return 10 + (35 - offset) * (FG_ILS_DEFAULT_RANGE - 10) / 25;
345 // } else if ( offset < 45 ) {
346 // return (45 - offset);
347 // } else if ( offset > 170 ) {
348 // return FG_ILS_DEFAULT_RANGE;
349 // } else if ( offset > 145 ) {
350 // return 10 + (offset - 145) * (FG_ILS_DEFAULT_RANGE - 10) / 25;
351 // } else if ( offset > 135 ) {
352 // return (offset - 135);
356 return FG_LOC_DEFAULT_RANGE;
360 //////////////////////////////////////////////////////////////////////////
361 // Update the various nav values based on position and valid tuned in navs
362 //////////////////////////////////////////////////////////////////////////
364 FGNavRadio::update(double dt)
370 // Create "formatted" versions of the nav frequencies for
371 // instrument displays.
373 sprintf( tmp, "%.2f", freq_node->getDoubleValue() );
374 fmt_freq_node->setStringValue(tmp);
375 sprintf( tmp, "%.2f", alt_freq_node->getDoubleValue() );
376 fmt_alt_freq_node->setStringValue(tmp);
378 if (power_btn_node->getBoolValue()
379 && (bus_power_node->getDoubleValue() > 1.0)
380 && nav_serviceable_node->getBoolValue() )
382 if (nav_slaved_to_gps_node->getBoolValue()) {
396 void FGNavRadio::clearOutputs()
398 inrange_node->setBoolValue( false );
399 cdi_deflection_node->setDoubleValue( 0.0 );
400 cdi_deflection_norm_node->setDoubleValue( 0.0 );
401 cdi_xtrack_error_node->setDoubleValue( 0.0 );
402 cdi_xtrack_hdg_err_node->setDoubleValue( 0.0 );
403 time_to_intercept->setDoubleValue( 0.0 );
404 gs_deflection_node->setDoubleValue( 0.0 );
405 gs_deflection_deg_node->setDoubleValue(0.0);
406 gs_deflection_norm_node->setDoubleValue(0.0);
407 gs_inrange_node->setBoolValue( false );
409 to_flag_node->setBoolValue( false );
410 from_flag_node->setBoolValue( false );
415 void FGNavRadio::updateReceiver(double dt)
417 // Do a nav station search only once a second to reduce
418 // unnecessary work. (Also, make sure to do this before caching
420 _time_before_search_sec -= dt;
421 if ( _time_before_search_sec < 0 ) {
426 _cdiDeflection = 0.0;
427 _cdiCrossTrackErrorM = 0.0;
428 _toFlag = _fromFlag = false;
429 _gsNeedleDeflection = 0.0;
430 _gsNeedleDeflectionNorm = 0.0;
431 inrange_node->setBoolValue(false);
435 SGGeod pos = SGGeod::fromDegFt(lon_node->getDoubleValue(),
436 lat_node->getDoubleValue(),
437 alt_node->getDoubleValue());
439 double nav_elev = _navaid->get_elev_ft();
440 SGVec3d aircraft = SGVec3d::fromGeod(pos);
441 double loc_dist = dist(aircraft, _navaid->cart());
442 loc_dist_node->setDoubleValue( loc_dist );
443 bool is_loc = loc_node->getBoolValue();
444 double signal_quality_norm = signal_quality_norm_node->getDoubleValue();
447 //////////////////////////////////////////////////////////
448 // compute forward and reverse wgs84 headings to localizer
449 //////////////////////////////////////////////////////////
451 SGGeodesy::inverse(pos, _navaid->geod(), hdg, az2, s);
452 heading_node->setDoubleValue(hdg);
453 double radial = az2 - twist;
454 double recip = radial + 180.0;
455 SG_NORMALIZE_RANGE(recip, 0.0, 360.0);
456 radial_node->setDoubleValue( radial );
457 recip_radial_node->setDoubleValue( recip );
459 //////////////////////////////////////////////////////////
460 // compute the target/selected radial in "true" heading
461 //////////////////////////////////////////////////////////
463 target_radial = sel_radial_node->getDoubleValue();
466 // VORs need twist (mag-var) added; ILS/LOCs don't but we set twist to 0.0
467 double trtrue = target_radial + twist;
468 SG_NORMALIZE_RANGE(trtrue, 0.0, 360.0);
469 target_radial_true_node->setDoubleValue( trtrue );
471 //////////////////////////////////////////////////////////
472 // adjust reception range for altitude
473 // FIXME: make sure we are using the navdata range now that
474 // it is valid in the data file
475 //////////////////////////////////////////////////////////
477 double offset = radial - target_radial;
478 SG_NORMALIZE_RANGE(offset, -180.0, 180.0);
480 = adjustILSRange( nav_elev, pos.getElevationM(), offset,
481 loc_dist * SG_METER_TO_NM );
484 = adjustNavRange( nav_elev, pos.getElevationM(), _navaid->get_range() );
487 double effective_range_m = effective_range * SG_NM_TO_METER;
489 //////////////////////////////////////////////////////////
490 // compute signal quality
491 // 100% within effective_range
492 // decreases 1/x^2 further out
493 //////////////////////////////////////////////////////////
494 double last_signal_quality_norm = signal_quality_norm;
496 if ( loc_dist < effective_range_m ) {
497 signal_quality_norm = 1.0;
499 double range_exceed_norm = loc_dist/effective_range_m;
500 signal_quality_norm = 1/(range_exceed_norm*range_exceed_norm);
503 signal_quality_norm = fgGetLowPass( last_signal_quality_norm,
504 signal_quality_norm, dt );
506 signal_quality_norm_node->setDoubleValue( signal_quality_norm );
507 bool inrange = signal_quality_norm > 0.2;
508 inrange_node->setBoolValue( inrange );
510 //////////////////////////////////////////////////////////
511 // compute to/from flag status
512 //////////////////////////////////////////////////////////
517 double offset = fabs(radial - target_radial);
518 _toFlag = (offset > 90.0 && offset < 270.0);
520 _fromFlag = !_toFlag;
522 _toFlag = _fromFlag = false;
526 double r = target_radial - radial;
527 SG_NORMALIZE_RANGE(r, -180.0, 180.0);
530 if (_falseCoursesEnabled) {
531 // The factor of 30.0 gives a period of 120 which gives us 3 cycles and six
532 // zeros i.e. six courses: one front course, one back course, and four
533 // false courses. Three of the six are reverse sensing.
534 _cdiDeflection = 30.0 * sawtooth(r / 30.0);
536 // no false courses, but we do need to create a back course
537 if (fabs(r) > 90.0) { // front course
538 _cdiDeflection = r - copysign(180.0, r);
540 _cdiDeflection = r; // back course
543 _cdiDeflection = -_cdiDeflection; // reverse for outbound radial
544 } // of false courses disabled
546 const double VOR_FULL_ARC = 20.0; // VOR is -10 .. 10 degree swing
547 _cdiDeflection *= VOR_FULL_ARC / _localizerWidth; // increased localiser sensitivity
549 if (backcourse_node->getBoolValue()) {
550 _cdiDeflection = -_cdiDeflection;
553 // handle the TO side of the VOR
554 if (fabs(r) > 90.0) {
555 r = ( r<0.0 ? -r-180.0 : -r+180.0 );
558 } // of non-localiser case
560 SG_CLAMP_RANGE(_cdiDeflection, -10.0, 10.0 );
561 _cdiDeflection *= signal_quality_norm;
563 // cross-track error (in metres)
564 _cdiCrossTrackErrorM = loc_dist * sin(r * SGD_DEGREES_TO_RADIANS);
566 updateGlideSlope(dt, aircraft, signal_quality_norm);
569 last_loc_dist = loc_dist;
572 void FGNavRadio::updateGlideSlope(double dt, const SGVec3d& aircraft, double signal_quality_norm)
574 _gsNeedleDeflection = 0.0;
575 if (!_gs || !inrange_node->getBoolValue()) {
576 gs_dist_node->setDoubleValue( 0.0 );
577 gs_inrange_node->setBoolValue(false);
581 double gsDist = dist(aircraft, _gsCart);
582 gs_dist_node->setDoubleValue(gsDist);
583 bool gsInRange = (gsDist < (_gs->get_range() * SG_NM_TO_METER));
584 gs_inrange_node->setBoolValue(gsInRange);
590 SGVec3d pos = aircraft - _gsCart; // relative vector from gs antenna to aircraft
591 // The positive GS axis points along the runway in the landing direction,
592 // toward the far end, not toward the approach area, so we need a - sign here:
593 double dot_h = -dot(pos, _gsAxis);
594 double dot_v = dot(pos, _gsVertical);
595 double angle = atan2(dot_v, dot_h) * SGD_RADIANS_TO_DEGREES;
596 double deflectionAngle = target_gs - angle;
598 if (_falseCoursesEnabled) {
599 // Construct false glideslopes. The scale factor of 1.5
600 // in the sawtooth gives a period of 6 degrees.
601 // There will be zeros at 3, 6r, 9, 12r et cetera
602 // where "r" indicates reverse sensing.
603 // This is is consistent with conventional pilot lore
604 // e.g. http://www.allstar.fiu.edu/aerojava/ILS.htm
605 // but inconsistent with
606 // http://www.freepatentsonline.com/3757338.html
608 // It may be that some of each exist.
609 if (deflectionAngle < 0) {
610 deflectionAngle = 1.5 * sawtooth(deflectionAngle / 1.5);
612 // no false GS below the true GS
616 _gsNeedleDeflection = deflectionAngle * 5.0;
617 _gsNeedleDeflection *= signal_quality_norm;
619 SG_CLAMP_RANGE(deflectionAngle, -0.7, 0.7);
620 _gsNeedleDeflectionNorm = (deflectionAngle / 0.7) * signal_quality_norm;
622 //////////////////////////////////////////////////////////
623 // Calculate desired rate of climb for intercepting the GS
624 //////////////////////////////////////////////////////////
625 double gs_diff = target_gs - angle;
626 // convert desired vertical path angle into a climb rate
627 double des_angle = angle - 10 * gs_diff;
629 // estimate horizontal speed towards ILS in meters per minute
630 double elapsedDistance = last_x - gsDist;
633 double new_vel = ( elapsedDistance / dt );
634 horiz_vel = 0.75 * horiz_vel + 0.25 * new_vel;
636 gs_rate_of_climb_node
637 ->setDoubleValue( -sin( des_angle * SGD_DEGREES_TO_RADIANS )
638 * horiz_vel * SG_METER_TO_FEET );
641 void FGNavRadio::updateDME(const SGVec3d& aircraft)
643 if (!_dme || !dme_serviceable_node->getBoolValue()) {
648 double dme_distance = dist(aircraft, _dme->cart());
649 _dmeInRange = (dme_distance < _dme->get_range() * SG_NM_TO_METER);
652 void FGNavRadio::updateGPSSlaved()
654 has_gs_node->setBoolValue(gps_has_gs_node->getBoolValue());
656 _toFlag = gps_to_flag_node->getBoolValue();
657 _fromFlag = gps_from_flag_node->getBoolValue();
659 bool gpsValid = (_toFlag | _fromFlag);
660 inrange_node->setBoolValue(gpsValid);
662 signal_quality_norm_node->setDoubleValue(0.0);
663 _cdiDeflection = 0.0;
664 _cdiCrossTrackErrorM = 0.0;
665 _gsNeedleDeflection = 0.0;
669 // this is unfortunate, but panel instruments use this value to decide
670 // if the navradio output is valid.
671 signal_quality_norm_node->setDoubleValue(1.0);
673 _cdiDeflection = gps_cdi_deflection_node->getDoubleValue();
674 // clmap to some range (+/- 10 degrees) as the regular deflection
675 SG_CLAMP_RANGE(_cdiDeflection, -10.0, 10.0 );
677 _cdiCrossTrackErrorM = gps_xtrack_error_nm_node->getDoubleValue() * SG_NM_TO_METER;
678 _gsNeedleDeflection = 0.0; // FIXME, supply this
680 double trtrue = gps_course_node->getDoubleValue() + _magvarNode->getDoubleValue();
681 SG_NORMALIZE_RANGE(trtrue, 0.0, 360.0);
682 target_radial_true_node->setDoubleValue( trtrue );
685 void FGNavRadio::updateCDI(double dt)
687 bool cdi_serviceable = cdi_serviceable_node->getBoolValue();
688 bool inrange = inrange_node->getBoolValue();
690 if (tofrom_serviceable_node->getBoolValue()) {
691 to_flag_node->setBoolValue(_toFlag);
692 from_flag_node->setBoolValue(_fromFlag);
694 to_flag_node->setBoolValue(false);
695 from_flag_node->setBoolValue(false);
698 if (!cdi_serviceable) {
699 _cdiDeflection = 0.0;
700 _cdiCrossTrackErrorM = 0.0;
703 cdi_deflection_node->setDoubleValue(_cdiDeflection);
704 cdi_deflection_norm_node->setDoubleValue(_cdiDeflection * 0.1);
705 cdi_xtrack_error_node->setDoubleValue(_cdiCrossTrackErrorM);
707 //////////////////////////////////////////////////////////
708 // compute an approximate ground track heading error
709 //////////////////////////////////////////////////////////
710 double hdg_error = 0.0;
711 if ( inrange && cdi_serviceable ) {
712 double vn = fgGetDouble( "/velocities/speed-north-fps" );
713 double ve = fgGetDouble( "/velocities/speed-east-fps" );
714 double gnd_trk_true = atan2( ve, vn ) * SGD_RADIANS_TO_DEGREES;
715 if ( gnd_trk_true < 0.0 ) { gnd_trk_true += 360.0; }
717 SGPropertyNode *true_hdg
718 = fgGetNode("/orientation/heading-deg", true);
719 hdg_error = gnd_trk_true - true_hdg->getDoubleValue();
721 // cout << "ground track = " << gnd_trk_true
722 // << " orientation = " << true_hdg->getDoubleValue() << endl;
724 cdi_xtrack_hdg_err_node->setDoubleValue( hdg_error );
726 //////////////////////////////////////////////////////////
727 // Calculate a suggested target heading to smoothly intercept
729 //////////////////////////////////////////////////////////
731 // Now that we have cross track heading adjustment built in,
732 // we shouldn't need to overdrive the heading angle within 8km
735 // The cdi deflection should be +/-10 for a full range of deflection
736 // so multiplying this by 3 gives us +/- 30 degrees heading
738 double adjustment = _cdiDeflection * 3.0;
739 SG_CLAMP_RANGE( adjustment, -30.0, 30.0 );
741 // determine the target heading to fly to intercept the
742 // tgt_radial = target radial (true) + cdi offset adjustmest -
743 // xtrack heading error adjustment
745 double trtrue = target_radial_true_node->getDoubleValue();
746 if ( loc_node->getBoolValue() && backcourse_node->getBoolValue() ) {
747 // tuned to a localizer and backcourse mode activated
748 trtrue += 180.0; // reverse the target localizer heading
749 SG_NORMALIZE_RANGE(trtrue, 0.0, 360.0);
750 nta_hdg = trtrue - adjustment - hdg_error;
752 nta_hdg = trtrue + adjustment - hdg_error;
755 SG_NORMALIZE_RANGE(nta_hdg, 0.0, 360.0);
756 target_auto_hdg_node->setDoubleValue( nta_hdg );
758 //////////////////////////////////////////////////////////
759 // compute the time to intercept selected radial (based on
760 // current and last cross track errors and dt
761 //////////////////////////////////////////////////////////
763 if ( inrange && cdi_serviceable ) {
764 double cur_rate = (last_xtrack_error - _cdiCrossTrackErrorM) / dt;
765 xrate_ms = 0.99 * xrate_ms + 0.01 * cur_rate;
766 if ( fabs(xrate_ms) > 0.00001 ) {
767 t = _cdiCrossTrackErrorM / xrate_ms;
772 time_to_intercept->setDoubleValue( t );
774 if (!gs_serviceable_node->getBoolValue() ) {
775 _gsNeedleDeflection = 0.0;
776 _gsNeedleDeflectionNorm = 0.0;
778 gs_deflection_node->setDoubleValue(_gsNeedleDeflection);
779 gs_deflection_deg_node->setDoubleValue(_gsNeedleDeflectionNorm * 0.7);
780 gs_deflection_norm_node->setDoubleValue(_gsNeedleDeflectionNorm);
782 last_xtrack_error = _cdiCrossTrackErrorM;
785 void FGNavRadio::updateAudio()
787 if (!_navaid || !inrange_node->getBoolValue() || !nav_serviceable_node->getBoolValue()) {
791 // play station ident via audio system if on + ident,
792 // otherwise turn it off
793 if (!power_btn_node->getBoolValue()
794 || !(bus_power_node->getDoubleValue() > 1.0)
795 || !ident_btn_node->getBoolValue()
796 || !audio_btn_node->getBoolValue() ) {
797 globals->get_soundmgr()->stop( nav_fx_name );
798 globals->get_soundmgr()->stop( dme_fx_name );
802 SGSoundSample *sound = globals->get_soundmgr()->find( nav_fx_name );
803 double vol = vol_btn_node->getDoubleValue();
804 SG_CLAMP_RANGE(vol, 0.0, 1.0);
806 if ( sound != NULL ) {
807 sound->set_volume( vol );
809 SG_LOG( SG_COCKPIT, SG_ALERT, "Can't find nav-vor-ident sound" );
812 sound = globals->get_soundmgr()->find( dme_fx_name );
813 if ( sound != NULL ) {
814 sound->set_volume( vol );
816 SG_LOG( SG_COCKPIT, SG_ALERT, "Can't find nav-dme-ident sound" );
819 const int NUM_IDENT_SLOTS = 5;
820 const time_t SLOT_LENGTH = 5; // seconds
822 // There are N slots numbered 0 through (NUM_IDENT_SLOTS-1) inclusive.
823 // Each slot is 5 seconds long.
824 // Slots 0 is for DME
825 // the rest are for azimuth.
826 time_t now = globals->get_time_params()->get_cur_time();
827 if ((now >= last_time) && (now < last_time + SLOT_LENGTH)) {
828 return; // wait longer
832 play_count = ++play_count % NUM_IDENT_SLOTS;
834 // Previous ident is out of time; if still playing, cut it off:
835 globals->get_soundmgr()->stop( nav_fx_name );
836 globals->get_soundmgr()->stop( dme_fx_name );
837 if (play_count == 0) { // the DME slot
838 if (_dmeInRange && dme_serviceable_node->getBoolValue()) {
840 globals->get_soundmgr()->play_once( dme_fx_name );
843 if (inrange_node->getBoolValue() && nav_serviceable_node->getBoolValue()) {
844 globals->get_soundmgr()->play_once(nav_fx_name);
849 FGNavRecord* FGNavRadio::findPrimaryNavaid(const SGGeod& aPos, double aFreqMHz)
851 FGNavRecord* nav = globals->get_navlist()->findByFreq(aFreqMHz, aPos);
856 return globals->get_loclist()->findByFreq(aFreqMHz, aPos);
859 // Update current nav/adf radio stations based on current postition
860 void FGNavRadio::search()
862 _time_before_search_sec = 1.0;
863 SGGeod pos = SGGeod::fromDegFt(lon_node->getDoubleValue(),
864 lat_node->getDoubleValue(), alt_node->getDoubleValue());
865 double freq = freq_node->getDoubleValue();
867 FGNavRecord* nav = findPrimaryNavaid(pos, freq);
868 if (nav == _navaid) {
869 return; // found the same as last search, we're done
873 char identBuffer[5] = " ";
875 _dme = globals->get_dmelist()->findByFreq(freq, pos);
877 nav_id_node->setStringValue(nav->get_ident());
878 strncpy(identBuffer, nav->ident().c_str(), 5);
880 effective_range = adjustNavRange(nav->get_elev_ft(), pos.getElevationM(), nav->get_range());
881 loc_node->setBoolValue(nav->type() != FGPositioned::VOR);
882 twist = nav->get_multiuse();
884 if (nav->type() == FGPositioned::VOR) {
885 target_radial = sel_radial_node->getDoubleValue();
887 has_gs_node->setBoolValue(false);
888 } else { // ILS or LOC
889 _gs = globals->get_gslist()->findByFreq(freq, pos);
890 has_gs_node->setBoolValue(_gs != NULL);
891 _localizerWidth = localizerWidth(nav);
893 effective_range = nav->get_range();
895 target_radial = nav->get_multiuse();
896 SG_NORMALIZE_RANGE(target_radial, 0.0, 360.0);
899 int tmp = (int)(_gs->get_multiuse() / 1000.0);
900 target_gs = (double)tmp / 100.0;
902 // until penaltyForNav goes away, we cannot assume we always pick
903 // paired LOC/GS trasmsitters. As we pass over a runway threshold, we
904 // often end up picking the 'wrong' LOC, but the correct GS. To avoid
905 // breaking the basis computation, ensure we use the GS radial and not
906 // the (potentially reversed) LOC radial.
907 double gs_radial = fmod(_gs->get_multiuse(), 1000.0);
908 SG_NORMALIZE_RANGE(gs_radial, 0.0, 360.0);
910 // GS axis unit tangent vector
911 // (along the runway)
912 _gsCart = _gs->cart();
913 _gsAxis = tangentVector(_gs->geod(), _gsCart, gs_radial);
915 // GS baseline unit tangent vector
916 // (perpendicular to the runay along the ground)
917 SGVec3d baseline = tangentVector(_gs->geod(), _gsCart, gs_radial + 90.0);
918 _gsVertical = cross(baseline, _gsAxis);
919 } // of have glideslope
920 } // of found LOC or ILS
923 } else { // found nothing
926 nav_id_node->setStringValue("");
927 globals->get_soundmgr()->remove( nav_fx_name );
928 globals->get_soundmgr()->remove( dme_fx_name );
931 is_valid_node->setBoolValue(nav != NULL);
932 id_c1_node->setIntValue( (int)identBuffer[0] );
933 id_c2_node->setIntValue( (int)identBuffer[1] );
934 id_c3_node->setIntValue( (int)identBuffer[2] );
935 id_c4_node->setIntValue( (int)identBuffer[3] );
938 double FGNavRadio::localizerWidth(FGNavRecord* aLOC)
940 FGRunway* rwy = aLOC->runway();
943 SGVec3d thresholdCart(SGVec3d::fromGeod(rwy->threshold()));
944 double axisLength = dist(aLOC->cart(), thresholdCart);
945 double landingLength = dist(thresholdCart, SGVec3d::fromGeod(rwy->end()));
947 // Reference: http://dcaa.slv.dk:8000/icaodocs/
948 // ICAO standard width at threshold is 210 m = 689 feet = approx 700 feet.
949 // ICAO 3.1.1 half course = DDM = 0.0775
950 // ICAO 3.1.3.7.1 Sensitivity 0.00145 DDM/m at threshold
951 // implies peg-to-peg of 214 m ... we will stick with 210.
952 // ICAO 3.1.3.7.1 "Course sector angle shall not exceed 6 degrees."
954 // Very short runway: less than 1200 m (4000 ft) landing length:
955 if (landingLength < 1200.0) {
956 // ICAO fudges localizer sensitivity for very short runways.
957 // This produces a non-monotonic sensitivity-versus length relation.
958 axisLength += 1050.0;
961 // Example: very short: San Diego KMYF (Montgomery Field) ILS RWY 28R
962 // Example: short: Tom's River KMJX (Robert J. Miller) ILS RWY 6
963 // Example: very long: Denver KDEN (Denver) ILS RWY 16R
964 double raw_width = 210.0 / axisLength * SGD_RADIANS_TO_DEGREES;
965 return raw_width < 6.0? raw_width : 6.0;
968 void FGNavRadio::audioNavidChanged()
970 if ( globals->get_soundmgr()->exists(nav_fx_name)) {
971 globals->get_soundmgr()->remove(nav_fx_name);
975 string trans_ident(_navaid->get_trans_ident());
976 SGSoundSample* sound = morse.make_ident(trans_ident, LO_FREQUENCY);
977 sound->set_volume( 0.3 );
978 if (!globals->get_soundmgr()->add( sound, nav_fx_name )) {
979 SG_LOG(SG_COCKPIT, SG_WARN, "Failed to add v1-vor-ident sound");
982 if ( globals->get_soundmgr()->exists( dme_fx_name ) ) {
983 globals->get_soundmgr()->remove( dme_fx_name );
986 sound = morse.make_ident( trans_ident, HI_FREQUENCY );
987 sound->set_volume( 0.3 );
988 globals->get_soundmgr()->add( sound, dme_fx_name );
990 int offset = (int)(sg_random() * 30.0);
991 play_count = offset / 4;
992 last_time = globals->get_time_params()->get_cur_time() - offset;
993 } catch (sg_io_exception& e) {
994 SG_LOG(SG_GENERAL, SG_ALERT, e.getFormattedMessage());