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 comp_h = -dot(pos, _gsAxis); // component in horiz direction
612 double comp_v = dot(pos, _gsVertical); // component in vertical direction
613 //double comp_b = dot(pos, _gsBaseline); // component in baseline direction
614 //if (comp_b) {} // ... (useful for debugging)
616 // _gsDirect represents the angle of elevation of the aircraft
617 // as seen by the GS transmitter.
618 _gsDirect = atan2(comp_v, comp_h) * SGD_RADIANS_TO_DEGREES;
619 // At this point, if the aircraft is centered on the glide slope,
620 // _gsDirect will be a small positive number, e.g. 3.0 degrees
622 // Aim the branch cut straight down
623 // into the ground below the GS transmitter:
624 if (_gsDirect < -90.0) _gsDirect += 360.0;
626 double deflectionAngle = target_gs - _gsDirect;
628 if (falseCoursesEnabledNode->getBoolValue()) {
629 // Construct false glideslopes. The scale factor of 1.5
630 // in the sawtooth gives a period of 6 degrees.
631 // There will be zeros at 3, 6r, 9, 12r et cetera
632 // where "r" indicates reverse sensing.
633 // This is is consistent with conventional pilot lore
634 // e.g. http://www.allstar.fiu.edu/aerojava/ILS.htm
635 // but inconsistent with
636 // http://www.freepatentsonline.com/3757338.html
638 // It may be that some of each exist.
639 if (deflectionAngle < 0) {
640 deflectionAngle = 1.5 * sawtooth(deflectionAngle / 1.5);
642 // no false GS below the true GS
646 // GS is documented to be 1.4 degrees thick,
647 // i.e. plus or minus 0.7 degrees from the midline:
648 SG_CLAMP_RANGE(deflectionAngle, -0.7, 0.7);
650 // Many older instrument xml frontends depend on
651 // the un-normalized gs-needle-deflection.
652 // Apparently the interface standard is plus or minus 3.5 "volts"
653 // for a full-scale deflection:
654 _gsNeedleDeflection = deflectionAngle * 5.0;
655 _gsNeedleDeflection *= signal_quality_norm;
657 _gsNeedleDeflectionNorm = (deflectionAngle / 0.7) * signal_quality_norm;
659 //////////////////////////////////////////////////////////
660 // Calculate desired rate of climb for intercepting the GS
661 //////////////////////////////////////////////////////////
662 double gs_diff = target_gs - _gsDirect;
663 // convert desired vertical path angle into a climb rate
664 double des_angle = _gsDirect - 10 * gs_diff;
665 /* printf("target_gs=%.1f angle=%.1f gs_diff=%.1f des_angle=%.1f\n",
666 target_gs, _gsDirect, gs_diff, des_angle); */
668 // estimate horizontal speed towards ILS in meters per minute
669 double elapsedDistance = last_x - gsDist;
672 double new_vel = ( elapsedDistance / dt );
673 horiz_vel = 0.99 * horiz_vel + 0.01 * new_vel;
674 /* printf("vel=%.1f (dist=%.1f dt=%.2f)\n", horiz_vel, elapsedDistance, dt);*/
676 gs_rate_of_climb_node
677 ->setDoubleValue( -sin( des_angle * SGD_DEGREES_TO_RADIANS )
678 * horiz_vel * SG_METER_TO_FEET );
679 gs_rate_of_climb_fpm_node
680 ->setDoubleValue( gs_rate_of_climb_node->getDoubleValue() * 60 );
683 void FGNavRadio::updateDME(const SGVec3d& aircraft)
685 if (!_dme || !dme_serviceable_node->getBoolValue()) {
690 double dme_distance = dist(aircraft, _dme->cart());
691 _dmeInRange = (dme_distance < _dme->get_range() * SG_NM_TO_METER);
694 void FGNavRadio::valueChanged (SGPropertyNode* prop)
696 if (prop == gps_course_node) {
697 if (!nav_slaved_to_gps_node->getBoolValue()) {
701 // GPS desired course has changed, sync up our selected-course
702 double v = prop->getDoubleValue();
703 if (v != sel_radial_node->getDoubleValue()) {
704 sel_radial_node->setDoubleValue(v);
706 } else if (prop == nav_slaved_to_gps_node) {
707 if (prop->getBoolValue()) {
708 // slaved-to-GPS activated, clear obsolete NAV outputs and sync up selected course
710 sel_radial_node->setDoubleValue(gps_course_node->getDoubleValue());
712 // slave-to-GPS enabled/disabled, resync NAV station (update all outputs)
714 _time_before_search_sec = 0;
718 void FGNavRadio::updateGPSSlaved()
720 has_gs_node->setBoolValue(gps_has_gs_node->getBoolValue());
722 _toFlag = gps_to_flag_node->getBoolValue();
723 _fromFlag = gps_from_flag_node->getBoolValue();
725 bool gpsValid = (_toFlag | _fromFlag);
726 inrange_node->setBoolValue(gpsValid);
728 signal_quality_norm_node->setDoubleValue(0.0);
729 _cdiDeflection = 0.0;
730 _cdiCrossTrackErrorM = 0.0;
731 _gsNeedleDeflection = 0.0;
732 _gsNeedleDeflectionNorm = 0.0;
736 // this is unfortunate, but panel instruments use this value to decide
737 // if the navradio output is valid.
738 signal_quality_norm_node->setDoubleValue(1.0);
740 _cdiDeflection = gps_cdi_deflection_node->getDoubleValue();
741 // clmap to some range (+/- 10 degrees) as the regular deflection
742 SG_CLAMP_RANGE(_cdiDeflection, -10.0, 10.0 );
744 _cdiCrossTrackErrorM = gps_xtrack_error_nm_node->getDoubleValue() * SG_NM_TO_METER;
745 _gsNeedleDeflection = 0.0; // FIXME, supply this
747 double trtrue = gps_course_node->getDoubleValue() + _magvarNode->getDoubleValue();
748 SG_NORMALIZE_RANGE(trtrue, 0.0, 360.0);
749 target_radial_true_node->setDoubleValue( trtrue );
752 void FGNavRadio::updateCDI(double dt)
754 bool cdi_serviceable = cdi_serviceable_node->getBoolValue();
755 bool inrange = inrange_node->getBoolValue();
757 if (tofrom_serviceable_node->getBoolValue()) {
758 to_flag_node->setBoolValue(_toFlag);
759 from_flag_node->setBoolValue(_fromFlag);
761 to_flag_node->setBoolValue(false);
762 from_flag_node->setBoolValue(false);
765 if (!cdi_serviceable) {
766 _cdiDeflection = 0.0;
767 _cdiCrossTrackErrorM = 0.0;
770 cdi_deflection_node->setDoubleValue(_cdiDeflection);
771 cdi_deflection_norm_node->setDoubleValue(_cdiDeflection * 0.1);
772 cdi_xtrack_error_node->setDoubleValue(_cdiCrossTrackErrorM);
774 //////////////////////////////////////////////////////////
775 // compute an approximate ground track heading error
776 //////////////////////////////////////////////////////////
777 double hdg_error = 0.0;
778 if ( inrange && cdi_serviceable ) {
779 double vn = fgGetDouble( "/velocities/speed-north-fps" );
780 double ve = fgGetDouble( "/velocities/speed-east-fps" );
781 double gnd_trk_true = atan2( ve, vn ) * SGD_RADIANS_TO_DEGREES;
782 if ( gnd_trk_true < 0.0 ) { gnd_trk_true += 360.0; }
784 SGPropertyNode *true_hdg
785 = fgGetNode("/orientation/heading-deg", true);
786 hdg_error = gnd_trk_true - true_hdg->getDoubleValue();
788 // cout << "ground track = " << gnd_trk_true
789 // << " orientation = " << true_hdg->getDoubleValue() << endl;
791 cdi_xtrack_hdg_err_node->setDoubleValue( hdg_error );
793 //////////////////////////////////////////////////////////
794 // Calculate a suggested target heading to smoothly intercept
796 //////////////////////////////////////////////////////////
798 // Now that we have cross track heading adjustment built in,
799 // we shouldn't need to overdrive the heading angle within 8km
802 // The cdi deflection should be +/-10 for a full range of deflection
803 // so multiplying this by 3 gives us +/- 30 degrees heading
805 double adjustment = _cdiDeflection * 3.0;
806 SG_CLAMP_RANGE( adjustment, -30.0, 30.0 );
808 // determine the target heading to fly to intercept the
809 // tgt_radial = target radial (true) + cdi offset adjustmest -
810 // xtrack heading error adjustment
812 double trtrue = target_radial_true_node->getDoubleValue();
813 if ( loc_node->getBoolValue() && backcourse_node->getBoolValue() ) {
814 // tuned to a localizer and backcourse mode activated
815 trtrue += 180.0; // reverse the target localizer heading
816 SG_NORMALIZE_RANGE(trtrue, 0.0, 360.0);
817 nta_hdg = trtrue - adjustment - hdg_error;
819 nta_hdg = trtrue + adjustment - hdg_error;
822 SG_NORMALIZE_RANGE(nta_hdg, 0.0, 360.0);
823 target_auto_hdg_node->setDoubleValue( nta_hdg );
825 //////////////////////////////////////////////////////////
826 // compute the time to intercept selected radial (based on
827 // current and last cross track errors and dt)
828 //////////////////////////////////////////////////////////
830 if ( inrange && cdi_serviceable ) {
831 double cur_rate = (last_xtrack_error - _cdiCrossTrackErrorM) / dt;
832 xrate_ms = 0.99 * xrate_ms + 0.01 * cur_rate;
833 if ( fabs(xrate_ms) > 0.00001 ) {
834 t = _cdiCrossTrackErrorM / xrate_ms;
839 time_to_intercept->setDoubleValue( t );
841 if (!gs_serviceable_node->getBoolValue() ) {
842 _gsNeedleDeflection = 0.0;
843 _gsNeedleDeflectionNorm = 0.0;
845 gs_deflection_node->setDoubleValue(_gsNeedleDeflection);
846 gs_deflection_deg_node->setDoubleValue(_gsNeedleDeflectionNorm * 0.7);
847 gs_deflection_norm_node->setDoubleValue(_gsNeedleDeflectionNorm);
848 gs_direct_node->setDoubleValue(_gsDirect);
850 last_xtrack_error = _cdiCrossTrackErrorM;
853 void FGNavRadio::updateAudio()
855 if (!_navaid || !inrange_node->getBoolValue() || !nav_serviceable_node->getBoolValue()) {
859 // play station ident via audio system if on + ident,
860 // otherwise turn it off
861 if (!power_btn_node->getBoolValue()
862 || !(bus_power_node->getDoubleValue() > 1.0)
863 || !ident_btn_node->getBoolValue()
864 || !audio_btn_node->getBoolValue() ) {
865 _sgr->stop( nav_fx_name );
866 _sgr->stop( dme_fx_name );
870 SGSoundSample *sound = _sgr->find( nav_fx_name );
871 double vol = vol_btn_node->getFloatValue();
872 SG_CLAMP_RANGE(vol, 0.0, 1.0);
874 if ( sound != NULL ) {
875 sound->set_volume( vol );
877 SG_LOG( SG_COCKPIT, SG_ALERT, "Can't find nav-vor-ident sound" );
880 sound = _sgr->find( dme_fx_name );
881 if ( sound != NULL ) {
882 sound->set_volume( vol );
884 SG_LOG( SG_COCKPIT, SG_ALERT, "Can't find nav-dme-ident sound" );
887 const int NUM_IDENT_SLOTS = 5;
888 const time_t SLOT_LENGTH = 5; // seconds
890 // There are N slots numbered 0 through (NUM_IDENT_SLOTS-1) inclusive.
891 // Each slot is 5 seconds long.
892 // Slots 0 is for DME
893 // the rest are for azimuth.
894 time_t now = globals->get_time_params()->get_cur_time();
895 if ((now >= last_time) && (now < last_time + SLOT_LENGTH)) {
896 return; // wait longer
900 play_count = ++play_count % NUM_IDENT_SLOTS;
902 // Previous ident is out of time; if still playing, cut it off:
903 _sgr->stop( nav_fx_name );
904 _sgr->stop( dme_fx_name );
905 if (play_count == 0) { // the DME slot
906 if (_dmeInRange && dme_serviceable_node->getBoolValue()) {
908 if (vol > 0.05) _sgr->play_once( dme_fx_name );
911 if (inrange_node->getBoolValue() && nav_serviceable_node->getBoolValue()) {
912 if (vol > 0.05) _sgr->play_once(nav_fx_name);
917 FGNavRecord* FGNavRadio::findPrimaryNavaid(const SGGeod& aPos, double aFreqMHz)
919 FGNavRecord* nav = globals->get_navlist()->findByFreq(aFreqMHz, aPos);
924 return globals->get_loclist()->findByFreq(aFreqMHz, aPos);
927 // Update current nav/adf radio stations based on current postition
928 void FGNavRadio::search()
930 _time_before_search_sec = 1.0;
931 SGGeod pos = SGGeod::fromDegFt(lon_node->getDoubleValue(),
932 lat_node->getDoubleValue(), alt_node->getDoubleValue());
933 double freq = freq_node->getDoubleValue();
935 FGNavRecord* nav = findPrimaryNavaid(pos, freq);
936 if (nav == _navaid) {
937 return; // found the same as last search, we're done
941 string identBuffer(4, ' ');
943 // use ILS signals as DME, otherwise search by frequency
944 if (nav->type()==FGPositioned::ILS)
947 _dme = globals->get_dmelist()->findByFreq(freq, pos);
949 nav_id_node->setStringValue(nav->get_ident());
950 identBuffer = simgear::strutils::rpad( nav->ident(), 4, ' ' );
952 effective_range = adjustNavRange(nav->get_elev_ft(), pos.getElevationM(), nav->get_range());
953 loc_node->setBoolValue(nav->type() != FGPositioned::VOR);
954 twist = nav->get_multiuse();
956 if (nav->type() == FGPositioned::VOR) {
957 target_radial = sel_radial_node->getDoubleValue();
959 has_gs_node->setBoolValue(false);
960 } else { // ILS or LOC
961 _gs = globals->get_gslist()->findByFreq(freq, pos);
962 has_gs_node->setBoolValue(_gs != NULL);
963 _localizerWidth = nav->localizerWidth();
965 effective_range = nav->get_range();
967 target_radial = nav->get_multiuse();
968 SG_NORMALIZE_RANGE(target_radial, 0.0, 360.0);
971 int tmp = (int)(_gs->get_multiuse() / 1000.0);
972 target_gs = (double)tmp / 100.0;
974 double gs_radial = fmod(_gs->get_multiuse(), 1000.0);
975 SG_NORMALIZE_RANGE(gs_radial, 0.0, 360.0);
976 _gsCart = _gs->cart();
978 // GS axis unit tangent vector
979 // (along the runway):
980 _gsAxis = tangentVector(_gs->geod(), gs_radial);
982 // GS baseline unit tangent vector
983 // (transverse to the runay along the ground)
984 _gsBaseline = tangentVector(_gs->geod(), gs_radial + 90.0);
985 _gsVertical = cross(_gsBaseline, _gsAxis);
986 } // of have glideslope
987 } // of found LOC or ILS
990 } else { // found nothing
993 nav_id_node->setStringValue("");
994 loc_node->setBoolValue(false);
995 has_gs_node->setBoolValue(false);
997 _sgr->remove( nav_fx_name );
998 _sgr->remove( dme_fx_name );
1001 is_valid_node->setBoolValue(nav != NULL);
1002 id_c1_node->setIntValue( (int)identBuffer[0] );
1003 id_c2_node->setIntValue( (int)identBuffer[1] );
1004 id_c3_node->setIntValue( (int)identBuffer[2] );
1005 id_c4_node->setIntValue( (int)identBuffer[3] );
1008 void FGNavRadio::audioNavidChanged()
1010 if (_sgr->exists(nav_fx_name)) {
1011 _sgr->remove(nav_fx_name);
1015 string trans_ident(_navaid->get_trans_ident());
1016 SGSoundSample* sound = morse.make_ident(trans_ident, LO_FREQUENCY);
1017 sound->set_volume( 0.3 );
1018 if (!_sgr->add( sound, nav_fx_name )) {
1019 SG_LOG(SG_COCKPIT, SG_WARN, "Failed to add v1-vor-ident sound");
1022 if ( _sgr->exists( dme_fx_name ) ) {
1023 _sgr->remove( dme_fx_name );
1026 sound = morse.make_ident( trans_ident, HI_FREQUENCY );
1027 sound->set_volume( 0.3 );
1028 _sgr->add( sound, dme_fx_name );
1030 int offset = (int)(sg_random() * 30.0);
1031 play_count = offset / 4;
1032 last_time = globals->get_time_params()->get_cur_time() - offset;
1033 } catch (sg_io_exception& e) {
1034 SG_LOG(SG_GENERAL, SG_ALERT, e.getFormattedMessage());