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>
47 #include <Sound/morse.hxx>
52 // General-purpose sawtooth function. Graph looks like this:
55 // Odd symmetry, inversion symmetry about the origin.
56 // Unit slope at the origin.
57 // Max 1, min -1, period 4.
58 // Two zero-crossings per period, one with + slope, one with - slope.
59 // Useful for false localizer courses.
60 static double sawtooth(double xx)
62 return 4.0 * fabs(xx/4.0 + 0.25 - floor(xx/4.0 + 0.75)) - 1.0;
65 // Calculate a Cartesian unit vector in the
66 // local horizontal plane, i.e. tangent to the
67 // surface of the earth at the local ground zero.
68 // The tangent vector passes through the given <midpoint>
69 // and points forward along the given <heading>.
70 // The <heading> is given in degrees.
71 static SGVec3d tangentVector(const SGGeod& midpoint, const double heading)
73 // The size of the delta is presumably chosen to give
74 // numerical stability. I don't know how the value was chosen.
75 // It probably doesn't matter much. It gets divided out.
76 double delta(100.0); // in meters
78 double az2; // ignored
79 SGGeodesy::direct(midpoint, heading, delta, head, az2);
80 SGGeodesy::direct(midpoint, 180+heading, delta, tail, az2);
81 head.setElevationM(midpoint.getElevationM());
82 tail.setElevationM(midpoint.getElevationM());
83 SGVec3d head_xyz = SGVec3d::fromGeod(head);
84 SGVec3d tail_xyz = SGVec3d::fromGeod(tail);
85 // Awkward formula here, needed because vector-by-scalar
86 // multiplication is defined, but not vector-by-scalar division.
87 return (head_xyz - tail_xyz) * (0.5/delta);
90 // Create a "serviceable" node with a default value of "true"
91 SGPropertyNode_ptr createServiceableProp(SGPropertyNode* aParent,
94 SGPropertyNode_ptr n =
95 aParent->getChild(aName, 0, true)->getChild("serviceable", 0, true);
96 simgear::props::Type typ = n->getType();
97 if ((typ == simgear::props::NONE) || (typ == simgear::props::UNSPECIFIED)) {
98 n->setBoolValue(true);
104 FGNavRadio::FGNavRadio(SGPropertyNode *node) :
108 lon_node(fgGetNode("/position/longitude-deg", true)),
109 lat_node(fgGetNode("/position/latitude-deg", true)),
110 alt_node(fgGetNode("/position/altitude-ft", true)),
115 effective_range(0.0),
120 last_xtrack_error(0.0),
122 _localizerWidth(5.0),
123 _name(node->getStringValue("name", "nav")),
124 _num(node->getIntValue("number", 0)),
125 _time_before_search_sec(-1.0),
126 _gsCart(SGVec3d::zeros()),
127 _gsAxis(SGVec3d::zeros()),
128 _gsVertical(SGVec3d::zeros()),
133 _cdiCrossTrackErrorM(0.0),
134 _gsNeedleDeflection(0.0),
135 _gsNeedleDeflectionNorm(0.0),
138 SGPath path( globals->get_fg_root() );
140 term.append( "Navaids/range.term" );
142 low.append( "Navaids/range.low" );
144 high.append( "Navaids/range.high" );
146 term_tbl = new SGInterpTable( term.str() );
147 low_tbl = new SGInterpTable( low.str() );
148 high_tbl = new SGInterpTable( high.str() );
150 string branch("/instrumentation/" + _name);
151 _radio_node = fgGetNode(branch.c_str(), _num, true);
156 FGNavRadio::~FGNavRadio()
158 if (gps_course_node) {
159 gps_course_node->removeChangeListener(this);
162 if (nav_slaved_to_gps_node) {
163 nav_slaved_to_gps_node->removeChangeListener(this);
175 SGSoundMgr *smgr = globals->get_soundmgr();
176 _sgr = smgr->find("avionics", true);
177 _sgr->tie_to_listener();
179 SGPropertyNode* node = _radio_node.get();
181 fgGetNode(("/systems/electrical/outputs/" + _name).c_str(), true);
184 is_valid_node = node->getChild("data-is-valid", 0, true);
185 power_btn_node = node->getChild("power-btn", 0, true);
186 power_btn_node->setBoolValue( true );
187 vol_btn_node = node->getChild("volume", 0, true);
188 ident_btn_node = node->getChild("ident", 0, true);
189 ident_btn_node->setBoolValue( true );
190 audio_btn_node = node->getChild("audio-btn", 0, true);
191 audio_btn_node->setBoolValue( true );
192 backcourse_node = node->getChild("back-course-btn", 0, true);
193 backcourse_node->setBoolValue( false );
195 nav_serviceable_node = node->getChild("serviceable", 0, true);
196 cdi_serviceable_node = createServiceableProp(node, "cdi");
197 gs_serviceable_node = createServiceableProp(node, "gs");
198 tofrom_serviceable_node = createServiceableProp(node, "to-from");
199 dme_serviceable_node = createServiceableProp(node, "dme");
201 falseCoursesEnabledNode =
202 fgGetNode("/sim/realism/false-radio-courses-enabled");
203 if (!falseCoursesEnabledNode) {
204 falseCoursesEnabledNode =
205 fgGetNode("/sim/realism/false-radio-courses-enabled", true);
206 falseCoursesEnabledNode->setBoolValue(true);
210 SGPropertyNode *subnode = node->getChild("frequencies", 0, true);
211 freq_node = subnode->getChild("selected-mhz", 0, true);
212 alt_freq_node = subnode->getChild("standby-mhz", 0, true);
213 fmt_freq_node = subnode->getChild("selected-mhz-fmt", 0, true);
214 fmt_alt_freq_node = subnode->getChild("standby-mhz-fmt", 0, true);
217 subnode = node->getChild("radials", 0, true);
218 sel_radial_node = subnode->getChild("selected-deg", 0, true);
219 radial_node = subnode->getChild("actual-deg", 0, true);
220 recip_radial_node = subnode->getChild("reciprocal-radial-deg", 0, true);
221 target_radial_true_node = subnode->getChild("target-radial-deg", 0, true);
222 target_auto_hdg_node = subnode->getChild("target-auto-hdg-deg", 0, true);
225 heading_node = node->getChild("heading-deg", 0, true);
226 time_to_intercept = node->getChild("time-to-intercept-sec", 0, true);
227 to_flag_node = node->getChild("to-flag", 0, true);
228 from_flag_node = node->getChild("from-flag", 0, true);
229 inrange_node = node->getChild("in-range", 0, true);
230 signal_quality_norm_node = node->getChild("signal-quality-norm", 0, true);
231 cdi_deflection_node = node->getChild("heading-needle-deflection", 0, true);
232 cdi_deflection_norm_node = node->getChild("heading-needle-deflection-norm", 0, true);
233 cdi_xtrack_error_node = node->getChild("crosstrack-error-m", 0, true);
234 cdi_xtrack_hdg_err_node
235 = node->getChild("crosstrack-heading-error-deg", 0, true);
236 has_gs_node = node->getChild("has-gs", 0, true);
237 loc_node = node->getChild("nav-loc", 0, true);
238 loc_dist_node = node->getChild("nav-distance", 0, true);
239 gs_deflection_node = node->getChild("gs-needle-deflection", 0, true);
240 gs_deflection_deg_node = node->getChild("gs-needle-deflection-deg", 0, true);
241 gs_deflection_norm_node = node->getChild("gs-needle-deflection-norm", 0, true);
242 gs_direct_node = node->getChild("gs-direct-deg", 0, true);
243 gs_rate_of_climb_node = node->getChild("gs-rate-of-climb", 0, true);
244 gs_rate_of_climb_fpm_node = node->getChild("gs-rate-of-climb-fpm", 0, true);
245 gs_dist_node = node->getChild("gs-distance", 0, true);
246 gs_inrange_node = node->getChild("gs-in-range", 0, true);
248 nav_id_node = node->getChild("nav-id", 0, true);
249 id_c1_node = node->getChild("nav-id_asc1", 0, true);
250 id_c2_node = node->getChild("nav-id_asc2", 0, true);
251 id_c3_node = node->getChild("nav-id_asc3", 0, true);
252 id_c4_node = node->getChild("nav-id_asc4", 0, true);
254 // gps slaving support
255 nav_slaved_to_gps_node = node->getChild("slaved-to-gps", 0, true);
256 nav_slaved_to_gps_node->addChangeListener(this);
258 gps_cdi_deflection_node = fgGetNode("/instrumentation/gps/cdi-deflection", true);
259 gps_to_flag_node = fgGetNode("/instrumentation/gps/to-flag", true);
260 gps_from_flag_node = fgGetNode("/instrumentation/gps/from-flag", true);
261 gps_has_gs_node = fgGetNode("/instrumentation/gps/has-gs", true);
262 gps_course_node = fgGetNode("/instrumentation/gps/desired-course-deg", true);
263 gps_course_node->addChangeListener(this);
265 gps_xtrack_error_nm_node = fgGetNode("/instrumentation/gps/wp/wp[1]/course-error-nm", true);
266 _magvarNode = fgGetNode("/environment/magnetic-variation-deg", true);
268 std::ostringstream temp;
269 temp << _name << "nav-ident" << _num;
270 nav_fx_name = temp.str();
271 temp << _name << "dme-ident" << _num;
272 dme_fx_name = temp.str();
278 tie("dme-in-range", SGRawValuePointer<bool>(&_dmeInRange));
279 tie("operable", SGRawValueMethods<FGNavRadio, bool>(*this, &FGNavRadio::isOperable, NULL));
284 FGNavRadio::unbind ()
286 for (unsigned int t=0; t<_tiedNodes.size(); ++t) {
287 _tiedNodes[t]->untie();
293 // model standard VOR/DME/TACAN service volumes as per AIM 1-1-8
294 double FGNavRadio::adjustNavRange( double stationElev, double aircraftElev,
295 double nominalRange )
297 if (nominalRange <= 0.0) {
298 nominalRange = FG_NAV_DEFAULT_RANGE;
301 // extend out actual usable range to be 1.3x the published safe range
302 const double usability_factor = 1.3;
304 // assumptions we model the standard service volume, plus
305 // ... rather than specifying a cylinder, we model a cone that
306 // contains the cylinder. Then we put an upside down cone on top
307 // to model diminishing returns at too-high altitudes.
309 // altitude difference
310 double alt = ( aircraftElev * SG_METER_TO_FEET - stationElev );
311 // cout << "aircraft elev = " << aircraftElev * SG_METER_TO_FEET
312 // << " station elev = " << stationElev << endl;
314 if ( nominalRange < 25.0 + SG_EPSILON ) {
315 // Standard Terminal Service Volume
316 return term_tbl->interpolate( alt ) * usability_factor;
317 } else if ( nominalRange < 50.0 + SG_EPSILON ) {
318 // Standard Low Altitude Service Volume
319 // table is based on range of 40, scale to actual range
320 return low_tbl->interpolate( alt ) * nominalRange / 40.0
323 // Standard High Altitude Service Volume
324 // table is based on range of 130, scale to actual range
325 return high_tbl->interpolate( alt ) * nominalRange / 130.0
331 // model standard ILS service volumes as per AIM 1-1-9
332 double FGNavRadio::adjustILSRange( double stationElev, double aircraftElev,
333 double offsetDegrees, double distance )
335 // assumptions we model the standard service volume, plus
337 // altitude difference
338 // double alt = ( aircraftElev * SG_METER_TO_FEET - stationElev );
339 // double offset = fabs( offsetDegrees );
341 // if ( offset < 10 ) {
342 // return FG_ILS_DEFAULT_RANGE;
343 // } else if ( offset < 35 ) {
344 // return 10 + (35 - offset) * (FG_ILS_DEFAULT_RANGE - 10) / 25;
345 // } else if ( offset < 45 ) {
346 // return (45 - offset);
347 // } else if ( offset > 170 ) {
348 // return FG_ILS_DEFAULT_RANGE;
349 // } else if ( offset > 145 ) {
350 // return 10 + (offset - 145) * (FG_ILS_DEFAULT_RANGE - 10) / 25;
351 // } else if ( offset > 135 ) {
352 // return (offset - 135);
356 return FG_LOC_DEFAULT_RANGE;
360 //////////////////////////////////////////////////////////////////////////
361 // Update the various nav values based on position and valid tuned in navs
362 //////////////////////////////////////////////////////////////////////////
364 FGNavRadio::update(double dt)
370 // Create "formatted" versions of the nav frequencies for
371 // instrument displays.
373 sprintf( tmp, "%.2f", freq_node->getDoubleValue() );
374 fmt_freq_node->setStringValue(tmp);
375 sprintf( tmp, "%.2f", alt_freq_node->getDoubleValue() );
376 fmt_alt_freq_node->setStringValue(tmp);
378 if (power_btn_node->getBoolValue()
379 && (bus_power_node->getDoubleValue() > 1.0)
380 && nav_serviceable_node->getBoolValue() )
392 void FGNavRadio::clearOutputs()
394 inrange_node->setBoolValue( false );
395 signal_quality_norm_node->setDoubleValue( 0.0 );
396 cdi_deflection_node->setDoubleValue( 0.0 );
397 cdi_deflection_norm_node->setDoubleValue( 0.0 );
398 cdi_xtrack_error_node->setDoubleValue( 0.0 );
399 cdi_xtrack_hdg_err_node->setDoubleValue( 0.0 );
400 time_to_intercept->setDoubleValue( 0.0 );
401 heading_node->setDoubleValue(0.0);
402 gs_deflection_node->setDoubleValue( 0.0 );
403 gs_deflection_deg_node->setDoubleValue(0.0);
404 gs_deflection_norm_node->setDoubleValue(0.0);
405 gs_direct_node->setDoubleValue(0.0);
406 gs_inrange_node->setBoolValue( false );
407 loc_node->setBoolValue( false );
408 has_gs_node->setBoolValue(false);
410 to_flag_node->setBoolValue( false );
411 from_flag_node->setBoolValue( false );
412 is_valid_node->setBoolValue(false);
413 nav_id_node->setStringValue("");
420 void FGNavRadio::updateReceiver(double dt)
422 SGGeod pos = SGGeod::fromDegFt(lon_node->getDoubleValue(),
423 lat_node->getDoubleValue(),
424 alt_node->getDoubleValue());
425 SGVec3d aircraft = SGVec3d::fromGeod(pos);
428 // Do a nav station search only once a second to reduce
429 // unnecessary work. (Also, make sure to do this before caching
431 _time_before_search_sec -= dt;
432 if ( _time_before_search_sec < 0 ) {
438 loc_dist = dist(aircraft, _navaid->cart());
439 loc_dist_node->setDoubleValue( loc_dist );
443 if (nav_slaved_to_gps_node->getBoolValue()) {
444 // when slaved to GPS: only allow stuff above: tune NAV station
445 // upate DME. All other data driven by GPS only.
451 _cdiDeflection = 0.0;
452 _cdiCrossTrackErrorM = 0.0;
453 _toFlag = _fromFlag = false;
454 _gsNeedleDeflection = 0.0;
455 _gsNeedleDeflectionNorm = 0.0;
456 heading_node->setDoubleValue(0.0);
457 inrange_node->setBoolValue(false);
461 double nav_elev = _navaid->get_elev_ft();
463 bool is_loc = loc_node->getBoolValue();
464 double signal_quality_norm = signal_quality_norm_node->getDoubleValue();
467 //////////////////////////////////////////////////////////
468 // compute forward and reverse wgs84 headings to localizer
469 //////////////////////////////////////////////////////////
471 SGGeodesy::inverse(pos, _navaid->geod(), hdg, az2, s);
472 heading_node->setDoubleValue(hdg);
473 double radial = az2 - twist;
474 double recip = radial + 180.0;
475 SG_NORMALIZE_RANGE(recip, 0.0, 360.0);
476 radial_node->setDoubleValue( radial );
477 recip_radial_node->setDoubleValue( recip );
479 //////////////////////////////////////////////////////////
480 // compute the target/selected radial in "true" heading
481 //////////////////////////////////////////////////////////
483 target_radial = sel_radial_node->getDoubleValue();
486 // VORs need twist (mag-var) added; ILS/LOCs don't but we set twist to 0.0
487 double trtrue = target_radial + twist;
488 SG_NORMALIZE_RANGE(trtrue, 0.0, 360.0);
489 target_radial_true_node->setDoubleValue( trtrue );
491 //////////////////////////////////////////////////////////
492 // adjust reception range for altitude
493 // FIXME: make sure we are using the navdata range now that
494 // it is valid in the data file
495 //////////////////////////////////////////////////////////
497 double offset = radial - target_radial;
498 SG_NORMALIZE_RANGE(offset, -180.0, 180.0);
500 = adjustILSRange( nav_elev, pos.getElevationM(), offset,
501 loc_dist * SG_METER_TO_NM );
504 = adjustNavRange( nav_elev, pos.getElevationM(), _navaid->get_range() );
507 double effective_range_m = effective_range * SG_NM_TO_METER;
509 //////////////////////////////////////////////////////////
510 // compute signal quality
511 // 100% within effective_range
512 // decreases 1/x^2 further out
513 //////////////////////////////////////////////////////////
514 double last_signal_quality_norm = signal_quality_norm;
516 if ( loc_dist < effective_range_m ) {
517 signal_quality_norm = 1.0;
519 double range_exceed_norm = loc_dist/effective_range_m;
520 signal_quality_norm = 1/(range_exceed_norm*range_exceed_norm);
523 signal_quality_norm = fgGetLowPass( last_signal_quality_norm,
524 signal_quality_norm, dt );
526 signal_quality_norm_node->setDoubleValue( signal_quality_norm );
527 bool inrange = signal_quality_norm > 0.2;
528 inrange_node->setBoolValue( inrange );
530 //////////////////////////////////////////////////////////
531 // compute to/from flag status
532 //////////////////////////////////////////////////////////
537 double offset = fabs(radial - target_radial);
538 _toFlag = (offset > 90.0 && offset < 270.0);
540 _fromFlag = !_toFlag;
542 _toFlag = _fromFlag = false;
546 double r = target_radial - radial;
547 SG_NORMALIZE_RANGE(r, -180.0, 180.0);
550 if (falseCoursesEnabledNode->getBoolValue()) {
551 // The factor of 30.0 gives a period of 120 which gives us 3 cycles and six
552 // zeros i.e. six courses: one front course, one back course, and four
553 // false courses. Three of the six are reverse sensing.
554 _cdiDeflection = 30.0 * sawtooth(r / 30.0);
556 // no false courses, but we do need to create a back course
557 if (fabs(r) > 90.0) { // front course
558 _cdiDeflection = r - copysign(180.0, r);
560 _cdiDeflection = r; // back course
563 _cdiDeflection = -_cdiDeflection; // reverse for outbound radial
564 } // of false courses disabled
566 const double VOR_FULL_ARC = 20.0; // VOR is -10 .. 10 degree swing
567 _cdiDeflection *= VOR_FULL_ARC / _localizerWidth; // increased localiser sensitivity
569 if (backcourse_node->getBoolValue()) {
570 _cdiDeflection = -_cdiDeflection;
573 // handle the TO side of the VOR
574 if (fabs(r) > 90.0) {
575 r = ( r<0.0 ? -r-180.0 : -r+180.0 );
578 } // of non-localiser case
580 SG_CLAMP_RANGE(_cdiDeflection, -10.0, 10.0 );
581 _cdiDeflection *= signal_quality_norm;
583 // cross-track error (in metres)
584 _cdiCrossTrackErrorM = loc_dist * sin(r * SGD_DEGREES_TO_RADIANS);
586 updateGlideSlope(dt, aircraft, signal_quality_norm);
589 void FGNavRadio::updateGlideSlope(double dt, const SGVec3d& aircraft, double signal_quality_norm)
591 _gsNeedleDeflection = 0.0;
592 if (!_gs || !inrange_node->getBoolValue()) {
593 gs_dist_node->setDoubleValue( 0.0 );
594 gs_inrange_node->setBoolValue(false);
595 _gsNeedleDeflection = 0.0;
596 _gsNeedleDeflectionNorm = 0.0;
600 double gsDist = dist(aircraft, _gsCart);
601 gs_dist_node->setDoubleValue(gsDist);
602 bool gsInRange = (gsDist < (_gs->get_range() * SG_NM_TO_METER));
603 gs_inrange_node->setBoolValue(gsInRange);
605 if (!gsInRange) return;
607 SGVec3d pos = aircraft - _gsCart; // relative vector from gs antenna to aircraft
608 // The positive GS axis points along the runway in the landing direction,
609 // toward the far end, not toward the approach area, so we need a - sign here:
610 double comp_h = -dot(pos, _gsAxis); // component in horiz direction
611 double comp_v = dot(pos, _gsVertical); // component in vertical direction
612 //double comp_b = dot(pos, _gsBaseline); // component in baseline direction
613 //if (comp_b) {} // ... (useful for debugging)
615 // _gsDirect represents the angle of elevation of the aircraft
616 // as seen by the GS transmitter.
617 _gsDirect = atan2(comp_v, comp_h) * SGD_RADIANS_TO_DEGREES;
618 // At this point, if the aircraft is centered on the glide slope,
619 // _gsDirect will be a small positive number, e.g. 3.0 degrees
621 // Aim the branch cut straight down
622 // into the ground below the GS transmitter:
623 if (_gsDirect < -90.0) _gsDirect += 360.0;
625 double deflectionAngle = target_gs - _gsDirect;
627 if (falseCoursesEnabledNode->getBoolValue()) {
628 // Construct false glideslopes. The scale factor of 1.5
629 // in the sawtooth gives a period of 6 degrees.
630 // There will be zeros at 3, 6r, 9, 12r et cetera
631 // where "r" indicates reverse sensing.
632 // This is is consistent with conventional pilot lore
633 // e.g. http://www.allstar.fiu.edu/aerojava/ILS.htm
634 // but inconsistent with
635 // http://www.freepatentsonline.com/3757338.html
637 // It may be that some of each exist.
638 if (deflectionAngle < 0) {
639 deflectionAngle = 1.5 * sawtooth(deflectionAngle / 1.5);
641 // no false GS below the true GS
645 // GS is documented to be 1.4 degrees thick,
646 // i.e. plus or minus 0.7 degrees from the midline:
647 SG_CLAMP_RANGE(deflectionAngle, -0.7, 0.7);
649 // Many older instrument xml frontends depend on
650 // the un-normalized gs-needle-deflection.
651 // Apparently the interface standard is plus or minus 3.5 "volts"
652 // for a full-scale deflection:
653 _gsNeedleDeflection = deflectionAngle * 5.0;
654 _gsNeedleDeflection *= signal_quality_norm;
656 _gsNeedleDeflectionNorm = (deflectionAngle / 0.7) * signal_quality_norm;
658 //////////////////////////////////////////////////////////
659 // Calculate desired rate of climb for intercepting the GS
660 //////////////////////////////////////////////////////////
661 double gs_diff = target_gs - _gsDirect;
662 // convert desired vertical path angle into a climb rate
663 double des_angle = _gsDirect - 10 * gs_diff;
664 /* printf("target_gs=%.1f angle=%.1f gs_diff=%.1f des_angle=%.1f\n",
665 target_gs, _gsDirect, gs_diff, des_angle); */
667 // estimate horizontal speed towards ILS in meters per minute
668 double elapsedDistance = last_x - gsDist;
671 double new_vel = ( elapsedDistance / dt );
672 horiz_vel = 0.99 * horiz_vel + 0.01 * new_vel;
673 /* printf("vel=%.1f (dist=%.1f dt=%.2f)\n", horiz_vel, elapsedDistance, dt);*/
675 gs_rate_of_climb_node
676 ->setDoubleValue( -sin( des_angle * SGD_DEGREES_TO_RADIANS )
677 * horiz_vel * SG_METER_TO_FEET );
678 gs_rate_of_climb_fpm_node
679 ->setDoubleValue( gs_rate_of_climb_node->getDoubleValue() * 60 );
682 void FGNavRadio::updateDME(const SGVec3d& aircraft)
684 if (!_dme || !dme_serviceable_node->getBoolValue()) {
689 double dme_distance = dist(aircraft, _dme->cart());
690 _dmeInRange = (dme_distance < _dme->get_range() * SG_NM_TO_METER);
693 void FGNavRadio::valueChanged (SGPropertyNode* prop)
695 if (prop == gps_course_node) {
696 if (!nav_slaved_to_gps_node->getBoolValue()) {
700 // GPS desired course has changed, sync up our selected-course
701 double v = prop->getDoubleValue();
702 if (v != sel_radial_node->getDoubleValue()) {
703 sel_radial_node->setDoubleValue(v);
705 } else if (prop == nav_slaved_to_gps_node) {
706 if (prop->getBoolValue()) {
707 // slaved-to-GPS activated, clear obsolete NAV outputs and sync up selected course
709 sel_radial_node->setDoubleValue(gps_course_node->getDoubleValue());
711 // slave-to-GPS enabled/disabled, resync NAV station (update all outputs)
713 _time_before_search_sec = 0;
717 void FGNavRadio::updateGPSSlaved()
719 has_gs_node->setBoolValue(gps_has_gs_node->getBoolValue());
721 _toFlag = gps_to_flag_node->getBoolValue();
722 _fromFlag = gps_from_flag_node->getBoolValue();
724 bool gpsValid = (_toFlag | _fromFlag);
725 inrange_node->setBoolValue(gpsValid);
727 signal_quality_norm_node->setDoubleValue(0.0);
728 _cdiDeflection = 0.0;
729 _cdiCrossTrackErrorM = 0.0;
730 _gsNeedleDeflection = 0.0;
731 _gsNeedleDeflectionNorm = 0.0;
735 // this is unfortunate, but panel instruments use this value to decide
736 // if the navradio output is valid.
737 signal_quality_norm_node->setDoubleValue(1.0);
739 _cdiDeflection = gps_cdi_deflection_node->getDoubleValue();
740 // clmap to some range (+/- 10 degrees) as the regular deflection
741 SG_CLAMP_RANGE(_cdiDeflection, -10.0, 10.0 );
743 _cdiCrossTrackErrorM = gps_xtrack_error_nm_node->getDoubleValue() * SG_NM_TO_METER;
744 _gsNeedleDeflection = 0.0; // FIXME, supply this
746 double trtrue = gps_course_node->getDoubleValue() + _magvarNode->getDoubleValue();
747 SG_NORMALIZE_RANGE(trtrue, 0.0, 360.0);
748 target_radial_true_node->setDoubleValue( trtrue );
751 void FGNavRadio::updateCDI(double dt)
753 bool cdi_serviceable = cdi_serviceable_node->getBoolValue();
754 bool inrange = inrange_node->getBoolValue();
756 if (tofrom_serviceable_node->getBoolValue()) {
757 to_flag_node->setBoolValue(_toFlag);
758 from_flag_node->setBoolValue(_fromFlag);
760 to_flag_node->setBoolValue(false);
761 from_flag_node->setBoolValue(false);
764 if (!cdi_serviceable) {
765 _cdiDeflection = 0.0;
766 _cdiCrossTrackErrorM = 0.0;
769 cdi_deflection_node->setDoubleValue(_cdiDeflection);
770 cdi_deflection_norm_node->setDoubleValue(_cdiDeflection * 0.1);
771 cdi_xtrack_error_node->setDoubleValue(_cdiCrossTrackErrorM);
773 //////////////////////////////////////////////////////////
774 // compute an approximate ground track heading error
775 //////////////////////////////////////////////////////////
776 double hdg_error = 0.0;
777 if ( inrange && cdi_serviceable ) {
778 double vn = fgGetDouble( "/velocities/speed-north-fps" );
779 double ve = fgGetDouble( "/velocities/speed-east-fps" );
780 double gnd_trk_true = atan2( ve, vn ) * SGD_RADIANS_TO_DEGREES;
781 if ( gnd_trk_true < 0.0 ) { gnd_trk_true += 360.0; }
783 SGPropertyNode *true_hdg
784 = fgGetNode("/orientation/heading-deg", true);
785 hdg_error = gnd_trk_true - true_hdg->getDoubleValue();
787 // cout << "ground track = " << gnd_trk_true
788 // << " orientation = " << true_hdg->getDoubleValue() << endl;
790 cdi_xtrack_hdg_err_node->setDoubleValue( hdg_error );
792 //////////////////////////////////////////////////////////
793 // Calculate a suggested target heading to smoothly intercept
795 //////////////////////////////////////////////////////////
797 // Now that we have cross track heading adjustment built in,
798 // we shouldn't need to overdrive the heading angle within 8km
801 // The cdi deflection should be +/-10 for a full range of deflection
802 // so multiplying this by 3 gives us +/- 30 degrees heading
804 double adjustment = _cdiDeflection * 3.0;
805 SG_CLAMP_RANGE( adjustment, -30.0, 30.0 );
807 // determine the target heading to fly to intercept the
808 // tgt_radial = target radial (true) + cdi offset adjustmest -
809 // xtrack heading error adjustment
811 double trtrue = target_radial_true_node->getDoubleValue();
812 if ( loc_node->getBoolValue() && backcourse_node->getBoolValue() ) {
813 // tuned to a localizer and backcourse mode activated
814 trtrue += 180.0; // reverse the target localizer heading
815 SG_NORMALIZE_RANGE(trtrue, 0.0, 360.0);
816 nta_hdg = trtrue - adjustment - hdg_error;
818 nta_hdg = trtrue + adjustment - hdg_error;
821 SG_NORMALIZE_RANGE(nta_hdg, 0.0, 360.0);
822 target_auto_hdg_node->setDoubleValue( nta_hdg );
824 //////////////////////////////////////////////////////////
825 // compute the time to intercept selected radial (based on
826 // current and last cross track errors and dt)
827 //////////////////////////////////////////////////////////
829 if ( inrange && cdi_serviceable ) {
830 double cur_rate = (last_xtrack_error - _cdiCrossTrackErrorM) / dt;
831 xrate_ms = 0.99 * xrate_ms + 0.01 * cur_rate;
832 if ( fabs(xrate_ms) > 0.00001 ) {
833 t = _cdiCrossTrackErrorM / xrate_ms;
838 time_to_intercept->setDoubleValue( t );
840 if (!gs_serviceable_node->getBoolValue() ) {
841 _gsNeedleDeflection = 0.0;
842 _gsNeedleDeflectionNorm = 0.0;
844 gs_deflection_node->setDoubleValue(_gsNeedleDeflection);
845 gs_deflection_deg_node->setDoubleValue(_gsNeedleDeflectionNorm * 0.7);
846 gs_deflection_norm_node->setDoubleValue(_gsNeedleDeflectionNorm);
847 gs_direct_node->setDoubleValue(_gsDirect);
849 last_xtrack_error = _cdiCrossTrackErrorM;
852 void FGNavRadio::updateAudio()
854 if (!_navaid || !inrange_node->getBoolValue() || !nav_serviceable_node->getBoolValue()) {
858 // play station ident via audio system if on + ident,
859 // otherwise turn it off
860 if (!power_btn_node->getBoolValue()
861 || !(bus_power_node->getDoubleValue() > 1.0)
862 || !ident_btn_node->getBoolValue()
863 || !audio_btn_node->getBoolValue() ) {
864 _sgr->stop( nav_fx_name );
865 _sgr->stop( dme_fx_name );
869 SGSoundSample *sound = _sgr->find( nav_fx_name );
870 double vol = vol_btn_node->getFloatValue();
871 SG_CLAMP_RANGE(vol, 0.0, 1.0);
873 if ( sound != NULL ) {
874 sound->set_volume( vol );
876 SG_LOG( SG_COCKPIT, SG_ALERT, "Can't find nav-vor-ident sound" );
879 sound = _sgr->find( dme_fx_name );
880 if ( sound != NULL ) {
881 sound->set_volume( vol );
883 SG_LOG( SG_COCKPIT, SG_ALERT, "Can't find nav-dme-ident sound" );
886 const int NUM_IDENT_SLOTS = 5;
887 const time_t SLOT_LENGTH = 5; // seconds
889 // There are N slots numbered 0 through (NUM_IDENT_SLOTS-1) inclusive.
890 // Each slot is 5 seconds long.
891 // Slots 0 is for DME
892 // the rest are for azimuth.
893 time_t now = globals->get_time_params()->get_cur_time();
894 if ((now >= last_time) && (now < last_time + SLOT_LENGTH)) {
895 return; // wait longer
900 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 = FGMorse::instance()->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 = FGMorse::instance()->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());