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) :
81 _time_before_search_sec(0),
84 fgTie("/environment/attention", this, (int_getter)0, &FGATIS::attend);
86 _root = fgGetNode("/instrumentation", true)->getNode(_name, num, true);
87 _volume = _root->getNode("volume",true);
88 _serviceable = _root->getNode("serviceable",true);
92 // only drive "operable" for non-nav instruments (nav radio drives this separately)
93 _operable = _root->getNode("operable",true);
94 _operable->setBoolValue(false);
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);
102 _lon_node = fgGetNode("/position/longitude-deg", true);
103 _lat_node = fgGetNode("/position/latitude-deg", true);
104 _elev_node = fgGetNode("/position/altitude-ft", true);
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);
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.
117 // Load the remap list from the .hxx file:
120 # define REMAP(from,to) _remap[#from] = to;
121 # include "atis_remap.hxx"
126 SG_LOG(SG_ATC, SG_ALERT, "ATIS initialized");
131 // http://localhost:5400/environment/attention?value=1&submit=update
134 fgUntie("/environment/attention");
137 FGATCVoice* FGATIS::GetVoicePointer()
139 FGATISMgr* pAtisMgr = globals->get_ATIS_mgr();
142 SG_LOG(SG_ATC, SG_ALERT, "ERROR! No ATIS manager! Oops...");
146 return pAtisMgr->GetVoicePointer(ATIS);
149 void FGATIS::init() {
150 // Nothing to see here. Move along.
154 FGATIS::attend (int attn)
158 int flag = fgGetInt("/sim/logging/atmo");
160 FGAltimeter().check_model();
161 FGAltimeter().dump_stack();
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);
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;
183 if ((_electrical->getDoubleValue()>8) && _serviceable->getBoolValue())
185 _time_before_search_sec -= dt;
186 // radio is switched on and OK
187 if (_operable.valid())
188 _operable->setBoolValue(true);
190 // Search the tuned frequencies
195 volume = _volume->getDoubleValue();
201 if (_operable.valid())
202 _operable->setBoolValue(false);
203 _time_before_search_sec = 0;
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);
214 // update output property
217 if (changed || volume != old_volume) {
218 // audio output enabled
219 Render(transmission, volume, _name, true);
222 _prev_display = _display;
226 _prev_display = false;
231 string uppercase(const string &s) {
233 for(string::iterator p = rslt.begin(); p != rslt.end(); p++){
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 + "-";
250 for ( ; (where = orig.find(www, where)) != string::npos ; ) {
251 orig.replace(where, www.length(), nnn);
252 where += nnn.length();
255 www = uppercase(www);
256 for ( ; (where = orig.find(www, where)) != string::npos ; ) {
257 orig.replace(where, www.length(), nnn);
258 where += nnn.length();
260 where = orig.length();
261 return orig.substr(1, where-2);
264 // Normally the interval is 1 hour,
265 // but you can shorten it for testing.
266 const int minute(60); // measured in seconds
268 const int ATIS_interval(2*minute);
270 const int ATIS_interval(60*minute);
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.
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;
289 for (string::const_iterator ptr = id.begin(); ptr != id.end(); ptr++) {
290 if (isdigit(*ptr)) return 1;
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;
304 string PAUSE = " / ";
306 int interval = _type == ATIS ?
307 ATIS_interval // ATIS updated hourly
308 : 2*minute; // AWOS updated more frequently
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
320 string time_str = fgGetString("sim/time/gmt-string");
322 string phonetic_seq_string;
326 int US_CA = Apt_US_CA(ident);
329 // UK CAA radiotelephony manual indicates ATIS transmissions start
330 // with "This is ..."
331 transmission += This_is + " ";
333 // In the US they just start with the airport name.
336 // SG_LOG(SG_ATC, SG_ALERT, "ATIS: facility name: " << name);
338 // Note that at this point, multi-word facility names
339 // will sometimes contain hyphens, not spaces.
341 vector<string> name_words;
342 boost::split(name_words, name, boost::is_any_of(" -"));
344 for (vector<string>::const_iterator wordp = name_words.begin();
345 wordp != name_words.end(); 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);
357 word = replace->second;
361 transmission += word + " ";
364 if (_type == ATIS /* as opposed to AWOS */) {
365 transmission += airport_information + " ";
367 transmission += Automated_weather_observation + " ";
370 phonetic_seq_string = GetPhoneticLetter(sequence); // Add the sequence letter
371 transmission += phonetic_seq_string + BRK;
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;
380 transmission += wind + ": ";
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:
403 transmission += " " + light_and_variable;
405 // FIXME: get gust factor in somehow
406 snprintf(buf, bs, "%03.0f", 5*SGMiscd::round(wind_dir/5));
407 transmission += ConvertNumToSpokenDigits(buf);
409 snprintf(buf, bs, "%1.0f", wind_speed);
410 transmission += " " + at + " " + ConvertNumToSpokenDigits(buf) + BRK;
413 // Sounds better with a pause in there:
414 transmission += PAUSE;
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;
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
435 // First, do the prefix if any:
436 if (coverage == scattered || coverage == few) {
438 transmission += " " + Sky_condition + ": ";
441 } else /* must be a ceiling */ if (!did_ceiling) {
442 transmission += " " + Ceiling + ": ";
446 transmission += " "; // no prefix required
448 int cig00 = int(SGMiscd::round(ceiling/100)); // hundreds of feet
450 int cig000 = cig00/10;
451 cig00 -= cig000*10; // just the hundreds digit
453 snprintf(buf, bs, "%i", cig000);
454 transmission += ConvertNumToSpokenDigits(buf);
455 transmission += " " + thousand + " ";
458 snprintf(buf, bs, "%i", cig00);
459 transmission += ConvertNumToSpokenDigits(buf);
460 transmission += " " + hundred + " ";
463 // Should this be "sky obscured?"
464 transmission += " " + zero + " "; // not "zero hundred"
466 transmission += coverage + BRK;
468 if (!did_some) transmission += " " + Sky + " " + clear + BRK;
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)));
474 transmission += lex::minus + " ";
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())));
483 transmission += lex::minus + " ";
485 snprintf(buf, bs, "%i", abs(temp));
486 transmission += ConvertNumToSpokenDigits(buf);
487 if (US_CA) transmission += " " + Celsius;
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;
505 if (visibility > 10) visibility = 10;
506 sprintf(buf, "%i", int(.5 + visibility));
507 transmission += ConvertNumToSpokenDigits(buf);
512 double Psl = fgGetDouble("/environment/pressure-sea-level-inhg");
516 tie(press, temp) = PT_vs_hpt(_geod.getElevationM(), Psl*inHg, Tsl + freezing);
518 SG_LOG(SG_ATC, SG_ALERT, "Field P: " << press << " T: " << temp);
519 SG_LOG(SG_ATC, SG_ALERT, "based on elev " << elev
523 myQNH = FGAtmo().QNH(_geod.getElevationM(), press);
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 + ": ";
530 if (myQNH > 1000) myQNH -= 1000; // drop high digit
531 snprintf(buf, bs, "%03.0f", myQNH);
532 transmission += ConvertNumToSpokenDigits(buf) + " " + millibars + BRK;
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;
541 if (_type == ATIS /* as opposed to AWOS */) {
542 const FGAirport* apt = fgFindAirportID(ident);
544 string rwy_no = apt->getActiveRunwayForUsage()->ident();
546 transmission += Landing_and_departing_runway + " ";
547 transmission += ConvertRwyNumToSpokenString(rwy_no) + BRK;
551 cout << "In atis.cxx, r.rwy_no: " << rwy_no
552 << " wind_dir: " << wind_dir << endl;
557 transmission += On_initial_contact_advise_you_have_information + " ";
558 transmission += phonetic_seq_string;
559 transmission += "... " + BRK + PAUSE + PAUSE;
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);
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]
579 // (Also, if in debug mode, dump it to the console.)
580 void FGATIS::TreeOut(int msg_OK)
582 _atis->setStringValue("<pre>\n" + transmission_readable + "</pre>\n");
583 SG_LOG(SG_ATC, SG_DEBUG, "**** ATIS active on: " << _name <<
584 "transmission: " << transmission_readable);
589 class RangeFilter : public CommStation::Filter
592 RangeFilter( const SGGeod & pos ) :
593 CommStation::Filter(),
594 _cart(SGVec3d::fromGeod(pos)),
599 virtual bool pass(FGPositioned* aPos) const
601 flightgear::CommStation * stn = dynamic_cast<flightgear::CommStation*>(aPos);
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);
611 return d2 <= (rangeM * rangeM);
618 // Search for ATC stations by frequency
619 void FGATIS::search(void)
621 double frequency = _freq->getDoubleValue();
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);
627 // throttle frequency searches
628 if ((freqKhz == _last_frequency)&&(_time_before_search_sec > 0))
631 _last_frequency = freqKhz;
632 _time_before_search_sec = 4.0;
634 // Position of the Users Aircraft
635 SGGeod aircraftPos = SGGeod::fromDegFt(_lon_node->getDoubleValue(),
636 _lat_node->getDoubleValue(),
637 _elev_node->getDoubleValue());
639 RangeFilter rangeFilter(aircraftPos );
640 CommStation* sta = CommStation::findByFreq(freqKhz, aircraftPos, &rangeFilter );
642 if (sta && sta->airport())
644 SG_LOG(SG_ATC, SG_DEBUG, "FGATIS " << _name << ": " << sta->airport()->name());
648 SG_LOG(SG_ATC, SG_DEBUG, "FGATIS " << _name << ": no station.");