1 // atis.cxx - routines to generate the ATIS info string
2 // This is the implementation of the FGATIS class
4 // Written by David Luff, started October 2001.
6 // Copyright (C) 2001 David C Luff - david.luff@nottingham.ac.uk
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.
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.
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.
23 ///// TODO: _Cumulative_ sky coverage.
24 ///// TODO: wind _gust_
25 ///// TODO: more-sensible encoding of voice samples
26 ///// u-law? outright synthesis?
34 #include "atis_lexicon.hxx"
36 #include <simgear/compiler.h>
37 #include <simgear/math/sg_random.h>
38 #include <simgear/misc/sg_path.hxx>
40 #include <stdlib.h> // atoi()
41 #include <stdio.h> // sprintf
45 #include <boost/tuple/tuple.hpp>
46 #include <boost/algorithm/string.hpp>
47 #include <boost/algorithm/string/case_conv.hpp>
49 #include <Environment/environment_mgr.hxx>
50 #include <Environment/environment.hxx>
51 #include <Environment/atmosphere.hxx>
53 #include <Main/fg_props.hxx>
54 #include <Main/globals.hxx>
55 #include <Airports/runways.hxx>
56 #include <Airports/dynamics.hxx>
58 #include <ATC/CommStation.hxx>
60 #include "ATCutils.hxx"
61 #include "ATISmgr.hxx"
69 using flightgear::CommStation;
71 FGATIS::FGATIS(const std::string& name, int num) :
74 _cb_attention(this, &FGATIS::attend, fgGetNode("/environment/attention", true)),
84 _time_before_search_sec(0),
87 _root = fgGetNode("/instrumentation", true)->getNode(_name, num, true);
88 _volume = _root->getNode("volume",true);
89 _serviceable = _root->getNode("serviceable",true);
93 // only drive "operable" for non-nav instruments (nav radio drives this separately)
94 _operable = _root->getNode("operable",true);
95 _operable->setBoolValue(false);
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);
103 _lon_node = fgGetNode("/position/longitude-deg", true);
104 _lat_node = fgGetNode("/position/latitude-deg", true);
105 _elev_node = fgGetNode("/position/altitude-ft", true);
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);
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.
118 // Load the remap list from the .hxx file:
121 # define REMAP(from,to) _remap[#from] = to;
122 # include "atis_remap.hxx"
127 SG_LOG(SG_ATC, SG_ALERT, "ATIS initialized");
132 // http://localhost:5400/environment/attention?value=1&submit=update
134 FGATCVoice* FGATIS::GetVoicePointer()
136 FGATISMgr* pAtisMgr = globals->get_ATIS_mgr();
139 SG_LOG(SG_ATC, SG_ALERT, "ERROR! No ATIS manager! Oops...");
143 return pAtisMgr->GetVoicePointer(ATIS);
146 void FGATIS::init() {
147 // Nothing to see here. Move along.
151 FGATIS::attend(SGPropertyNode* node)
153 _attention = node->getBoolValue();
155 int flag = fgGetInt("/sim/logging/atmo");
157 FGAltimeter().check_model();
158 FGAltimeter().dump_stack();
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);
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;
180 if ((_electrical->getDoubleValue()>8) && _serviceable->getBoolValue())
182 _time_before_search_sec -= dt;
183 // radio is switched on and OK
184 if (_operable.valid())
185 _operable->setBoolValue(true);
187 // Search the tuned frequencies
192 volume = _volume->getDoubleValue();
198 if (_operable.valid())
199 _operable->setBoolValue(false);
200 _time_before_search_sec = 0;
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);
211 // update output property
214 if (changed || volume != old_volume) {
215 // audio output enabled
216 Render(transmission, volume, _name, true);
219 _prev_display = _display;
223 _prev_display = false;
230 string uppercase(const string &s) {
232 for(string::iterator p = rslt.begin(); p != rslt.end(); p++){
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 + "-";
249 for ( ; (where = orig.find(www, where)) != string::npos ; ) {
250 orig.replace(where, www.length(), nnn);
251 where += nnn.length();
254 www = uppercase(www);
255 for ( ; (where = orig.find(www, where)) != string::npos ; ) {
256 orig.replace(where, www.length(), nnn);
257 where += nnn.length();
259 where = orig.length();
260 return orig.substr(1, where-2);
263 // Normally the interval is 1 hour,
264 // but you can shorten it for testing.
265 const int minute(60); // measured in seconds
267 const int ATIS_interval(2*minute);
269 const int ATIS_interval(60*minute);
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.
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;
288 for (string::const_iterator ptr = id.begin(); ptr != id.end(); ptr++) {
289 if (isdigit(*ptr)) return 1;
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;
303 string PAUSE = " / ";
305 int interval = _type == ATIS ?
306 ATIS_interval // ATIS updated hourly
307 : 2*minute; // AWOS updated more frequently
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
319 string time_str = fgGetString("sim/time/gmt-string");
321 string phonetic_seq_string;
325 int US_CA = Apt_US_CA(ident);
328 // UK CAA radiotelephony manual indicates ATIS transmissions start
329 // with "This is ..."
330 transmission += This_is + " ";
332 // In the US they just start with the airport name.
335 // SG_LOG(SG_ATC, SG_ALERT, "ATIS: facility name: " << name);
337 // Note that at this point, multi-word facility names
338 // will sometimes contain hyphens, not spaces.
340 vector<string> name_words;
341 boost::split(name_words, name, boost::is_any_of(" -"));
343 for (vector<string>::const_iterator wordp = name_words.begin();
344 wordp != name_words.end(); 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);
356 word = replace->second;
360 transmission += word + " ";
363 if (_type == ATIS /* as opposed to AWOS */) {
364 transmission += airport_information + " ";
366 transmission += Automated_weather_observation + " ";
369 phonetic_seq_string = GetPhoneticLetter(sequence); // Add the sequence letter
370 transmission += phonetic_seq_string + BRK;
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;
379 transmission += wind + ": ";
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:
402 transmission += " " + light_and_variable;
404 // FIXME: get gust factor in somehow
405 snprintf(buf, bs, "%03.0f", 5*SGMiscd::round(wind_dir/5));
406 transmission += ConvertNumToSpokenDigits(buf);
408 snprintf(buf, bs, "%1.0f", wind_speed);
409 transmission += " " + at + " " + ConvertNumToSpokenDigits(buf) + BRK;
412 // Sounds better with a pause in there:
413 transmission += PAUSE;
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;
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
434 // First, do the prefix if any:
435 if (coverage == scattered || coverage == few) {
437 transmission += " " + Sky_condition + ": ";
440 } else /* must be a ceiling */ if (!did_ceiling) {
441 transmission += " " + Ceiling + ": ";
445 transmission += " "; // no prefix required
447 int cig00 = int(SGMiscd::round(ceiling/100)); // hundreds of feet
449 int cig000 = cig00/10;
450 cig00 -= cig000*10; // just the hundreds digit
452 snprintf(buf, bs, "%i", cig000);
453 transmission += ConvertNumToSpokenDigits(buf);
454 transmission += " " + thousand + " ";
457 snprintf(buf, bs, "%i", cig00);
458 transmission += ConvertNumToSpokenDigits(buf);
459 transmission += " " + hundred + " ";
462 // Should this be "sky obscured?"
463 transmission += " " + zero + " "; // not "zero hundred"
465 transmission += coverage + BRK;
467 if (!did_some) transmission += " " + Sky + " " + clear + BRK;
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)));
473 transmission += lex::minus + " ";
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())));
482 transmission += lex::minus + " ";
484 snprintf(buf, bs, "%i", abs(temp));
485 transmission += ConvertNumToSpokenDigits(buf);
486 if (US_CA) transmission += " " + Celsius;
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;
504 if (visibility > 10) visibility = 10;
505 sprintf(buf, "%i", int(.5 + visibility));
506 transmission += ConvertNumToSpokenDigits(buf);
511 double Psl = fgGetDouble("/environment/pressure-sea-level-inhg");
515 tie(press, temp) = PT_vs_hpt(_geod.getElevationM(), Psl*inHg, Tsl + freezing);
517 SG_LOG(SG_ATC, SG_ALERT, "Field P: " << press << " T: " << temp);
518 SG_LOG(SG_ATC, SG_ALERT, "based on elev " << elev
522 myQNH = FGAtmo().QNH(_geod.getElevationM(), press);
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 + ": ";
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)
533 transmission += " " + millibars; // "hectopascal" (millibars) spoken for values below 1000 only (to avoid confusion with inHg)
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;
543 if (_type == ATIS /* as opposed to AWOS */) {
544 const FGAirport* apt = fgFindAirportID(ident);
546 string rwy_no = apt->getActiveRunwayForUsage()->ident();
548 transmission += Landing_and_departing_runway + " ";
549 transmission += ConvertRwyNumToSpokenString(rwy_no) + BRK;
553 cout << "In atis.cxx, r.rwy_no: " << rwy_no
554 << " wind_dir: " << wind_dir << endl;
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;
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);
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]
583 // (Also, if in debug mode, dump it to the console.)
584 void FGATIS::TreeOut(int msg_OK)
586 _atis->setStringValue("<pre>\n" + transmission_readable + "</pre>\n");
587 SG_LOG(SG_ATC, SG_DEBUG, "**** ATIS active on: " << _name <<
588 "transmission: " << transmission_readable);
593 class RangeFilter : public CommStation::Filter
596 RangeFilter( const SGGeod & pos ) :
597 CommStation::Filter(),
598 _cart(SGVec3d::fromGeod(pos)),
603 virtual bool pass(FGPositioned* aPos) const
605 flightgear::CommStation * stn = dynamic_cast<flightgear::CommStation*>(aPos);
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);
615 return d2 <= (rangeM * rangeM);
618 virtual CommStation::Type minType() const
620 return CommStation::FREQ_ATIS;
623 virtual CommStation::Type maxType() const
625 return CommStation::FREQ_AWOS;
633 // Search for ATC stations by frequency
634 void FGATIS::search(void)
636 double frequency = _freq->getDoubleValue();
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);
642 // throttle frequency searches
643 if ((freqKhz == _last_frequency)&&(_time_before_search_sec > 0))
646 _last_frequency = freqKhz;
647 _time_before_search_sec = 4.0;
649 // Position of the Users Aircraft
650 SGGeod aircraftPos = SGGeod::fromDegFt(_lon_node->getDoubleValue(),
651 _lat_node->getDoubleValue(),
652 _elev_node->getDoubleValue());
654 RangeFilter rangeFilter(aircraftPos );
655 CommStation* sta = CommStation::findByFreq(freqKhz, aircraftPos, &rangeFilter );
657 if (sta && sta->airport())
659 SG_LOG(SG_ATC, SG_DEBUG, "FGATIS " << _name << ": " << sta->airport()->name());
663 SG_LOG(SG_ATC, SG_DEBUG, "FGATIS " << _name << ": no station.");