]> git.mxchange.org Git - flightgear.git/blob - src/Instrumentation/tcas.cxx
#346 related: missing status message for property server
[flightgear.git] / src / Instrumentation / tcas.cxx
1 // tcas.cxx -- Traffic Alert and Collision Avoidance System (TCAS) Emulation
2 //
3 // Written by Thorsten Brehm, started December 2010.
4 //
5 // Copyright (C) 2010 Thorsten Brehm - brehmt (at) gmail com
6 //
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.
11 //
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.
16 //
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.
20 //
21 ///////////////////////////////////////////////////////////////////////////////
22
23 /* References:
24  *
25  *  [TCASII] Introduction to TCAS II Version 7, Federal Aviation Administration, November 2000
26  *           http://www.arinc.com/downloads/tcas/tcas.pdf
27  *
28  *  [EUROACAS] Eurocontrol Airborne Collision Avoidance System (ACAS),
29  *           http://www.eurocontrol.int/msa/public/standard_page/ACAS_Startpage.html
30  *
31  * Glossary:
32  *
33  *  ALIM: Altitude Limit
34  *
35  *  CPA: Closest point of approach as computed from a threat's range and range rate.
36  *
37  *  DMOD: Distance MODification
38  *
39  *  Intruder: A target that has satisfied the traffic detection criteria.
40  *
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.
43  *
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.
47  *
48  *  SL: Sensitivity Level. A value used in defining the size of the protected volume
49  *      around the own aircraft.
50  *
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.
53  *
54  *  Tau: Approximation of the time, in seconds, to CPA or to the aircraft being at the
55  *       same altitude.
56  *
57  *  TCAS: Traffic alert and Collision Avoidance System
58  */
59
60 /* Module properties:
61  *
62  *   serviceable             enable/disable TCAS processing
63  *   
64  *   voice/file-prefix       path (and optional prefix) for sound sample files
65  *                           (only evaluated at start-up)  
66  *
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
69  *
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)
73  *
74  *   speaker/max-dist        Max. distance where speaker is heard
75  *   speaker/reference-dist  Distance to pilot
76  *   speaker/volume          Volume at reference distance
77  *
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)
81  */
82
83 #ifdef _MSC_VER
84 #  pragma warning( disable: 4355 )
85 #endif
86
87 #ifdef HAVE_CONFIG_H
88 #  include <config.h>
89 #endif
90
91 #include <stdio.h>
92 #include <string.h>
93 #include <assert.h>
94 #include <math.h>
95
96 #include <string>
97 #include <sstream>
98
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>
105
106 using std::string;
107
108 #if defined( HAVE_VERSION_H ) && HAVE_VERSION_H
109 #  include <Include/version.h>
110 #else
111 #  include <Include/no_version.h>
112 #endif
113
114 #include <Main/fg_props.hxx>
115 #include <Main/globals.hxx>
116 #include "instrument_mgr.hxx"
117 #include "tcas.hxx"
118
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
128
129 ///////////////////////////////////////////////////////////////////////////////
130 // constants //////////////////////////////////////////////////////////////////
131 ///////////////////////////////////////////////////////////////////////////////
132
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}}
145 };
146
147 ///////////////////////////////////////////////////////////////////////////////
148 // helpers ////////////////////////////////////////////////////////////////////
149 ///////////////////////////////////////////////////////////////////////////////
150
151 #define ADD_VOICE(Var, Sample, SayTwice)    \
152     { make_voice(&Var);                    \
153       append(Var, Sample);                  \
154       if (SayTwice) append(Var, Sample); }
155
156 #define AVAILABLE_RA(Options, Advisory) (Advisory == (Advisory & Options))
157
158 #ifdef FEATURE_TCAS_DEBUG_THREAT_DETECTOR
159 /** calculate relative angle in between two headings */
160 static float
161 relAngle(float Heading1, float Heading2)
162 {
163     Heading1 -= Heading2;
164
165     while (Heading1 >= 360.0)
166         Heading1 -= 360.0;
167
168     while (Heading1 < 0.0)
169         Heading1 += 360;
170
171     return Heading1;
172 }
173 #endif
174
175 /** calculate range and bearing of lat2/lon2 relative to lat1/lon1 */ 
176 static void
177 calcRangeBearing(double lat1, double lon1, double lat2, double lon2,
178                  double &rangeNm, double &bearing)
179 {
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;
184 }
185
186 ///////////////////////////////////////////////////////////////////////////////
187 // VoicePlayer ////////////////////////////////////////////////////////////////
188 ///////////////////////////////////////////////////////////////////////////////
189
190 void
191 TCAS::VoicePlayer::init(void)
192 {
193     FGVoicePlayer::init();
194
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);
211
212     speaker.update_configuration();
213 }
214
215 /////////////////////////////////////////////////////////////////////////////
216 // TCAS::Annunciator ////////////////////////////////////////////////////////
217 /////////////////////////////////////////////////////////////////////////////
218
219 TCAS::Annunciator::Annunciator(TCAS* _tcas) :
220     tcas(_tcas),
221     pLastVoice(NULL),
222     voicePlayer(_tcas)
223 {
224     clear();
225 }
226
227 void TCAS::Annunciator::clear(void)
228 {
229     previous.threatLevel = ThreatNone;
230     previous.RA          = AdvisoryClear;
231     previous.RAOption    = OptionNone;
232     pLastVoice = NULL;
233 }
234
235 void
236 TCAS::Annunciator::bind(SGPropertyNode* node)
237 {
238     voicePlayer.bind(node, "Sounds/tcas/female/");
239 }
240
241 void
242 TCAS::Annunciator::init(void)
243 {
244     //TODO link to GPWS module/audio-on signal must be configurable
245     nodeGpwsAlertOn = fgGetNode("/instrumentation/mk-viii/outputs/discretes/audio-on", true);
246     voicePlayer.init();
247 }
248
249 void
250 TCAS::Annunciator::update(void)
251 {
252     voicePlayer.update();
253     
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())
258         voicePlayer.pause();
259     else
260         voicePlayer.resume();
261 }
262
263 /** Trigger voice sample for current alert. */
264 void
265 TCAS::Annunciator::trigger(const ResolutionAdvisory& current, bool revertedRA)
266 {
267     int RA = current.RA;
268     int RAOption = current.RAOption;
269
270     if (RA == AdvisoryClear)
271     {
272         if (previous.RA != AdvisoryClear)
273         {
274             voicePlayer.play(voicePlayer.Voices.pClear, VoicePlayer::PLAY_NOW);
275             previous = current;
276         }
277         pLastVoice = NULL;
278         return;
279     }
280
281     if ((previous.RA == AdvisoryClear)||
282         (tcas->tracker.newTraffic()))
283     {
284         voicePlayer.play(voicePlayer.Voices.pTrafficTraffic, VoicePlayer::PLAY_NOW);
285     }
286
287     // pick voice sample
288     VoicePlayer::Voice* pVoice = NULL;
289     switch(RA)
290     {
291         case AdvisoryClimb:
292             if (revertedRA)
293                 pVoice = voicePlayer.Voices.pClimbNow;
294             else
295             if (AVAILABLE_RA(RAOption, OptionIncreaseClimb))
296                 pVoice = voicePlayer.Voices.pClimbIncrease;
297             else
298             if (AVAILABLE_RA(RAOption, OptionCrossingClimb))
299                 pVoice = voicePlayer.Voices.pClimbCrossing;
300             else
301                 pVoice = voicePlayer.Voices.pClimb;
302             break;
303
304         case AdvisoryDescend:
305             if (revertedRA)
306                 pVoice = voicePlayer.Voices.pDescendNow;
307             else
308             if (AVAILABLE_RA(RAOption, OptionIncreaseDescend))
309                 pVoice = voicePlayer.Voices.pDescendIncrease;
310             else
311             if (AVAILABLE_RA(RAOption, OptionCrossingDescent))
312                 pVoice = voicePlayer.Voices.pDescendCrossing;
313             else
314                 pVoice = voicePlayer.Voices.pDescend;
315             break;
316
317         case AdvisoryAdjustVSpeed:
318             pVoice = voicePlayer.Voices.pAdjustVSpeed;
319             break;
320
321         case AdvisoryMaintVSpeed:
322             pVoice = voicePlayer.Voices.pMaintVSpeed;
323             break;
324
325         case AdvisoryMonitorVSpeed:
326             pVoice = voicePlayer.Voices.pMonitorVSpeed;
327             break;
328
329         case AdvisoryLevelOff:
330             pVoice = voicePlayer.Voices.pLevelOff;
331             break;
332
333         case AdvisoryIntrusion:
334             break;
335
336         default:
337             RA = AdvisoryIntrusion;
338             break;
339     }
340
341     previous = current;
342
343     if ((pLastVoice == pVoice)&&
344         (!tcas->tracker.newTraffic()))
345     {
346         // don't repeat annunciation
347         return;
348     }
349     pLastVoice = pVoice;
350     if (pVoice)
351         voicePlayer.play(pVoice);
352
353 #ifdef FEATURE_TCAS_DEBUG_ANNUNCIATOR
354     cout << "Annunciating TCAS RA " << RA << endl;
355 #endif
356 }
357
358 void
359 TCAS::Annunciator::test(bool testOk)
360 {
361     if (testOk)
362         voicePlayer.play(voicePlayer.Voices.pTestOk);
363     else
364         voicePlayer.play(voicePlayer.Voices.pTestFail);
365 }
366
367 /////////////////////////////////////////////////////////////////////////////
368 // TCAS::AdvisoryCoordinator ////////////////////////////////////////////////
369 /////////////////////////////////////////////////////////////////////////////
370
371 TCAS::AdvisoryCoordinator::AdvisoryCoordinator(TCAS* _tcas) :
372   tcas(_tcas),
373   lastTATime(0)
374 {
375     init();
376 }
377
378 void
379 TCAS::AdvisoryCoordinator::init(void)
380 {
381     clear();
382     previous = current;
383 }
384
385 void
386 TCAS::AdvisoryCoordinator::bind(SGPropertyNode* node)
387 {
388     nodeTAWarning = node->getNode("outputs/traffic-alert", true);
389     nodeTAWarning->setBoolValue(false);
390 }
391
392 void
393 TCAS::AdvisoryCoordinator::clear(void)
394 {
395     current.threatLevel = ThreatNone;
396     current.RA          = AdvisoryClear;
397     current.RAOption    = OptionNone;
398 }
399
400 /** Add all suitable resolution advisories for a single threat. */
401 void
402 TCAS::AdvisoryCoordinator::add(const ResolutionAdvisory& newAdvisory)
403 {
404     if ((newAdvisory.RA == AdvisoryClear)||
405         (newAdvisory.threatLevel < current.threatLevel))
406         return;
407
408     if (current.threatLevel == newAdvisory.threatLevel)
409     {
410         // combine with other advisories so far
411         current.RA &= newAdvisory.RA;
412         // remember any advisory modifier
413         current.RAOption |= newAdvisory.RAOption;
414     }
415     else
416     {
417         current = newAdvisory;
418     }
419 }
420
421 /** Pick and trigger suitable resolution advisory. */
422 void
423 TCAS::AdvisoryCoordinator::update(int mode)
424 {
425     bool revertedRA = false; // has advisory changed?
426     double currentTime = globals->get_sim_time_sec();
427
428     if (current.RA == AdvisoryClear)
429     {
430         // filter: wait 5 seconds after last TA/RA before announcing TA clearance
431         if ((previous.RA != AdvisoryClear)&&
432              (currentTime - lastTATime < 5.0))
433             return;
434     }
435     else
436     {
437         // intruder detected
438
439 #ifdef FEATURE_TCAS_DEBUG_COORDINATOR
440         cout << "TCAS::Annunciator::update: previous: " << previous.RA << ", new: " << current.RA << endl;
441 #endif
442
443         lastTATime = currentTime;
444         if ((previous.RA == AdvisoryClear)||
445             (previous.RA == AdvisoryIntrusion)||
446             ((current.RA & previous.RA) != previous.RA))
447         {
448             // no RA yet, or we can't keep previous RA: pick one - in order of priority
449
450             if (AVAILABLE_RA(current.RA, AdvisoryMonitorVSpeed))
451             {
452                 // prio 1: monitor vertical speed only
453                 current.RA = AdvisoryMonitorVSpeed;
454             }
455             else
456             if (AVAILABLE_RA(current.RA, AdvisoryMaintVSpeed))
457             {
458                 // prio 2: maintain vertical speed
459                 current.RA = AdvisoryMaintVSpeed;
460             }
461             else
462             if (AVAILABLE_RA(current.RA, AdvisoryAdjustVSpeed))
463             {
464                 // prio 3: adjust vertical speed (TCAS II 7.0 only)
465                 current.RA = AdvisoryAdjustVSpeed;
466             }
467             else
468             if (AVAILABLE_RA(current.RA, AdvisoryLevelOff))
469             {
470                 // prio 3: adjust vertical speed (TCAS II 7.1 only, [EUROACAS]: CP115)
471                 current.RA = AdvisoryLevelOff;
472             }
473             else
474             if (AVAILABLE_RA(current.RA, AdvisoryClimb))
475             {
476                 // prio 4: climb
477                 current.RA = AdvisoryClimb;
478             }
479             else
480             if (AVAILABLE_RA(current.RA, AdvisoryDescend))
481             {
482                 // prio 5: descend
483                 current.RA = AdvisoryDescend;
484             }
485             else
486             {
487                 // no RA, issue a TA only
488                 current.RA = AdvisoryIntrusion;
489             }
490
491             // check if earlier advisory was reverted
492             revertedRA = ((previous.RA != current.RA)&&
493                           (previous.RA != 0)&&
494                           (previous.RA != AdvisoryIntrusion));
495         }
496         else
497         {
498             // keep earlier RA
499             current.RA = previous.RA;
500         }
501     }
502
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);
507     else
508     if (current.RA == AdvisoryClear)
509     {
510         /* explicitly clear traffic alert (since aural annunciation disabled) */
511         tcas->annunciator.clear();
512     }
513
514     previous = current;
515     
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);
520 }
521
522 ///////////////////////////////////////////////////////////////////////////////
523 // TCAS::ThreatDetector ///////////////////////////////////////////////////////
524 ///////////////////////////////////////////////////////////////////////////////
525
526 TCAS::ThreatDetector::ThreatDetector(TCAS* _tcas) :
527     tcas(_tcas),
528     pAlarmThresholds(&sensitivityLevels[0])
529 {
530     unitTest();
531 }
532
533 void
534 TCAS::ThreatDetector::init(void)
535 {
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);
542     
543     tcas->advisoryGenerator.init(&self,&currentThreat);
544 }
545
546 /** Update local position and threat sensitivity levels. */
547 void
548 TCAS::ThreatDetector::update(void)
549 {
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();
557
558     checkCount = 0;
559
560     // determine current altitude's "Sensitivity Level Definition and Alarm Thresholds" 
561     int sl=0;
562     for (sl=0;((self.altFt > sensitivityLevels[sl].maxAltitude)&&
563                (sensitivityLevels[sl].maxAltitude));sl++);
564     pAlarmThresholds = &sensitivityLevels[sl];
565     tcas->advisoryGenerator.setAlarmThresholds(pAlarmThresholds);
566 }
567
568 /** Check if plane's transponder is enabled. */
569 bool
570 TCAS::ThreatDetector::checkTransponder(const SGPropertyNode* pModel, float velocityKt)
571 {
572     const string name = pModel->getName();
573     if (name != "multiplayer" && name != "aircraft")
574     {
575         // assume non-MP/non-AI planes (e.g. ships) have no transponder
576         return false;
577     }
578
579     if (velocityKt < 40)
580     {
581         /* assume all pilots have their transponder switched off while taxiing/parking
582          * (at low speed) */
583         return false;
584     }
585
586     if ((name == "multiplayer")&&
587         (pModel->getBoolValue("controls/invisible")))
588     {
589         // ignored MP plane: pretend transponder is switched off
590         return false;
591     }
592
593     return true;
594 }
595
596 /** Check if plane is a threat. */
597 int
598 TCAS::ThreatDetector::checkThreat(int mode, const SGPropertyNode* pModel)
599 {
600     checkCount++;
601     
602     float velocityKt  = pModel->getDoubleValue("velocities/true-airspeed-kt");
603
604     if (!checkTransponder(pModel, velocityKt))
605         return ThreatInvisible;
606
607     int threatLevel = ThreatNone;
608     float altFt = pModel->getDoubleValue("position/altitude-ft");
609     currentThreat.relativeAltitudeFt = altFt - self.altFt;
610
611     // save computation time: don't care when relative altitude is excessive
612     if (fabs(currentThreat.relativeAltitudeFt) > 10000)
613         return threatLevel;
614
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");
619
620     double distanceNm, bearing;
621     calcRangeBearing(self.lat, self.lon, lat, lon, distanceNm, bearing);
622
623     // save computation time: don't care for excessive distances (also captures NaNs...)
624     if ((distanceNm > 10)||(distanceNm < 0))
625         return threatLevel;
626
627     currentThreat.verticalFps = pModel->getDoubleValue("velocities/vertical-speed-fps");
628     
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))
634     {
635         // at least a proximity target
636         threatLevel = ThreatProximity;
637     }
638
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)))
642     {
643         return threatLevel;
644     }
645
646     if (tcas->tracker.active())
647     {
648         currentThreat.callsign = pModel->getStringValue("callsign");
649         currentThreat.isTracked = tcas->tracker.isTracked(currentThreat.callsign);
650     }
651     else
652         currentThreat.isTracked = false;
653     
654     // first stage: vertical movement
655     checkVerticalThreat();
656
657     // stop processing when no vertical threat
658     if ((!currentThreat.verticalTA)&&
659         (!currentThreat.isTracked))
660         return threatLevel;
661
662     // second stage: horizontal movement
663     horizontalThreat(bearing, distanceNm, heading, velocityKt);
664
665     if (!currentThreat.isTracked)
666     {
667         // no horizontal threat?
668         if (!currentThreat.horizontalTA)
669             return threatLevel;
670
671         if ((currentThreat.horizontalTau < 0)||
672             (currentThreat.verticalTau < 0))
673         {
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)
677                 return threatLevel;
678         }
679     }
680
681 #ifdef FEATURE_TCAS_DEBUG_THREAT_DETECTOR
682     cout << "#" << checkCount << ": " << pModel->getStringValue("callsign") << endl;
683 #endif
684
685     
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
689      *    an advisory." */
690     if (currentThreat.horizontalTA && currentThreat.verticalTA)
691         threatLevel = ThreatTA;
692     if (currentThreat.horizontalRA && currentThreat.verticalRA)
693         threatLevel = ThreatRA;
694
695     if (!tcas->tracker.active())
696         currentThreat.callsign = pModel->getStringValue("callsign");
697
698     tcas->tracker.add(currentThreat.callsign, threatLevel);
699     
700     // check existing threat level
701     if (currentThreat.isTracked)
702     {
703         int oldLevel = tcas->tracker.getThreatLevel(currentThreat.callsign);
704         if (oldLevel > threatLevel)
705             threatLevel = oldLevel;
706     }
707
708     // find all resolution options for this conflict
709     threatLevel = tcas->advisoryGenerator.resolution(mode, threatLevel, distanceNm, altFt, heading, velocityKt);
710    
711     
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"
716            "\n",
717            distanceNm, relAngle(bearing, self.heading), altFt, velocityKt, heading, currentThreat.verticalFps,
718            self.altFt, self.heading, self.velocityKt
719            //, currentThreat.closingSpeedKt
720            ,currentThreat.verticalTau
721            );
722 #endif
723
724     return threatLevel;
725 }
726
727 /** Check if plane is a vertical threat. */
728 void
729 TCAS::ThreatDetector::checkVerticalThreat(void)
730 {
731     // calculate relative vertical speed and altitude
732     float dV = self.verticalFps - currentThreat.verticalFps;
733     float dA = currentThreat.relativeAltitudeFt;
734
735     currentThreat.verticalTA  = false;
736     currentThreat.verticalRA  = false;
737     currentThreat.verticalTau = 0;
738
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)
741      *   times 60." */
742     float tau = 0;
743     if (fabs(dV) > 0.1)
744         tau = dA/dV;
745
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)))
751     {
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)
756         {
757             // continuous intrusion at RA-level
758             currentThreat.verticalTA = true;
759             currentThreat.verticalRA = true;
760         }
761         else
762         if (abs_dA < pAlarmThresholds->TA.ALIM)
763         {
764             // continuous intrusion: with TA-level, but no RA-threat
765             currentThreat.verticalTA = true;
766         }
767         // else: no RA/TA threat
768     }
769     else
770     {
771         if ((tau < pAlarmThresholds->TA.Tau)&&
772             (tau >= -5))
773         {
774             currentThreat.verticalTA = true;
775             currentThreat.verticalRA = (tau < pAlarmThresholds->RA.Tau);
776         }
777     }
778     currentThreat.verticalTau = tau;
779
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);
783 #endif
784 }
785
786 /** Check if plane is a horizontal threat. */
787 void
788 TCAS::ThreatDetector::horizontalThreat(float bearing, float distanceNm, float heading, float velocityKt)
789 {
790     // calculate speed
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;
793
794     // calculate horizontal closing speed
795     float closingSpeedKt2 = vxKt*vxKt+vyKt*vyKt; 
796     float closingSpeedKt  = sqrt(closingSpeedKt2);
797
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;
803
804     if (closingSpeedKt < 100)
805     {
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
811          *    encounters." */
812         TA_rangeNm += (100.0-closingSpeedKt)*(pAlarmThresholds->TA.DMOD/100.0);
813         RA_rangeNm += (100.0-closingSpeedKt)*(pAlarmThresholds->RA.DMOD/100.0);
814     }
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;
819
820     currentThreat.horizontalTA   = (distanceNm < TA_rangeNm);
821     currentThreat.horizontalRA   = (distanceNm < RA_rangeNm);
822     currentThreat.horizontalTau  = -1;
823     
824     if ((currentThreat.horizontalRA)&&
825         (currentThreat.verticalRA))
826     {
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.
830          */
831
832         /* relative position of intruder is
833          *   Sx(t) = sx + vx*t
834          *   Sy(t) = sy + vy*t
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
843          * at t=tau:
844          *    r2'(tau) = 0 = b + 2*a*tau
845          * => tau = -b/(2*a) 
846          */
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);
853         float tau = 0;
854         if (a > 0.0001)
855             tau = -b/(2*a);
856 #ifdef FEATURE_TCAS_DEBUG_THREAT_DETECTOR
857         printf("  Time to horizontal CPA: %4.2f\n",tau);
858 #endif
859         if (tau > pAlarmThresholds->RA.Tau)
860             tau = pAlarmThresholds->RA.Tau;
861         
862         // remember time to horizontal CPA
863         currentThreat.horizontalTau = tau;
864     }
865 }
866
867 /** Test threat detection logic. */
868 void
869 TCAS::ThreatDetector::unitTest(void)
870 {
871     pAlarmThresholds = &sensitivityLevels[1];
872 #if 0
873     // vertical tests
874     self.verticalFps = 0;
875     self.altFt = 1000;
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);
888
889     // horizontal tests
890     self.heading = 0;
891     self.velocityKt = 0;
892     cout << "10nm behind, overtaking with 1Nm/s" << endl;
893     horizontalThreat(-180, 10, 0, 1/(SG_KT_TO_MPS*SG_METER_TO_NM));
894
895     cout << "10nm ahead, departing with 1Nm/s" << endl;
896     horizontalThreat(0, 20, 0, 1/(SG_KT_TO_MPS*SG_METER_TO_NM));
897
898     self.heading = 90;
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));
902
903     self.heading = 20;
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));
907 #endif
908 }
909
910 ///////////////////////////////////////////////////////////////////////////////
911 // TCAS::AdvisoryGenerator ////////////////////////////////////////////////////
912 ///////////////////////////////////////////////////////////////////////////////
913
914 TCAS::AdvisoryGenerator::AdvisoryGenerator(TCAS* _tcas) :
915     tcas(_tcas),
916     pSelf(NULL),
917     pCurrentThreat(NULL),
918     pAlarmThresholds(NULL)
919 {
920 }
921
922 void
923 TCAS::AdvisoryGenerator::init(const LocalInfo* _pSelf, ThreatInfo* _pCurrentThreat)
924 {
925     pCurrentThreat = _pCurrentThreat;
926     pSelf = _pSelf;
927 }
928
929 void
930 TCAS::AdvisoryGenerator::setAlarmThresholds(const SensitivityLevel* _pAlarmThresholds)
931 {
932     pAlarmThresholds = _pAlarmThresholds;
933 }
934
935 /** Calculate projected vertical separation at horizontal CPA. */
936 float
937 TCAS::AdvisoryGenerator::verticalSeparation(float newVerticalFps)
938 {
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...
943     if (tau < 0.5)
944         tau = 0.5;
945     return pCurrentThreat->relativeAltitudeFt + tau * dV;
946 }
947
948 /** Determine RA sense. */
949 void
950 TCAS::AdvisoryGenerator::determineRAsense(int& RASense, bool& isCrossing)
951 {
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." */
954     RASense = 0;
955     isCrossing = false;
956     
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
965     else
966         RASense = -1; // downward
967
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." */
973     if ((RASense > 0)&&
974         (pCurrentThreat->relativeAltitudeFt > 200))
975     {
976         // threat is above and RA is crossing
977         if (fabs(downSenseRelAltFt) > pAlarmThresholds->TA.ALIM)
978         {
979             // non-crossing descend is sufficient 
980             RASense = -1;
981         }
982         else
983         {
984             // keep crossing climb RA
985             isCrossing = true;
986         }
987     }
988     else
989     if ((RASense < 0)&&
990         (pCurrentThreat->relativeAltitudeFt < -200))
991     {
992         // threat is below and RA is crossing
993         if (fabs(upSenseRelAltFt) > pAlarmThresholds->TA.ALIM)
994         {
995             // non-crossing climb is sufficient 
996             RASense = 1;
997         }
998         else
999         {
1000             // keep crossing descent RA
1001             isCrossing = true;
1002         }
1003     }
1004     // else: threat is at same altitude, keep optimal RA sense (non-crossing)
1005
1006     pCurrentThreat->RASense = RASense;
1007
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",
1010                RASense,isCrossing,
1011                pCurrentThreat->relativeAltitudeFt,
1012                upSenseRelAltFt,downSenseRelAltFt);
1013 #endif
1014 }
1015
1016 /** Determine suitable resolution advisories. */
1017 int
1018 TCAS::AdvisoryGenerator::resolution(int mode, int threatLevel, float rangeNm, float altFt,
1019                                     float heading, float velocityKt)
1020 {
1021     int RAOption = OptionNone;
1022     int RA       = AdvisoryIntrusion;
1023
1024     // RAs are disabled under certain conditions
1025     if (threatLevel == ThreatRA)
1026     {
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."*/
1030         if (altFt < 360)
1031             threatLevel = ThreatTA;
1032
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;
1037         
1038         // RAs only issued in mode "Auto" (= "TA/RA" mode)
1039         if (mode != SwitchAuto)
1040             threatLevel = ThreatTA;
1041     }
1042
1043     bool isCrossing = false; 
1044     int RASense = 0;
1045     // determine suitable RAs
1046     if (threatLevel == ThreatRA)
1047     {
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);
1051
1052         /* second step: determine required strength */
1053         if (RASense > 0)
1054         {
1055             // upward
1056
1057             if ((pSelf->verticalFps < -1000/60.0)&&
1058                 (!isCrossing))
1059             {
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;
1064             }
1065             RA |= AdvisoryClimb;
1066             if (isCrossing)
1067                 RAOption |= OptionCrossingClimb;
1068         }
1069
1070         if (RASense < 0)
1071         {
1072             // downward
1073
1074             if ((pSelf->verticalFps > 1000/60.0)&&
1075                 (!isCrossing))
1076             {
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;
1081             }
1082             RA |= AdvisoryDescend;
1083             if (isCrossing)
1084                 RAOption |= OptionCrossingDescent;
1085         }
1086
1087         //TODO
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." */
1092         
1093         //TODO
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
1097          *   Descend RA)." */
1098         
1099         //TODO
1100         /* [TCASII]: "TCAS is designed to inhibit Increase Descent RAs below 1450 feet AGL; */
1101         
1102         /* [TCASII]: "Descend RAs below 1100 feet AGL;" (inhibited) */
1103         if (pSelf->altFt < 1100)
1104         {
1105             RA &= ~AdvisoryDescend;
1106             //TODO Support "Do not descend" RA
1107             RA |= AdvisoryIntrusion;
1108         }
1109     }
1110
1111 #ifdef FEATURE_TCAS_DEBUG_ADV_GENERATOR
1112     cout << "  resolution advisory: " << RA << endl;
1113 #endif
1114
1115     ResolutionAdvisory newAdvisory;
1116     newAdvisory.RAOption    = RAOption;
1117     newAdvisory.RA          = RA;
1118     newAdvisory.threatLevel = threatLevel;
1119     tcas->advisoryCoordinator.add(newAdvisory);
1120     
1121     return threatLevel;
1122 }
1123
1124 ///////////////////////////////////////////////////////////////////////////////
1125 // TCAS ///////////////////////////////////////////////////////////////////////
1126 ///////////////////////////////////////////////////////////////////////////////
1127
1128 TCAS::TCAS(SGPropertyNode* pNode) :
1129     name("tcas"),
1130     num(0),
1131     nextUpdateTime(0),
1132     selfTestStep(0),
1133     properties_handler(this),
1134     threatDetector(this),
1135     tracker(this),
1136     advisoryCoordinator(this),
1137     advisoryGenerator(this),
1138     annunciator(this)
1139 {
1140     for (int i = 0; i < pNode->nChildren(); ++i)
1141     {
1142         SGPropertyNode* pChild = pNode->getChild(i);
1143         string cname = pChild->getName();
1144         string cval = pChild->getStringValue();
1145
1146         if (cname == "name")
1147             name = cval;
1148         else if (cname == "number")
1149             num = pChild->getIntValue();
1150         else
1151         {
1152             SG_LOG(SG_INSTR, SG_WARN, "Error in TCAS config logic");
1153             if (name.length())
1154                 SG_LOG(SG_INSTR, SG_WARN, "Section = " << name);
1155         }
1156     }
1157 }
1158
1159 void
1160 TCAS::init(void)
1161 {
1162     annunciator.init();
1163     advisoryCoordinator.init();
1164     threatDetector.init();
1165 }
1166
1167 void
1168 TCAS::bind(void)
1169 {
1170     SGPropertyNode* node = fgGetNode(("/instrumentation/" + name).c_str(), num, true);
1171
1172     nodeServiceable  = node->getNode("serviceable", true);
1173
1174     // TCAS mode selection (0=off, 1=standby, 2=TA only, 3=auto(TA/RA) ) 
1175     nodeModeSwitch   = node->getNode("inputs/mode", true);
1176     // self-test button
1177     nodeSelfTest     = node->getNode("inputs/self-test", true);
1178     // default value
1179     nodeSelfTest->setBoolValue(false);
1180
1181 #ifdef FEATURE_TCAS_DEBUG_PROPERTIES
1182     SGPropertyNode* nodeDebug = node->getNode("debug", true);
1183     // debug triggers
1184     nodeDebugTrigger = nodeDebug->getNode("threat-trigger", true);
1185     nodeDebugRA      = nodeDebug->getNode("threat-RA",      true);
1186     nodeDebugThreat  = nodeDebug->getNode("threat-level",   true);
1187     // default values
1188     nodeDebugTrigger->setBoolValue(false);
1189     nodeDebugRA->setIntValue(3);
1190     nodeDebugThreat->setIntValue(1);
1191 #endif
1192
1193     annunciator.bind(node);
1194     advisoryCoordinator.bind(node);
1195 }
1196
1197 void
1198 TCAS::unbind(void)
1199 {
1200     properties_handler.unbind();
1201 }
1202
1203 /** Monitor traffic for safety threats. */
1204 void
1205 TCAS::update(double dt)
1206 {
1207     if (!nodeServiceable->getBoolValue())
1208         return;
1209     int mode = nodeModeSwitch->getIntValue();
1210     if (mode == SwitchOff)
1211         return;
1212
1213     nextUpdateTime -= dt;
1214     if (nextUpdateTime <= 0.0 )
1215     {
1216         nextUpdateTime = 1.0;
1217
1218         // remove obsolete targets
1219         tracker.update();
1220
1221         // get aircrafts current position/speed/heading
1222         threatDetector.update();
1223
1224         // clear old threats
1225         advisoryCoordinator.clear();
1226
1227         if (nodeSelfTest->getBoolValue())
1228         {
1229             if (threatDetector.getVelocityKt() >= 40)
1230             {
1231                 // disable self-test when plane moves above taxiing speed
1232                 nodeSelfTest->setBoolValue(false);
1233                 selfTestStep = 0;
1234             }
1235             else
1236             {
1237                 selfTest();
1238                 // speed-up self test
1239                 nextUpdateTime = 0;
1240                 // no further TCAS processing during self-test
1241                 return;
1242             }
1243         }
1244
1245 #ifdef FEATURE_TCAS_DEBUG_PROPERTIES
1246         if (nodeDebugTrigger->getBoolValue())
1247         {
1248             // debugging test
1249             ResolutionAdvisory debugAdvisory;
1250             debugAdvisory.RAOption    = OptionNone;
1251             debugAdvisory.RA          = nodeDebugRA->getIntValue();
1252             debugAdvisory.threatLevel = nodeDebugThreat->getIntValue();
1253             advisoryCoordinator.add(debugAdvisory);
1254         }
1255         else
1256 #endif
1257         {
1258             SGPropertyNode* pAi = fgGetNode("/ai/models", true);
1259
1260             // check all aircraft
1261             for (int i = pAi->nChildren() - 1; i >= -1; i--)
1262             {
1263                 SGPropertyNode* pModel = pAi->getChild(i);
1264                 if ((pModel)&&(pModel->nChildren()))
1265                 {
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);
1272                 }
1273             }
1274         }
1275         advisoryCoordinator.update(mode);
1276     }
1277     annunciator.update();
1278 }
1279
1280 /** Run a single self-test iteration. */
1281 void
1282 TCAS::selfTest(void)
1283 {
1284     annunciator.update();
1285     if (annunciator.isPlaying())
1286     {
1287         return;
1288     }
1289
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);
1296
1297     // trigger various advisories
1298     switch(selfTestStep)
1299     {
1300         case 0:
1301             newAdvisory.RA = AdvisoryIntrusion;
1302             newAdvisory.threatLevel = ThreatTA;
1303             break;
1304         case 1:
1305             newAdvisory.RA = AdvisoryClimb;
1306             break;
1307         case 2:
1308             newAdvisory.RA = AdvisoryClimb;
1309             newAdvisory.RAOption = OptionIncreaseClimb;
1310             break;
1311         case 3:
1312             newAdvisory.RA = AdvisoryClimb;
1313             newAdvisory.RAOption = OptionCrossingClimb;
1314             break;
1315         case 4:
1316             newAdvisory.RA = AdvisoryDescend;
1317             break;
1318         case 5:
1319             newAdvisory.RA = AdvisoryDescend;
1320             newAdvisory.RAOption = OptionIncreaseDescend;
1321             break;
1322         case 6:
1323             newAdvisory.RA = AdvisoryDescend;
1324             newAdvisory.RAOption = OptionCrossingDescent;
1325             break;
1326         case 7:
1327             newAdvisory.RA = AdvisoryAdjustVSpeed;
1328             break;
1329         case 8:
1330             newAdvisory.RA = AdvisoryMaintVSpeed;
1331             break;
1332         case 9:
1333             newAdvisory.RA = AdvisoryMonitorVSpeed;
1334             break;
1335         case 10:
1336             newAdvisory.threatLevel = ThreatNone;
1337             newAdvisory.RA = AdvisoryClear;
1338             break;
1339         case 11:
1340             annunciator.test(true);
1341             selfTestStep+=2;
1342             return;
1343         default:
1344             nodeSelfTest->setBoolValue(false);
1345             selfTestStep = 0;
1346             return;
1347     }
1348
1349     advisoryCoordinator.add(newAdvisory);
1350     advisoryCoordinator.update(SwitchAuto);
1351
1352     selfTestStep++;
1353 }
1354
1355 ///////////////////////////////////////////////////////////////////////////////
1356 // TCAS::Tracker //////////////////////////////////////////////////////////////
1357 ///////////////////////////////////////////////////////////////////////////////
1358
1359 TCAS::Tracker::Tracker(TCAS* _tcas) :
1360     tcas(_tcas),
1361     currentTime(0),
1362     haveTargets(false),
1363     newTargets(false)
1364 {
1365     targets.clear();
1366 }
1367
1368 void
1369 TCAS::Tracker::update(void)
1370 {
1371     currentTime = globals->get_sim_time_sec();
1372     newTargets = false;
1373
1374     if (haveTargets)
1375     {
1376         // remove outdated targets
1377         TrackerTargets::iterator it = targets.begin();
1378         while (it != targets.end())
1379         {
1380             TrackerTarget* pTarget = it->second;
1381             if (currentTime - pTarget->TAtimestamp > 10.0)
1382             {
1383                 TrackerTargets::iterator temp = it;
1384                 ++it;
1385 #ifdef FEATURE_TCAS_DEBUG_TRACKER
1386                 printf("target %s no longer a TA threat.\n",temp->first.c_str());
1387 #endif
1388                 targets.erase(temp->first);
1389                 delete pTarget;
1390                 pTarget = NULL;
1391             }
1392             else
1393             {
1394                 if ((pTarget->threatLevel == ThreatRA)&&
1395                     (currentTime - pTarget->RAtimestamp > 7.0))
1396                 {
1397                     pTarget->threatLevel = ThreatTA;
1398 #ifdef FEATURE_TCAS_DEBUG_TRACKER
1399                     printf("target %s no longer an RA threat.\n",it->first.c_str());
1400 #endif
1401                 }
1402                 ++it;
1403             }
1404         }
1405         haveTargets = !targets.empty();
1406     }
1407 }
1408
1409 void
1410 TCAS::Tracker::add(const string callsign, int detectedLevel)
1411 {
1412     TrackerTarget* pTarget = NULL;
1413     if (haveTargets)
1414     {
1415         TrackerTargets::iterator it = targets.find(callsign);
1416         if (it != targets.end())
1417         {
1418             pTarget = it->second;
1419         }
1420     }
1421
1422     if (!pTarget)
1423     {
1424         pTarget = new TrackerTarget();
1425         pTarget->TAtimestamp = 0;
1426         pTarget->RAtimestamp = 0;
1427         pTarget->threatLevel = 0;
1428         newTargets = true;
1429         targets[callsign] = pTarget;
1430 #ifdef FEATURE_TCAS_DEBUG_TRACKER
1431         printf("new target: %s, level: %i\n",callsign.c_str(),detectedLevel);
1432 #endif
1433     }
1434
1435     if (detectedLevel > pTarget->threatLevel)
1436         pTarget->threatLevel = detectedLevel;
1437
1438     if (detectedLevel >= ThreatTA)
1439         pTarget->TAtimestamp = currentTime;
1440
1441     if (detectedLevel >= ThreatRA)
1442         pTarget->RAtimestamp = currentTime;
1443
1444     haveTargets = true;
1445 }
1446
1447 bool
1448 TCAS::Tracker::_isTracked(string callsign)
1449 {
1450     return targets.find(callsign) != targets.end();
1451 }
1452
1453 int
1454 TCAS::Tracker::getThreatLevel(string callsign)
1455 {
1456     TrackerTargets::iterator it = targets.find(callsign);
1457     if (it != targets.end())
1458         return it->second->threatLevel;
1459     else
1460         return 0;
1461 }