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.getAlt() > 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) :
528 pAlarmThresholds(&sensitivityLevels[0])
534 TCAS::ThreatDetector::init(void)
536 nodeLat = fgGetNode("/position/latitude-deg", true);
537 nodeLon = fgGetNode("/position/longitude-deg", true);
538 nodeAlt = fgGetNode("/position/altitude-ft", true);
539 nodeHeading = fgGetNode("/orientation/heading-deg", true);
540 nodeVelocity = fgGetNode("/velocities/airspeed-kt", true);
541 nodeVerticalFps = fgGetNode("/velocities/vertical-speed-fps", true);
543 tcas->advisoryGenerator.init(&self,¤tThreat);
546 /** Update local position and threat sensitivity levels. */
548 TCAS::ThreatDetector::update(void)
550 // update local position
551 self.lat = nodeLat->getDoubleValue();
552 self.lon = nodeLon->getDoubleValue();
553 self.altFt = nodeAlt->getDoubleValue();
554 self.heading = nodeHeading->getDoubleValue();
555 self.velocityKt = nodeVelocity->getDoubleValue();
556 self.verticalFps = nodeVerticalFps->getDoubleValue();
560 // determine current altitude's "Sensitivity Level Definition and Alarm Thresholds"
562 for (sl=0;((self.altFt > sensitivityLevels[sl].maxAltitude)&&
563 (sensitivityLevels[sl].maxAltitude));sl++);
564 pAlarmThresholds = &sensitivityLevels[sl];
565 tcas->advisoryGenerator.setAlarmThresholds(pAlarmThresholds);
568 /** Check if plane's transponder is enabled. */
570 TCAS::ThreatDetector::checkTransponder(const SGPropertyNode* pModel, float velocityKt)
572 const string name = pModel->getName();
573 if (name != "multiplayer" && name != "aircraft")
575 // assume non-MP/non-AI planes (e.g. ships) have no transponder
581 /* assume all pilots have their transponder switched off while taxiing/parking
586 if ((name == "multiplayer")&&
587 (pModel->getBoolValue("controls/invisible")))
589 // ignored MP plane: pretend transponder is switched off
596 /** Check if plane is a threat. */
598 TCAS::ThreatDetector::checkThreat(int mode, const SGPropertyNode* pModel)
602 float velocityKt = pModel->getDoubleValue("velocities/true-airspeed-kt");
604 if (!checkTransponder(pModel, velocityKt))
605 return ThreatInvisible;
607 int threatLevel = ThreatNone;
608 float altFt = pModel->getDoubleValue("position/altitude-ft");
609 currentThreat.relativeAltitudeFt = altFt - self.altFt;
611 // save computation time: don't care when relative altitude is excessive
612 if (fabs(currentThreat.relativeAltitudeFt) > 10000)
615 // position data of current intruder
616 double lat = pModel->getDoubleValue("position/latitude-deg");
617 double lon = pModel->getDoubleValue("position/longitude-deg");
618 float heading = pModel->getDoubleValue("orientation/true-heading-deg");
620 double distanceNm, bearing;
621 calcRangeBearing(self.lat, self.lon, lat, lon, distanceNm, bearing);
623 // save computation time: don't care for excessive distances (also captures NaNs...)
624 if ((distanceNm > 10)||(distanceNm < 0))
627 currentThreat.verticalFps = pModel->getDoubleValue("velocities/vertical-speed-fps");
629 /* Detect proximity targets
630 * [TCASII]: "Any target that is less than 6 nmi in range and within +/-1200ft
631 * vertically, but that does not meet the intruder or threat criteria." */
632 if ((distanceNm < 6)&&
633 (fabs(currentThreat.relativeAltitudeFt) < 1200))
635 // at least a proximity target
636 threatLevel = ThreatProximity;
639 /* do not detect any threats when in standby or on ground and taxiing */
640 if ((mode <= SwitchStandby)||
641 ((self.altFt < 360)&&(self.velocityKt < 40)))
646 if (tcas->tracker.active())
648 currentThreat.callsign = pModel->getStringValue("callsign");
649 currentThreat.isTracked = tcas->tracker.isTracked(currentThreat.callsign);
652 currentThreat.isTracked = false;
654 // first stage: vertical movement
655 checkVerticalThreat();
657 // stop processing when no vertical threat
658 if ((!currentThreat.verticalTA)&&
659 (!currentThreat.isTracked))
662 // second stage: horizontal movement
663 horizontalThreat(bearing, distanceNm, heading, velocityKt);
665 if (!currentThreat.isTracked)
667 // no horizontal threat?
668 if (!currentThreat.horizontalTA)
671 if ((currentThreat.horizontalTau < 0)||
672 (currentThreat.verticalTau < 0))
674 // do not trigger new alerts when Tau is negative, but keep existing alerts
675 int previousThreatLevel = pModel->getIntValue("tcas/threat-level", 0);
676 if (previousThreatLevel == 0)
681 #ifdef FEATURE_TCAS_DEBUG_THREAT_DETECTOR
682 cout << "#" << checkCount << ": " << pModel->getStringValue("callsign") << endl;
686 /* [TCASII]: "For either a TA or an RA to be issued, both the range and
687 * vertical criteria, in terms of tau or the fixed thresholds, must be
688 * satisfied only one of the criteria is satisfied, TCAS will not issue
690 if (currentThreat.horizontalTA && currentThreat.verticalTA)
691 threatLevel = ThreatTA;
692 if (currentThreat.horizontalRA && currentThreat.verticalRA)
693 threatLevel = ThreatRA;
695 if (!tcas->tracker.active())
696 currentThreat.callsign = pModel->getStringValue("callsign");
698 tcas->tracker.add(currentThreat.callsign, threatLevel);
700 // check existing threat level
701 if (currentThreat.isTracked)
703 int oldLevel = tcas->tracker.getThreatLevel(currentThreat.callsign);
704 if (oldLevel > threatLevel)
705 threatLevel = oldLevel;
708 // find all resolution options for this conflict
709 threatLevel = tcas->advisoryGenerator.resolution(mode, threatLevel, distanceNm, altFt, heading, velocityKt);
712 #ifdef FEATURE_TCAS_DEBUG_THREAT_DETECTOR
713 printf(" threat: distance: %4.1f, bearing: %4.1f, alt: %5.1f, velocity: %4.1f, heading: %4.1f, vspeed: %4.1f, "
714 "own alt: %5.1f, own heading: %4.1f, own velocity: %4.1f, vertical tau: %3.2f"
715 //", closing speed: %f"
717 distanceNm, relAngle(bearing, self.heading), altFt, velocityKt, heading, currentThreat.verticalFps,
718 self.altFt, self.heading, self.velocityKt
719 //, currentThreat.closingSpeedKt
720 ,currentThreat.verticalTau
727 /** Check if plane is a vertical threat. */
729 TCAS::ThreatDetector::checkVerticalThreat(void)
731 // calculate relative vertical speed and altitude
732 float dV = self.verticalFps - currentThreat.verticalFps;
733 float dA = currentThreat.relativeAltitudeFt;
735 currentThreat.verticalTA = false;
736 currentThreat.verticalRA = false;
737 currentThreat.verticalTau = 0;
739 /* [TCASII]: "The vertical tau is equal to the altitude separation (feet)
740 * divided by the combined vertical speed of the two aircraft (feet/minute)
746 /* [TCASII]: "When the combined vertical speed of the TCAS and the intruder aircraft
747 * is low, TCAS will use a fixed-altitude threshold to determine whether a TA or
748 * an RA should be issued." */
749 if ((fabs(dV) < 3.0)||
750 ((tau < 0) && (tau > -5)))
752 /* vertical closing speed is low (below 180fpm/3fps), check
753 * fixed altitude range. */
754 float abs_dA = fabs(dA);
755 if (abs_dA < pAlarmThresholds->RA.ALIM)
757 // continuous intrusion at RA-level
758 currentThreat.verticalTA = true;
759 currentThreat.verticalRA = true;
762 if (abs_dA < pAlarmThresholds->TA.ALIM)
764 // continuous intrusion: with TA-level, but no RA-threat
765 currentThreat.verticalTA = true;
767 // else: no RA/TA threat
771 if ((tau < pAlarmThresholds->TA.Tau)&&
774 currentThreat.verticalTA = true;
775 currentThreat.verticalRA = (tau < pAlarmThresholds->RA.Tau);
778 currentThreat.verticalTau = tau;
780 #ifdef FEATURE_TCAS_DEBUG_THREAT_DETECTOR
781 if (currentThreat.verticalTA)
782 printf(" vertical dV=%f (%f-%f), dA=%f\n", dV, self.verticalFps, currentThreat.verticalFps, dA);
786 /** Check if plane is a horizontal threat. */
788 TCAS::ThreatDetector::horizontalThreat(float bearing, float distanceNm, float heading, float velocityKt)
791 float vxKt = sin(heading*SGD_DEGREES_TO_RADIANS)*velocityKt - sin(self.heading*SGD_DEGREES_TO_RADIANS)*self.velocityKt;
792 float vyKt = cos(heading*SGD_DEGREES_TO_RADIANS)*velocityKt - cos(self.heading*SGD_DEGREES_TO_RADIANS)*self.velocityKt;
794 // calculate horizontal closing speed
795 float closingSpeedKt2 = vxKt*vxKt+vyKt*vyKt;
796 float closingSpeedKt = sqrt(closingSpeedKt2);
798 /* [TCASII]: "The range tau is equal to the slant range (nmi) divided by the closing speed
799 * (knots) multiplied by 3600."
800 * => calculate allowed slant range (nmi) based on known maximum tau */
801 float TA_rangeNm = (pAlarmThresholds->TA.Tau*closingSpeedKt)/3600;
802 float RA_rangeNm = (pAlarmThresholds->RA.Tau*closingSpeedKt)/3600;
804 if (closingSpeedKt < 100)
806 /* [TCASII]: "In events where the rate of closure is very low, [..]
807 * an intruder aircraft can come very close in range without crossing the
808 * range tau boundaries [..]. To provide protection in these types of
809 * advisories, the range tau boundaries are modified [..] to use
810 * a fixed-range threshold to issue TAs and RAs in these slow closure
812 TA_rangeNm += (100.0-closingSpeedKt)*(pAlarmThresholds->TA.DMOD/100.0);
813 RA_rangeNm += (100.0-closingSpeedKt)*(pAlarmThresholds->RA.DMOD/100.0);
815 if (TA_rangeNm < pAlarmThresholds->TA.DMOD)
816 TA_rangeNm = pAlarmThresholds->TA.DMOD;
817 if (RA_rangeNm < pAlarmThresholds->RA.DMOD)
818 RA_rangeNm = pAlarmThresholds->RA.DMOD;
820 currentThreat.horizontalTA = (distanceNm < TA_rangeNm);
821 currentThreat.horizontalRA = (distanceNm < RA_rangeNm);
822 currentThreat.horizontalTau = -1;
824 if ((currentThreat.horizontalRA)&&
825 (currentThreat.verticalRA))
827 /* an RA will be issued. Prepare extra data for the
828 * traffic resolution stage, i.e. calculate
829 * exact time tau to horizontal CPA.
832 /* relative position of intruder is
835 * horizontal distance to intruder is r(t)
836 * r(t) = sqrt( Sx(t)^2 + Sy(t)^2 )
837 * => horizontal CPA at time t=tau, where r(t) has minimum
838 * r2(t) := r^2(t) = Sx(t)^2 + Sy(t)^2
839 * since r(t)>0 for all t => minimum of r(t) is also minimum of r2(t)
840 * => (d/dt) r2(t) = r2'(t) is 0 for t=tau
841 * r2(t) = ((Sx(t)^2 + Sy(t))^2) = c + b*t + a*t^2
842 * => r2'(t) = b + a*2*t
844 * r2'(tau) = 0 = b + 2*a*tau
847 float sx = sin(bearing*SGD_DEGREES_TO_RADIANS)*distanceNm;
848 float sy = cos(bearing*SGD_DEGREES_TO_RADIANS)*distanceNm;
849 float vx = vxKt * (SG_KT_TO_MPS*SG_METER_TO_NM);
850 float vy = vyKt * (SG_KT_TO_MPS*SG_METER_TO_NM);
851 float a = vx*vx + vy*vy;
852 float b = 2*(sx*vx + sy*vy);
856 #ifdef FEATURE_TCAS_DEBUG_THREAT_DETECTOR
857 printf(" Time to horizontal CPA: %4.2f\n",tau);
859 if (tau > pAlarmThresholds->RA.Tau)
860 tau = pAlarmThresholds->RA.Tau;
862 // remember time to horizontal CPA
863 currentThreat.horizontalTau = tau;
867 /** Test threat detection logic. */
869 TCAS::ThreatDetector::unitTest(void)
871 pAlarmThresholds = &sensitivityLevels[1];
874 self.verticalFps = 0;
876 cout << "identical altitude and vspeed " << endl;
877 checkVerticalThreat(self.altFt, self.verticalFps);
878 cout << "1000ft alt offset, dV=100 " << endl;
879 checkVerticalThreat(self.altFt+1000, 100);
880 cout << "-1000ft alt offset, dV=100 " << endl;
881 checkVerticalThreat(self.altFt-1000, 100);
882 cout << "3000ft alt offset, dV=10 " << endl;
883 checkVerticalThreat(self.altFt+3000, 10);
884 cout << "500ft alt offset, dV=100 " << endl;
885 checkVerticalThreat(self.altFt+500, 100);
886 cout << "500ft alt offset, dV=-100 " << endl;
887 checkVerticalThreat(self.altFt+500, -100);
892 cout << "10nm behind, overtaking with 1Nm/s" << endl;
893 horizontalThreat(-180, 10, 0, 1/(SG_KT_TO_MPS*SG_METER_TO_NM));
895 cout << "10nm ahead, departing with 1Nm/s" << endl;
896 horizontalThreat(0, 20, 0, 1/(SG_KT_TO_MPS*SG_METER_TO_NM));
899 self.velocityKt = 1/(SG_KT_TO_MPS*SG_METER_TO_NM);
900 cout << "10nm behind, overtaking with 1Nm/s at 90 degrees" << endl;
901 horizontalThreat(-90, 20, 90, 2/(SG_KT_TO_MPS*SG_METER_TO_NM));
904 self.velocityKt = 1/(SG_KT_TO_MPS*SG_METER_TO_NM);
905 cout << "10nm behind, overtaking with 1Nm/s at 20 degrees" << endl;
906 horizontalThreat(200, 20, 20, 2/(SG_KT_TO_MPS*SG_METER_TO_NM));
910 ///////////////////////////////////////////////////////////////////////////////
911 // TCAS::AdvisoryGenerator ////////////////////////////////////////////////////
912 ///////////////////////////////////////////////////////////////////////////////
914 TCAS::AdvisoryGenerator::AdvisoryGenerator(TCAS* _tcas) :
917 pCurrentThreat(NULL),
918 pAlarmThresholds(NULL)
923 TCAS::AdvisoryGenerator::init(const LocalInfo* _pSelf, ThreatInfo* _pCurrentThreat)
925 pCurrentThreat = _pCurrentThreat;
930 TCAS::AdvisoryGenerator::setAlarmThresholds(const SensitivityLevel* _pAlarmThresholds)
932 pAlarmThresholds = _pAlarmThresholds;
935 /** Calculate projected vertical separation at horizontal CPA. */
937 TCAS::AdvisoryGenerator::verticalSeparation(float newVerticalFps)
939 // calculate relative vertical speed and altitude
940 float dV = pCurrentThreat->verticalFps - newVerticalFps;
941 float tau = pCurrentThreat->horizontalTau;
942 // don't use negative tau to project future separation...
945 return pCurrentThreat->relativeAltitudeFt + tau * dV;
948 /** Determine RA sense. */
950 TCAS::AdvisoryGenerator::determineRAsense(int& RASense, bool& isCrossing)
952 /* [TCASII]: "[..] a two step process is used to select the appropriate RA for the encounter
953 * geometry. The first step in the process is to select the RA sense, i.e., upward or downward." */
957 /* [TCASII]: "Based on the range and altitude tracks of the intruder, the CAS logic models the
958 * intruder's flight path from its present position to CPA. The CAS logic then models upward
959 * and downward sense RAs for own aircraft [..] to determine which sense provides the most
960 * vertical separation at CPA." */
961 float upSenseRelAltFt = verticalSeparation(+2000/60.0);
962 float downSenseRelAltFt = verticalSeparation(-2000/60.0);
963 if (fabs(upSenseRelAltFt) >= fabs(downSenseRelAltFt))
964 RASense = +1; // upward
966 RASense = -1; // downward
968 /* [TCASII]: "In encounters where either of the senses results in the TCAS aircraft crossing through
969 * the intruder's altitude, TCAS is designed to select the nonaltitude crossing sense if the
970 * noncrossing sense provides the desired vertical separation, known as ALIM, at CPA." */
971 /* [TCASII]: "If ALIM cannot be obtained in the nonaltitude crossing sense, an altitude
972 * crossing RA will be issued." */
974 (pCurrentThreat->relativeAltitudeFt > 200))
976 // threat is above and RA is crossing
977 if (fabs(downSenseRelAltFt) > pAlarmThresholds->TA.ALIM)
979 // non-crossing descend is sufficient
984 // keep crossing climb RA
990 (pCurrentThreat->relativeAltitudeFt < -200))
992 // threat is below and RA is crossing
993 if (fabs(upSenseRelAltFt) > pAlarmThresholds->TA.ALIM)
995 // non-crossing climb is sufficient
1000 // keep crossing descent RA
1004 // else: threat is at same altitude, keep optimal RA sense (non-crossing)
1006 pCurrentThreat->RASense = RASense;
1008 #ifdef FEATURE_TCAS_DEBUG_ADV_GENERATOR
1009 printf(" RASense: %i, crossing: %u, relAlt: %4.1f, upward separation: %4.1f, downward separation: %4.1f\n",
1011 pCurrentThreat->relativeAltitudeFt,
1012 upSenseRelAltFt,downSenseRelAltFt);
1016 /** Determine suitable resolution advisories. */
1018 TCAS::AdvisoryGenerator::resolution(int mode, int threatLevel, float rangeNm, float altFt,
1019 float heading, float velocityKt)
1021 int RAOption = OptionNone;
1022 int RA = AdvisoryIntrusion;
1024 // RAs are disabled under certain conditions
1025 if (threatLevel == ThreatRA)
1027 /* [TCASII]: "... less than 360 feet, TCAS considers the reporting aircraft
1028 * to be on the ground. If TCAS determines the intruder to be on the ground, it
1029 * inhibits the generation of advisories against this aircraft."*/
1031 threatLevel = ThreatTA;
1033 /* [EUROACAS]: "Certain RAs are inhibited at altitudes based on inputs from the radio altimeter:
1034 * [..] (c)1000ft (+/- 100ft) and below, all RAs are inhibited;" */
1035 if (pSelf->altFt < 1000)
1036 threatLevel = ThreatTA;
1038 // RAs only issued in mode "Auto" (= "TA/RA" mode)
1039 if (mode != SwitchAuto)
1040 threatLevel = ThreatTA;
1043 bool isCrossing = false;
1045 // determine suitable RAs
1046 if (threatLevel == ThreatRA)
1048 /* [TCASII]: "[..] a two step process is used to select the appropriate RA for the encounter
1049 * geometry. The first step in the process is to select the RA sense, i.e., upward or downward." */
1050 determineRAsense(RASense, isCrossing);
1052 /* second step: determine required strength */
1057 if ((pSelf->verticalFps < -1000/60.0)&&
1060 // currently descending, see if reducing current descent is sufficient
1061 float relAltFt = verticalSeparation(-500/60.0);
1062 if (relAltFt > pAlarmThresholds->TA.ALIM)
1063 RA |= AdvisoryAdjustVSpeed;
1065 RA |= AdvisoryClimb;
1067 RAOption |= OptionCrossingClimb;
1074 if ((pSelf->verticalFps > 1000/60.0)&&
1077 // currently climbing, see if reducing current climb is sufficient
1078 float relAltFt = verticalSeparation(500/60.0);
1079 if (relAltFt < -pAlarmThresholds->TA.ALIM)
1080 RA |= AdvisoryAdjustVSpeed;
1082 RA |= AdvisoryDescend;
1084 RAOption |= OptionCrossingDescent;
1088 /* [TCASII]: "When two TCAS-equipped aircraft are converging vertically with opposite rates
1089 * and are currently well separated in altitude, TCAS will first issue a vertical speed
1090 * limit (Negative) RA to reinforce the pilots' likely intention to level off at adjacent
1091 * flight levels." */
1094 /* [TCASII]: "[..] if the CAS logic determines that the response to a Positive RA has provided
1095 * ALIM feet of vertical separation before CPA, the initial RA will be weakened to either a
1096 * Do Not Descend RA (after an initial Climb RA) or a Do Not Climb RA (after an initial
1100 /* [TCASII]: "TCAS is designed to inhibit Increase Descent RAs below 1450 feet AGL; */
1102 /* [TCASII]: "Descend RAs below 1100 feet AGL;" (inhibited) */
1103 if (pSelf->altFt < 1100)
1105 RA &= ~AdvisoryDescend;
1106 //TODO Support "Do not descend" RA
1107 RA |= AdvisoryIntrusion;
1111 #ifdef FEATURE_TCAS_DEBUG_ADV_GENERATOR
1112 cout << " resolution advisory: " << RA << endl;
1115 ResolutionAdvisory newAdvisory;
1116 newAdvisory.RAOption = RAOption;
1117 newAdvisory.RA = RA;
1118 newAdvisory.threatLevel = threatLevel;
1119 tcas->advisoryCoordinator.add(newAdvisory);
1124 ///////////////////////////////////////////////////////////////////////////////
1125 // TCAS ///////////////////////////////////////////////////////////////////////
1126 ///////////////////////////////////////////////////////////////////////////////
1128 TCAS::TCAS(SGPropertyNode* pNode) :
1133 properties_handler(this),
1134 threatDetector(this),
1136 advisoryCoordinator(this),
1137 advisoryGenerator(this),
1140 for (int i = 0; i < pNode->nChildren(); ++i)
1142 SGPropertyNode* pChild = pNode->getChild(i);
1143 string cname = pChild->getName();
1144 string cval = pChild->getStringValue();
1146 if (cname == "name")
1148 else if (cname == "number")
1149 num = pChild->getIntValue();
1152 SG_LOG(SG_INSTR, SG_WARN, "Error in TCAS config logic");
1154 SG_LOG(SG_INSTR, SG_WARN, "Section = " << name);
1163 advisoryCoordinator.init();
1164 threatDetector.init();
1170 SGPropertyNode* node = fgGetNode(("/instrumentation/" + name).c_str(), num, true);
1172 nodeServiceable = node->getNode("serviceable", true);
1174 // TCAS mode selection (0=off, 1=standby, 2=TA only, 3=auto(TA/RA) )
1175 nodeModeSwitch = node->getNode("inputs/mode", true);
1177 nodeSelfTest = node->getNode("inputs/self-test", true);
1179 nodeSelfTest->setBoolValue(false);
1181 #ifdef FEATURE_TCAS_DEBUG_PROPERTIES
1182 SGPropertyNode* nodeDebug = node->getNode("debug", true);
1184 nodeDebugTrigger = nodeDebug->getNode("threat-trigger", true);
1185 nodeDebugRA = nodeDebug->getNode("threat-RA", true);
1186 nodeDebugThreat = nodeDebug->getNode("threat-level", true);
1188 nodeDebugTrigger->setBoolValue(false);
1189 nodeDebugRA->setIntValue(3);
1190 nodeDebugThreat->setIntValue(1);
1193 annunciator.bind(node);
1194 advisoryCoordinator.bind(node);
1200 properties_handler.unbind();
1203 /** Monitor traffic for safety threats. */
1205 TCAS::update(double dt)
1207 if (!nodeServiceable->getBoolValue())
1209 int mode = nodeModeSwitch->getIntValue();
1210 if (mode == SwitchOff)
1213 nextUpdateTime -= dt;
1214 if (nextUpdateTime <= 0.0 )
1216 nextUpdateTime = 1.0;
1218 // remove obsolete targets
1221 // get aircrafts current position/speed/heading
1222 threatDetector.update();
1224 // clear old threats
1225 advisoryCoordinator.clear();
1227 if (nodeSelfTest->getBoolValue())
1229 if (threatDetector.getVelocityKt() >= 40)
1231 // disable self-test when plane moves above taxiing speed
1232 nodeSelfTest->setBoolValue(false);
1238 // speed-up self test
1240 // no further TCAS processing during self-test
1245 #ifdef FEATURE_TCAS_DEBUG_PROPERTIES
1246 if (nodeDebugTrigger->getBoolValue())
1249 ResolutionAdvisory debugAdvisory;
1250 debugAdvisory.RAOption = OptionNone;
1251 debugAdvisory.RA = nodeDebugRA->getIntValue();
1252 debugAdvisory.threatLevel = nodeDebugThreat->getIntValue();
1253 advisoryCoordinator.add(debugAdvisory);
1258 SGPropertyNode* pAi = fgGetNode("/ai/models", true);
1260 // check all aircraft
1261 for (int i = pAi->nChildren() - 1; i >= -1; i--)
1263 SGPropertyNode* pModel = pAi->getChild(i);
1264 if ((pModel)&&(pModel->nChildren()))
1266 int threatLevel = threatDetector.checkThreat(mode, pModel);
1267 /* expose aircraft threat-level (to be used by other instruments,
1268 * i.e. TCAS display) */
1269 if (threatLevel==ThreatRA)
1270 pModel->setIntValue("tcas/ra-sense", -threatDetector.getRASense());
1271 pModel->setIntValue("tcas/threat-level", threatLevel);
1275 advisoryCoordinator.update(mode);
1277 annunciator.update();
1280 /** Run a single self-test iteration. */
1282 TCAS::selfTest(void)
1284 annunciator.update();
1285 if (annunciator.isPlaying())
1290 ResolutionAdvisory newAdvisory;
1291 newAdvisory.threatLevel = ThreatRA;
1292 newAdvisory.RA = AdvisoryClear;
1293 newAdvisory.RAOption = OptionNone;
1294 // TCAS audio is disabled below 500ft
1295 threatDetector.setAlt(501);
1297 // trigger various advisories
1298 switch(selfTestStep)
1301 newAdvisory.RA = AdvisoryIntrusion;
1302 newAdvisory.threatLevel = ThreatTA;
1305 newAdvisory.RA = AdvisoryClimb;
1308 newAdvisory.RA = AdvisoryClimb;
1309 newAdvisory.RAOption = OptionIncreaseClimb;
1312 newAdvisory.RA = AdvisoryClimb;
1313 newAdvisory.RAOption = OptionCrossingClimb;
1316 newAdvisory.RA = AdvisoryDescend;
1319 newAdvisory.RA = AdvisoryDescend;
1320 newAdvisory.RAOption = OptionIncreaseDescend;
1323 newAdvisory.RA = AdvisoryDescend;
1324 newAdvisory.RAOption = OptionCrossingDescent;
1327 newAdvisory.RA = AdvisoryAdjustVSpeed;
1330 newAdvisory.RA = AdvisoryMaintVSpeed;
1333 newAdvisory.RA = AdvisoryMonitorVSpeed;
1336 newAdvisory.threatLevel = ThreatNone;
1337 newAdvisory.RA = AdvisoryClear;
1340 annunciator.test(true);
1344 nodeSelfTest->setBoolValue(false);
1349 advisoryCoordinator.add(newAdvisory);
1350 advisoryCoordinator.update(SwitchAuto);
1355 ///////////////////////////////////////////////////////////////////////////////
1356 // TCAS::Tracker //////////////////////////////////////////////////////////////
1357 ///////////////////////////////////////////////////////////////////////////////
1359 TCAS::Tracker::Tracker(TCAS* _tcas) :
1369 TCAS::Tracker::update(void)
1371 currentTime = globals->get_sim_time_sec();
1376 // remove outdated targets
1377 TrackerTargets::iterator it = targets.begin();
1378 while (it != targets.end())
1380 TrackerTarget* pTarget = it->second;
1381 if (currentTime - pTarget->TAtimestamp > 10.0)
1383 TrackerTargets::iterator temp = it;
1385 #ifdef FEATURE_TCAS_DEBUG_TRACKER
1386 printf("target %s no longer a TA threat.\n",temp->first.c_str());
1388 targets.erase(temp->first);
1394 if ((pTarget->threatLevel == ThreatRA)&&
1395 (currentTime - pTarget->RAtimestamp > 7.0))
1397 pTarget->threatLevel = ThreatTA;
1398 #ifdef FEATURE_TCAS_DEBUG_TRACKER
1399 printf("target %s no longer an RA threat.\n",it->first.c_str());
1405 haveTargets = !targets.empty();
1410 TCAS::Tracker::add(const string callsign, int detectedLevel)
1412 TrackerTarget* pTarget = NULL;
1415 TrackerTargets::iterator it = targets.find(callsign);
1416 if (it != targets.end())
1418 pTarget = it->second;
1424 pTarget = new TrackerTarget();
1425 pTarget->TAtimestamp = 0;
1426 pTarget->RAtimestamp = 0;
1427 pTarget->threatLevel = 0;
1429 targets[callsign] = pTarget;
1430 #ifdef FEATURE_TCAS_DEBUG_TRACKER
1431 printf("new target: %s, level: %i\n",callsign.c_str(),detectedLevel);
1435 if (detectedLevel > pTarget->threatLevel)
1436 pTarget->threatLevel = detectedLevel;
1438 if (detectedLevel >= ThreatTA)
1439 pTarget->TAtimestamp = currentTime;
1441 if (detectedLevel >= ThreatRA)
1442 pTarget->RAtimestamp = currentTime;
1448 TCAS::Tracker::_isTracked(string callsign)
1450 return targets.find(callsign) != targets.end();
1454 TCAS::Tracker::getThreatLevel(string callsign)
1456 TrackerTargets::iterator it = targets.find(callsign);
1457 if (it != targets.end())
1458 return it->second->threatLevel;