]> git.mxchange.org Git - flightgear.git/blob - src/ATCDCL/atis.cxx
Fix ATIS output.
[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 #include <ATC/CommStation.hxx>
59
60 #include "ATCutils.hxx"
61 #include "ATISmgr.hxx"
62
63 using std::string;
64 using std::map;
65 using std::cout;
66 using std::cout;
67 using boost::ref;
68 using boost::tie;
69 using flightgear::CommStation;
70
71 FGATIS::FGATIS(const std::string& name, int num) :
72   _name(name),
73   _num(num),
74   _cb_attention(this, &FGATIS::attend, fgGetNode("/environment/attention", true)),
75   transmission(""),
76   trans_ident(""),
77   old_volume(0),
78   atis_failed(false),
79   msg_time(0),
80   cur_time(0),
81   msg_OK(0),
82   _attention(false),
83   _prev_display(0),
84   _time_before_search_sec(0),
85   _last_frequency(0)
86 {
87   _root         = fgGetNode("/instrumentation", true)->getNode(_name, num, true);
88   _volume       = _root->getNode("volume",true);
89   _serviceable  = _root->getNode("serviceable",true);
90
91   if (name != "nav")
92   {
93       // only drive "operable" for non-nav instruments (nav radio drives this separately)
94       _operable = _root->getNode("operable",true);
95       _operable->setBoolValue(false);
96   }
97
98   _electrical   = fgGetNode("/systems/electrical/outputs",true)->getNode(_name,num, true);
99   _atis         = _root->getNode("atis",true);
100   _freq         = _root->getNode("frequencies/selected-mhz",true);
101
102   // current position
103   _lon_node  = fgGetNode("/position/longitude-deg", true);
104   _lat_node  = fgGetNode("/position/latitude-deg",  true);
105   _elev_node = fgGetNode("/position/altitude-ft",   true);
106
107   // backward compatibility: some properties may not exist (but default to "ON")
108   if (!_serviceable->hasValue())
109       _serviceable->setBoolValue(true);
110   if (!_electrical->hasValue())
111       _electrical->setDoubleValue(24.0);
112
113 ///////////////
114 // FIXME:  This would be more flexible and more extensible
115 // if the mappings were taken from an XML file, not hard-coded ...
116 // ... although having it in a .hxx file is better than nothing.
117 //
118 // Load the remap list from the .hxx file:
119   using namespace lex;
120 # define NIL ""
121 # define REMAP(from,to) _remap[#from] = to;
122 # include "atis_remap.hxx"
123 # undef REMAP
124 # undef NIL
125
126 #ifdef ATIS_TEST
127   SG_LOG(SG_ATC, SG_ALERT, "ATIS initialized");
128 #endif
129 }
130
131 // Hint:
132 // http://localhost:5400/environment/attention?value=1&submit=update
133
134 FGATCVoice* FGATIS::GetVoicePointer()
135 {
136     FGATISMgr* pAtisMgr = globals->get_ATIS_mgr();
137     if (!pAtisMgr)
138     {
139         SG_LOG(SG_ATC, SG_ALERT, "ERROR! No ATIS manager! Oops...");
140         return NULL;
141     }
142
143     return pAtisMgr->GetVoicePointer(ATIS);
144 }
145
146 void FGATIS::init() {
147 // Nothing to see here.  Move along.
148 }
149
150 void
151 FGATIS::attend(SGPropertyNode* node)
152 {
153   _attention = node->getBoolValue();
154 #ifdef ATMO_TEST
155   int flag = fgGetInt("/sim/logging/atmo");
156   if (flag) {
157     FGAltimeter().check_model();
158         FGAltimeter().dump_stack();
159   }
160 #endif
161 }
162
163
164 // Main update function - checks whether we are displaying or not the correct message.
165 void FGATIS::update(double dt) {
166   cur_time = globals->get_time_params()->get_cur_time();
167   msg_OK = (msg_time < cur_time);
168
169 #ifdef ATIS_TEST
170   if (msg_OK || _display != _prev_display) {
171     cout << "ATIS Update: " << _display << "  " << _prev_display
172       << "  len: " << transmission.length()
173       << "  oldvol: " << old_volume
174       << "  dt: " << dt << endl;
175     msg_time = cur_time;
176   }
177 #endif
178
179   double volume = 0;
180   if ((_electrical->getDoubleValue()>8) && _serviceable->getBoolValue())
181   {
182       _time_before_search_sec -= dt;
183       // radio is switched on and OK
184       if (_operable.valid())
185           _operable->setBoolValue(true);
186
187       // Search the tuned frequencies
188       search();
189
190       if (_display)
191       {
192           volume = _volume->getDoubleValue();
193       }
194   }
195   else
196   {
197       // radio is OFF
198       if (_operable.valid())
199           _operable->setBoolValue(false);
200       _time_before_search_sec = 0;
201   }
202
203   if (volume > 0.05)
204   {
205     // Check if we need to update the message
206     // - basically every hour and if the weather changes significantly at the station
207     // If !_prev_display, the radio had been detuned for a while and our
208     // "transmission" variable was lost when we were de-instantiated.
209     int changed = GenTransmission(!_prev_display, _attention);
210
211     // update output property
212     TreeOut(msg_OK);
213
214     if (changed || volume != old_volume) {
215       // audio output enabled
216       Render(transmission, volume, _name, true);
217       old_volume = volume;
218     }
219     _prev_display = _display;
220   } else {
221     // silence
222     NoRender(_name);
223     _prev_display = false;
224   }
225   _attention = false;
226
227   FGATC::update(dt);
228 }
229
230 string uppercase(const string &s) {
231   string rslt(s);
232   for(string::iterator p = rslt.begin(); p != rslt.end(); p++){
233     *p = toupper(*p);
234   }
235   return rslt;
236 }
237
238 // Replace all occurrences of a given word.
239 // Words in the original string must be separated by hyphens (not spaces).
240 // We check for the word as given, and for the all-caps version thereof.
241 string replace_word(const string _orig, const string _www, const string _nnn){
242 // The following are so we can match words at the beginning
243 // and end of the string.
244   string orig = "-" + _orig + "-";
245   string www = "-" + _www + "-";
246   string nnn = "-" + _nnn + "-";
247
248   size_t where(0);
249   for ( ; (where = orig.find(www, where)) != string::npos ; ) {
250     orig.replace(where, www.length(), nnn);
251     where += nnn.length();
252   }
253   
254   www = uppercase(www);
255   for ( ; (where = orig.find(www, where)) != string::npos ; ) {
256     orig.replace(where, www.length(), nnn);
257     where += nnn.length();
258   }
259   where = orig.length();
260   return orig.substr(1, where-2);
261 }
262
263 // Normally the interval is 1 hour, 
264 // but you can shorten it for testing.
265 const int minute(60);           // measured in seconds
266 #ifdef ATIS_TEST
267   const int ATIS_interval(2*minute);
268 #else
269   const int ATIS_interval(60*minute);
270 #endif
271
272 // FIXME:  This is heuristic.  It gets the right answer for
273 // more than 90% of the world's airports, which is a lot
274 // better than nothing ... but it's not 100%.
275 // We know "most" of the world uses millibars,
276 // but the US, Canada and *some* other places use inches of mercury,
277 // but (a) we have not implemented a reliable method of
278 // ascertaining which airports are in the US, let alone
279 // (b) ascertaining which other places use inches.
280 //
281 int Apt_US_CA(const string id) {
282 // Assume all IDs have length 3 or 4.
283 // No counterexamples have been seen.
284   if (id.length() == 4) {
285     if (id.substr(0,1) == "K") return 1;
286     if (id.substr(0,2) == "CY") return 1;
287   }
288   for (string::const_iterator ptr = id.begin(); ptr != id.end();  ptr++) {
289     if (isdigit(*ptr)) return 1;
290   }
291   return 0;
292 }
293
294 // Generate the actual broadcast ATIS transmission.
295 // Regen means regenerate the /current/ transmission.
296 // Special means generate a new transmission, with a new sequence.
297 // Returns 1 if we actually generated something.
298 int FGATIS::GenTransmission(const int regen, const bool special) {
299   using namespace atmodel;
300   using namespace lex;
301
302   string BRK = ".\n";
303   string PAUSE = " / ";
304
305   int interval = _type == ATIS ?
306         ATIS_interval   // ATIS updated hourly
307       : 2*minute;       // AWOS updated more frequently
308
309   FGAirport* apt = FGAirport::findByIdent(ident);
310   int sequence = apt->getDynamics()->updateAtisSequence(interval, special);
311   if (!regen && sequence > LTRS) {
312 //xx      if (msg_OK) cout << "ATIS:  no change: " << sequence << endl;
313 //xx      msg_time = cur_time;
314     return 0;   // no change since last time
315   }
316
317   const int bs(100);
318   char buf[bs];
319   string time_str = fgGetString("sim/time/gmt-string");
320   string hours, mins;
321   string phonetic_seq_string;
322
323   transmission = "";
324
325   int US_CA = Apt_US_CA(ident);
326
327   if (!US_CA) {
328 // UK CAA radiotelephony manual indicates ATIS transmissions start
329 // with "This is ..." 
330     transmission += This_is + " ";
331   } else {
332     // In the US they just start with the airport name.
333   }
334
335   // SG_LOG(SG_ATC, SG_ALERT, "ATIS: facility name: " << name);
336
337 // Note that at this point, multi-word facility names
338 // will sometimes contain hyphens, not spaces.
339   
340   vector<string> name_words;
341   boost::split(name_words, name, boost::is_any_of(" -"));
342
343   for (vector<string>::const_iterator wordp = name_words.begin();
344                 wordp != name_words.end(); wordp++) {
345     string word(*wordp);
346 // Remap some abbreviations that occur in apt.dat, to
347 // make things nicer for the text-to-speech system:
348     for (MSS::const_iterator replace = _remap.begin();
349           replace != _remap.end(); replace++) {
350       // Due to inconsistent capitalisation in the apt.dat file, we need
351       // to do a case-insensitive comparison here.
352       string tmp1 = word, tmp2 = replace->first;
353       boost::algorithm::to_lower(tmp1);
354       boost::algorithm::to_lower(tmp2);
355       if (tmp1 == tmp2) {
356         word = replace->second;
357         break;
358       }
359     }
360     transmission += word + " ";
361   }
362
363   if (_type == ATIS /* as opposed to AWOS */) {
364     transmission += airport_information + " ";
365   } else {
366     transmission += Automated_weather_observation + " ";
367   }
368
369   phonetic_seq_string = GetPhoneticLetter(sequence);  // Add the sequence letter
370   transmission += phonetic_seq_string + BRK;
371
372 // Warning - this is fragile if the time string format changes
373   hours = time_str.substr(0,2).c_str();
374   mins  = time_str.substr(3,2).c_str();
375 // speak each digit separately:
376   transmission += ConvertNumToSpokenDigits(hours + mins);
377   transmission += " " + zulu + " " + weather + BRK;
378
379   transmission += wind + ": ";
380
381   double wind_speed = fgGetDouble("/environment/config/boundary/entry[0]/wind-speed-kt");
382   double wind_dir = fgGetDouble("/environment/config/boundary/entry[0]/wind-from-heading-deg");
383   while (wind_dir <= 0) wind_dir += 360;
384 // The following isn't as bad a kludge as it might seem.
385 // It combines the magvar at the /aircraft/ location with
386 // the wind direction in the environment/config array.
387 // But if the aircraft is close enough to the station to
388 // be receiving the ATIS signal, this should be a good-enough
389 // approximation.  For more-distant aircraft, the wind_dir
390 // shouldn't be corrected anyway.
391 // The less-kludgy approach would be to use the magvar associated
392 // with the station, but that is not tabulated in the stationweather
393 // structure as it stands, and computing it would be expensive.
394 // Also note that as it stands, there is only one environment in
395 // the entire FG universe, so the aircraft environment is the same
396 // as the station environment anyway.
397   wind_dir -= fgGetDouble("/environment/magnetic-variation-deg");       // wind_dir now magnetic
398   if (wind_speed == 0) {
399 // Force west-facing rwys to be used in no-wind situations
400 // which is consistent with Flightgear's initial setup:
401       wind_dir = 270;
402       transmission += " " + light_and_variable;
403   } else {
404       // FIXME: get gust factor in somehow
405       snprintf(buf, bs, "%03.0f", 5*SGMiscd::round(wind_dir/5));
406       transmission += ConvertNumToSpokenDigits(buf);
407
408       snprintf(buf, bs, "%1.0f", wind_speed);
409       transmission += " " + at + " " + ConvertNumToSpokenDigits(buf) + BRK;
410   }
411
412 // Sounds better with a pause in there:
413   transmission += PAUSE;
414
415   int did_some(0);
416   int did_ceiling(0);
417
418   for (int layer = 0; layer <= 4; layer++) {
419     snprintf(buf, bs, "/environment/clouds/layer[%i]/coverage", layer);
420     string coverage = fgGetString(buf);
421     if (coverage == clear) continue;
422     snprintf(buf, bs, "/environment/clouds/layer[%i]/thickness-ft", layer);
423     if (fgGetDouble(buf) == 0) continue;
424     snprintf(buf, bs, "/environment/clouds/layer[%i]/elevation-ft", layer);
425     double ceiling = int(fgGetDouble(buf) - _geod.getElevationFt());
426     if (ceiling > 12000) continue;
427
428 // BEWARE:  At the present time, the environment system has no
429 // way (so far as I know) to represent a "thin broken" or
430 // "thin overcast" layer.  If/when such things are implemented
431 // in the environment system, code will have to be written here
432 // to handle them.
433
434 // First, do the prefix if any:
435     if (coverage == scattered || coverage == few) {
436       if (!did_some) {
437         transmission += "   " + Sky_condition + ": ";
438         did_some++;
439       }
440     } else /* must be a ceiling */  if (!did_ceiling) {
441       transmission += "   " + Ceiling + ": ";
442       did_ceiling++;
443       did_some++;
444     } else {
445       transmission += "   ";    // no prefix required
446     }
447     int cig00  = int(SGMiscd::round(ceiling/100));  // hundreds of feet
448     if (cig00) {
449       int cig000 = cig00/10;
450       cig00 -= cig000*10;       // just the hundreds digit
451       if (cig000) {
452         snprintf(buf, bs, "%i", cig000);
453         transmission += ConvertNumToSpokenDigits(buf);
454         transmission += " " + thousand + " ";
455       }
456       if (cig00) {
457         snprintf(buf, bs, "%i", cig00);
458         transmission += ConvertNumToSpokenDigits(buf);
459         transmission += " " + hundred + " ";
460       }
461     } else {
462       // Should this be "sky obscured?"
463       transmission += " " + zero + " ";     // not "zero hundred"
464     }
465     transmission += coverage + BRK;
466   }
467   if (!did_some) transmission += "   " + Sky + " " + clear + BRK;
468
469   transmission += Temperature + ": ";
470   double Tsl = fgGetDouble("/environment/temperature-sea-level-degc");
471   int temp = int(SGMiscd::round(FGAtmo().fake_T_vs_a_us(_geod.getElevationFt(), Tsl)));
472   if(temp < 0) {
473       transmission += lex::minus + " ";
474   }
475   snprintf(buf, bs, "%i", abs(temp));
476   transmission += ConvertNumToSpokenDigits(buf);
477   if (US_CA) transmission += " " + Celsius;
478   transmission += " " + dewpoint + " ";
479   double dpsl = fgGetDouble("/environment/dewpoint-sea-level-degc");
480   temp = int(SGMiscd::round(FGAtmo().fake_dp_vs_a_us(dpsl, _geod.getElevationFt())));
481   if(temp < 0) {
482       transmission += lex::minus + " ";
483   }
484   snprintf(buf, bs, "%i", abs(temp));
485   transmission += ConvertNumToSpokenDigits(buf);
486   if (US_CA) transmission += " " + Celsius;
487   transmission += BRK;
488
489   transmission += Visibility + ": ";
490   double visibility = fgGetDouble("/environment/config/boundary/entry[0]/visibility-m");
491   visibility /= atmodel::sm;    // convert to statute miles
492   if (visibility < 0.25) {
493     transmission += less_than_one_quarter;
494   } else if (visibility < 0.5) {
495     transmission += one_quarter;
496   } else if (visibility < 0.75) {
497     transmission += one_half;
498   } else if (visibility < 1.0) {
499     transmission += three_quarters;
500   } else if (visibility >= 1.5 && visibility < 2.0) {
501     transmission += one_and_one_half;
502   } else {
503     // integer miles
504     if (visibility > 10) visibility = 10;
505     sprintf(buf, "%i", int(.5 + visibility));
506     transmission += ConvertNumToSpokenDigits(buf);
507   }
508   transmission += BRK;
509
510   double myQNH;
511   double Psl = fgGetDouble("/environment/pressure-sea-level-inhg");
512   {
513     double press, temp;
514     
515     tie(press, temp) = PT_vs_hpt(_geod.getElevationM(), Psl*inHg, Tsl + freezing);
516 #if 0
517     SG_LOG(SG_ATC, SG_ALERT, "Field P: " << press << "  T: " << temp);
518     SG_LOG(SG_ATC, SG_ALERT, "based on elev " << elev 
519                                 << "  Psl: " << Psl
520                                 << "  Tsl: " << Tsl);
521 #endif
522     myQNH = FGAtmo().QNH(_geod.getElevationM(), press);
523   }
524
525 // Convert to millibars for most of the world (not US, not CA)
526   if((!US_CA) && fgGetBool("/sim/atc/use-millibars")) {
527     transmission += QNH + ": ";
528     myQNH /= mbar;
529     snprintf(buf, bs, "%03.0f", myQNH);
530     transmission += ConvertNumToSpokenDigits(buf);
531     // TODO Extend voice samples so we can replace "millibars" with "hectopascal" (new ATIS standard since 2011)
532     if  (myQNH < 1000)
533         transmission += " " + millibars; // "hectopascal" (millibars) spoken for values below 1000 only (to avoid confusion with inHg)
534     transmission += BRK;
535   } else {
536     transmission += Altimeter + ": ";
537     double asetting = myQNH / inHg;         // use inches of mercury
538     asetting *= 100.;                       // shift two decimal places
539     snprintf(buf, bs, "%04.0f", asetting);
540     transmission += ConvertNumToSpokenDigits(buf) + BRK;
541   }
542
543   if (_type == ATIS /* as opposed to AWOS */) {
544     const FGAirport* apt = fgFindAirportID(ident);
545     if (apt) {
546       string rwy_no = apt->getActiveRunwayForUsage()->ident();
547       if(rwy_no != "NN") {
548         transmission += Landing_and_departing_runway + " ";
549         transmission += ConvertRwyNumToSpokenString(rwy_no) + BRK;
550 #ifdef ATIS_TEST
551         if (msg_OK) {
552           msg_time = cur_time;
553           cout << "In atis.cxx, r.rwy_no: " << rwy_no
554              << " wind_dir: " << wind_dir << endl;
555         }
556 #endif
557       }
558     }
559     transmission += On_initial_contact_advise_you_have_information + " ";
560     transmission += phonetic_seq_string;
561     transmission += "... " + BRK;
562     // Pause in between two ATIS messages must be 3-5 seconds
563     transmission += PAUSE + PAUSE + PAUSE + PAUSE;
564   }
565   transmission_readable = transmission;
566 // Take the previous readable string and munge it to
567 // be relatively-more acceptable to the primitive tts system.
568 // Note that : ; and . are among the token-delimiters recognized
569 // by the tts system.
570   for (size_t where;;) {
571     where = transmission.find_first_of(":.");
572     if (where == string::npos) break;
573     transmission.replace(where, 1, PAUSE);
574   }
575   return 1;
576 }
577
578 // Put the transmission into the property tree.
579 // You can see it by pointing a web browser
580 // at the property tree.  The second comm radio is:
581 // http://localhost:5400/instrumentation/comm[1]
582 //
583 // (Also, if in debug mode, dump it to the console.)
584 void FGATIS::TreeOut(int msg_OK)
585 {
586     _atis->setStringValue("<pre>\n" + transmission_readable + "</pre>\n");
587     SG_LOG(SG_ATC, SG_DEBUG, "**** ATIS active on: " << _name <<
588            "transmission: " << transmission_readable);
589 }
590
591
592
593 class RangeFilter : public CommStation::Filter
594 {
595 public:
596     RangeFilter( const SGGeod & pos ) :
597       CommStation::Filter(),
598       _cart(SGVec3d::fromGeod(pos)),
599       _pos(pos)
600     {
601     }
602
603     virtual bool pass(FGPositioned* aPos) const
604     {
605         flightgear::CommStation * stn = dynamic_cast<flightgear::CommStation*>(aPos);
606         if( NULL == stn )
607             return false;
608
609         // do the range check in cartesian space, since the distances are potentially
610         // large enough that the geodetic functions become unstable
611         // (eg, station on opposite side of the planet)
612         double rangeM = SGMiscd::max( stn->rangeNm(), 10.0 ) * SG_NM_TO_METER;
613         double d2 = distSqr( aPos->cart(), _cart);
614
615         return d2 <= (rangeM * rangeM);
616     }
617
618     virtual CommStation::Type minType() const
619     {
620       return CommStation::FREQ_ATIS;
621     }
622
623     virtual CommStation::Type maxType() const
624     {
625       return CommStation::FREQ_AWOS;
626     }
627
628 private:
629     SGVec3d _cart;
630     SGGeod _pos;
631 };
632
633 // Search for ATC stations by frequency
634 void FGATIS::search(void)
635 {
636     double frequency = _freq->getDoubleValue();
637
638     // Note:  122.375 must be rounded DOWN to 122370
639     // in order to be consistent with apt.dat et cetera.
640     int freqKhz = 10 * static_cast<int>(frequency * 100 + 0.25);
641
642     // throttle frequency searches
643     if ((freqKhz == _last_frequency)&&(_time_before_search_sec > 0))
644         return;
645
646     _last_frequency = freqKhz;
647     _time_before_search_sec = 4.0;
648
649     // Position of the Users Aircraft
650     SGGeod aircraftPos = SGGeod::fromDegFt(_lon_node->getDoubleValue(),
651                                            _lat_node->getDoubleValue(),
652                                            _elev_node->getDoubleValue());
653
654     RangeFilter rangeFilter(aircraftPos );
655     CommStation* sta = CommStation::findByFreq(freqKhz, aircraftPos, &rangeFilter );
656     SetStation(sta);
657     if (sta && sta->airport())
658     {
659         SG_LOG(SG_ATC, SG_DEBUG, "FGATIS " << _name << ": " << sta->airport()->name());
660     }
661     else
662     {
663         SG_LOG(SG_ATC, SG_DEBUG, "FGATIS " << _name << ": no station.");
664     }
665 }