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 Cartesian unit vector in the
65 // local horizontal plane, i.e. tangent to the
66 // surface of the earth at the local ground zero.
67 // The tangent vector passes through the given <midpoint>
68 // and points forward along the given <heading>.
69 // The <heading> is given in degrees.
70 static SGVec3d tangentVector(const SGGeod& midpoint, const double heading)
72 // The size of the delta is presumably chosen to give
73 // numerical stability. I don't know how the value was chosen.
74 // It probably doesn't matter much. It gets divided out.
75 double delta(100.0); // in meters
77 double az2; // ignored
78 SGGeodesy::direct(midpoint, heading, delta, head, az2);
79 SGGeodesy::direct(midpoint, 180+heading, delta, tail, az2);
80 head.setElevationM(midpoint.getElevationM());
81 tail.setElevationM(midpoint.getElevationM());
82 SGVec3d head_xyz = SGVec3d::fromGeod(head);
83 SGVec3d tail_xyz = SGVec3d::fromGeod(tail);
84 // Awkward formula here, needed because vector-by-scalar
85 // multiplication is defined, but not vector-by-scalar division.
86 return (head_xyz - tail_xyz) * (0.5/delta);
89 // Create a "serviceable" node with a default value of "true"
90 SGPropertyNode_ptr createServiceableProp(SGPropertyNode* aParent,
93 SGPropertyNode_ptr n =
94 aParent->getChild(aName, 0, true)->getChild("serviceable", 0, true);
95 simgear::props::Type typ = n->getType();
96 if ((typ == simgear::props::NONE) || (typ == simgear::props::UNSPECIFIED)) {
97 n->setBoolValue(true);
103 FGNavRadio::FGNavRadio(SGPropertyNode *node) :
107 lon_node(fgGetNode("/position/longitude-deg", true)),
108 lat_node(fgGetNode("/position/latitude-deg", true)),
109 alt_node(fgGetNode("/position/altitude-ft", true)),
114 effective_range(0.0),
119 last_xtrack_error(0.0),
121 _localizerWidth(5.0),
122 _name(node->getStringValue("name", "nav")),
123 _num(node->getIntValue("number", 0)),
124 _time_before_search_sec(-1.0),
125 _gsCart(SGVec3d::zeros()),
126 _gsAxis(SGVec3d::zeros()),
127 _gsVertical(SGVec3d::zeros()),
132 _cdiCrossTrackErrorM(0.0),
133 _gsNeedleDeflection(0.0),
134 _gsNeedleDeflectionNorm(0.0),
137 SGPath path( globals->get_fg_root() );
139 term.append( "Navaids/range.term" );
141 low.append( "Navaids/range.low" );
143 high.append( "Navaids/range.high" );
145 term_tbl = new SGInterpTable( term.str() );
146 low_tbl = new SGInterpTable( low.str() );
147 high_tbl = new SGInterpTable( high.str() );
149 string branch("/instrumentation/" + _name);
150 _radio_node = fgGetNode(branch.c_str(), _num, true);
155 FGNavRadio::~FGNavRadio()
157 if (gps_course_node) {
158 gps_course_node->removeChangeListener(this);
161 if (nav_slaved_to_gps_node) {
162 nav_slaved_to_gps_node->removeChangeListener(this);
174 SGSoundMgr *smgr = globals->get_soundmgr();
175 _sgr = smgr->find("avionics", true);
176 _sgr->tie_to_listener();
180 SGPropertyNode* node = _radio_node.get();
182 fgGetNode(("/systems/electrical/outputs/" + _name).c_str(), true);
185 is_valid_node = node->getChild("data-is-valid", 0, true);
186 power_btn_node = node->getChild("power-btn", 0, true);
187 power_btn_node->setBoolValue( true );
188 vol_btn_node = node->getChild("volume", 0, true);
189 ident_btn_node = node->getChild("ident", 0, true);
190 ident_btn_node->setBoolValue( true );
191 audio_btn_node = node->getChild("audio-btn", 0, true);
192 audio_btn_node->setBoolValue( true );
193 backcourse_node = node->getChild("back-course-btn", 0, true);
194 backcourse_node->setBoolValue( false );
196 nav_serviceable_node = node->getChild("serviceable", 0, true);
197 cdi_serviceable_node = createServiceableProp(node, "cdi");
198 gs_serviceable_node = createServiceableProp(node, "gs");
199 tofrom_serviceable_node = createServiceableProp(node, "to-from");
200 dme_serviceable_node = createServiceableProp(node, "dme");
202 falseCoursesEnabledNode =
203 fgGetNode("/sim/realism/false-radio-courses-enabled");
204 if (!falseCoursesEnabledNode) {
205 falseCoursesEnabledNode =
206 fgGetNode("/sim/realism/false-radio-courses-enabled", true);
207 falseCoursesEnabledNode->setBoolValue(true);
211 SGPropertyNode *subnode = node->getChild("frequencies", 0, true);
212 freq_node = subnode->getChild("selected-mhz", 0, true);
213 alt_freq_node = subnode->getChild("standby-mhz", 0, true);
214 fmt_freq_node = subnode->getChild("selected-mhz-fmt", 0, true);
215 fmt_alt_freq_node = subnode->getChild("standby-mhz-fmt", 0, true);
218 subnode = node->getChild("radials", 0, true);
219 sel_radial_node = subnode->getChild("selected-deg", 0, true);
220 radial_node = subnode->getChild("actual-deg", 0, true);
221 recip_radial_node = subnode->getChild("reciprocal-radial-deg", 0, true);
222 target_radial_true_node = subnode->getChild("target-radial-deg", 0, true);
223 target_auto_hdg_node = subnode->getChild("target-auto-hdg-deg", 0, true);
226 heading_node = node->getChild("heading-deg", 0, true);
227 time_to_intercept = node->getChild("time-to-intercept-sec", 0, true);
228 to_flag_node = node->getChild("to-flag", 0, true);
229 from_flag_node = node->getChild("from-flag", 0, true);
230 inrange_node = node->getChild("in-range", 0, true);
231 signal_quality_norm_node = node->getChild("signal-quality-norm", 0, true);
232 cdi_deflection_node = node->getChild("heading-needle-deflection", 0, true);
233 cdi_deflection_norm_node = node->getChild("heading-needle-deflection-norm", 0, true);
234 cdi_xtrack_error_node = node->getChild("crosstrack-error-m", 0, true);
235 cdi_xtrack_hdg_err_node
236 = node->getChild("crosstrack-heading-error-deg", 0, true);
237 has_gs_node = node->getChild("has-gs", 0, true);
238 loc_node = node->getChild("nav-loc", 0, true);
239 loc_dist_node = node->getChild("nav-distance", 0, true);
240 gs_deflection_node = node->getChild("gs-needle-deflection", 0, true);
241 gs_deflection_deg_node = node->getChild("gs-needle-deflection-deg", 0, true);
242 gs_deflection_norm_node = node->getChild("gs-needle-deflection-norm", 0, true);
243 gs_direct_node = node->getChild("gs-direct-deg", 0, true);
244 gs_rate_of_climb_node = node->getChild("gs-rate-of-climb", 0, true);
245 gs_rate_of_climb_fpm_node = node->getChild("gs-rate-of-climb-fpm", 0, true);
246 gs_dist_node = node->getChild("gs-distance", 0, true);
247 gs_inrange_node = node->getChild("gs-in-range", 0, true);
249 nav_id_node = node->getChild("nav-id", 0, true);
250 id_c1_node = node->getChild("nav-id_asc1", 0, true);
251 id_c2_node = node->getChild("nav-id_asc2", 0, true);
252 id_c3_node = node->getChild("nav-id_asc3", 0, true);
253 id_c4_node = node->getChild("nav-id_asc4", 0, true);
255 // gps slaving support
256 nav_slaved_to_gps_node = node->getChild("slaved-to-gps", 0, true);
257 nav_slaved_to_gps_node->addChangeListener(this);
259 gps_cdi_deflection_node = fgGetNode("/instrumentation/gps/cdi-deflection", true);
260 gps_to_flag_node = fgGetNode("/instrumentation/gps/to-flag", true);
261 gps_from_flag_node = fgGetNode("/instrumentation/gps/from-flag", true);
262 gps_has_gs_node = fgGetNode("/instrumentation/gps/has-gs", true);
263 gps_course_node = fgGetNode("/instrumentation/gps/desired-course-deg", true);
264 gps_course_node->addChangeListener(this);
266 gps_xtrack_error_nm_node = fgGetNode("/instrumentation/gps/wp/wp[1]/course-error-nm", true);
267 _magvarNode = fgGetNode("/environment/magnetic-variation-deg", true);
269 std::ostringstream temp;
270 temp << _name << "nav-ident" << _num;
271 nav_fx_name = temp.str();
272 temp << _name << "dme-ident" << _num;
273 dme_fx_name = temp.str();
279 tie("dme-in-range", SGRawValuePointer<bool>(&_dmeInRange));
280 tie("operable", SGRawValueMethods<FGNavRadio, bool>(*this, &FGNavRadio::isOperable, NULL));
285 FGNavRadio::unbind ()
287 for (unsigned int t=0; t<_tiedNodes.size(); ++t) {
288 _tiedNodes[t]->untie();
294 // model standard VOR/DME/TACAN service volumes as per AIM 1-1-8
295 double FGNavRadio::adjustNavRange( double stationElev, double aircraftElev,
296 double nominalRange )
298 if (nominalRange <= 0.0) {
299 nominalRange = FG_NAV_DEFAULT_RANGE;
302 // extend out actual usable range to be 1.3x the published safe range
303 const double usability_factor = 1.3;
305 // assumptions we model the standard service volume, plus
306 // ... rather than specifying a cylinder, we model a cone that
307 // contains the cylinder. Then we put an upside down cone on top
308 // to model diminishing returns at too-high altitudes.
310 // altitude difference
311 double alt = ( aircraftElev * SG_METER_TO_FEET - stationElev );
312 // cout << "aircraft elev = " << aircraftElev * SG_METER_TO_FEET
313 // << " station elev = " << stationElev << endl;
315 if ( nominalRange < 25.0 + SG_EPSILON ) {
316 // Standard Terminal Service Volume
317 return term_tbl->interpolate( alt ) * usability_factor;
318 } else if ( nominalRange < 50.0 + SG_EPSILON ) {
319 // Standard Low Altitude Service Volume
320 // table is based on range of 40, scale to actual range
321 return low_tbl->interpolate( alt ) * nominalRange / 40.0
324 // Standard High Altitude Service Volume
325 // table is based on range of 130, scale to actual range
326 return high_tbl->interpolate( alt ) * nominalRange / 130.0
332 // model standard ILS service volumes as per AIM 1-1-9
333 double FGNavRadio::adjustILSRange( double stationElev, double aircraftElev,
334 double offsetDegrees, double distance )
336 // assumptions we model the standard service volume, plus
338 // altitude difference
339 // double alt = ( aircraftElev * SG_METER_TO_FEET - stationElev );
340 // double offset = fabs( offsetDegrees );
342 // if ( offset < 10 ) {
343 // return FG_ILS_DEFAULT_RANGE;
344 // } else if ( offset < 35 ) {
345 // return 10 + (35 - offset) * (FG_ILS_DEFAULT_RANGE - 10) / 25;
346 // } else if ( offset < 45 ) {
347 // return (45 - offset);
348 // } else if ( offset > 170 ) {
349 // return FG_ILS_DEFAULT_RANGE;
350 // } else if ( offset > 145 ) {
351 // return 10 + (offset - 145) * (FG_ILS_DEFAULT_RANGE - 10) / 25;
352 // } else if ( offset > 135 ) {
353 // return (offset - 135);
357 return FG_LOC_DEFAULT_RANGE;
361 //////////////////////////////////////////////////////////////////////////
362 // Update the various nav values based on position and valid tuned in navs
363 //////////////////////////////////////////////////////////////////////////
365 FGNavRadio::update(double dt)
371 // Create "formatted" versions of the nav frequencies for
372 // instrument displays.
374 sprintf( tmp, "%.2f", freq_node->getDoubleValue() );
375 fmt_freq_node->setStringValue(tmp);
376 sprintf( tmp, "%.2f", alt_freq_node->getDoubleValue() );
377 fmt_alt_freq_node->setStringValue(tmp);
379 if (power_btn_node->getBoolValue()
380 && (bus_power_node->getDoubleValue() > 1.0)
381 && nav_serviceable_node->getBoolValue() )
393 void FGNavRadio::clearOutputs()
395 inrange_node->setBoolValue( false );
396 signal_quality_norm_node->setDoubleValue( 0.0 );
397 cdi_deflection_node->setDoubleValue( 0.0 );
398 cdi_deflection_norm_node->setDoubleValue( 0.0 );
399 cdi_xtrack_error_node->setDoubleValue( 0.0 );
400 cdi_xtrack_hdg_err_node->setDoubleValue( 0.0 );
401 time_to_intercept->setDoubleValue( 0.0 );
402 heading_node->setDoubleValue(0.0);
403 gs_deflection_node->setDoubleValue( 0.0 );
404 gs_deflection_deg_node->setDoubleValue(0.0);
405 gs_deflection_norm_node->setDoubleValue(0.0);
406 gs_direct_node->setDoubleValue(0.0);
407 gs_inrange_node->setBoolValue( false );
408 loc_node->setBoolValue( false );
409 has_gs_node->setBoolValue(false);
411 to_flag_node->setBoolValue( false );
412 from_flag_node->setBoolValue( false );
413 is_valid_node->setBoolValue(false);
414 nav_id_node->setStringValue("");
421 void FGNavRadio::updateReceiver(double dt)
423 SGGeod pos = SGGeod::fromDegFt(lon_node->getDoubleValue(),
424 lat_node->getDoubleValue(),
425 alt_node->getDoubleValue());
426 SGVec3d aircraft = SGVec3d::fromGeod(pos);
429 // Do a nav station search only once a second to reduce
430 // unnecessary work. (Also, make sure to do this before caching
432 _time_before_search_sec -= dt;
433 if ( _time_before_search_sec < 0 ) {
439 loc_dist = dist(aircraft, _navaid->cart());
440 loc_dist_node->setDoubleValue( loc_dist );
444 if (nav_slaved_to_gps_node->getBoolValue()) {
445 // when slaved to GPS: only allow stuff above: tune NAV station
446 // upate DME. All other data driven by GPS only.
452 _cdiDeflection = 0.0;
453 _cdiCrossTrackErrorM = 0.0;
454 _toFlag = _fromFlag = false;
455 _gsNeedleDeflection = 0.0;
456 _gsNeedleDeflectionNorm = 0.0;
457 heading_node->setDoubleValue(0.0);
458 inrange_node->setBoolValue(false);
462 double nav_elev = _navaid->get_elev_ft();
464 bool is_loc = loc_node->getBoolValue();
465 double signal_quality_norm = signal_quality_norm_node->getDoubleValue();
468 //////////////////////////////////////////////////////////
469 // compute forward and reverse wgs84 headings to localizer
470 //////////////////////////////////////////////////////////
472 SGGeodesy::inverse(pos, _navaid->geod(), hdg, az2, s);
473 heading_node->setDoubleValue(hdg);
474 double radial = az2 - twist;
475 double recip = radial + 180.0;
476 SG_NORMALIZE_RANGE(recip, 0.0, 360.0);
477 radial_node->setDoubleValue( radial );
478 recip_radial_node->setDoubleValue( recip );
480 //////////////////////////////////////////////////////////
481 // compute the target/selected radial in "true" heading
482 //////////////////////////////////////////////////////////
484 target_radial = sel_radial_node->getDoubleValue();
487 // VORs need twist (mag-var) added; ILS/LOCs don't but we set twist to 0.0
488 double trtrue = target_radial + twist;
489 SG_NORMALIZE_RANGE(trtrue, 0.0, 360.0);
490 target_radial_true_node->setDoubleValue( trtrue );
492 //////////////////////////////////////////////////////////
493 // adjust reception range for altitude
494 // FIXME: make sure we are using the navdata range now that
495 // it is valid in the data file
496 //////////////////////////////////////////////////////////
498 double offset = radial - target_radial;
499 SG_NORMALIZE_RANGE(offset, -180.0, 180.0);
501 = adjustILSRange( nav_elev, pos.getElevationM(), offset,
502 loc_dist * SG_METER_TO_NM );
505 = adjustNavRange( nav_elev, pos.getElevationM(), _navaid->get_range() );
508 double effective_range_m = effective_range * SG_NM_TO_METER;
510 //////////////////////////////////////////////////////////
511 // compute signal quality
512 // 100% within effective_range
513 // decreases 1/x^2 further out
514 //////////////////////////////////////////////////////////
515 double last_signal_quality_norm = signal_quality_norm;
517 if ( loc_dist < effective_range_m ) {
518 signal_quality_norm = 1.0;
520 double range_exceed_norm = loc_dist/effective_range_m;
521 signal_quality_norm = 1/(range_exceed_norm*range_exceed_norm);
524 signal_quality_norm = fgGetLowPass( last_signal_quality_norm,
525 signal_quality_norm, dt );
527 signal_quality_norm_node->setDoubleValue( signal_quality_norm );
528 bool inrange = signal_quality_norm > 0.2;
529 inrange_node->setBoolValue( inrange );
531 //////////////////////////////////////////////////////////
532 // compute to/from flag status
533 //////////////////////////////////////////////////////////
538 double offset = fabs(radial - target_radial);
539 _toFlag = (offset > 90.0 && offset < 270.0);
541 _fromFlag = !_toFlag;
543 _toFlag = _fromFlag = false;
547 double r = target_radial - radial;
548 SG_NORMALIZE_RANGE(r, -180.0, 180.0);
551 if (falseCoursesEnabledNode->getBoolValue()) {
552 // The factor of 30.0 gives a period of 120 which gives us 3 cycles and six
553 // zeros i.e. six courses: one front course, one back course, and four
554 // false courses. Three of the six are reverse sensing.
555 _cdiDeflection = 30.0 * sawtooth(r / 30.0);
557 // no false courses, but we do need to create a back course
558 if (fabs(r) > 90.0) { // front course
559 _cdiDeflection = r - copysign(180.0, r);
561 _cdiDeflection = r; // back course
564 _cdiDeflection = -_cdiDeflection; // reverse for outbound radial
565 } // of false courses disabled
567 const double VOR_FULL_ARC = 20.0; // VOR is -10 .. 10 degree swing
568 _cdiDeflection *= VOR_FULL_ARC / _localizerWidth; // increased localiser sensitivity
570 if (backcourse_node->getBoolValue()) {
571 _cdiDeflection = -_cdiDeflection;
574 // handle the TO side of the VOR
575 if (fabs(r) > 90.0) {
576 r = ( r<0.0 ? -r-180.0 : -r+180.0 );
579 } // of non-localiser case
581 SG_CLAMP_RANGE(_cdiDeflection, -10.0, 10.0 );
582 _cdiDeflection *= signal_quality_norm;
584 // cross-track error (in metres)
585 _cdiCrossTrackErrorM = loc_dist * sin(r * SGD_DEGREES_TO_RADIANS);
587 updateGlideSlope(dt, aircraft, signal_quality_norm);
590 void FGNavRadio::updateGlideSlope(double dt, const SGVec3d& aircraft, double signal_quality_norm)
592 _gsNeedleDeflection = 0.0;
593 if (!_gs || !inrange_node->getBoolValue()) {
594 gs_dist_node->setDoubleValue( 0.0 );
595 gs_inrange_node->setBoolValue(false);
596 _gsNeedleDeflection = 0.0;
597 _gsNeedleDeflectionNorm = 0.0;
601 double gsDist = dist(aircraft, _gsCart);
602 gs_dist_node->setDoubleValue(gsDist);
603 bool gsInRange = (gsDist < (_gs->get_range() * SG_NM_TO_METER));
604 gs_inrange_node->setBoolValue(gsInRange);
606 if (!gsInRange) return;
608 SGVec3d pos = aircraft - _gsCart; // relative vector from gs antenna to aircraft
609 // The positive GS axis points along the runway in the landing direction,
610 // toward the far end, not toward the approach area, so we need a - sign here:
611 double dot_h = -dot(pos, _gsAxis);
612 double dot_v = dot(pos, _gsVertical);
613 _gsDirect = atan2(dot_v, dot_h) * SGD_RADIANS_TO_DEGREES;
614 double deflectionAngle = target_gs - _gsDirect;
616 if (falseCoursesEnabledNode->getBoolValue()) {
617 // Construct false glideslopes. The scale factor of 1.5
618 // in the sawtooth gives a period of 6 degrees.
619 // There will be zeros at 3, 6r, 9, 12r et cetera
620 // where "r" indicates reverse sensing.
621 // This is is consistent with conventional pilot lore
622 // e.g. http://www.allstar.fiu.edu/aerojava/ILS.htm
623 // but inconsistent with
624 // http://www.freepatentsonline.com/3757338.html
626 // It may be that some of each exist.
627 if (deflectionAngle < 0) {
628 deflectionAngle = 1.5 * sawtooth(deflectionAngle / 1.5);
630 // no false GS below the true GS
634 _gsNeedleDeflection = deflectionAngle * 5.0;
635 _gsNeedleDeflection *= signal_quality_norm;
637 SG_CLAMP_RANGE(deflectionAngle, -0.7, 0.7);
638 _gsNeedleDeflectionNorm = (deflectionAngle / 0.7) * signal_quality_norm;
640 //////////////////////////////////////////////////////////
641 // Calculate desired rate of climb for intercepting the GS
642 //////////////////////////////////////////////////////////
643 double gs_diff = target_gs - _gsDirect;
644 // convert desired vertical path angle into a climb rate
645 double des_angle = _gsDirect - 10 * gs_diff;
646 /* printf("target_gs=%.1f angle=%.1f gs_diff=%.1f des_angle=%.1f\n",
647 target_gs, _gsDirect, gs_diff, des_angle); */
649 // estimate horizontal speed towards ILS in meters per minute
650 double elapsedDistance = last_x - gsDist;
653 double new_vel = ( elapsedDistance / dt );
654 horiz_vel = 0.99 * horiz_vel + 0.01 * new_vel;
655 /* printf("vel=%.1f (dist=%.1f dt=%.2f)\n", horiz_vel, elapsedDistance, dt);*/
657 gs_rate_of_climb_node
658 ->setDoubleValue( -sin( des_angle * SGD_DEGREES_TO_RADIANS )
659 * horiz_vel * SG_METER_TO_FEET );
660 gs_rate_of_climb_fpm_node
661 ->setDoubleValue( gs_rate_of_climb_node->getDoubleValue() * 60 );
664 void FGNavRadio::updateDME(const SGVec3d& aircraft)
666 if (!_dme || !dme_serviceable_node->getBoolValue()) {
671 double dme_distance = dist(aircraft, _dme->cart());
672 _dmeInRange = (dme_distance < _dme->get_range() * SG_NM_TO_METER);
675 void FGNavRadio::valueChanged (SGPropertyNode* prop)
677 if (prop == gps_course_node) {
678 if (!nav_slaved_to_gps_node->getBoolValue()) {
682 // GPS desired course has changed, sync up our selected-course
683 double v = prop->getDoubleValue();
684 if (v != sel_radial_node->getDoubleValue()) {
685 sel_radial_node->setDoubleValue(v);
687 } else if (prop == nav_slaved_to_gps_node) {
688 if (prop->getBoolValue()) {
689 // slaved-to-GPS activated, clear obsolete NAV outputs and sync up selected course
691 sel_radial_node->setDoubleValue(gps_course_node->getDoubleValue());
693 // slave-to-GPS enabled/disabled, resync NAV station (update all outputs)
695 _time_before_search_sec = 0;
699 void FGNavRadio::updateGPSSlaved()
701 has_gs_node->setBoolValue(gps_has_gs_node->getBoolValue());
703 _toFlag = gps_to_flag_node->getBoolValue();
704 _fromFlag = gps_from_flag_node->getBoolValue();
706 bool gpsValid = (_toFlag | _fromFlag);
707 inrange_node->setBoolValue(gpsValid);
709 signal_quality_norm_node->setDoubleValue(0.0);
710 _cdiDeflection = 0.0;
711 _cdiCrossTrackErrorM = 0.0;
712 _gsNeedleDeflection = 0.0;
713 _gsNeedleDeflectionNorm = 0.0;
717 // this is unfortunate, but panel instruments use this value to decide
718 // if the navradio output is valid.
719 signal_quality_norm_node->setDoubleValue(1.0);
721 _cdiDeflection = gps_cdi_deflection_node->getDoubleValue();
722 // clmap to some range (+/- 10 degrees) as the regular deflection
723 SG_CLAMP_RANGE(_cdiDeflection, -10.0, 10.0 );
725 _cdiCrossTrackErrorM = gps_xtrack_error_nm_node->getDoubleValue() * SG_NM_TO_METER;
726 _gsNeedleDeflection = 0.0; // FIXME, supply this
728 double trtrue = gps_course_node->getDoubleValue() + _magvarNode->getDoubleValue();
729 SG_NORMALIZE_RANGE(trtrue, 0.0, 360.0);
730 target_radial_true_node->setDoubleValue( trtrue );
733 void FGNavRadio::updateCDI(double dt)
735 bool cdi_serviceable = cdi_serviceable_node->getBoolValue();
736 bool inrange = inrange_node->getBoolValue();
738 if (tofrom_serviceable_node->getBoolValue()) {
739 to_flag_node->setBoolValue(_toFlag);
740 from_flag_node->setBoolValue(_fromFlag);
742 to_flag_node->setBoolValue(false);
743 from_flag_node->setBoolValue(false);
746 if (!cdi_serviceable) {
747 _cdiDeflection = 0.0;
748 _cdiCrossTrackErrorM = 0.0;
751 cdi_deflection_node->setDoubleValue(_cdiDeflection);
752 cdi_deflection_norm_node->setDoubleValue(_cdiDeflection * 0.1);
753 cdi_xtrack_error_node->setDoubleValue(_cdiCrossTrackErrorM);
755 //////////////////////////////////////////////////////////
756 // compute an approximate ground track heading error
757 //////////////////////////////////////////////////////////
758 double hdg_error = 0.0;
759 if ( inrange && cdi_serviceable ) {
760 double vn = fgGetDouble( "/velocities/speed-north-fps" );
761 double ve = fgGetDouble( "/velocities/speed-east-fps" );
762 double gnd_trk_true = atan2( ve, vn ) * SGD_RADIANS_TO_DEGREES;
763 if ( gnd_trk_true < 0.0 ) { gnd_trk_true += 360.0; }
765 SGPropertyNode *true_hdg
766 = fgGetNode("/orientation/heading-deg", true);
767 hdg_error = gnd_trk_true - true_hdg->getDoubleValue();
769 // cout << "ground track = " << gnd_trk_true
770 // << " orientation = " << true_hdg->getDoubleValue() << endl;
772 cdi_xtrack_hdg_err_node->setDoubleValue( hdg_error );
774 //////////////////////////////////////////////////////////
775 // Calculate a suggested target heading to smoothly intercept
777 //////////////////////////////////////////////////////////
779 // Now that we have cross track heading adjustment built in,
780 // we shouldn't need to overdrive the heading angle within 8km
783 // The cdi deflection should be +/-10 for a full range of deflection
784 // so multiplying this by 3 gives us +/- 30 degrees heading
786 double adjustment = _cdiDeflection * 3.0;
787 SG_CLAMP_RANGE( adjustment, -30.0, 30.0 );
789 // determine the target heading to fly to intercept the
790 // tgt_radial = target radial (true) + cdi offset adjustmest -
791 // xtrack heading error adjustment
793 double trtrue = target_radial_true_node->getDoubleValue();
794 if ( loc_node->getBoolValue() && backcourse_node->getBoolValue() ) {
795 // tuned to a localizer and backcourse mode activated
796 trtrue += 180.0; // reverse the target localizer heading
797 SG_NORMALIZE_RANGE(trtrue, 0.0, 360.0);
798 nta_hdg = trtrue - adjustment - hdg_error;
800 nta_hdg = trtrue + adjustment - hdg_error;
803 SG_NORMALIZE_RANGE(nta_hdg, 0.0, 360.0);
804 target_auto_hdg_node->setDoubleValue( nta_hdg );
806 //////////////////////////////////////////////////////////
807 // compute the time to intercept selected radial (based on
808 // current and last cross track errors and dt)
809 //////////////////////////////////////////////////////////
811 if ( inrange && cdi_serviceable ) {
812 double cur_rate = (last_xtrack_error - _cdiCrossTrackErrorM) / dt;
813 xrate_ms = 0.99 * xrate_ms + 0.01 * cur_rate;
814 if ( fabs(xrate_ms) > 0.00001 ) {
815 t = _cdiCrossTrackErrorM / xrate_ms;
820 time_to_intercept->setDoubleValue( t );
822 if (!gs_serviceable_node->getBoolValue() ) {
823 _gsNeedleDeflection = 0.0;
824 _gsNeedleDeflectionNorm = 0.0;
826 gs_deflection_node->setDoubleValue(_gsNeedleDeflection);
827 gs_deflection_deg_node->setDoubleValue(_gsNeedleDeflectionNorm * 0.7);
828 gs_deflection_norm_node->setDoubleValue(_gsNeedleDeflectionNorm);
829 gs_direct_node->setDoubleValue(_gsDirect);
831 last_xtrack_error = _cdiCrossTrackErrorM;
834 void FGNavRadio::updateAudio()
836 if (!_navaid || !inrange_node->getBoolValue() || !nav_serviceable_node->getBoolValue()) {
840 // play station ident via audio system if on + ident,
841 // otherwise turn it off
842 if (!power_btn_node->getBoolValue()
843 || !(bus_power_node->getDoubleValue() > 1.0)
844 || !ident_btn_node->getBoolValue()
845 || !audio_btn_node->getBoolValue() ) {
846 _sgr->stop( nav_fx_name );
847 _sgr->stop( dme_fx_name );
851 SGSoundSample *sound = _sgr->find( nav_fx_name );
852 double vol = vol_btn_node->getFloatValue();
853 SG_CLAMP_RANGE(vol, 0.0, 1.0);
855 if ( sound != NULL ) {
856 sound->set_volume( vol );
858 SG_LOG( SG_COCKPIT, SG_ALERT, "Can't find nav-vor-ident sound" );
861 sound = _sgr->find( dme_fx_name );
862 if ( sound != NULL ) {
863 sound->set_volume( vol );
865 SG_LOG( SG_COCKPIT, SG_ALERT, "Can't find nav-dme-ident sound" );
868 const int NUM_IDENT_SLOTS = 5;
869 const time_t SLOT_LENGTH = 5; // seconds
871 // There are N slots numbered 0 through (NUM_IDENT_SLOTS-1) inclusive.
872 // Each slot is 5 seconds long.
873 // Slots 0 is for DME
874 // the rest are for azimuth.
875 time_t now = globals->get_time_params()->get_cur_time();
876 if ((now >= last_time) && (now < last_time + SLOT_LENGTH)) {
877 return; // wait longer
881 play_count = ++play_count % NUM_IDENT_SLOTS;
883 // Previous ident is out of time; if still playing, cut it off:
884 _sgr->stop( nav_fx_name );
885 _sgr->stop( dme_fx_name );
886 if (play_count == 0) { // the DME slot
887 if (_dmeInRange && dme_serviceable_node->getBoolValue()) {
889 if (vol > 0.05) _sgr->play_once( dme_fx_name );
892 if (inrange_node->getBoolValue() && nav_serviceable_node->getBoolValue()) {
893 if (vol > 0.05) _sgr->play_once(nav_fx_name);
898 FGNavRecord* FGNavRadio::findPrimaryNavaid(const SGGeod& aPos, double aFreqMHz)
900 FGNavRecord* nav = globals->get_navlist()->findByFreq(aFreqMHz, aPos);
905 return globals->get_loclist()->findByFreq(aFreqMHz, aPos);
908 // Update current nav/adf radio stations based on current postition
909 void FGNavRadio::search()
911 _time_before_search_sec = 1.0;
912 SGGeod pos = SGGeod::fromDegFt(lon_node->getDoubleValue(),
913 lat_node->getDoubleValue(), alt_node->getDoubleValue());
914 double freq = freq_node->getDoubleValue();
916 FGNavRecord* nav = findPrimaryNavaid(pos, freq);
917 if (nav == _navaid) {
918 return; // found the same as last search, we're done
922 string identBuffer(4, ' ');
924 _dme = globals->get_dmelist()->findByFreq(freq, pos);
926 nav_id_node->setStringValue(nav->get_ident());
927 identBuffer = simgear::strutils::rpad( nav->ident(), 4, ' ' );
929 effective_range = adjustNavRange(nav->get_elev_ft(), pos.getElevationM(), nav->get_range());
930 loc_node->setBoolValue(nav->type() != FGPositioned::VOR);
931 twist = nav->get_multiuse();
933 if (nav->type() == FGPositioned::VOR) {
934 target_radial = sel_radial_node->getDoubleValue();
936 has_gs_node->setBoolValue(false);
937 } else { // ILS or LOC
938 _gs = globals->get_gslist()->findByFreq(freq, pos);
939 has_gs_node->setBoolValue(_gs != NULL);
940 _localizerWidth = nav->localizerWidth();
942 effective_range = nav->get_range();
944 target_radial = nav->get_multiuse();
945 SG_NORMALIZE_RANGE(target_radial, 0.0, 360.0);
948 int tmp = (int)(_gs->get_multiuse() / 1000.0);
949 target_gs = (double)tmp / 100.0;
951 double gs_radial = fmod(_gs->get_multiuse(), 1000.0);
952 SG_NORMALIZE_RANGE(gs_radial, 0.0, 360.0);
953 _gsCart = _gs->cart();
955 // GS axis unit tangent vector
956 // (along the runway):
957 _gsAxis = tangentVector(_gs->geod(), gs_radial);
959 // GS baseline unit tangent vector
960 // (perpendicular to the runay along the ground)
961 SGVec3d baseline = tangentVector(_gs->geod(), gs_radial + 90.0);
962 _gsVertical = cross(baseline, _gsAxis);
963 } // of have glideslope
964 } // of found LOC or ILS
967 } else { // found nothing
970 nav_id_node->setStringValue("");
971 loc_node->setBoolValue(false);
972 has_gs_node->setBoolValue(false);
974 _sgr->remove( nav_fx_name );
975 _sgr->remove( dme_fx_name );
978 is_valid_node->setBoolValue(nav != NULL);
979 id_c1_node->setIntValue( (int)identBuffer[0] );
980 id_c2_node->setIntValue( (int)identBuffer[1] );
981 id_c3_node->setIntValue( (int)identBuffer[2] );
982 id_c4_node->setIntValue( (int)identBuffer[3] );
985 void FGNavRadio::audioNavidChanged()
987 if (_sgr->exists(nav_fx_name)) {
988 _sgr->remove(nav_fx_name);
992 string trans_ident(_navaid->get_trans_ident());
993 SGSoundSample* sound = morse.make_ident(trans_ident, LO_FREQUENCY);
994 sound->set_volume( 0.3 );
995 if (!_sgr->add( sound, nav_fx_name )) {
996 SG_LOG(SG_COCKPIT, SG_WARN, "Failed to add v1-vor-ident sound");
999 if ( _sgr->exists( dme_fx_name ) ) {
1000 _sgr->remove( dme_fx_name );
1003 sound = morse.make_ident( trans_ident, HI_FREQUENCY );
1004 sound->set_volume( 0.3 );
1005 _sgr->add( sound, dme_fx_name );
1007 int offset = (int)(sg_random() * 30.0);
1008 play_count = offset / 4;
1009 last_time = globals->get_time_params()->get_cur_time() - offset;
1010 } catch (sg_io_exception& e) {
1011 SG_LOG(SG_GENERAL, SG_ALERT, e.getFormattedMessage());