Debian Codegraph @

src/Instrumentation/tcas.cxx

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