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()
132 gps_course_node->removeChangeListener(this);
133 nav_slaved_to_gps_node->removeChangeListener(this);
144 SGSoundMgr *smgr = globals->get_soundmgr();
145 _sgr = smgr->find("avionics", true);
146 _sgr->tie_to_listener();
150 SGPropertyNode* node = _radio_node.get();
152 fgGetNode(("/systems/electrical/outputs/" + _name).c_str(), true);
155 is_valid_node = node->getChild("data-is-valid", 0, true);
156 power_btn_node = node->getChild("power-btn", 0, true);
157 power_btn_node->setBoolValue( true );
158 vol_btn_node = node->getChild("volume", 0, true);
159 ident_btn_node = node->getChild("ident", 0, true);
160 ident_btn_node->setBoolValue( true );
161 audio_btn_node = node->getChild("audio-btn", 0, true);
162 audio_btn_node->setBoolValue( true );
163 backcourse_node = node->getChild("back-course-btn", 0, true);
164 backcourse_node->setBoolValue( false );
166 nav_serviceable_node = node->getChild("serviceable", 0, true);
167 cdi_serviceable_node = createServiceableProp(node, "cdi");
168 gs_serviceable_node = createServiceableProp(node, "gs");
169 tofrom_serviceable_node = createServiceableProp(node, "to-from");
170 dme_serviceable_node = createServiceableProp(node, "dme");
172 falseCoursesEnabledNode =
173 fgGetNode("/sim/realism/false-radio-courses-enabled");
174 if (!falseCoursesEnabledNode) {
175 falseCoursesEnabledNode =
176 fgGetNode("/sim/realism/false-radio-courses-enabled", true);
177 falseCoursesEnabledNode->setBoolValue(true);
181 SGPropertyNode *subnode = node->getChild("frequencies", 0, true);
182 freq_node = subnode->getChild("selected-mhz", 0, true);
183 alt_freq_node = subnode->getChild("standby-mhz", 0, true);
184 fmt_freq_node = subnode->getChild("selected-mhz-fmt", 0, true);
185 fmt_alt_freq_node = subnode->getChild("standby-mhz-fmt", 0, true);
188 subnode = node->getChild("radials", 0, true);
189 sel_radial_node = subnode->getChild("selected-deg", 0, true);
190 radial_node = subnode->getChild("actual-deg", 0, true);
191 recip_radial_node = subnode->getChild("reciprocal-radial-deg", 0, true);
192 target_radial_true_node = subnode->getChild("target-radial-deg", 0, true);
193 target_auto_hdg_node = subnode->getChild("target-auto-hdg-deg", 0, true);
196 heading_node = node->getChild("heading-deg", 0, true);
197 time_to_intercept = node->getChild("time-to-intercept-sec", 0, true);
198 to_flag_node = node->getChild("to-flag", 0, true);
199 from_flag_node = node->getChild("from-flag", 0, true);
200 inrange_node = node->getChild("in-range", 0, true);
201 signal_quality_norm_node = node->getChild("signal-quality-norm", 0, true);
202 cdi_deflection_node = node->getChild("heading-needle-deflection", 0, true);
203 cdi_deflection_norm_node = node->getChild("heading-needle-deflection-norm", 0, true);
204 cdi_xtrack_error_node = node->getChild("crosstrack-error-m", 0, true);
205 cdi_xtrack_hdg_err_node
206 = node->getChild("crosstrack-heading-error-deg", 0, true);
207 has_gs_node = node->getChild("has-gs", 0, true);
208 loc_node = node->getChild("nav-loc", 0, true);
209 loc_dist_node = node->getChild("nav-distance", 0, true);
210 gs_deflection_node = node->getChild("gs-needle-deflection", 0, true);
211 gs_deflection_deg_node = node->getChild("gs-needle-deflection-deg", 0, true);
212 gs_deflection_norm_node = node->getChild("gs-needle-deflection-norm", 0, true);
213 gs_rate_of_climb_node = node->getChild("gs-rate-of-climb", 0, true);
214 gs_rate_of_climb_fpm_node = node->getChild("gs-rate-of-climb-fpm", 0, true);
215 gs_dist_node = node->getChild("gs-distance", 0, true);
216 gs_inrange_node = node->getChild("gs-in-range", 0, true);
218 nav_id_node = node->getChild("nav-id", 0, true);
219 id_c1_node = node->getChild("nav-id_asc1", 0, true);
220 id_c2_node = node->getChild("nav-id_asc2", 0, true);
221 id_c3_node = node->getChild("nav-id_asc3", 0, true);
222 id_c4_node = node->getChild("nav-id_asc4", 0, true);
224 // gps slaving support
225 nav_slaved_to_gps_node = node->getChild("slaved-to-gps", 0, true);
226 nav_slaved_to_gps_node->addChangeListener(this);
228 gps_cdi_deflection_node = fgGetNode("/instrumentation/gps/cdi-deflection", true);
229 gps_to_flag_node = fgGetNode("/instrumentation/gps/to-flag", true);
230 gps_from_flag_node = fgGetNode("/instrumentation/gps/from-flag", true);
231 gps_has_gs_node = fgGetNode("/instrumentation/gps/has-gs", true);
232 gps_course_node = fgGetNode("/instrumentation/gps/desired-course-deg", true);
233 gps_course_node->addChangeListener(this);
235 gps_xtrack_error_nm_node = fgGetNode("/instrumentation/gps/wp/wp[1]/course-error-nm", true);
236 _magvarNode = fgGetNode("/environment/magnetic-variation-deg", true);
238 std::ostringstream temp;
239 temp << _name << "nav-ident" << _num;
240 nav_fx_name = temp.str();
241 temp << _name << "dme-ident" << _num;
242 dme_fx_name = temp.str();
248 tie("dme-in-range", SGRawValuePointer<bool>(&_dmeInRange));
249 tie("operable", SGRawValueMethods<FGNavRadio, bool>(*this, &FGNavRadio::isOperable, NULL));
254 FGNavRadio::unbind ()
256 for (unsigned int t=0; t<_tiedNodes.size(); ++t) {
257 _tiedNodes[t]->untie();
263 // model standard VOR/DME/TACAN service volumes as per AIM 1-1-8
264 double FGNavRadio::adjustNavRange( double stationElev, double aircraftElev,
265 double nominalRange )
267 if (nominalRange <= 0.0) {
268 nominalRange = FG_NAV_DEFAULT_RANGE;
271 // extend out actual usable range to be 1.3x the published safe range
272 const double usability_factor = 1.3;
274 // assumptions we model the standard service volume, plus
275 // ... rather than specifying a cylinder, we model a cone that
276 // contains the cylinder. Then we put an upside down cone on top
277 // to model diminishing returns at too-high altitudes.
279 // altitude difference
280 double alt = ( aircraftElev * SG_METER_TO_FEET - stationElev );
281 // cout << "aircraft elev = " << aircraftElev * SG_METER_TO_FEET
282 // << " station elev = " << stationElev << endl;
284 if ( nominalRange < 25.0 + SG_EPSILON ) {
285 // Standard Terminal Service Volume
286 return term_tbl->interpolate( alt ) * usability_factor;
287 } else if ( nominalRange < 50.0 + SG_EPSILON ) {
288 // Standard Low Altitude Service Volume
289 // table is based on range of 40, scale to actual range
290 return low_tbl->interpolate( alt ) * nominalRange / 40.0
293 // Standard High Altitude Service Volume
294 // table is based on range of 130, scale to actual range
295 return high_tbl->interpolate( alt ) * nominalRange / 130.0
301 // model standard ILS service volumes as per AIM 1-1-9
302 double FGNavRadio::adjustILSRange( double stationElev, double aircraftElev,
303 double offsetDegrees, double distance )
305 // assumptions we model the standard service volume, plus
307 // altitude difference
308 // double alt = ( aircraftElev * SG_METER_TO_FEET - stationElev );
309 // double offset = fabs( offsetDegrees );
311 // if ( offset < 10 ) {
312 // return FG_ILS_DEFAULT_RANGE;
313 // } else if ( offset < 35 ) {
314 // return 10 + (35 - offset) * (FG_ILS_DEFAULT_RANGE - 10) / 25;
315 // } else if ( offset < 45 ) {
316 // return (45 - offset);
317 // } else if ( offset > 170 ) {
318 // return FG_ILS_DEFAULT_RANGE;
319 // } else if ( offset > 145 ) {
320 // return 10 + (offset - 145) * (FG_ILS_DEFAULT_RANGE - 10) / 25;
321 // } else if ( offset > 135 ) {
322 // return (offset - 135);
326 return FG_LOC_DEFAULT_RANGE;
330 //////////////////////////////////////////////////////////////////////////
331 // Update the various nav values based on position and valid tuned in navs
332 //////////////////////////////////////////////////////////////////////////
334 FGNavRadio::update(double dt)
340 // Create "formatted" versions of the nav frequencies for
341 // instrument displays.
343 sprintf( tmp, "%.2f", freq_node->getDoubleValue() );
344 fmt_freq_node->setStringValue(tmp);
345 sprintf( tmp, "%.2f", alt_freq_node->getDoubleValue() );
346 fmt_alt_freq_node->setStringValue(tmp);
348 if (power_btn_node->getBoolValue()
349 && (bus_power_node->getDoubleValue() > 1.0)
350 && nav_serviceable_node->getBoolValue() )
353 if (nav_slaved_to_gps_node->getBoolValue()) {
367 void FGNavRadio::clearOutputs()
369 inrange_node->setBoolValue( false );
370 cdi_deflection_node->setDoubleValue( 0.0 );
371 cdi_deflection_norm_node->setDoubleValue( 0.0 );
372 cdi_xtrack_error_node->setDoubleValue( 0.0 );
373 cdi_xtrack_hdg_err_node->setDoubleValue( 0.0 );
374 time_to_intercept->setDoubleValue( 0.0 );
375 gs_deflection_node->setDoubleValue( 0.0 );
376 gs_deflection_deg_node->setDoubleValue(0.0);
377 gs_deflection_norm_node->setDoubleValue(0.0);
378 gs_inrange_node->setBoolValue( false );
379 loc_node->setBoolValue( false );
380 has_gs_node->setBoolValue(false);
382 to_flag_node->setBoolValue( false );
383 from_flag_node->setBoolValue( false );
389 void FGNavRadio::updateReceiver(double dt)
391 // Do a nav station search only once a second to reduce
392 // unnecessary work. (Also, make sure to do this before caching
394 _time_before_search_sec -= dt;
395 if ( _time_before_search_sec < 0 ) {
400 _cdiDeflection = 0.0;
401 _cdiCrossTrackErrorM = 0.0;
402 _toFlag = _fromFlag = false;
403 _gsNeedleDeflection = 0.0;
404 _gsNeedleDeflectionNorm = 0.0;
405 inrange_node->setBoolValue(false);
409 SGGeod pos = SGGeod::fromDegFt(lon_node->getDoubleValue(),
410 lat_node->getDoubleValue(),
411 alt_node->getDoubleValue());
413 double nav_elev = _navaid->get_elev_ft();
414 SGVec3d aircraft = SGVec3d::fromGeod(pos);
415 double loc_dist = dist(aircraft, _navaid->cart());
416 loc_dist_node->setDoubleValue( loc_dist );
417 bool is_loc = loc_node->getBoolValue();
418 double signal_quality_norm = signal_quality_norm_node->getDoubleValue();
421 //////////////////////////////////////////////////////////
422 // compute forward and reverse wgs84 headings to localizer
423 //////////////////////////////////////////////////////////
425 SGGeodesy::inverse(pos, _navaid->geod(), hdg, az2, s);
426 heading_node->setDoubleValue(hdg);
427 double radial = az2 - twist;
428 double recip = radial + 180.0;
429 SG_NORMALIZE_RANGE(recip, 0.0, 360.0);
430 radial_node->setDoubleValue( radial );
431 recip_radial_node->setDoubleValue( recip );
433 //////////////////////////////////////////////////////////
434 // compute the target/selected radial in "true" heading
435 //////////////////////////////////////////////////////////
437 target_radial = sel_radial_node->getDoubleValue();
440 // VORs need twist (mag-var) added; ILS/LOCs don't but we set twist to 0.0
441 double trtrue = target_radial + twist;
442 SG_NORMALIZE_RANGE(trtrue, 0.0, 360.0);
443 target_radial_true_node->setDoubleValue( trtrue );
445 //////////////////////////////////////////////////////////
446 // adjust reception range for altitude
447 // FIXME: make sure we are using the navdata range now that
448 // it is valid in the data file
449 //////////////////////////////////////////////////////////
451 double offset = radial - target_radial;
452 SG_NORMALIZE_RANGE(offset, -180.0, 180.0);
454 = adjustILSRange( nav_elev, pos.getElevationM(), offset,
455 loc_dist * SG_METER_TO_NM );
458 = adjustNavRange( nav_elev, pos.getElevationM(), _navaid->get_range() );
461 double effective_range_m = effective_range * SG_NM_TO_METER;
463 //////////////////////////////////////////////////////////
464 // compute signal quality
465 // 100% within effective_range
466 // decreases 1/x^2 further out
467 //////////////////////////////////////////////////////////
468 double last_signal_quality_norm = signal_quality_norm;
470 if ( loc_dist < effective_range_m ) {
471 signal_quality_norm = 1.0;
473 double range_exceed_norm = loc_dist/effective_range_m;
474 signal_quality_norm = 1/(range_exceed_norm*range_exceed_norm);
477 signal_quality_norm = fgGetLowPass( last_signal_quality_norm,
478 signal_quality_norm, dt );
480 signal_quality_norm_node->setDoubleValue( signal_quality_norm );
481 bool inrange = signal_quality_norm > 0.2;
482 inrange_node->setBoolValue( inrange );
484 //////////////////////////////////////////////////////////
485 // compute to/from flag status
486 //////////////////////////////////////////////////////////
491 double offset = fabs(radial - target_radial);
492 _toFlag = (offset > 90.0 && offset < 270.0);
494 _fromFlag = !_toFlag;
496 _toFlag = _fromFlag = false;
500 double r = target_radial - radial;
501 SG_NORMALIZE_RANGE(r, -180.0, 180.0);
504 if (falseCoursesEnabledNode->getBoolValue()) {
505 // The factor of 30.0 gives a period of 120 which gives us 3 cycles and six
506 // zeros i.e. six courses: one front course, one back course, and four
507 // false courses. Three of the six are reverse sensing.
508 _cdiDeflection = 30.0 * sawtooth(r / 30.0);
510 // no false courses, but we do need to create a back course
511 if (fabs(r) > 90.0) { // front course
512 _cdiDeflection = r - copysign(180.0, r);
514 _cdiDeflection = r; // back course
517 _cdiDeflection = -_cdiDeflection; // reverse for outbound radial
518 } // of false courses disabled
520 const double VOR_FULL_ARC = 20.0; // VOR is -10 .. 10 degree swing
521 _cdiDeflection *= VOR_FULL_ARC / _localizerWidth; // increased localiser sensitivity
523 if (backcourse_node->getBoolValue()) {
524 _cdiDeflection = -_cdiDeflection;
527 // handle the TO side of the VOR
528 if (fabs(r) > 90.0) {
529 r = ( r<0.0 ? -r-180.0 : -r+180.0 );
532 } // of non-localiser case
534 SG_CLAMP_RANGE(_cdiDeflection, -10.0, 10.0 );
535 _cdiDeflection *= signal_quality_norm;
537 // cross-track error (in metres)
538 _cdiCrossTrackErrorM = loc_dist * sin(r * SGD_DEGREES_TO_RADIANS);
540 updateGlideSlope(dt, aircraft, signal_quality_norm);
543 last_loc_dist = loc_dist;
546 void FGNavRadio::updateGlideSlope(double dt, const SGVec3d& aircraft, double signal_quality_norm)
548 _gsNeedleDeflection = 0.0;
549 if (!_gs || !inrange_node->getBoolValue()) {
550 gs_dist_node->setDoubleValue( 0.0 );
551 gs_inrange_node->setBoolValue(false);
552 _gsNeedleDeflection = 0.0;
553 _gsNeedleDeflectionNorm = 0.0;
557 double gsDist = dist(aircraft, _gsCart);
558 gs_dist_node->setDoubleValue(gsDist);
559 bool gsInRange = (gsDist < (_gs->get_range() * SG_NM_TO_METER));
560 gs_inrange_node->setBoolValue(gsInRange);
563 _gsNeedleDeflection = 0.0;
564 _gsNeedleDeflectionNorm = 0.0;
568 SGVec3d pos = aircraft - _gsCart; // relative vector from gs antenna to aircraft
569 // The positive GS axis points along the runway in the landing direction,
570 // toward the far end, not toward the approach area, so we need a - sign here:
571 double dot_h = -dot(pos, _gsAxis);
572 double dot_v = dot(pos, _gsVertical);
573 double angle = atan2(dot_v, dot_h) * SGD_RADIANS_TO_DEGREES;
574 double deflectionAngle = target_gs - angle;
576 if (falseCoursesEnabledNode->getBoolValue()) {
577 // Construct false glideslopes. The scale factor of 1.5
578 // in the sawtooth gives a period of 6 degrees.
579 // There will be zeros at 3, 6r, 9, 12r et cetera
580 // where "r" indicates reverse sensing.
581 // This is is consistent with conventional pilot lore
582 // e.g. http://www.allstar.fiu.edu/aerojava/ILS.htm
583 // but inconsistent with
584 // http://www.freepatentsonline.com/3757338.html
586 // It may be that some of each exist.
587 if (deflectionAngle < 0) {
588 deflectionAngle = 1.5 * sawtooth(deflectionAngle / 1.5);
590 // no false GS below the true GS
594 _gsNeedleDeflection = deflectionAngle * 5.0;
595 _gsNeedleDeflection *= signal_quality_norm;
597 SG_CLAMP_RANGE(deflectionAngle, -0.7, 0.7);
598 _gsNeedleDeflectionNorm = (deflectionAngle / 0.7) * signal_quality_norm;
600 //////////////////////////////////////////////////////////
601 // Calculate desired rate of climb for intercepting the GS
602 //////////////////////////////////////////////////////////
603 double gs_diff = target_gs - angle;
604 // convert desired vertical path angle into a climb rate
605 double des_angle = angle - 10 * gs_diff;
606 /* printf("target_gs=%.1f angle=%.1f gs_diff=%.1f des_angle=%.1f\n",
607 target_gs, angle, gs_diff, des_angle); */
609 // estimate horizontal speed towards ILS in meters per minute
610 double elapsedDistance = last_x - gsDist;
613 double new_vel = ( elapsedDistance / dt );
614 horiz_vel = 0.99 * horiz_vel + 0.01 * new_vel;
615 /* printf("vel=%.1f (dist=%.1f dt=%.2f)\n", horiz_vel, elapsedDistance, dt);*/
617 gs_rate_of_climb_node
618 ->setDoubleValue( -sin( des_angle * SGD_DEGREES_TO_RADIANS )
619 * horiz_vel * SG_METER_TO_FEET );
620 gs_rate_of_climb_fpm_node
621 ->setDoubleValue( gs_rate_of_climb_node->getDoubleValue() * 60 );
624 void FGNavRadio::updateDME(const SGVec3d& aircraft)
626 if (!_dme || !dme_serviceable_node->getBoolValue()) {
631 double dme_distance = dist(aircraft, _dme->cart());
632 _dmeInRange = (dme_distance < _dme->get_range() * SG_NM_TO_METER);
635 void FGNavRadio::valueChanged (SGPropertyNode* prop)
637 if (prop == gps_course_node) {
638 if (!nav_slaved_to_gps_node->getBoolValue()) {
642 // GPS desired course has changed, sync up our selected-course
643 double v = prop->getDoubleValue();
644 if (v != sel_radial_node->getDoubleValue()) {
645 sel_radial_node->setDoubleValue(v);
647 } else if (prop == nav_slaved_to_gps_node) {
648 if (prop->getBoolValue()) {
649 // slaved-to-GPS activated, sync up selected course
650 sel_radial_node->setDoubleValue(gps_course_node->getDoubleValue());
655 void FGNavRadio::updateGPSSlaved()
657 has_gs_node->setBoolValue(gps_has_gs_node->getBoolValue());
659 _toFlag = gps_to_flag_node->getBoolValue();
660 _fromFlag = gps_from_flag_node->getBoolValue();
662 bool gpsValid = (_toFlag | _fromFlag);
663 inrange_node->setBoolValue(gpsValid);
665 signal_quality_norm_node->setDoubleValue(0.0);
666 _cdiDeflection = 0.0;
667 _cdiCrossTrackErrorM = 0.0;
668 _gsNeedleDeflection = 0.0;
672 // this is unfortunate, but panel instruments use this value to decide
673 // if the navradio output is valid.
674 signal_quality_norm_node->setDoubleValue(1.0);
676 _cdiDeflection = gps_cdi_deflection_node->getDoubleValue();
677 // clmap to some range (+/- 10 degrees) as the regular deflection
678 SG_CLAMP_RANGE(_cdiDeflection, -10.0, 10.0 );
680 _cdiCrossTrackErrorM = gps_xtrack_error_nm_node->getDoubleValue() * SG_NM_TO_METER;
681 _gsNeedleDeflection = 0.0; // FIXME, supply this
683 double trtrue = gps_course_node->getDoubleValue() + _magvarNode->getDoubleValue();
684 SG_NORMALIZE_RANGE(trtrue, 0.0, 360.0);
685 target_radial_true_node->setDoubleValue( trtrue );
688 void FGNavRadio::updateCDI(double dt)
690 bool cdi_serviceable = cdi_serviceable_node->getBoolValue();
691 bool inrange = inrange_node->getBoolValue();
693 if (tofrom_serviceable_node->getBoolValue()) {
694 to_flag_node->setBoolValue(_toFlag);
695 from_flag_node->setBoolValue(_fromFlag);
697 to_flag_node->setBoolValue(false);
698 from_flag_node->setBoolValue(false);
701 if (!cdi_serviceable) {
702 _cdiDeflection = 0.0;
703 _cdiCrossTrackErrorM = 0.0;
706 cdi_deflection_node->setDoubleValue(_cdiDeflection);
707 cdi_deflection_norm_node->setDoubleValue(_cdiDeflection * 0.1);
708 cdi_xtrack_error_node->setDoubleValue(_cdiCrossTrackErrorM);
710 //////////////////////////////////////////////////////////
711 // compute an approximate ground track heading error
712 //////////////////////////////////////////////////////////
713 double hdg_error = 0.0;
714 if ( inrange && cdi_serviceable ) {
715 double vn = fgGetDouble( "/velocities/speed-north-fps" );
716 double ve = fgGetDouble( "/velocities/speed-east-fps" );
717 double gnd_trk_true = atan2( ve, vn ) * SGD_RADIANS_TO_DEGREES;
718 if ( gnd_trk_true < 0.0 ) { gnd_trk_true += 360.0; }
720 SGPropertyNode *true_hdg
721 = fgGetNode("/orientation/heading-deg", true);
722 hdg_error = gnd_trk_true - true_hdg->getDoubleValue();
724 // cout << "ground track = " << gnd_trk_true
725 // << " orientation = " << true_hdg->getDoubleValue() << endl;
727 cdi_xtrack_hdg_err_node->setDoubleValue( hdg_error );
729 //////////////////////////////////////////////////////////
730 // Calculate a suggested target heading to smoothly intercept
732 //////////////////////////////////////////////////////////
734 // Now that we have cross track heading adjustment built in,
735 // we shouldn't need to overdrive the heading angle within 8km
738 // The cdi deflection should be +/-10 for a full range of deflection
739 // so multiplying this by 3 gives us +/- 30 degrees heading
741 double adjustment = _cdiDeflection * 3.0;
742 SG_CLAMP_RANGE( adjustment, -30.0, 30.0 );
744 // determine the target heading to fly to intercept the
745 // tgt_radial = target radial (true) + cdi offset adjustmest -
746 // xtrack heading error adjustment
748 double trtrue = target_radial_true_node->getDoubleValue();
749 if ( loc_node->getBoolValue() && backcourse_node->getBoolValue() ) {
750 // tuned to a localizer and backcourse mode activated
751 trtrue += 180.0; // reverse the target localizer heading
752 SG_NORMALIZE_RANGE(trtrue, 0.0, 360.0);
753 nta_hdg = trtrue - adjustment - hdg_error;
755 nta_hdg = trtrue + adjustment - hdg_error;
758 SG_NORMALIZE_RANGE(nta_hdg, 0.0, 360.0);
759 target_auto_hdg_node->setDoubleValue( nta_hdg );
761 //////////////////////////////////////////////////////////
762 // compute the time to intercept selected radial (based on
763 // current and last cross track errors and dt
764 //////////////////////////////////////////////////////////
766 if ( inrange && cdi_serviceable ) {
767 double cur_rate = (last_xtrack_error - _cdiCrossTrackErrorM) / dt;
768 xrate_ms = 0.99 * xrate_ms + 0.01 * cur_rate;
769 if ( fabs(xrate_ms) > 0.00001 ) {
770 t = _cdiCrossTrackErrorM / xrate_ms;
775 time_to_intercept->setDoubleValue( t );
777 if (!gs_serviceable_node->getBoolValue() ) {
778 _gsNeedleDeflection = 0.0;
779 _gsNeedleDeflectionNorm = 0.0;
781 gs_deflection_node->setDoubleValue(_gsNeedleDeflection);
782 gs_deflection_deg_node->setDoubleValue(_gsNeedleDeflectionNorm * 0.7);
783 gs_deflection_norm_node->setDoubleValue(_gsNeedleDeflectionNorm);
785 last_xtrack_error = _cdiCrossTrackErrorM;
788 void FGNavRadio::updateAudio()
790 if (!_navaid || !inrange_node->getBoolValue() || !nav_serviceable_node->getBoolValue()) {
794 // play station ident via audio system if on + ident,
795 // otherwise turn it off
796 if (!power_btn_node->getBoolValue()
797 || !(bus_power_node->getDoubleValue() > 1.0)
798 || !ident_btn_node->getBoolValue()
799 || !audio_btn_node->getBoolValue() ) {
800 _sgr->stop( nav_fx_name );
801 _sgr->stop( dme_fx_name );
805 SGSoundSample *sound = _sgr->find( nav_fx_name );
806 double vol = vol_btn_node->getFloatValue();
807 SG_CLAMP_RANGE(vol, 0.0, 1.0);
809 if ( sound != NULL ) {
810 sound->set_volume( vol );
812 SG_LOG( SG_COCKPIT, SG_ALERT, "Can't find nav-vor-ident sound" );
815 sound = _sgr->find( dme_fx_name );
816 if ( sound != NULL ) {
817 sound->set_volume( vol );
819 SG_LOG( SG_COCKPIT, SG_ALERT, "Can't find nav-dme-ident sound" );
822 const int NUM_IDENT_SLOTS = 5;
823 const time_t SLOT_LENGTH = 5; // seconds
825 // There are N slots numbered 0 through (NUM_IDENT_SLOTS-1) inclusive.
826 // Each slot is 5 seconds long.
827 // Slots 0 is for DME
828 // the rest are for azimuth.
829 time_t now = globals->get_time_params()->get_cur_time();
830 if ((now >= last_time) && (now < last_time + SLOT_LENGTH)) {
831 return; // wait longer
835 play_count = ++play_count % NUM_IDENT_SLOTS;
837 // Previous ident is out of time; if still playing, cut it off:
838 _sgr->stop( nav_fx_name );
839 _sgr->stop( dme_fx_name );
840 if (play_count == 0) { // the DME slot
841 if (_dmeInRange && dme_serviceable_node->getBoolValue()) {
843 if (vol > 0.05) _sgr->play_once( dme_fx_name );
846 if (inrange_node->getBoolValue() && nav_serviceable_node->getBoolValue()) {
847 if (vol > 0.05) _sgr->play_once(nav_fx_name);
852 FGNavRecord* FGNavRadio::findPrimaryNavaid(const SGGeod& aPos, double aFreqMHz)
854 FGNavRecord* nav = globals->get_navlist()->findByFreq(aFreqMHz, aPos);
859 return globals->get_loclist()->findByFreq(aFreqMHz, aPos);
862 // Update current nav/adf radio stations based on current postition
863 void FGNavRadio::search()
865 _time_before_search_sec = 1.0;
866 SGGeod pos = SGGeod::fromDegFt(lon_node->getDoubleValue(),
867 lat_node->getDoubleValue(), alt_node->getDoubleValue());
868 double freq = freq_node->getDoubleValue();
870 FGNavRecord* nav = findPrimaryNavaid(pos, freq);
871 if (nav == _navaid) {
872 return; // found the same as last search, we're done
876 char identBuffer[5] = " ";
878 _dme = globals->get_dmelist()->findByFreq(freq, pos);
880 nav_id_node->setStringValue(nav->get_ident());
881 strncpy(identBuffer, nav->ident().c_str(), 5);
883 effective_range = adjustNavRange(nav->get_elev_ft(), pos.getElevationM(), nav->get_range());
884 loc_node->setBoolValue(nav->type() != FGPositioned::VOR);
885 twist = nav->get_multiuse();
887 if (nav->type() == FGPositioned::VOR) {
888 target_radial = sel_radial_node->getDoubleValue();
890 has_gs_node->setBoolValue(false);
891 } else { // ILS or LOC
892 _gs = globals->get_gslist()->findByFreq(freq, pos);
893 has_gs_node->setBoolValue(_gs != NULL);
894 _localizerWidth = nav->localizerWidth();
896 effective_range = nav->get_range();
898 target_radial = nav->get_multiuse();
899 SG_NORMALIZE_RANGE(target_radial, 0.0, 360.0);
902 int tmp = (int)(_gs->get_multiuse() / 1000.0);
903 target_gs = (double)tmp / 100.0;
905 // until penaltyForNav goes away, we cannot assume we always pick
906 // paired LOC/GS trasmsitters. As we pass over a runway threshold, we
907 // often end up picking the 'wrong' LOC, but the correct GS. To avoid
908 // breaking the basis computation, ensure we use the GS radial and not
909 // the (potentially reversed) LOC radial.
910 double gs_radial = fmod(_gs->get_multiuse(), 1000.0);
911 SG_NORMALIZE_RANGE(gs_radial, 0.0, 360.0);
913 // GS axis unit tangent vector
914 // (along the runway)
915 _gsCart = _gs->cart();
916 _gsAxis = tangentVector(_gs->geod(), _gsCart, gs_radial);
918 // GS baseline unit tangent vector
919 // (perpendicular to the runay along the ground)
920 SGVec3d baseline = tangentVector(_gs->geod(), _gsCart, gs_radial + 90.0);
921 _gsVertical = cross(baseline, _gsAxis);
922 } // of have glideslope
923 } // of found LOC or ILS
926 } else { // found nothing
929 nav_id_node->setStringValue("");
930 loc_node->setBoolValue(false);
931 has_gs_node->setBoolValue(false);
933 _sgr->remove( nav_fx_name );
934 _sgr->remove( dme_fx_name );
937 is_valid_node->setBoolValue(nav != NULL);
938 id_c1_node->setIntValue( (int)identBuffer[0] );
939 id_c2_node->setIntValue( (int)identBuffer[1] );
940 id_c3_node->setIntValue( (int)identBuffer[2] );
941 id_c4_node->setIntValue( (int)identBuffer[3] );
944 void FGNavRadio::audioNavidChanged()
946 if (_sgr->exists(nav_fx_name)) {
947 _sgr->remove(nav_fx_name);
951 string trans_ident(_navaid->get_trans_ident());
952 SGSoundSample* sound = morse.make_ident(trans_ident, LO_FREQUENCY);
953 sound->set_volume( 0.3 );
954 if (!_sgr->add( sound, nav_fx_name )) {
955 SG_LOG(SG_COCKPIT, SG_WARN, "Failed to add v1-vor-ident sound");
958 if ( _sgr->exists( dme_fx_name ) ) {
959 _sgr->remove( dme_fx_name );
962 sound = morse.make_ident( trans_ident, HI_FREQUENCY );
963 sound->set_volume( 0.3 );
964 _sgr->add( sound, dme_fx_name );
966 int offset = (int)(sg_random() * 30.0);
967 play_count = offset / 4;
968 last_time = globals->get_time_params()->get_cur_time() - offset;
969 } catch (sg_io_exception& e) {
970 SG_LOG(SG_GENERAL, SG_ALERT, e.getFormattedMessage());