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