1 // tcas.cxx -- Traffic Alert and Collision Avoidance System (TCAS) Emulation
3 // Written by Thorsten Brehm, started December 2010.
5 // Copyright (C) 2010 Thorsten Brehm - brehmt (at) gmail com
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 St, Fifth Floor, Boston, MA 02110-1301, USA.
21 ///////////////////////////////////////////////////////////////////////////////
25 * [TCASII] Introduction to TCAS II Version 7, Federal Aviation Administration, November 2000
26 * http://www.arinc.com/downloads/tcas/tcas.pdf
28 * [EUROACAS] Eurocontrol Airborne Collision Avoidance System (ACAS),
29 * http://www.eurocontrol.int/msa/public/standard_page/ACAS_Startpage.html
33 * ALIM: Altitude Limit
35 * CPA: Closest point of approach as computed from a threat's range and range rate.
37 * DMOD: Distance MODification
39 * Intruder: A target that has satisfied the traffic detection criteria.
41 * Proximity target: Any target that is less than 6 nmi in range and within +/-1200ft
42 * vertically, but that does not meet the intruder or threat criteria.
44 * RA: Resolution advisory. An indication given by TCAS II to a flight crew that a
45 * vertical maneuver should, or in some cases should not, be performed to attain or
46 * maintain safe separation from a threat.
48 * SL: Sensitivity Level. A value used in defining the size of the protected volume
49 * around the own aircraft.
51 * TA: Traffic Advisory. An indication given by TCAS to the pilot when an aircraft has
52 * entered, or is projected to enter, the protected volume around the own aircraft.
54 * Tau: Approximation of the time, in seconds, to CPA or to the aircraft being at the
57 * TCAS: Traffic alert and Collision Avoidance System
62 * serviceable enable/disable TCAS processing
64 * voice/file-prefix path (and optional prefix) for sound sample files
65 * (only evaluated at start-up)
67 * inputs/mode TCAS mode selection: 0=off,1=standby,2=TA only,3=auto(TA/RA)
68 * inputs/self-test trigger self-test sequence
70 * outputs/traffic-alert intruder detected (true=TA-threat is active, includes RA-threats)
71 * outputs/advisory-alert resolution advisory is issued (true=advisory is valid)
72 * outputs/vertical-speed vertical speed required by advisory (+/-2000/1500/500/0)
74 * speaker/max-dist Max. distance where speaker is heard
75 * speaker/reference-dist Distance to pilot
76 * speaker/volume Volume at reference distance
78 * debug/threat-trigger trigger debugging test (in debug mode only)
79 * debug/threat-RA debugging RA value (in debug mode only)
80 * debug/threat-level debugging threat level (in debug mode only)
84 # pragma warning( disable: 4355 )
99 #include <simgear/constants.h>
100 #include <simgear/sg_inlines.h>
101 #include <simgear/debug/logstream.hxx>
102 #include <simgear/math/sg_geodesy.hxx>
103 #include <simgear/sound/soundmgr_openal.hxx>
104 #include <simgear/structure/exception.hxx>
108 #if defined( HAVE_VERSION_H ) && HAVE_VERSION_H
109 # include <Include/version.h>
111 # include <Include/no_version.h>
114 #include <Main/fg_props.hxx>
115 #include <Main/globals.hxx>
116 #include "instrument_mgr.hxx"
119 ///////////////////////////////////////////////////////////////////////////////
120 // debug switches /////////////////////////////////////////////////////////////
121 ///////////////////////////////////////////////////////////////////////////////
122 //#define FEATURE_TCAS_DEBUG_ANNUNCIATOR
123 //#define FEATURE_TCAS_DEBUG_COORDINATOR
124 //#define FEATURE_TCAS_DEBUG_THREAT_DETECTOR
125 //#define FEATURE_TCAS_DEBUG_TRACKER
126 //#define FEATURE_TCAS_DEBUG_ADV_GENERATOR
127 //#define FEATURE_TCAS_DEBUG_PROPERTIES
129 ///////////////////////////////////////////////////////////////////////////////
130 // constants //////////////////////////////////////////////////////////////////
131 ///////////////////////////////////////////////////////////////////////////////
133 /** Sensitivity Level Definition and Alarm Thresholds (TCASII, Version 7)
134 * Max Own | |TA-level |RA-level
135 * Altitude(ft) | SL |Tau(s),DMOD(nm),ALIM(ft)|Tau(s),DMOD(nm),ALIM(ft) */
136 const TCAS::SensitivityLevel
137 TCAS::ThreatDetector::sensitivityLevels[] = {
138 { 1000, 2, {20, 0.30, 850}, {0, 0, 0 }},
139 { 2350, 3, {25, 0.33, 850}, {15, 0.20, 300}},
140 { 5000, 4, {30, 0.48, 850}, {20, 0.35, 300}},
141 {10000, 5, {40, 0.75, 850}, {25, 0.55, 350}},
142 {20000, 6, {45, 1.00, 850}, {30, 0.80, 400}},
143 {42000, 7, {48, 1.30, 850}, {35, 1.10, 600}},
144 {0, 8, {48, 1.30, 1200}, {35, 1.10, 700}}
147 ///////////////////////////////////////////////////////////////////////////////
148 // helpers ////////////////////////////////////////////////////////////////////
149 ///////////////////////////////////////////////////////////////////////////////
151 #define ADD_VOICE(Var, Sample, SayTwice) \
152 { make_voice(&Var); \
153 append(Var, Sample); \
154 if (SayTwice) append(Var, Sample); }
156 #define AVAILABLE_RA(Options, Advisory) (Advisory == (Advisory & Options))
158 #ifdef FEATURE_TCAS_DEBUG_THREAT_DETECTOR
159 /** calculate relative angle in between two headings */
161 relAngle(float Heading1, float Heading2)
163 Heading1 -= Heading2;
165 while (Heading1 >= 360.0)
168 while (Heading1 < 0.0)
175 /** calculate range and bearing of lat2/lon2 relative to lat1/lon1 */
177 calcRangeBearing(double lat1, double lon1, double lat2, double lon2,
178 double &rangeNm, double &bearing)
180 // calculate the bearing and range of the second pos from the first
181 double az2, distanceM;
182 geo_inverse_wgs_84(lat1, lon1, lat2, lon2, &bearing, &az2, &distanceM);
183 rangeNm = distanceM * SG_METER_TO_NM;
186 ///////////////////////////////////////////////////////////////////////////////
187 // VoicePlayer ////////////////////////////////////////////////////////////////
188 ///////////////////////////////////////////////////////////////////////////////
191 TCAS::VoicePlayer::init(void)
193 FGVoicePlayer::init();
195 ADD_VOICE(Voices.pTrafficTraffic, "traffic", true);
196 ADD_VOICE(Voices.pClear, "clear", false);
197 ADD_VOICE(Voices.pClimb, "climb", true);
198 ADD_VOICE(Voices.pClimbNow, "climb_now", true);
199 ADD_VOICE(Voices.pClimbCrossing, "climb_crossing", true);
200 ADD_VOICE(Voices.pClimbIncrease, "increase_climb", false);
201 ADD_VOICE(Voices.pDescend, "descend", true);
202 ADD_VOICE(Voices.pDescendNow, "descend_now", true);
203 ADD_VOICE(Voices.pDescendCrossing,"descend_crossing", true);
204 ADD_VOICE(Voices.pDescendIncrease,"increase_descent", false);
205 ADD_VOICE(Voices.pAdjustVSpeed, "adjust_vertical_speed", false);
206 ADD_VOICE(Voices.pMaintVSpeed, "maintain_vertical_speed", false);
207 ADD_VOICE(Voices.pMonitorVSpeed, "monitor_vertical_speed", false);
208 ADD_VOICE(Voices.pLevelOff, "level_off", false);
209 ADD_VOICE(Voices.pTestOk, "test_ok", false);
210 ADD_VOICE(Voices.pTestFail, "test_fail", false);
212 speaker.update_configuration();
215 /////////////////////////////////////////////////////////////////////////////
216 // TCAS::Annunciator ////////////////////////////////////////////////////////
217 /////////////////////////////////////////////////////////////////////////////
219 TCAS::Annunciator::Annunciator(TCAS* _tcas) :
227 void TCAS::Annunciator::clear(void)
229 previous.threatLevel = ThreatNone;
230 previous.RA = AdvisoryClear;
231 previous.RAOption = OptionNone;
236 TCAS::Annunciator::bind(SGPropertyNode* node)
238 voicePlayer.bind(node, "Sounds/tcas/female/");
242 TCAS::Annunciator::init(void)
244 //TODO link to GPWS module/audio-on signal must be configurable
245 nodeGpwsAlertOn = fgGetNode("/instrumentation/mk-viii/outputs/discretes/audio-on", true);
250 TCAS::Annunciator::update(void)
252 voicePlayer.update();
254 /* [TCASII]: "The priority scheme gives ground proximity warning systems (GPWS)
255 * a higher annunciation priority than a TCAS alert. TCAS aural annunciation will
256 * be inhibited during the time that a GPWS alert is active." */
257 if (nodeGpwsAlertOn->getBoolValue())
260 voicePlayer.resume();
263 /** Trigger voice sample for current alert. */
265 TCAS::Annunciator::trigger(const ResolutionAdvisory& current, bool revertedRA)
268 int RAOption = current.RAOption;
270 if (RA == AdvisoryClear)
272 if (previous.RA != AdvisoryClear)
274 voicePlayer.play(voicePlayer.Voices.pClear, VoicePlayer::PLAY_NOW);
281 if ((previous.RA == AdvisoryClear)||
282 (tcas->tracker.newTraffic()))
284 voicePlayer.play(voicePlayer.Voices.pTrafficTraffic, VoicePlayer::PLAY_NOW);
288 VoicePlayer::Voice* pVoice = NULL;
293 pVoice = voicePlayer.Voices.pClimbNow;
295 if (AVAILABLE_RA(RAOption, OptionIncreaseClimb))
296 pVoice = voicePlayer.Voices.pClimbIncrease;
298 if (AVAILABLE_RA(RAOption, OptionCrossingClimb))
299 pVoice = voicePlayer.Voices.pClimbCrossing;
301 pVoice = voicePlayer.Voices.pClimb;
304 case AdvisoryDescend:
306 pVoice = voicePlayer.Voices.pDescendNow;
308 if (AVAILABLE_RA(RAOption, OptionIncreaseDescend))
309 pVoice = voicePlayer.Voices.pDescendIncrease;
311 if (AVAILABLE_RA(RAOption, OptionCrossingDescent))
312 pVoice = voicePlayer.Voices.pDescendCrossing;
314 pVoice = voicePlayer.Voices.pDescend;
317 case AdvisoryAdjustVSpeed:
318 pVoice = voicePlayer.Voices.pAdjustVSpeed;
321 case AdvisoryMaintVSpeed:
322 pVoice = voicePlayer.Voices.pMaintVSpeed;
325 case AdvisoryMonitorVSpeed:
326 pVoice = voicePlayer.Voices.pMonitorVSpeed;
329 case AdvisoryLevelOff:
330 pVoice = voicePlayer.Voices.pLevelOff;
333 case AdvisoryIntrusion:
337 RA = AdvisoryIntrusion;
343 if ((pLastVoice == pVoice)&&
344 (!tcas->tracker.newTraffic()))
346 // don't repeat annunciation
351 voicePlayer.play(pVoice);
353 #ifdef FEATURE_TCAS_DEBUG_ANNUNCIATOR
354 cout << "Annunciating TCAS RA " << RA << endl;
359 TCAS::Annunciator::test(bool testOk)
362 voicePlayer.play(voicePlayer.Voices.pTestOk);
364 voicePlayer.play(voicePlayer.Voices.pTestFail);
367 /////////////////////////////////////////////////////////////////////////////
368 // TCAS::AdvisoryCoordinator ////////////////////////////////////////////////
369 /////////////////////////////////////////////////////////////////////////////
371 TCAS::AdvisoryCoordinator::AdvisoryCoordinator(TCAS* _tcas) :
379 TCAS::AdvisoryCoordinator::init(void)
385 TCAS::AdvisoryCoordinator::reinit(void)
392 TCAS::AdvisoryCoordinator::bind(SGPropertyNode* node)
394 nodeTAWarning = node->getNode("outputs/traffic-alert", true);
395 nodeTAWarning->setBoolValue(false);
399 TCAS::AdvisoryCoordinator::clear(void)
401 current.threatLevel = ThreatNone;
402 current.RA = AdvisoryClear;
403 current.RAOption = OptionNone;
406 /** Add all suitable resolution advisories for a single threat. */
408 TCAS::AdvisoryCoordinator::add(const ResolutionAdvisory& newAdvisory)
410 if ((newAdvisory.RA == AdvisoryClear)||
411 (newAdvisory.threatLevel < current.threatLevel))
414 if (current.threatLevel == newAdvisory.threatLevel)
416 // combine with other advisories so far
417 current.RA &= newAdvisory.RA;
418 // remember any advisory modifier
419 current.RAOption |= newAdvisory.RAOption;
423 current = newAdvisory;
427 /** Pick and trigger suitable resolution advisory. */
429 TCAS::AdvisoryCoordinator::update(int mode)
431 bool revertedRA = false; // has advisory changed?
432 double currentTime = globals->get_sim_time_sec();
434 if (current.RA == AdvisoryClear)
436 // filter: wait 5 seconds after last TA/RA before announcing TA clearance
437 if ((previous.RA != AdvisoryClear)&&
438 (currentTime - lastTATime < 5.0))
445 #ifdef FEATURE_TCAS_DEBUG_COORDINATOR
446 cout << "TCAS::Annunciator::update: previous: " << previous.RA << ", new: " << current.RA << endl;
449 lastTATime = currentTime;
450 if ((previous.RA == AdvisoryClear)||
451 (previous.RA == AdvisoryIntrusion)||
452 ((current.RA & previous.RA) != previous.RA))
454 // no RA yet, or we can't keep previous RA: pick one - in order of priority
456 if (AVAILABLE_RA(current.RA, AdvisoryMonitorVSpeed))
458 // prio 1: monitor vertical speed only
459 current.RA = AdvisoryMonitorVSpeed;
462 if (AVAILABLE_RA(current.RA, AdvisoryMaintVSpeed))
464 // prio 2: maintain vertical speed
465 current.RA = AdvisoryMaintVSpeed;
468 if (AVAILABLE_RA(current.RA, AdvisoryAdjustVSpeed))
470 // prio 3: adjust vertical speed (TCAS II 7.0 only)
471 current.RA = AdvisoryAdjustVSpeed;
474 if (AVAILABLE_RA(current.RA, AdvisoryLevelOff))
476 // prio 3: adjust vertical speed (TCAS II 7.1 only, [EUROACAS]: CP115)
477 current.RA = AdvisoryLevelOff;
480 if (AVAILABLE_RA(current.RA, AdvisoryClimb))
483 current.RA = AdvisoryClimb;
486 if (AVAILABLE_RA(current.RA, AdvisoryDescend))
489 current.RA = AdvisoryDescend;
493 // no RA, issue a TA only
494 current.RA = AdvisoryIntrusion;
497 // check if earlier advisory was reverted
498 revertedRA = ((previous.RA != current.RA)&&
500 (previous.RA != AdvisoryIntrusion));
505 current.RA = previous.RA;
509 /* [TCASII]: "Aural annunciations are inhibited below 500+/-100 feet AGL." */
510 if ((tcas->threatDetector.getRadarAlt() > 500)&&
511 (mode >= SwitchTaOnly))
512 tcas->annunciator.trigger(current, revertedRA);
514 if (current.RA == AdvisoryClear)
516 /* explicitly clear traffic alert (since aural annunciation disabled) */
517 tcas->annunciator.clear();
522 /* [TCASII] "[..] also performs the function of setting flags that control the displays.
523 * The traffic display, the RA display, [..] use these flags to alert the pilot to
524 * the presence of TAs and RAs." */
525 nodeTAWarning->setBoolValue(current.RA != AdvisoryClear);
528 ///////////////////////////////////////////////////////////////////////////////
529 // TCAS::ThreatDetector ///////////////////////////////////////////////////////
530 ///////////////////////////////////////////////////////////////////////////////
532 TCAS::ThreatDetector::ThreatDetector(TCAS* _tcas) :
535 pAlarmThresholds(&sensitivityLevels[0])
537 self.radarAltFt = 0.0;
542 TCAS::ThreatDetector::init(void)
544 nodeLat = fgGetNode("/position/latitude-deg", true);
545 nodeLon = fgGetNode("/position/longitude-deg", true);
546 nodePressureAlt = fgGetNode("/position/altitude-ft", true);
547 nodeRadarAlt = fgGetNode("/position/altitude-agl-ft", true);
548 nodeHeading = fgGetNode("/orientation/heading-deg", true);
549 nodeVelocity = fgGetNode("/velocities/airspeed-kt", true);
550 nodeVerticalFps = fgGetNode("/velocities/vertical-speed-fps", true);
552 tcas->advisoryGenerator.init(&self,¤tThreat);
555 /** Update local position and threat sensitivity levels. */
557 TCAS::ThreatDetector::update(void)
559 // update local position
560 self.lat = nodeLat->getDoubleValue();
561 self.lon = nodeLon->getDoubleValue();
562 self.pressureAltFt = nodePressureAlt->getDoubleValue();
563 self.heading = nodeHeading->getDoubleValue();
564 self.velocityKt = nodeVelocity->getDoubleValue();
565 self.verticalFps = nodeVerticalFps->getDoubleValue();
567 /* radar altimeter provides a lot of spikes due to uneven terrain
568 * MK-VIII GPWS-spec requires smoothing the radar altitude with a
569 * 10second moving average. Likely the TCAS spec requires the same.
570 * => We use a cheap 10 second exponential average method.
572 const double SmoothingFactor = 0.3;
573 self.radarAltFt = nodeRadarAlt->getDoubleValue()*SmoothingFactor +
574 (1-SmoothingFactor)*self.radarAltFt;
576 #ifdef FEATURE_TCAS_DEBUG_THREAT_DETECTOR
577 printf("TCAS::ThreatDetector::update: radarAlt = %f\n",self.radarAltFt);
581 // determine current altitude's "Sensitivity Level Definition and Alarm Thresholds"
583 for (sl=0;((self.radarAltFt > sensitivityLevels[sl].maxAltitude)&&
584 (sensitivityLevels[sl].maxAltitude));sl++);
585 pAlarmThresholds = &sensitivityLevels[sl];
586 tcas->advisoryGenerator.setAlarmThresholds(pAlarmThresholds);
589 /** Check if plane's transponder is enabled. */
591 TCAS::ThreatDetector::checkTransponder(const SGPropertyNode* pModel, float velocityKt)
593 const string name = pModel->getName();
594 if (name != "multiplayer" && name != "aircraft")
596 // assume non-MP/non-AI planes (e.g. ships) have no transponder
602 /* assume all pilots have their transponder switched off while taxiing/parking
607 if ((name == "multiplayer")&&
608 (pModel->getBoolValue("controls/invisible")))
610 // ignored MP plane: pretend transponder is switched off
617 /** Check if plane is a threat. */
619 TCAS::ThreatDetector::checkThreat(int mode, const SGPropertyNode* pModel)
621 #ifdef FEATURE_TCAS_DEBUG_THREAT_DETECTOR
625 float velocityKt = pModel->getDoubleValue("velocities/true-airspeed-kt");
627 if (!checkTransponder(pModel, velocityKt))
628 return ThreatInvisible;
630 int threatLevel = ThreatNone;
631 float altFt = pModel->getDoubleValue("position/altitude-ft");
632 currentThreat.relativeAltitudeFt = altFt - self.pressureAltFt;
634 // save computation time: don't care when relative altitude is excessive
635 if (fabs(currentThreat.relativeAltitudeFt) > 10000)
638 // position data of current intruder
639 double lat = pModel->getDoubleValue("position/latitude-deg");
640 double lon = pModel->getDoubleValue("position/longitude-deg");
641 float heading = pModel->getDoubleValue("orientation/true-heading-deg");
643 double distanceNm, bearing;
644 calcRangeBearing(self.lat, self.lon, lat, lon, distanceNm, bearing);
646 // save computation time: don't care for excessive distances (also captures NaNs...)
647 if ((distanceNm > 10)||(distanceNm < 0))
650 currentThreat.verticalFps = pModel->getDoubleValue("velocities/vertical-speed-fps");
652 /* Detect proximity targets
653 * [TCASII]: "Any target that is less than 6 nmi in range and within +/-1200ft
654 * vertically, but that does not meet the intruder or threat criteria." */
655 if ((distanceNm < 6)&&
656 (fabs(currentThreat.relativeAltitudeFt) < 1200))
658 // at least a proximity target
659 threatLevel = ThreatProximity;
662 /* do not detect any threats when in standby or on ground and taxiing */
663 if ((mode <= SwitchStandby)||
664 ((self.radarAltFt < 360)&&(self.velocityKt < 40)))
669 if (tcas->tracker.active())
671 currentThreat.callsign = pModel->getStringValue("callsign");
672 currentThreat.isTracked = tcas->tracker.isTracked(currentThreat.callsign);
675 currentThreat.isTracked = false;
677 // first stage: vertical movement
678 checkVerticalThreat();
680 // stop processing when no vertical threat
681 if ((!currentThreat.verticalTA)&&
682 (!currentThreat.isTracked))
685 // second stage: horizontal movement
686 horizontalThreat(bearing, distanceNm, heading, velocityKt);
688 if (!currentThreat.isTracked)
690 // no horizontal threat?
691 if (!currentThreat.horizontalTA)
694 if ((currentThreat.horizontalTau < 0)||
695 (currentThreat.verticalTau < 0))
697 // do not trigger new alerts when Tau is negative, but keep existing alerts
698 int previousThreatLevel = pModel->getIntValue("tcas/threat-level", 0);
699 if (previousThreatLevel == 0)
704 #ifdef FEATURE_TCAS_DEBUG_THREAT_DETECTOR
705 cout << "#" << checkCount << ": " << pModel->getStringValue("callsign") << endl;
709 /* [TCASII]: "For either a TA or an RA to be issued, both the range and
710 * vertical criteria, in terms of tau or the fixed thresholds, must be
711 * satisfied only one of the criteria is satisfied, TCAS will not issue
713 if (currentThreat.horizontalTA && currentThreat.verticalTA)
714 threatLevel = ThreatTA;
715 if (currentThreat.horizontalRA && currentThreat.verticalRA)
716 threatLevel = ThreatRA;
718 if (!tcas->tracker.active())
719 currentThreat.callsign = pModel->getStringValue("callsign");
721 tcas->tracker.add(currentThreat.callsign, threatLevel);
723 // check existing threat level
724 if (currentThreat.isTracked)
726 int oldLevel = tcas->tracker.getThreatLevel(currentThreat.callsign);
727 if (oldLevel > threatLevel)
728 threatLevel = oldLevel;
731 // find all resolution options for this conflict
732 threatLevel = tcas->advisoryGenerator.resolution(mode, threatLevel, distanceNm, altFt, heading, velocityKt);
735 #ifdef FEATURE_TCAS_DEBUG_THREAT_DETECTOR
736 printf(" threat: distance: %4.1f, bearing: %4.1f, alt: %5.1f, velocity: %4.1f, heading: %4.1f, vspeed: %4.1f, "
737 "own alt: %5.1f, own heading: %4.1f, own velocity: %4.1f, vertical tau: %3.2f"
738 //", closing speed: %f"
740 distanceNm, relAngle(bearing, self.heading), altFt, velocityKt, heading, currentThreat.verticalFps,
741 self.altFt, self.heading, self.velocityKt
742 //, currentThreat.closingSpeedKt
743 ,currentThreat.verticalTau
750 /** Check if plane is a vertical threat. */
752 TCAS::ThreatDetector::checkVerticalThreat(void)
754 // calculate relative vertical speed and altitude
755 float dV = self.verticalFps - currentThreat.verticalFps;
756 float dA = currentThreat.relativeAltitudeFt;
758 currentThreat.verticalTA = false;
759 currentThreat.verticalRA = false;
760 currentThreat.verticalTau = 0;
762 /* [TCASII]: "The vertical tau is equal to the altitude separation (feet)
763 * divided by the combined vertical speed of the two aircraft (feet/minute)
769 /* [TCASII]: "When the combined vertical speed of the TCAS and the intruder aircraft
770 * is low, TCAS will use a fixed-altitude threshold to determine whether a TA or
771 * an RA should be issued." */
772 if ((fabs(dV) < 3.0)||
773 ((tau < 0) && (tau > -5)))
775 /* vertical closing speed is low (below 180fpm/3fps), check
776 * fixed altitude range. */
777 float abs_dA = fabs(dA);
778 if (abs_dA < pAlarmThresholds->RA.ALIM)
780 // continuous intrusion at RA-level
781 currentThreat.verticalTA = true;
782 currentThreat.verticalRA = true;
785 if (abs_dA < pAlarmThresholds->TA.ALIM)
787 // continuous intrusion: with TA-level, but no RA-threat
788 currentThreat.verticalTA = true;
790 // else: no RA/TA threat
794 if ((tau < pAlarmThresholds->TA.Tau)&&
797 currentThreat.verticalTA = true;
798 currentThreat.verticalRA = (tau < pAlarmThresholds->RA.Tau);
801 currentThreat.verticalTau = tau;
803 #ifdef FEATURE_TCAS_DEBUG_THREAT_DETECTOR
804 if (currentThreat.verticalTA)
805 printf(" vertical dV=%f (%f-%f), dA=%f\n", dV, self.verticalFps, currentThreat.verticalFps, dA);
809 /** Check if plane is a horizontal threat. */
811 TCAS::ThreatDetector::horizontalThreat(float bearing, float distanceNm, float heading, float velocityKt)
814 float vxKt = sin(heading*SGD_DEGREES_TO_RADIANS)*velocityKt - sin(self.heading*SGD_DEGREES_TO_RADIANS)*self.velocityKt;
815 float vyKt = cos(heading*SGD_DEGREES_TO_RADIANS)*velocityKt - cos(self.heading*SGD_DEGREES_TO_RADIANS)*self.velocityKt;
817 // calculate horizontal closing speed
818 float closingSpeedKt2 = vxKt*vxKt+vyKt*vyKt;
819 float closingSpeedKt = sqrt(closingSpeedKt2);
821 /* [TCASII]: "The range tau is equal to the slant range (nmi) divided by the closing speed
822 * (knots) multiplied by 3600."
823 * => calculate allowed slant range (nmi) based on known maximum tau */
824 float TA_rangeNm = (pAlarmThresholds->TA.Tau*closingSpeedKt)/3600;
825 float RA_rangeNm = (pAlarmThresholds->RA.Tau*closingSpeedKt)/3600;
827 if (closingSpeedKt < 100)
829 /* [TCASII]: "In events where the rate of closure is very low, [..]
830 * an intruder aircraft can come very close in range without crossing the
831 * range tau boundaries [..]. To provide protection in these types of
832 * advisories, the range tau boundaries are modified [..] to use
833 * a fixed-range threshold to issue TAs and RAs in these slow closure
835 TA_rangeNm += (100.0-closingSpeedKt)*(pAlarmThresholds->TA.DMOD/100.0);
836 RA_rangeNm += (100.0-closingSpeedKt)*(pAlarmThresholds->RA.DMOD/100.0);
838 if (TA_rangeNm < pAlarmThresholds->TA.DMOD)
839 TA_rangeNm = pAlarmThresholds->TA.DMOD;
840 if (RA_rangeNm < pAlarmThresholds->RA.DMOD)
841 RA_rangeNm = pAlarmThresholds->RA.DMOD;
843 currentThreat.horizontalTA = (distanceNm < TA_rangeNm);
844 currentThreat.horizontalRA = (distanceNm < RA_rangeNm);
845 currentThreat.horizontalTau = -1;
847 if ((currentThreat.horizontalRA)&&
848 (currentThreat.verticalRA))
850 /* an RA will be issued. Prepare extra data for the
851 * traffic resolution stage, i.e. calculate
852 * exact time tau to horizontal CPA.
855 /* relative position of intruder is
858 * horizontal distance to intruder is r(t)
859 * r(t) = sqrt( Sx(t)^2 + Sy(t)^2 )
860 * => horizontal CPA at time t=tau, where r(t) has minimum
861 * r2(t) := r^2(t) = Sx(t)^2 + Sy(t)^2
862 * since r(t)>0 for all t => minimum of r(t) is also minimum of r2(t)
863 * => (d/dt) r2(t) = r2'(t) is 0 for t=tau
864 * r2(t) = ((Sx(t)^2 + Sy(t))^2) = c + b*t + a*t^2
865 * => r2'(t) = b + a*2*t
867 * r2'(tau) = 0 = b + 2*a*tau
870 float sx = sin(bearing*SGD_DEGREES_TO_RADIANS)*distanceNm;
871 float sy = cos(bearing*SGD_DEGREES_TO_RADIANS)*distanceNm;
872 float vx = vxKt * (SG_KT_TO_MPS*SG_METER_TO_NM);
873 float vy = vyKt * (SG_KT_TO_MPS*SG_METER_TO_NM);
874 float a = vx*vx + vy*vy;
875 float b = 2*(sx*vx + sy*vy);
879 #ifdef FEATURE_TCAS_DEBUG_THREAT_DETECTOR
880 printf(" Time to horizontal CPA: %4.2f\n",tau);
882 if (tau > pAlarmThresholds->RA.Tau)
883 tau = pAlarmThresholds->RA.Tau;
885 // remember time to horizontal CPA
886 currentThreat.horizontalTau = tau;
890 /** Test threat detection logic. */
892 TCAS::ThreatDetector::unitTest(void)
894 pAlarmThresholds = &sensitivityLevels[1];
897 self.verticalFps = 0;
899 cout << "identical altitude and vspeed " << endl;
900 checkVerticalThreat(self.altFt, self.verticalFps);
901 cout << "1000ft alt offset, dV=100 " << endl;
902 checkVerticalThreat(self.altFt+1000, 100);
903 cout << "-1000ft alt offset, dV=100 " << endl;
904 checkVerticalThreat(self.altFt-1000, 100);
905 cout << "3000ft alt offset, dV=10 " << endl;
906 checkVerticalThreat(self.altFt+3000, 10);
907 cout << "500ft alt offset, dV=100 " << endl;
908 checkVerticalThreat(self.altFt+500, 100);
909 cout << "500ft alt offset, dV=-100 " << endl;
910 checkVerticalThreat(self.altFt+500, -100);
915 cout << "10nm behind, overtaking with 1Nm/s" << endl;
916 horizontalThreat(-180, 10, 0, 1/(SG_KT_TO_MPS*SG_METER_TO_NM));
918 cout << "10nm ahead, departing with 1Nm/s" << endl;
919 horizontalThreat(0, 20, 0, 1/(SG_KT_TO_MPS*SG_METER_TO_NM));
922 self.velocityKt = 1/(SG_KT_TO_MPS*SG_METER_TO_NM);
923 cout << "10nm behind, overtaking with 1Nm/s at 90 degrees" << endl;
924 horizontalThreat(-90, 20, 90, 2/(SG_KT_TO_MPS*SG_METER_TO_NM));
927 self.velocityKt = 1/(SG_KT_TO_MPS*SG_METER_TO_NM);
928 cout << "10nm behind, overtaking with 1Nm/s at 20 degrees" << endl;
929 horizontalThreat(200, 20, 20, 2/(SG_KT_TO_MPS*SG_METER_TO_NM));
933 ///////////////////////////////////////////////////////////////////////////////
934 // TCAS::AdvisoryGenerator ////////////////////////////////////////////////////
935 ///////////////////////////////////////////////////////////////////////////////
937 TCAS::AdvisoryGenerator::AdvisoryGenerator(TCAS* _tcas) :
940 pCurrentThreat(NULL),
941 pAlarmThresholds(NULL)
946 TCAS::AdvisoryGenerator::init(const LocalInfo* _pSelf, ThreatInfo* _pCurrentThreat)
948 pCurrentThreat = _pCurrentThreat;
953 TCAS::AdvisoryGenerator::setAlarmThresholds(const SensitivityLevel* _pAlarmThresholds)
955 pAlarmThresholds = _pAlarmThresholds;
958 /** Calculate projected vertical separation at horizontal CPA. */
960 TCAS::AdvisoryGenerator::verticalSeparation(float newVerticalFps)
962 // calculate relative vertical speed and altitude
963 float dV = pCurrentThreat->verticalFps - newVerticalFps;
964 float tau = pCurrentThreat->horizontalTau;
965 // don't use negative tau to project future separation...
968 return pCurrentThreat->relativeAltitudeFt + tau * dV;
971 /** Determine RA sense. */
973 TCAS::AdvisoryGenerator::determineRAsense(int& RASense, bool& isCrossing)
975 /* [TCASII]: "[..] a two step process is used to select the appropriate RA for the encounter
976 * geometry. The first step in the process is to select the RA sense, i.e., upward or downward." */
980 /* [TCASII]: "Based on the range and altitude tracks of the intruder, the CAS logic models the
981 * intruder's flight path from its present position to CPA. The CAS logic then models upward
982 * and downward sense RAs for own aircraft [..] to determine which sense provides the most
983 * vertical separation at CPA." */
984 float upSenseRelAltFt = verticalSeparation(+2000/60.0);
985 float downSenseRelAltFt = verticalSeparation(-2000/60.0);
986 if (fabs(upSenseRelAltFt) >= fabs(downSenseRelAltFt))
987 RASense = +1; // upward
989 RASense = -1; // downward
991 /* [TCASII]: "In encounters where either of the senses results in the TCAS aircraft crossing through
992 * the intruder's altitude, TCAS is designed to select the nonaltitude crossing sense if the
993 * noncrossing sense provides the desired vertical separation, known as ALIM, at CPA." */
994 /* [TCASII]: "If ALIM cannot be obtained in the nonaltitude crossing sense, an altitude
995 * crossing RA will be issued." */
997 (pCurrentThreat->relativeAltitudeFt > 200))
999 // threat is above and RA is crossing
1000 if (fabs(downSenseRelAltFt) > pAlarmThresholds->TA.ALIM)
1002 // non-crossing descend is sufficient
1007 // keep crossing climb RA
1013 (pCurrentThreat->relativeAltitudeFt < -200))
1015 // threat is below and RA is crossing
1016 if (fabs(upSenseRelAltFt) > pAlarmThresholds->TA.ALIM)
1018 // non-crossing climb is sufficient
1023 // keep crossing descent RA
1027 // else: threat is at same altitude, keep optimal RA sense (non-crossing)
1029 pCurrentThreat->RASense = RASense;
1031 #ifdef FEATURE_TCAS_DEBUG_ADV_GENERATOR
1032 printf(" RASense: %i, crossing: %u, relAlt: %4.1f, upward separation: %4.1f, downward separation: %4.1f\n",
1034 pCurrentThreat->relativeAltitudeFt,
1035 upSenseRelAltFt,downSenseRelAltFt);
1039 /** Determine suitable resolution advisories. */
1041 TCAS::AdvisoryGenerator::resolution(int mode, int threatLevel, float rangeNm, float altFt,
1042 float heading, float velocityKt)
1044 int RAOption = OptionNone;
1045 int RA = AdvisoryIntrusion;
1047 // RAs are disabled under certain conditions
1048 if (threatLevel == ThreatRA)
1050 /* [TCASII]: "... less than 360 feet, TCAS considers the reporting aircraft
1051 * to be on the ground. If TCAS determines the intruder to be on the ground, it
1052 * inhibits the generation of advisories against this aircraft."*/
1054 threatLevel = ThreatTA;
1056 /* [EUROACAS]: "Certain RAs are inhibited at altitudes based on inputs from the radio altimeter:
1057 * [..] (c)1000ft (+/- 100ft) and below, all RAs are inhibited;" */
1058 if (pSelf->radarAltFt < 1000)
1059 threatLevel = ThreatTA;
1061 // RAs only issued in mode "Auto" (= "TA/RA" mode)
1062 if (mode != SwitchAuto)
1063 threatLevel = ThreatTA;
1066 bool isCrossing = false;
1068 // determine suitable RAs
1069 if (threatLevel == ThreatRA)
1071 /* [TCASII]: "[..] a two step process is used to select the appropriate RA for the encounter
1072 * geometry. The first step in the process is to select the RA sense, i.e., upward or downward." */
1073 determineRAsense(RASense, isCrossing);
1075 /* second step: determine required strength */
1080 if ((pSelf->verticalFps < -1000/60.0)&&
1083 // currently descending, see if reducing current descent is sufficient
1084 float relAltFt = verticalSeparation(-500/60.0);
1085 if (relAltFt > pAlarmThresholds->TA.ALIM)
1086 RA |= AdvisoryAdjustVSpeed;
1088 RA |= AdvisoryClimb;
1090 RAOption |= OptionCrossingClimb;
1097 if ((pSelf->verticalFps > 1000/60.0)&&
1100 // currently climbing, see if reducing current climb is sufficient
1101 float relAltFt = verticalSeparation(500/60.0);
1102 if (relAltFt < -pAlarmThresholds->TA.ALIM)
1103 RA |= AdvisoryAdjustVSpeed;
1105 RA |= AdvisoryDescend;
1107 RAOption |= OptionCrossingDescent;
1111 /* [TCASII]: "When two TCAS-equipped aircraft are converging vertically with opposite rates
1112 * and are currently well separated in altitude, TCAS will first issue a vertical speed
1113 * limit (Negative) RA to reinforce the pilots' likely intention to level off at adjacent
1114 * flight levels." */
1117 /* [TCASII]: "[..] if the CAS logic determines that the response to a Positive RA has provided
1118 * ALIM feet of vertical separation before CPA, the initial RA will be weakened to either a
1119 * Do Not Descend RA (after an initial Climb RA) or a Do Not Climb RA (after an initial
1123 /* [TCASII]: "TCAS is designed to inhibit Increase Descent RAs below 1450 feet AGL; */
1125 /* [TCASII]: "Descend RAs below 1100 feet AGL;" (inhibited) */
1126 if (pSelf->radarAltFt < 1100)
1128 RA &= ~AdvisoryDescend;
1129 //TODO Support "Do not descend" RA
1130 RA |= AdvisoryIntrusion;
1134 #ifdef FEATURE_TCAS_DEBUG_ADV_GENERATOR
1135 cout << " resolution advisory: " << RA << endl;
1138 ResolutionAdvisory newAdvisory;
1139 newAdvisory.RAOption = RAOption;
1140 newAdvisory.RA = RA;
1141 newAdvisory.threatLevel = threatLevel;
1142 tcas->advisoryCoordinator.add(newAdvisory);
1147 ///////////////////////////////////////////////////////////////////////////////
1148 // TCAS ///////////////////////////////////////////////////////////////////////
1149 ///////////////////////////////////////////////////////////////////////////////
1151 TCAS::TCAS(SGPropertyNode* pNode) :
1156 properties_handler(this),
1157 threatDetector(this),
1159 advisoryCoordinator(this),
1160 advisoryGenerator(this),
1163 for (int i = 0; i < pNode->nChildren(); ++i)
1165 SGPropertyNode* pChild = pNode->getChild(i);
1166 string cname = pChild->getName();
1167 string cval = pChild->getStringValue();
1169 if (cname == "name")
1171 else if (cname == "number")
1172 num = pChild->getIntValue();
1175 SG_LOG(SG_INSTR, SG_WARN, "Error in TCAS config logic");
1177 SG_LOG(SG_INSTR, SG_WARN, "Section = " << name);
1186 advisoryCoordinator.init();
1187 threatDetector.init();
1194 advisoryCoordinator.reinit();
1200 SGPropertyNode* node = fgGetNode(("/instrumentation/" + name).c_str(), num, true);
1202 nodeServiceable = node->getNode("serviceable", true);
1204 // TCAS mode selection (0=off, 1=standby, 2=TA only, 3=auto(TA/RA) )
1205 nodeModeSwitch = node->getNode("inputs/mode", true);
1207 nodeSelfTest = node->getNode("inputs/self-test", true);
1209 nodeSelfTest->setBoolValue(false);
1211 #ifdef FEATURE_TCAS_DEBUG_PROPERTIES
1212 SGPropertyNode* nodeDebug = node->getNode("debug", true);
1214 nodeDebugTrigger = nodeDebug->getNode("threat-trigger", true);
1215 nodeDebugRA = nodeDebug->getNode("threat-RA", true);
1216 nodeDebugThreat = nodeDebug->getNode("threat-level", true);
1218 nodeDebugTrigger->setBoolValue(false);
1219 nodeDebugRA->setIntValue(3);
1220 nodeDebugThreat->setIntValue(1);
1223 annunciator.bind(node);
1224 advisoryCoordinator.bind(node);
1230 properties_handler.unbind();
1233 /** Monitor traffic for safety threats. */
1235 TCAS::update(double dt)
1237 if (!nodeServiceable->getBoolValue())
1239 int mode = nodeModeSwitch->getIntValue();
1240 if (mode == SwitchOff)
1243 nextUpdateTime -= dt;
1244 if (nextUpdateTime <= 0.0 )
1246 nextUpdateTime = 1.0;
1248 // remove obsolete targets
1251 // get aircrafts current position/speed/heading
1252 threatDetector.update();
1254 // clear old threats
1255 advisoryCoordinator.clear();
1257 if (nodeSelfTest->getBoolValue())
1259 if (threatDetector.getVelocityKt() >= 40)
1261 // disable self-test when plane moves above taxiing speed
1262 nodeSelfTest->setBoolValue(false);
1268 // speed-up self test
1270 // no further TCAS processing during self-test
1275 #ifdef FEATURE_TCAS_DEBUG_PROPERTIES
1276 if (nodeDebugTrigger->getBoolValue())
1279 ResolutionAdvisory debugAdvisory;
1280 debugAdvisory.RAOption = OptionNone;
1281 debugAdvisory.RA = nodeDebugRA->getIntValue();
1282 debugAdvisory.threatLevel = nodeDebugThreat->getIntValue();
1283 advisoryCoordinator.add(debugAdvisory);
1288 SGPropertyNode* pAi = fgGetNode("/ai/models", true);
1290 // check all aircraft
1291 for (int i = pAi->nChildren() - 1; i >= -1; i--)
1293 SGPropertyNode* pModel = pAi->getChild(i);
1294 if ((pModel)&&(pModel->nChildren()))
1296 int threatLevel = threatDetector.checkThreat(mode, pModel);
1297 /* expose aircraft threat-level (to be used by other instruments,
1298 * i.e. TCAS display) */
1299 if (threatLevel==ThreatRA)
1300 pModel->setIntValue("tcas/ra-sense", -threatDetector.getRASense());
1301 pModel->setIntValue("tcas/threat-level", threatLevel);
1305 advisoryCoordinator.update(mode);
1307 annunciator.update();
1310 /** Run a single self-test iteration. */
1312 TCAS::selfTest(void)
1314 annunciator.update();
1315 if (annunciator.isPlaying())
1320 ResolutionAdvisory newAdvisory;
1321 newAdvisory.threatLevel = ThreatRA;
1322 newAdvisory.RA = AdvisoryClear;
1323 newAdvisory.RAOption = OptionNone;
1324 // TCAS audio is disabled below 500ft AGL
1325 threatDetector.setRadarAlt(501);
1327 // trigger various advisories
1328 switch(selfTestStep)
1331 newAdvisory.RA = AdvisoryIntrusion;
1332 newAdvisory.threatLevel = ThreatTA;
1335 newAdvisory.RA = AdvisoryClimb;
1338 newAdvisory.RA = AdvisoryClimb;
1339 newAdvisory.RAOption = OptionIncreaseClimb;
1342 newAdvisory.RA = AdvisoryClimb;
1343 newAdvisory.RAOption = OptionCrossingClimb;
1346 newAdvisory.RA = AdvisoryDescend;
1349 newAdvisory.RA = AdvisoryDescend;
1350 newAdvisory.RAOption = OptionIncreaseDescend;
1353 newAdvisory.RA = AdvisoryDescend;
1354 newAdvisory.RAOption = OptionCrossingDescent;
1357 newAdvisory.RA = AdvisoryAdjustVSpeed;
1360 newAdvisory.RA = AdvisoryMaintVSpeed;
1363 newAdvisory.RA = AdvisoryMonitorVSpeed;
1366 newAdvisory.threatLevel = ThreatNone;
1367 newAdvisory.RA = AdvisoryClear;
1370 annunciator.test(true);
1374 nodeSelfTest->setBoolValue(false);
1379 advisoryCoordinator.add(newAdvisory);
1380 advisoryCoordinator.update(SwitchAuto);
1385 ///////////////////////////////////////////////////////////////////////////////
1386 // TCAS::Tracker //////////////////////////////////////////////////////////////
1387 ///////////////////////////////////////////////////////////////////////////////
1389 TCAS::Tracker::Tracker(TCAS* _tcas) :
1399 TCAS::Tracker::update(void)
1401 currentTime = globals->get_sim_time_sec();
1406 // remove outdated targets
1407 TrackerTargets::iterator it = targets.begin();
1408 while (it != targets.end())
1410 TrackerTarget* pTarget = it->second;
1411 if (currentTime - pTarget->TAtimestamp > 10.0)
1413 TrackerTargets::iterator temp = it;
1415 #ifdef FEATURE_TCAS_DEBUG_TRACKER
1416 printf("target %s no longer a TA threat.\n",temp->first.c_str());
1418 targets.erase(temp->first);
1424 if ((pTarget->threatLevel == ThreatRA)&&
1425 (currentTime - pTarget->RAtimestamp > 7.0))
1427 pTarget->threatLevel = ThreatTA;
1428 #ifdef FEATURE_TCAS_DEBUG_TRACKER
1429 printf("target %s no longer an RA threat.\n",it->first.c_str());
1435 haveTargets = !targets.empty();
1440 TCAS::Tracker::add(const string callsign, int detectedLevel)
1442 TrackerTarget* pTarget = NULL;
1445 TrackerTargets::iterator it = targets.find(callsign);
1446 if (it != targets.end())
1448 pTarget = it->second;
1454 pTarget = new TrackerTarget();
1455 pTarget->TAtimestamp = 0;
1456 pTarget->RAtimestamp = 0;
1457 pTarget->threatLevel = 0;
1459 targets[callsign] = pTarget;
1460 #ifdef FEATURE_TCAS_DEBUG_TRACKER
1461 printf("new target: %s, level: %i\n",callsign.c_str(),detectedLevel);
1465 if (detectedLevel > pTarget->threatLevel)
1466 pTarget->threatLevel = detectedLevel;
1468 if (detectedLevel >= ThreatTA)
1469 pTarget->TAtimestamp = currentTime;
1471 if (detectedLevel >= ThreatRA)
1472 pTarget->RAtimestamp = currentTime;
1478 TCAS::Tracker::_isTracked(string callsign)
1480 return targets.find(callsign) != targets.end();
1484 TCAS::Tracker::getThreatLevel(string callsign)
1486 TrackerTargets::iterator it = targets.find(callsign);
1487 if (it != targets.end())
1488 return it->second->threatLevel;