]> git.mxchange.org Git - flightgear.git/blob - src/ATCDCL/ATCmgr.cxx
Merge branch 'next' of git@gitorious.org:fg/flightgear into next
[flightgear.git] / src / ATCDCL / 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 "ground.hxx"
35
36
37 /*
38 // periodic radio station search wrapper
39 static void fgATCSearch( void ) {
40     globals->get_ATC_mgr()->Search();
41 }
42 */ //This wouldn't compile - including Time/event.hxx breaks it :-(
43    // Is this still true?? -EMH-
44
45 AirportATC::AirportATC() :
46     atis_freq(0.0),
47     atis_active(false),
48     tower_freq(0.0),
49     tower_active(false),
50     ground_freq(0.0),
51     ground_active(false),
52     set_by_AI(false),
53     numAI(0)
54     //airport_atc_map.clear();
55 {
56 }
57
58 FGATCMgr::FGATCMgr() :
59     initDone(false),
60     atc_list(new atc_list_type),
61 #ifdef ENABLE_AUDIO_SUPPORT
62     voiceOK(false),
63     voice(true),
64 #else
65     voice(false),
66 #endif
67     last_in_range(false),
68     v1(0)
69 {
70 }
71
72 FGATCMgr::~FGATCMgr() {
73     delete v1;
74 }
75
76 void FGATCMgr::bind() {
77 }
78
79 void FGATCMgr::unbind() {
80 }
81
82 void FGATCMgr::init() {
83     //cout << "ATCMgr::init called..." << endl;
84     
85     lon_node = fgGetNode("/position/longitude-deg", true);
86     lat_node = fgGetNode("/position/latitude-deg", true);
87     elev_node = fgGetNode("/position/altitude-ft", true);
88     atc_list_itr = atc_list->begin();
89     
90     // Search for connected ATC stations once per 0.8 seconds or so
91     // globals->get_event_mgr()->add( "fgATCSearch()", fgATCSearch,
92         //                                 FGEvent::FG_EVENT_READY, 800);
93         //  
94     // For some reason the above doesn't compile - including Time/event.hxx stops compilation.
95         // Is this still true after the reorganization of the event managar??
96         // -EMH-
97     
98     // Initialise the ATC Dialogs
99     SG_LOG(SG_ATC, SG_INFO, "  ATC Dialog System");
100     current_atcdialog = new FGATCDialog;
101     current_atcdialog->Init();
102
103     initDone = true;
104     //cout << "ATCmgr::init done!" << endl;
105 }
106
107 void FGATCMgr::update(double dt) {
108     if(!initDone) {
109         init();
110         SG_LOG(SG_ATC, SG_WARN, "Warning - ATCMgr::update(...) called before ATCMgr::init()");
111     }
112     
113     current_atcdialog->Update(dt);
114     
115     //cout << "Entering update..." << endl;
116     //Traverse the list of active stations.
117     //Only update one class per update step to avoid the whole ATC system having to calculate between frames.
118     //Eventually we should only update every so many steps.
119     //cout << "In FGATCMgr::update - atc_list.size = " << atc_list->size() << endl;
120     if(atc_list->size()) {
121         if(atc_list_itr == atc_list->end()) {
122             atc_list_itr = atc_list->begin();
123         }
124         //cout << "Updating " << (*atc_list_itr)->get_ident() << ' ' << (*atc_list_itr)->GetType() << '\n';
125         //cout << "Freq = " << (*atc_list_itr)->get_freq() << '\n';
126         (*atc_list_itr).second->Update(dt * atc_list->size());
127         //cout << "Done ATC update..." << endl;
128         ++atc_list_itr;
129     }
130     
131 #ifdef ATC_TEST
132     cout << "ATC_LIST: " << atc_list->size() << ' ';
133     for(atc_list_iterator it = atc_list->begin(); it != atc_list->end(); it++) {
134         cout << (*it)->get_ident() << ' ';
135     }
136     cout << '\n';
137 #endif
138     
139     // Search the tuned frequencies every now and then - this should be done with the event scheduler
140     static int i = 0;   // Very ugly - but there should only ever be one instance of FGATCMgr.
141     if(i == 15) {
142         //cout << "About to search navcomm1" << endl;
143         FreqSearch("comm", 0);
144         FreqSearch("nav", 0);
145     }
146     if(i == 30) {
147         //cout << "About to search navcomm2" << endl;
148         FreqSearch("comm", 1);
149         FreqSearch("nav", 1);
150         i = 0;
151     }
152     ++i;
153     
154     //cout << "comm1 type = " << comm_type[0] << '\n';
155     //cout << "Leaving update..." << endl;
156 }
157
158
159 // Returns frequency in KHz - should I alter this to return in MHz?
160 unsigned short int FGATCMgr::GetFrequency(const string& ident, const atc_type& tp) {
161     ATCData test;
162     bool ok = current_commlist->FindByCode(ident, test, tp);
163     return(ok ? test.freq : 0);
164 }   
165
166 // Register the fact that the comm radio is tuned to an airport
167 // Channel is zero based
168 bool FGATCMgr::CommRegisterAirport(const string& ident, int chan, const atc_type& tp) {
169     SG_LOG(SG_ATC, SG_BULK, "Comm channel " << chan << " registered airport " << ident);
170     //cout << "Comm channel " << chan << " registered airport " << ident << ' ' << tp << '\n';
171     if(airport_atc_map.find(ident) != airport_atc_map.end()) {
172         //cout << "IN MAP - flagging set by comm..." << endl;
173 //xx        airport_atc_map[ident]->set_by_comm[chan][tp] = true;
174         if(tp == ATIS || tp == AWOS) {
175             airport_atc_map[ident]->atis_active = true;
176         } else if(tp == TOWER) {
177             airport_atc_map[ident]->tower_active = true;
178         } else if(tp == GROUND) {
179             airport_atc_map[ident]->ground_active = true;
180         } else if(tp == APPROACH) {
181             //a->approach_active = true;
182         }   // TODO - there *must* be a better way to do this!!!
183         return(true);
184     } else {
185         //cout << "NOT IN MAP - creating new..." << endl;
186         const FGAirport *ap = fgFindAirportID(ident);
187         if (ap) {
188             AirportATC *a = new AirportATC;
189             // I'm not entirely sure that this AirportATC structure business is actually needed - it just duplicates what we can find out anyway!
190             a->geod = ap->geod();
191             a->atis_freq = GetFrequency(ident, ATIS)
192                     || GetFrequency(ident, AWOS);
193             a->atis_active = false;
194             a->tower_freq = GetFrequency(ident, TOWER);
195             a->tower_active = false;
196             a->ground_freq = GetFrequency(ident, GROUND);
197             a->ground_active = false;
198             if(tp == ATIS || tp == AWOS) {
199                 a->atis_active = true;
200             } else if(tp == TOWER) {
201                 a->tower_active = true;
202             } else if(tp == GROUND) {
203                 a->ground_active = true;
204             } else if(tp == APPROACH) {
205                 //a->approach_active = true;
206             }   // TODO - there *must* be a better way to do this!!!
207             // TODO - some airports will have a tower/ground frequency but be inactive overnight.
208             a->set_by_AI = false;
209             a->numAI = 0;
210 //xx            a->set_by_comm[chan][tp] = true;
211             airport_atc_map[ident] = a;
212             return(true);
213         }
214     }
215     return(false);
216 }
217
218 typedef map<string,int> MSI;
219
220 void FGATCMgr::ZapOtherService(const string ncunit, const string svc_name){
221   for (atc_list_iterator svc = atc_list->begin(); svc != atc_list->end(); svc++) {
222    
223     if (svc->first != svc_name) {
224       MSI &actv = svc->second->active_on;
225       // OK, we have found some OTHER service;
226       // see if it is (was) active on our unit:
227       if (!actv.count(ncunit)) continue;
228       // cout << "Eradicating '" << svc->first << "' from: " << ncunit << endl;
229       actv.erase(ncunit);
230       if (!actv.size()) {
231         //cout << "Eradicating service: '" << svc->first << "'" << endl;
232     svc->second->SetNoDisplay();
233     svc->second->Update(0);     // one last update
234     SG_LOG(SG_GENERAL, SG_INFO, "would have erased ATC service:" << svc->second->get_name()<< "/" 
235       << svc->second->get_ident());
236    // delete svc->second;
237     atc_list->erase(svc);
238 // ALL pointers into the ATC list are now invalid,
239 // so let's reset them:
240     atc_list_itr = atc_list->begin();
241       }
242       break;        // cannot be duplicates in the active list
243     }
244   }
245 }
246
247
248 // Find in list - return a currently active ATC pointer given ICAO code and type
249 // Return NULL if the given service is not in the list
250 // - *** THE CALLING FUNCTION MUST CHECK FOR THIS ***
251 FGATC* FGATCMgr::FindInList(const string& id, const atc_type& tp) {
252   string ndx = id + decimalNumeral(tp);
253   if (!atc_list->count(ndx)) return 0;
254   return (*atc_list)[ndx];
255 }
256
257 // Returns true if the airport is found in the map
258 bool FGATCMgr::GetAirportATCDetails(const string& icao, AirportATC* a) {
259     if(airport_atc_map.find(icao) != airport_atc_map.end()) {
260         *a = *airport_atc_map[icao];
261         return(true);
262     } else {
263         return(false);
264     }
265 }
266
267
268 // Return a pointer to a given sort of ATC at a given airport and activate if necessary
269 // Returns NULL if service doesn't exist - calling function should check for this.
270 // We really ought to make this private and call it from the CommRegisterAirport / AIRegisterAirport functions
271 // - at the moment all these GetATC... functions exposed are just too complicated.
272 FGATC* FGATCMgr::GetATCPointer(const string& icao, const atc_type& type) {
273     if(airport_atc_map.find(icao) == airport_atc_map.end()) {
274         //cout << "Unable to find " << icao << ' ' << type << " in the airport_atc_map" << endl;
275         return NULL;
276     }
277     //cout << "In GetATCPointer, found " << icao << ' ' << type << endl;
278     AirportATC *a = airport_atc_map[icao];
279     //cout << "a->lon = " << a->lon << '\n';
280     //cout << "a->elev = " << a->elev << '\n';
281     //cout << "a->tower_freq = " << a->tower_freq << '\n';
282     switch(type) {
283     case TOWER:
284         if(a->tower_active) {
285             // Get the pointer from the list
286             return(FindInList(icao, type));
287         } else {
288             ATCData data;
289             if(current_commlist->FindByFreq(a->geod, a->tower_freq, &data, TOWER)) {
290                 FGTower* t = new FGTower;
291                 t->SetData(&data);
292                 (*atc_list)[icao+decimalNumeral(type)] = t;
293                 a->tower_active = true;
294                 airport_atc_map[icao] = a;
295                 //cout << "Initing tower " << icao << " in GetATCPointer()\n";
296                 t->Init();
297                 return(t);
298             } else {
299                 SG_LOG(SG_ATC, SG_ALERT, "ERROR - tower that should exist in FGATCMgr::GetATCPointer for airport " << icao << " not found");
300             }
301         }
302         break;
303     case APPROACH:
304         break;
305     case ATIS: case AWOS:
306         SG_LOG(SG_ATC, SG_ALERT, "ERROR - ATIS station should not be requested from FGATCMgr::GetATCPointer");
307         break;
308     case GROUND:
309         //cout << "IN CASE GROUND" << endl;
310         if(a->ground_active) {
311             // Get the pointer from the list
312             return(FindInList(icao, type));
313         } else {
314             ATCData data;
315             if(current_commlist->FindByFreq(a->geod, a->ground_freq, &data, GROUND)) {
316                 FGGround* g = new FGGround;
317                 g->SetData(&data);
318                 (*atc_list)[icao+decimalNumeral(type)] = g;
319                 a->ground_active = true;
320                 airport_atc_map[icao] = a;
321                 g->Init();
322                 return(g);
323             } else {
324                 SG_LOG(SG_ATC, SG_ALERT, "ERROR - ground control that should exist in FGATCMgr::GetATCPointer for airport " << icao << " not found");
325             }
326         }
327         break;
328         case INVALID:
329         break;
330         case ENROUTE:
331         break;
332         case DEPARTURE:
333         break;
334     }
335     
336     SG_LOG(SG_ATC, SG_ALERT, "ERROR IN FGATCMgr - reached end of GetATCPointer");
337     //cout << "ERROR IN FGATCMgr - reached end of GetATCPointer" << endl;
338     
339     return(NULL);
340 }
341
342 // Return a pointer to an appropriate voice for a given type of ATC
343 // creating the voice if necessary - ie. make sure exactly one copy
344 // of every voice in use exists in memory.
345 //
346 // TODO - in the future this will get more complex and dole out country/airport
347 // specific voices, and possible make sure that the same voice doesn't get used
348 // at different airports in quick succession if a large enough selection are available.
349 FGATCVoice* FGATCMgr::GetVoicePointer(const atc_type& type) {
350     // TODO - implement me better - maintain a list of loaded voices and other voices!!
351     if(voice) {
352         switch(type) {
353         case ATIS: case AWOS:
354 #ifdef ENABLE_AUDIO_SUPPORT
355             // Delayed loading fo all available voices, needed because the
356             // soundmanager might not be initialized (at all) at this point.
357             // For now we'll do one hardwired one
358
359             /* I've loaded the voice even if /sim/sound/pause is true
360              *  since I know no way of forcing load of the voice if the user
361              *  subsequently switches /sim/sound/audible to true.
362              *  (which is the right thing to do -- CLO) :-)
363              */
364             if (!voiceOK && fgGetBool("/sim/sound/working")) {
365                 v1 = new FGATCVoice;
366                 try {
367                     voiceOK = v1->LoadVoice("default");
368                     voice = voiceOK;
369                 } catch ( sg_io_exception & e) {
370                     voiceOK  = false;
371                     SG_LOG(SG_ATC, SG_ALERT, "Unable to load default voice : "
372                                             << e.getFormattedMessage().c_str());
373                     voice = false;
374                     delete v1;
375                     v1 = 0;
376                 }
377             }
378 #endif
379             if(voiceOK) {
380                 return(v1);
381             }
382         case TOWER:
383             return(NULL);
384         case APPROACH:
385             return(NULL);
386         case GROUND:
387             return(NULL);
388         default:
389             return(NULL);
390         }
391         return(NULL);
392     } else {
393         return(NULL);
394     }
395 }
396
397 // Search for ATC stations by frequency
398 void FGATCMgr::FreqSearch(const string navcomm, const int unit) {
399
400
401         string ncunit = navcomm + "[" + decimalNumeral(unit) + "]";
402     string commbase = "/instrumentation/" + ncunit;
403     string commfreq = commbase + "/frequencies/selected-mhz";
404         SGPropertyNode_ptr comm_node = fgGetNode(commfreq.c_str(), false);
405
406     //cout << "FreqSearch: " << ncunit
407     //  << "  node: " << comm_node << endl;
408     if (!comm_node) return; // no such radio unit
409
410     ATCData data;   
411     double freq = comm_node->getDoubleValue();
412     _aircraftPos = SGGeod::fromDegFt(lon_node->getDoubleValue(),
413       lat_node->getDoubleValue(), elev_node->getDoubleValue());
414     
415 // Query the data store and get the closest match if any
416     //cout << "Will FindByFreq: " << lat << " " << lon << " " << elev
417     //      << "  freq: " << freq << endl;
418     if(current_commlist->FindByFreq(_aircraftPos, freq, &data)) {
419       //cout << "FoundByFreq: " << freq 
420       //  << "  ident: " << data.ident 
421       //  << "  type: " << data.type << " ***" << endl;
422 // We are in range of something.
423
424
425 // Get rid of any *other* service that was on this radio unit:
426             string svc_name = data.ident+decimalNumeral(data.type);
427         ZapOtherService(ncunit, svc_name);
428 // See if the service already exists, possibly connected to
429 // some other radio unit:
430         if (atc_list->count(svc_name)) {
431           // make sure the service knows it's tuned on this radio:
432           FGATC* svc = (*atc_list)[svc_name];
433           svc->active_on[ncunit] = 1;
434           svc->SetDisplay();
435           if (data.type == APPROACH) svc->AddPlane("Player");
436           return;
437         }
438
439         CommRegisterAirport(data.ident, unit, data.type);
440
441 // This was a switch-case statement but the compiler didn't like 
442 // the new variable creation with it. 
443         if      (data.type == ATIS
444               || data.type == AWOS)     (*atc_list)[svc_name] = new FGATIS;
445         else if (data.type == TOWER)    (*atc_list)[svc_name] = new FGTower;
446         else if (data.type == GROUND)   (*atc_list)[svc_name] = new FGGround;
447         FGATC* svc = (*atc_list)[svc_name];
448         svc->SetData(&data);
449         svc->active_on[ncunit] = 1;
450         svc->SetDisplay();
451         svc->Init();
452         if (data.type == APPROACH) svc->AddPlane("Player");
453     } else {
454       // No services in range.  Zap any service on this unit.
455       ZapOtherService(ncunit, "x x x");
456     } 
457 }