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) :
98 lon_node(fgGetNode("/position/longitude-deg", true)),
99 lat_node(fgGetNode("/position/latitude-deg", true)),
100 alt_node(fgGetNode("/position/altitude-ft", true)),
105 effective_range(0.0),
110 last_xtrack_error(0.0),
112 _localizerWidth(5.0),
113 _name(node->getStringValue("name", "nav")),
114 _num(node->getIntValue("number", 0)),
115 _time_before_search_sec(-1.0),
116 _gsCart(SGVec3d::zeros()),
117 _gsAxis(SGVec3d::zeros()),
118 _gsVertical(SGVec3d::zeros()),
123 _cdiCrossTrackErrorM(0.0),
124 _gsNeedleDeflection(0.0),
125 _gsNeedleDeflectionNorm(0.0),
128 SGPath path( globals->get_fg_root() );
130 term.append( "Navaids/range.term" );
132 low.append( "Navaids/range.low" );
134 high.append( "Navaids/range.high" );
136 term_tbl = new SGInterpTable( term.str() );
137 low_tbl = new SGInterpTable( low.str() );
138 high_tbl = new SGInterpTable( high.str() );
140 string branch("/instrumentation/" + _name);
141 _radio_node = fgGetNode(branch.c_str(), _num, true);
146 FGNavRadio::~FGNavRadio()
148 if (gps_course_node) {
149 gps_course_node->removeChangeListener(this);
152 if (nav_slaved_to_gps_node) {
153 nav_slaved_to_gps_node->removeChangeListener(this);
165 SGSoundMgr *smgr = globals->get_soundmgr();
166 _sgr = smgr->find("avionics", true);
167 _sgr->tie_to_listener();
171 SGPropertyNode* node = _radio_node.get();
173 fgGetNode(("/systems/electrical/outputs/" + _name).c_str(), true);
176 is_valid_node = node->getChild("data-is-valid", 0, true);
177 power_btn_node = node->getChild("power-btn", 0, true);
178 power_btn_node->setBoolValue( true );
179 vol_btn_node = node->getChild("volume", 0, true);
180 ident_btn_node = node->getChild("ident", 0, true);
181 ident_btn_node->setBoolValue( true );
182 audio_btn_node = node->getChild("audio-btn", 0, true);
183 audio_btn_node->setBoolValue( true );
184 backcourse_node = node->getChild("back-course-btn", 0, true);
185 backcourse_node->setBoolValue( false );
187 nav_serviceable_node = node->getChild("serviceable", 0, true);
188 cdi_serviceable_node = createServiceableProp(node, "cdi");
189 gs_serviceable_node = createServiceableProp(node, "gs");
190 tofrom_serviceable_node = createServiceableProp(node, "to-from");
191 dme_serviceable_node = createServiceableProp(node, "dme");
193 falseCoursesEnabledNode =
194 fgGetNode("/sim/realism/false-radio-courses-enabled");
195 if (!falseCoursesEnabledNode) {
196 falseCoursesEnabledNode =
197 fgGetNode("/sim/realism/false-radio-courses-enabled", true);
198 falseCoursesEnabledNode->setBoolValue(true);
202 SGPropertyNode *subnode = node->getChild("frequencies", 0, true);
203 freq_node = subnode->getChild("selected-mhz", 0, true);
204 alt_freq_node = subnode->getChild("standby-mhz", 0, true);
205 fmt_freq_node = subnode->getChild("selected-mhz-fmt", 0, true);
206 fmt_alt_freq_node = subnode->getChild("standby-mhz-fmt", 0, true);
209 subnode = node->getChild("radials", 0, true);
210 sel_radial_node = subnode->getChild("selected-deg", 0, true);
211 radial_node = subnode->getChild("actual-deg", 0, true);
212 recip_radial_node = subnode->getChild("reciprocal-radial-deg", 0, true);
213 target_radial_true_node = subnode->getChild("target-radial-deg", 0, true);
214 target_auto_hdg_node = subnode->getChild("target-auto-hdg-deg", 0, true);
217 heading_node = node->getChild("heading-deg", 0, true);
218 time_to_intercept = node->getChild("time-to-intercept-sec", 0, true);
219 to_flag_node = node->getChild("to-flag", 0, true);
220 from_flag_node = node->getChild("from-flag", 0, true);
221 inrange_node = node->getChild("in-range", 0, true);
222 signal_quality_norm_node = node->getChild("signal-quality-norm", 0, true);
223 cdi_deflection_node = node->getChild("heading-needle-deflection", 0, true);
224 cdi_deflection_norm_node = node->getChild("heading-needle-deflection-norm", 0, true);
225 cdi_xtrack_error_node = node->getChild("crosstrack-error-m", 0, true);
226 cdi_xtrack_hdg_err_node
227 = node->getChild("crosstrack-heading-error-deg", 0, true);
228 has_gs_node = node->getChild("has-gs", 0, true);
229 loc_node = node->getChild("nav-loc", 0, true);
230 loc_dist_node = node->getChild("nav-distance", 0, true);
231 gs_deflection_node = node->getChild("gs-needle-deflection", 0, true);
232 gs_deflection_deg_node = node->getChild("gs-needle-deflection-deg", 0, true);
233 gs_deflection_norm_node = node->getChild("gs-needle-deflection-norm", 0, true);
234 gs_direct_node = node->getChild("gs-direct-deg", 0, true);
235 gs_rate_of_climb_node = node->getChild("gs-rate-of-climb", 0, true);
236 gs_rate_of_climb_fpm_node = node->getChild("gs-rate-of-climb-fpm", 0, true);
237 gs_dist_node = node->getChild("gs-distance", 0, true);
238 gs_inrange_node = node->getChild("gs-in-range", 0, true);
240 nav_id_node = node->getChild("nav-id", 0, true);
241 id_c1_node = node->getChild("nav-id_asc1", 0, true);
242 id_c2_node = node->getChild("nav-id_asc2", 0, true);
243 id_c3_node = node->getChild("nav-id_asc3", 0, true);
244 id_c4_node = node->getChild("nav-id_asc4", 0, true);
246 // gps slaving support
247 nav_slaved_to_gps_node = node->getChild("slaved-to-gps", 0, true);
248 nav_slaved_to_gps_node->addChangeListener(this);
250 gps_cdi_deflection_node = fgGetNode("/instrumentation/gps/cdi-deflection", true);
251 gps_to_flag_node = fgGetNode("/instrumentation/gps/to-flag", true);
252 gps_from_flag_node = fgGetNode("/instrumentation/gps/from-flag", true);
253 gps_has_gs_node = fgGetNode("/instrumentation/gps/has-gs", true);
254 gps_course_node = fgGetNode("/instrumentation/gps/desired-course-deg", true);
255 gps_course_node->addChangeListener(this);
257 gps_xtrack_error_nm_node = fgGetNode("/instrumentation/gps/wp/wp[1]/course-error-nm", true);
258 _magvarNode = fgGetNode("/environment/magnetic-variation-deg", true);
260 std::ostringstream temp;
261 temp << _name << "nav-ident" << _num;
262 nav_fx_name = temp.str();
263 temp << _name << "dme-ident" << _num;
264 dme_fx_name = temp.str();
270 tie("dme-in-range", SGRawValuePointer<bool>(&_dmeInRange));
271 tie("operable", SGRawValueMethods<FGNavRadio, bool>(*this, &FGNavRadio::isOperable, NULL));
276 FGNavRadio::unbind ()
278 for (unsigned int t=0; t<_tiedNodes.size(); ++t) {
279 _tiedNodes[t]->untie();
285 // model standard VOR/DME/TACAN service volumes as per AIM 1-1-8
286 double FGNavRadio::adjustNavRange( double stationElev, double aircraftElev,
287 double nominalRange )
289 if (nominalRange <= 0.0) {
290 nominalRange = FG_NAV_DEFAULT_RANGE;
293 // extend out actual usable range to be 1.3x the published safe range
294 const double usability_factor = 1.3;
296 // assumptions we model the standard service volume, plus
297 // ... rather than specifying a cylinder, we model a cone that
298 // contains the cylinder. Then we put an upside down cone on top
299 // to model diminishing returns at too-high altitudes.
301 // altitude difference
302 double alt = ( aircraftElev * SG_METER_TO_FEET - stationElev );
303 // cout << "aircraft elev = " << aircraftElev * SG_METER_TO_FEET
304 // << " station elev = " << stationElev << endl;
306 if ( nominalRange < 25.0 + SG_EPSILON ) {
307 // Standard Terminal Service Volume
308 return term_tbl->interpolate( alt ) * usability_factor;
309 } else if ( nominalRange < 50.0 + SG_EPSILON ) {
310 // Standard Low Altitude Service Volume
311 // table is based on range of 40, scale to actual range
312 return low_tbl->interpolate( alt ) * nominalRange / 40.0
315 // Standard High Altitude Service Volume
316 // table is based on range of 130, scale to actual range
317 return high_tbl->interpolate( alt ) * nominalRange / 130.0
323 // model standard ILS service volumes as per AIM 1-1-9
324 double FGNavRadio::adjustILSRange( double stationElev, double aircraftElev,
325 double offsetDegrees, double distance )
327 // assumptions we model the standard service volume, plus
329 // altitude difference
330 // double alt = ( aircraftElev * SG_METER_TO_FEET - stationElev );
331 // double offset = fabs( offsetDegrees );
333 // if ( offset < 10 ) {
334 // return FG_ILS_DEFAULT_RANGE;
335 // } else if ( offset < 35 ) {
336 // return 10 + (35 - offset) * (FG_ILS_DEFAULT_RANGE - 10) / 25;
337 // } else if ( offset < 45 ) {
338 // return (45 - offset);
339 // } else if ( offset > 170 ) {
340 // return FG_ILS_DEFAULT_RANGE;
341 // } else if ( offset > 145 ) {
342 // return 10 + (offset - 145) * (FG_ILS_DEFAULT_RANGE - 10) / 25;
343 // } else if ( offset > 135 ) {
344 // return (offset - 135);
348 return FG_LOC_DEFAULT_RANGE;
352 //////////////////////////////////////////////////////////////////////////
353 // Update the various nav values based on position and valid tuned in navs
354 //////////////////////////////////////////////////////////////////////////
356 FGNavRadio::update(double dt)
362 // Create "formatted" versions of the nav frequencies for
363 // instrument displays.
365 sprintf( tmp, "%.2f", freq_node->getDoubleValue() );
366 fmt_freq_node->setStringValue(tmp);
367 sprintf( tmp, "%.2f", alt_freq_node->getDoubleValue() );
368 fmt_alt_freq_node->setStringValue(tmp);
370 if (power_btn_node->getBoolValue()
371 && (bus_power_node->getDoubleValue() > 1.0)
372 && nav_serviceable_node->getBoolValue() )
384 void FGNavRadio::clearOutputs()
386 inrange_node->setBoolValue( false );
387 signal_quality_norm_node->setDoubleValue( 0.0 );
388 cdi_deflection_node->setDoubleValue( 0.0 );
389 cdi_deflection_norm_node->setDoubleValue( 0.0 );
390 cdi_xtrack_error_node->setDoubleValue( 0.0 );
391 cdi_xtrack_hdg_err_node->setDoubleValue( 0.0 );
392 time_to_intercept->setDoubleValue( 0.0 );
393 heading_node->setDoubleValue(0.0);
394 gs_deflection_node->setDoubleValue( 0.0 );
395 gs_deflection_deg_node->setDoubleValue(0.0);
396 gs_deflection_norm_node->setDoubleValue(0.0);
397 gs_direct_node->setDoubleValue(0.0);
398 gs_inrange_node->setBoolValue( false );
399 loc_node->setBoolValue( false );
400 has_gs_node->setBoolValue(false);
402 to_flag_node->setBoolValue( false );
403 from_flag_node->setBoolValue( false );
404 is_valid_node->setBoolValue(false);
405 nav_id_node->setStringValue("");
412 void FGNavRadio::updateReceiver(double dt)
414 SGGeod pos = SGGeod::fromDegFt(lon_node->getDoubleValue(),
415 lat_node->getDoubleValue(),
416 alt_node->getDoubleValue());
417 SGVec3d aircraft = SGVec3d::fromGeod(pos);
420 // Do a nav station search only once a second to reduce
421 // unnecessary work. (Also, make sure to do this before caching
423 _time_before_search_sec -= dt;
424 if ( _time_before_search_sec < 0 ) {
430 loc_dist = dist(aircraft, _navaid->cart());
431 loc_dist_node->setDoubleValue( loc_dist );
435 if (nav_slaved_to_gps_node->getBoolValue()) {
436 // when slaved to GPS: only allow stuff above: tune NAV station
437 // upate DME. All other data driven by GPS only.
443 _cdiDeflection = 0.0;
444 _cdiCrossTrackErrorM = 0.0;
445 _toFlag = _fromFlag = false;
446 _gsNeedleDeflection = 0.0;
447 _gsNeedleDeflectionNorm = 0.0;
448 heading_node->setDoubleValue(0.0);
449 inrange_node->setBoolValue(false);
453 double nav_elev = _navaid->get_elev_ft();
455 bool is_loc = loc_node->getBoolValue();
456 double signal_quality_norm = signal_quality_norm_node->getDoubleValue();
459 //////////////////////////////////////////////////////////
460 // compute forward and reverse wgs84 headings to localizer
461 //////////////////////////////////////////////////////////
463 SGGeodesy::inverse(pos, _navaid->geod(), hdg, az2, s);
464 heading_node->setDoubleValue(hdg);
465 double radial = az2 - twist;
466 double recip = radial + 180.0;
467 SG_NORMALIZE_RANGE(recip, 0.0, 360.0);
468 radial_node->setDoubleValue( radial );
469 recip_radial_node->setDoubleValue( recip );
471 //////////////////////////////////////////////////////////
472 // compute the target/selected radial in "true" heading
473 //////////////////////////////////////////////////////////
475 target_radial = sel_radial_node->getDoubleValue();
478 // VORs need twist (mag-var) added; ILS/LOCs don't but we set twist to 0.0
479 double trtrue = target_radial + twist;
480 SG_NORMALIZE_RANGE(trtrue, 0.0, 360.0);
481 target_radial_true_node->setDoubleValue( trtrue );
483 //////////////////////////////////////////////////////////
484 // adjust reception range for altitude
485 // FIXME: make sure we are using the navdata range now that
486 // it is valid in the data file
487 //////////////////////////////////////////////////////////
489 double offset = radial - target_radial;
490 SG_NORMALIZE_RANGE(offset, -180.0, 180.0);
492 = adjustILSRange( nav_elev, pos.getElevationM(), offset,
493 loc_dist * SG_METER_TO_NM );
496 = adjustNavRange( nav_elev, pos.getElevationM(), _navaid->get_range() );
499 double effective_range_m = effective_range * SG_NM_TO_METER;
501 //////////////////////////////////////////////////////////
502 // compute signal quality
503 // 100% within effective_range
504 // decreases 1/x^2 further out
505 //////////////////////////////////////////////////////////
506 double last_signal_quality_norm = signal_quality_norm;
508 if ( loc_dist < effective_range_m ) {
509 signal_quality_norm = 1.0;
511 double range_exceed_norm = loc_dist/effective_range_m;
512 signal_quality_norm = 1/(range_exceed_norm*range_exceed_norm);
515 signal_quality_norm = fgGetLowPass( last_signal_quality_norm,
516 signal_quality_norm, dt );
518 signal_quality_norm_node->setDoubleValue( signal_quality_norm );
519 bool inrange = signal_quality_norm > 0.2;
520 inrange_node->setBoolValue( inrange );
522 //////////////////////////////////////////////////////////
523 // compute to/from flag status
524 //////////////////////////////////////////////////////////
529 double offset = fabs(radial - target_radial);
530 _toFlag = (offset > 90.0 && offset < 270.0);
532 _fromFlag = !_toFlag;
534 _toFlag = _fromFlag = false;
538 double r = target_radial - radial;
539 SG_NORMALIZE_RANGE(r, -180.0, 180.0);
542 if (falseCoursesEnabledNode->getBoolValue()) {
543 // The factor of 30.0 gives a period of 120 which gives us 3 cycles and six
544 // zeros i.e. six courses: one front course, one back course, and four
545 // false courses. Three of the six are reverse sensing.
546 _cdiDeflection = 30.0 * sawtooth(r / 30.0);
548 // no false courses, but we do need to create a back course
549 if (fabs(r) > 90.0) { // front course
550 _cdiDeflection = r - copysign(180.0, r);
552 _cdiDeflection = r; // back course
555 _cdiDeflection = -_cdiDeflection; // reverse for outbound radial
556 } // of false courses disabled
558 const double VOR_FULL_ARC = 20.0; // VOR is -10 .. 10 degree swing
559 _cdiDeflection *= VOR_FULL_ARC / _localizerWidth; // increased localiser sensitivity
561 if (backcourse_node->getBoolValue()) {
562 _cdiDeflection = -_cdiDeflection;
565 // handle the TO side of the VOR
566 if (fabs(r) > 90.0) {
567 r = ( r<0.0 ? -r-180.0 : -r+180.0 );
570 } // of non-localiser case
572 SG_CLAMP_RANGE(_cdiDeflection, -10.0, 10.0 );
573 _cdiDeflection *= signal_quality_norm;
575 // cross-track error (in metres)
576 _cdiCrossTrackErrorM = loc_dist * sin(r * SGD_DEGREES_TO_RADIANS);
578 updateGlideSlope(dt, aircraft, signal_quality_norm);
581 void FGNavRadio::updateGlideSlope(double dt, const SGVec3d& aircraft, double signal_quality_norm)
583 _gsNeedleDeflection = 0.0;
584 if (!_gs || !inrange_node->getBoolValue()) {
585 gs_dist_node->setDoubleValue( 0.0 );
586 gs_inrange_node->setBoolValue(false);
587 _gsNeedleDeflection = 0.0;
588 _gsNeedleDeflectionNorm = 0.0;
592 double gsDist = dist(aircraft, _gsCart);
593 gs_dist_node->setDoubleValue(gsDist);
594 bool gsInRange = (gsDist < (_gs->get_range() * SG_NM_TO_METER));
595 gs_inrange_node->setBoolValue(gsInRange);
597 if (!gsInRange) return;
599 SGVec3d pos = aircraft - _gsCart; // relative vector from gs antenna to aircraft
600 // The positive GS axis points along the runway in the landing direction,
601 // toward the far end, not toward the approach area, so we need a - sign here:
602 double dot_h = -dot(pos, _gsAxis);
603 double dot_v = dot(pos, _gsVertical);
604 _gsDirect = atan2(dot_v, dot_h) * SGD_RADIANS_TO_DEGREES;
605 double deflectionAngle = target_gs - _gsDirect;
607 if (falseCoursesEnabledNode->getBoolValue()) {
608 // Construct false glideslopes. The scale factor of 1.5
609 // in the sawtooth gives a period of 6 degrees.
610 // There will be zeros at 3, 6r, 9, 12r et cetera
611 // where "r" indicates reverse sensing.
612 // This is is consistent with conventional pilot lore
613 // e.g. http://www.allstar.fiu.edu/aerojava/ILS.htm
614 // but inconsistent with
615 // http://www.freepatentsonline.com/3757338.html
617 // It may be that some of each exist.
618 if (deflectionAngle < 0) {
619 deflectionAngle = 1.5 * sawtooth(deflectionAngle / 1.5);
621 // no false GS below the true GS
625 _gsNeedleDeflection = deflectionAngle * 5.0;
626 _gsNeedleDeflection *= signal_quality_norm;
628 SG_CLAMP_RANGE(deflectionAngle, -0.7, 0.7);
629 _gsNeedleDeflectionNorm = (deflectionAngle / 0.7) * signal_quality_norm;
631 //////////////////////////////////////////////////////////
632 // Calculate desired rate of climb for intercepting the GS
633 //////////////////////////////////////////////////////////
634 double gs_diff = target_gs - _gsDirect;
635 // convert desired vertical path angle into a climb rate
636 double des_angle = _gsDirect - 10 * gs_diff;
637 /* printf("target_gs=%.1f angle=%.1f gs_diff=%.1f des_angle=%.1f\n",
638 target_gs, _gsDirect, gs_diff, des_angle); */
640 // estimate horizontal speed towards ILS in meters per minute
641 double elapsedDistance = last_x - gsDist;
644 double new_vel = ( elapsedDistance / dt );
645 horiz_vel = 0.99 * horiz_vel + 0.01 * new_vel;
646 /* printf("vel=%.1f (dist=%.1f dt=%.2f)\n", horiz_vel, elapsedDistance, dt);*/
648 gs_rate_of_climb_node
649 ->setDoubleValue( -sin( des_angle * SGD_DEGREES_TO_RADIANS )
650 * horiz_vel * SG_METER_TO_FEET );
651 gs_rate_of_climb_fpm_node
652 ->setDoubleValue( gs_rate_of_climb_node->getDoubleValue() * 60 );
655 void FGNavRadio::updateDME(const SGVec3d& aircraft)
657 if (!_dme || !dme_serviceable_node->getBoolValue()) {
662 double dme_distance = dist(aircraft, _dme->cart());
663 _dmeInRange = (dme_distance < _dme->get_range() * SG_NM_TO_METER);
666 void FGNavRadio::valueChanged (SGPropertyNode* prop)
668 if (prop == gps_course_node) {
669 if (!nav_slaved_to_gps_node->getBoolValue()) {
673 // GPS desired course has changed, sync up our selected-course
674 double v = prop->getDoubleValue();
675 if (v != sel_radial_node->getDoubleValue()) {
676 sel_radial_node->setDoubleValue(v);
678 } else if (prop == nav_slaved_to_gps_node) {
679 if (prop->getBoolValue()) {
680 // slaved-to-GPS activated, clear obsolete NAV outputs and sync up selected course
682 sel_radial_node->setDoubleValue(gps_course_node->getDoubleValue());
684 // slave-to-GPS enabled/disabled, resync NAV station (update all outputs)
686 _time_before_search_sec = 0;
690 void FGNavRadio::updateGPSSlaved()
692 has_gs_node->setBoolValue(gps_has_gs_node->getBoolValue());
694 _toFlag = gps_to_flag_node->getBoolValue();
695 _fromFlag = gps_from_flag_node->getBoolValue();
697 bool gpsValid = (_toFlag | _fromFlag);
698 inrange_node->setBoolValue(gpsValid);
700 signal_quality_norm_node->setDoubleValue(0.0);
701 _cdiDeflection = 0.0;
702 _cdiCrossTrackErrorM = 0.0;
703 _gsNeedleDeflection = 0.0;
704 _gsNeedleDeflectionNorm = 0.0;
708 // this is unfortunate, but panel instruments use this value to decide
709 // if the navradio output is valid.
710 signal_quality_norm_node->setDoubleValue(1.0);
712 _cdiDeflection = gps_cdi_deflection_node->getDoubleValue();
713 // clmap to some range (+/- 10 degrees) as the regular deflection
714 SG_CLAMP_RANGE(_cdiDeflection, -10.0, 10.0 );
716 _cdiCrossTrackErrorM = gps_xtrack_error_nm_node->getDoubleValue() * SG_NM_TO_METER;
717 _gsNeedleDeflection = 0.0; // FIXME, supply this
719 double trtrue = gps_course_node->getDoubleValue() + _magvarNode->getDoubleValue();
720 SG_NORMALIZE_RANGE(trtrue, 0.0, 360.0);
721 target_radial_true_node->setDoubleValue( trtrue );
724 void FGNavRadio::updateCDI(double dt)
726 bool cdi_serviceable = cdi_serviceable_node->getBoolValue();
727 bool inrange = inrange_node->getBoolValue();
729 if (tofrom_serviceable_node->getBoolValue()) {
730 to_flag_node->setBoolValue(_toFlag);
731 from_flag_node->setBoolValue(_fromFlag);
733 to_flag_node->setBoolValue(false);
734 from_flag_node->setBoolValue(false);
737 if (!cdi_serviceable) {
738 _cdiDeflection = 0.0;
739 _cdiCrossTrackErrorM = 0.0;
742 cdi_deflection_node->setDoubleValue(_cdiDeflection);
743 cdi_deflection_norm_node->setDoubleValue(_cdiDeflection * 0.1);
744 cdi_xtrack_error_node->setDoubleValue(_cdiCrossTrackErrorM);
746 //////////////////////////////////////////////////////////
747 // compute an approximate ground track heading error
748 //////////////////////////////////////////////////////////
749 double hdg_error = 0.0;
750 if ( inrange && cdi_serviceable ) {
751 double vn = fgGetDouble( "/velocities/speed-north-fps" );
752 double ve = fgGetDouble( "/velocities/speed-east-fps" );
753 double gnd_trk_true = atan2( ve, vn ) * SGD_RADIANS_TO_DEGREES;
754 if ( gnd_trk_true < 0.0 ) { gnd_trk_true += 360.0; }
756 SGPropertyNode *true_hdg
757 = fgGetNode("/orientation/heading-deg", true);
758 hdg_error = gnd_trk_true - true_hdg->getDoubleValue();
760 // cout << "ground track = " << gnd_trk_true
761 // << " orientation = " << true_hdg->getDoubleValue() << endl;
763 cdi_xtrack_hdg_err_node->setDoubleValue( hdg_error );
765 //////////////////////////////////////////////////////////
766 // Calculate a suggested target heading to smoothly intercept
768 //////////////////////////////////////////////////////////
770 // Now that we have cross track heading adjustment built in,
771 // we shouldn't need to overdrive the heading angle within 8km
774 // The cdi deflection should be +/-10 for a full range of deflection
775 // so multiplying this by 3 gives us +/- 30 degrees heading
777 double adjustment = _cdiDeflection * 3.0;
778 SG_CLAMP_RANGE( adjustment, -30.0, 30.0 );
780 // determine the target heading to fly to intercept the
781 // tgt_radial = target radial (true) + cdi offset adjustmest -
782 // xtrack heading error adjustment
784 double trtrue = target_radial_true_node->getDoubleValue();
785 if ( loc_node->getBoolValue() && backcourse_node->getBoolValue() ) {
786 // tuned to a localizer and backcourse mode activated
787 trtrue += 180.0; // reverse the target localizer heading
788 SG_NORMALIZE_RANGE(trtrue, 0.0, 360.0);
789 nta_hdg = trtrue - adjustment - hdg_error;
791 nta_hdg = trtrue + adjustment - hdg_error;
794 SG_NORMALIZE_RANGE(nta_hdg, 0.0, 360.0);
795 target_auto_hdg_node->setDoubleValue( nta_hdg );
797 //////////////////////////////////////////////////////////
798 // compute the time to intercept selected radial (based on
799 // current and last cross track errors and dt)
800 //////////////////////////////////////////////////////////
802 if ( inrange && cdi_serviceable ) {
803 double cur_rate = (last_xtrack_error - _cdiCrossTrackErrorM) / dt;
804 xrate_ms = 0.99 * xrate_ms + 0.01 * cur_rate;
805 if ( fabs(xrate_ms) > 0.00001 ) {
806 t = _cdiCrossTrackErrorM / xrate_ms;
811 time_to_intercept->setDoubleValue( t );
813 if (!gs_serviceable_node->getBoolValue() ) {
814 _gsNeedleDeflection = 0.0;
815 _gsNeedleDeflectionNorm = 0.0;
817 gs_deflection_node->setDoubleValue(_gsNeedleDeflection);
818 gs_deflection_deg_node->setDoubleValue(_gsNeedleDeflectionNorm * 0.7);
819 gs_deflection_norm_node->setDoubleValue(_gsNeedleDeflectionNorm);
820 gs_direct_node->setDoubleValue(_gsDirect);
822 last_xtrack_error = _cdiCrossTrackErrorM;
825 void FGNavRadio::updateAudio()
827 if (!_navaid || !inrange_node->getBoolValue() || !nav_serviceable_node->getBoolValue()) {
831 // play station ident via audio system if on + ident,
832 // otherwise turn it off
833 if (!power_btn_node->getBoolValue()
834 || !(bus_power_node->getDoubleValue() > 1.0)
835 || !ident_btn_node->getBoolValue()
836 || !audio_btn_node->getBoolValue() ) {
837 _sgr->stop( nav_fx_name );
838 _sgr->stop( dme_fx_name );
842 SGSoundSample *sound = _sgr->find( nav_fx_name );
843 double vol = vol_btn_node->getFloatValue();
844 SG_CLAMP_RANGE(vol, 0.0, 1.0);
846 if ( sound != NULL ) {
847 sound->set_volume( vol );
849 SG_LOG( SG_COCKPIT, SG_ALERT, "Can't find nav-vor-ident sound" );
852 sound = _sgr->find( dme_fx_name );
853 if ( sound != NULL ) {
854 sound->set_volume( vol );
856 SG_LOG( SG_COCKPIT, SG_ALERT, "Can't find nav-dme-ident sound" );
859 const int NUM_IDENT_SLOTS = 5;
860 const time_t SLOT_LENGTH = 5; // seconds
862 // There are N slots numbered 0 through (NUM_IDENT_SLOTS-1) inclusive.
863 // Each slot is 5 seconds long.
864 // Slots 0 is for DME
865 // the rest are for azimuth.
866 time_t now = globals->get_time_params()->get_cur_time();
867 if ((now >= last_time) && (now < last_time + SLOT_LENGTH)) {
868 return; // wait longer
872 play_count = ++play_count % NUM_IDENT_SLOTS;
874 // Previous ident is out of time; if still playing, cut it off:
875 _sgr->stop( nav_fx_name );
876 _sgr->stop( dme_fx_name );
877 if (play_count == 0) { // the DME slot
878 if (_dmeInRange && dme_serviceable_node->getBoolValue()) {
880 if (vol > 0.05) _sgr->play_once( dme_fx_name );
883 if (inrange_node->getBoolValue() && nav_serviceable_node->getBoolValue()) {
884 if (vol > 0.05) _sgr->play_once(nav_fx_name);
889 FGNavRecord* FGNavRadio::findPrimaryNavaid(const SGGeod& aPos, double aFreqMHz)
891 FGNavRecord* nav = globals->get_navlist()->findByFreq(aFreqMHz, aPos);
896 return globals->get_loclist()->findByFreq(aFreqMHz, aPos);
899 // Update current nav/adf radio stations based on current postition
900 void FGNavRadio::search()
902 _time_before_search_sec = 1.0;
903 SGGeod pos = SGGeod::fromDegFt(lon_node->getDoubleValue(),
904 lat_node->getDoubleValue(), alt_node->getDoubleValue());
905 double freq = freq_node->getDoubleValue();
907 FGNavRecord* nav = findPrimaryNavaid(pos, freq);
908 if (nav == _navaid) {
909 return; // found the same as last search, we're done
913 string identBuffer(4, ' ');
915 _dme = globals->get_dmelist()->findByFreq(freq, pos);
917 nav_id_node->setStringValue(nav->get_ident());
918 identBuffer = simgear::strutils::rpad( nav->ident(), 4, ' ' );
920 effective_range = adjustNavRange(nav->get_elev_ft(), pos.getElevationM(), nav->get_range());
921 loc_node->setBoolValue(nav->type() != FGPositioned::VOR);
922 twist = nav->get_multiuse();
924 if (nav->type() == FGPositioned::VOR) {
925 target_radial = sel_radial_node->getDoubleValue();
927 has_gs_node->setBoolValue(false);
928 } else { // ILS or LOC
929 _gs = globals->get_gslist()->findByFreq(freq, pos);
930 has_gs_node->setBoolValue(_gs != NULL);
931 _localizerWidth = nav->localizerWidth();
933 effective_range = nav->get_range();
935 target_radial = nav->get_multiuse();
936 SG_NORMALIZE_RANGE(target_radial, 0.0, 360.0);
939 int tmp = (int)(_gs->get_multiuse() / 1000.0);
940 target_gs = (double)tmp / 100.0;
942 // until penaltyForNav goes away, we cannot assume we always pick
943 // paired LOC/GS trasmsitters. As we pass over a runway threshold, we
944 // often end up picking the 'wrong' LOC, but the correct GS. To avoid
945 // breaking the basis computation, ensure we use the GS radial and not
946 // the (potentially reversed) LOC radial.
947 double gs_radial = fmod(_gs->get_multiuse(), 1000.0);
948 SG_NORMALIZE_RANGE(gs_radial, 0.0, 360.0);
950 // GS axis unit tangent vector
951 // (along the runway)
952 _gsCart = _gs->cart();
953 _gsAxis = tangentVector(_gs->geod(), _gsCart, gs_radial);
955 // GS baseline unit tangent vector
956 // (perpendicular to the runay along the ground)
957 SGVec3d baseline = tangentVector(_gs->geod(), _gsCart, gs_radial + 90.0);
958 _gsVertical = cross(baseline, _gsAxis);
959 } // of have glideslope
960 } // of found LOC or ILS
963 } else { // found nothing
966 nav_id_node->setStringValue("");
967 loc_node->setBoolValue(false);
968 has_gs_node->setBoolValue(false);
970 _sgr->remove( nav_fx_name );
971 _sgr->remove( dme_fx_name );
974 is_valid_node->setBoolValue(nav != NULL);
975 id_c1_node->setIntValue( (int)identBuffer[0] );
976 id_c2_node->setIntValue( (int)identBuffer[1] );
977 id_c3_node->setIntValue( (int)identBuffer[2] );
978 id_c4_node->setIntValue( (int)identBuffer[3] );
981 void FGNavRadio::audioNavidChanged()
983 if (_sgr->exists(nav_fx_name)) {
984 _sgr->remove(nav_fx_name);
988 string trans_ident(_navaid->get_trans_ident());
989 SGSoundSample* sound = morse.make_ident(trans_ident, LO_FREQUENCY);
990 sound->set_volume( 0.3 );
991 if (!_sgr->add( sound, nav_fx_name )) {
992 SG_LOG(SG_COCKPIT, SG_WARN, "Failed to add v1-vor-ident sound");
995 if ( _sgr->exists( dme_fx_name ) ) {
996 _sgr->remove( dme_fx_name );
999 sound = morse.make_ident( trans_ident, HI_FREQUENCY );
1000 sound->set_volume( 0.3 );
1001 _sgr->add( sound, dme_fx_name );
1003 int offset = (int)(sg_random() * 30.0);
1004 play_count = offset / 4;
1005 last_time = globals->get_time_params()->get_cur_time() - offset;
1006 } catch (sg_io_exception& e) {
1007 SG_LOG(SG_GENERAL, SG_ALERT, e.getFormattedMessage());