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