]> git.mxchange.org Git - flightgear.git/blob - src/Instrumentation/tcas.cxx
Fix issues with explicit GPS instruments.
[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/sound/sample_group.hxx>
105 #include <simgear/structure/exception.hxx>
106
107 using std::string;
108
109 #if defined( HAVE_VERSION_H ) && HAVE_VERSION_H
110 #  include <Include/version.h>
111 #else
112 #  include <Include/no_version.h>
113 #endif
114
115 #include <Main/fg_props.hxx>
116 #include <Main/globals.hxx>
117 #include "instrument_mgr.hxx"
118 #include "tcas.hxx"
119
120 ///////////////////////////////////////////////////////////////////////////////
121 // debug switches /////////////////////////////////////////////////////////////
122 ///////////////////////////////////////////////////////////////////////////////
123 //#define FEATURE_TCAS_DEBUG_ANNUNCIATOR
124 //#define FEATURE_TCAS_DEBUG_COORDINATOR
125 //#define FEATURE_TCAS_DEBUG_THREAT_DETECTOR
126 //#define FEATURE_TCAS_DEBUG_TRACKER
127 //#define FEATURE_TCAS_DEBUG_ADV_GENERATOR
128 //#define FEATURE_TCAS_DEBUG_PROPERTIES
129
130 ///////////////////////////////////////////////////////////////////////////////
131 // constants //////////////////////////////////////////////////////////////////
132 ///////////////////////////////////////////////////////////////////////////////
133
134 /** Sensitivity Level Definition and Alarm Thresholds (TCASII, Version 7) 
135  *  Max Own        |    |TA-level                |RA-level
136  *  Altitude(ft)   | SL |Tau(s),DMOD(nm),ALIM(ft)|Tau(s),DMOD(nm),ALIM(ft) */
137 const TCAS::SensitivityLevel
138 TCAS::ThreatDetector::sensitivityLevels[] = {
139    { 1000,           2,  {20,   0.30,     850},  {0,    0,        0  }}, 
140    { 2350,           3,  {25,   0.33,     850},  {15,   0.20,     300}},
141    { 5000,           4,  {30,   0.48,     850},  {20,   0.35,     300}},
142    {10000,           5,  {40,   0.75,     850},  {25,   0.55,     350}},
143    {20000,           6,  {45,   1.00,     850},  {30,   0.80,     400}},
144    {42000,           7,  {48,   1.30,     850},  {35,   1.10,     600}},
145    {0,               8,  {48,   1.30,    1200},  {35,   1.10,     700}}
146 };
147
148 ///////////////////////////////////////////////////////////////////////////////
149 // helpers ////////////////////////////////////////////////////////////////////
150 ///////////////////////////////////////////////////////////////////////////////
151
152 #define ADD_VOICE(Var, Sample, SayTwice)    \
153     { make_voice(&Var);                    \
154       append(Var, Sample);                  \
155       if (SayTwice) append(Var, Sample); }
156
157 #define AVAILABLE_RA(Options, Advisory) (Advisory == (Advisory & Options))
158
159 #ifdef FEATURE_TCAS_DEBUG_THREAT_DETECTOR
160 /** calculate relative angle in between two headings */
161 static float
162 relAngle(float Heading1, float Heading2)
163 {
164     Heading1 -= Heading2;
165
166     while (Heading1 >= 360.0)
167         Heading1 -= 360.0;
168
169     while (Heading1 < 0.0)
170         Heading1 += 360;
171
172     return Heading1;
173 }
174 #endif
175
176 /** calculate range and bearing of lat2/lon2 relative to lat1/lon1 */ 
177 static void
178 calcRangeBearing(double lat1, double lon1, double lat2, double lon2,
179                  double &rangeNm, double &bearing)
180 {
181     // calculate the bearing and range of the second pos from the first
182     double az2, distanceM;
183     geo_inverse_wgs_84(lat1, lon1, lat2, lon2, &bearing, &az2, &distanceM);
184     rangeNm = distanceM * SG_METER_TO_NM;
185 }
186
187 ///////////////////////////////////////////////////////////////////////////////
188 // VoicePlayer ////////////////////////////////////////////////////////////////
189 ///////////////////////////////////////////////////////////////////////////////
190
191 void
192 TCAS::VoicePlayer::init(void)
193 {
194     FGVoicePlayer::init();
195
196     ADD_VOICE(Voices.pTrafficTraffic, "traffic",                 true);
197     ADD_VOICE(Voices.pClear,          "clear",                   false);
198     ADD_VOICE(Voices.pClimb,          "climb",                   true);
199     ADD_VOICE(Voices.pClimbNow,       "climb_now",               true);
200     ADD_VOICE(Voices.pClimbCrossing,  "climb_crossing",          true);
201     ADD_VOICE(Voices.pClimbIncrease,  "increase_climb",          false);
202     ADD_VOICE(Voices.pDescend,        "descend",                 true);
203     ADD_VOICE(Voices.pDescendNow,     "descend_now",             true);
204     ADD_VOICE(Voices.pDescendCrossing,"descend_crossing",        true);
205     ADD_VOICE(Voices.pDescendIncrease,"increase_descent",        false);
206     ADD_VOICE(Voices.pAdjustVSpeed,   "adjust_vertical_speed",   false);
207     ADD_VOICE(Voices.pMaintVSpeed,    "maintain_vertical_speed", false);
208     ADD_VOICE(Voices.pMonitorVSpeed,  "monitor_vertical_speed",  false);
209     ADD_VOICE(Voices.pLevelOff,       "level_off",               false);
210     ADD_VOICE(Voices.pTestOk,         "test_ok",                 false);
211     ADD_VOICE(Voices.pTestFail,       "test_fail",               false);
212
213     speaker.update_configuration();
214 }
215
216 /////////////////////////////////////////////////////////////////////////////
217 // TCAS::Annunciator ////////////////////////////////////////////////////////
218 /////////////////////////////////////////////////////////////////////////////
219
220 TCAS::Annunciator::Annunciator(TCAS* _tcas) :
221     tcas(_tcas),
222     pLastVoice(NULL),
223     voicePlayer(_tcas)
224 {
225     clear();
226 }
227
228 void TCAS::Annunciator::clear(void)
229 {
230     previous.threatLevel = ThreatNone;
231     previous.RA          = AdvisoryClear;
232     previous.RAOption    = OptionNone;
233     pLastVoice = NULL;
234 }
235
236 void
237 TCAS::Annunciator::bind(SGPropertyNode* node)
238 {
239     voicePlayer.bind(node, "Sounds/tcas/female/");
240 }
241
242 void
243 TCAS::Annunciator::init(void)
244 {
245     //TODO link to GPWS module/audio-on signal must be configurable
246     nodeGpwsAlertOn = fgGetNode("/instrumentation/mk-viii/outputs/discretes/audio-on", true);
247     voicePlayer.init();
248 }
249
250 void
251 TCAS::Annunciator::update(void)
252 {
253     voicePlayer.update();
254     
255     /* [TCASII]: "The priority scheme gives ground proximity warning systems (GPWS)
256      *   a higher annunciation priority than a TCAS alert. TCAS aural annunciation will
257      *   be inhibited during the time that a GPWS alert is active." */
258     if (nodeGpwsAlertOn->getBoolValue())
259         voicePlayer.pause();
260     else
261         voicePlayer.resume();
262 }
263
264 /** Trigger voice sample for current alert. */
265 void
266 TCAS::Annunciator::trigger(const ResolutionAdvisory& current, bool revertedRA)
267 {
268     int RA = current.RA;
269     int RAOption = current.RAOption;
270
271     if (RA == AdvisoryClear)
272     {
273         if (previous.RA != AdvisoryClear)
274         {
275             voicePlayer.play(voicePlayer.Voices.pClear, VoicePlayer::PLAY_NOW);
276             previous = current;
277         }
278         pLastVoice = NULL;
279         return;
280     }
281
282     if ((previous.RA == AdvisoryClear)||
283         (tcas->tracker.newTraffic()))
284     {
285         voicePlayer.play(voicePlayer.Voices.pTrafficTraffic, VoicePlayer::PLAY_NOW);
286     }
287
288     // pick voice sample
289     VoicePlayer::Voice* pVoice = NULL;
290     switch(RA)
291     {
292         case AdvisoryClimb:
293             if (revertedRA)
294                 pVoice = voicePlayer.Voices.pClimbNow;
295             else
296             if (AVAILABLE_RA(RAOption, OptionIncreaseClimb))
297                 pVoice = voicePlayer.Voices.pClimbIncrease;
298             else
299             if (AVAILABLE_RA(RAOption, OptionCrossingClimb))
300                 pVoice = voicePlayer.Voices.pClimbCrossing;
301             else
302                 pVoice = voicePlayer.Voices.pClimb;
303             break;
304
305         case AdvisoryDescend:
306             if (revertedRA)
307                 pVoice = voicePlayer.Voices.pDescendNow;
308             else
309             if (AVAILABLE_RA(RAOption, OptionIncreaseDescend))
310                 pVoice = voicePlayer.Voices.pDescendIncrease;
311             else
312             if (AVAILABLE_RA(RAOption, OptionCrossingDescent))
313                 pVoice = voicePlayer.Voices.pDescendCrossing;
314             else
315                 pVoice = voicePlayer.Voices.pDescend;
316             break;
317
318         case AdvisoryAdjustVSpeed:
319             pVoice = voicePlayer.Voices.pAdjustVSpeed;
320             break;
321
322         case AdvisoryMaintVSpeed:
323             pVoice = voicePlayer.Voices.pMaintVSpeed;
324             break;
325
326         case AdvisoryMonitorVSpeed:
327             pVoice = voicePlayer.Voices.pMonitorVSpeed;
328             break;
329
330         case AdvisoryLevelOff:
331             pVoice = voicePlayer.Voices.pLevelOff;
332             break;
333
334         case AdvisoryIntrusion:
335             break;
336
337         default:
338             RA = AdvisoryIntrusion;
339             break;
340     }
341
342     previous = current;
343
344     if ((pLastVoice == pVoice)&&
345         (!tcas->tracker.newTraffic()))
346     {
347         // don't repeat annunciation
348         return;
349     }
350     pLastVoice = pVoice;
351     if (pVoice)
352         voicePlayer.play(pVoice);
353
354 #ifdef FEATURE_TCAS_DEBUG_ANNUNCIATOR
355     cout << "Annunciating TCAS RA " << RA << endl;
356 #endif
357 }
358
359 void
360 TCAS::Annunciator::test(bool testOk)
361 {
362     if (testOk)
363         voicePlayer.play(voicePlayer.Voices.pTestOk);
364     else
365         voicePlayer.play(voicePlayer.Voices.pTestFail);
366 }
367
368 /////////////////////////////////////////////////////////////////////////////
369 // TCAS::AdvisoryCoordinator ////////////////////////////////////////////////
370 /////////////////////////////////////////////////////////////////////////////
371
372 TCAS::AdvisoryCoordinator::AdvisoryCoordinator(TCAS* _tcas) :
373   tcas(_tcas),
374   lastTATime(0)
375 {
376     init();
377 }
378
379 void
380 TCAS::AdvisoryCoordinator::init(void)
381 {
382     reinit();
383 }
384
385 void
386 TCAS::AdvisoryCoordinator::reinit(void)
387 {
388     clear();
389     previous = current;
390 }
391
392 void
393 TCAS::AdvisoryCoordinator::bind(SGPropertyNode* node)
394 {
395     nodeTAWarning = node->getNode("outputs/traffic-alert", true);
396     nodeTAWarning->setBoolValue(false);
397 }
398
399 void
400 TCAS::AdvisoryCoordinator::clear(void)
401 {
402     current.threatLevel = ThreatNone;
403     current.RA          = AdvisoryClear;
404     current.RAOption    = OptionNone;
405 }
406
407 /** Add all suitable resolution advisories for a single threat. */
408 void
409 TCAS::AdvisoryCoordinator::add(const ResolutionAdvisory& newAdvisory)
410 {
411     if ((newAdvisory.RA == AdvisoryClear)||
412         (newAdvisory.threatLevel < current.threatLevel))
413         return;
414
415     if (current.threatLevel == newAdvisory.threatLevel)
416     {
417         // combine with other advisories so far
418         current.RA &= newAdvisory.RA;
419         // remember any advisory modifier
420         current.RAOption |= newAdvisory.RAOption;
421     }
422     else
423     {
424         current = newAdvisory;
425     }
426 }
427
428 /** Pick and trigger suitable resolution advisory. */
429 void
430 TCAS::AdvisoryCoordinator::update(int mode)
431 {
432     bool revertedRA = false; // has advisory changed?
433     double currentTime = globals->get_sim_time_sec();
434
435     if (current.RA == AdvisoryClear)
436     {
437         // filter: wait 5 seconds after last TA/RA before announcing TA clearance
438         if ((previous.RA != AdvisoryClear)&&
439              (currentTime - lastTATime < 5.0))
440             return;
441     }
442     else
443     {
444         // intruder detected
445
446 #ifdef FEATURE_TCAS_DEBUG_COORDINATOR
447         cout << "TCAS::Annunciator::update: previous: " << previous.RA << ", new: " << current.RA << endl;
448 #endif
449
450         lastTATime = currentTime;
451         if ((previous.RA == AdvisoryClear)||
452             (previous.RA == AdvisoryIntrusion)||
453             ((current.RA & previous.RA) != previous.RA))
454         {
455             // no RA yet, or we can't keep previous RA: pick one - in order of priority
456
457             if (AVAILABLE_RA(current.RA, AdvisoryMonitorVSpeed))
458             {
459                 // prio 1: monitor vertical speed only
460                 current.RA = AdvisoryMonitorVSpeed;
461             }
462             else
463             if (AVAILABLE_RA(current.RA, AdvisoryMaintVSpeed))
464             {
465                 // prio 2: maintain vertical speed
466                 current.RA = AdvisoryMaintVSpeed;
467             }
468             else
469             if (AVAILABLE_RA(current.RA, AdvisoryAdjustVSpeed))
470             {
471                 // prio 3: adjust vertical speed (TCAS II 7.0 only)
472                 current.RA = AdvisoryAdjustVSpeed;
473             }
474             else
475             if (AVAILABLE_RA(current.RA, AdvisoryLevelOff))
476             {
477                 // prio 3: adjust vertical speed (TCAS II 7.1 only, [EUROACAS]: CP115)
478                 current.RA = AdvisoryLevelOff;
479             }
480             else
481             if (AVAILABLE_RA(current.RA, AdvisoryClimb))
482             {
483                 // prio 4: climb
484                 current.RA = AdvisoryClimb;
485             }
486             else
487             if (AVAILABLE_RA(current.RA, AdvisoryDescend))
488             {
489                 // prio 5: descend
490                 current.RA = AdvisoryDescend;
491             }
492             else
493             {
494                 // no RA, issue a TA only
495                 current.RA = AdvisoryIntrusion;
496             }
497
498             // check if earlier advisory was reverted
499             revertedRA = ((previous.RA != current.RA)&&
500                           (previous.RA != 0)&&
501                           (previous.RA != AdvisoryIntrusion));
502         }
503         else
504         {
505             // keep earlier RA
506             current.RA = previous.RA;
507         }
508     }
509
510     /* [TCASII]: "Aural annunciations are inhibited below 500+/-100 feet AGL." */
511     if ((tcas->threatDetector.getRadarAlt() > 500)&&
512         (mode >= SwitchTaOnly))
513         tcas->annunciator.trigger(current, revertedRA);
514     else
515     if (current.RA == AdvisoryClear)
516     {
517         /* explicitly clear traffic alert (since aural annunciation disabled) */
518         tcas->annunciator.clear();
519     }
520
521     previous = current;
522     
523     /* [TCASII] "[..] also performs the function of setting flags that control the displays.
524      *   The traffic display, the RA display, [..] use these flags to alert the pilot to
525      *   the presence of TAs and RAs." */
526     nodeTAWarning->setBoolValue(current.RA != AdvisoryClear);
527 }
528
529 ///////////////////////////////////////////////////////////////////////////////
530 // TCAS::ThreatDetector ///////////////////////////////////////////////////////
531 ///////////////////////////////////////////////////////////////////////////////
532
533 TCAS::ThreatDetector::ThreatDetector(TCAS* _tcas) :
534     tcas(_tcas),
535     checkCount(0),
536     pAlarmThresholds(&sensitivityLevels[0])
537 {
538     self.radarAltFt = 0.0;
539     unitTest();
540 }
541
542 void
543 TCAS::ThreatDetector::init(void)
544 {
545     nodeLat         = fgGetNode("/position/latitude-deg",          true);
546     nodeLon         = fgGetNode("/position/longitude-deg",         true);
547     nodePressureAlt = fgGetNode("/position/altitude-ft",           true);
548     nodeRadarAlt    = fgGetNode("/position/altitude-agl-ft",       true);
549     nodeHeading     = fgGetNode("/orientation/heading-deg",        true);
550     nodeVelocity    = fgGetNode("/velocities/airspeed-kt",         true);
551     nodeVerticalFps = fgGetNode("/velocities/vertical-speed-fps",  true);
552     
553     tcas->advisoryGenerator.init(&self,&currentThreat);
554 }
555
556 /** Update local position and threat sensitivity levels. */
557 void
558 TCAS::ThreatDetector::update(void)
559 {
560     // update local position
561     self.lat           = nodeLat->getDoubleValue();
562     self.lon           = nodeLon->getDoubleValue();
563     self.pressureAltFt = nodePressureAlt->getDoubleValue();
564     self.heading       = nodeHeading->getDoubleValue();
565     self.velocityKt    = nodeVelocity->getDoubleValue();
566     self.verticalFps   = nodeVerticalFps->getDoubleValue();
567
568     /* radar altimeter provides a lot of spikes due to uneven terrain
569      * MK-VIII GPWS-spec requires smoothing the radar altitude with a
570      * 10second moving average. Likely the TCAS spec requires the same.
571      * => We use a cheap 10 second exponential average method.
572      */
573     const double SmoothingFactor = 0.3;
574     self.radarAltFt = nodeRadarAlt->getDoubleValue()*SmoothingFactor +
575             (1-SmoothingFactor)*self.radarAltFt;
576
577 #ifdef FEATURE_TCAS_DEBUG_THREAT_DETECTOR
578     printf("TCAS::ThreatDetector::update: radarAlt = %f\n",self.radarAltFt);
579     checkCount = 0;
580 #endif
581
582     // determine current altitude's "Sensitivity Level Definition and Alarm Thresholds" 
583     int sl=0;
584     for (sl=0;((self.radarAltFt > sensitivityLevels[sl].maxAltitude)&&
585                (sensitivityLevels[sl].maxAltitude));sl++);
586     pAlarmThresholds = &sensitivityLevels[sl];
587     tcas->advisoryGenerator.setAlarmThresholds(pAlarmThresholds);
588 }
589
590 /** Check if plane's transponder is enabled. */
591 bool
592 TCAS::ThreatDetector::checkTransponder(const SGPropertyNode* pModel, float velocityKt)
593 {
594     const string name = pModel->getName();
595     if (name != "multiplayer" && name != "aircraft")
596     {
597         // assume non-MP/non-AI planes (e.g. ships) have no transponder
598         return false;
599     }
600
601     if (velocityKt < 40)
602     {
603         /* assume all pilots have their transponder switched off while taxiing/parking
604          * (at low speed) */
605         return false;
606     }
607
608     if ((name == "multiplayer")&&
609         (pModel->getBoolValue("controls/invisible")))
610     {
611         // ignored MP plane: pretend transponder is switched off
612         return false;
613     }
614
615     return true;
616 }
617
618 /** Check if plane is a threat. */
619 int
620 TCAS::ThreatDetector::checkThreat(int mode, const SGPropertyNode* pModel)
621 {
622 #ifdef FEATURE_TCAS_DEBUG_THREAT_DETECTOR
623     checkCount++;
624 #endif
625     
626     float velocityKt  = pModel->getDoubleValue("velocities/true-airspeed-kt");
627
628     if (!checkTransponder(pModel, velocityKt))
629         return ThreatInvisible;
630
631     int threatLevel = ThreatNone;
632     float altFt = pModel->getDoubleValue("position/altitude-ft");
633     currentThreat.relativeAltitudeFt = altFt - self.pressureAltFt;
634
635     // save computation time: don't care when relative altitude is excessive
636     if (fabs(currentThreat.relativeAltitudeFt) > 10000)
637         return threatLevel;
638
639     // position data of current intruder
640     double lat        = pModel->getDoubleValue("position/latitude-deg");
641     double lon        = pModel->getDoubleValue("position/longitude-deg");
642     float heading     = pModel->getDoubleValue("orientation/true-heading-deg");
643
644     double distanceNm, bearing;
645     calcRangeBearing(self.lat, self.lon, lat, lon, distanceNm, bearing);
646
647     // save computation time: don't care for excessive distances (also captures NaNs...)
648     if ((distanceNm > 10)||(distanceNm < 0))
649         return threatLevel;
650
651     currentThreat.verticalFps = pModel->getDoubleValue("velocities/vertical-speed-fps");
652     
653     /* Detect proximity targets
654      * [TCASII]: "Any target that is less than 6 nmi in range and within +/-1200ft
655      *  vertically, but that does not meet the intruder or threat criteria." */
656     if ((distanceNm < 6)&&
657         (fabs(currentThreat.relativeAltitudeFt) < 1200))
658     {
659         // at least a proximity target
660         threatLevel = ThreatProximity;
661     }
662
663     /* do not detect any threats when in standby or on ground and taxiing */
664     if ((mode <= SwitchStandby)||
665         ((self.radarAltFt < 360)&&(self.velocityKt < 40)))
666     {
667         return threatLevel;
668     }
669
670     if (tcas->tracker.active())
671     {
672         currentThreat.callsign = pModel->getStringValue("callsign");
673         currentThreat.isTracked = tcas->tracker.isTracked(currentThreat.callsign);
674     }
675     else
676         currentThreat.isTracked = false;
677     
678     // first stage: vertical movement
679     checkVerticalThreat();
680
681     // stop processing when no vertical threat
682     if ((!currentThreat.verticalTA)&&
683         (!currentThreat.isTracked))
684         return threatLevel;
685
686     // second stage: horizontal movement
687     horizontalThreat(bearing, distanceNm, heading, velocityKt);
688
689     if (!currentThreat.isTracked)
690     {
691         // no horizontal threat?
692         if (!currentThreat.horizontalTA)
693             return threatLevel;
694
695         if ((currentThreat.horizontalTau < 0)||
696             (currentThreat.verticalTau < 0))
697         {
698             // do not trigger new alerts when Tau is negative, but keep existing alerts
699             int previousThreatLevel = pModel->getIntValue("tcas/threat-level", 0);
700             if (previousThreatLevel == 0)
701                 return threatLevel;
702         }
703     }
704
705 #ifdef FEATURE_TCAS_DEBUG_THREAT_DETECTOR
706     cout << "#" << checkCount << ": " << pModel->getStringValue("callsign") << endl;
707 #endif
708
709     
710     /* [TCASII]: "For either a TA or an RA to be issued, both the range and 
711      *    vertical criteria, in terms of tau or the fixed thresholds, must be
712      *    satisfied only one of the criteria is satisfied, TCAS will not issue
713      *    an advisory." */
714     if (currentThreat.horizontalTA && currentThreat.verticalTA)
715         threatLevel = ThreatTA;
716     if (currentThreat.horizontalRA && currentThreat.verticalRA)
717         threatLevel = ThreatRA;
718
719     if (!tcas->tracker.active())
720         currentThreat.callsign = pModel->getStringValue("callsign");
721
722     tcas->tracker.add(currentThreat.callsign, threatLevel);
723     
724     // check existing threat level
725     if (currentThreat.isTracked)
726     {
727         int oldLevel = tcas->tracker.getThreatLevel(currentThreat.callsign);
728         if (oldLevel > threatLevel)
729             threatLevel = oldLevel;
730     }
731
732     // find all resolution options for this conflict
733     threatLevel = tcas->advisoryGenerator.resolution(mode, threatLevel, distanceNm, altFt, heading, velocityKt);
734    
735     
736 #ifdef FEATURE_TCAS_DEBUG_THREAT_DETECTOR
737     printf("  threat: distance: %4.1f, bearing: %4.1f, alt: %5.1f, velocity: %4.1f, heading: %4.1f, vspeed: %4.1f, "
738            "own alt: %5.1f, own heading: %4.1f, own velocity: %4.1f, vertical tau: %3.2f"
739            //", closing speed: %f"
740            "\n",
741            distanceNm, relAngle(bearing, self.heading), altFt, velocityKt, heading, currentThreat.verticalFps,
742            self.altFt, self.heading, self.velocityKt
743            //, currentThreat.closingSpeedKt
744            ,currentThreat.verticalTau
745            );
746 #endif
747
748     return threatLevel;
749 }
750
751 /** Check if plane is a vertical threat. */
752 void
753 TCAS::ThreatDetector::checkVerticalThreat(void)
754 {
755     // calculate relative vertical speed and altitude
756     float dV = self.verticalFps - currentThreat.verticalFps;
757     float dA = currentThreat.relativeAltitudeFt;
758
759     currentThreat.verticalTA  = false;
760     currentThreat.verticalRA  = false;
761     currentThreat.verticalTau = 0;
762
763     /* [TCASII]: "The vertical tau is equal to the altitude separation (feet)
764      *   divided by the combined vertical speed of the two aircraft (feet/minute)
765      *   times 60." */
766     float tau = 0;
767     if (fabs(dV) > 0.1)
768         tau = dA/dV;
769
770     /* [TCASII]: "When the combined vertical speed of the TCAS and the intruder aircraft
771      *    is low, TCAS will use a fixed-altitude threshold to determine whether a TA or
772      *    an RA should be issued." */
773     if ((fabs(dV) < 3.0)||
774         ((tau < 0) && (tau > -5)))
775     {
776         /* vertical closing speed is low (below 180fpm/3fps), check
777          * fixed altitude range. */
778         float abs_dA = fabs(dA);
779         if (abs_dA < pAlarmThresholds->RA.ALIM)
780         {
781             // continuous intrusion at RA-level
782             currentThreat.verticalTA = true;
783             currentThreat.verticalRA = true;
784         }
785         else
786         if (abs_dA < pAlarmThresholds->TA.ALIM)
787         {
788             // continuous intrusion: with TA-level, but no RA-threat
789             currentThreat.verticalTA = true;
790         }
791         // else: no RA/TA threat
792     }
793     else
794     {
795         if ((tau < pAlarmThresholds->TA.Tau)&&
796             (tau >= -5))
797         {
798             currentThreat.verticalTA = true;
799             currentThreat.verticalRA = (tau < pAlarmThresholds->RA.Tau);
800         }
801     }
802     currentThreat.verticalTau = tau;
803
804 #ifdef FEATURE_TCAS_DEBUG_THREAT_DETECTOR
805     if (currentThreat.verticalTA)
806         printf("  vertical dV=%f (%f-%f), dA=%f\n", dV, self.verticalFps, currentThreat.verticalFps, dA);
807 #endif
808 }
809
810 /** Check if plane is a horizontal threat. */
811 void
812 TCAS::ThreatDetector::horizontalThreat(float bearing, float distanceNm, float heading, float velocityKt)
813 {
814     // calculate speed
815     float vxKt = sin(heading*SGD_DEGREES_TO_RADIANS)*velocityKt - sin(self.heading*SGD_DEGREES_TO_RADIANS)*self.velocityKt;
816     float vyKt = cos(heading*SGD_DEGREES_TO_RADIANS)*velocityKt - cos(self.heading*SGD_DEGREES_TO_RADIANS)*self.velocityKt;
817
818     // calculate horizontal closing speed
819     float closingSpeedKt2 = vxKt*vxKt+vyKt*vyKt; 
820     float closingSpeedKt  = sqrt(closingSpeedKt2);
821
822     /* [TCASII]: "The range tau is equal to the slant range (nmi) divided by the closing speed
823      *    (knots) multiplied by 3600."
824      * => calculate allowed slant range (nmi) based on known maximum tau */
825     float TA_rangeNm = (pAlarmThresholds->TA.Tau*closingSpeedKt)/3600;
826     float RA_rangeNm = (pAlarmThresholds->RA.Tau*closingSpeedKt)/3600;
827
828     if (closingSpeedKt < 100)
829     {
830         /* [TCASII]: "In events where the rate of closure is very low, [..]
831          *    an intruder aircraft can come very close in range without crossing the
832          *    range tau boundaries [..]. To provide protection in these types of
833          *    advisories, the range tau boundaries are modified [..] to use
834          *    a fixed-range threshold to issue TAs and RAs in these slow closure
835          *    encounters." */
836         TA_rangeNm += (100.0-closingSpeedKt)*(pAlarmThresholds->TA.DMOD/100.0);
837         RA_rangeNm += (100.0-closingSpeedKt)*(pAlarmThresholds->RA.DMOD/100.0);
838     }
839     if (TA_rangeNm < pAlarmThresholds->TA.DMOD)
840         TA_rangeNm = pAlarmThresholds->TA.DMOD;
841     if (RA_rangeNm < pAlarmThresholds->RA.DMOD)
842         RA_rangeNm = pAlarmThresholds->RA.DMOD;
843
844     currentThreat.horizontalTA   = (distanceNm < TA_rangeNm);
845     currentThreat.horizontalRA   = (distanceNm < RA_rangeNm);
846     currentThreat.horizontalTau  = -1;
847     
848     if ((currentThreat.horizontalRA)&&
849         (currentThreat.verticalRA))
850     {
851         /* an RA will be issued. Prepare extra data for the
852          * traffic resolution stage, i.e. calculate
853          * exact time tau to horizontal CPA.
854          */
855
856         /* relative position of intruder is
857          *   Sx(t) = sx + vx*t
858          *   Sy(t) = sy + vy*t
859          * horizontal distance to intruder is r(t)
860          *   r(t) = sqrt( Sx(t)^2 + Sy(t)^2 )
861          * => horizontal CPA at time t=tau, where r(t) has minimum
862          * r2(t) := r^2(t) = Sx(t)^2 + Sy(t)^2
863          * since r(t)>0 for all t => minimum of r(t) is also minimum of r2(t)
864          * => (d/dt) r2(t) = r2'(t) is 0 for t=tau
865          *    r2(t) = ((Sx(t)^2 + Sy(t))^2) = c + b*t + a*t^2
866          * => r2'(t) = b + a*2*t
867          * at t=tau:
868          *    r2'(tau) = 0 = b + 2*a*tau
869          * => tau = -b/(2*a) 
870          */
871         float sx = sin(bearing*SGD_DEGREES_TO_RADIANS)*distanceNm;
872         float sy = cos(bearing*SGD_DEGREES_TO_RADIANS)*distanceNm;
873         float vx = vxKt * (SG_KT_TO_MPS*SG_METER_TO_NM);
874         float vy = vyKt * (SG_KT_TO_MPS*SG_METER_TO_NM);
875         float a  = vx*vx + vy*vy;
876         float b  = 2*(sx*vx + sy*vy);
877         float tau = 0;
878         if (a > 0.0001)
879             tau = -b/(2*a);
880 #ifdef FEATURE_TCAS_DEBUG_THREAT_DETECTOR
881         printf("  Time to horizontal CPA: %4.2f\n",tau);
882 #endif
883         if (tau > pAlarmThresholds->RA.Tau)
884             tau = pAlarmThresholds->RA.Tau;
885         
886         // remember time to horizontal CPA
887         currentThreat.horizontalTau = tau;
888     }
889 }
890
891 /** Test threat detection logic. */
892 void
893 TCAS::ThreatDetector::unitTest(void)
894 {
895     pAlarmThresholds = &sensitivityLevels[1];
896 #if 0
897     // vertical tests
898     self.verticalFps = 0;
899     self.altFt = 1000;
900     cout << "identical altitude and vspeed " << endl;
901     checkVerticalThreat(self.altFt, self.verticalFps);
902     cout << "1000ft alt offset, dV=100 " << endl;
903     checkVerticalThreat(self.altFt+1000, 100);
904     cout << "-1000ft alt offset, dV=100 " << endl;
905     checkVerticalThreat(self.altFt-1000, 100);
906     cout << "3000ft alt offset, dV=10 " << endl;
907     checkVerticalThreat(self.altFt+3000, 10);
908     cout << "500ft alt offset, dV=100 " << endl;
909     checkVerticalThreat(self.altFt+500, 100);
910     cout << "500ft alt offset, dV=-100 " << endl;
911     checkVerticalThreat(self.altFt+500, -100);
912
913     // horizontal tests
914     self.heading = 0;
915     self.velocityKt = 0;
916     cout << "10nm behind, overtaking with 1Nm/s" << endl;
917     horizontalThreat(-180, 10, 0, 1/(SG_KT_TO_MPS*SG_METER_TO_NM));
918
919     cout << "10nm ahead, departing with 1Nm/s" << endl;
920     horizontalThreat(0, 20, 0, 1/(SG_KT_TO_MPS*SG_METER_TO_NM));
921
922     self.heading = 90;
923     self.velocityKt = 1/(SG_KT_TO_MPS*SG_METER_TO_NM);
924     cout << "10nm behind, overtaking with 1Nm/s at 90 degrees" << endl;
925     horizontalThreat(-90, 20, 90, 2/(SG_KT_TO_MPS*SG_METER_TO_NM));
926
927     self.heading = 20;
928     self.velocityKt = 1/(SG_KT_TO_MPS*SG_METER_TO_NM);
929     cout << "10nm behind, overtaking with 1Nm/s at 20 degrees" << endl;
930     horizontalThreat(200, 20, 20, 2/(SG_KT_TO_MPS*SG_METER_TO_NM));
931 #endif
932 }
933
934 ///////////////////////////////////////////////////////////////////////////////
935 // TCAS::AdvisoryGenerator ////////////////////////////////////////////////////
936 ///////////////////////////////////////////////////////////////////////////////
937
938 TCAS::AdvisoryGenerator::AdvisoryGenerator(TCAS* _tcas) :
939     tcas(_tcas),
940     pSelf(NULL),
941     pCurrentThreat(NULL),
942     pAlarmThresholds(NULL)
943 {
944 }
945
946 void
947 TCAS::AdvisoryGenerator::init(const LocalInfo* _pSelf, ThreatInfo* _pCurrentThreat)
948 {
949     pCurrentThreat = _pCurrentThreat;
950     pSelf = _pSelf;
951 }
952
953 void
954 TCAS::AdvisoryGenerator::setAlarmThresholds(const SensitivityLevel* _pAlarmThresholds)
955 {
956     pAlarmThresholds = _pAlarmThresholds;
957 }
958
959 /** Calculate projected vertical separation at horizontal CPA. */
960 float
961 TCAS::AdvisoryGenerator::verticalSeparation(float newVerticalFps)
962 {
963     // calculate relative vertical speed and altitude
964     float dV = pCurrentThreat->verticalFps - newVerticalFps;
965     float tau = pCurrentThreat->horizontalTau;
966     // don't use negative tau to project future separation...
967     if (tau < 0.5)
968         tau = 0.5;
969     return pCurrentThreat->relativeAltitudeFt + tau * dV;
970 }
971
972 /** Determine RA sense. */
973 void
974 TCAS::AdvisoryGenerator::determineRAsense(int& RASense, bool& isCrossing)
975 {
976     /* [TCASII]: "[..] a two step process is used to select the appropriate RA for the encounter
977              *   geometry. The first step in the process is to select the RA sense, i.e., upward or downward." */
978     RASense = 0;
979     isCrossing = false;
980     
981     /* [TCASII]: "Based on the range and altitude tracks of the intruder, the CAS logic models the
982      *   intruder's flight path from its present position to CPA. The CAS logic then models upward
983      *   and downward sense RAs for own aircraft [..] to determine which sense provides the most
984      *   vertical separation at CPA." */
985     float upSenseRelAltFt   = verticalSeparation(+2000/60.0);
986     float downSenseRelAltFt = verticalSeparation(-2000/60.0);
987     if (fabs(upSenseRelAltFt) >= fabs(downSenseRelAltFt))
988         RASense = +1;  // upward
989     else
990         RASense = -1; // downward
991
992     /* [TCASII]: "In encounters where either of the senses results in the TCAS aircraft crossing through
993      *   the intruder's altitude, TCAS is designed to select the nonaltitude crossing sense if the
994      *   noncrossing sense provides the desired vertical separation, known as ALIM, at CPA." */
995     /* [TCASII]: "If ALIM cannot be obtained in the nonaltitude crossing sense, an altitude
996      *   crossing RA will be issued." */
997     if ((RASense > 0)&&
998         (pCurrentThreat->relativeAltitudeFt > 200))
999     {
1000         // threat is above and RA is crossing
1001         if (fabs(downSenseRelAltFt) > pAlarmThresholds->TA.ALIM)
1002         {
1003             // non-crossing descend is sufficient 
1004             RASense = -1;
1005         }
1006         else
1007         {
1008             // keep crossing climb RA
1009             isCrossing = true;
1010         }
1011     }
1012     else
1013     if ((RASense < 0)&&
1014         (pCurrentThreat->relativeAltitudeFt < -200))
1015     {
1016         // threat is below and RA is crossing
1017         if (fabs(upSenseRelAltFt) > pAlarmThresholds->TA.ALIM)
1018         {
1019             // non-crossing climb is sufficient 
1020             RASense = 1;
1021         }
1022         else
1023         {
1024             // keep crossing descent RA
1025             isCrossing = true;
1026         }
1027     }
1028     // else: threat is at same altitude, keep optimal RA sense (non-crossing)
1029
1030     pCurrentThreat->RASense = RASense;
1031
1032 #ifdef FEATURE_TCAS_DEBUG_ADV_GENERATOR
1033         printf("  RASense: %i, crossing: %u, relAlt: %4.1f, upward separation: %4.1f, downward separation: %4.1f\n",
1034                RASense,isCrossing,
1035                pCurrentThreat->relativeAltitudeFt,
1036                upSenseRelAltFt,downSenseRelAltFt);
1037 #endif
1038 }
1039
1040 /** Determine suitable resolution advisories. */
1041 int
1042 TCAS::AdvisoryGenerator::resolution(int mode, int threatLevel, float rangeNm, float altFt,
1043                                     float heading, float velocityKt)
1044 {
1045     int RAOption = OptionNone;
1046     int RA       = AdvisoryIntrusion;
1047
1048     // RAs are disabled under certain conditions
1049     if (threatLevel == ThreatRA)
1050     {
1051         /* [TCASII]: "... less than 360 feet, TCAS considers the reporting aircraft
1052          *   to be on the ground. If TCAS determines the intruder to be on the ground, it
1053          *   inhibits the generation of advisories against this aircraft."*/
1054         if (altFt < 360)
1055             threatLevel = ThreatTA;
1056
1057         /* [EUROACAS]: "Certain RAs are inhibited at altitudes based on inputs from the radio altimeter:
1058          *   [..] (c)1000ft (+/- 100ft) and below, all RAs are inhibited;" */
1059         if (pSelf->radarAltFt < 1000)
1060             threatLevel = ThreatTA;
1061         
1062         // RAs only issued in mode "Auto" (= "TA/RA" mode)
1063         if (mode != SwitchAuto)
1064             threatLevel = ThreatTA;
1065     }
1066
1067     bool isCrossing = false; 
1068     int RASense = 0;
1069     // determine suitable RAs
1070     if (threatLevel == ThreatRA)
1071     {
1072         /* [TCASII]: "[..] a two step process is used to select the appropriate RA for the encounter
1073          *   geometry. The first step in the process is to select the RA sense, i.e., upward or downward." */
1074         determineRAsense(RASense, isCrossing);
1075
1076         /* second step: determine required strength */
1077         if (RASense > 0)
1078         {
1079             // upward
1080
1081             if ((pSelf->verticalFps < -1000/60.0)&&
1082                 (!isCrossing))
1083             {
1084                 // currently descending, see if reducing current descent is sufficient 
1085                 float relAltFt = verticalSeparation(-500/60.0);
1086                 if (relAltFt > pAlarmThresholds->TA.ALIM)
1087                     RA |= AdvisoryAdjustVSpeed;
1088             }
1089             RA |= AdvisoryClimb;
1090             if (isCrossing)
1091                 RAOption |= OptionCrossingClimb;
1092         }
1093
1094         if (RASense < 0)
1095         {
1096             // downward
1097
1098             if ((pSelf->verticalFps > 1000/60.0)&&
1099                 (!isCrossing))
1100             {
1101                 // currently climbing, see if reducing current climb is sufficient 
1102                 float relAltFt = verticalSeparation(500/60.0);
1103                 if (relAltFt < -pAlarmThresholds->TA.ALIM)
1104                     RA |= AdvisoryAdjustVSpeed;
1105             }
1106             RA |= AdvisoryDescend;
1107             if (isCrossing)
1108                 RAOption |= OptionCrossingDescent;
1109         }
1110
1111         //TODO
1112         /* [TCASII]: "When two TCAS-equipped aircraft are converging vertically with opposite rates
1113          *   and are currently well separated in altitude, TCAS will first issue a vertical speed
1114          *   limit (Negative) RA to reinforce the pilots' likely intention to level off at adjacent
1115          *   flight levels." */
1116         
1117         //TODO
1118         /* [TCASII]: "[..] if the CAS logic determines that the response to a Positive RA has provided
1119          *   ALIM feet of vertical separation before CPA, the initial RA will be weakened to either a
1120          *   Do Not Descend RA (after an initial Climb RA) or a Do Not Climb RA (after an initial
1121          *   Descend RA)." */
1122         
1123         //TODO
1124         /* [TCASII]: "TCAS is designed to inhibit Increase Descent RAs below 1450 feet AGL; */
1125         
1126         /* [TCASII]: "Descend RAs below 1100 feet AGL;" (inhibited) */
1127         if (pSelf->radarAltFt < 1100)
1128         {
1129             RA &= ~AdvisoryDescend;
1130             //TODO Support "Do not descend" RA
1131             RA |= AdvisoryIntrusion;
1132         }
1133     }
1134
1135 #ifdef FEATURE_TCAS_DEBUG_ADV_GENERATOR
1136     cout << "  resolution advisory: " << RA << endl;
1137 #endif
1138
1139     ResolutionAdvisory newAdvisory;
1140     newAdvisory.RAOption    = RAOption;
1141     newAdvisory.RA          = RA;
1142     newAdvisory.threatLevel = threatLevel;
1143     tcas->advisoryCoordinator.add(newAdvisory);
1144     
1145     return threatLevel;
1146 }
1147
1148 ///////////////////////////////////////////////////////////////////////////////
1149 // TCAS ///////////////////////////////////////////////////////////////////////
1150 ///////////////////////////////////////////////////////////////////////////////
1151
1152 TCAS::TCAS(SGPropertyNode* pNode) :
1153     name("tcas"),
1154     num(0),
1155     nextUpdateTime(0),
1156     selfTestStep(0),
1157     properties_handler(this),
1158     threatDetector(this),
1159     tracker(this),
1160     advisoryCoordinator(this),
1161     advisoryGenerator(this),
1162     annunciator(this)
1163 {
1164     for (int i = 0; i < pNode->nChildren(); ++i)
1165     {
1166         SGPropertyNode* pChild = pNode->getChild(i);
1167         string cname = pChild->getName();
1168         string cval = pChild->getStringValue();
1169
1170         if (cname == "name")
1171             name = cval;
1172         else if (cname == "number")
1173             num = pChild->getIntValue();
1174         else
1175         {
1176             SG_LOG(SG_INSTR, SG_WARN, "Error in TCAS config logic");
1177             if (name.length())
1178                 SG_LOG(SG_INSTR, SG_WARN, "Section = " << name);
1179         }
1180     }
1181 }
1182
1183 void
1184 TCAS::init(void)
1185 {
1186     annunciator.init();
1187     advisoryCoordinator.init();
1188     threatDetector.init();
1189 }
1190
1191 void
1192 TCAS::reinit(void)
1193 {
1194     nextUpdateTime = 0;
1195     advisoryCoordinator.reinit();
1196 }
1197
1198 void
1199 TCAS::bind(void)
1200 {
1201     SGPropertyNode* node = fgGetNode(("/instrumentation/" + name).c_str(), num, true);
1202
1203     nodeServiceable  = node->getNode("serviceable", true);
1204
1205     // TCAS mode selection (0=off, 1=standby, 2=TA only, 3=auto(TA/RA) ) 
1206     nodeModeSwitch   = node->getNode("inputs/mode", true);
1207     // self-test button
1208     nodeSelfTest     = node->getNode("inputs/self-test", true);
1209     // default value
1210     nodeSelfTest->setBoolValue(false);
1211
1212 #ifdef FEATURE_TCAS_DEBUG_PROPERTIES
1213     SGPropertyNode* nodeDebug = node->getNode("debug", true);
1214     // debug triggers
1215     nodeDebugTrigger = nodeDebug->getNode("threat-trigger", true);
1216     nodeDebugRA      = nodeDebug->getNode("threat-RA",      true);
1217     nodeDebugThreat  = nodeDebug->getNode("threat-level",   true);
1218     // default values
1219     nodeDebugTrigger->setBoolValue(false);
1220     nodeDebugRA->setIntValue(3);
1221     nodeDebugThreat->setIntValue(1);
1222 #endif
1223
1224     annunciator.bind(node);
1225     advisoryCoordinator.bind(node);
1226 }
1227
1228 void
1229 TCAS::unbind(void)
1230 {
1231     properties_handler.unbind();
1232 }
1233
1234 /** Monitor traffic for safety threats. */
1235 void
1236 TCAS::update(double dt)
1237 {
1238     if (!nodeServiceable->getBoolValue())
1239         return;
1240     int mode = nodeModeSwitch->getIntValue();
1241     if (mode == SwitchOff)
1242         return;
1243
1244     nextUpdateTime -= dt;
1245     if (nextUpdateTime <= 0.0 )
1246     {
1247         nextUpdateTime = 1.0;
1248
1249         // remove obsolete targets
1250         tracker.update();
1251
1252         // get aircrafts current position/speed/heading
1253         threatDetector.update();
1254
1255         // clear old threats
1256         advisoryCoordinator.clear();
1257
1258         if (nodeSelfTest->getBoolValue())
1259         {
1260             if (threatDetector.getVelocityKt() >= 40)
1261             {
1262                 // disable self-test when plane moves above taxiing speed
1263                 nodeSelfTest->setBoolValue(false);
1264                 selfTestStep = 0;
1265             }
1266             else
1267             {
1268                 selfTest();
1269                 // speed-up self test
1270                 nextUpdateTime = 0;
1271                 // no further TCAS processing during self-test
1272                 return;
1273             }
1274         }
1275
1276 #ifdef FEATURE_TCAS_DEBUG_PROPERTIES
1277         if (nodeDebugTrigger->getBoolValue())
1278         {
1279             // debugging test
1280             ResolutionAdvisory debugAdvisory;
1281             debugAdvisory.RAOption    = OptionNone;
1282             debugAdvisory.RA          = nodeDebugRA->getIntValue();
1283             debugAdvisory.threatLevel = nodeDebugThreat->getIntValue();
1284             advisoryCoordinator.add(debugAdvisory);
1285         }
1286         else
1287 #endif
1288         {
1289             SGPropertyNode* pAi = fgGetNode("/ai/models", true);
1290
1291             // check all aircraft
1292             for (int i = pAi->nChildren() - 1; i >= -1; i--)
1293             {
1294                 SGPropertyNode* pModel = pAi->getChild(i);
1295                 if ((pModel)&&(pModel->nChildren()))
1296                 {
1297                     int threatLevel = threatDetector.checkThreat(mode, pModel);
1298                     /* expose aircraft threat-level (to be used by other instruments,
1299                      * i.e. TCAS display) */
1300                     if (threatLevel==ThreatRA)
1301                         pModel->setIntValue("tcas/ra-sense", -threatDetector.getRASense());
1302                     pModel->setIntValue("tcas/threat-level", threatLevel);
1303                 }
1304             }
1305         }
1306         advisoryCoordinator.update(mode);
1307     }
1308     annunciator.update();
1309 }
1310
1311 /** Run a single self-test iteration. */
1312 void
1313 TCAS::selfTest(void)
1314 {
1315     annunciator.update();
1316     if (annunciator.isPlaying())
1317     {
1318         return;
1319     }
1320
1321     ResolutionAdvisory newAdvisory;
1322     newAdvisory.threatLevel = ThreatRA;
1323     newAdvisory.RA          = AdvisoryClear;
1324     newAdvisory.RAOption    = OptionNone;
1325     // TCAS audio is disabled below 500ft AGL
1326     threatDetector.setRadarAlt(501);
1327
1328     // trigger various advisories
1329     switch(selfTestStep)
1330     {
1331         case 0:
1332             newAdvisory.RA = AdvisoryIntrusion;
1333             newAdvisory.threatLevel = ThreatTA;
1334             break;
1335         case 1:
1336             newAdvisory.RA = AdvisoryClimb;
1337             break;
1338         case 2:
1339             newAdvisory.RA = AdvisoryClimb;
1340             newAdvisory.RAOption = OptionIncreaseClimb;
1341             break;
1342         case 3:
1343             newAdvisory.RA = AdvisoryClimb;
1344             newAdvisory.RAOption = OptionCrossingClimb;
1345             break;
1346         case 4:
1347             newAdvisory.RA = AdvisoryDescend;
1348             break;
1349         case 5:
1350             newAdvisory.RA = AdvisoryDescend;
1351             newAdvisory.RAOption = OptionIncreaseDescend;
1352             break;
1353         case 6:
1354             newAdvisory.RA = AdvisoryDescend;
1355             newAdvisory.RAOption = OptionCrossingDescent;
1356             break;
1357         case 7:
1358             newAdvisory.RA = AdvisoryAdjustVSpeed;
1359             break;
1360         case 8:
1361             newAdvisory.RA = AdvisoryMaintVSpeed;
1362             break;
1363         case 9:
1364             newAdvisory.RA = AdvisoryMonitorVSpeed;
1365             break;
1366         case 10:
1367             newAdvisory.threatLevel = ThreatNone;
1368             newAdvisory.RA = AdvisoryClear;
1369             break;
1370         case 11:
1371             annunciator.test(true);
1372             selfTestStep+=2;
1373             return;
1374         default:
1375             nodeSelfTest->setBoolValue(false);
1376             selfTestStep = 0;
1377             return;
1378     }
1379
1380     advisoryCoordinator.add(newAdvisory);
1381     advisoryCoordinator.update(SwitchAuto);
1382
1383     selfTestStep++;
1384 }
1385
1386 ///////////////////////////////////////////////////////////////////////////////
1387 // TCAS::Tracker //////////////////////////////////////////////////////////////
1388 ///////////////////////////////////////////////////////////////////////////////
1389
1390 TCAS::Tracker::Tracker(TCAS* _tcas) :
1391     tcas(_tcas),
1392     currentTime(0),
1393     haveTargets(false),
1394     newTargets(false)
1395 {
1396     targets.clear();
1397 }
1398
1399 void
1400 TCAS::Tracker::update(void)
1401 {
1402     currentTime = globals->get_sim_time_sec();
1403     newTargets = false;
1404
1405     if (haveTargets)
1406     {
1407         // remove outdated targets
1408         TrackerTargets::iterator it = targets.begin();
1409         while (it != targets.end())
1410         {
1411             TrackerTarget* pTarget = it->second;
1412             if (currentTime - pTarget->TAtimestamp > 10.0)
1413             {
1414                 TrackerTargets::iterator temp = it;
1415                 ++it;
1416 #ifdef FEATURE_TCAS_DEBUG_TRACKER
1417                 printf("target %s no longer a TA threat.\n",temp->first.c_str());
1418 #endif
1419                 targets.erase(temp->first);
1420                 delete pTarget;
1421                 pTarget = NULL;
1422             }
1423             else
1424             {
1425                 if ((pTarget->threatLevel == ThreatRA)&&
1426                     (currentTime - pTarget->RAtimestamp > 7.0))
1427                 {
1428                     pTarget->threatLevel = ThreatTA;
1429 #ifdef FEATURE_TCAS_DEBUG_TRACKER
1430                     printf("target %s no longer an RA threat.\n",it->first.c_str());
1431 #endif
1432                 }
1433                 ++it;
1434             }
1435         }
1436         haveTargets = !targets.empty();
1437     }
1438 }
1439
1440 void
1441 TCAS::Tracker::add(const string callsign, int detectedLevel)
1442 {
1443     TrackerTarget* pTarget = NULL;
1444     if (haveTargets)
1445     {
1446         TrackerTargets::iterator it = targets.find(callsign);
1447         if (it != targets.end())
1448         {
1449             pTarget = it->second;
1450         }
1451     }
1452
1453     if (!pTarget)
1454     {
1455         pTarget = new TrackerTarget();
1456         pTarget->TAtimestamp = 0;
1457         pTarget->RAtimestamp = 0;
1458         pTarget->threatLevel = 0;
1459         newTargets = true;
1460         targets[callsign] = pTarget;
1461 #ifdef FEATURE_TCAS_DEBUG_TRACKER
1462         printf("new target: %s, level: %i\n",callsign.c_str(),detectedLevel);
1463 #endif
1464     }
1465
1466     if (detectedLevel > pTarget->threatLevel)
1467         pTarget->threatLevel = detectedLevel;
1468
1469     if (detectedLevel >= ThreatTA)
1470         pTarget->TAtimestamp = currentTime;
1471
1472     if (detectedLevel >= ThreatRA)
1473         pTarget->RAtimestamp = currentTime;
1474
1475     haveTargets = true;
1476 }
1477
1478 bool
1479 TCAS::Tracker::_isTracked(string callsign)
1480 {
1481     return targets.find(callsign) != targets.end();
1482 }
1483
1484 int
1485 TCAS::Tracker::getThreatLevel(string callsign)
1486 {
1487     TrackerTargets::iterator it = targets.find(callsign);
1488     if (it != targets.end())
1489         return it->second->threatLevel;
1490     else
1491         return 0;
1492 }