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., 675 Mass Ave, Cambridge, MA 02139, 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)
386 TCAS::AdvisoryCoordinator::bind(SGPropertyNode* node)
388 nodeTAWarning = node->getNode("outputs/traffic-alert", true);
389 nodeTAWarning->setBoolValue(false);
393 TCAS::AdvisoryCoordinator::clear(void)
395 current.threatLevel = ThreatNone;
396 current.RA = AdvisoryClear;
397 current.RAOption = OptionNone;
400 /** Add all suitable resolution advisories for a single threat. */
402 TCAS::AdvisoryCoordinator::add(const ResolutionAdvisory& newAdvisory)
404 if ((newAdvisory.RA == AdvisoryClear)||
405 (newAdvisory.threatLevel < current.threatLevel))
408 if (current.threatLevel == newAdvisory.threatLevel)
410 // combine with other advisories so far
411 current.RA &= newAdvisory.RA;
412 // remember any advisory modifier
413 current.RAOption |= newAdvisory.RAOption;
417 current = newAdvisory;
421 /** Pick and trigger suitable resolution advisory. */
423 TCAS::AdvisoryCoordinator::update(int mode)
425 bool revertedRA = false; // has advisory changed?
426 double currentTime = globals->get_sim_time_sec();
428 if (current.RA == AdvisoryClear)
430 // filter: wait 5 seconds after last TA/RA before announcing TA clearance
431 if ((previous.RA != AdvisoryClear)&&
432 (currentTime - lastTATime < 5.0))
439 #ifdef FEATURE_TCAS_DEBUG_COORDINATOR
440 cout << "TCAS::Annunciator::update: previous: " << previous.RA << ", new: " << current.RA << endl;
443 lastTATime = currentTime;
444 if ((previous.RA == AdvisoryClear)||
445 (previous.RA == AdvisoryIntrusion)||
446 ((current.RA & previous.RA) != previous.RA))
448 // no RA yet, or we can't keep previous RA: pick one - in order of priority
450 if (AVAILABLE_RA(current.RA, AdvisoryMonitorVSpeed))
452 // prio 1: monitor vertical speed only
453 current.RA = AdvisoryMonitorVSpeed;
456 if (AVAILABLE_RA(current.RA, AdvisoryMaintVSpeed))
458 // prio 2: maintain vertical speed
459 current.RA = AdvisoryMaintVSpeed;
462 if (AVAILABLE_RA(current.RA, AdvisoryAdjustVSpeed))
464 // prio 3: adjust vertical speed (TCAS II 7.0 only)
465 current.RA = AdvisoryAdjustVSpeed;
468 if (AVAILABLE_RA(current.RA, AdvisoryLevelOff))
470 // prio 3: adjust vertical speed (TCAS II 7.1 only, [EUROACAS]: CP115)
471 current.RA = AdvisoryLevelOff;
474 if (AVAILABLE_RA(current.RA, AdvisoryClimb))
477 current.RA = AdvisoryClimb;
480 if (AVAILABLE_RA(current.RA, AdvisoryDescend))
483 current.RA = AdvisoryDescend;
487 // no RA, issue a TA only
488 current.RA = AdvisoryIntrusion;
491 // check if earlier advisory was reverted
492 revertedRA = ((previous.RA != current.RA)&&
494 (previous.RA != AdvisoryIntrusion));
499 current.RA = previous.RA;
503 /* [TCASII]: "Aural annunciations are inhibited below 500+/-100 feet AGL." */
504 if ((tcas->threatDetector.getRadarAlt() > 500)&&
505 (mode >= SwitchTaOnly))
506 tcas->annunciator.trigger(current, revertedRA);
508 if (current.RA == AdvisoryClear)
510 /* explicitly clear traffic alert (since aural annunciation disabled) */
511 tcas->annunciator.clear();
516 /* [TCASII] "[..] also performs the function of setting flags that control the displays.
517 * The traffic display, the RA display, [..] use these flags to alert the pilot to
518 * the presence of TAs and RAs." */
519 nodeTAWarning->setBoolValue(current.RA != AdvisoryClear);
522 ///////////////////////////////////////////////////////////////////////////////
523 // TCAS::ThreatDetector ///////////////////////////////////////////////////////
524 ///////////////////////////////////////////////////////////////////////////////
526 TCAS::ThreatDetector::ThreatDetector(TCAS* _tcas) :
529 pAlarmThresholds(&sensitivityLevels[0])
531 self.radarAltFt = 0.0;
536 TCAS::ThreatDetector::init(void)
538 nodeLat = fgGetNode("/position/latitude-deg", true);
539 nodeLon = fgGetNode("/position/longitude-deg", true);
540 nodePressureAlt = fgGetNode("/position/altitude-ft", true);
541 nodeRadarAlt = fgGetNode("/position/altitude-agl-ft", true);
542 nodeHeading = fgGetNode("/orientation/heading-deg", true);
543 nodeVelocity = fgGetNode("/velocities/airspeed-kt", true);
544 nodeVerticalFps = fgGetNode("/velocities/vertical-speed-fps", true);
546 tcas->advisoryGenerator.init(&self,¤tThreat);
549 /** Update local position and threat sensitivity levels. */
551 TCAS::ThreatDetector::update(void)
553 // update local position
554 self.lat = nodeLat->getDoubleValue();
555 self.lon = nodeLon->getDoubleValue();
556 self.pressureAltFt = nodePressureAlt->getDoubleValue();
557 self.heading = nodeHeading->getDoubleValue();
558 self.velocityKt = nodeVelocity->getDoubleValue();
559 self.verticalFps = nodeVerticalFps->getDoubleValue();
561 /* radar altimeter provides a lot of spikes due to uneven terrain
562 * MK-VIII GPWS-spec requires smoothing the radar altitude with a
563 * 10second moving average. Likely the TCAS spec requires the same.
564 * => We use a cheap 10 second exponential average method.
566 const double SmoothingFactor = 0.3;
567 self.radarAltFt = nodeRadarAlt->getDoubleValue()*SmoothingFactor +
568 (1-SmoothingFactor)*self.radarAltFt;
570 #ifdef FEATURE_TCAS_DEBUG_THREAT_DETECTOR
571 printf("TCAS::ThreatDetector::update: radarAlt = %f\n",self.radarAltFt);
575 // determine current altitude's "Sensitivity Level Definition and Alarm Thresholds"
577 for (sl=0;((self.radarAltFt > sensitivityLevels[sl].maxAltitude)&&
578 (sensitivityLevels[sl].maxAltitude));sl++);
579 pAlarmThresholds = &sensitivityLevels[sl];
580 tcas->advisoryGenerator.setAlarmThresholds(pAlarmThresholds);
583 /** Check if plane's transponder is enabled. */
585 TCAS::ThreatDetector::checkTransponder(const SGPropertyNode* pModel, float velocityKt)
587 const string name = pModel->getName();
588 if (name != "multiplayer" && name != "aircraft")
590 // assume non-MP/non-AI planes (e.g. ships) have no transponder
596 /* assume all pilots have their transponder switched off while taxiing/parking
601 if ((name == "multiplayer")&&
602 (pModel->getBoolValue("controls/invisible")))
604 // ignored MP plane: pretend transponder is switched off
611 /** Check if plane is a threat. */
613 TCAS::ThreatDetector::checkThreat(int mode, const SGPropertyNode* pModel)
615 #ifdef FEATURE_TCAS_DEBUG_THREAT_DETECTOR
619 float velocityKt = pModel->getDoubleValue("velocities/true-airspeed-kt");
621 if (!checkTransponder(pModel, velocityKt))
622 return ThreatInvisible;
624 int threatLevel = ThreatNone;
625 float altFt = pModel->getDoubleValue("position/altitude-ft");
626 currentThreat.relativeAltitudeFt = altFt - self.pressureAltFt;
628 // save computation time: don't care when relative altitude is excessive
629 if (fabs(currentThreat.relativeAltitudeFt) > 10000)
632 // position data of current intruder
633 double lat = pModel->getDoubleValue("position/latitude-deg");
634 double lon = pModel->getDoubleValue("position/longitude-deg");
635 float heading = pModel->getDoubleValue("orientation/true-heading-deg");
637 double distanceNm, bearing;
638 calcRangeBearing(self.lat, self.lon, lat, lon, distanceNm, bearing);
640 // save computation time: don't care for excessive distances (also captures NaNs...)
641 if ((distanceNm > 10)||(distanceNm < 0))
644 currentThreat.verticalFps = pModel->getDoubleValue("velocities/vertical-speed-fps");
646 /* Detect proximity targets
647 * [TCASII]: "Any target that is less than 6 nmi in range and within +/-1200ft
648 * vertically, but that does not meet the intruder or threat criteria." */
649 if ((distanceNm < 6)&&
650 (fabs(currentThreat.relativeAltitudeFt) < 1200))
652 // at least a proximity target
653 threatLevel = ThreatProximity;
656 /* do not detect any threats when in standby or on ground and taxiing */
657 if ((mode <= SwitchStandby)||
658 ((self.radarAltFt < 360)&&(self.velocityKt < 40)))
663 if (tcas->tracker.active())
665 currentThreat.callsign = pModel->getStringValue("callsign");
666 currentThreat.isTracked = tcas->tracker.isTracked(currentThreat.callsign);
669 currentThreat.isTracked = false;
671 // first stage: vertical movement
672 checkVerticalThreat();
674 // stop processing when no vertical threat
675 if ((!currentThreat.verticalTA)&&
676 (!currentThreat.isTracked))
679 // second stage: horizontal movement
680 horizontalThreat(bearing, distanceNm, heading, velocityKt);
682 if (!currentThreat.isTracked)
684 // no horizontal threat?
685 if (!currentThreat.horizontalTA)
688 if ((currentThreat.horizontalTau < 0)||
689 (currentThreat.verticalTau < 0))
691 // do not trigger new alerts when Tau is negative, but keep existing alerts
692 int previousThreatLevel = pModel->getIntValue("tcas/threat-level", 0);
693 if (previousThreatLevel == 0)
698 #ifdef FEATURE_TCAS_DEBUG_THREAT_DETECTOR
699 cout << "#" << checkCount << ": " << pModel->getStringValue("callsign") << endl;
703 /* [TCASII]: "For either a TA or an RA to be issued, both the range and
704 * vertical criteria, in terms of tau or the fixed thresholds, must be
705 * satisfied only one of the criteria is satisfied, TCAS will not issue
707 if (currentThreat.horizontalTA && currentThreat.verticalTA)
708 threatLevel = ThreatTA;
709 if (currentThreat.horizontalRA && currentThreat.verticalRA)
710 threatLevel = ThreatRA;
712 if (!tcas->tracker.active())
713 currentThreat.callsign = pModel->getStringValue("callsign");
715 tcas->tracker.add(currentThreat.callsign, threatLevel);
717 // check existing threat level
718 if (currentThreat.isTracked)
720 int oldLevel = tcas->tracker.getThreatLevel(currentThreat.callsign);
721 if (oldLevel > threatLevel)
722 threatLevel = oldLevel;
725 // find all resolution options for this conflict
726 threatLevel = tcas->advisoryGenerator.resolution(mode, threatLevel, distanceNm, altFt, heading, velocityKt);
729 #ifdef FEATURE_TCAS_DEBUG_THREAT_DETECTOR
730 printf(" threat: distance: %4.1f, bearing: %4.1f, alt: %5.1f, velocity: %4.1f, heading: %4.1f, vspeed: %4.1f, "
731 "own alt: %5.1f, own heading: %4.1f, own velocity: %4.1f, vertical tau: %3.2f"
732 //", closing speed: %f"
734 distanceNm, relAngle(bearing, self.heading), altFt, velocityKt, heading, currentThreat.verticalFps,
735 self.altFt, self.heading, self.velocityKt
736 //, currentThreat.closingSpeedKt
737 ,currentThreat.verticalTau
744 /** Check if plane is a vertical threat. */
746 TCAS::ThreatDetector::checkVerticalThreat(void)
748 // calculate relative vertical speed and altitude
749 float dV = self.verticalFps - currentThreat.verticalFps;
750 float dA = currentThreat.relativeAltitudeFt;
752 currentThreat.verticalTA = false;
753 currentThreat.verticalRA = false;
754 currentThreat.verticalTau = 0;
756 /* [TCASII]: "The vertical tau is equal to the altitude separation (feet)
757 * divided by the combined vertical speed of the two aircraft (feet/minute)
763 /* [TCASII]: "When the combined vertical speed of the TCAS and the intruder aircraft
764 * is low, TCAS will use a fixed-altitude threshold to determine whether a TA or
765 * an RA should be issued." */
766 if ((fabs(dV) < 3.0)||
767 ((tau < 0) && (tau > -5)))
769 /* vertical closing speed is low (below 180fpm/3fps), check
770 * fixed altitude range. */
771 float abs_dA = fabs(dA);
772 if (abs_dA < pAlarmThresholds->RA.ALIM)
774 // continuous intrusion at RA-level
775 currentThreat.verticalTA = true;
776 currentThreat.verticalRA = true;
779 if (abs_dA < pAlarmThresholds->TA.ALIM)
781 // continuous intrusion: with TA-level, but no RA-threat
782 currentThreat.verticalTA = true;
784 // else: no RA/TA threat
788 if ((tau < pAlarmThresholds->TA.Tau)&&
791 currentThreat.verticalTA = true;
792 currentThreat.verticalRA = (tau < pAlarmThresholds->RA.Tau);
795 currentThreat.verticalTau = tau;
797 #ifdef FEATURE_TCAS_DEBUG_THREAT_DETECTOR
798 if (currentThreat.verticalTA)
799 printf(" vertical dV=%f (%f-%f), dA=%f\n", dV, self.verticalFps, currentThreat.verticalFps, dA);
803 /** Check if plane is a horizontal threat. */
805 TCAS::ThreatDetector::horizontalThreat(float bearing, float distanceNm, float heading, float velocityKt)
808 float vxKt = sin(heading*SGD_DEGREES_TO_RADIANS)*velocityKt - sin(self.heading*SGD_DEGREES_TO_RADIANS)*self.velocityKt;
809 float vyKt = cos(heading*SGD_DEGREES_TO_RADIANS)*velocityKt - cos(self.heading*SGD_DEGREES_TO_RADIANS)*self.velocityKt;
811 // calculate horizontal closing speed
812 float closingSpeedKt2 = vxKt*vxKt+vyKt*vyKt;
813 float closingSpeedKt = sqrt(closingSpeedKt2);
815 /* [TCASII]: "The range tau is equal to the slant range (nmi) divided by the closing speed
816 * (knots) multiplied by 3600."
817 * => calculate allowed slant range (nmi) based on known maximum tau */
818 float TA_rangeNm = (pAlarmThresholds->TA.Tau*closingSpeedKt)/3600;
819 float RA_rangeNm = (pAlarmThresholds->RA.Tau*closingSpeedKt)/3600;
821 if (closingSpeedKt < 100)
823 /* [TCASII]: "In events where the rate of closure is very low, [..]
824 * an intruder aircraft can come very close in range without crossing the
825 * range tau boundaries [..]. To provide protection in these types of
826 * advisories, the range tau boundaries are modified [..] to use
827 * a fixed-range threshold to issue TAs and RAs in these slow closure
829 TA_rangeNm += (100.0-closingSpeedKt)*(pAlarmThresholds->TA.DMOD/100.0);
830 RA_rangeNm += (100.0-closingSpeedKt)*(pAlarmThresholds->RA.DMOD/100.0);
832 if (TA_rangeNm < pAlarmThresholds->TA.DMOD)
833 TA_rangeNm = pAlarmThresholds->TA.DMOD;
834 if (RA_rangeNm < pAlarmThresholds->RA.DMOD)
835 RA_rangeNm = pAlarmThresholds->RA.DMOD;
837 currentThreat.horizontalTA = (distanceNm < TA_rangeNm);
838 currentThreat.horizontalRA = (distanceNm < RA_rangeNm);
839 currentThreat.horizontalTau = -1;
841 if ((currentThreat.horizontalRA)&&
842 (currentThreat.verticalRA))
844 /* an RA will be issued. Prepare extra data for the
845 * traffic resolution stage, i.e. calculate
846 * exact time tau to horizontal CPA.
849 /* relative position of intruder is
852 * horizontal distance to intruder is r(t)
853 * r(t) = sqrt( Sx(t)^2 + Sy(t)^2 )
854 * => horizontal CPA at time t=tau, where r(t) has minimum
855 * r2(t) := r^2(t) = Sx(t)^2 + Sy(t)^2
856 * since r(t)>0 for all t => minimum of r(t) is also minimum of r2(t)
857 * => (d/dt) r2(t) = r2'(t) is 0 for t=tau
858 * r2(t) = ((Sx(t)^2 + Sy(t))^2) = c + b*t + a*t^2
859 * => r2'(t) = b + a*2*t
861 * r2'(tau) = 0 = b + 2*a*tau
864 float sx = sin(bearing*SGD_DEGREES_TO_RADIANS)*distanceNm;
865 float sy = cos(bearing*SGD_DEGREES_TO_RADIANS)*distanceNm;
866 float vx = vxKt * (SG_KT_TO_MPS*SG_METER_TO_NM);
867 float vy = vyKt * (SG_KT_TO_MPS*SG_METER_TO_NM);
868 float a = vx*vx + vy*vy;
869 float b = 2*(sx*vx + sy*vy);
873 #ifdef FEATURE_TCAS_DEBUG_THREAT_DETECTOR
874 printf(" Time to horizontal CPA: %4.2f\n",tau);
876 if (tau > pAlarmThresholds->RA.Tau)
877 tau = pAlarmThresholds->RA.Tau;
879 // remember time to horizontal CPA
880 currentThreat.horizontalTau = tau;
884 /** Test threat detection logic. */
886 TCAS::ThreatDetector::unitTest(void)
888 pAlarmThresholds = &sensitivityLevels[1];
891 self.verticalFps = 0;
893 cout << "identical altitude and vspeed " << endl;
894 checkVerticalThreat(self.altFt, self.verticalFps);
895 cout << "1000ft alt offset, dV=100 " << endl;
896 checkVerticalThreat(self.altFt+1000, 100);
897 cout << "-1000ft alt offset, dV=100 " << endl;
898 checkVerticalThreat(self.altFt-1000, 100);
899 cout << "3000ft alt offset, dV=10 " << endl;
900 checkVerticalThreat(self.altFt+3000, 10);
901 cout << "500ft alt offset, dV=100 " << endl;
902 checkVerticalThreat(self.altFt+500, 100);
903 cout << "500ft alt offset, dV=-100 " << endl;
904 checkVerticalThreat(self.altFt+500, -100);
909 cout << "10nm behind, overtaking with 1Nm/s" << endl;
910 horizontalThreat(-180, 10, 0, 1/(SG_KT_TO_MPS*SG_METER_TO_NM));
912 cout << "10nm ahead, departing with 1Nm/s" << endl;
913 horizontalThreat(0, 20, 0, 1/(SG_KT_TO_MPS*SG_METER_TO_NM));
916 self.velocityKt = 1/(SG_KT_TO_MPS*SG_METER_TO_NM);
917 cout << "10nm behind, overtaking with 1Nm/s at 90 degrees" << endl;
918 horizontalThreat(-90, 20, 90, 2/(SG_KT_TO_MPS*SG_METER_TO_NM));
921 self.velocityKt = 1/(SG_KT_TO_MPS*SG_METER_TO_NM);
922 cout << "10nm behind, overtaking with 1Nm/s at 20 degrees" << endl;
923 horizontalThreat(200, 20, 20, 2/(SG_KT_TO_MPS*SG_METER_TO_NM));
927 ///////////////////////////////////////////////////////////////////////////////
928 // TCAS::AdvisoryGenerator ////////////////////////////////////////////////////
929 ///////////////////////////////////////////////////////////////////////////////
931 TCAS::AdvisoryGenerator::AdvisoryGenerator(TCAS* _tcas) :
934 pCurrentThreat(NULL),
935 pAlarmThresholds(NULL)
940 TCAS::AdvisoryGenerator::init(const LocalInfo* _pSelf, ThreatInfo* _pCurrentThreat)
942 pCurrentThreat = _pCurrentThreat;
947 TCAS::AdvisoryGenerator::setAlarmThresholds(const SensitivityLevel* _pAlarmThresholds)
949 pAlarmThresholds = _pAlarmThresholds;
952 /** Calculate projected vertical separation at horizontal CPA. */
954 TCAS::AdvisoryGenerator::verticalSeparation(float newVerticalFps)
956 // calculate relative vertical speed and altitude
957 float dV = pCurrentThreat->verticalFps - newVerticalFps;
958 float tau = pCurrentThreat->horizontalTau;
959 // don't use negative tau to project future separation...
962 return pCurrentThreat->relativeAltitudeFt + tau * dV;
965 /** Determine RA sense. */
967 TCAS::AdvisoryGenerator::determineRAsense(int& RASense, bool& isCrossing)
969 /* [TCASII]: "[..] a two step process is used to select the appropriate RA for the encounter
970 * geometry. The first step in the process is to select the RA sense, i.e., upward or downward." */
974 /* [TCASII]: "Based on the range and altitude tracks of the intruder, the CAS logic models the
975 * intruder's flight path from its present position to CPA. The CAS logic then models upward
976 * and downward sense RAs for own aircraft [..] to determine which sense provides the most
977 * vertical separation at CPA." */
978 float upSenseRelAltFt = verticalSeparation(+2000/60.0);
979 float downSenseRelAltFt = verticalSeparation(-2000/60.0);
980 if (fabs(upSenseRelAltFt) >= fabs(downSenseRelAltFt))
981 RASense = +1; // upward
983 RASense = -1; // downward
985 /* [TCASII]: "In encounters where either of the senses results in the TCAS aircraft crossing through
986 * the intruder's altitude, TCAS is designed to select the nonaltitude crossing sense if the
987 * noncrossing sense provides the desired vertical separation, known as ALIM, at CPA." */
988 /* [TCASII]: "If ALIM cannot be obtained in the nonaltitude crossing sense, an altitude
989 * crossing RA will be issued." */
991 (pCurrentThreat->relativeAltitudeFt > 200))
993 // threat is above and RA is crossing
994 if (fabs(downSenseRelAltFt) > pAlarmThresholds->TA.ALIM)
996 // non-crossing descend is sufficient
1001 // keep crossing climb RA
1007 (pCurrentThreat->relativeAltitudeFt < -200))
1009 // threat is below and RA is crossing
1010 if (fabs(upSenseRelAltFt) > pAlarmThresholds->TA.ALIM)
1012 // non-crossing climb is sufficient
1017 // keep crossing descent RA
1021 // else: threat is at same altitude, keep optimal RA sense (non-crossing)
1023 pCurrentThreat->RASense = RASense;
1025 #ifdef FEATURE_TCAS_DEBUG_ADV_GENERATOR
1026 printf(" RASense: %i, crossing: %u, relAlt: %4.1f, upward separation: %4.1f, downward separation: %4.1f\n",
1028 pCurrentThreat->relativeAltitudeFt,
1029 upSenseRelAltFt,downSenseRelAltFt);
1033 /** Determine suitable resolution advisories. */
1035 TCAS::AdvisoryGenerator::resolution(int mode, int threatLevel, float rangeNm, float altFt,
1036 float heading, float velocityKt)
1038 int RAOption = OptionNone;
1039 int RA = AdvisoryIntrusion;
1041 // RAs are disabled under certain conditions
1042 if (threatLevel == ThreatRA)
1044 /* [TCASII]: "... less than 360 feet, TCAS considers the reporting aircraft
1045 * to be on the ground. If TCAS determines the intruder to be on the ground, it
1046 * inhibits the generation of advisories against this aircraft."*/
1048 threatLevel = ThreatTA;
1050 /* [EUROACAS]: "Certain RAs are inhibited at altitudes based on inputs from the radio altimeter:
1051 * [..] (c)1000ft (+/- 100ft) and below, all RAs are inhibited;" */
1052 if (pSelf->radarAltFt < 1000)
1053 threatLevel = ThreatTA;
1055 // RAs only issued in mode "Auto" (= "TA/RA" mode)
1056 if (mode != SwitchAuto)
1057 threatLevel = ThreatTA;
1060 bool isCrossing = false;
1062 // determine suitable RAs
1063 if (threatLevel == ThreatRA)
1065 /* [TCASII]: "[..] a two step process is used to select the appropriate RA for the encounter
1066 * geometry. The first step in the process is to select the RA sense, i.e., upward or downward." */
1067 determineRAsense(RASense, isCrossing);
1069 /* second step: determine required strength */
1074 if ((pSelf->verticalFps < -1000/60.0)&&
1077 // currently descending, see if reducing current descent is sufficient
1078 float relAltFt = verticalSeparation(-500/60.0);
1079 if (relAltFt > pAlarmThresholds->TA.ALIM)
1080 RA |= AdvisoryAdjustVSpeed;
1082 RA |= AdvisoryClimb;
1084 RAOption |= OptionCrossingClimb;
1091 if ((pSelf->verticalFps > 1000/60.0)&&
1094 // currently climbing, see if reducing current climb is sufficient
1095 float relAltFt = verticalSeparation(500/60.0);
1096 if (relAltFt < -pAlarmThresholds->TA.ALIM)
1097 RA |= AdvisoryAdjustVSpeed;
1099 RA |= AdvisoryDescend;
1101 RAOption |= OptionCrossingDescent;
1105 /* [TCASII]: "When two TCAS-equipped aircraft are converging vertically with opposite rates
1106 * and are currently well separated in altitude, TCAS will first issue a vertical speed
1107 * limit (Negative) RA to reinforce the pilots' likely intention to level off at adjacent
1108 * flight levels." */
1111 /* [TCASII]: "[..] if the CAS logic determines that the response to a Positive RA has provided
1112 * ALIM feet of vertical separation before CPA, the initial RA will be weakened to either a
1113 * Do Not Descend RA (after an initial Climb RA) or a Do Not Climb RA (after an initial
1117 /* [TCASII]: "TCAS is designed to inhibit Increase Descent RAs below 1450 feet AGL; */
1119 /* [TCASII]: "Descend RAs below 1100 feet AGL;" (inhibited) */
1120 if (pSelf->radarAltFt < 1100)
1122 RA &= ~AdvisoryDescend;
1123 //TODO Support "Do not descend" RA
1124 RA |= AdvisoryIntrusion;
1128 #ifdef FEATURE_TCAS_DEBUG_ADV_GENERATOR
1129 cout << " resolution advisory: " << RA << endl;
1132 ResolutionAdvisory newAdvisory;
1133 newAdvisory.RAOption = RAOption;
1134 newAdvisory.RA = RA;
1135 newAdvisory.threatLevel = threatLevel;
1136 tcas->advisoryCoordinator.add(newAdvisory);
1141 ///////////////////////////////////////////////////////////////////////////////
1142 // TCAS ///////////////////////////////////////////////////////////////////////
1143 ///////////////////////////////////////////////////////////////////////////////
1145 TCAS::TCAS(SGPropertyNode* pNode) :
1150 properties_handler(this),
1151 threatDetector(this),
1153 advisoryCoordinator(this),
1154 advisoryGenerator(this),
1157 for (int i = 0; i < pNode->nChildren(); ++i)
1159 SGPropertyNode* pChild = pNode->getChild(i);
1160 string cname = pChild->getName();
1161 string cval = pChild->getStringValue();
1163 if (cname == "name")
1165 else if (cname == "number")
1166 num = pChild->getIntValue();
1169 SG_LOG(SG_INSTR, SG_WARN, "Error in TCAS config logic");
1171 SG_LOG(SG_INSTR, SG_WARN, "Section = " << name);
1180 advisoryCoordinator.init();
1181 threatDetector.init();
1187 SGPropertyNode* node = fgGetNode(("/instrumentation/" + name).c_str(), num, true);
1189 nodeServiceable = node->getNode("serviceable", true);
1191 // TCAS mode selection (0=off, 1=standby, 2=TA only, 3=auto(TA/RA) )
1192 nodeModeSwitch = node->getNode("inputs/mode", true);
1194 nodeSelfTest = node->getNode("inputs/self-test", true);
1196 nodeSelfTest->setBoolValue(false);
1198 #ifdef FEATURE_TCAS_DEBUG_PROPERTIES
1199 SGPropertyNode* nodeDebug = node->getNode("debug", true);
1201 nodeDebugTrigger = nodeDebug->getNode("threat-trigger", true);
1202 nodeDebugRA = nodeDebug->getNode("threat-RA", true);
1203 nodeDebugThreat = nodeDebug->getNode("threat-level", true);
1205 nodeDebugTrigger->setBoolValue(false);
1206 nodeDebugRA->setIntValue(3);
1207 nodeDebugThreat->setIntValue(1);
1210 annunciator.bind(node);
1211 advisoryCoordinator.bind(node);
1217 properties_handler.unbind();
1220 /** Monitor traffic for safety threats. */
1222 TCAS::update(double dt)
1224 if (!nodeServiceable->getBoolValue())
1226 int mode = nodeModeSwitch->getIntValue();
1227 if (mode == SwitchOff)
1230 nextUpdateTime -= dt;
1231 if (nextUpdateTime <= 0.0 )
1233 nextUpdateTime = 1.0;
1235 // remove obsolete targets
1238 // get aircrafts current position/speed/heading
1239 threatDetector.update();
1241 // clear old threats
1242 advisoryCoordinator.clear();
1244 if (nodeSelfTest->getBoolValue())
1246 if (threatDetector.getVelocityKt() >= 40)
1248 // disable self-test when plane moves above taxiing speed
1249 nodeSelfTest->setBoolValue(false);
1255 // speed-up self test
1257 // no further TCAS processing during self-test
1262 #ifdef FEATURE_TCAS_DEBUG_PROPERTIES
1263 if (nodeDebugTrigger->getBoolValue())
1266 ResolutionAdvisory debugAdvisory;
1267 debugAdvisory.RAOption = OptionNone;
1268 debugAdvisory.RA = nodeDebugRA->getIntValue();
1269 debugAdvisory.threatLevel = nodeDebugThreat->getIntValue();
1270 advisoryCoordinator.add(debugAdvisory);
1275 SGPropertyNode* pAi = fgGetNode("/ai/models", true);
1277 // check all aircraft
1278 for (int i = pAi->nChildren() - 1; i >= -1; i--)
1280 SGPropertyNode* pModel = pAi->getChild(i);
1281 if ((pModel)&&(pModel->nChildren()))
1283 int threatLevel = threatDetector.checkThreat(mode, pModel);
1284 /* expose aircraft threat-level (to be used by other instruments,
1285 * i.e. TCAS display) */
1286 if (threatLevel==ThreatRA)
1287 pModel->setIntValue("tcas/ra-sense", -threatDetector.getRASense());
1288 pModel->setIntValue("tcas/threat-level", threatLevel);
1292 advisoryCoordinator.update(mode);
1294 annunciator.update();
1297 /** Run a single self-test iteration. */
1299 TCAS::selfTest(void)
1301 annunciator.update();
1302 if (annunciator.isPlaying())
1307 ResolutionAdvisory newAdvisory;
1308 newAdvisory.threatLevel = ThreatRA;
1309 newAdvisory.RA = AdvisoryClear;
1310 newAdvisory.RAOption = OptionNone;
1311 // TCAS audio is disabled below 500ft AGL
1312 threatDetector.setRadarAlt(501);
1314 // trigger various advisories
1315 switch(selfTestStep)
1318 newAdvisory.RA = AdvisoryIntrusion;
1319 newAdvisory.threatLevel = ThreatTA;
1322 newAdvisory.RA = AdvisoryClimb;
1325 newAdvisory.RA = AdvisoryClimb;
1326 newAdvisory.RAOption = OptionIncreaseClimb;
1329 newAdvisory.RA = AdvisoryClimb;
1330 newAdvisory.RAOption = OptionCrossingClimb;
1333 newAdvisory.RA = AdvisoryDescend;
1336 newAdvisory.RA = AdvisoryDescend;
1337 newAdvisory.RAOption = OptionIncreaseDescend;
1340 newAdvisory.RA = AdvisoryDescend;
1341 newAdvisory.RAOption = OptionCrossingDescent;
1344 newAdvisory.RA = AdvisoryAdjustVSpeed;
1347 newAdvisory.RA = AdvisoryMaintVSpeed;
1350 newAdvisory.RA = AdvisoryMonitorVSpeed;
1353 newAdvisory.threatLevel = ThreatNone;
1354 newAdvisory.RA = AdvisoryClear;
1357 annunciator.test(true);
1361 nodeSelfTest->setBoolValue(false);
1366 advisoryCoordinator.add(newAdvisory);
1367 advisoryCoordinator.update(SwitchAuto);
1372 ///////////////////////////////////////////////////////////////////////////////
1373 // TCAS::Tracker //////////////////////////////////////////////////////////////
1374 ///////////////////////////////////////////////////////////////////////////////
1376 TCAS::Tracker::Tracker(TCAS* _tcas) :
1386 TCAS::Tracker::update(void)
1388 currentTime = globals->get_sim_time_sec();
1393 // remove outdated targets
1394 TrackerTargets::iterator it = targets.begin();
1395 while (it != targets.end())
1397 TrackerTarget* pTarget = it->second;
1398 if (currentTime - pTarget->TAtimestamp > 10.0)
1400 TrackerTargets::iterator temp = it;
1402 #ifdef FEATURE_TCAS_DEBUG_TRACKER
1403 printf("target %s no longer a TA threat.\n",temp->first.c_str());
1405 targets.erase(temp->first);
1411 if ((pTarget->threatLevel == ThreatRA)&&
1412 (currentTime - pTarget->RAtimestamp > 7.0))
1414 pTarget->threatLevel = ThreatTA;
1415 #ifdef FEATURE_TCAS_DEBUG_TRACKER
1416 printf("target %s no longer an RA threat.\n",it->first.c_str());
1422 haveTargets = !targets.empty();
1427 TCAS::Tracker::add(const string callsign, int detectedLevel)
1429 TrackerTarget* pTarget = NULL;
1432 TrackerTargets::iterator it = targets.find(callsign);
1433 if (it != targets.end())
1435 pTarget = it->second;
1441 pTarget = new TrackerTarget();
1442 pTarget->TAtimestamp = 0;
1443 pTarget->RAtimestamp = 0;
1444 pTarget->threatLevel = 0;
1446 targets[callsign] = pTarget;
1447 #ifdef FEATURE_TCAS_DEBUG_TRACKER
1448 printf("new target: %s, level: %i\n",callsign.c_str(),detectedLevel);
1452 if (detectedLevel > pTarget->threatLevel)
1453 pTarget->threatLevel = detectedLevel;
1455 if (detectedLevel >= ThreatTA)
1456 pTarget->TAtimestamp = currentTime;
1458 if (detectedLevel >= ThreatRA)
1459 pTarget->RAtimestamp = currentTime;
1465 TCAS::Tracker::_isTracked(string callsign)
1467 return targets.find(callsign) != targets.end();
1471 TCAS::Tracker::getThreatLevel(string callsign)
1473 TrackerTargets::iterator it = targets.find(callsign);
1474 if (it != targets.end())
1475 return it->second->threatLevel;