]> git.mxchange.org Git - flightgear.git/blob - src/ATCDCL/atis.cxx
Merge branch 'next' of gitorious.org:fg/flightgear into next
[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
38 #include <stdlib.h> // atoi()
39 #include <stdio.h>  // sprintf
40 #include <string>
41 #include <iostream>
42
43 #include <boost/tuple/tuple.hpp>
44 #include <boost/algorithm/string.hpp>
45 #include <boost/algorithm/string/case_conv.hpp>
46
47
48 #include <simgear/misc/sg_path.hxx>
49
50 #include <Environment/environment_mgr.hxx>
51 #include <Environment/environment.hxx>
52 #include <Environment/atmosphere.hxx>
53
54 #include <Main/fg_props.hxx>
55 #include <Main/globals.hxx>
56 #include <Airports/runways.hxx>
57
58
59 #include "commlist.hxx"
60 #include "ATCutils.hxx"
61 #include "ATCmgr.hxx"
62
63 using std::cout;
64 using std::cout;
65 using boost::ref;
66 using boost::tie;
67
68 FGATIS::FGATIS() :
69   transmission(""),
70   trans_ident(""),
71   old_volume(0),
72   atis_failed(false),
73   msg_OK(0),
74   attention(0),
75   _prev_display(0),
76   refname("atis")
77 {
78   _vPtr = globals->get_ATC_mgr()->GetVoicePointer(ATIS);
79   _voiceOK = (_vPtr == NULL ? false : true);
80   if (!(_type != ATIS || _type == AWOS)) {
81        SG_LOG(SG_ATC, SG_ALERT, "ERROR - _type not ATIS or AWOS in atis.cxx");
82   }
83   fgTie("/environment/attention", this, (int_getter)0, &FGATIS::attend);
84
85 ///////////////
86 // FIXME:  This would be more flexible and more extensible
87 // if the mappings were taken from an XML file, not hard-coded ...
88 // ... although having it in a .hxx file is better than nothing.
89 //
90 // Load the remap list from the .hxx file:
91   using namespace lex;
92 # define NIL ""
93 # define REMAP(from,to) _remap[#from] = to;
94 # include "atis_remap.hxx"
95 # undef REMAP
96 # undef NIL
97
98 #ifdef ATIS_TEST
99   SG_LOG(SG_ATC, SG_ALERT, "ATIS initialized");
100 #endif
101 }
102
103 // Hint:
104 // http://localhost:5400/environment/attention?value=1&submit=update
105
106 FGATIS::~FGATIS() {
107   fgUntie("/environment/attention");
108 }
109
110 void FGATIS::Init() {
111 // Nothing to see here.  Move along.
112 }
113
114 void
115 FGATIS::attend (int attn)
116 {
117   attention = attn;
118 #ifdef ATMO_TEST
119   int flag = fgGetInt("/sim/logging/atmo");
120   if (flag) {
121     FGAltimeter().check_model();
122         FGAltimeter().dump_stack();
123   }
124 #endif
125 }
126
127
128 // Main update function - checks whether we are displaying or not the correct message.
129 void FGATIS::Update(double dt) {
130   cur_time = globals->get_time_params()->get_cur_time();
131   msg_OK = (msg_time < cur_time);
132 #ifdef ATIS_TEST
133   if (msg_OK || _display != _prev_display) {
134     cout << "ATIS Update: " << _display << "  " << _prev_display
135       << "  len: " << transmission.length()
136       << "  oldvol: " << old_volume
137       << "  dt: " << dt << endl;
138     msg_time = cur_time;
139   }
140 #endif
141   if(_display) {
142     double volume(0);
143     for (map<string,int>::iterator act = active_on.begin();
144     act != active_on.end(); act++) {
145       string prop = "/instrumentation/" + act->first + "/volume";
146       volume += globals->get_props()->getDoubleValue(prop.c_str());
147     }
148
149 // Check if we need to update the message
150 // - basically every hour and if the weather changes significantly at the station
151 // If !_prev_display, the radio had been detuned for a while and our
152 // "transmission" variable was lost when we were de-instantiated.
153     int rslt = GenTransmission(!_prev_display, attention);
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 // Generate the actual broadcast ATIS transmission.
211 // Regen means regenerate the /current/ transmission.
212 // Special means generate a new transmission, with a new sequence.
213 // Returns 1 if we actually generated something.
214 int FGATIS::GenTransmission(const int regen, const int special) {
215   using namespace atmodel;
216   using namespace lex;
217
218   string BRK = ".\n";
219   string PAUSE = " / ";
220
221   double tstamp = atof(fgGetString("sim/time/elapsed-sec"));
222   int interval = _type == ATIS ?
223         ATIS_interval   // ATIS updated hourly
224       : 2*minute;       // AWOS updated more frequently
225   int sequence = current_commlist->GetAtisSequence(ident, 
226                         tstamp, interval, special);
227   if (!regen && sequence > LTRS) {
228 //xx      if (msg_OK) cout << "ATIS:  no change: " << sequence << endl;
229 //xx      msg_time = cur_time;
230     return 0;   // no change since last time
231   }
232
233   const int bs(100);
234   char buf[bs];
235   string time_str = fgGetString("sim/time/gmt-string");
236   string hours, mins;
237   string phonetic_seq_string;
238
239   transmission = "";
240
241   if (ident.substr(0,2) == "EG") {
242 // UK CAA radiotelephony manual indicates ATIS transmissions start
243 // with "This is ..." 
244     transmission += This_is + " ";
245   } else {
246     // In the US they just start with the airport name.
247   }
248
249   // SG_LOG(SG_ATC, SG_ALERT, "ATIS: facility name: " << name);
250
251 // Note that at this point, multi-word facility names
252 // will sometimes contain hyphens, not spaces.
253   
254   vector<string> name_words;
255   boost::split(name_words, name, boost::is_any_of(" -"));
256
257   for (vector<string>::const_iterator wordp = name_words.begin();
258                 wordp != name_words.end(); wordp++) {
259     string word(*wordp);
260 // Remap some abbreviations that occur in apt.dat, to
261 // make things nicer for the text-to-speech system:
262     for (MSS::const_iterator replace = _remap.begin();
263           replace != _remap.end(); replace++) {
264       // Due to inconsistent capitalisation in the apt.dat file, we need
265       // to do a case-insensitive comparison here.
266       string tmp1 = word, tmp2 = replace->first;
267       boost::algorithm::to_lower(tmp1);
268       boost::algorithm::to_lower(tmp2);
269       if (tmp1 == tmp2) {
270         word = replace->second;
271         break;
272       }
273     }
274     transmission += word + " ";
275   }
276
277   if (_type == ATIS /* as opposed to AWOS */) {
278     transmission += airport_information + " ";
279   } else {
280     transmission += Automated_weather_observation + " ";
281   }
282
283   phonetic_seq_string = GetPhoneticLetter(sequence);  // Add the sequence letter
284   transmission += phonetic_seq_string + BRK;
285
286 // Warning - this is fragile if the time string format changes
287   hours = time_str.substr(0,2).c_str();
288   mins  = time_str.substr(3,2).c_str();
289 // speak each digit separately:
290   transmission += ConvertNumToSpokenDigits(hours + mins);
291   transmission += " " + zulu + " " + weather + BRK;
292
293   transmission += wind + ": ";
294
295   double wind_speed = fgGetDouble("/environment/config/boundary/entry[0]/wind-speed-kt");
296   double wind_dir = fgGetDouble("/environment/config/boundary/entry[0]/wind-from-heading-deg");
297   while (wind_dir <= 0) wind_dir += 360;
298 // The following isn't as bad a kludge as it might seem.
299 // It combines the magvar at the /aircraft/ location with
300 // the wind direction in the environment/config array.
301 // But if the aircraft is close enough to the station to
302 // be receiving the ATIS signal, this should be a good-enough
303 // approximation.  For more-distant aircraft, the wind_dir
304 // shouldn't be corrected anyway.
305 // The less-kludgy approach would be to use the magvar associated
306 // with the station, but that is not tabulated in the stationweather
307 // structure as it stands, and computing it would be expensive.
308 // Also note that as it stands, there is only one environment in
309 // the entire FG universe, so the aircraft environment is the same
310 // as the station environment anyway.
311   wind_dir -= fgGetDouble("/environment/magnetic-variation-deg");       // wind_dir now magnetic
312   if (wind_speed == 0) {
313 // Force west-facing rwys to be used in no-wind situations
314 // which is consistent with Flightgear's initial setup:
315       wind_dir = 270;
316       transmission += " " + light_and_variable;
317   } else {
318       // FIXME: get gust factor in somehow
319       snprintf(buf, bs, "%03.0f", 5*SGMiscd::round(wind_dir/5));
320       transmission += ConvertNumToSpokenDigits(buf);
321
322       snprintf(buf, bs, "%1.0f", wind_speed);
323       transmission += " " + at + " " + ConvertNumToSpokenDigits(buf) + BRK;
324   }
325
326 // Sounds better with a pause in there:
327   transmission += PAUSE;
328
329   int did_some(0);
330   int did_ceiling(0);
331
332   for (int layer = 0; layer <= 4; layer++) {
333     snprintf(buf, bs, "/environment/clouds/layer[%i]/coverage", layer);
334     string coverage = fgGetString(buf);
335     if (coverage == clear) continue;
336     snprintf(buf, bs, "/environment/clouds/layer[%i]/thickness-ft", layer);
337     if (fgGetDouble(buf) == 0) continue;
338     snprintf(buf, bs, "/environment/clouds/layer[%i]/elevation-ft", layer);
339     double ceiling = int(fgGetDouble(buf) - _geod.getElevationFt());
340     if (ceiling > 12000) continue;
341     if (coverage == scattered) {
342       if (!did_some) transmission += "   " + Sky_condition + ": ";
343       did_some++;
344     } else /* must be a ceiling */  if (!did_ceiling) {
345       transmission += "   " + Ceiling + ": ";
346       did_ceiling++;
347       did_some++;
348     } else {
349       transmission += "   ";
350     }
351     int cig00  = int(SGMiscd::round(ceiling/100));  // hundreds of feet
352     if (cig00) {
353       int cig000 = cig00/10;
354       cig00 -= cig000*10;       // just the hundreds digit
355       if (cig000) {
356     snprintf(buf, bs, "%i", cig000);
357     transmission += ConvertNumToSpokenDigits(buf);
358     transmission += " " + thousand + " ";
359       }
360       if (cig00) {
361     snprintf(buf, bs, "%i", cig00);
362     transmission += ConvertNumToSpokenDigits(buf);
363     transmission += " " + hundred + " ";
364       }
365     } else {
366       // Should this be "sky obscured?"
367       transmission += " " + zero + " ";     // not "zero hundred"
368     }
369     transmission += coverage + BRK;
370   }
371
372   transmission += Temperature + ": ";
373   double Tsl = fgGetDouble("/environment/temperature-sea-level-degc");
374   int temp = int(SGMiscd::round(FGAtmo().fake_T_vs_a_us(_geod.getElevationFt(), Tsl)));
375   if(temp < 0) {
376       transmission += lex::minus + " ";
377   }
378   snprintf(buf, bs, "%i", abs(temp));
379   transmission += ConvertNumToSpokenDigits(buf);
380   transmission += " " + Celsius;
381   transmission += " " + dewpoint + " ";
382   double dpsl = fgGetDouble("/environment/dewpoint-sea-level-degc");
383   temp = int(SGMiscd::round(FGAtmo().fake_dp_vs_a_us(dpsl, _geod.getElevationFt())));
384   if(temp < 0) {
385       transmission += lex::minus + " ";
386   }
387   snprintf(buf, bs, "%i", abs(temp));
388   transmission += ConvertNumToSpokenDigits(buf);
389   transmission += " " + Celsius + BRK;
390
391   transmission += Visibility + ": ";
392   double visibility = fgGetDouble("/environment/config/boundary/entry[0]/visibility-m");
393   visibility /= atmodel::sm;    // convert to statute miles
394   if (visibility < 0.25) {
395     transmission += less_than_one_quarter;
396   } else if (visibility < 0.5) {
397     transmission += one_quarter;
398   } else if (visibility < 0.75) {
399     transmission += one_half;
400   } else if (visibility < 1.0) {
401     transmission += three_quarters;
402   } else if (visibility >= 1.5 && visibility < 2.0) {
403     transmission += one_and_one_half;
404   } else {
405     // integer miles
406     if (visibility > 10) visibility = 10;
407     sprintf(buf, "%i", int(.5 + visibility));
408     transmission += ConvertNumToSpokenDigits(buf);
409   }
410   transmission += BRK;
411
412   transmission += Altimeter + ": ";
413   double myQNH;
414   double Psl = fgGetDouble("/environment/pressure-sea-level-inhg");
415   {
416     double press, temp;
417     
418     tie(press, temp) = PT_vs_hpt(_geod.getElevationM(), Psl*inHg, Tsl + freezing);
419 #if 0
420     SG_LOG(SG_ATC, SG_ALERT, "Field P: " << press << "  T: " << temp);
421     SG_LOG(SG_ATC, SG_ALERT, "based on elev " << elev 
422                                 << "  Psl: " << Psl
423                                 << "  Tsl: " << Tsl);
424 #endif
425     myQNH = FGAtmo().QNH(_geod.getElevationM(), press);
426   }
427   if(ident.substr(0,2) == "EG" && fgGetBool("/sim/atc/use-millibars")) {
428     // Convert to millibars for the UK!
429     myQNH /= mbar;
430     if  (myQNH > 1000) myQNH -= 1000;       // drop high digit
431     snprintf(buf, bs, "%03.0f", myQNH);
432   } else {
433     myQNH /= inHg;
434     myQNH *= 100.;                        // shift two decimal places
435     snprintf(buf, bs, "%04.0f", myQNH);
436   }
437   transmission += ConvertNumToSpokenDigits(buf) + BRK;
438
439   if (_type == ATIS /* as opposed to AWOS */) {
440     const FGAirport* apt = fgFindAirportID(ident);
441     if (apt) {
442       string rwy_no = apt->getActiveRunwayForUsage()->ident();
443       if(rwy_no != "NN") {
444         transmission += Landing_and_departing_runway + " ";
445         transmission += ConvertRwyNumToSpokenString(rwy_no) + BRK;
446 #ifdef ATIS_TEST
447         if (msg_OK) {
448           msg_time = cur_time;
449           cout << "In atis.cxx, r.rwy_no: " << rwy_no
450              << " wind_dir: " << wind_dir << endl;
451         }
452 #endif
453       }
454     }
455     transmission += On_initial_contact_advise_you_have_information + " ";
456     transmission += phonetic_seq_string;
457     transmission += "... " + BRK + PAUSE + PAUSE;
458   }
459 #ifdef ATIS_TEST
460   cout << "**** ATIS active on:";
461 #endif
462   for (map<string,int>::iterator act = active_on.begin(); act != active_on.end(); act++){
463     string prop = "/instrumentation/" + act->first + "/atis";
464     globals->get_props()->setStringValue(prop.c_str(),
465       ("<pre>\n" + transmission + "</pre>\n").c_str());
466 #ifdef ATIS_TEST
467     cout << "  " << prop;
468 #endif
469   }
470 #ifdef ATIS_TEST
471   cout << " ****" << endl;
472   cout << transmission << endl;
473 // Note that even if we aren't outputting the transmission
474 // on stdout, you can still see it by pointing a web browser
475 // at the property tree.  The second comm radio is:
476 // http://localhost:5400/instrumentation/comm[1]
477 #endif
478
479 // Take the previous English-looking string and munge it to
480 // be relatively-more acceptable to the primitive tts system.
481 // Note that : ; and . are among the token-delimeters recognized
482 // by the tts system.
483   for (size_t where;;) {
484     where = transmission.find_first_of(":.");
485     if (where == string::npos) break;
486     transmission.replace(where, 1, PAUSE);
487   }
488   return 1;
489 }