]> git.mxchange.org Git - flightgear.git/blob - src/Instrumentation/tcas.cxx
Fix a dumb bug in NavDisplay text-enable.
[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., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301, 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.getRadarAlt() > 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     checkCount(0),
529     pAlarmThresholds(&sensitivityLevels[0])
530 {
531     self.radarAltFt = 0.0;
532     unitTest();
533 }
534
535 void
536 TCAS::ThreatDetector::init(void)
537 {
538     nodeLat         = fgGetNode("/position/latitude-deg",          true);
539     nodeLon         = fgGetNode("/position/longitude-deg",         true);
540     nodePressureAlt = fgGetNode("/position/altitude-ft",           true);
541     nodeRadarAlt    = fgGetNode("/position/altitude-agl-ft",       true);
542     nodeHeading     = fgGetNode("/orientation/heading-deg",        true);
543     nodeVelocity    = fgGetNode("/velocities/airspeed-kt",         true);
544     nodeVerticalFps = fgGetNode("/velocities/vertical-speed-fps",  true);
545     
546     tcas->advisoryGenerator.init(&self,&currentThreat);
547 }
548
549 /** Update local position and threat sensitivity levels. */
550 void
551 TCAS::ThreatDetector::update(void)
552 {
553     // update local position
554     self.lat           = nodeLat->getDoubleValue();
555     self.lon           = nodeLon->getDoubleValue();
556     self.pressureAltFt = nodePressureAlt->getDoubleValue();
557     self.heading       = nodeHeading->getDoubleValue();
558     self.velocityKt    = nodeVelocity->getDoubleValue();
559     self.verticalFps   = nodeVerticalFps->getDoubleValue();
560
561     /* radar altimeter provides a lot of spikes due to uneven terrain
562      * MK-VIII GPWS-spec requires smoothing the radar altitude with a
563      * 10second moving average. Likely the TCAS spec requires the same.
564      * => We use a cheap 10 second exponential average method.
565      */
566     const double SmoothingFactor = 0.3;
567     self.radarAltFt = nodeRadarAlt->getDoubleValue()*SmoothingFactor +
568             (1-SmoothingFactor)*self.radarAltFt;
569
570 #ifdef FEATURE_TCAS_DEBUG_THREAT_DETECTOR
571     printf("TCAS::ThreatDetector::update: radarAlt = %f\n",self.radarAltFt);
572     checkCount = 0;
573 #endif
574
575     // determine current altitude's "Sensitivity Level Definition and Alarm Thresholds" 
576     int sl=0;
577     for (sl=0;((self.radarAltFt > sensitivityLevels[sl].maxAltitude)&&
578                (sensitivityLevels[sl].maxAltitude));sl++);
579     pAlarmThresholds = &sensitivityLevels[sl];
580     tcas->advisoryGenerator.setAlarmThresholds(pAlarmThresholds);
581 }
582
583 /** Check if plane's transponder is enabled. */
584 bool
585 TCAS::ThreatDetector::checkTransponder(const SGPropertyNode* pModel, float velocityKt)
586 {
587     const string name = pModel->getName();
588     if (name != "multiplayer" && name != "aircraft")
589     {
590         // assume non-MP/non-AI planes (e.g. ships) have no transponder
591         return false;
592     }
593
594     if (velocityKt < 40)
595     {
596         /* assume all pilots have their transponder switched off while taxiing/parking
597          * (at low speed) */
598         return false;
599     }
600
601     if ((name == "multiplayer")&&
602         (pModel->getBoolValue("controls/invisible")))
603     {
604         // ignored MP plane: pretend transponder is switched off
605         return false;
606     }
607
608     return true;
609 }
610
611 /** Check if plane is a threat. */
612 int
613 TCAS::ThreatDetector::checkThreat(int mode, const SGPropertyNode* pModel)
614 {
615 #ifdef FEATURE_TCAS_DEBUG_THREAT_DETECTOR
616     checkCount++;
617 #endif
618     
619     float velocityKt  = pModel->getDoubleValue("velocities/true-airspeed-kt");
620
621     if (!checkTransponder(pModel, velocityKt))
622         return ThreatInvisible;
623
624     int threatLevel = ThreatNone;
625     float altFt = pModel->getDoubleValue("position/altitude-ft");
626     currentThreat.relativeAltitudeFt = altFt - self.pressureAltFt;
627
628     // save computation time: don't care when relative altitude is excessive
629     if (fabs(currentThreat.relativeAltitudeFt) > 10000)
630         return threatLevel;
631
632     // position data of current intruder
633     double lat        = pModel->getDoubleValue("position/latitude-deg");
634     double lon        = pModel->getDoubleValue("position/longitude-deg");
635     float heading     = pModel->getDoubleValue("orientation/true-heading-deg");
636
637     double distanceNm, bearing;
638     calcRangeBearing(self.lat, self.lon, lat, lon, distanceNm, bearing);
639
640     // save computation time: don't care for excessive distances (also captures NaNs...)
641     if ((distanceNm > 10)||(distanceNm < 0))
642         return threatLevel;
643
644     currentThreat.verticalFps = pModel->getDoubleValue("velocities/vertical-speed-fps");
645     
646     /* Detect proximity targets
647      * [TCASII]: "Any target that is less than 6 nmi in range and within +/-1200ft
648      *  vertically, but that does not meet the intruder or threat criteria." */
649     if ((distanceNm < 6)&&
650         (fabs(currentThreat.relativeAltitudeFt) < 1200))
651     {
652         // at least a proximity target
653         threatLevel = ThreatProximity;
654     }
655
656     /* do not detect any threats when in standby or on ground and taxiing */
657     if ((mode <= SwitchStandby)||
658         ((self.radarAltFt < 360)&&(self.velocityKt < 40)))
659     {
660         return threatLevel;
661     }
662
663     if (tcas->tracker.active())
664     {
665         currentThreat.callsign = pModel->getStringValue("callsign");
666         currentThreat.isTracked = tcas->tracker.isTracked(currentThreat.callsign);
667     }
668     else
669         currentThreat.isTracked = false;
670     
671     // first stage: vertical movement
672     checkVerticalThreat();
673
674     // stop processing when no vertical threat
675     if ((!currentThreat.verticalTA)&&
676         (!currentThreat.isTracked))
677         return threatLevel;
678
679     // second stage: horizontal movement
680     horizontalThreat(bearing, distanceNm, heading, velocityKt);
681
682     if (!currentThreat.isTracked)
683     {
684         // no horizontal threat?
685         if (!currentThreat.horizontalTA)
686             return threatLevel;
687
688         if ((currentThreat.horizontalTau < 0)||
689             (currentThreat.verticalTau < 0))
690         {
691             // do not trigger new alerts when Tau is negative, but keep existing alerts
692             int previousThreatLevel = pModel->getIntValue("tcas/threat-level", 0);
693             if (previousThreatLevel == 0)
694                 return threatLevel;
695         }
696     }
697
698 #ifdef FEATURE_TCAS_DEBUG_THREAT_DETECTOR
699     cout << "#" << checkCount << ": " << pModel->getStringValue("callsign") << endl;
700 #endif
701
702     
703     /* [TCASII]: "For either a TA or an RA to be issued, both the range and 
704      *    vertical criteria, in terms of tau or the fixed thresholds, must be
705      *    satisfied only one of the criteria is satisfied, TCAS will not issue
706      *    an advisory." */
707     if (currentThreat.horizontalTA && currentThreat.verticalTA)
708         threatLevel = ThreatTA;
709     if (currentThreat.horizontalRA && currentThreat.verticalRA)
710         threatLevel = ThreatRA;
711
712     if (!tcas->tracker.active())
713         currentThreat.callsign = pModel->getStringValue("callsign");
714
715     tcas->tracker.add(currentThreat.callsign, threatLevel);
716     
717     // check existing threat level
718     if (currentThreat.isTracked)
719     {
720         int oldLevel = tcas->tracker.getThreatLevel(currentThreat.callsign);
721         if (oldLevel > threatLevel)
722             threatLevel = oldLevel;
723     }
724
725     // find all resolution options for this conflict
726     threatLevel = tcas->advisoryGenerator.resolution(mode, threatLevel, distanceNm, altFt, heading, velocityKt);
727    
728     
729 #ifdef FEATURE_TCAS_DEBUG_THREAT_DETECTOR
730     printf("  threat: distance: %4.1f, bearing: %4.1f, alt: %5.1f, velocity: %4.1f, heading: %4.1f, vspeed: %4.1f, "
731            "own alt: %5.1f, own heading: %4.1f, own velocity: %4.1f, vertical tau: %3.2f"
732            //", closing speed: %f"
733            "\n",
734            distanceNm, relAngle(bearing, self.heading), altFt, velocityKt, heading, currentThreat.verticalFps,
735            self.altFt, self.heading, self.velocityKt
736            //, currentThreat.closingSpeedKt
737            ,currentThreat.verticalTau
738            );
739 #endif
740
741     return threatLevel;
742 }
743
744 /** Check if plane is a vertical threat. */
745 void
746 TCAS::ThreatDetector::checkVerticalThreat(void)
747 {
748     // calculate relative vertical speed and altitude
749     float dV = self.verticalFps - currentThreat.verticalFps;
750     float dA = currentThreat.relativeAltitudeFt;
751
752     currentThreat.verticalTA  = false;
753     currentThreat.verticalRA  = false;
754     currentThreat.verticalTau = 0;
755
756     /* [TCASII]: "The vertical tau is equal to the altitude separation (feet)
757      *   divided by the combined vertical speed of the two aircraft (feet/minute)
758      *   times 60." */
759     float tau = 0;
760     if (fabs(dV) > 0.1)
761         tau = dA/dV;
762
763     /* [TCASII]: "When the combined vertical speed of the TCAS and the intruder aircraft
764      *    is low, TCAS will use a fixed-altitude threshold to determine whether a TA or
765      *    an RA should be issued." */
766     if ((fabs(dV) < 3.0)||
767         ((tau < 0) && (tau > -5)))
768     {
769         /* vertical closing speed is low (below 180fpm/3fps), check
770          * fixed altitude range. */
771         float abs_dA = fabs(dA);
772         if (abs_dA < pAlarmThresholds->RA.ALIM)
773         {
774             // continuous intrusion at RA-level
775             currentThreat.verticalTA = true;
776             currentThreat.verticalRA = true;
777         }
778         else
779         if (abs_dA < pAlarmThresholds->TA.ALIM)
780         {
781             // continuous intrusion: with TA-level, but no RA-threat
782             currentThreat.verticalTA = true;
783         }
784         // else: no RA/TA threat
785     }
786     else
787     {
788         if ((tau < pAlarmThresholds->TA.Tau)&&
789             (tau >= -5))
790         {
791             currentThreat.verticalTA = true;
792             currentThreat.verticalRA = (tau < pAlarmThresholds->RA.Tau);
793         }
794     }
795     currentThreat.verticalTau = tau;
796
797 #ifdef FEATURE_TCAS_DEBUG_THREAT_DETECTOR
798     if (currentThreat.verticalTA)
799         printf("  vertical dV=%f (%f-%f), dA=%f\n", dV, self.verticalFps, currentThreat.verticalFps, dA);
800 #endif
801 }
802
803 /** Check if plane is a horizontal threat. */
804 void
805 TCAS::ThreatDetector::horizontalThreat(float bearing, float distanceNm, float heading, float velocityKt)
806 {
807     // calculate speed
808     float vxKt = sin(heading*SGD_DEGREES_TO_RADIANS)*velocityKt - sin(self.heading*SGD_DEGREES_TO_RADIANS)*self.velocityKt;
809     float vyKt = cos(heading*SGD_DEGREES_TO_RADIANS)*velocityKt - cos(self.heading*SGD_DEGREES_TO_RADIANS)*self.velocityKt;
810
811     // calculate horizontal closing speed
812     float closingSpeedKt2 = vxKt*vxKt+vyKt*vyKt; 
813     float closingSpeedKt  = sqrt(closingSpeedKt2);
814
815     /* [TCASII]: "The range tau is equal to the slant range (nmi) divided by the closing speed
816      *    (knots) multiplied by 3600."
817      * => calculate allowed slant range (nmi) based on known maximum tau */
818     float TA_rangeNm = (pAlarmThresholds->TA.Tau*closingSpeedKt)/3600;
819     float RA_rangeNm = (pAlarmThresholds->RA.Tau*closingSpeedKt)/3600;
820
821     if (closingSpeedKt < 100)
822     {
823         /* [TCASII]: "In events where the rate of closure is very low, [..]
824          *    an intruder aircraft can come very close in range without crossing the
825          *    range tau boundaries [..]. To provide protection in these types of
826          *    advisories, the range tau boundaries are modified [..] to use
827          *    a fixed-range threshold to issue TAs and RAs in these slow closure
828          *    encounters." */
829         TA_rangeNm += (100.0-closingSpeedKt)*(pAlarmThresholds->TA.DMOD/100.0);
830         RA_rangeNm += (100.0-closingSpeedKt)*(pAlarmThresholds->RA.DMOD/100.0);
831     }
832     if (TA_rangeNm < pAlarmThresholds->TA.DMOD)
833         TA_rangeNm = pAlarmThresholds->TA.DMOD;
834     if (RA_rangeNm < pAlarmThresholds->RA.DMOD)
835         RA_rangeNm = pAlarmThresholds->RA.DMOD;
836
837     currentThreat.horizontalTA   = (distanceNm < TA_rangeNm);
838     currentThreat.horizontalRA   = (distanceNm < RA_rangeNm);
839     currentThreat.horizontalTau  = -1;
840     
841     if ((currentThreat.horizontalRA)&&
842         (currentThreat.verticalRA))
843     {
844         /* an RA will be issued. Prepare extra data for the
845          * traffic resolution stage, i.e. calculate
846          * exact time tau to horizontal CPA.
847          */
848
849         /* relative position of intruder is
850          *   Sx(t) = sx + vx*t
851          *   Sy(t) = sy + vy*t
852          * horizontal distance to intruder is r(t)
853          *   r(t) = sqrt( Sx(t)^2 + Sy(t)^2 )
854          * => horizontal CPA at time t=tau, where r(t) has minimum
855          * r2(t) := r^2(t) = Sx(t)^2 + Sy(t)^2
856          * since r(t)>0 for all t => minimum of r(t) is also minimum of r2(t)
857          * => (d/dt) r2(t) = r2'(t) is 0 for t=tau
858          *    r2(t) = ((Sx(t)^2 + Sy(t))^2) = c + b*t + a*t^2
859          * => r2'(t) = b + a*2*t
860          * at t=tau:
861          *    r2'(tau) = 0 = b + 2*a*tau
862          * => tau = -b/(2*a) 
863          */
864         float sx = sin(bearing*SGD_DEGREES_TO_RADIANS)*distanceNm;
865         float sy = cos(bearing*SGD_DEGREES_TO_RADIANS)*distanceNm;
866         float vx = vxKt * (SG_KT_TO_MPS*SG_METER_TO_NM);
867         float vy = vyKt * (SG_KT_TO_MPS*SG_METER_TO_NM);
868         float a  = vx*vx + vy*vy;
869         float b  = 2*(sx*vx + sy*vy);
870         float tau = 0;
871         if (a > 0.0001)
872             tau = -b/(2*a);
873 #ifdef FEATURE_TCAS_DEBUG_THREAT_DETECTOR
874         printf("  Time to horizontal CPA: %4.2f\n",tau);
875 #endif
876         if (tau > pAlarmThresholds->RA.Tau)
877             tau = pAlarmThresholds->RA.Tau;
878         
879         // remember time to horizontal CPA
880         currentThreat.horizontalTau = tau;
881     }
882 }
883
884 /** Test threat detection logic. */
885 void
886 TCAS::ThreatDetector::unitTest(void)
887 {
888     pAlarmThresholds = &sensitivityLevels[1];
889 #if 0
890     // vertical tests
891     self.verticalFps = 0;
892     self.altFt = 1000;
893     cout << "identical altitude and vspeed " << endl;
894     checkVerticalThreat(self.altFt, self.verticalFps);
895     cout << "1000ft alt offset, dV=100 " << endl;
896     checkVerticalThreat(self.altFt+1000, 100);
897     cout << "-1000ft alt offset, dV=100 " << endl;
898     checkVerticalThreat(self.altFt-1000, 100);
899     cout << "3000ft alt offset, dV=10 " << endl;
900     checkVerticalThreat(self.altFt+3000, 10);
901     cout << "500ft alt offset, dV=100 " << endl;
902     checkVerticalThreat(self.altFt+500, 100);
903     cout << "500ft alt offset, dV=-100 " << endl;
904     checkVerticalThreat(self.altFt+500, -100);
905
906     // horizontal tests
907     self.heading = 0;
908     self.velocityKt = 0;
909     cout << "10nm behind, overtaking with 1Nm/s" << endl;
910     horizontalThreat(-180, 10, 0, 1/(SG_KT_TO_MPS*SG_METER_TO_NM));
911
912     cout << "10nm ahead, departing with 1Nm/s" << endl;
913     horizontalThreat(0, 20, 0, 1/(SG_KT_TO_MPS*SG_METER_TO_NM));
914
915     self.heading = 90;
916     self.velocityKt = 1/(SG_KT_TO_MPS*SG_METER_TO_NM);
917     cout << "10nm behind, overtaking with 1Nm/s at 90 degrees" << endl;
918     horizontalThreat(-90, 20, 90, 2/(SG_KT_TO_MPS*SG_METER_TO_NM));
919
920     self.heading = 20;
921     self.velocityKt = 1/(SG_KT_TO_MPS*SG_METER_TO_NM);
922     cout << "10nm behind, overtaking with 1Nm/s at 20 degrees" << endl;
923     horizontalThreat(200, 20, 20, 2/(SG_KT_TO_MPS*SG_METER_TO_NM));
924 #endif
925 }
926
927 ///////////////////////////////////////////////////////////////////////////////
928 // TCAS::AdvisoryGenerator ////////////////////////////////////////////////////
929 ///////////////////////////////////////////////////////////////////////////////
930
931 TCAS::AdvisoryGenerator::AdvisoryGenerator(TCAS* _tcas) :
932     tcas(_tcas),
933     pSelf(NULL),
934     pCurrentThreat(NULL),
935     pAlarmThresholds(NULL)
936 {
937 }
938
939 void
940 TCAS::AdvisoryGenerator::init(const LocalInfo* _pSelf, ThreatInfo* _pCurrentThreat)
941 {
942     pCurrentThreat = _pCurrentThreat;
943     pSelf = _pSelf;
944 }
945
946 void
947 TCAS::AdvisoryGenerator::setAlarmThresholds(const SensitivityLevel* _pAlarmThresholds)
948 {
949     pAlarmThresholds = _pAlarmThresholds;
950 }
951
952 /** Calculate projected vertical separation at horizontal CPA. */
953 float
954 TCAS::AdvisoryGenerator::verticalSeparation(float newVerticalFps)
955 {
956     // calculate relative vertical speed and altitude
957     float dV = pCurrentThreat->verticalFps - newVerticalFps;
958     float tau = pCurrentThreat->horizontalTau;
959     // don't use negative tau to project future separation...
960     if (tau < 0.5)
961         tau = 0.5;
962     return pCurrentThreat->relativeAltitudeFt + tau * dV;
963 }
964
965 /** Determine RA sense. */
966 void
967 TCAS::AdvisoryGenerator::determineRAsense(int& RASense, bool& isCrossing)
968 {
969     /* [TCASII]: "[..] a two step process is used to select the appropriate RA for the encounter
970              *   geometry. The first step in the process is to select the RA sense, i.e., upward or downward." */
971     RASense = 0;
972     isCrossing = false;
973     
974     /* [TCASII]: "Based on the range and altitude tracks of the intruder, the CAS logic models the
975      *   intruder's flight path from its present position to CPA. The CAS logic then models upward
976      *   and downward sense RAs for own aircraft [..] to determine which sense provides the most
977      *   vertical separation at CPA." */
978     float upSenseRelAltFt   = verticalSeparation(+2000/60.0);
979     float downSenseRelAltFt = verticalSeparation(-2000/60.0);
980     if (fabs(upSenseRelAltFt) >= fabs(downSenseRelAltFt))
981         RASense = +1;  // upward
982     else
983         RASense = -1; // downward
984
985     /* [TCASII]: "In encounters where either of the senses results in the TCAS aircraft crossing through
986      *   the intruder's altitude, TCAS is designed to select the nonaltitude crossing sense if the
987      *   noncrossing sense provides the desired vertical separation, known as ALIM, at CPA." */
988     /* [TCASII]: "If ALIM cannot be obtained in the nonaltitude crossing sense, an altitude
989      *   crossing RA will be issued." */
990     if ((RASense > 0)&&
991         (pCurrentThreat->relativeAltitudeFt > 200))
992     {
993         // threat is above and RA is crossing
994         if (fabs(downSenseRelAltFt) > pAlarmThresholds->TA.ALIM)
995         {
996             // non-crossing descend is sufficient 
997             RASense = -1;
998         }
999         else
1000         {
1001             // keep crossing climb RA
1002             isCrossing = true;
1003         }
1004     }
1005     else
1006     if ((RASense < 0)&&
1007         (pCurrentThreat->relativeAltitudeFt < -200))
1008     {
1009         // threat is below and RA is crossing
1010         if (fabs(upSenseRelAltFt) > pAlarmThresholds->TA.ALIM)
1011         {
1012             // non-crossing climb is sufficient 
1013             RASense = 1;
1014         }
1015         else
1016         {
1017             // keep crossing descent RA
1018             isCrossing = true;
1019         }
1020     }
1021     // else: threat is at same altitude, keep optimal RA sense (non-crossing)
1022
1023     pCurrentThreat->RASense = RASense;
1024
1025 #ifdef FEATURE_TCAS_DEBUG_ADV_GENERATOR
1026         printf("  RASense: %i, crossing: %u, relAlt: %4.1f, upward separation: %4.1f, downward separation: %4.1f\n",
1027                RASense,isCrossing,
1028                pCurrentThreat->relativeAltitudeFt,
1029                upSenseRelAltFt,downSenseRelAltFt);
1030 #endif
1031 }
1032
1033 /** Determine suitable resolution advisories. */
1034 int
1035 TCAS::AdvisoryGenerator::resolution(int mode, int threatLevel, float rangeNm, float altFt,
1036                                     float heading, float velocityKt)
1037 {
1038     int RAOption = OptionNone;
1039     int RA       = AdvisoryIntrusion;
1040
1041     // RAs are disabled under certain conditions
1042     if (threatLevel == ThreatRA)
1043     {
1044         /* [TCASII]: "... less than 360 feet, TCAS considers the reporting aircraft
1045          *   to be on the ground. If TCAS determines the intruder to be on the ground, it
1046          *   inhibits the generation of advisories against this aircraft."*/
1047         if (altFt < 360)
1048             threatLevel = ThreatTA;
1049
1050         /* [EUROACAS]: "Certain RAs are inhibited at altitudes based on inputs from the radio altimeter:
1051          *   [..] (c)1000ft (+/- 100ft) and below, all RAs are inhibited;" */
1052         if (pSelf->radarAltFt < 1000)
1053             threatLevel = ThreatTA;
1054         
1055         // RAs only issued in mode "Auto" (= "TA/RA" mode)
1056         if (mode != SwitchAuto)
1057             threatLevel = ThreatTA;
1058     }
1059
1060     bool isCrossing = false; 
1061     int RASense = 0;
1062     // determine suitable RAs
1063     if (threatLevel == ThreatRA)
1064     {
1065         /* [TCASII]: "[..] a two step process is used to select the appropriate RA for the encounter
1066          *   geometry. The first step in the process is to select the RA sense, i.e., upward or downward." */
1067         determineRAsense(RASense, isCrossing);
1068
1069         /* second step: determine required strength */
1070         if (RASense > 0)
1071         {
1072             // upward
1073
1074             if ((pSelf->verticalFps < -1000/60.0)&&
1075                 (!isCrossing))
1076             {
1077                 // currently descending, see if reducing current descent is sufficient 
1078                 float relAltFt = verticalSeparation(-500/60.0);
1079                 if (relAltFt > pAlarmThresholds->TA.ALIM)
1080                     RA |= AdvisoryAdjustVSpeed;
1081             }
1082             RA |= AdvisoryClimb;
1083             if (isCrossing)
1084                 RAOption |= OptionCrossingClimb;
1085         }
1086
1087         if (RASense < 0)
1088         {
1089             // downward
1090
1091             if ((pSelf->verticalFps > 1000/60.0)&&
1092                 (!isCrossing))
1093             {
1094                 // currently climbing, see if reducing current climb is sufficient 
1095                 float relAltFt = verticalSeparation(500/60.0);
1096                 if (relAltFt < -pAlarmThresholds->TA.ALIM)
1097                     RA |= AdvisoryAdjustVSpeed;
1098             }
1099             RA |= AdvisoryDescend;
1100             if (isCrossing)
1101                 RAOption |= OptionCrossingDescent;
1102         }
1103
1104         //TODO
1105         /* [TCASII]: "When two TCAS-equipped aircraft are converging vertically with opposite rates
1106          *   and are currently well separated in altitude, TCAS will first issue a vertical speed
1107          *   limit (Negative) RA to reinforce the pilots' likely intention to level off at adjacent
1108          *   flight levels." */
1109         
1110         //TODO
1111         /* [TCASII]: "[..] if the CAS logic determines that the response to a Positive RA has provided
1112          *   ALIM feet of vertical separation before CPA, the initial RA will be weakened to either a
1113          *   Do Not Descend RA (after an initial Climb RA) or a Do Not Climb RA (after an initial
1114          *   Descend RA)." */
1115         
1116         //TODO
1117         /* [TCASII]: "TCAS is designed to inhibit Increase Descent RAs below 1450 feet AGL; */
1118         
1119         /* [TCASII]: "Descend RAs below 1100 feet AGL;" (inhibited) */
1120         if (pSelf->radarAltFt < 1100)
1121         {
1122             RA &= ~AdvisoryDescend;
1123             //TODO Support "Do not descend" RA
1124             RA |= AdvisoryIntrusion;
1125         }
1126     }
1127
1128 #ifdef FEATURE_TCAS_DEBUG_ADV_GENERATOR
1129     cout << "  resolution advisory: " << RA << endl;
1130 #endif
1131
1132     ResolutionAdvisory newAdvisory;
1133     newAdvisory.RAOption    = RAOption;
1134     newAdvisory.RA          = RA;
1135     newAdvisory.threatLevel = threatLevel;
1136     tcas->advisoryCoordinator.add(newAdvisory);
1137     
1138     return threatLevel;
1139 }
1140
1141 ///////////////////////////////////////////////////////////////////////////////
1142 // TCAS ///////////////////////////////////////////////////////////////////////
1143 ///////////////////////////////////////////////////////////////////////////////
1144
1145 TCAS::TCAS(SGPropertyNode* pNode) :
1146     name("tcas"),
1147     num(0),
1148     nextUpdateTime(0),
1149     selfTestStep(0),
1150     properties_handler(this),
1151     threatDetector(this),
1152     tracker(this),
1153     advisoryCoordinator(this),
1154     advisoryGenerator(this),
1155     annunciator(this)
1156 {
1157     for (int i = 0; i < pNode->nChildren(); ++i)
1158     {
1159         SGPropertyNode* pChild = pNode->getChild(i);
1160         string cname = pChild->getName();
1161         string cval = pChild->getStringValue();
1162
1163         if (cname == "name")
1164             name = cval;
1165         else if (cname == "number")
1166             num = pChild->getIntValue();
1167         else
1168         {
1169             SG_LOG(SG_INSTR, SG_WARN, "Error in TCAS config logic");
1170             if (name.length())
1171                 SG_LOG(SG_INSTR, SG_WARN, "Section = " << name);
1172         }
1173     }
1174 }
1175
1176 void
1177 TCAS::init(void)
1178 {
1179     annunciator.init();
1180     advisoryCoordinator.init();
1181     threatDetector.init();
1182 }
1183
1184 void
1185 TCAS::bind(void)
1186 {
1187     SGPropertyNode* node = fgGetNode(("/instrumentation/" + name).c_str(), num, true);
1188
1189     nodeServiceable  = node->getNode("serviceable", true);
1190
1191     // TCAS mode selection (0=off, 1=standby, 2=TA only, 3=auto(TA/RA) ) 
1192     nodeModeSwitch   = node->getNode("inputs/mode", true);
1193     // self-test button
1194     nodeSelfTest     = node->getNode("inputs/self-test", true);
1195     // default value
1196     nodeSelfTest->setBoolValue(false);
1197
1198 #ifdef FEATURE_TCAS_DEBUG_PROPERTIES
1199     SGPropertyNode* nodeDebug = node->getNode("debug", true);
1200     // debug triggers
1201     nodeDebugTrigger = nodeDebug->getNode("threat-trigger", true);
1202     nodeDebugRA      = nodeDebug->getNode("threat-RA",      true);
1203     nodeDebugThreat  = nodeDebug->getNode("threat-level",   true);
1204     // default values
1205     nodeDebugTrigger->setBoolValue(false);
1206     nodeDebugRA->setIntValue(3);
1207     nodeDebugThreat->setIntValue(1);
1208 #endif
1209
1210     annunciator.bind(node);
1211     advisoryCoordinator.bind(node);
1212 }
1213
1214 void
1215 TCAS::unbind(void)
1216 {
1217     properties_handler.unbind();
1218 }
1219
1220 /** Monitor traffic for safety threats. */
1221 void
1222 TCAS::update(double dt)
1223 {
1224     if (!nodeServiceable->getBoolValue())
1225         return;
1226     int mode = nodeModeSwitch->getIntValue();
1227     if (mode == SwitchOff)
1228         return;
1229
1230     nextUpdateTime -= dt;
1231     if (nextUpdateTime <= 0.0 )
1232     {
1233         nextUpdateTime = 1.0;
1234
1235         // remove obsolete targets
1236         tracker.update();
1237
1238         // get aircrafts current position/speed/heading
1239         threatDetector.update();
1240
1241         // clear old threats
1242         advisoryCoordinator.clear();
1243
1244         if (nodeSelfTest->getBoolValue())
1245         {
1246             if (threatDetector.getVelocityKt() >= 40)
1247             {
1248                 // disable self-test when plane moves above taxiing speed
1249                 nodeSelfTest->setBoolValue(false);
1250                 selfTestStep = 0;
1251             }
1252             else
1253             {
1254                 selfTest();
1255                 // speed-up self test
1256                 nextUpdateTime = 0;
1257                 // no further TCAS processing during self-test
1258                 return;
1259             }
1260         }
1261
1262 #ifdef FEATURE_TCAS_DEBUG_PROPERTIES
1263         if (nodeDebugTrigger->getBoolValue())
1264         {
1265             // debugging test
1266             ResolutionAdvisory debugAdvisory;
1267             debugAdvisory.RAOption    = OptionNone;
1268             debugAdvisory.RA          = nodeDebugRA->getIntValue();
1269             debugAdvisory.threatLevel = nodeDebugThreat->getIntValue();
1270             advisoryCoordinator.add(debugAdvisory);
1271         }
1272         else
1273 #endif
1274         {
1275             SGPropertyNode* pAi = fgGetNode("/ai/models", true);
1276
1277             // check all aircraft
1278             for (int i = pAi->nChildren() - 1; i >= -1; i--)
1279             {
1280                 SGPropertyNode* pModel = pAi->getChild(i);
1281                 if ((pModel)&&(pModel->nChildren()))
1282                 {
1283                     int threatLevel = threatDetector.checkThreat(mode, pModel);
1284                     /* expose aircraft threat-level (to be used by other instruments,
1285                      * i.e. TCAS display) */
1286                     if (threatLevel==ThreatRA)
1287                         pModel->setIntValue("tcas/ra-sense", -threatDetector.getRASense());
1288                     pModel->setIntValue("tcas/threat-level", threatLevel);
1289                 }
1290             }
1291         }
1292         advisoryCoordinator.update(mode);
1293     }
1294     annunciator.update();
1295 }
1296
1297 /** Run a single self-test iteration. */
1298 void
1299 TCAS::selfTest(void)
1300 {
1301     annunciator.update();
1302     if (annunciator.isPlaying())
1303     {
1304         return;
1305     }
1306
1307     ResolutionAdvisory newAdvisory;
1308     newAdvisory.threatLevel = ThreatRA;
1309     newAdvisory.RA          = AdvisoryClear;
1310     newAdvisory.RAOption    = OptionNone;
1311     // TCAS audio is disabled below 500ft AGL
1312     threatDetector.setRadarAlt(501);
1313
1314     // trigger various advisories
1315     switch(selfTestStep)
1316     {
1317         case 0:
1318             newAdvisory.RA = AdvisoryIntrusion;
1319             newAdvisory.threatLevel = ThreatTA;
1320             break;
1321         case 1:
1322             newAdvisory.RA = AdvisoryClimb;
1323             break;
1324         case 2:
1325             newAdvisory.RA = AdvisoryClimb;
1326             newAdvisory.RAOption = OptionIncreaseClimb;
1327             break;
1328         case 3:
1329             newAdvisory.RA = AdvisoryClimb;
1330             newAdvisory.RAOption = OptionCrossingClimb;
1331             break;
1332         case 4:
1333             newAdvisory.RA = AdvisoryDescend;
1334             break;
1335         case 5:
1336             newAdvisory.RA = AdvisoryDescend;
1337             newAdvisory.RAOption = OptionIncreaseDescend;
1338             break;
1339         case 6:
1340             newAdvisory.RA = AdvisoryDescend;
1341             newAdvisory.RAOption = OptionCrossingDescent;
1342             break;
1343         case 7:
1344             newAdvisory.RA = AdvisoryAdjustVSpeed;
1345             break;
1346         case 8:
1347             newAdvisory.RA = AdvisoryMaintVSpeed;
1348             break;
1349         case 9:
1350             newAdvisory.RA = AdvisoryMonitorVSpeed;
1351             break;
1352         case 10:
1353             newAdvisory.threatLevel = ThreatNone;
1354             newAdvisory.RA = AdvisoryClear;
1355             break;
1356         case 11:
1357             annunciator.test(true);
1358             selfTestStep+=2;
1359             return;
1360         default:
1361             nodeSelfTest->setBoolValue(false);
1362             selfTestStep = 0;
1363             return;
1364     }
1365
1366     advisoryCoordinator.add(newAdvisory);
1367     advisoryCoordinator.update(SwitchAuto);
1368
1369     selfTestStep++;
1370 }
1371
1372 ///////////////////////////////////////////////////////////////////////////////
1373 // TCAS::Tracker //////////////////////////////////////////////////////////////
1374 ///////////////////////////////////////////////////////////////////////////////
1375
1376 TCAS::Tracker::Tracker(TCAS* _tcas) :
1377     tcas(_tcas),
1378     currentTime(0),
1379     haveTargets(false),
1380     newTargets(false)
1381 {
1382     targets.clear();
1383 }
1384
1385 void
1386 TCAS::Tracker::update(void)
1387 {
1388     currentTime = globals->get_sim_time_sec();
1389     newTargets = false;
1390
1391     if (haveTargets)
1392     {
1393         // remove outdated targets
1394         TrackerTargets::iterator it = targets.begin();
1395         while (it != targets.end())
1396         {
1397             TrackerTarget* pTarget = it->second;
1398             if (currentTime - pTarget->TAtimestamp > 10.0)
1399             {
1400                 TrackerTargets::iterator temp = it;
1401                 ++it;
1402 #ifdef FEATURE_TCAS_DEBUG_TRACKER
1403                 printf("target %s no longer a TA threat.\n",temp->first.c_str());
1404 #endif
1405                 targets.erase(temp->first);
1406                 delete pTarget;
1407                 pTarget = NULL;
1408             }
1409             else
1410             {
1411                 if ((pTarget->threatLevel == ThreatRA)&&
1412                     (currentTime - pTarget->RAtimestamp > 7.0))
1413                 {
1414                     pTarget->threatLevel = ThreatTA;
1415 #ifdef FEATURE_TCAS_DEBUG_TRACKER
1416                     printf("target %s no longer an RA threat.\n",it->first.c_str());
1417 #endif
1418                 }
1419                 ++it;
1420             }
1421         }
1422         haveTargets = !targets.empty();
1423     }
1424 }
1425
1426 void
1427 TCAS::Tracker::add(const string callsign, int detectedLevel)
1428 {
1429     TrackerTarget* pTarget = NULL;
1430     if (haveTargets)
1431     {
1432         TrackerTargets::iterator it = targets.find(callsign);
1433         if (it != targets.end())
1434         {
1435             pTarget = it->second;
1436         }
1437     }
1438
1439     if (!pTarget)
1440     {
1441         pTarget = new TrackerTarget();
1442         pTarget->TAtimestamp = 0;
1443         pTarget->RAtimestamp = 0;
1444         pTarget->threatLevel = 0;
1445         newTargets = true;
1446         targets[callsign] = pTarget;
1447 #ifdef FEATURE_TCAS_DEBUG_TRACKER
1448         printf("new target: %s, level: %i\n",callsign.c_str(),detectedLevel);
1449 #endif
1450     }
1451
1452     if (detectedLevel > pTarget->threatLevel)
1453         pTarget->threatLevel = detectedLevel;
1454
1455     if (detectedLevel >= ThreatTA)
1456         pTarget->TAtimestamp = currentTime;
1457
1458     if (detectedLevel >= ThreatRA)
1459         pTarget->RAtimestamp = currentTime;
1460
1461     haveTargets = true;
1462 }
1463
1464 bool
1465 TCAS::Tracker::_isTracked(string callsign)
1466 {
1467     return targets.find(callsign) != targets.end();
1468 }
1469
1470 int
1471 TCAS::Tracker::getThreatLevel(string callsign)
1472 {
1473     TrackerTargets::iterator it = targets.find(callsign);
1474     if (it != targets.end())
1475         return it->second->threatLevel;
1476     else
1477         return 0;
1478 }