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),
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()
187 SGSoundMgr *smgr = globals->get_soundmgr();
188 _sgr = smgr->find("avionics", true);
189 _sgr->tie_to_listener();
194 branch = "/instrumentation/" + _name;
196 SGPropertyNode *node = fgGetNode(branch.c_str(), _num, true );
199 fgGetNode(("/systems/electrical/outputs/" + _name).c_str(), true);
202 is_valid_node = node->getChild("data-is-valid", 0, true);
203 power_btn_node = node->getChild("power-btn", 0, true);
204 power_btn_node->setBoolValue( true );
205 vol_btn_node = node->getChild("volume", 0, true);
206 ident_btn_node = node->getChild("ident", 0, true);
207 ident_btn_node->setBoolValue( true );
208 audio_btn_node = node->getChild("audio-btn", 0, true);
209 audio_btn_node->setBoolValue( true );
210 backcourse_node = node->getChild("back-course-btn", 0, true);
211 backcourse_node->setBoolValue( false );
213 nav_serviceable_node = node->getChild("serviceable", 0, true);
214 cdi_serviceable_node = createServiceableProp(node, "cdi");
215 gs_serviceable_node = createServiceableProp(node, "gs");
216 tofrom_serviceable_node = createServiceableProp(node, "to-from");
217 dme_serviceable_node = createServiceableProp(node, "dme");
219 falseCoursesEnabledNode =
220 fgGetNode("/sim/realism/false-radio-courses-enabled");
221 if (!falseCoursesEnabledNode) {
222 falseCoursesEnabledNode =
223 fgGetNode("/sim/realism/false-radio-courses-enabled", true);
224 falseCoursesEnabledNode->setBoolValue(true);
228 SGPropertyNode *subnode = node->getChild("frequencies", 0, true);
229 freq_node = subnode->getChild("selected-mhz", 0, true);
230 alt_freq_node = subnode->getChild("standby-mhz", 0, true);
231 fmt_freq_node = subnode->getChild("selected-mhz-fmt", 0, true);
232 fmt_alt_freq_node = subnode->getChild("standby-mhz-fmt", 0, true);
235 subnode = node->getChild("radials", 0, true);
236 sel_radial_node = subnode->getChild("selected-deg", 0, true);
237 radial_node = subnode->getChild("actual-deg", 0, true);
238 recip_radial_node = subnode->getChild("reciprocal-radial-deg", 0, true);
239 target_radial_true_node = subnode->getChild("target-radial-deg", 0, true);
240 target_auto_hdg_node = subnode->getChild("target-auto-hdg-deg", 0, true);
243 heading_node = node->getChild("heading-deg", 0, true);
244 time_to_intercept = node->getChild("time-to-intercept-sec", 0, true);
245 to_flag_node = node->getChild("to-flag", 0, true);
246 from_flag_node = node->getChild("from-flag", 0, true);
247 inrange_node = node->getChild("in-range", 0, true);
248 signal_quality_norm_node = node->getChild("signal-quality-norm", 0, true);
249 cdi_deflection_node = node->getChild("heading-needle-deflection", 0, true);
250 cdi_deflection_norm_node = node->getChild("heading-needle-deflection-norm", 0, true);
251 cdi_xtrack_error_node = node->getChild("crosstrack-error-m", 0, true);
252 cdi_xtrack_hdg_err_node
253 = node->getChild("crosstrack-heading-error-deg", 0, true);
254 has_gs_node = node->getChild("has-gs", 0, true);
255 loc_node = node->getChild("nav-loc", 0, true);
256 loc_dist_node = node->getChild("nav-distance", 0, true);
257 gs_deflection_node = node->getChild("gs-needle-deflection", 0, true);
258 gs_deflection_deg_node = node->getChild("gs-needle-deflection-deg", 0, true);
259 gs_deflection_norm_node = node->getChild("gs-needle-deflection-norm", 0, true);
260 gs_rate_of_climb_node = node->getChild("gs-rate-of-climb", 0, true);
261 gs_dist_node = node->getChild("gs-distance", 0, true);
262 gs_inrange_node = node->getChild("gs-in-range", 0, true);
264 nav_id_node = node->getChild("nav-id", 0, true);
265 id_c1_node = node->getChild("nav-id_asc1", 0, true);
266 id_c2_node = node->getChild("nav-id_asc2", 0, true);
267 id_c3_node = node->getChild("nav-id_asc3", 0, true);
268 id_c4_node = node->getChild("nav-id_asc4", 0, true);
270 node->tie("dme-in-range", SGRawValuePointer<bool>(&_dmeInRange));
272 // gps slaving support
273 nav_slaved_to_gps_node = node->getChild("slaved-to-gps", 0, true);
274 gps_cdi_deflection_node = fgGetNode("/instrumentation/gps/cdi-deflection", true);
275 gps_to_flag_node = fgGetNode("/instrumentation/gps/to-flag", true);
276 gps_from_flag_node = fgGetNode("/instrumentation/gps/from-flag", true);
277 gps_has_gs_node = fgGetNode("/instrumentation/gps/has-gs", true);
278 gps_course_node = fgGetNode("/instrumentation/gps/selected-course-deg", true);
279 gps_xtrack_error_nm_node = fgGetNode("/instrumentation/gps/wp/wp[1]/course-error-nm", true);
280 _magvarNode = fgGetNode("/environment/magnetic-variation-deg", true);
282 std::ostringstream temp;
283 temp << _name << "nav-ident" << _num;
284 nav_fx_name = temp.str();
285 temp << _name << "dme-ident" << _num;
286 dme_fx_name = temp.str();
297 FGNavRadio::unbind ()
302 // model standard VOR/DME/TACAN service volumes as per AIM 1-1-8
303 double FGNavRadio::adjustNavRange( double stationElev, double aircraftElev,
304 double nominalRange )
306 if (nominalRange <= 0.0) {
307 nominalRange = FG_NAV_DEFAULT_RANGE;
310 // extend out actual usable range to be 1.3x the published safe range
311 const double usability_factor = 1.3;
313 // assumptions we model the standard service volume, plus
314 // ... rather than specifying a cylinder, we model a cone that
315 // contains the cylinder. Then we put an upside down cone on top
316 // to model diminishing returns at too-high altitudes.
318 // altitude difference
319 double alt = ( aircraftElev * SG_METER_TO_FEET - stationElev );
320 // cout << "aircraft elev = " << aircraftElev * SG_METER_TO_FEET
321 // << " station elev = " << stationElev << endl;
323 if ( nominalRange < 25.0 + SG_EPSILON ) {
324 // Standard Terminal Service Volume
325 return term_tbl->interpolate( alt ) * usability_factor;
326 } else if ( nominalRange < 50.0 + SG_EPSILON ) {
327 // Standard Low Altitude Service Volume
328 // table is based on range of 40, scale to actual range
329 return low_tbl->interpolate( alt ) * nominalRange / 40.0
332 // Standard High Altitude Service Volume
333 // table is based on range of 130, scale to actual range
334 return high_tbl->interpolate( alt ) * nominalRange / 130.0
340 // model standard ILS service volumes as per AIM 1-1-9
341 double FGNavRadio::adjustILSRange( double stationElev, double aircraftElev,
342 double offsetDegrees, double distance )
344 // assumptions we model the standard service volume, plus
346 // altitude difference
347 // double alt = ( aircraftElev * SG_METER_TO_FEET - stationElev );
348 // double offset = fabs( offsetDegrees );
350 // if ( offset < 10 ) {
351 // return FG_ILS_DEFAULT_RANGE;
352 // } else if ( offset < 35 ) {
353 // return 10 + (35 - offset) * (FG_ILS_DEFAULT_RANGE - 10) / 25;
354 // } else if ( offset < 45 ) {
355 // return (45 - offset);
356 // } else if ( offset > 170 ) {
357 // return FG_ILS_DEFAULT_RANGE;
358 // } else if ( offset > 145 ) {
359 // return 10 + (offset - 145) * (FG_ILS_DEFAULT_RANGE - 10) / 25;
360 // } else if ( offset > 135 ) {
361 // return (offset - 135);
365 return FG_LOC_DEFAULT_RANGE;
369 //////////////////////////////////////////////////////////////////////////
370 // Update the various nav values based on position and valid tuned in navs
371 //////////////////////////////////////////////////////////////////////////
373 FGNavRadio::update(double dt)
379 // Create "formatted" versions of the nav frequencies for
380 // instrument displays.
382 sprintf( tmp, "%.2f", freq_node->getDoubleValue() );
383 fmt_freq_node->setStringValue(tmp);
384 sprintf( tmp, "%.2f", alt_freq_node->getDoubleValue() );
385 fmt_alt_freq_node->setStringValue(tmp);
387 if (power_btn_node->getBoolValue()
388 && (bus_power_node->getDoubleValue() > 1.0)
389 && nav_serviceable_node->getBoolValue() )
391 if (nav_slaved_to_gps_node->getBoolValue()) {
405 void FGNavRadio::clearOutputs()
407 inrange_node->setBoolValue( false );
408 cdi_deflection_node->setDoubleValue( 0.0 );
409 cdi_deflection_norm_node->setDoubleValue( 0.0 );
410 cdi_xtrack_error_node->setDoubleValue( 0.0 );
411 cdi_xtrack_hdg_err_node->setDoubleValue( 0.0 );
412 time_to_intercept->setDoubleValue( 0.0 );
413 gs_deflection_node->setDoubleValue( 0.0 );
414 gs_deflection_deg_node->setDoubleValue(0.0);
415 gs_deflection_norm_node->setDoubleValue(0.0);
416 gs_inrange_node->setBoolValue( false );
418 to_flag_node->setBoolValue( false );
419 from_flag_node->setBoolValue( false );
424 void FGNavRadio::updateReceiver(double dt)
426 // Do a nav station search only once a second to reduce
427 // unnecessary work. (Also, make sure to do this before caching
429 _time_before_search_sec -= dt;
430 if ( _time_before_search_sec < 0 ) {
435 _cdiDeflection = 0.0;
436 _cdiCrossTrackErrorM = 0.0;
437 _toFlag = _fromFlag = false;
438 _gsNeedleDeflection = 0.0;
439 _gsNeedleDeflectionNorm = 0.0;
440 inrange_node->setBoolValue(false);
444 SGGeod pos = SGGeod::fromDegFt(lon_node->getDoubleValue(),
445 lat_node->getDoubleValue(),
446 alt_node->getDoubleValue());
448 double nav_elev = _navaid->get_elev_ft();
449 SGVec3d aircraft = SGVec3d::fromGeod(pos);
450 double loc_dist = dist(aircraft, _navaid->cart());
451 loc_dist_node->setDoubleValue( loc_dist );
452 bool is_loc = loc_node->getBoolValue();
453 double signal_quality_norm = signal_quality_norm_node->getDoubleValue();
456 //////////////////////////////////////////////////////////
457 // compute forward and reverse wgs84 headings to localizer
458 //////////////////////////////////////////////////////////
460 SGGeodesy::inverse(pos, _navaid->geod(), hdg, az2, s);
461 heading_node->setDoubleValue(hdg);
462 double radial = az2 - twist;
463 double recip = radial + 180.0;
464 SG_NORMALIZE_RANGE(recip, 0.0, 360.0);
465 radial_node->setDoubleValue( radial );
466 recip_radial_node->setDoubleValue( recip );
468 //////////////////////////////////////////////////////////
469 // compute the target/selected radial in "true" heading
470 //////////////////////////////////////////////////////////
472 target_radial = sel_radial_node->getDoubleValue();
475 // VORs need twist (mag-var) added; ILS/LOCs don't but we set twist to 0.0
476 double trtrue = target_radial + twist;
477 SG_NORMALIZE_RANGE(trtrue, 0.0, 360.0);
478 target_radial_true_node->setDoubleValue( trtrue );
480 //////////////////////////////////////////////////////////
481 // adjust reception range for altitude
482 // FIXME: make sure we are using the navdata range now that
483 // it is valid in the data file
484 //////////////////////////////////////////////////////////
486 double offset = radial - target_radial;
487 SG_NORMALIZE_RANGE(offset, -180.0, 180.0);
489 = adjustILSRange( nav_elev, pos.getElevationM(), offset,
490 loc_dist * SG_METER_TO_NM );
493 = adjustNavRange( nav_elev, pos.getElevationM(), _navaid->get_range() );
496 double effective_range_m = effective_range * SG_NM_TO_METER;
498 //////////////////////////////////////////////////////////
499 // compute signal quality
500 // 100% within effective_range
501 // decreases 1/x^2 further out
502 //////////////////////////////////////////////////////////
503 double last_signal_quality_norm = signal_quality_norm;
505 if ( loc_dist < effective_range_m ) {
506 signal_quality_norm = 1.0;
508 double range_exceed_norm = loc_dist/effective_range_m;
509 signal_quality_norm = 1/(range_exceed_norm*range_exceed_norm);
512 signal_quality_norm = fgGetLowPass( last_signal_quality_norm,
513 signal_quality_norm, dt );
515 signal_quality_norm_node->setDoubleValue( signal_quality_norm );
516 bool inrange = signal_quality_norm > 0.2;
517 inrange_node->setBoolValue( inrange );
519 //////////////////////////////////////////////////////////
520 // compute to/from flag status
521 //////////////////////////////////////////////////////////
526 double offset = fabs(radial - target_radial);
527 _toFlag = (offset > 90.0 && offset < 270.0);
529 _fromFlag = !_toFlag;
531 _toFlag = _fromFlag = false;
535 double r = target_radial - radial;
536 SG_NORMALIZE_RANGE(r, -180.0, 180.0);
539 if (falseCoursesEnabledNode->getBoolValue()) {
540 // The factor of 30.0 gives a period of 120 which gives us 3 cycles and six
541 // zeros i.e. six courses: one front course, one back course, and four
542 // false courses. Three of the six are reverse sensing.
543 _cdiDeflection = 30.0 * sawtooth(r / 30.0);
545 // no false courses, but we do need to create a back course
546 if (fabs(r) > 90.0) { // front course
547 _cdiDeflection = r - copysign(180.0, r);
549 _cdiDeflection = r; // back course
552 _cdiDeflection = -_cdiDeflection; // reverse for outbound radial
553 } // of false courses disabled
555 const double VOR_FULL_ARC = 20.0; // VOR is -10 .. 10 degree swing
556 _cdiDeflection *= VOR_FULL_ARC / _localizerWidth; // increased localiser sensitivity
558 if (backcourse_node->getBoolValue()) {
559 _cdiDeflection = -_cdiDeflection;
562 // handle the TO side of the VOR
563 if (fabs(r) > 90.0) {
564 r = ( r<0.0 ? -r-180.0 : -r+180.0 );
567 } // of non-localiser case
569 SG_CLAMP_RANGE(_cdiDeflection, -10.0, 10.0 );
570 _cdiDeflection *= signal_quality_norm;
572 // cross-track error (in metres)
573 _cdiCrossTrackErrorM = loc_dist * sin(r * SGD_DEGREES_TO_RADIANS);
575 updateGlideSlope(dt, aircraft, signal_quality_norm);
578 last_loc_dist = loc_dist;
581 void FGNavRadio::updateGlideSlope(double dt, const SGVec3d& aircraft, double signal_quality_norm)
583 _gsNeedleDeflection = 0.0;
584 if (!_gs || !inrange_node->getBoolValue()) {
585 gs_dist_node->setDoubleValue( 0.0 );
586 gs_inrange_node->setBoolValue(false);
587 _gsNeedleDeflection = 0.0;
588 _gsNeedleDeflectionNorm = 0.0;
592 double gsDist = dist(aircraft, _gsCart);
593 gs_dist_node->setDoubleValue(gsDist);
594 bool gsInRange = (gsDist < (_gs->get_range() * SG_NM_TO_METER));
595 gs_inrange_node->setBoolValue(gsInRange);
598 _gsNeedleDeflection = 0.0;
599 _gsNeedleDeflectionNorm = 0.0;
603 SGVec3d pos = aircraft - _gsCart; // relative vector from gs antenna to aircraft
604 // The positive GS axis points along the runway in the landing direction,
605 // toward the far end, not toward the approach area, so we need a - sign here:
606 double dot_h = -dot(pos, _gsAxis);
607 double dot_v = dot(pos, _gsVertical);
608 double angle = atan2(dot_v, dot_h) * SGD_RADIANS_TO_DEGREES;
609 double deflectionAngle = target_gs - angle;
611 if (falseCoursesEnabledNode->getBoolValue()) {
612 // Construct false glideslopes. The scale factor of 1.5
613 // in the sawtooth gives a period of 6 degrees.
614 // There will be zeros at 3, 6r, 9, 12r et cetera
615 // where "r" indicates reverse sensing.
616 // This is is consistent with conventional pilot lore
617 // e.g. http://www.allstar.fiu.edu/aerojava/ILS.htm
618 // but inconsistent with
619 // http://www.freepatentsonline.com/3757338.html
621 // It may be that some of each exist.
622 if (deflectionAngle < 0) {
623 deflectionAngle = 1.5 * sawtooth(deflectionAngle / 1.5);
625 // no false GS below the true GS
629 _gsNeedleDeflection = deflectionAngle * 5.0;
630 _gsNeedleDeflection *= signal_quality_norm;
632 SG_CLAMP_RANGE(deflectionAngle, -0.7, 0.7);
633 _gsNeedleDeflectionNorm = (deflectionAngle / 0.7) * signal_quality_norm;
635 //////////////////////////////////////////////////////////
636 // Calculate desired rate of climb for intercepting the GS
637 //////////////////////////////////////////////////////////
638 double gs_diff = target_gs - angle;
639 // convert desired vertical path angle into a climb rate
640 double des_angle = angle - 10 * gs_diff;
642 // estimate horizontal speed towards ILS in meters per minute
643 double elapsedDistance = last_x - gsDist;
646 double new_vel = ( elapsedDistance / dt );
647 horiz_vel = 0.75 * horiz_vel + 0.25 * new_vel;
649 gs_rate_of_climb_node
650 ->setDoubleValue( -sin( des_angle * SGD_DEGREES_TO_RADIANS )
651 * horiz_vel * SG_METER_TO_FEET );
654 void FGNavRadio::updateDME(const SGVec3d& aircraft)
656 if (!_dme || !dme_serviceable_node->getBoolValue()) {
661 double dme_distance = dist(aircraft, _dme->cart());
662 _dmeInRange = (dme_distance < _dme->get_range() * SG_NM_TO_METER);
665 void FGNavRadio::updateGPSSlaved()
667 has_gs_node->setBoolValue(gps_has_gs_node->getBoolValue());
669 _toFlag = gps_to_flag_node->getBoolValue();
670 _fromFlag = gps_from_flag_node->getBoolValue();
672 bool gpsValid = (_toFlag | _fromFlag);
673 inrange_node->setBoolValue(gpsValid);
675 signal_quality_norm_node->setDoubleValue(0.0);
676 _cdiDeflection = 0.0;
677 _cdiCrossTrackErrorM = 0.0;
678 _gsNeedleDeflection = 0.0;
682 // this is unfortunate, but panel instruments use this value to decide
683 // if the navradio output is valid.
684 signal_quality_norm_node->setDoubleValue(1.0);
686 _cdiDeflection = gps_cdi_deflection_node->getDoubleValue();
687 // clmap to some range (+/- 10 degrees) as the regular deflection
688 SG_CLAMP_RANGE(_cdiDeflection, -10.0, 10.0 );
690 _cdiCrossTrackErrorM = gps_xtrack_error_nm_node->getDoubleValue() * SG_NM_TO_METER;
691 _gsNeedleDeflection = 0.0; // FIXME, supply this
693 double trtrue = gps_course_node->getDoubleValue() + _magvarNode->getDoubleValue();
694 SG_NORMALIZE_RANGE(trtrue, 0.0, 360.0);
695 target_radial_true_node->setDoubleValue( trtrue );
698 void FGNavRadio::updateCDI(double dt)
700 bool cdi_serviceable = cdi_serviceable_node->getBoolValue();
701 bool inrange = inrange_node->getBoolValue();
703 if (tofrom_serviceable_node->getBoolValue()) {
704 to_flag_node->setBoolValue(_toFlag);
705 from_flag_node->setBoolValue(_fromFlag);
707 to_flag_node->setBoolValue(false);
708 from_flag_node->setBoolValue(false);
711 if (!cdi_serviceable) {
712 _cdiDeflection = 0.0;
713 _cdiCrossTrackErrorM = 0.0;
716 cdi_deflection_node->setDoubleValue(_cdiDeflection);
717 cdi_deflection_norm_node->setDoubleValue(_cdiDeflection * 0.1);
718 cdi_xtrack_error_node->setDoubleValue(_cdiCrossTrackErrorM);
720 //////////////////////////////////////////////////////////
721 // compute an approximate ground track heading error
722 //////////////////////////////////////////////////////////
723 double hdg_error = 0.0;
724 if ( inrange && cdi_serviceable ) {
725 double vn = fgGetDouble( "/velocities/speed-north-fps" );
726 double ve = fgGetDouble( "/velocities/speed-east-fps" );
727 double gnd_trk_true = atan2( ve, vn ) * SGD_RADIANS_TO_DEGREES;
728 if ( gnd_trk_true < 0.0 ) { gnd_trk_true += 360.0; }
730 SGPropertyNode *true_hdg
731 = fgGetNode("/orientation/heading-deg", true);
732 hdg_error = gnd_trk_true - true_hdg->getDoubleValue();
734 // cout << "ground track = " << gnd_trk_true
735 // << " orientation = " << true_hdg->getDoubleValue() << endl;
737 cdi_xtrack_hdg_err_node->setDoubleValue( hdg_error );
739 //////////////////////////////////////////////////////////
740 // Calculate a suggested target heading to smoothly intercept
742 //////////////////////////////////////////////////////////
744 // Now that we have cross track heading adjustment built in,
745 // we shouldn't need to overdrive the heading angle within 8km
748 // The cdi deflection should be +/-10 for a full range of deflection
749 // so multiplying this by 3 gives us +/- 30 degrees heading
751 double adjustment = _cdiDeflection * 3.0;
752 SG_CLAMP_RANGE( adjustment, -30.0, 30.0 );
754 // determine the target heading to fly to intercept the
755 // tgt_radial = target radial (true) + cdi offset adjustmest -
756 // xtrack heading error adjustment
758 double trtrue = target_radial_true_node->getDoubleValue();
759 if ( loc_node->getBoolValue() && backcourse_node->getBoolValue() ) {
760 // tuned to a localizer and backcourse mode activated
761 trtrue += 180.0; // reverse the target localizer heading
762 SG_NORMALIZE_RANGE(trtrue, 0.0, 360.0);
763 nta_hdg = trtrue - adjustment - hdg_error;
765 nta_hdg = trtrue + adjustment - hdg_error;
768 SG_NORMALIZE_RANGE(nta_hdg, 0.0, 360.0);
769 target_auto_hdg_node->setDoubleValue( nta_hdg );
771 //////////////////////////////////////////////////////////
772 // compute the time to intercept selected radial (based on
773 // current and last cross track errors and dt
774 //////////////////////////////////////////////////////////
776 if ( inrange && cdi_serviceable ) {
777 double cur_rate = (last_xtrack_error - _cdiCrossTrackErrorM) / dt;
778 xrate_ms = 0.99 * xrate_ms + 0.01 * cur_rate;
779 if ( fabs(xrate_ms) > 0.00001 ) {
780 t = _cdiCrossTrackErrorM / xrate_ms;
785 time_to_intercept->setDoubleValue( t );
787 if (!gs_serviceable_node->getBoolValue() ) {
788 _gsNeedleDeflection = 0.0;
789 _gsNeedleDeflectionNorm = 0.0;
791 gs_deflection_node->setDoubleValue(_gsNeedleDeflection);
792 gs_deflection_deg_node->setDoubleValue(_gsNeedleDeflectionNorm * 0.7);
793 gs_deflection_norm_node->setDoubleValue(_gsNeedleDeflectionNorm);
795 last_xtrack_error = _cdiCrossTrackErrorM;
798 void FGNavRadio::updateAudio()
800 if (!_navaid || !inrange_node->getBoolValue() || !nav_serviceable_node->getBoolValue()) {
804 // play station ident via audio system if on + ident,
805 // otherwise turn it off
806 if (!power_btn_node->getBoolValue()
807 || !(bus_power_node->getDoubleValue() > 1.0)
808 || !ident_btn_node->getBoolValue()
809 || !audio_btn_node->getBoolValue() ) {
810 _sgr->stop( nav_fx_name );
811 _sgr->stop( dme_fx_name );
815 SGSoundSample *sound = _sgr->find( nav_fx_name );
816 double vol = vol_btn_node->getFloatValue();
817 SG_CLAMP_RANGE(vol, 0.0, 1.0);
819 if ( sound != NULL ) {
820 sound->set_volume( vol );
822 SG_LOG( SG_COCKPIT, SG_ALERT, "Can't find nav-vor-ident sound" );
825 sound = _sgr->find( dme_fx_name );
826 if ( sound != NULL ) {
827 sound->set_volume( vol );
829 SG_LOG( SG_COCKPIT, SG_ALERT, "Can't find nav-dme-ident sound" );
832 const int NUM_IDENT_SLOTS = 5;
833 const time_t SLOT_LENGTH = 5; // seconds
835 // There are N slots numbered 0 through (NUM_IDENT_SLOTS-1) inclusive.
836 // Each slot is 5 seconds long.
837 // Slots 0 is for DME
838 // the rest are for azimuth.
839 time_t now = globals->get_time_params()->get_cur_time();
840 if ((now >= last_time) && (now < last_time + SLOT_LENGTH)) {
841 return; // wait longer
845 play_count = ++play_count % NUM_IDENT_SLOTS;
847 // Previous ident is out of time; if still playing, cut it off:
848 _sgr->stop( nav_fx_name );
849 _sgr->stop( dme_fx_name );
850 if (play_count == 0) { // the DME slot
851 if (_dmeInRange && dme_serviceable_node->getBoolValue()) {
853 if (vol > 0.05) _sgr->play_once( dme_fx_name );
856 if (inrange_node->getBoolValue() && nav_serviceable_node->getBoolValue()) {
857 if (vol > 0.05) _sgr->play_once(nav_fx_name);
862 FGNavRecord* FGNavRadio::findPrimaryNavaid(const SGGeod& aPos, double aFreqMHz)
864 FGNavRecord* nav = globals->get_navlist()->findByFreq(aFreqMHz, aPos);
869 return globals->get_loclist()->findByFreq(aFreqMHz, aPos);
872 // Update current nav/adf radio stations based on current postition
873 void FGNavRadio::search()
875 _time_before_search_sec = 1.0;
876 SGGeod pos = SGGeod::fromDegFt(lon_node->getDoubleValue(),
877 lat_node->getDoubleValue(), alt_node->getDoubleValue());
878 double freq = freq_node->getDoubleValue();
880 FGNavRecord* nav = findPrimaryNavaid(pos, freq);
881 if (nav == _navaid) {
882 return; // found the same as last search, we're done
886 char identBuffer[5] = " ";
888 _dme = globals->get_dmelist()->findByFreq(freq, pos);
890 nav_id_node->setStringValue(nav->get_ident());
891 strncpy(identBuffer, nav->ident().c_str(), 5);
893 effective_range = adjustNavRange(nav->get_elev_ft(), pos.getElevationM(), nav->get_range());
894 loc_node->setBoolValue(nav->type() != FGPositioned::VOR);
895 twist = nav->get_multiuse();
897 if (nav->type() == FGPositioned::VOR) {
898 target_radial = sel_radial_node->getDoubleValue();
900 has_gs_node->setBoolValue(false);
901 } else { // ILS or LOC
902 _gs = globals->get_gslist()->findByFreq(freq, pos);
903 has_gs_node->setBoolValue(_gs != NULL);
904 _localizerWidth = localizerWidth(nav);
906 effective_range = nav->get_range();
908 target_radial = nav->get_multiuse();
909 SG_NORMALIZE_RANGE(target_radial, 0.0, 360.0);
912 int tmp = (int)(_gs->get_multiuse() / 1000.0);
913 target_gs = (double)tmp / 100.0;
915 // until penaltyForNav goes away, we cannot assume we always pick
916 // paired LOC/GS trasmsitters. As we pass over a runway threshold, we
917 // often end up picking the 'wrong' LOC, but the correct GS. To avoid
918 // breaking the basis computation, ensure we use the GS radial and not
919 // the (potentially reversed) LOC radial.
920 double gs_radial = fmod(_gs->get_multiuse(), 1000.0);
921 SG_NORMALIZE_RANGE(gs_radial, 0.0, 360.0);
923 // GS axis unit tangent vector
924 // (along the runway)
925 _gsCart = _gs->cart();
926 _gsAxis = tangentVector(_gs->geod(), _gsCart, gs_radial);
928 // GS baseline unit tangent vector
929 // (perpendicular to the runay along the ground)
930 SGVec3d baseline = tangentVector(_gs->geod(), _gsCart, gs_radial + 90.0);
931 _gsVertical = cross(baseline, _gsAxis);
932 } // of have glideslope
933 } // of found LOC or ILS
936 } else { // found nothing
939 nav_id_node->setStringValue("");
941 _sgr->remove( nav_fx_name );
942 _sgr->remove( dme_fx_name );
945 is_valid_node->setBoolValue(nav != NULL);
946 id_c1_node->setIntValue( (int)identBuffer[0] );
947 id_c2_node->setIntValue( (int)identBuffer[1] );
948 id_c3_node->setIntValue( (int)identBuffer[2] );
949 id_c4_node->setIntValue( (int)identBuffer[3] );
952 double FGNavRadio::localizerWidth(FGNavRecord* aLOC)
954 FGRunway* rwy = aLOC->runway();
957 SGVec3d thresholdCart(SGVec3d::fromGeod(rwy->threshold()));
958 double axisLength = dist(aLOC->cart(), thresholdCart);
959 double landingLength = dist(thresholdCart, SGVec3d::fromGeod(rwy->end()));
961 // Reference: http://dcaa.slv.dk:8000/icaodocs/
962 // ICAO standard width at threshold is 210 m = 689 feet = approx 700 feet.
963 // ICAO 3.1.1 half course = DDM = 0.0775
964 // ICAO 3.1.3.7.1 Sensitivity 0.00145 DDM/m at threshold
965 // implies peg-to-peg of 214 m ... we will stick with 210.
966 // ICAO 3.1.3.7.1 "Course sector angle shall not exceed 6 degrees."
968 // Very short runway: less than 1200 m (4000 ft) landing length:
969 if (landingLength < 1200.0) {
970 // ICAO fudges localizer sensitivity for very short runways.
971 // This produces a non-monotonic sensitivity-versus length relation.
972 axisLength += 1050.0;
975 // Example: very short: San Diego KMYF (Montgomery Field) ILS RWY 28R
976 // Example: short: Tom's River KMJX (Robert J. Miller) ILS RWY 6
977 // Example: very long: Denver KDEN (Denver) ILS RWY 16R
978 double raw_width = 210.0 / axisLength * SGD_RADIANS_TO_DEGREES;
979 return raw_width < 6.0? raw_width : 6.0;
982 void FGNavRadio::audioNavidChanged()
984 if (_sgr->exists(nav_fx_name)) {
985 _sgr->remove(nav_fx_name);
989 string trans_ident(_navaid->get_trans_ident());
990 SGSoundSample* sound = morse.make_ident(trans_ident, LO_FREQUENCY);
991 sound->set_volume( 0.3 );
992 if (!_sgr->add( sound, nav_fx_name )) {
993 SG_LOG(SG_COCKPIT, SG_WARN, "Failed to add v1-vor-ident sound");
996 if ( _sgr->exists( dme_fx_name ) ) {
997 _sgr->remove( dme_fx_name );
1000 sound = morse.make_ident( trans_ident, HI_FREQUENCY );
1001 sound->set_volume( 0.3 );
1002 _sgr->add( sound, dme_fx_name );
1004 int offset = (int)(sg_random() * 30.0);
1005 play_count = offset / 4;
1006 last_time = globals->get_time_params()->get_cur_time() - offset;
1007 } catch (sg_io_exception& e) {
1008 SG_LOG(SG_GENERAL, SG_ALERT, e.getFormattedMessage());