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"
33 #include <simgear/sg_inlines.h>
34 #include <simgear/timing/sg_time.hxx>
35 #include <simgear/math/sg_random.h>
36 #include <simgear/misc/sg_path.hxx>
37 #include <simgear/math/sg_geodesy.hxx>
38 #include <simgear/structure/exception.hxx>
39 #include <simgear/math/interpolater.hxx>
40 #include <simgear/misc/strutils.hxx>
42 #include <Navaids/navrecord.hxx>
44 #include <Airports/runways.hxx>
45 #include <Navaids/navlist.hxx>
46 #include <Main/util.hxx>
51 // General-purpose sawtooth function. Graph looks like this:
54 // Odd symmetry, inversion symmetry about the origin.
55 // Unit slope at the origin.
56 // Max 1, min -1, period 4.
57 // Two zero-crossings per period, one with + slope, one with - slope.
58 // Useful for false localizer courses.
59 static double sawtooth(double xx)
61 return 4.0 * fabs(xx/4.0 + 0.25 - floor(xx/4.0 + 0.75)) - 1.0;
64 // Calculate a unit vector in the horizontal tangent plane
65 // starting at the given "tail" of the vector and going off
66 // with the given heading.
67 static SGVec3d tangentVector(const SGGeod& tail, const SGVec3d& tail_xyz,
70 // The fudge factor here is presumably intended to improve
71 // numerical stability. I don't know if it is necessary.
72 // It gets divided out later.
75 double az2; // ignored
76 SGGeodesy::direct(tail, heading, fudge, head, az2);
77 head.setElevationM(tail.getElevationM());
78 SGVec3d head_xyz = SGVec3d::fromGeod(head);
79 return (head_xyz - tail_xyz) * (1.0/fudge);
82 // Create a "serviceable" node with a default value of "true"
83 SGPropertyNode_ptr createServiceableProp(SGPropertyNode* aParent, const char* aName)
85 SGPropertyNode_ptr n = (aParent->getChild(aName, 0, true)->getChild("serviceable", 0, true));
86 simgear::props::Type typ = n->getType();
87 if ((typ == simgear::props::NONE) || (typ == simgear::props::UNSPECIFIED)) {
88 n->setBoolValue(true);
94 FGNavRadio::FGNavRadio(SGPropertyNode *node) :
95 lon_node(fgGetNode("/position/longitude-deg", true)),
96 lat_node(fgGetNode("/position/latitude-deg", true)),
97 alt_node(fgGetNode("/position/altitude-ft", true)),
104 last_xtrack_error(0.0),
106 _localizerWidth(5.0),
107 _name(node->getStringValue("name", "nav")),
108 _num(node->getIntValue("number", 0)),
109 _time_before_search_sec(-1.0),
112 SGPath path( globals->get_fg_root() );
114 term.append( "Navaids/range.term" );
116 low.append( "Navaids/range.low" );
118 high.append( "Navaids/range.high" );
120 term_tbl = new SGInterpTable( term.str() );
121 low_tbl = new SGInterpTable( low.str() );
122 high_tbl = new SGInterpTable( high.str() );
125 string branch("/instrumentation/" + _name);
126 _radio_node = fgGetNode(branch.c_str(), _num, true);
131 FGNavRadio::~FGNavRadio()
133 if (gps_course_node) {
134 gps_course_node->removeChangeListener(this);
137 if (nav_slaved_to_gps_node) {
138 nav_slaved_to_gps_node->removeChangeListener(this);
150 SGSoundMgr *smgr = globals->get_soundmgr();
151 _sgr = smgr->find("avionics", true);
152 _sgr->tie_to_listener();
156 SGPropertyNode* node = _radio_node.get();
158 fgGetNode(("/systems/electrical/outputs/" + _name).c_str(), true);
161 is_valid_node = node->getChild("data-is-valid", 0, true);
162 power_btn_node = node->getChild("power-btn", 0, true);
163 power_btn_node->setBoolValue( true );
164 vol_btn_node = node->getChild("volume", 0, true);
165 ident_btn_node = node->getChild("ident", 0, true);
166 ident_btn_node->setBoolValue( true );
167 audio_btn_node = node->getChild("audio-btn", 0, true);
168 audio_btn_node->setBoolValue( true );
169 backcourse_node = node->getChild("back-course-btn", 0, true);
170 backcourse_node->setBoolValue( false );
172 nav_serviceable_node = node->getChild("serviceable", 0, true);
173 cdi_serviceable_node = createServiceableProp(node, "cdi");
174 gs_serviceable_node = createServiceableProp(node, "gs");
175 tofrom_serviceable_node = createServiceableProp(node, "to-from");
176 dme_serviceable_node = createServiceableProp(node, "dme");
178 falseCoursesEnabledNode =
179 fgGetNode("/sim/realism/false-radio-courses-enabled");
180 if (!falseCoursesEnabledNode) {
181 falseCoursesEnabledNode =
182 fgGetNode("/sim/realism/false-radio-courses-enabled", true);
183 falseCoursesEnabledNode->setBoolValue(true);
187 SGPropertyNode *subnode = node->getChild("frequencies", 0, true);
188 freq_node = subnode->getChild("selected-mhz", 0, true);
189 alt_freq_node = subnode->getChild("standby-mhz", 0, true);
190 fmt_freq_node = subnode->getChild("selected-mhz-fmt", 0, true);
191 fmt_alt_freq_node = subnode->getChild("standby-mhz-fmt", 0, true);
194 subnode = node->getChild("radials", 0, true);
195 sel_radial_node = subnode->getChild("selected-deg", 0, true);
196 radial_node = subnode->getChild("actual-deg", 0, true);
197 recip_radial_node = subnode->getChild("reciprocal-radial-deg", 0, true);
198 target_radial_true_node = subnode->getChild("target-radial-deg", 0, true);
199 target_auto_hdg_node = subnode->getChild("target-auto-hdg-deg", 0, true);
202 heading_node = node->getChild("heading-deg", 0, true);
203 time_to_intercept = node->getChild("time-to-intercept-sec", 0, true);
204 to_flag_node = node->getChild("to-flag", 0, true);
205 from_flag_node = node->getChild("from-flag", 0, true);
206 inrange_node = node->getChild("in-range", 0, true);
207 signal_quality_norm_node = node->getChild("signal-quality-norm", 0, true);
208 cdi_deflection_node = node->getChild("heading-needle-deflection", 0, true);
209 cdi_deflection_norm_node = node->getChild("heading-needle-deflection-norm", 0, true);
210 cdi_xtrack_error_node = node->getChild("crosstrack-error-m", 0, true);
211 cdi_xtrack_hdg_err_node
212 = node->getChild("crosstrack-heading-error-deg", 0, true);
213 has_gs_node = node->getChild("has-gs", 0, true);
214 loc_node = node->getChild("nav-loc", 0, true);
215 loc_dist_node = node->getChild("nav-distance", 0, true);
216 gs_deflection_node = node->getChild("gs-needle-deflection", 0, true);
217 gs_deflection_deg_node = node->getChild("gs-needle-deflection-deg", 0, true);
218 gs_deflection_norm_node = node->getChild("gs-needle-deflection-norm", 0, true);
219 gs_rate_of_climb_node = node->getChild("gs-rate-of-climb", 0, true);
220 gs_rate_of_climb_fpm_node = node->getChild("gs-rate-of-climb-fpm", 0, true);
221 gs_dist_node = node->getChild("gs-distance", 0, true);
222 gs_inrange_node = node->getChild("gs-in-range", 0, true);
224 nav_id_node = node->getChild("nav-id", 0, true);
225 id_c1_node = node->getChild("nav-id_asc1", 0, true);
226 id_c2_node = node->getChild("nav-id_asc2", 0, true);
227 id_c3_node = node->getChild("nav-id_asc3", 0, true);
228 id_c4_node = node->getChild("nav-id_asc4", 0, true);
230 // gps slaving support
231 nav_slaved_to_gps_node = node->getChild("slaved-to-gps", 0, true);
232 nav_slaved_to_gps_node->addChangeListener(this);
234 gps_cdi_deflection_node = fgGetNode("/instrumentation/gps/cdi-deflection", true);
235 gps_to_flag_node = fgGetNode("/instrumentation/gps/to-flag", true);
236 gps_from_flag_node = fgGetNode("/instrumentation/gps/from-flag", true);
237 gps_has_gs_node = fgGetNode("/instrumentation/gps/has-gs", true);
238 gps_course_node = fgGetNode("/instrumentation/gps/desired-course-deg", true);
239 gps_course_node->addChangeListener(this);
241 gps_xtrack_error_nm_node = fgGetNode("/instrumentation/gps/wp/wp[1]/course-error-nm", true);
242 _magvarNode = fgGetNode("/environment/magnetic-variation-deg", true);
244 std::ostringstream temp;
245 temp << _name << "nav-ident" << _num;
246 nav_fx_name = temp.str();
247 temp << _name << "dme-ident" << _num;
248 dme_fx_name = temp.str();
254 tie("dme-in-range", SGRawValuePointer<bool>(&_dmeInRange));
255 tie("operable", SGRawValueMethods<FGNavRadio, bool>(*this, &FGNavRadio::isOperable, NULL));
260 FGNavRadio::unbind ()
262 for (unsigned int t=0; t<_tiedNodes.size(); ++t) {
263 _tiedNodes[t]->untie();
269 // model standard VOR/DME/TACAN service volumes as per AIM 1-1-8
270 double FGNavRadio::adjustNavRange( double stationElev, double aircraftElev,
271 double nominalRange )
273 if (nominalRange <= 0.0) {
274 nominalRange = FG_NAV_DEFAULT_RANGE;
277 // extend out actual usable range to be 1.3x the published safe range
278 const double usability_factor = 1.3;
280 // assumptions we model the standard service volume, plus
281 // ... rather than specifying a cylinder, we model a cone that
282 // contains the cylinder. Then we put an upside down cone on top
283 // to model diminishing returns at too-high altitudes.
285 // altitude difference
286 double alt = ( aircraftElev * SG_METER_TO_FEET - stationElev );
287 // cout << "aircraft elev = " << aircraftElev * SG_METER_TO_FEET
288 // << " station elev = " << stationElev << endl;
290 if ( nominalRange < 25.0 + SG_EPSILON ) {
291 // Standard Terminal Service Volume
292 return term_tbl->interpolate( alt ) * usability_factor;
293 } else if ( nominalRange < 50.0 + SG_EPSILON ) {
294 // Standard Low Altitude Service Volume
295 // table is based on range of 40, scale to actual range
296 return low_tbl->interpolate( alt ) * nominalRange / 40.0
299 // Standard High Altitude Service Volume
300 // table is based on range of 130, scale to actual range
301 return high_tbl->interpolate( alt ) * nominalRange / 130.0
307 // model standard ILS service volumes as per AIM 1-1-9
308 double FGNavRadio::adjustILSRange( double stationElev, double aircraftElev,
309 double offsetDegrees, double distance )
311 // assumptions we model the standard service volume, plus
313 // altitude difference
314 // double alt = ( aircraftElev * SG_METER_TO_FEET - stationElev );
315 // double offset = fabs( offsetDegrees );
317 // if ( offset < 10 ) {
318 // return FG_ILS_DEFAULT_RANGE;
319 // } else if ( offset < 35 ) {
320 // return 10 + (35 - offset) * (FG_ILS_DEFAULT_RANGE - 10) / 25;
321 // } else if ( offset < 45 ) {
322 // return (45 - offset);
323 // } else if ( offset > 170 ) {
324 // return FG_ILS_DEFAULT_RANGE;
325 // } else if ( offset > 145 ) {
326 // return 10 + (offset - 145) * (FG_ILS_DEFAULT_RANGE - 10) / 25;
327 // } else if ( offset > 135 ) {
328 // return (offset - 135);
332 return FG_LOC_DEFAULT_RANGE;
336 //////////////////////////////////////////////////////////////////////////
337 // Update the various nav values based on position and valid tuned in navs
338 //////////////////////////////////////////////////////////////////////////
340 FGNavRadio::update(double dt)
346 // Create "formatted" versions of the nav frequencies for
347 // instrument displays.
349 sprintf( tmp, "%.2f", freq_node->getDoubleValue() );
350 fmt_freq_node->setStringValue(tmp);
351 sprintf( tmp, "%.2f", alt_freq_node->getDoubleValue() );
352 fmt_alt_freq_node->setStringValue(tmp);
354 if (power_btn_node->getBoolValue()
355 && (bus_power_node->getDoubleValue() > 1.0)
356 && nav_serviceable_node->getBoolValue() )
359 if (nav_slaved_to_gps_node->getBoolValue()) {
373 void FGNavRadio::clearOutputs()
375 inrange_node->setBoolValue( false );
376 cdi_deflection_node->setDoubleValue( 0.0 );
377 cdi_deflection_norm_node->setDoubleValue( 0.0 );
378 cdi_xtrack_error_node->setDoubleValue( 0.0 );
379 cdi_xtrack_hdg_err_node->setDoubleValue( 0.0 );
380 time_to_intercept->setDoubleValue( 0.0 );
381 gs_deflection_node->setDoubleValue( 0.0 );
382 gs_deflection_deg_node->setDoubleValue(0.0);
383 gs_deflection_norm_node->setDoubleValue(0.0);
384 gs_inrange_node->setBoolValue( false );
385 loc_node->setBoolValue( false );
386 has_gs_node->setBoolValue(false);
388 to_flag_node->setBoolValue( false );
389 from_flag_node->setBoolValue( false );
396 void FGNavRadio::updateReceiver(double dt)
398 // Do a nav station search only once a second to reduce
399 // unnecessary work. (Also, make sure to do this before caching
401 _time_before_search_sec -= dt;
402 if ( _time_before_search_sec < 0 ) {
407 _cdiDeflection = 0.0;
408 _cdiCrossTrackErrorM = 0.0;
409 _toFlag = _fromFlag = false;
410 _gsNeedleDeflection = 0.0;
411 _gsNeedleDeflectionNorm = 0.0;
412 inrange_node->setBoolValue(false);
416 SGGeod pos = SGGeod::fromDegFt(lon_node->getDoubleValue(),
417 lat_node->getDoubleValue(),
418 alt_node->getDoubleValue());
420 double nav_elev = _navaid->get_elev_ft();
421 SGVec3d aircraft = SGVec3d::fromGeod(pos);
422 double loc_dist = dist(aircraft, _navaid->cart());
423 loc_dist_node->setDoubleValue( loc_dist );
424 bool is_loc = loc_node->getBoolValue();
425 double signal_quality_norm = signal_quality_norm_node->getDoubleValue();
428 //////////////////////////////////////////////////////////
429 // compute forward and reverse wgs84 headings to localizer
430 //////////////////////////////////////////////////////////
432 SGGeodesy::inverse(pos, _navaid->geod(), hdg, az2, s);
433 heading_node->setDoubleValue(hdg);
434 double radial = az2 - twist;
435 double recip = radial + 180.0;
436 SG_NORMALIZE_RANGE(recip, 0.0, 360.0);
437 radial_node->setDoubleValue( radial );
438 recip_radial_node->setDoubleValue( recip );
440 //////////////////////////////////////////////////////////
441 // compute the target/selected radial in "true" heading
442 //////////////////////////////////////////////////////////
444 target_radial = sel_radial_node->getDoubleValue();
447 // VORs need twist (mag-var) added; ILS/LOCs don't but we set twist to 0.0
448 double trtrue = target_radial + twist;
449 SG_NORMALIZE_RANGE(trtrue, 0.0, 360.0);
450 target_radial_true_node->setDoubleValue( trtrue );
452 //////////////////////////////////////////////////////////
453 // adjust reception range for altitude
454 // FIXME: make sure we are using the navdata range now that
455 // it is valid in the data file
456 //////////////////////////////////////////////////////////
458 double offset = radial - target_radial;
459 SG_NORMALIZE_RANGE(offset, -180.0, 180.0);
461 = adjustILSRange( nav_elev, pos.getElevationM(), offset,
462 loc_dist * SG_METER_TO_NM );
465 = adjustNavRange( nav_elev, pos.getElevationM(), _navaid->get_range() );
468 double effective_range_m = effective_range * SG_NM_TO_METER;
470 //////////////////////////////////////////////////////////
471 // compute signal quality
472 // 100% within effective_range
473 // decreases 1/x^2 further out
474 //////////////////////////////////////////////////////////
475 double last_signal_quality_norm = signal_quality_norm;
477 if ( loc_dist < effective_range_m ) {
478 signal_quality_norm = 1.0;
480 double range_exceed_norm = loc_dist/effective_range_m;
481 signal_quality_norm = 1/(range_exceed_norm*range_exceed_norm);
484 signal_quality_norm = fgGetLowPass( last_signal_quality_norm,
485 signal_quality_norm, dt );
487 signal_quality_norm_node->setDoubleValue( signal_quality_norm );
488 bool inrange = signal_quality_norm > 0.2;
489 inrange_node->setBoolValue( inrange );
491 //////////////////////////////////////////////////////////
492 // compute to/from flag status
493 //////////////////////////////////////////////////////////
498 double offset = fabs(radial - target_radial);
499 _toFlag = (offset > 90.0 && offset < 270.0);
501 _fromFlag = !_toFlag;
503 _toFlag = _fromFlag = false;
507 double r = target_radial - radial;
508 SG_NORMALIZE_RANGE(r, -180.0, 180.0);
511 if (falseCoursesEnabledNode->getBoolValue()) {
512 // The factor of 30.0 gives a period of 120 which gives us 3 cycles and six
513 // zeros i.e. six courses: one front course, one back course, and four
514 // false courses. Three of the six are reverse sensing.
515 _cdiDeflection = 30.0 * sawtooth(r / 30.0);
517 // no false courses, but we do need to create a back course
518 if (fabs(r) > 90.0) { // front course
519 _cdiDeflection = r - copysign(180.0, r);
521 _cdiDeflection = r; // back course
524 _cdiDeflection = -_cdiDeflection; // reverse for outbound radial
525 } // of false courses disabled
527 const double VOR_FULL_ARC = 20.0; // VOR is -10 .. 10 degree swing
528 _cdiDeflection *= VOR_FULL_ARC / _localizerWidth; // increased localiser sensitivity
530 if (backcourse_node->getBoolValue()) {
531 _cdiDeflection = -_cdiDeflection;
534 // handle the TO side of the VOR
535 if (fabs(r) > 90.0) {
536 r = ( r<0.0 ? -r-180.0 : -r+180.0 );
539 } // of non-localiser case
541 SG_CLAMP_RANGE(_cdiDeflection, -10.0, 10.0 );
542 _cdiDeflection *= signal_quality_norm;
544 // cross-track error (in metres)
545 _cdiCrossTrackErrorM = loc_dist * sin(r * SGD_DEGREES_TO_RADIANS);
547 updateGlideSlope(dt, aircraft, signal_quality_norm);
550 last_loc_dist = loc_dist;
553 void FGNavRadio::updateGlideSlope(double dt, const SGVec3d& aircraft, double signal_quality_norm)
555 _gsNeedleDeflection = 0.0;
556 if (!_gs || !inrange_node->getBoolValue()) {
557 gs_dist_node->setDoubleValue( 0.0 );
558 gs_inrange_node->setBoolValue(false);
559 _gsNeedleDeflection = 0.0;
560 _gsNeedleDeflectionNorm = 0.0;
564 double gsDist = dist(aircraft, _gsCart);
565 gs_dist_node->setDoubleValue(gsDist);
566 bool gsInRange = (gsDist < (_gs->get_range() * SG_NM_TO_METER));
567 gs_inrange_node->setBoolValue(gsInRange);
570 _gsNeedleDeflection = 0.0;
571 _gsNeedleDeflectionNorm = 0.0;
575 SGVec3d pos = aircraft - _gsCart; // relative vector from gs antenna to aircraft
576 // The positive GS axis points along the runway in the landing direction,
577 // toward the far end, not toward the approach area, so we need a - sign here:
578 double dot_h = -dot(pos, _gsAxis);
579 double dot_v = dot(pos, _gsVertical);
580 double angle = atan2(dot_v, dot_h) * SGD_RADIANS_TO_DEGREES;
581 double deflectionAngle = target_gs - angle;
583 if (falseCoursesEnabledNode->getBoolValue()) {
584 // Construct false glideslopes. The scale factor of 1.5
585 // in the sawtooth gives a period of 6 degrees.
586 // There will be zeros at 3, 6r, 9, 12r et cetera
587 // where "r" indicates reverse sensing.
588 // This is is consistent with conventional pilot lore
589 // e.g. http://www.allstar.fiu.edu/aerojava/ILS.htm
590 // but inconsistent with
591 // http://www.freepatentsonline.com/3757338.html
593 // It may be that some of each exist.
594 if (deflectionAngle < 0) {
595 deflectionAngle = 1.5 * sawtooth(deflectionAngle / 1.5);
597 // no false GS below the true GS
601 _gsNeedleDeflection = deflectionAngle * 5.0;
602 _gsNeedleDeflection *= signal_quality_norm;
604 SG_CLAMP_RANGE(deflectionAngle, -0.7, 0.7);
605 _gsNeedleDeflectionNorm = (deflectionAngle / 0.7) * signal_quality_norm;
607 //////////////////////////////////////////////////////////
608 // Calculate desired rate of climb for intercepting the GS
609 //////////////////////////////////////////////////////////
610 double gs_diff = target_gs - angle;
611 // convert desired vertical path angle into a climb rate
612 double des_angle = angle - 10 * gs_diff;
613 /* printf("target_gs=%.1f angle=%.1f gs_diff=%.1f des_angle=%.1f\n",
614 target_gs, angle, gs_diff, des_angle); */
616 // estimate horizontal speed towards ILS in meters per minute
617 double elapsedDistance = last_x - gsDist;
620 double new_vel = ( elapsedDistance / dt );
621 horiz_vel = 0.99 * horiz_vel + 0.01 * new_vel;
622 /* printf("vel=%.1f (dist=%.1f dt=%.2f)\n", horiz_vel, elapsedDistance, dt);*/
624 gs_rate_of_climb_node
625 ->setDoubleValue( -sin( des_angle * SGD_DEGREES_TO_RADIANS )
626 * horiz_vel * SG_METER_TO_FEET );
627 gs_rate_of_climb_fpm_node
628 ->setDoubleValue( gs_rate_of_climb_node->getDoubleValue() * 60 );
631 void FGNavRadio::updateDME(const SGVec3d& aircraft)
633 if (!_dme || !dme_serviceable_node->getBoolValue()) {
638 double dme_distance = dist(aircraft, _dme->cart());
639 _dmeInRange = (dme_distance < _dme->get_range() * SG_NM_TO_METER);
642 void FGNavRadio::valueChanged (SGPropertyNode* prop)
644 if (prop == gps_course_node) {
645 if (!nav_slaved_to_gps_node->getBoolValue()) {
649 // GPS desired course has changed, sync up our selected-course
650 double v = prop->getDoubleValue();
651 if (v != sel_radial_node->getDoubleValue()) {
652 sel_radial_node->setDoubleValue(v);
654 } else if (prop == nav_slaved_to_gps_node) {
655 if (prop->getBoolValue()) {
656 // slaved-to-GPS activated, sync up selected course
657 sel_radial_node->setDoubleValue(gps_course_node->getDoubleValue());
662 void FGNavRadio::updateGPSSlaved()
664 has_gs_node->setBoolValue(gps_has_gs_node->getBoolValue());
666 _toFlag = gps_to_flag_node->getBoolValue();
667 _fromFlag = gps_from_flag_node->getBoolValue();
669 bool gpsValid = (_toFlag | _fromFlag);
670 inrange_node->setBoolValue(gpsValid);
672 signal_quality_norm_node->setDoubleValue(0.0);
673 _cdiDeflection = 0.0;
674 _cdiCrossTrackErrorM = 0.0;
675 _gsNeedleDeflection = 0.0;
679 // this is unfortunate, but panel instruments use this value to decide
680 // if the navradio output is valid.
681 signal_quality_norm_node->setDoubleValue(1.0);
683 _cdiDeflection = gps_cdi_deflection_node->getDoubleValue();
684 // clmap to some range (+/- 10 degrees) as the regular deflection
685 SG_CLAMP_RANGE(_cdiDeflection, -10.0, 10.0 );
687 _cdiCrossTrackErrorM = gps_xtrack_error_nm_node->getDoubleValue() * SG_NM_TO_METER;
688 _gsNeedleDeflection = 0.0; // FIXME, supply this
690 double trtrue = gps_course_node->getDoubleValue() + _magvarNode->getDoubleValue();
691 SG_NORMALIZE_RANGE(trtrue, 0.0, 360.0);
692 target_radial_true_node->setDoubleValue( trtrue );
695 void FGNavRadio::updateCDI(double dt)
697 bool cdi_serviceable = cdi_serviceable_node->getBoolValue();
698 bool inrange = inrange_node->getBoolValue();
700 if (tofrom_serviceable_node->getBoolValue()) {
701 to_flag_node->setBoolValue(_toFlag);
702 from_flag_node->setBoolValue(_fromFlag);
704 to_flag_node->setBoolValue(false);
705 from_flag_node->setBoolValue(false);
708 if (!cdi_serviceable) {
709 _cdiDeflection = 0.0;
710 _cdiCrossTrackErrorM = 0.0;
713 cdi_deflection_node->setDoubleValue(_cdiDeflection);
714 cdi_deflection_norm_node->setDoubleValue(_cdiDeflection * 0.1);
715 cdi_xtrack_error_node->setDoubleValue(_cdiCrossTrackErrorM);
717 //////////////////////////////////////////////////////////
718 // compute an approximate ground track heading error
719 //////////////////////////////////////////////////////////
720 double hdg_error = 0.0;
721 if ( inrange && cdi_serviceable ) {
722 double vn = fgGetDouble( "/velocities/speed-north-fps" );
723 double ve = fgGetDouble( "/velocities/speed-east-fps" );
724 double gnd_trk_true = atan2( ve, vn ) * SGD_RADIANS_TO_DEGREES;
725 if ( gnd_trk_true < 0.0 ) { gnd_trk_true += 360.0; }
727 SGPropertyNode *true_hdg
728 = fgGetNode("/orientation/heading-deg", true);
729 hdg_error = gnd_trk_true - true_hdg->getDoubleValue();
731 // cout << "ground track = " << gnd_trk_true
732 // << " orientation = " << true_hdg->getDoubleValue() << endl;
734 cdi_xtrack_hdg_err_node->setDoubleValue( hdg_error );
736 //////////////////////////////////////////////////////////
737 // Calculate a suggested target heading to smoothly intercept
739 //////////////////////////////////////////////////////////
741 // Now that we have cross track heading adjustment built in,
742 // we shouldn't need to overdrive the heading angle within 8km
745 // The cdi deflection should be +/-10 for a full range of deflection
746 // so multiplying this by 3 gives us +/- 30 degrees heading
748 double adjustment = _cdiDeflection * 3.0;
749 SG_CLAMP_RANGE( adjustment, -30.0, 30.0 );
751 // determine the target heading to fly to intercept the
752 // tgt_radial = target radial (true) + cdi offset adjustmest -
753 // xtrack heading error adjustment
755 double trtrue = target_radial_true_node->getDoubleValue();
756 if ( loc_node->getBoolValue() && backcourse_node->getBoolValue() ) {
757 // tuned to a localizer and backcourse mode activated
758 trtrue += 180.0; // reverse the target localizer heading
759 SG_NORMALIZE_RANGE(trtrue, 0.0, 360.0);
760 nta_hdg = trtrue - adjustment - hdg_error;
762 nta_hdg = trtrue + adjustment - hdg_error;
765 SG_NORMALIZE_RANGE(nta_hdg, 0.0, 360.0);
766 target_auto_hdg_node->setDoubleValue( nta_hdg );
768 //////////////////////////////////////////////////////////
769 // compute the time to intercept selected radial (based on
770 // current and last cross track errors and dt
771 //////////////////////////////////////////////////////////
773 if ( inrange && cdi_serviceable ) {
774 double cur_rate = (last_xtrack_error - _cdiCrossTrackErrorM) / dt;
775 xrate_ms = 0.99 * xrate_ms + 0.01 * cur_rate;
776 if ( fabs(xrate_ms) > 0.00001 ) {
777 t = _cdiCrossTrackErrorM / xrate_ms;
782 time_to_intercept->setDoubleValue( t );
784 if (!gs_serviceable_node->getBoolValue() ) {
785 _gsNeedleDeflection = 0.0;
786 _gsNeedleDeflectionNorm = 0.0;
788 gs_deflection_node->setDoubleValue(_gsNeedleDeflection);
789 gs_deflection_deg_node->setDoubleValue(_gsNeedleDeflectionNorm * 0.7);
790 gs_deflection_norm_node->setDoubleValue(_gsNeedleDeflectionNorm);
792 last_xtrack_error = _cdiCrossTrackErrorM;
795 void FGNavRadio::updateAudio()
797 if (!_navaid || !inrange_node->getBoolValue() || !nav_serviceable_node->getBoolValue()) {
801 // play station ident via audio system if on + ident,
802 // otherwise turn it off
803 if (!power_btn_node->getBoolValue()
804 || !(bus_power_node->getDoubleValue() > 1.0)
805 || !ident_btn_node->getBoolValue()
806 || !audio_btn_node->getBoolValue() ) {
807 _sgr->stop( nav_fx_name );
808 _sgr->stop( dme_fx_name );
812 SGSoundSample *sound = _sgr->find( nav_fx_name );
813 double vol = vol_btn_node->getFloatValue();
814 SG_CLAMP_RANGE(vol, 0.0, 1.0);
816 if ( sound != NULL ) {
817 sound->set_volume( vol );
819 SG_LOG( SG_COCKPIT, SG_ALERT, "Can't find nav-vor-ident sound" );
822 sound = _sgr->find( dme_fx_name );
823 if ( sound != NULL ) {
824 sound->set_volume( vol );
826 SG_LOG( SG_COCKPIT, SG_ALERT, "Can't find nav-dme-ident sound" );
829 const int NUM_IDENT_SLOTS = 5;
830 const time_t SLOT_LENGTH = 5; // seconds
832 // There are N slots numbered 0 through (NUM_IDENT_SLOTS-1) inclusive.
833 // Each slot is 5 seconds long.
834 // Slots 0 is for DME
835 // the rest are for azimuth.
836 time_t now = globals->get_time_params()->get_cur_time();
837 if ((now >= last_time) && (now < last_time + SLOT_LENGTH)) {
838 return; // wait longer
842 play_count = ++play_count % NUM_IDENT_SLOTS;
844 // Previous ident is out of time; if still playing, cut it off:
845 _sgr->stop( nav_fx_name );
846 _sgr->stop( dme_fx_name );
847 if (play_count == 0) { // the DME slot
848 if (_dmeInRange && dme_serviceable_node->getBoolValue()) {
850 if (vol > 0.05) _sgr->play_once( dme_fx_name );
853 if (inrange_node->getBoolValue() && nav_serviceable_node->getBoolValue()) {
854 if (vol > 0.05) _sgr->play_once(nav_fx_name);
859 FGNavRecord* FGNavRadio::findPrimaryNavaid(const SGGeod& aPos, double aFreqMHz)
861 FGNavRecord* nav = globals->get_navlist()->findByFreq(aFreqMHz, aPos);
866 return globals->get_loclist()->findByFreq(aFreqMHz, aPos);
869 // Update current nav/adf radio stations based on current postition
870 void FGNavRadio::search()
872 _time_before_search_sec = 1.0;
873 SGGeod pos = SGGeod::fromDegFt(lon_node->getDoubleValue(),
874 lat_node->getDoubleValue(), alt_node->getDoubleValue());
875 double freq = freq_node->getDoubleValue();
877 FGNavRecord* nav = findPrimaryNavaid(pos, freq);
878 if (nav == _navaid) {
879 return; // found the same as last search, we're done
883 string identBuffer(4, ' ');
885 _dme = globals->get_dmelist()->findByFreq(freq, pos);
887 nav_id_node->setStringValue(nav->get_ident());
888 identBuffer = simgear::strutils::rpad( nav->ident(), 4, ' ' );
890 effective_range = adjustNavRange(nav->get_elev_ft(), pos.getElevationM(), nav->get_range());
891 loc_node->setBoolValue(nav->type() != FGPositioned::VOR);
892 twist = nav->get_multiuse();
894 if (nav->type() == FGPositioned::VOR) {
895 target_radial = sel_radial_node->getDoubleValue();
897 has_gs_node->setBoolValue(false);
898 } else { // ILS or LOC
899 _gs = globals->get_gslist()->findByFreq(freq, pos);
900 has_gs_node->setBoolValue(_gs != NULL);
901 _localizerWidth = nav->localizerWidth();
903 effective_range = nav->get_range();
905 target_radial = nav->get_multiuse();
906 SG_NORMALIZE_RANGE(target_radial, 0.0, 360.0);
909 int tmp = (int)(_gs->get_multiuse() / 1000.0);
910 target_gs = (double)tmp / 100.0;
912 // until penaltyForNav goes away, we cannot assume we always pick
913 // paired LOC/GS trasmsitters. As we pass over a runway threshold, we
914 // often end up picking the 'wrong' LOC, but the correct GS. To avoid
915 // breaking the basis computation, ensure we use the GS radial and not
916 // the (potentially reversed) LOC radial.
917 double gs_radial = fmod(_gs->get_multiuse(), 1000.0);
918 SG_NORMALIZE_RANGE(gs_radial, 0.0, 360.0);
920 // GS axis unit tangent vector
921 // (along the runway)
922 _gsCart = _gs->cart();
923 _gsAxis = tangentVector(_gs->geod(), _gsCart, gs_radial);
925 // GS baseline unit tangent vector
926 // (perpendicular to the runay along the ground)
927 SGVec3d baseline = tangentVector(_gs->geod(), _gsCart, gs_radial + 90.0);
928 _gsVertical = cross(baseline, _gsAxis);
929 } // of have glideslope
930 } // of found LOC or ILS
933 } else { // found nothing
936 nav_id_node->setStringValue("");
937 loc_node->setBoolValue(false);
938 has_gs_node->setBoolValue(false);
940 _sgr->remove( nav_fx_name );
941 _sgr->remove( dme_fx_name );
944 is_valid_node->setBoolValue(nav != NULL);
945 id_c1_node->setIntValue( (int)identBuffer[0] );
946 id_c2_node->setIntValue( (int)identBuffer[1] );
947 id_c3_node->setIntValue( (int)identBuffer[2] );
948 id_c4_node->setIntValue( (int)identBuffer[3] );
951 void FGNavRadio::audioNavidChanged()
953 if (_sgr->exists(nav_fx_name)) {
954 _sgr->remove(nav_fx_name);
958 string trans_ident(_navaid->get_trans_ident());
959 SGSoundSample* sound = morse.make_ident(trans_ident, LO_FREQUENCY);
960 sound->set_volume( 0.3 );
961 if (!_sgr->add( sound, nav_fx_name )) {
962 SG_LOG(SG_COCKPIT, SG_WARN, "Failed to add v1-vor-ident sound");
965 if ( _sgr->exists( dme_fx_name ) ) {
966 _sgr->remove( dme_fx_name );
969 sound = morse.make_ident( trans_ident, HI_FREQUENCY );
970 sound->set_volume( 0.3 );
971 _sgr->add( sound, dme_fx_name );
973 int offset = (int)(sg_random() * 30.0);
974 play_count = offset / 4;
975 last_time = globals->get_time_params()->get_cur_time() - offset;
976 } catch (sg_io_exception& e) {
977 SG_LOG(SG_GENERAL, SG_ALERT, e.getFormattedMessage());