]> git.mxchange.org Git - flightgear.git/blob - ATCmgr.cxx
2cb352a4f7b5f6c05323340fe9b62bbc35d7c2d4
[flightgear.git] / ATCmgr.cxx
1 // ATCmgr.cxx - Implementation of FGATCMgr - a global Flightgear ATC manager.
2 //
3 // Written by David Luff, started February 2002.
4 //
5 // Copyright (C) 2002  David C Luff - david.luff@nottingham.ac.uk
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 Street, Fifth Floor, Boston, MA  02110-1301, USA.
20
21 #ifdef HAVE_CONFIG_H
22 #  include <config.h>
23 #endif
24
25 #include <simgear/misc/sg_path.hxx>
26 #include <simgear/debug/logstream.hxx>
27
28 #include <Airports/simple.hxx>
29
30 #include "ATCmgr.hxx"
31 #include "commlist.hxx"
32 #include "ATCDialog.hxx"
33 #include "ATCutils.hxx"
34 #include "transmissionlist.hxx"
35 #include "ground.hxx"
36
37
38 /*
39 // periodic radio station search wrapper
40 static void fgATCSearch( void ) {
41     globals->get_ATC_mgr()->Search();
42 }
43 */ //This wouldn't compile - including Time/event.hxx breaks it :-(
44    // Is this still true?? -EMH-
45
46 AirportATC::AirportATC() :
47     atis_freq(0.0),
48     atis_active(false),
49     tower_freq(0.0),
50     tower_active(false),
51     ground_freq(0.0),
52     ground_active(false),
53     set_by_AI(false),
54     numAI(0)
55     //airport_atc_map.clear();
56 {
57 }
58
59 FGATCMgr::FGATCMgr() :
60     initDone(false),
61     atc_list(new atc_list_type),
62 #ifdef ENABLE_AUDIO_SUPPORT
63     voiceOK(false),
64     voice(true),
65 #else
66     voice(false),
67 #endif
68     last_in_range(false),
69     v1(0)
70 {
71 }
72
73 FGATCMgr::~FGATCMgr() {
74     delete v1;
75 }
76
77 void FGATCMgr::bind() {
78 }
79
80 void FGATCMgr::unbind() {
81 }
82
83 void FGATCMgr::init() {
84     //cout << "ATCMgr::init called..." << endl;
85     
86     lon_node = fgGetNode("/position/longitude-deg", true);
87     lat_node = fgGetNode("/position/latitude-deg", true);
88     elev_node = fgGetNode("/position/altitude-ft", true);
89     atc_list_itr = atc_list->begin();
90     
91     // Search for connected ATC stations once per 0.8 seconds or so
92     // globals->get_event_mgr()->add( "fgATCSearch()", fgATCSearch,
93         //                                 FGEvent::FG_EVENT_READY, 800);
94         //  
95     // For some reason the above doesn't compile - including Time/event.hxx stops compilation.
96         // Is this still true after the reorganization of the event managar??
97         // -EMH-
98     
99     // Initialise the ATC Dialogs
100     //cout << "Initing Transmissions..." << endl;
101     SG_LOG(SG_ATC, SG_INFO, "  ATC Transmissions");
102     current_transmissionlist = new FGTransmissionList;
103     SGPath p_transmission( globals->get_fg_root() );
104     p_transmission.append( "ATC/default.transmissions" );
105     current_transmissionlist->init( p_transmission );
106     //cout << "Done Transmissions" << endl;
107
108     SG_LOG(SG_ATC, SG_INFO, "  ATC Dialog System");
109     current_atcdialog = new FGATCDialog;
110     current_atcdialog->Init();
111
112     initDone = true;
113     //cout << "ATCmgr::init done!" << endl;
114 }
115
116 void FGATCMgr::update(double dt) {
117     if(!initDone) {
118         init();
119         SG_LOG(SG_ATC, SG_WARN, "Warning - ATCMgr::update(...) called before ATCMgr::init()");
120     }
121     
122     current_atcdialog->Update(dt);
123     
124     //cout << "Entering update..." << endl;
125     //Traverse the list of active stations.
126     //Only update one class per update step to avoid the whole ATC system having to calculate between frames.
127     //Eventually we should only update every so many steps.
128     //cout << "In FGATCMgr::update - atc_list.size = " << atc_list->size() << endl;
129     if(atc_list->size()) {
130         if(atc_list_itr == atc_list->end()) {
131             atc_list_itr = atc_list->begin();
132         }
133         //cout << "Updating " << (*atc_list_itr)->get_ident() << ' ' << (*atc_list_itr)->GetType() << '\n';
134         //cout << "Freq = " << (*atc_list_itr)->get_freq() << '\n';
135         (*atc_list_itr).second->Update(dt * atc_list->size());
136         //cout << "Done ATC update..." << endl;
137         ++atc_list_itr;
138     }
139     
140 #ifdef ATC_TEST
141     cout << "ATC_LIST: " << atc_list->size() << ' ';
142     for(atc_list_iterator it = atc_list->begin(); it != atc_list->end(); it++) {
143         cout << (*it)->get_ident() << ' ';
144     }
145     cout << '\n';
146 #endif
147     
148     // Search the tuned frequencies every now and then - this should be done with the event scheduler
149     static int i = 0;   // Very ugly - but there should only ever be one instance of FGATCMgr.
150     /*** Area search is defeated.  Why?
151     if(i == 7) {
152         //cout << "About to AreaSearch()" << endl;
153         AreaSearch();
154     }
155     ***/
156     if(i == 15) {
157         //cout << "About to search navcomm1" << endl;
158         FreqSearch("comm", 0);
159         FreqSearch("nav", 0);
160     }
161     if(i == 30) {
162         //cout << "About to search navcomm2" << endl;
163         FreqSearch("comm", 1);
164         FreqSearch("nav", 1);
165         i = 0;
166     }
167     ++i;
168     
169     //cout << "comm1 type = " << comm_type[0] << '\n';
170     //cout << "Leaving update..." << endl;
171 }
172
173
174 // Returns frequency in KHz - should I alter this to return in MHz?
175 unsigned short int FGATCMgr::GetFrequency(const string& ident, const atc_type& tp) {
176     ATCData test;
177     bool ok = current_commlist->FindByCode(ident, test, tp);
178     return(ok ? test.freq : 0);
179 }   
180
181
182 // Register the fact that the AI system wants to activate an airport
183 // Might need more sophistication in this in the future - eg registration by aircraft call-sign.
184 bool FGATCMgr::AIRegisterAirport(const string& ident) {
185     SG_LOG(SG_ATC, SG_BULK, "AI registered airport " << ident << " with the ATC system");
186     //cout << "AI registered airport " << ident << " with the ATC system" << '\n';
187     if(airport_atc_map.find(ident) != airport_atc_map.end()) {
188         airport_atc_map[ident]->set_by_AI = true;
189         airport_atc_map[ident]->numAI++;
190         return(true);
191     } else {
192         const FGAirport *ap = fgFindAirportID(ident);
193         if (ap) {
194             //cout << "ident = " << ident << '\n';
195             AirportATC *a = new AirportATC;
196             // I'm not entirely sure that this AirportATC structure business is actually needed - it just duplicates what we can find out anyway!
197             a->geod = ap->geod();
198             a->atis_freq = GetFrequency(ident, ATIS)
199                     || GetFrequency(ident, AWOS);
200             //cout << "ATIS freq = " << a->atis_freq << '\n';
201             a->atis_active = false;
202             a->tower_freq = GetFrequency(ident, TOWER);
203             //cout << "Tower freq = " << a->tower_freq << '\n';
204             a->tower_active = false;
205             a->ground_freq = GetFrequency(ident, GROUND);
206             //cout << "Ground freq = " << a->ground_freq << '\n';
207             a->ground_active = false;
208             // TODO - some airports will have a tower/ground frequency but be inactive overnight.
209             a->set_by_AI = true;
210             a->numAI = 1;
211             airport_atc_map[ident] = a;
212             return(true);
213         } else {
214             SG_LOG(SG_ATC, SG_ALERT, "ERROR - can't find airport " << ident << " in AIRegisterAirport(...)");
215         }
216     }
217     return(false);
218 }
219
220 // Register the fact that the comm radio is tuned to an airport
221 // Channel is zero based
222 bool FGATCMgr::CommRegisterAirport(const string& ident, int chan, const atc_type& tp) {
223     SG_LOG(SG_ATC, SG_BULK, "Comm channel " << chan << " registered airport " << ident);
224     //cout << "Comm channel " << chan << " registered airport " << ident << ' ' << tp << '\n';
225     if(airport_atc_map.find(ident) != airport_atc_map.end()) {
226         //cout << "IN MAP - flagging set by comm..." << endl;
227 //xx        airport_atc_map[ident]->set_by_comm[chan][tp] = true;
228         if(tp == ATIS || tp == AWOS) {
229             airport_atc_map[ident]->atis_active = true;
230         } else if(tp == TOWER) {
231             airport_atc_map[ident]->tower_active = true;
232         } else if(tp == GROUND) {
233             airport_atc_map[ident]->ground_active = true;
234         } else if(tp == APPROACH) {
235             //a->approach_active = true;
236         }   // TODO - there *must* be a better way to do this!!!
237         return(true);
238     } else {
239         //cout << "NOT IN MAP - creating new..." << endl;
240         const FGAirport *ap = fgFindAirportID(ident);
241         if (ap) {
242             AirportATC *a = new AirportATC;
243             // I'm not entirely sure that this AirportATC structure business is actually needed - it just duplicates what we can find out anyway!
244             a->geod = ap->geod();
245             a->atis_freq = GetFrequency(ident, ATIS)
246                     || GetFrequency(ident, AWOS);
247             a->atis_active = false;
248             a->tower_freq = GetFrequency(ident, TOWER);
249             a->tower_active = false;
250             a->ground_freq = GetFrequency(ident, GROUND);
251             a->ground_active = false;
252             if(tp == ATIS || tp == AWOS) {
253                 a->atis_active = true;
254             } else if(tp == TOWER) {
255                 a->tower_active = true;
256             } else if(tp == GROUND) {
257                 a->ground_active = true;
258             } else if(tp == APPROACH) {
259                 //a->approach_active = true;
260             }   // TODO - there *must* be a better way to do this!!!
261             // TODO - some airports will have a tower/ground frequency but be inactive overnight.
262             a->set_by_AI = false;
263             a->numAI = 0;
264 //xx            a->set_by_comm[chan][tp] = true;
265             airport_atc_map[ident] = a;
266             return(true);
267         }
268     }
269     return(false);
270 }
271
272 typedef map<string,int> MSI;
273
274 void FGATCMgr::ZapOtherService(const string ncunit, const string svc_name){
275   for (atc_list_iterator svc = atc_list->begin(); svc != atc_list->end(); svc++) {
276    
277     if (svc->first != svc_name) {
278       MSI &actv = svc->second->active_on;
279       // OK, we have found some OTHER service;
280       // see if it is (was) active on our unit:
281       if (!actv.count(ncunit)) continue;
282       // cout << "Eradicating '" << svc->first << "' from: " << ncunit << endl;
283       actv.erase(ncunit);
284       if (!actv.size()) {
285         //cout << "Eradicating service: '" << svc->first << "'" << endl;
286     svc->second->SetNoDisplay();
287     svc->second->Update(0);     // one last update
288     SG_LOG(SG_GENERAL, SG_INFO, "would have erased ATC service:" << svc->second->get_name()<< "/" 
289       << svc->second->get_ident());
290    // delete svc->second;
291     atc_list->erase(svc);
292 // ALL pointers into the ATC list are now invalid,
293 // so let's reset them:
294     atc_list_itr = atc_list->begin();
295       }
296       break;        // cannot be duplicates in the active list
297     }
298   }
299 }
300
301
302 // Find in list - return a currently active ATC pointer given ICAO code and type
303 // Return NULL if the given service is not in the list
304 // - *** THE CALLING FUNCTION MUST CHECK FOR THIS ***
305 FGATC* FGATCMgr::FindInList(const string& id, const atc_type& tp) {
306   string ndx = id + decimalNumeral(tp);
307   if (!atc_list->count(ndx)) return 0;
308   return (*atc_list)[ndx];
309 }
310
311 // Returns true if the airport is found in the map
312 bool FGATCMgr::GetAirportATCDetails(const string& icao, AirportATC* a) {
313     if(airport_atc_map.find(icao) != airport_atc_map.end()) {
314         *a = *airport_atc_map[icao];
315         return(true);
316     } else {
317         return(false);
318     }
319 }
320
321
322 // Return a pointer to a given sort of ATC at a given airport and activate if necessary
323 // Returns NULL if service doesn't exist - calling function should check for this.
324 // We really ought to make this private and call it from the CommRegisterAirport / AIRegisterAirport functions
325 // - at the moment all these GetATC... functions exposed are just too complicated.
326 FGATC* FGATCMgr::GetATCPointer(const string& icao, const atc_type& type) {
327     if(airport_atc_map.find(icao) == airport_atc_map.end()) {
328         //cout << "Unable to find " << icao << ' ' << type << " in the airport_atc_map" << endl;
329         return NULL;
330     }
331     //cout << "In GetATCPointer, found " << icao << ' ' << type << endl;
332     AirportATC *a = airport_atc_map[icao];
333     //cout << "a->lon = " << a->lon << '\n';
334     //cout << "a->elev = " << a->elev << '\n';
335     //cout << "a->tower_freq = " << a->tower_freq << '\n';
336     switch(type) {
337     case TOWER:
338         if(a->tower_active) {
339             // Get the pointer from the list
340             return(FindInList(icao, type));
341         } else {
342             ATCData data;
343             if(current_commlist->FindByFreq(a->geod, a->tower_freq, &data, TOWER)) {
344                 FGTower* t = new FGTower;
345                 t->SetData(&data);
346                 (*atc_list)[icao+decimalNumeral(type)] = t;
347                 a->tower_active = true;
348                 airport_atc_map[icao] = a;
349                 //cout << "Initing tower " << icao << " in GetATCPointer()\n";
350                 t->Init();
351                 return(t);
352             } else {
353                 SG_LOG(SG_ATC, SG_ALERT, "ERROR - tower that should exist in FGATCMgr::GetATCPointer for airport " << icao << " not found");
354             }
355         }
356         break;
357     case APPROACH:
358         break;
359     case ATIS: case AWOS:
360         SG_LOG(SG_ATC, SG_ALERT, "ERROR - ATIS station should not be requested from FGATCMgr::GetATCPointer");
361         break;
362     case GROUND:
363         //cout << "IN CASE GROUND" << endl;
364         if(a->ground_active) {
365             // Get the pointer from the list
366             return(FindInList(icao, type));
367         } else {
368             ATCData data;
369             if(current_commlist->FindByFreq(a->geod, a->ground_freq, &data, GROUND)) {
370                 FGGround* g = new FGGround;
371                 g->SetData(&data);
372                 (*atc_list)[icao+decimalNumeral(type)] = g;
373                 a->ground_active = true;
374                 airport_atc_map[icao] = a;
375                 g->Init();
376                 return(g);
377             } else {
378                 SG_LOG(SG_ATC, SG_ALERT, "ERROR - ground control that should exist in FGATCMgr::GetATCPointer for airport " << icao << " not found");
379             }
380         }
381         break;
382         case INVALID:
383         break;
384         case ENROUTE:
385         break;
386         case DEPARTURE:
387         break;
388     }
389     
390     SG_LOG(SG_ATC, SG_ALERT, "ERROR IN FGATCMgr - reached end of GetATCPointer");
391     //cout << "ERROR IN FGATCMgr - reached end of GetATCPointer" << endl;
392     
393     return(NULL);
394 }
395
396 // Return a pointer to an appropriate voice for a given type of ATC
397 // creating the voice if necessary - ie. make sure exactly one copy
398 // of every voice in use exists in memory.
399 //
400 // TODO - in the future this will get more complex and dole out country/airport
401 // specific voices, and possible make sure that the same voice doesn't get used
402 // at different airports in quick succession if a large enough selection are available.
403 FGATCVoice* FGATCMgr::GetVoicePointer(const atc_type& type) {
404     // TODO - implement me better - maintain a list of loaded voices and other voices!!
405     if(voice) {
406         switch(type) {
407         case ATIS: case AWOS:
408 #ifdef ENABLE_AUDIO_SUPPORT
409             // Delayed loading fo all available voices, needed because the
410             // soundmanager might not be initialized (at all) at this point.
411             // For now we'll do one hardwired one
412
413             /* I've loaded the voice even if /sim/sound/pause is true
414              *  since I know no way of forcing load of the voice if the user
415              *  subsequently switches /sim/sound/audible to true.
416              *  (which is the right thing to do -- CLO) :-)
417              */
418             if (!voiceOK && fgGetBool("/sim/sound/working")) {
419                 v1 = new FGATCVoice;
420                 try {
421                     voiceOK = v1->LoadVoice("default");
422                     voice = voiceOK;
423                 } catch ( sg_io_exception & e) {
424                     voiceOK  = false;
425                     SG_LOG(SG_ATC, SG_ALERT, "Unable to load default voice : "
426                                             << e.getFormattedMessage().c_str());
427                     voice = false;
428                     delete v1;
429                     v1 = 0;
430                 }
431             }
432 #endif
433             if(voiceOK) {
434                 return(v1);
435             }
436         case TOWER:
437             return(NULL);
438         case APPROACH:
439             return(NULL);
440         case GROUND:
441             return(NULL);
442         default:
443             return(NULL);
444         }
445         return(NULL);
446     } else {
447         return(NULL);
448     }
449 }
450
451 // Search for ATC stations by frequency
452 void FGATCMgr::FreqSearch(const string navcomm, const int unit) {
453
454
455         string ncunit = navcomm + "[" + decimalNumeral(unit) + "]";
456     string commbase = "/instrumentation/" + ncunit;
457     string commfreq = commbase + "/frequencies/selected-mhz";
458         SGPropertyNode_ptr comm_node = fgGetNode(commfreq.c_str(), false);
459
460     //cout << "FreqSearch: " << ncunit
461     //  << "  node: " << comm_node << endl;
462     if (!comm_node) return; // no such radio unit
463
464     ATCData data;   
465     double freq = comm_node->getDoubleValue();
466     _aircraftPos = SGGeod::fromDegFt(lon_node->getDoubleValue(),
467       lat_node->getDoubleValue(), elev_node->getDoubleValue());
468     
469 // Query the data store and get the closest match if any
470     //cout << "Will FindByFreq: " << lat << " " << lon << " " << elev
471     //      << "  freq: " << freq << endl;
472     if(current_commlist->FindByFreq(_aircraftPos, freq, &data)) {
473       //cout << "FoundByFreq: " << freq 
474       //  << "  ident: " << data.ident 
475       //  << "  type: " << data.type << " ***" << endl;
476 // We are in range of something.
477
478
479 // Get rid of any *other* service that was on this radio unit:
480             string svc_name = data.ident+decimalNumeral(data.type);
481         ZapOtherService(ncunit, svc_name);
482 // See if the service already exists, possibly connected to
483 // some other radio unit:
484         if (atc_list->count(svc_name)) {
485           // make sure the service knows it's tuned on this radio:
486           FGATC* svc = (*atc_list)[svc_name];
487           svc->active_on[ncunit] = 1;
488           svc->SetDisplay();
489           if (data.type == APPROACH) svc->AddPlane("Player");
490           return;
491         }
492
493         CommRegisterAirport(data.ident, unit, data.type);
494
495 // This was a switch-case statement but the compiler didn't like 
496 // the new variable creation with it. 
497         if      (data.type == ATIS
498               || data.type == AWOS)     (*atc_list)[svc_name] = new FGATIS;
499         else if (data.type == TOWER)    (*atc_list)[svc_name] = new FGTower;
500         else if (data.type == GROUND)   (*atc_list)[svc_name] = new FGGround;
501         else if (data.type == APPROACH) (*atc_list)[svc_name] = new FGApproach;
502         FGATC* svc = (*atc_list)[svc_name];
503         svc->SetData(&data);
504         svc->active_on[ncunit] = 1;
505         svc->SetDisplay();
506         svc->Init();
507         if (data.type == APPROACH) svc->AddPlane("Player");
508     } else {
509       // No services in range.  Zap any service on this unit.
510       ZapOtherService(ncunit, "x x x");
511     } 
512 }
513
514 #ifdef AREA_SEARCH
515 /* I don't think AreaSearch ever gets called */
516 // Search ATC stations by area in order that we appear 'on the radar'
517 void FGATCMgr::AreaSearch() {
518   const string AREA("AREA");
519   // Search for Approach stations
520   comm_list_type approaches;
521   comm_list_iterator app_itr;
522
523   lon = lon_node->getDoubleValue();
524   lat = lat_node->getDoubleValue();
525   elev = elev_node->getDoubleValue() * SG_FEET_TO_METER;
526   for (atc_list_iterator svc = atc_list->begin(); svc != atc_list->end(); svc++) {
527     MSI &actv = svc->second->active_on;
528     if (actv.count(AREA)) actv[AREA] = 0;  // Mark all as maybe not in range
529   }
530
531   // search stations in range
532   int num_app = current_commlist->FindByPos(lon, lat, elev, 100.0, &approaches, APPROACH);
533   if (num_app != 0) {
534     //cout << num_app << " approaches found in area search !!!!" << endl;
535
536     for(app_itr = approaches.begin(); app_itr != approaches.end(); app_itr++) {
537       FGATC* app = FindInList(app_itr->ident, app_itr->type);
538       string svc_name = app_itr->ident+decimalNumeral(app_itr->type);
539       if(app != NULL) {
540     // The station is already in the ATC list
541     app->AddPlane("Player");
542       } else {
543     // Generate the station and put in the ATC list
544     FGApproach* a = new FGApproach;
545     a->SetData(&(*app_itr));
546     a->AddPlane("Player");
547     (*atc_list)[svc_name] = a;
548     //cout << "New area service: " << svc_name << endl;
549       }
550       FGATC* svc = (*atc_list)[svc_name];
551       svc->active_on[AREA] = 1;
552     }
553   }
554
555   for (atc_list_iterator svc = atc_list->begin(); svc != atc_list->end(); svc++) {
556     MSI &actv = svc->second->active_on;
557     if (!actv.count(AREA)) continue;
558     if (!actv[AREA]) actv.erase(AREA);
559     if (!actv.size()) {     // this service no longer active at all
560       cout << "Eradicating area service: " << svc->first << endl;
561       svc->second->SetNoDisplay();
562       svc->second->Update(0);
563       delete (svc->second);
564       atc_list->erase(svc);
565 // Reset the persistent iterator, since any erase() makes it invalid:
566       atc_list_itr = atc_list->begin(); 
567 // Hope we only move out of one approach-area;
568 // others will not be noticed until next update:
569       break;
570     }
571   }
572 }
573 #endif