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)),
103 last_xtrack_error(0.0),
105 _localizerWidth(5.0),
106 _name(node->getStringValue("name", "nav")),
107 _num(node->getIntValue("number", 0)),
108 _time_before_search_sec(-1.0),
111 SGPath path( globals->get_fg_root() );
113 term.append( "Navaids/range.term" );
115 low.append( "Navaids/range.low" );
117 high.append( "Navaids/range.high" );
119 term_tbl = new SGInterpTable( term.str() );
120 low_tbl = new SGInterpTable( low.str() );
121 high_tbl = new SGInterpTable( high.str() );
124 string branch("/instrumentation/" + _name);
125 _radio_node = fgGetNode(branch.c_str(), _num, true);
130 FGNavRadio::~FGNavRadio()
141 SGSoundMgr *smgr = globals->get_soundmgr();
142 _sgr = smgr->find("avionics", true);
143 _sgr->tie_to_listener();
147 SGPropertyNode* node = _radio_node.get();
149 fgGetNode(("/systems/electrical/outputs/" + _name).c_str(), true);
152 is_valid_node = node->getChild("data-is-valid", 0, true);
153 power_btn_node = node->getChild("power-btn", 0, true);
154 power_btn_node->setBoolValue( true );
155 vol_btn_node = node->getChild("volume", 0, true);
156 ident_btn_node = node->getChild("ident", 0, true);
157 ident_btn_node->setBoolValue( true );
158 audio_btn_node = node->getChild("audio-btn", 0, true);
159 audio_btn_node->setBoolValue( true );
160 backcourse_node = node->getChild("back-course-btn", 0, true);
161 backcourse_node->setBoolValue( false );
163 nav_serviceable_node = node->getChild("serviceable", 0, true);
164 cdi_serviceable_node = createServiceableProp(node, "cdi");
165 gs_serviceable_node = createServiceableProp(node, "gs");
166 tofrom_serviceable_node = createServiceableProp(node, "to-from");
167 dme_serviceable_node = createServiceableProp(node, "dme");
169 falseCoursesEnabledNode =
170 fgGetNode("/sim/realism/false-radio-courses-enabled");
171 if (!falseCoursesEnabledNode) {
172 falseCoursesEnabledNode =
173 fgGetNode("/sim/realism/false-radio-courses-enabled", true);
174 falseCoursesEnabledNode->setBoolValue(true);
178 SGPropertyNode *subnode = node->getChild("frequencies", 0, true);
179 freq_node = subnode->getChild("selected-mhz", 0, true);
180 alt_freq_node = subnode->getChild("standby-mhz", 0, true);
181 fmt_freq_node = subnode->getChild("selected-mhz-fmt", 0, true);
182 fmt_alt_freq_node = subnode->getChild("standby-mhz-fmt", 0, true);
185 subnode = node->getChild("radials", 0, true);
186 sel_radial_node = subnode->getChild("selected-deg", 0, true);
187 radial_node = subnode->getChild("actual-deg", 0, true);
188 recip_radial_node = subnode->getChild("reciprocal-radial-deg", 0, true);
189 target_radial_true_node = subnode->getChild("target-radial-deg", 0, true);
190 target_auto_hdg_node = subnode->getChild("target-auto-hdg-deg", 0, true);
193 heading_node = node->getChild("heading-deg", 0, true);
194 time_to_intercept = node->getChild("time-to-intercept-sec", 0, true);
195 to_flag_node = node->getChild("to-flag", 0, true);
196 from_flag_node = node->getChild("from-flag", 0, true);
197 inrange_node = node->getChild("in-range", 0, true);
198 signal_quality_norm_node = node->getChild("signal-quality-norm", 0, true);
199 cdi_deflection_node = node->getChild("heading-needle-deflection", 0, true);
200 cdi_deflection_norm_node = node->getChild("heading-needle-deflection-norm", 0, true);
201 cdi_xtrack_error_node = node->getChild("crosstrack-error-m", 0, true);
202 cdi_xtrack_hdg_err_node
203 = node->getChild("crosstrack-heading-error-deg", 0, true);
204 has_gs_node = node->getChild("has-gs", 0, true);
205 loc_node = node->getChild("nav-loc", 0, true);
206 loc_dist_node = node->getChild("nav-distance", 0, true);
207 gs_deflection_node = node->getChild("gs-needle-deflection", 0, true);
208 gs_deflection_deg_node = node->getChild("gs-needle-deflection-deg", 0, true);
209 gs_deflection_norm_node = node->getChild("gs-needle-deflection-norm", 0, true);
210 gs_rate_of_climb_node = node->getChild("gs-rate-of-climb", 0, true);
211 gs_dist_node = node->getChild("gs-distance", 0, true);
212 gs_inrange_node = node->getChild("gs-in-range", 0, true);
214 nav_id_node = node->getChild("nav-id", 0, true);
215 id_c1_node = node->getChild("nav-id_asc1", 0, true);
216 id_c2_node = node->getChild("nav-id_asc2", 0, true);
217 id_c3_node = node->getChild("nav-id_asc3", 0, true);
218 id_c4_node = node->getChild("nav-id_asc4", 0, true);
220 // gps slaving support
221 nav_slaved_to_gps_node = node->getChild("slaved-to-gps", 0, true);
222 gps_cdi_deflection_node = fgGetNode("/instrumentation/gps/cdi-deflection", true);
223 gps_to_flag_node = fgGetNode("/instrumentation/gps/to-flag", true);
224 gps_from_flag_node = fgGetNode("/instrumentation/gps/from-flag", true);
225 gps_has_gs_node = fgGetNode("/instrumentation/gps/has-gs", true);
226 gps_course_node = fgGetNode("/instrumentation/gps/selected-course-deg", true);
227 gps_xtrack_error_nm_node = fgGetNode("/instrumentation/gps/wp/wp[1]/course-error-nm", true);
228 _magvarNode = fgGetNode("/environment/magnetic-variation-deg", true);
230 std::ostringstream temp;
231 temp << _name << "nav-ident" << _num;
232 nav_fx_name = temp.str();
233 temp << _name << "dme-ident" << _num;
234 dme_fx_name = temp.str();
240 tie("dme-in-range", SGRawValuePointer<bool>(&_dmeInRange));
241 tie("operable", SGRawValueMethods<FGNavRadio, bool>(*this, &FGNavRadio::isOperable, NULL));
246 FGNavRadio::unbind ()
248 for (unsigned int t=0; t<_tiedNodes.size(); ++t) {
249 _tiedNodes[t]->untie();
255 // model standard VOR/DME/TACAN service volumes as per AIM 1-1-8
256 double FGNavRadio::adjustNavRange( double stationElev, double aircraftElev,
257 double nominalRange )
259 if (nominalRange <= 0.0) {
260 nominalRange = FG_NAV_DEFAULT_RANGE;
263 // extend out actual usable range to be 1.3x the published safe range
264 const double usability_factor = 1.3;
266 // assumptions we model the standard service volume, plus
267 // ... rather than specifying a cylinder, we model a cone that
268 // contains the cylinder. Then we put an upside down cone on top
269 // to model diminishing returns at too-high altitudes.
271 // altitude difference
272 double alt = ( aircraftElev * SG_METER_TO_FEET - stationElev );
273 // cout << "aircraft elev = " << aircraftElev * SG_METER_TO_FEET
274 // << " station elev = " << stationElev << endl;
276 if ( nominalRange < 25.0 + SG_EPSILON ) {
277 // Standard Terminal Service Volume
278 return term_tbl->interpolate( alt ) * usability_factor;
279 } else if ( nominalRange < 50.0 + SG_EPSILON ) {
280 // Standard Low Altitude Service Volume
281 // table is based on range of 40, scale to actual range
282 return low_tbl->interpolate( alt ) * nominalRange / 40.0
285 // Standard High Altitude Service Volume
286 // table is based on range of 130, scale to actual range
287 return high_tbl->interpolate( alt ) * nominalRange / 130.0
293 // model standard ILS service volumes as per AIM 1-1-9
294 double FGNavRadio::adjustILSRange( double stationElev, double aircraftElev,
295 double offsetDegrees, double distance )
297 // assumptions we model the standard service volume, plus
299 // altitude difference
300 // double alt = ( aircraftElev * SG_METER_TO_FEET - stationElev );
301 // double offset = fabs( offsetDegrees );
303 // if ( offset < 10 ) {
304 // return FG_ILS_DEFAULT_RANGE;
305 // } else if ( offset < 35 ) {
306 // return 10 + (35 - offset) * (FG_ILS_DEFAULT_RANGE - 10) / 25;
307 // } else if ( offset < 45 ) {
308 // return (45 - offset);
309 // } else if ( offset > 170 ) {
310 // return FG_ILS_DEFAULT_RANGE;
311 // } else if ( offset > 145 ) {
312 // return 10 + (offset - 145) * (FG_ILS_DEFAULT_RANGE - 10) / 25;
313 // } else if ( offset > 135 ) {
314 // return (offset - 135);
318 return FG_LOC_DEFAULT_RANGE;
322 //////////////////////////////////////////////////////////////////////////
323 // Update the various nav values based on position and valid tuned in navs
324 //////////////////////////////////////////////////////////////////////////
326 FGNavRadio::update(double dt)
332 // Create "formatted" versions of the nav frequencies for
333 // instrument displays.
335 sprintf( tmp, "%.2f", freq_node->getDoubleValue() );
336 fmt_freq_node->setStringValue(tmp);
337 sprintf( tmp, "%.2f", alt_freq_node->getDoubleValue() );
338 fmt_alt_freq_node->setStringValue(tmp);
340 if (power_btn_node->getBoolValue()
341 && (bus_power_node->getDoubleValue() > 1.0)
342 && nav_serviceable_node->getBoolValue() )
345 if (nav_slaved_to_gps_node->getBoolValue()) {
359 void FGNavRadio::clearOutputs()
361 inrange_node->setBoolValue( false );
362 cdi_deflection_node->setDoubleValue( 0.0 );
363 cdi_deflection_norm_node->setDoubleValue( 0.0 );
364 cdi_xtrack_error_node->setDoubleValue( 0.0 );
365 cdi_xtrack_hdg_err_node->setDoubleValue( 0.0 );
366 time_to_intercept->setDoubleValue( 0.0 );
367 gs_deflection_node->setDoubleValue( 0.0 );
368 gs_deflection_deg_node->setDoubleValue(0.0);
369 gs_deflection_norm_node->setDoubleValue(0.0);
370 gs_inrange_node->setBoolValue( false );
372 to_flag_node->setBoolValue( false );
373 from_flag_node->setBoolValue( false );
379 void FGNavRadio::updateReceiver(double dt)
381 // Do a nav station search only once a second to reduce
382 // unnecessary work. (Also, make sure to do this before caching
384 _time_before_search_sec -= dt;
385 if ( _time_before_search_sec < 0 ) {
390 _cdiDeflection = 0.0;
391 _cdiCrossTrackErrorM = 0.0;
392 _toFlag = _fromFlag = false;
393 _gsNeedleDeflection = 0.0;
394 _gsNeedleDeflectionNorm = 0.0;
395 inrange_node->setBoolValue(false);
399 SGGeod pos = SGGeod::fromDegFt(lon_node->getDoubleValue(),
400 lat_node->getDoubleValue(),
401 alt_node->getDoubleValue());
403 double nav_elev = _navaid->get_elev_ft();
404 SGVec3d aircraft = SGVec3d::fromGeod(pos);
405 double loc_dist = dist(aircraft, _navaid->cart());
406 loc_dist_node->setDoubleValue( loc_dist );
407 bool is_loc = loc_node->getBoolValue();
408 double signal_quality_norm = signal_quality_norm_node->getDoubleValue();
411 //////////////////////////////////////////////////////////
412 // compute forward and reverse wgs84 headings to localizer
413 //////////////////////////////////////////////////////////
415 SGGeodesy::inverse(pos, _navaid->geod(), hdg, az2, s);
416 heading_node->setDoubleValue(hdg);
417 double radial = az2 - twist;
418 double recip = radial + 180.0;
419 SG_NORMALIZE_RANGE(recip, 0.0, 360.0);
420 radial_node->setDoubleValue( radial );
421 recip_radial_node->setDoubleValue( recip );
423 //////////////////////////////////////////////////////////
424 // compute the target/selected radial in "true" heading
425 //////////////////////////////////////////////////////////
427 target_radial = sel_radial_node->getDoubleValue();
430 // VORs need twist (mag-var) added; ILS/LOCs don't but we set twist to 0.0
431 double trtrue = target_radial + twist;
432 SG_NORMALIZE_RANGE(trtrue, 0.0, 360.0);
433 target_radial_true_node->setDoubleValue( trtrue );
435 //////////////////////////////////////////////////////////
436 // adjust reception range for altitude
437 // FIXME: make sure we are using the navdata range now that
438 // it is valid in the data file
439 //////////////////////////////////////////////////////////
441 double offset = radial - target_radial;
442 SG_NORMALIZE_RANGE(offset, -180.0, 180.0);
444 = adjustILSRange( nav_elev, pos.getElevationM(), offset,
445 loc_dist * SG_METER_TO_NM );
448 = adjustNavRange( nav_elev, pos.getElevationM(), _navaid->get_range() );
451 double effective_range_m = effective_range * SG_NM_TO_METER;
453 //////////////////////////////////////////////////////////
454 // compute signal quality
455 // 100% within effective_range
456 // decreases 1/x^2 further out
457 //////////////////////////////////////////////////////////
458 double last_signal_quality_norm = signal_quality_norm;
460 if ( loc_dist < effective_range_m ) {
461 signal_quality_norm = 1.0;
463 double range_exceed_norm = loc_dist/effective_range_m;
464 signal_quality_norm = 1/(range_exceed_norm*range_exceed_norm);
467 signal_quality_norm = fgGetLowPass( last_signal_quality_norm,
468 signal_quality_norm, dt );
470 signal_quality_norm_node->setDoubleValue( signal_quality_norm );
471 bool inrange = signal_quality_norm > 0.2;
472 inrange_node->setBoolValue( inrange );
474 //////////////////////////////////////////////////////////
475 // compute to/from flag status
476 //////////////////////////////////////////////////////////
481 double offset = fabs(radial - target_radial);
482 _toFlag = (offset > 90.0 && offset < 270.0);
484 _fromFlag = !_toFlag;
486 _toFlag = _fromFlag = false;
490 double r = target_radial - radial;
491 SG_NORMALIZE_RANGE(r, -180.0, 180.0);
494 if (falseCoursesEnabledNode->getBoolValue()) {
495 // The factor of 30.0 gives a period of 120 which gives us 3 cycles and six
496 // zeros i.e. six courses: one front course, one back course, and four
497 // false courses. Three of the six are reverse sensing.
498 _cdiDeflection = 30.0 * sawtooth(r / 30.0);
500 // no false courses, but we do need to create a back course
501 if (fabs(r) > 90.0) { // front course
502 _cdiDeflection = r - copysign(180.0, r);
504 _cdiDeflection = r; // back course
507 _cdiDeflection = -_cdiDeflection; // reverse for outbound radial
508 } // of false courses disabled
510 const double VOR_FULL_ARC = 20.0; // VOR is -10 .. 10 degree swing
511 _cdiDeflection *= VOR_FULL_ARC / _localizerWidth; // increased localiser sensitivity
513 if (backcourse_node->getBoolValue()) {
514 _cdiDeflection = -_cdiDeflection;
517 // handle the TO side of the VOR
518 if (fabs(r) > 90.0) {
519 r = ( r<0.0 ? -r-180.0 : -r+180.0 );
522 } // of non-localiser case
524 SG_CLAMP_RANGE(_cdiDeflection, -10.0, 10.0 );
525 _cdiDeflection *= signal_quality_norm;
527 // cross-track error (in metres)
528 _cdiCrossTrackErrorM = loc_dist * sin(r * SGD_DEGREES_TO_RADIANS);
530 updateGlideSlope(dt, aircraft, signal_quality_norm);
533 last_loc_dist = loc_dist;
536 void FGNavRadio::updateGlideSlope(double dt, const SGVec3d& aircraft, double signal_quality_norm)
538 _gsNeedleDeflection = 0.0;
539 if (!_gs || !inrange_node->getBoolValue()) {
540 gs_dist_node->setDoubleValue( 0.0 );
541 gs_inrange_node->setBoolValue(false);
542 _gsNeedleDeflection = 0.0;
543 _gsNeedleDeflectionNorm = 0.0;
547 double gsDist = dist(aircraft, _gsCart);
548 gs_dist_node->setDoubleValue(gsDist);
549 bool gsInRange = (gsDist < (_gs->get_range() * SG_NM_TO_METER));
550 gs_inrange_node->setBoolValue(gsInRange);
553 _gsNeedleDeflection = 0.0;
554 _gsNeedleDeflectionNorm = 0.0;
558 SGVec3d pos = aircraft - _gsCart; // relative vector from gs antenna to aircraft
559 // The positive GS axis points along the runway in the landing direction,
560 // toward the far end, not toward the approach area, so we need a - sign here:
561 double dot_h = -dot(pos, _gsAxis);
562 double dot_v = dot(pos, _gsVertical);
563 double angle = atan2(dot_v, dot_h) * SGD_RADIANS_TO_DEGREES;
564 double deflectionAngle = target_gs - angle;
566 if (falseCoursesEnabledNode->getBoolValue()) {
567 // Construct false glideslopes. The scale factor of 1.5
568 // in the sawtooth gives a period of 6 degrees.
569 // There will be zeros at 3, 6r, 9, 12r et cetera
570 // where "r" indicates reverse sensing.
571 // This is is consistent with conventional pilot lore
572 // e.g. http://www.allstar.fiu.edu/aerojava/ILS.htm
573 // but inconsistent with
574 // http://www.freepatentsonline.com/3757338.html
576 // It may be that some of each exist.
577 if (deflectionAngle < 0) {
578 deflectionAngle = 1.5 * sawtooth(deflectionAngle / 1.5);
580 // no false GS below the true GS
584 _gsNeedleDeflection = deflectionAngle * 5.0;
585 _gsNeedleDeflection *= signal_quality_norm;
587 SG_CLAMP_RANGE(deflectionAngle, -0.7, 0.7);
588 _gsNeedleDeflectionNorm = (deflectionAngle / 0.7) * signal_quality_norm;
590 //////////////////////////////////////////////////////////
591 // Calculate desired rate of climb for intercepting the GS
592 //////////////////////////////////////////////////////////
593 double gs_diff = target_gs - angle;
594 // convert desired vertical path angle into a climb rate
595 double des_angle = angle - 10 * gs_diff;
597 // estimate horizontal speed towards ILS in meters per minute
598 double elapsedDistance = last_x - gsDist;
601 double new_vel = ( elapsedDistance / dt );
602 horiz_vel = 0.75 * horiz_vel + 0.25 * new_vel;
604 gs_rate_of_climb_node
605 ->setDoubleValue( -sin( des_angle * SGD_DEGREES_TO_RADIANS )
606 * horiz_vel * SG_METER_TO_FEET );
609 void FGNavRadio::updateDME(const SGVec3d& aircraft)
611 if (!_dme || !dme_serviceable_node->getBoolValue()) {
616 double dme_distance = dist(aircraft, _dme->cart());
617 _dmeInRange = (dme_distance < _dme->get_range() * SG_NM_TO_METER);
620 void FGNavRadio::updateGPSSlaved()
622 has_gs_node->setBoolValue(gps_has_gs_node->getBoolValue());
624 _toFlag = gps_to_flag_node->getBoolValue();
625 _fromFlag = gps_from_flag_node->getBoolValue();
627 bool gpsValid = (_toFlag | _fromFlag);
628 inrange_node->setBoolValue(gpsValid);
630 signal_quality_norm_node->setDoubleValue(0.0);
631 _cdiDeflection = 0.0;
632 _cdiCrossTrackErrorM = 0.0;
633 _gsNeedleDeflection = 0.0;
637 // this is unfortunate, but panel instruments use this value to decide
638 // if the navradio output is valid.
639 signal_quality_norm_node->setDoubleValue(1.0);
641 _cdiDeflection = gps_cdi_deflection_node->getDoubleValue();
642 // clmap to some range (+/- 10 degrees) as the regular deflection
643 SG_CLAMP_RANGE(_cdiDeflection, -10.0, 10.0 );
645 _cdiCrossTrackErrorM = gps_xtrack_error_nm_node->getDoubleValue() * SG_NM_TO_METER;
646 _gsNeedleDeflection = 0.0; // FIXME, supply this
648 double trtrue = gps_course_node->getDoubleValue() + _magvarNode->getDoubleValue();
649 SG_NORMALIZE_RANGE(trtrue, 0.0, 360.0);
650 target_radial_true_node->setDoubleValue( trtrue );
653 void FGNavRadio::updateCDI(double dt)
655 bool cdi_serviceable = cdi_serviceable_node->getBoolValue();
656 bool inrange = inrange_node->getBoolValue();
658 if (tofrom_serviceable_node->getBoolValue()) {
659 to_flag_node->setBoolValue(_toFlag);
660 from_flag_node->setBoolValue(_fromFlag);
662 to_flag_node->setBoolValue(false);
663 from_flag_node->setBoolValue(false);
666 if (!cdi_serviceable) {
667 _cdiDeflection = 0.0;
668 _cdiCrossTrackErrorM = 0.0;
671 cdi_deflection_node->setDoubleValue(_cdiDeflection);
672 cdi_deflection_norm_node->setDoubleValue(_cdiDeflection * 0.1);
673 cdi_xtrack_error_node->setDoubleValue(_cdiCrossTrackErrorM);
675 //////////////////////////////////////////////////////////
676 // compute an approximate ground track heading error
677 //////////////////////////////////////////////////////////
678 double hdg_error = 0.0;
679 if ( inrange && cdi_serviceable ) {
680 double vn = fgGetDouble( "/velocities/speed-north-fps" );
681 double ve = fgGetDouble( "/velocities/speed-east-fps" );
682 double gnd_trk_true = atan2( ve, vn ) * SGD_RADIANS_TO_DEGREES;
683 if ( gnd_trk_true < 0.0 ) { gnd_trk_true += 360.0; }
685 SGPropertyNode *true_hdg
686 = fgGetNode("/orientation/heading-deg", true);
687 hdg_error = gnd_trk_true - true_hdg->getDoubleValue();
689 // cout << "ground track = " << gnd_trk_true
690 // << " orientation = " << true_hdg->getDoubleValue() << endl;
692 cdi_xtrack_hdg_err_node->setDoubleValue( hdg_error );
694 //////////////////////////////////////////////////////////
695 // Calculate a suggested target heading to smoothly intercept
697 //////////////////////////////////////////////////////////
699 // Now that we have cross track heading adjustment built in,
700 // we shouldn't need to overdrive the heading angle within 8km
703 // The cdi deflection should be +/-10 for a full range of deflection
704 // so multiplying this by 3 gives us +/- 30 degrees heading
706 double adjustment = _cdiDeflection * 3.0;
707 SG_CLAMP_RANGE( adjustment, -30.0, 30.0 );
709 // determine the target heading to fly to intercept the
710 // tgt_radial = target radial (true) + cdi offset adjustmest -
711 // xtrack heading error adjustment
713 double trtrue = target_radial_true_node->getDoubleValue();
714 if ( loc_node->getBoolValue() && backcourse_node->getBoolValue() ) {
715 // tuned to a localizer and backcourse mode activated
716 trtrue += 180.0; // reverse the target localizer heading
717 SG_NORMALIZE_RANGE(trtrue, 0.0, 360.0);
718 nta_hdg = trtrue - adjustment - hdg_error;
720 nta_hdg = trtrue + adjustment - hdg_error;
723 SG_NORMALIZE_RANGE(nta_hdg, 0.0, 360.0);
724 target_auto_hdg_node->setDoubleValue( nta_hdg );
726 //////////////////////////////////////////////////////////
727 // compute the time to intercept selected radial (based on
728 // current and last cross track errors and dt
729 //////////////////////////////////////////////////////////
731 if ( inrange && cdi_serviceable ) {
732 double cur_rate = (last_xtrack_error - _cdiCrossTrackErrorM) / dt;
733 xrate_ms = 0.99 * xrate_ms + 0.01 * cur_rate;
734 if ( fabs(xrate_ms) > 0.00001 ) {
735 t = _cdiCrossTrackErrorM / xrate_ms;
740 time_to_intercept->setDoubleValue( t );
742 if (!gs_serviceable_node->getBoolValue() ) {
743 _gsNeedleDeflection = 0.0;
744 _gsNeedleDeflectionNorm = 0.0;
746 gs_deflection_node->setDoubleValue(_gsNeedleDeflection);
747 gs_deflection_deg_node->setDoubleValue(_gsNeedleDeflectionNorm * 0.7);
748 gs_deflection_norm_node->setDoubleValue(_gsNeedleDeflectionNorm);
750 last_xtrack_error = _cdiCrossTrackErrorM;
753 void FGNavRadio::updateAudio()
755 if (!_navaid || !inrange_node->getBoolValue() || !nav_serviceable_node->getBoolValue()) {
759 // play station ident via audio system if on + ident,
760 // otherwise turn it off
761 if (!power_btn_node->getBoolValue()
762 || !(bus_power_node->getDoubleValue() > 1.0)
763 || !ident_btn_node->getBoolValue()
764 || !audio_btn_node->getBoolValue() ) {
765 _sgr->stop( nav_fx_name );
766 _sgr->stop( dme_fx_name );
770 SGSoundSample *sound = _sgr->find( nav_fx_name );
771 double vol = vol_btn_node->getFloatValue();
772 SG_CLAMP_RANGE(vol, 0.0, 1.0);
774 if ( sound != NULL ) {
775 sound->set_volume( vol );
777 SG_LOG( SG_COCKPIT, SG_ALERT, "Can't find nav-vor-ident sound" );
780 sound = _sgr->find( dme_fx_name );
781 if ( sound != NULL ) {
782 sound->set_volume( vol );
784 SG_LOG( SG_COCKPIT, SG_ALERT, "Can't find nav-dme-ident sound" );
787 const int NUM_IDENT_SLOTS = 5;
788 const time_t SLOT_LENGTH = 5; // seconds
790 // There are N slots numbered 0 through (NUM_IDENT_SLOTS-1) inclusive.
791 // Each slot is 5 seconds long.
792 // Slots 0 is for DME
793 // the rest are for azimuth.
794 time_t now = globals->get_time_params()->get_cur_time();
795 if ((now >= last_time) && (now < last_time + SLOT_LENGTH)) {
796 return; // wait longer
800 play_count = ++play_count % NUM_IDENT_SLOTS;
802 // Previous ident is out of time; if still playing, cut it off:
803 _sgr->stop( nav_fx_name );
804 _sgr->stop( dme_fx_name );
805 if (play_count == 0) { // the DME slot
806 if (_dmeInRange && dme_serviceable_node->getBoolValue()) {
808 if (vol > 0.05) _sgr->play_once( dme_fx_name );
811 if (inrange_node->getBoolValue() && nav_serviceable_node->getBoolValue()) {
812 if (vol > 0.05) _sgr->play_once(nav_fx_name);
817 FGNavRecord* FGNavRadio::findPrimaryNavaid(const SGGeod& aPos, double aFreqMHz)
819 FGNavRecord* nav = globals->get_navlist()->findByFreq(aFreqMHz, aPos);
824 return globals->get_loclist()->findByFreq(aFreqMHz, aPos);
827 // Update current nav/adf radio stations based on current postition
828 void FGNavRadio::search()
830 _time_before_search_sec = 1.0;
831 SGGeod pos = SGGeod::fromDegFt(lon_node->getDoubleValue(),
832 lat_node->getDoubleValue(), alt_node->getDoubleValue());
833 double freq = freq_node->getDoubleValue();
835 FGNavRecord* nav = findPrimaryNavaid(pos, freq);
836 if (nav == _navaid) {
837 return; // found the same as last search, we're done
841 char identBuffer[5] = " ";
843 _dme = globals->get_dmelist()->findByFreq(freq, pos);
845 nav_id_node->setStringValue(nav->get_ident());
846 strncpy(identBuffer, nav->ident().c_str(), 5);
848 effective_range = adjustNavRange(nav->get_elev_ft(), pos.getElevationM(), nav->get_range());
849 loc_node->setBoolValue(nav->type() != FGPositioned::VOR);
850 twist = nav->get_multiuse();
852 if (nav->type() == FGPositioned::VOR) {
853 target_radial = sel_radial_node->getDoubleValue();
855 has_gs_node->setBoolValue(false);
856 } else { // ILS or LOC
857 _gs = globals->get_gslist()->findByFreq(freq, pos);
858 has_gs_node->setBoolValue(_gs != NULL);
859 _localizerWidth = localizerWidth(nav);
861 effective_range = nav->get_range();
863 target_radial = nav->get_multiuse();
864 SG_NORMALIZE_RANGE(target_radial, 0.0, 360.0);
867 int tmp = (int)(_gs->get_multiuse() / 1000.0);
868 target_gs = (double)tmp / 100.0;
870 // until penaltyForNav goes away, we cannot assume we always pick
871 // paired LOC/GS trasmsitters. As we pass over a runway threshold, we
872 // often end up picking the 'wrong' LOC, but the correct GS. To avoid
873 // breaking the basis computation, ensure we use the GS radial and not
874 // the (potentially reversed) LOC radial.
875 double gs_radial = fmod(_gs->get_multiuse(), 1000.0);
876 SG_NORMALIZE_RANGE(gs_radial, 0.0, 360.0);
878 // GS axis unit tangent vector
879 // (along the runway)
880 _gsCart = _gs->cart();
881 _gsAxis = tangentVector(_gs->geod(), _gsCart, gs_radial);
883 // GS baseline unit tangent vector
884 // (perpendicular to the runay along the ground)
885 SGVec3d baseline = tangentVector(_gs->geod(), _gsCart, gs_radial + 90.0);
886 _gsVertical = cross(baseline, _gsAxis);
887 } // of have glideslope
888 } // of found LOC or ILS
891 } else { // found nothing
894 nav_id_node->setStringValue("");
896 _sgr->remove( nav_fx_name );
897 _sgr->remove( dme_fx_name );
900 is_valid_node->setBoolValue(nav != NULL);
901 id_c1_node->setIntValue( (int)identBuffer[0] );
902 id_c2_node->setIntValue( (int)identBuffer[1] );
903 id_c3_node->setIntValue( (int)identBuffer[2] );
904 id_c4_node->setIntValue( (int)identBuffer[3] );
907 double FGNavRadio::localizerWidth(FGNavRecord* aLOC)
909 FGRunway* rwy = aLOC->runway();
912 SGVec3d thresholdCart(SGVec3d::fromGeod(rwy->threshold()));
913 double axisLength = dist(aLOC->cart(), thresholdCart);
914 double landingLength = dist(thresholdCart, SGVec3d::fromGeod(rwy->end()));
916 // Reference: http://dcaa.slv.dk:8000/icaodocs/
917 // ICAO standard width at threshold is 210 m = 689 feet = approx 700 feet.
918 // ICAO 3.1.1 half course = DDM = 0.0775
919 // ICAO 3.1.3.7.1 Sensitivity 0.00145 DDM/m at threshold
920 // implies peg-to-peg of 214 m ... we will stick with 210.
921 // ICAO 3.1.3.7.1 "Course sector angle shall not exceed 6 degrees."
923 // Very short runway: less than 1200 m (4000 ft) landing length:
924 if (landingLength < 1200.0) {
925 // ICAO fudges localizer sensitivity for very short runways.
926 // This produces a non-monotonic sensitivity-versus length relation.
927 axisLength += 1050.0;
930 // Example: very short: San Diego KMYF (Montgomery Field) ILS RWY 28R
931 // Example: short: Tom's River KMJX (Robert J. Miller) ILS RWY 6
932 // Example: very long: Denver KDEN (Denver) ILS RWY 16R
933 double raw_width = 210.0 / axisLength * SGD_RADIANS_TO_DEGREES;
934 return raw_width < 6.0? raw_width : 6.0;
937 void FGNavRadio::audioNavidChanged()
939 if (_sgr->exists(nav_fx_name)) {
940 _sgr->remove(nav_fx_name);
944 string trans_ident(_navaid->get_trans_ident());
945 SGSoundSample* sound = morse.make_ident(trans_ident, LO_FREQUENCY);
946 sound->set_volume( 0.3 );
947 if (!_sgr->add( sound, nav_fx_name )) {
948 SG_LOG(SG_COCKPIT, SG_WARN, "Failed to add v1-vor-ident sound");
951 if ( _sgr->exists( dme_fx_name ) ) {
952 _sgr->remove( dme_fx_name );
955 sound = morse.make_ident( trans_ident, HI_FREQUENCY );
956 sound->set_volume( 0.3 );
957 _sgr->add( sound, dme_fx_name );
959 int offset = (int)(sg_random() * 30.0);
960 play_count = offset / 4;
961 last_time = globals->get_time_params()->get_cur_time() - offset;
962 } catch (sg_io_exception& e) {
963 SG_LOG(SG_GENERAL, SG_ALERT, e.getFormattedMessage());