]> git.mxchange.org Git - flightgear.git/blob - src/ATCDCL/atis.cxx
Push some of the ATIS logic into AirportDynamics, in preparation for ATIS being owned...
[flightgear.git] / src / ATCDCL / atis.cxx
1 // atis.cxx - routines to generate the ATIS info string
2 // This is the implementation of the FGATIS class
3 //
4 // Written by David Luff, started October 2001.
5 //
6 // Copyright (C) 2001  David C Luff - david.luff@nottingham.ac.uk
7 //
8 // This program is free software; you can redistribute it and/or
9 // modify it under the terms of the GNU General Public License as
10 // published by the Free Software Foundation; either version 2 of the
11 // License, or (at your option) any later version.
12 //
13 // This program is distributed in the hope that it will be useful, but
14 // WITHOUT ANY WARRANTY; without even the implied warranty of
15 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16 // General Public License for more details.
17 //
18 // You should have received a copy of the GNU General Public License
19 // along with this program; if not, write to the Free Software
20 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
21
22 /////
23 ///// TODO:  _Cumulative_ sky coverage.
24 ///// TODO:  wind _gust_
25 ///// TODO:  more-sensible encoding of voice samples
26 /////       u-law?  outright synthesis?
27 /////
28
29 #ifdef HAVE_CONFIG_H
30 #  include <config.h>
31 #endif
32
33 #include "atis.hxx"
34 #include "atis_lexicon.hxx"
35
36 #include <simgear/compiler.h>
37 #include <simgear/math/sg_random.h>
38 #include <simgear/misc/sg_path.hxx>
39
40 #include <stdlib.h> // atoi()
41 #include <stdio.h>  // sprintf
42 #include <string>
43 #include <iostream>
44
45 #include <boost/tuple/tuple.hpp>
46 #include <boost/algorithm/string.hpp>
47 #include <boost/algorithm/string/case_conv.hpp>
48
49 #include <Environment/environment_mgr.hxx>
50 #include <Environment/environment.hxx>
51 #include <Environment/atmosphere.hxx>
52
53 #include <Main/fg_props.hxx>
54 #include <Main/globals.hxx>
55 #include <Airports/runways.hxx>
56 #include <Airports/dynamics.hxx>
57
58
59 #include "ATCutils.hxx"
60 #include "ATCmgr.hxx"
61
62 using std::cout;
63 using std::cout;
64 using boost::ref;
65 using boost::tie;
66
67 FGATIS::FGATIS() :
68   transmission(""),
69   trans_ident(""),
70   old_volume(0),
71   atis_failed(false),
72   msg_OK(0),
73   attention(0),
74   _prev_display(0),
75   refname("atis")
76 {
77   _vPtr = globals->get_ATC_mgr()->GetVoicePointer(ATIS);
78   _voiceOK = (_vPtr == NULL ? false : true);
79   if (!(_type != ATIS || _type == AWOS)) {
80        SG_LOG(SG_ATC, SG_ALERT, "ERROR - _type not ATIS or AWOS in atis.cxx");
81   }
82   fgTie("/environment/attention", this, (int_getter)0, &FGATIS::attend);
83
84 ///////////////
85 // FIXME:  This would be more flexible and more extensible
86 // if the mappings were taken from an XML file, not hard-coded ...
87 // ... although having it in a .hxx file is better than nothing.
88 //
89 // Load the remap list from the .hxx file:
90   using namespace lex;
91 # define NIL ""
92 # define REMAP(from,to) _remap[#from] = to;
93 # include "atis_remap.hxx"
94 # undef REMAP
95 # undef NIL
96
97 #ifdef ATIS_TEST
98   SG_LOG(SG_ATC, SG_ALERT, "ATIS initialized");
99 #endif
100 }
101
102 // Hint:
103 // http://localhost:5400/environment/attention?value=1&submit=update
104
105 FGATIS::~FGATIS() {
106   fgUntie("/environment/attention");
107 }
108
109 void FGATIS::Init() {
110 // Nothing to see here.  Move along.
111 }
112
113 void
114 FGATIS::attend (int attn)
115 {
116   attention = attn;
117 #ifdef ATMO_TEST
118   int flag = fgGetInt("/sim/logging/atmo");
119   if (flag) {
120     FGAltimeter().check_model();
121         FGAltimeter().dump_stack();
122   }
123 #endif
124 }
125
126
127 // Main update function - checks whether we are displaying or not the correct message.
128 void FGATIS::Update(double dt) {
129   cur_time = globals->get_time_params()->get_cur_time();
130   msg_OK = (msg_time < cur_time);
131 #ifdef ATIS_TEST
132   if (msg_OK || _display != _prev_display) {
133     cout << "ATIS Update: " << _display << "  " << _prev_display
134       << "  len: " << transmission.length()
135       << "  oldvol: " << old_volume
136       << "  dt: " << dt << endl;
137     msg_time = cur_time;
138   }
139 #endif
140   if(_display) {
141     double volume(0);
142     for (map<string,int>::iterator act = active_on.begin();
143     act != active_on.end(); act++) {
144       string prop = "/instrumentation/" + act->first + "/volume";
145       volume += globals->get_props()->getDoubleValue(prop.c_str());
146     }
147
148 // Check if we need to update the message
149 // - basically every hour and if the weather changes significantly at the station
150 // If !_prev_display, the radio had been detuned for a while and our
151 // "transmission" variable was lost when we were de-instantiated.
152     int rslt = GenTransmission(!_prev_display, attention);
153     TreeOut(msg_OK);
154     if (rslt || volume != old_volume) {
155       //cout << "ATIS calling ATC::render  volume: " << volume << endl;
156       Render(transmission, volume, refname, true);
157       old_volume = volume;
158     }
159   } else {
160 // We shouldn't be displaying
161     //cout << "ATIS.CXX - calling NoRender()..." << endl;
162     NoRender(refname);
163   }
164   _prev_display = _display;
165   attention = 0;
166 }
167
168 string uppercase(const string &s) {
169   string rslt(s);
170   for(string::iterator p = rslt.begin(); p != rslt.end(); p++){
171     *p = toupper(*p);
172   }
173   return rslt;
174 }
175
176 // Replace all occurrences of a given word.
177 // Words in the original string must be separated by hyphens (not spaces).
178 // We check for the word as given, and for the all-caps version thereof.
179 string replace_word(const string _orig, const string _www, const string _nnn){
180 // The following are so we can match words at the beginning
181 // and end of the string.
182   string orig = "-" + _orig + "-";
183   string www = "-" + _www + "-";
184   string nnn = "-" + _nnn + "-";
185
186   size_t where(0);
187   for ( ; (where = orig.find(www, where)) != string::npos ; ) {
188     orig.replace(where, www.length(), nnn);
189     where += nnn.length();
190   }
191   
192   www = uppercase(www);
193   for ( ; (where = orig.find(www, where)) != string::npos ; ) {
194     orig.replace(where, www.length(), nnn);
195     where += nnn.length();
196   }
197   where = orig.length();
198   return orig.substr(1, where-2);
199 }
200
201 // Normally the interval is 1 hour, 
202 // but you can shorten it for testing.
203 const int minute(60);           // measured in seconds
204 #ifdef ATIS_TEST
205   const int ATIS_interval(2*minute);
206 #else
207   const int ATIS_interval(60*minute);
208 #endif
209
210 // FIXME:  This is heuristic.  It gets the right answer for
211 // more than 90% of the world's airports, which is a lot
212 // better than nothing ... but it's not 100%.
213 // We know "most" of the world uses millibars,
214 // but the US, Canada and *some* other places use inches of mercury,
215 // but (a) we have not implemented a reliable method of
216 // ascertaining which airports are in the US, let alone
217 // (b) ascertaining which other places use inches.
218 //
219 int Apt_US_CA(const string id) {
220 // Assume all IDs have length 3 or 4.
221 // No counterexamples have been seen.
222   if (id.length() == 4) {
223     if (id.substr(0,1) == "K") return 1;
224     if (id.substr(0,2) == "CY") return 1;
225   }
226   for (string::const_iterator ptr = id.begin(); ptr != id.end();  ptr++) {
227     if (isdigit(*ptr)) return 1;
228   }
229   return 0;
230 }
231
232 // Generate the actual broadcast ATIS transmission.
233 // Regen means regenerate the /current/ transmission.
234 // Special means generate a new transmission, with a new sequence.
235 // Returns 1 if we actually generated something.
236 int FGATIS::GenTransmission(const int regen, const int special) {
237   using namespace atmodel;
238   using namespace lex;
239
240   string BRK = ".\n";
241   string PAUSE = " / ";
242
243   int interval = _type == ATIS ?
244         ATIS_interval   // ATIS updated hourly
245       : 2*minute;       // AWOS updated more frequently
246
247   FGAirport* apt = FGAirport::findByIdent(ident);
248   int sequence = apt->getDynamics()->updateAtisSequence(interval, special);
249   if (!regen && sequence > LTRS) {
250 //xx      if (msg_OK) cout << "ATIS:  no change: " << sequence << endl;
251 //xx      msg_time = cur_time;
252     return 0;   // no change since last time
253   }
254
255   const int bs(100);
256   char buf[bs];
257   string time_str = fgGetString("sim/time/gmt-string");
258   string hours, mins;
259   string phonetic_seq_string;
260
261   transmission = "";
262
263   int US_CA = Apt_US_CA(ident);
264
265   if (!US_CA) {
266 // UK CAA radiotelephony manual indicates ATIS transmissions start
267 // with "This is ..." 
268     transmission += This_is + " ";
269   } else {
270     // In the US they just start with the airport name.
271   }
272
273   // SG_LOG(SG_ATC, SG_ALERT, "ATIS: facility name: " << name);
274
275 // Note that at this point, multi-word facility names
276 // will sometimes contain hyphens, not spaces.
277   
278   vector<string> name_words;
279   boost::split(name_words, name, boost::is_any_of(" -"));
280
281   for (vector<string>::const_iterator wordp = name_words.begin();
282                 wordp != name_words.end(); wordp++) {
283     string word(*wordp);
284 // Remap some abbreviations that occur in apt.dat, to
285 // make things nicer for the text-to-speech system:
286     for (MSS::const_iterator replace = _remap.begin();
287           replace != _remap.end(); replace++) {
288       // Due to inconsistent capitalisation in the apt.dat file, we need
289       // to do a case-insensitive comparison here.
290       string tmp1 = word, tmp2 = replace->first;
291       boost::algorithm::to_lower(tmp1);
292       boost::algorithm::to_lower(tmp2);
293       if (tmp1 == tmp2) {
294         word = replace->second;
295         break;
296       }
297     }
298     transmission += word + " ";
299   }
300
301   if (_type == ATIS /* as opposed to AWOS */) {
302     transmission += airport_information + " ";
303   } else {
304     transmission += Automated_weather_observation + " ";
305   }
306
307   phonetic_seq_string = GetPhoneticLetter(sequence);  // Add the sequence letter
308   transmission += phonetic_seq_string + BRK;
309
310 // Warning - this is fragile if the time string format changes
311   hours = time_str.substr(0,2).c_str();
312   mins  = time_str.substr(3,2).c_str();
313 // speak each digit separately:
314   transmission += ConvertNumToSpokenDigits(hours + mins);
315   transmission += " " + zulu + " " + weather + BRK;
316
317   transmission += wind + ": ";
318
319   double wind_speed = fgGetDouble("/environment/config/boundary/entry[0]/wind-speed-kt");
320   double wind_dir = fgGetDouble("/environment/config/boundary/entry[0]/wind-from-heading-deg");
321   while (wind_dir <= 0) wind_dir += 360;
322 // The following isn't as bad a kludge as it might seem.
323 // It combines the magvar at the /aircraft/ location with
324 // the wind direction in the environment/config array.
325 // But if the aircraft is close enough to the station to
326 // be receiving the ATIS signal, this should be a good-enough
327 // approximation.  For more-distant aircraft, the wind_dir
328 // shouldn't be corrected anyway.
329 // The less-kludgy approach would be to use the magvar associated
330 // with the station, but that is not tabulated in the stationweather
331 // structure as it stands, and computing it would be expensive.
332 // Also note that as it stands, there is only one environment in
333 // the entire FG universe, so the aircraft environment is the same
334 // as the station environment anyway.
335   wind_dir -= fgGetDouble("/environment/magnetic-variation-deg");       // wind_dir now magnetic
336   if (wind_speed == 0) {
337 // Force west-facing rwys to be used in no-wind situations
338 // which is consistent with Flightgear's initial setup:
339       wind_dir = 270;
340       transmission += " " + light_and_variable;
341   } else {
342       // FIXME: get gust factor in somehow
343       snprintf(buf, bs, "%03.0f", 5*SGMiscd::round(wind_dir/5));
344       transmission += ConvertNumToSpokenDigits(buf);
345
346       snprintf(buf, bs, "%1.0f", wind_speed);
347       transmission += " " + at + " " + ConvertNumToSpokenDigits(buf) + BRK;
348   }
349
350 // Sounds better with a pause in there:
351   transmission += PAUSE;
352
353   int did_some(0);
354   int did_ceiling(0);
355
356   for (int layer = 0; layer <= 4; layer++) {
357     snprintf(buf, bs, "/environment/clouds/layer[%i]/coverage", layer);
358     string coverage = fgGetString(buf);
359     if (coverage == clear) continue;
360     snprintf(buf, bs, "/environment/clouds/layer[%i]/thickness-ft", layer);
361     if (fgGetDouble(buf) == 0) continue;
362     snprintf(buf, bs, "/environment/clouds/layer[%i]/elevation-ft", layer);
363     double ceiling = int(fgGetDouble(buf) - _geod.getElevationFt());
364     if (ceiling > 12000) continue;
365
366 // BEWARE:  At the present time, the environment system has no
367 // way (so far as I know) to represent a "thin broken" or
368 // "thin overcast" layer.  If/when such things are implemented
369 // in the environment system, code will have to be written here
370 // to handle them.
371
372 // First, do the prefix if any:
373     if (coverage == scattered || coverage == few) {
374       if (!did_some) {
375         transmission += "   " + Sky_condition + ": ";
376         did_some++;
377       }
378     } else /* must be a ceiling */  if (!did_ceiling) {
379       transmission += "   " + Ceiling + ": ";
380       did_ceiling++;
381       did_some++;
382     } else {
383       transmission += "   ";    // no prefix required
384     }
385     int cig00  = int(SGMiscd::round(ceiling/100));  // hundreds of feet
386     if (cig00) {
387       int cig000 = cig00/10;
388       cig00 -= cig000*10;       // just the hundreds digit
389       if (cig000) {
390         snprintf(buf, bs, "%i", cig000);
391         transmission += ConvertNumToSpokenDigits(buf);
392         transmission += " " + thousand + " ";
393       }
394       if (cig00) {
395         snprintf(buf, bs, "%i", cig00);
396         transmission += ConvertNumToSpokenDigits(buf);
397         transmission += " " + hundred + " ";
398       }
399     } else {
400       // Should this be "sky obscured?"
401       transmission += " " + zero + " ";     // not "zero hundred"
402     }
403     transmission += coverage + BRK;
404   }
405   if (!did_some) transmission += "   " + Sky + " " + clear + BRK;
406
407   transmission += Temperature + ": ";
408   double Tsl = fgGetDouble("/environment/temperature-sea-level-degc");
409   int temp = int(SGMiscd::round(FGAtmo().fake_T_vs_a_us(_geod.getElevationFt(), Tsl)));
410   if(temp < 0) {
411       transmission += lex::minus + " ";
412   }
413   snprintf(buf, bs, "%i", abs(temp));
414   transmission += ConvertNumToSpokenDigits(buf);
415   if (US_CA) transmission += " " + Celsius;
416   transmission += " " + dewpoint + " ";
417   double dpsl = fgGetDouble("/environment/dewpoint-sea-level-degc");
418   temp = int(SGMiscd::round(FGAtmo().fake_dp_vs_a_us(dpsl, _geod.getElevationFt())));
419   if(temp < 0) {
420       transmission += lex::minus + " ";
421   }
422   snprintf(buf, bs, "%i", abs(temp));
423   transmission += ConvertNumToSpokenDigits(buf);
424   if (US_CA) transmission += " " + Celsius;
425   transmission += BRK;
426
427   transmission += Visibility + ": ";
428   double visibility = fgGetDouble("/environment/config/boundary/entry[0]/visibility-m");
429   visibility /= atmodel::sm;    // convert to statute miles
430   if (visibility < 0.25) {
431     transmission += less_than_one_quarter;
432   } else if (visibility < 0.5) {
433     transmission += one_quarter;
434   } else if (visibility < 0.75) {
435     transmission += one_half;
436   } else if (visibility < 1.0) {
437     transmission += three_quarters;
438   } else if (visibility >= 1.5 && visibility < 2.0) {
439     transmission += one_and_one_half;
440   } else {
441     // integer miles
442     if (visibility > 10) visibility = 10;
443     sprintf(buf, "%i", int(.5 + visibility));
444     transmission += ConvertNumToSpokenDigits(buf);
445   }
446   transmission += BRK;
447
448   double myQNH;
449   double Psl = fgGetDouble("/environment/pressure-sea-level-inhg");
450   {
451     double press, temp;
452     
453     tie(press, temp) = PT_vs_hpt(_geod.getElevationM(), Psl*inHg, Tsl + freezing);
454 #if 0
455     SG_LOG(SG_ATC, SG_ALERT, "Field P: " << press << "  T: " << temp);
456     SG_LOG(SG_ATC, SG_ALERT, "based on elev " << elev 
457                                 << "  Psl: " << Psl
458                                 << "  Tsl: " << Tsl);
459 #endif
460     myQNH = FGAtmo().QNH(_geod.getElevationM(), press);
461   }
462
463 // Convert to millibars for most of the world (not US, not CA)
464   if((!US_CA) && fgGetBool("/sim/atc/use-millibars")) {
465     transmission += QNH + ": ";
466     myQNH /= mbar;
467     if  (myQNH > 1000) myQNH -= 1000;       // drop high digit
468     snprintf(buf, bs, "%03.0f", myQNH);
469     transmission += ConvertNumToSpokenDigits(buf) + " " + millibars + BRK;
470   } else {
471     transmission += Altimeter + ": ";
472     double asetting = myQNH / inHg;         // use inches of mercury
473     asetting *= 100.;                       // shift two decimal places
474     snprintf(buf, bs, "%04.0f", asetting);
475     transmission += ConvertNumToSpokenDigits(buf) + BRK;
476   }
477
478   if (_type == ATIS /* as opposed to AWOS */) {
479     const FGAirport* apt = fgFindAirportID(ident);
480     if (apt) {
481       string rwy_no = apt->getActiveRunwayForUsage()->ident();
482       if(rwy_no != "NN") {
483         transmission += Landing_and_departing_runway + " ";
484         transmission += ConvertRwyNumToSpokenString(rwy_no) + BRK;
485 #ifdef ATIS_TEST
486         if (msg_OK) {
487           msg_time = cur_time;
488           cout << "In atis.cxx, r.rwy_no: " << rwy_no
489              << " wind_dir: " << wind_dir << endl;
490         }
491 #endif
492       }
493     }
494     transmission += On_initial_contact_advise_you_have_information + " ";
495     transmission += phonetic_seq_string;
496     transmission += "... " + BRK + PAUSE + PAUSE;
497   }
498   transmission_readable = transmission;
499 // Take the previous readable string and munge it to
500 // be relatively-more acceptable to the primitive tts system.
501 // Note that : ; and . are among the token-delimeters recognized
502 // by the tts system.
503   for (size_t where;;) {
504     where = transmission.find_first_of(":.");
505     if (where == string::npos) break;
506     transmission.replace(where, 1, PAUSE);
507   }
508   return 1;
509 }
510
511 // Put the transmission into the property tree,
512 // possibly in multiple places if multiple radios
513 // are tuned to the same ATIS.
514 // You can see it by pointing a web browser
515 // at the property tree.  The second comm radio is:
516 // http://localhost:5400/instrumentation/comm[1]
517 //
518 // (Also, if in debug mode, dump it to the console.)
519 void FGATIS::TreeOut(int msg_OK){
520   for (map<string,int>::iterator act = active_on.begin();
521                 act != active_on.end();
522                 act++){
523     string prop = "/instrumentation/" + act->first + "/atis";
524     globals->get_props()->setStringValue(prop.c_str(),
525       ("<pre>\n" + transmission_readable + "</pre>\n").c_str());
526 #ifdef ATIS_TEST
527     if (msg_OK) cout << "**** ATIS active on: " << prop << endl;
528 #endif
529   }
530 #ifdef ATIS_TEST
531   if (msg_OK) cout << transmission_readable << endl;
532 #endif
533 }