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/math/sg_random.h>
104 #include <simgear/misc/sg_path.hxx>
105 #include <simgear/sound/soundmgr_openal.hxx>
106 #include <simgear/structure/exception.hxx>
110 #if defined( HAVE_VERSION_H ) && HAVE_VERSION_H
111 # include <Include/version.h>
113 # include <Include/no_version.h>
116 #include <Main/fg_props.hxx>
117 #include <Main/globals.hxx>
118 #include <AIModel/submodel.hxx>
119 #include "instrument_mgr.hxx"
122 ///////////////////////////////////////////////////////////////////////////////
123 // debug switches /////////////////////////////////////////////////////////////
124 ///////////////////////////////////////////////////////////////////////////////
125 //#define FEATURE_TCAS_DEBUG_ANNUNCIATOR
126 //#define FEATURE_TCAS_DEBUG_COORDINATOR
127 //#define FEATURE_TCAS_DEBUG_THREAT_DETECTOR
128 //#define FEATURE_TCAS_DEBUG_ADV_GENERATOR
129 //#define FEATURE_TCAS_DEBUG_PROPERTIES
131 ///////////////////////////////////////////////////////////////////////////////
132 // constants //////////////////////////////////////////////////////////////////
133 ///////////////////////////////////////////////////////////////////////////////
135 /** Sensitivity Level Definition and Alarm Thresholds (TCASII, Version 7)
136 * Max Own | |TA-level |RA-level
137 * Altitude(ft) | SL |Tau(s),DMOD(nm),ALIM(ft)|Tau(s),DMOD(nm),ALIM(ft) */
138 const TCAS::SensitivityLevel
139 TCAS::ThreatDetector::sensitivityLevels[] = {
140 { 1000, 2, {20, 0.30, 850}, {0, 0, 0 }},
141 { 2350, 3, {25, 0.33, 850}, {15, 0.20, 300}},
142 { 5000, 4, {30, 0.48, 850}, {20, 0.35, 300}},
143 {10000, 5, {40, 0.75, 850}, {25, 0.55, 350}},
144 {20000, 6, {45, 1.00, 850}, {30, 0.80, 400}},
145 {42000, 7, {48, 1.30, 850}, {35, 1.10, 600}},
146 {0, 8, {48, 1.30, 1200}, {35, 1.10, 700}}
149 ///////////////////////////////////////////////////////////////////////////////
150 // helpers ////////////////////////////////////////////////////////////////////
151 ///////////////////////////////////////////////////////////////////////////////
153 #define ADD_VOICE(Var, Sample, SayTwice) \
154 { make_voice(&Var); \
155 append(Var, Sample); \
156 if (SayTwice) append(Var, Sample); }
158 #define AVAILABLE_RA(Options, Advisory) (Advisory == (Advisory & Options))
160 #ifdef FEATURE_TCAS_DEBUG_THREAT_DETECTOR
161 /** calculate relative angle in between two headings */
163 relAngle(float Heading1, float Heading2)
165 Heading1 -= Heading2;
167 while (Heading1 >= 360.0)
170 while (Heading1 < 0.0)
177 /** calculate range and bearing of lat2/lon2 relative to lat1/lon1 */
179 calcRangeBearing(double lat1, double lon1, double lat2, double lon2,
180 double &rangeNm, double &bearing)
182 // calculate the bearing and range of the second pos from the first
183 double az2, distanceM;
184 geo_inverse_wgs_84(lat1, lon1, lat2, lon2, &bearing, &az2, &distanceM);
185 rangeNm = distanceM * SG_METER_TO_NM;
188 ///////////////////////////////////////////////////////////////////////////////
189 // VoicePlayer ////////////////////////////////////////////////////////////////
190 ///////////////////////////////////////////////////////////////////////////////
193 TCAS::VoicePlayer::init(void)
195 FGVoicePlayer::init();
197 ADD_VOICE(Voices.pTrafficTraffic, "traffic", true);
198 ADD_VOICE(Voices.pClear, "clear", false);
199 ADD_VOICE(Voices.pClimb, "climb", true);
200 ADD_VOICE(Voices.pClimbNow, "climb_now", true);
201 ADD_VOICE(Voices.pClimbCrossing, "climb_crossing", true);
202 ADD_VOICE(Voices.pClimbIncrease, "increase_climb", false);
203 ADD_VOICE(Voices.pDescend, "descend", true);
204 ADD_VOICE(Voices.pDescendNow, "descend_now", true);
205 ADD_VOICE(Voices.pDescendCrossing,"descend_crossing", true);
206 ADD_VOICE(Voices.pDescendIncrease,"increase_descent", false);
207 ADD_VOICE(Voices.pAdjustVSpeed, "adjust_vertical_speed", false);
208 ADD_VOICE(Voices.pMaintVSpeed, "maintain_vertical_speed", false);
209 ADD_VOICE(Voices.pMonitorVSpeed, "monitor_vertical_speed", false);
210 ADD_VOICE(Voices.pLevelOff, "level_off", false);
211 ADD_VOICE(Voices.pTestOk, "test_ok", false);
212 ADD_VOICE(Voices.pTestFail, "test_fail", false);
214 speaker.update_configuration();
217 /////////////////////////////////////////////////////////////////////////////
218 // TCAS::Annunciator ////////////////////////////////////////////////////////
219 /////////////////////////////////////////////////////////////////////////////
221 TCAS::Annunciator::Annunciator(TCAS* tcas) :
228 void TCAS::Annunciator::clear(void)
230 previous.threatLevel = ThreatNone;
231 previous.RA = AdvisoryClear;
232 previous.RAOption = OptionNone;
237 TCAS::Annunciator::bind(SGPropertyNode* node)
239 voicePlayer.bind(node, "Sounds/tcas/");
243 TCAS::Annunciator::init(void)
245 //TODO link to GPWS module/audio-on signal must be configurable
246 nodeGpwsAlertOn = fgGetNode("/instrumentation/mk-viii/outputs/discretes/audio-on", true);
251 TCAS::Annunciator::update(void)
253 voicePlayer.update();
255 /* [TCASII]: "The priority scheme gives ground proximity warning systems (GPWS)
256 * a higher annunciation priority than a TCAS alert. TCAS aural annunciation will
257 * be inhibited during the time that a GPWS alert is active." */
258 if (nodeGpwsAlertOn->getBoolValue())
261 voicePlayer.resume();
264 /** Trigger voice sample for current alert. */
266 TCAS::Annunciator::trigger(const ResolutionAdvisory& current, bool revertedRA)
269 int RAOption = current.RAOption;
271 if (RA == AdvisoryClear)
273 if (previous.RA != AdvisoryClear)
275 voicePlayer.play(voicePlayer.Voices.pClear, VoicePlayer::PLAY_NOW);
282 if (previous.RA == AdvisoryClear)
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)
345 // don't repeat annunciation
350 voicePlayer.play(pVoice);
352 #ifdef FEATURE_TCAS_DEBUG_ANNUNCIATOR
353 cout << "Annunciating TCAS RA " << RA << endl;
358 TCAS::Annunciator::test(bool testOk)
361 voicePlayer.play(voicePlayer.Voices.pTestOk);
363 voicePlayer.play(voicePlayer.Voices.pTestFail);
366 /////////////////////////////////////////////////////////////////////////////
367 // TCAS::AdvisoryCoordinator ////////////////////////////////////////////////
368 /////////////////////////////////////////////////////////////////////////////
370 TCAS::AdvisoryCoordinator::AdvisoryCoordinator(TCAS* _tcas) :
378 TCAS::AdvisoryCoordinator::init(void)
385 TCAS::AdvisoryCoordinator::bind(SGPropertyNode* node)
387 nodeTAWarning = node->getNode("outputs/traffic-alert", true);
388 nodeTAWarning->setBoolValue(false);
392 TCAS::AdvisoryCoordinator::clear(void)
394 current.threatLevel = ThreatNone;
395 current.RA = AdvisoryClear;
396 current.RAOption = OptionNone;
399 /** Add all suitable resolution advisories for a single threat. */
401 TCAS::AdvisoryCoordinator::add(const ResolutionAdvisory& newAdvisory)
403 if (newAdvisory.RA == AdvisoryClear)
406 if ((current.RA == AdvisoryClear)||
407 (current.threatLevel == ThreatTA))
409 current = newAdvisory;
413 // combine with other advisories so far
414 current.RA &= newAdvisory.RA;
415 // remember any advisory modifier
416 current.RAOption |= newAdvisory.RAOption;
420 /** Pick and trigger suitable resolution advisory. */
422 TCAS::AdvisoryCoordinator::update(int mode)
424 bool revertedRA = false; // has advisory changed?
425 double currentTime = globals->get_sim_time_sec();
427 if (current.RA == AdvisoryClear)
429 // filter: wait 5 seconds after last TA/RA before announcing TA clearance
430 if ((previous.RA != AdvisoryClear)&&
431 (currentTime - lastTATime < 5.0))
438 #ifdef FEATURE_TCAS_DEBUG_COORDINATOR
439 cout << "TCAS::Annunciator::update: previous: " << previous.RA << ", new: " << current.RA << endl;
442 lastTATime = currentTime;
443 if ((previous.RA == AdvisoryClear)||
444 (previous.RA == AdvisoryIntrusion)||
445 ((current.RA & previous.RA) != previous.RA))
447 // no RA yet, or we can't keep previous RA: pick one - in order of priority
449 if (AVAILABLE_RA(current.RA, AdvisoryMonitorVSpeed))
451 // prio 1: monitor vertical speed only
452 current.RA = AdvisoryMonitorVSpeed;
455 if (AVAILABLE_RA(current.RA, AdvisoryMaintVSpeed))
457 // prio 2: maintain vertical speed
458 current.RA = AdvisoryMaintVSpeed;
461 if (AVAILABLE_RA(current.RA, AdvisoryAdjustVSpeed))
463 // prio 3: adjust vertical speed (TCAS II 7.0 only)
464 current.RA = AdvisoryAdjustVSpeed;
467 if (AVAILABLE_RA(current.RA, AdvisoryLevelOff))
469 // prio 3: adjust vertical speed (TCAS II 7.1 only, [EUROACAS]: CP115)
470 current.RA = AdvisoryLevelOff;
473 if (AVAILABLE_RA(current.RA, AdvisoryClimb))
476 current.RA = AdvisoryClimb;
479 if (AVAILABLE_RA(current.RA, AdvisoryDescend))
482 current.RA = AdvisoryDescend;
486 // no RA, issue a TA only
487 current.RA = AdvisoryIntrusion;
490 // check if earlier advisory was reverted
491 revertedRA = ((previous.RA != current.RA)&&
493 (previous.RA != AdvisoryIntrusion));
498 current.RA = previous.RA;
502 /* [TCASII]: "Aural annunciations are inhibited below 500+/-100 feet AGL." */
503 if ((tcas->threatDetector.getAlt() > 500)&&
504 (mode >= SwitchTaOnly))
505 tcas->annunciator.trigger(current, revertedRA);
507 if (current.RA == AdvisoryClear)
509 /* explicitly clear traffic alert (since aural annunciation disabled) */
510 tcas->annunciator.clear();
515 /* [TCASII] "[..] also performs the function of setting flags that control the displays.
516 * The traffic display, the RA display, [..] use these flags to alert the pilot to
517 * the presence of TAs and RAs." */
518 nodeTAWarning->setBoolValue(current.RA != AdvisoryClear);
521 ///////////////////////////////////////////////////////////////////////////////
522 // TCAS::ThreatDetector ///////////////////////////////////////////////////////
523 ///////////////////////////////////////////////////////////////////////////////
525 TCAS::ThreatDetector::ThreatDetector(TCAS* _tcas) :
527 pAlarmThresholds(&sensitivityLevels[0])
533 TCAS::ThreatDetector::init(void)
535 nodeLat = fgGetNode("/position/latitude-deg", true);
536 nodeLon = fgGetNode("/position/longitude-deg", true);
537 nodeAlt = fgGetNode("/position/altitude-ft", true);
538 nodeHeading = fgGetNode("/orientation/heading-deg", true);
539 nodeVelocity = fgGetNode("/velocities/airspeed-kt", true);
540 nodeVerticalFps = fgGetNode("/velocities/vertical-speed-fps", true);
542 tcas->advisoryGenerator.init(&self,¤tThreat);
545 /** Update local position and threat sensitivity levels. */
547 TCAS::ThreatDetector::update(void)
549 // update local position
550 self.lat = nodeLat->getDoubleValue();
551 self.lon = nodeLon->getDoubleValue();
552 self.altFt = nodeAlt->getDoubleValue();
553 self.heading = nodeHeading->getDoubleValue();
554 self.velocityKt = nodeVelocity->getDoubleValue();
555 self.verticalFps = nodeVerticalFps->getDoubleValue();
559 // determine current altitude's "Sensitivity Level Definition and Alarm Thresholds"
561 for (sl=0;((self.altFt > sensitivityLevels[sl].maxAltitude)&&
562 (sensitivityLevels[sl].maxAltitude));sl++);
563 pAlarmThresholds = &sensitivityLevels[sl];
564 tcas->advisoryGenerator.setAlarmThresholds(pAlarmThresholds);
567 /** Check if plane's transponder is enabled. */
569 TCAS::ThreatDetector::checkTransponder(const SGPropertyNode* pModel, float velocityKt)
571 const string name = pModel->getName();
572 if (name != "multiplayer" && name != "aircraft")
574 // assume non-MP/non-AI planes (e.g. ships) have no transponder
580 /* assume all pilots have their transponder switched off while taxiing/parking
588 /** Check if plane is a threat. */
590 TCAS::ThreatDetector::checkThreat(int mode, const SGPropertyNode* pModel)
594 float velocityKt = pModel->getDoubleValue("velocities/true-airspeed-kt");
596 if (!checkTransponder(pModel, velocityKt))
597 return ThreatInvisible;
599 int threatLevel = ThreatNone;
600 float altFt = pModel->getDoubleValue("position/altitude-ft");
601 currentThreat.relativeAltitudeFt = altFt - self.altFt;
603 // save computation time: don't care when relative altitude is excessive
604 if (fabs(currentThreat.relativeAltitudeFt) > 10000)
607 // position data of current intruder
608 double lat = pModel->getDoubleValue("position/latitude-deg");
609 double lon = pModel->getDoubleValue("position/longitude-deg");
610 float heading = pModel->getDoubleValue("orientation/true-heading-deg");
612 double distanceNm, bearing;
613 calcRangeBearing(self.lat, self.lon, lat, lon, distanceNm, bearing);
615 // save computation time: don't care for excessive distances (also captures NaNs...)
616 if ((distanceNm > 10)||(distanceNm < 0))
619 // first stage: vertical movement
620 currentThreat.verticalFps = pModel->getDoubleValue("velocities/vertical-speed-fps");
622 /* Detect proximity targets
623 * [TCASII]: "Any target that is less than 6 nmi in range and within +/-1200ft
624 * vertically, but that does not meet the intruder or threat criteria." */
625 if ((distanceNm < 6)&&
626 (fabs(currentThreat.relativeAltitudeFt) < 1200))
628 // at least a proximity target
629 threatLevel = ThreatProximity;
632 checkVerticalThreat();
634 // stop processing when no vertical threat
635 if (!currentThreat.verticalTA)
638 // second stage: horizontal movement
639 horizontalThreat(bearing, distanceNm, heading, velocityKt);
641 // no horizontal threat?
642 if (!currentThreat.horizontalTA)
645 if ((currentThreat.horizontalTau < 0)||
646 (currentThreat.verticalTau < 0))
648 // do not trigger new alerts when Tau is negative, but keep existing alerts
649 int previousThreatLevel = pModel->getIntValue("tcas/threat-level", 0);
650 if (previousThreatLevel == 0)
654 #ifdef FEATURE_TCAS_DEBUG_THREAT_DETECTOR
655 cout << "#" << checkCount << ": " << pModel->getStringValue("callsign") << endl;
658 threatLevel = ThreatTA;
659 /* at least a TA-level threat, may also have a RA-level threat...
660 * [TCASII]: "For either a TA or an RA to be issued, both the range and
661 * vertical criteria, in terms of tau or the fixed thresholds, must be
662 * satisfied only one of the criteria is satisfied, TCAS will not issue
664 if (currentThreat.horizontalRA && currentThreat.verticalRA)
665 threatLevel = ThreatRA;
667 // find all resolution options for this conflict
668 tcas->advisoryGenerator.resolution(mode, threatLevel, distanceNm, altFt, heading, velocityKt);
670 #ifdef FEATURE_TCAS_DEBUG_THREAT_DETECTOR
671 printf(" threat: distance: %4.1f, bearing: %4.1f, alt: %5.1f, velocity: %4.1f, heading: %4.1f, vspeed: %4.1f, "
672 "own alt: %5.1f, own heading: %4.1f, own velocity: %4.1f, vertical tau: %3.2f"
673 //", closing speed: %f"
675 distanceNm, relAngle(bearing, self.heading), altFt, velocityKt, heading, currentThreat.verticalFps,
676 self.altFt, self.heading, self.velocityKt
677 //, currentThreat.closingSpeedKt
678 ,currentThreat.verticalTau
685 /** Check if plane is a vertical threat. */
687 TCAS::ThreatDetector::checkVerticalThreat(void)
689 // calculate relative vertical speed and altitude
690 float dV = self.verticalFps - currentThreat.verticalFps;
691 float dA = currentThreat.relativeAltitudeFt;
693 currentThreat.verticalTA = false;
694 currentThreat.verticalRA = false;
695 currentThreat.verticalTau = 0;
697 /* [TCASII]: "The vertical tau is equal to the altitude separation (feet)
698 * divided by the combined vertical speed of the two aircraft (feet/minute)
704 /* [TCASII]: "When the combined vertical speed of the TCAS and the intruder aircraft
705 * is low, TCAS will use a fixed-altitude threshold to determine whether a TA or
706 * an RA should be issued." */
707 if ((fabs(dV) < 3.0)||
708 ((tau < 0) && (tau > -5)))
710 /* vertical closing speed is low (below 180fpm/3fps), check
711 * fixed altitude range. */
712 float abs_dA = fabs(dA);
713 if (abs_dA < pAlarmThresholds->RA.ALIM)
715 // continuous intrusion at RA-level
716 currentThreat.verticalTA = true;
717 currentThreat.verticalRA = true;
720 if (abs_dA < pAlarmThresholds->TA.ALIM)
722 // continuous intrusion: with TA-level, but no RA-threat
723 currentThreat.verticalTA = true;
725 // else: no RA/TA threat
729 if ((tau < pAlarmThresholds->TA.Tau)&&
732 currentThreat.verticalTA = true;
733 currentThreat.verticalRA = (tau<pAlarmThresholds->RA.Tau);
736 currentThreat.verticalTau = tau;
738 #ifdef FEATURE_TCAS_DEBUG_THREAT_DETECTOR
739 if (currentThreat.verticalTA)
740 printf(" vertical dV=%f (%f-%f), dA=%f\n", dV, self.verticalFps, currentThreat.verticalFps, dA);
744 /** Check if plane is a horizontal threat. */
746 TCAS::ThreatDetector::horizontalThreat(float bearing, float distanceNm, float heading, float velocityKt)
749 float vxKt = sin(heading*SGD_DEGREES_TO_RADIANS)*velocityKt - sin(self.heading*SGD_DEGREES_TO_RADIANS)*self.velocityKt;
750 float vyKt = cos(heading*SGD_DEGREES_TO_RADIANS)*velocityKt - cos(self.heading*SGD_DEGREES_TO_RADIANS)*self.velocityKt;
752 // calculate horizontal closing speed
753 float closingSpeedKt2 = vxKt*vxKt+vyKt*vyKt;
754 float closingSpeedKt = sqrt(closingSpeedKt2);
756 /* [TCASII]: "The range tau is equal to the slant range (nmi) divided by the closing speed
757 * (knots) multiplied by 3600."
758 * => calculate allowed slant range (nmi) based on known maximum tau */
759 float TA_rangeNm = (pAlarmThresholds->TA.Tau*closingSpeedKt)/3600;
760 float RA_rangeNm = (pAlarmThresholds->RA.Tau*closingSpeedKt)/3600;
762 if (closingSpeedKt < 100)
764 /* [TCASII]: "In events where the rate of closure is very low, [..]
765 * an intruder aircraft can come very close in range without crossing the
766 * range tau boundaries [..]. To provide protection in these types of
767 * advisories, the range tau boundaries are modified [..] to use
768 * a fixed-range threshold to issue TAs and RAs in these slow closure
770 TA_rangeNm += (100.0-closingSpeedKt)*(pAlarmThresholds->TA.DMOD/100.0);
771 RA_rangeNm += (100.0-closingSpeedKt)*(pAlarmThresholds->RA.DMOD/100.0);
773 if (TA_rangeNm < pAlarmThresholds->TA.DMOD)
774 TA_rangeNm = pAlarmThresholds->TA.DMOD;
775 if (RA_rangeNm < pAlarmThresholds->RA.DMOD)
776 RA_rangeNm = pAlarmThresholds->RA.DMOD;
778 currentThreat.horizontalTA = (distanceNm < TA_rangeNm);
779 currentThreat.horizontalRA = (distanceNm < RA_rangeNm);
780 currentThreat.horizontalTau = -1;
782 if ((currentThreat.horizontalRA)&&
783 (currentThreat.verticalRA))
785 /* an RA will be issued. Prepare extra data for the
786 * traffic resolution stage, i.e. calculate
787 * exact time tau to horizontal CPA.
790 /* relative position of intruder is
793 * horizontal distance to intruder is r(t)
794 * r(t) = sqrt( Sx(t)^2 + Sy(t)^2 )
795 * => horizontal CPA at time t=tau, where r(t) has minimum
796 * r2(t) := r^2(t) = Sx(t)^2 + Sy(t)^2
797 * since r(t)>0 for all t => minimum of r(t) is also minimum of r2(t)
798 * => (d/dt) r2(t) = r2'(t) is 0 for t=tau
799 * r2(t) = ((Sx(t)^2 + Sy(t))^2) = c + b*t + a*t^2
800 * => r2'(t) = b + a*2*t
802 * r2'(tau) = 0 = b + 2*a*tau
805 float sx = sin(bearing*SGD_DEGREES_TO_RADIANS)*distanceNm;
806 float sy = cos(bearing*SGD_DEGREES_TO_RADIANS)*distanceNm;
807 float vx = vxKt * (SG_KT_TO_MPS*SG_METER_TO_NM);
808 float vy = vyKt * (SG_KT_TO_MPS*SG_METER_TO_NM);
809 float a = vx*vx + vy*vy;
810 float b = 2*(sx*vx + sy*vy);
814 #ifdef FEATURE_TCAS_DEBUG_THREAT_DETECTOR
815 printf(" Time to horizontal CPA: %4.2f\n",tau);
817 if (tau > pAlarmThresholds->RA.Tau)
818 tau = pAlarmThresholds->RA.Tau;
820 // remember time to horizontal CPA
821 currentThreat.horizontalTau = tau;
825 /** Test threat detection logic. */
827 TCAS::ThreatDetector::unitTest(void)
829 pAlarmThresholds = &sensitivityLevels[1];
832 self.verticalFps = 0;
834 cout << "identical altitude and vspeed " << endl;
835 checkVerticalThreat(self.altFt, self.verticalFps);
836 cout << "1000ft alt offset, dV=100 " << endl;
837 checkVerticalThreat(self.altFt+1000, 100);
838 cout << "-1000ft alt offset, dV=100 " << endl;
839 checkVerticalThreat(self.altFt-1000, 100);
840 cout << "3000ft alt offset, dV=10 " << endl;
841 checkVerticalThreat(self.altFt+3000, 10);
842 cout << "500ft alt offset, dV=100 " << endl;
843 checkVerticalThreat(self.altFt+500, 100);
844 cout << "500ft alt offset, dV=-100 " << endl;
845 checkVerticalThreat(self.altFt+500, -100);
850 cout << "10nm behind, overtaking with 1Nm/s" << endl;
851 horizontalThreat(-180, 10, 0, 1/(SG_KT_TO_MPS*SG_METER_TO_NM));
853 cout << "10nm ahead, departing with 1Nm/s" << endl;
854 horizontalThreat(0, 20, 0, 1/(SG_KT_TO_MPS*SG_METER_TO_NM));
857 self.velocityKt = 1/(SG_KT_TO_MPS*SG_METER_TO_NM);
858 cout << "10nm behind, overtaking with 1Nm/s at 90 degrees" << endl;
859 horizontalThreat(-90, 20, 90, 2/(SG_KT_TO_MPS*SG_METER_TO_NM));
862 self.velocityKt = 1/(SG_KT_TO_MPS*SG_METER_TO_NM);
863 cout << "10nm behind, overtaking with 1Nm/s at 20 degrees" << endl;
864 horizontalThreat(200, 20, 20, 2/(SG_KT_TO_MPS*SG_METER_TO_NM));
868 ///////////////////////////////////////////////////////////////////////////////
869 // TCAS::AdvisoryGenerator ////////////////////////////////////////////////////
870 ///////////////////////////////////////////////////////////////////////////////
872 TCAS::AdvisoryGenerator::AdvisoryGenerator(TCAS* _tcas) :
875 pCurrentThreat(NULL),
876 pAlarmThresholds(NULL)
881 TCAS::AdvisoryGenerator::init(const LocalInfo* _pSelf, const ThreatInfo* _pCurrentThreat)
883 pCurrentThreat = _pCurrentThreat;
888 TCAS::AdvisoryGenerator::setAlarmThresholds(const SensitivityLevel* _pAlarmThresholds)
890 pAlarmThresholds = _pAlarmThresholds;
893 /** Calculate projected vertical separation at horizontal CPA. */
895 TCAS::AdvisoryGenerator::verticalSeparation(float newVerticalFps)
897 // calculate relative vertical speed and altitude
898 float dV = pCurrentThreat->verticalFps - newVerticalFps;
899 float tau = pCurrentThreat->horizontalTau;
900 // don't use negative tau to project future separation...
903 return pCurrentThreat->relativeAltitudeFt + tau * dV;
906 /** Determine RA sense. */
908 TCAS::AdvisoryGenerator::determineRAsense(int& RASense, bool& isCrossing)
910 /* [TCASII]: "[..] a two step process is used to select the appropriate RA for the encounter
911 * geometry. The first step in the process is to select the RA sense, i.e., upward or downward." */
915 /* [TCASII]: "Based on the range and altitude tracks of the intruder, the CAS logic models the
916 * intruder's flight path from its present position to CPA. The CAS logic then models upward
917 * and downward sense RAs for own aircraft [..] to determine which sense provides the most
918 * vertical separation at CPA." */
919 float upSenseRelAltFt = verticalSeparation(+2000/60.0);
920 float downSenseRelAltFt = verticalSeparation(-2000/60.0);
921 if (fabs(upSenseRelAltFt) >= fabs(downSenseRelAltFt))
922 RASense = +1; // upward
924 RASense = -1; // downward
926 /* [TCASII]: "In encounters where either of the senses results in the TCAS aircraft crossing through
927 * the intruder's altitude, TCAS is designed to select the nonaltitude crossing sense if the
928 * noncrossing sense provides the desired vertical separation, known as ALIM, at CPA." */
929 /* [TCASII]: "If ALIM cannot be obtained in the nonaltitude crossing sense, an altitude
930 * crossing RA will be issued." */
932 (pCurrentThreat->relativeAltitudeFt > 200))
934 // threat is above and RA is crossing
935 if (fabs(downSenseRelAltFt) > pAlarmThresholds->TA.ALIM)
937 // non-crossing descend is sufficient
942 // keep crossing climb RA
948 (pCurrentThreat->relativeAltitudeFt < -200))
950 // threat is below and RA is crossing
951 if (fabs(upSenseRelAltFt) > pAlarmThresholds->TA.ALIM)
953 // non-crossing climb is sufficient
958 // keep crossing descent RA
962 // else: threat is at same altitude, keep optimal RA sense (non-crossing)
964 #ifdef FEATURE_TCAS_DEBUG_ADV_GENERATOR
965 printf(" RASense: %i, crossing: %u, relAlt: %4.1f, upward separation: %4.1f, downward separation: %4.1f\n",
967 pCurrentThreat->relativeAltitudeFt,
968 upSenseRelAltFt,downSenseRelAltFt);
972 /** Determine suitable resolution advisories. */
974 TCAS::AdvisoryGenerator::resolution(int mode, int threatLevel, float rangeNm, float altFt,
975 float heading, float velocityKt)
977 int RAOption = OptionNone;
978 int RA = AdvisoryIntrusion;
980 // RAs are disabled under certain conditions
981 if (threatLevel == ThreatRA)
983 /* [TCASII]: "... less than 360 feet, TCAS considers the reporting aircraft
984 * to be on the ground. If TCAS determines the intruder to be on the ground, it
985 * inhibits the generation of advisories against this aircraft."*/
987 threatLevel = ThreatTA;
989 /* [EUROACAS]: "Certain RAs are inhibited at altitudes based on inputs from the radio altimeter:
990 * [..] (c)1000ft (+/- 100ft) and below, all RAs are inhibited;" */
991 if (pSelf->altFt < 1000)
992 threatLevel = ThreatTA;
994 // RAs only issued in mode "Auto" (= "TA/RA" mode)
995 if (mode != SwitchAuto)
996 threatLevel = ThreatTA;
999 bool isCrossing = false;
1001 // determine suitable RAs
1002 if (threatLevel == ThreatRA)
1004 /* [TCASII]: "[..] a two step process is used to select the appropriate RA for the encounter
1005 * geometry. The first step in the process is to select the RA sense, i.e., upward or downward." */
1006 determineRAsense(RASense, isCrossing);
1008 /* second step: determine required strength */
1013 if ((pSelf->verticalFps < -1000/60.0)&&
1016 // currently descending, see if reducing current descent is sufficient
1017 float relAltFt = verticalSeparation(-500/60.0);
1018 if (relAltFt > pAlarmThresholds->TA.ALIM)
1019 RA |= AdvisoryAdjustVSpeed;
1021 RA |= AdvisoryClimb;
1023 RAOption |= OptionCrossingClimb;
1030 if ((pSelf->verticalFps > 1000/60.0)&&
1033 // currently climbing, see if reducing current climb is sufficient
1034 float relAltFt = verticalSeparation(500/60.0);
1035 if (relAltFt < -pAlarmThresholds->TA.ALIM)
1036 RA |= AdvisoryAdjustVSpeed;
1038 RA |= AdvisoryDescend;
1040 RAOption |= OptionCrossingDescent;
1044 /* [TCASII]: "When two TCAS-equipped aircraft are converging vertically with opposite rates
1045 * and are currently well separated in altitude, TCAS will first issue a vertical speed
1046 * limit (Negative) RA to reinforce the pilots' likely intention to level off at adjacent
1047 * flight levels." */
1050 /* [TCASII]: "[..] if the CAS logic determines that the response to a Positive RA has provided
1051 * ALIM feet of vertical separation before CPA, the initial RA will be weakened to either a
1052 * Do Not Descend RA (after an initial Climb RA) or a Do Not Climb RA (after an initial
1056 /* [TCASII]: "TCAS is designed to inhibit Increase Descent RAs below 1450 feet AGL; */
1058 /* [TCASII]: "Descend RAs below 1100 feet AGL;" (inhibited) */
1059 if (pSelf->altFt < 1100)
1061 RA &= ~AdvisoryDescend;
1062 //TODO Support "Do not descend" RA
1063 RA |= AdvisoryIntrusion;
1067 #ifdef FEATURE_TCAS_DEBUG_ADV_GENERATOR
1068 cout << " resolution advisory: " << RA << endl;
1071 ResolutionAdvisory newAdvisory;
1072 newAdvisory.RAOption = RAOption;
1073 newAdvisory.RA = RA;
1074 newAdvisory.threatLevel = threatLevel;
1075 tcas->advisoryCoordinator.add(newAdvisory);
1080 ///////////////////////////////////////////////////////////////////////////////
1081 // TCAS ///////////////////////////////////////////////////////////////////////
1082 ///////////////////////////////////////////////////////////////////////////////
1084 TCAS::TCAS(SGPropertyNode* pNode) :
1089 properties_handler(this),
1090 threatDetector(this),
1091 advisoryCoordinator(this),
1092 advisoryGenerator(this),
1095 for (int i = 0; i < pNode->nChildren(); ++i)
1097 SGPropertyNode* pChild = pNode->getChild(i);
1098 string cname = pChild->getName();
1099 string cval = pChild->getStringValue();
1101 if (cname == "name")
1103 else if (cname == "number")
1104 num = pChild->getIntValue();
1107 SG_LOG(SG_INSTR, SG_WARN, "Error in TCAS config logic");
1109 SG_LOG(SG_INSTR, SG_WARN, "Section = " << name);
1118 advisoryCoordinator.init();
1119 threatDetector.init();
1125 SGPropertyNode* node = fgGetNode(("/instrumentation/" + name).c_str(), num, true);
1127 nodeServiceable = node->getNode("serviceable", true);
1129 // TCAS mode selection (0=off, 1=standby, 2=TA only, 3=auto(TA/RA) )
1130 nodeModeSwitch = node->getNode("inputs/mode", true);
1132 nodeSelfTest = node->getNode("inputs/self-test", true);
1134 nodeSelfTest->setBoolValue(false);
1136 #ifdef FEATURE_TCAS_DEBUG_PROPERTIES
1137 SGPropertyNode* nodeDebug = node->getNode("debug", true);
1139 nodeDebugTrigger = nodeDebug->getNode("threat-trigger", true);
1140 nodeDebugRA = nodeDebug->getNode("threat-RA", true);
1141 nodeDebugThreat = nodeDebug->getNode("threat-level", true);
1143 nodeDebugTrigger->setBoolValue(false);
1144 nodeDebugRA->setIntValue(3);
1145 nodeDebugThreat->setIntValue(1);
1148 annunciator.bind(node);
1149 advisoryCoordinator.bind(node);
1155 properties_handler.unbind();
1158 /** Monitor traffic for safety threats. */
1160 TCAS::update(double dt)
1162 if (!nodeServiceable->getBoolValue())
1164 int mode = nodeModeSwitch->getIntValue();
1165 if (mode == SwitchOff)
1168 nextUpdateTime -= dt;
1169 if (nextUpdateTime <= 0.0 )
1171 nextUpdateTime = 1.0;
1173 // get aircrafts current position/speed/heading
1174 threatDetector.update();
1176 // clear old threats
1177 advisoryCoordinator.clear();
1179 if (nodeSelfTest->getBoolValue())
1181 if (threatDetector.getVelocityKt() >= 40)
1183 // disable self-test when plane moves above taxiing speed
1184 nodeSelfTest->setBoolValue(false);
1190 // speed-up self test
1192 // no further TCAS processing during self-test
1197 #ifdef FEATURE_TCAS_DEBUG_PROPERTIES
1198 if (nodeDebugTrigger->getBoolValue())
1201 ResolutionAdvisory debugAdvisory;
1202 debugAdvisory.RAOption = OptionNone;
1203 debugAdvisory.RA = nodeDebugRA->getIntValue();
1204 debugAdvisory.threatLevel = nodeDebugThreat->getIntValue();
1205 advisoryCoordinator.add(debugAdvisory);
1210 SGPropertyNode* pAi = fgGetNode("/ai/models", true);
1212 // check all aircraft
1213 for (int i = pAi->nChildren() - 1; i >= -1; i--)
1215 SGPropertyNode* pModel = pAi->getChild(i);
1216 if ((pModel)&&(pModel->nChildren()))
1218 int threatLevel = threatDetector.checkThreat(mode, pModel);
1219 /* expose aircraft threat-level (to be used by other instruments,
1220 * i.e. TCAS display) */
1221 pModel->setIntValue("tcas/threat-level", threatLevel);
1225 advisoryCoordinator.update(mode);
1227 annunciator.update();
1230 /** Run a single self-test iteration. */
1232 TCAS::selfTest(void)
1234 annunciator.update();
1235 if (annunciator.isPlaying())
1240 ResolutionAdvisory newAdvisory;
1241 newAdvisory.threatLevel = ThreatRA;
1242 newAdvisory.RA = AdvisoryClear;
1243 newAdvisory.RAOption = OptionNone;
1244 // TCAS audio is disabled below 500ft
1245 threatDetector.setAlt(501);
1247 // trigger various advisories
1248 switch(selfTestStep)
1251 newAdvisory.RA = AdvisoryIntrusion;
1252 newAdvisory.threatLevel = ThreatTA;
1255 newAdvisory.RA = AdvisoryClimb;
1258 newAdvisory.RA = AdvisoryClimb;
1259 newAdvisory.RAOption = OptionIncreaseClimb;
1262 newAdvisory.RA = AdvisoryClimb;
1263 newAdvisory.RAOption = OptionCrossingClimb;
1266 newAdvisory.RA = AdvisoryDescend;
1269 newAdvisory.RA = AdvisoryDescend;
1270 newAdvisory.RAOption = OptionIncreaseDescend;
1273 newAdvisory.RA = AdvisoryDescend;
1274 newAdvisory.RAOption = OptionCrossingDescent;
1277 newAdvisory.RA = AdvisoryAdjustVSpeed;
1280 newAdvisory.RA = AdvisoryMaintVSpeed;
1283 newAdvisory.RA = AdvisoryMonitorVSpeed;
1286 newAdvisory.threatLevel = ThreatNone;
1287 newAdvisory.RA = AdvisoryClear;
1290 annunciator.test(true);
1294 nodeSelfTest->setBoolValue(false);
1299 advisoryCoordinator.add(newAdvisory);
1300 advisoryCoordinator.update(SwitchAuto);