1 // environment_ctrl.cxx -- manager for natural environment information.
3 // Written by David Megginson, started February 2002.
5 // Copyright (C) 2002 David Megginson - david@megginson.com
7 // This program is free software; you can redistribute it and/or
8 // modify it under the terms of the GNU General Public License as
9 // published by the Free Software Foundation; either version 2 of the
10 // License, or (at your option) any later version.
12 // This program is distributed in the hope that it will be useful, but
13 // WITHOUT ANY WARRANTY; without even the implied warranty of
14 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 // General Public License for more details.
17 // You should have received a copy of the GNU General Public License
18 // along with this program; if not, write to the Free Software
19 // Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
23 #include <simgear/debug/logstream.hxx>
28 #include <simgear/structure/commands.hxx>
29 #include <simgear/structure/exception.hxx>
31 #include <Airports/simple.hxx>
32 #include <Main/fg_props.hxx>
33 #include <Main/util.hxx>
35 #include "environment_mgr.hxx"
36 #include "environment_ctrl.hxx"
42 ////////////////////////////////////////////////////////////////////////
43 // Implementation of FGEnvironmentCtrl abstract base class.
44 ////////////////////////////////////////////////////////////////////////
46 FGEnvironmentCtrl::FGEnvironmentCtrl ()
54 FGEnvironmentCtrl::~FGEnvironmentCtrl ()
59 FGEnvironmentCtrl::setEnvironment (FGEnvironment * environment)
61 _environment = environment;
65 FGEnvironmentCtrl::setLongitudeDeg (double lon_deg)
71 FGEnvironmentCtrl::setLatitudeDeg (double lat_deg)
77 FGEnvironmentCtrl::setElevationFt (double elev_ft)
83 FGEnvironmentCtrl::setPosition (double lon_deg, double lat_deg, double elev_ft)
92 ////////////////////////////////////////////////////////////////////////
93 // Implementation of FGUserDefEnvironmentCtrl.
94 ////////////////////////////////////////////////////////////////////////
96 FGUserDefEnvironmentCtrl::FGUserDefEnvironmentCtrl ()
97 : _base_wind_speed_node(0),
98 _gust_wind_speed_node(0),
99 _current_wind_speed_kt(0),
100 _delta_wind_speed_kt(0)
104 FGUserDefEnvironmentCtrl::~FGUserDefEnvironmentCtrl ()
109 FGUserDefEnvironmentCtrl::init ()
111 // Fill in some defaults.
112 if (!fgHasNode("/environment/params/base-wind-speed-kt"))
113 fgSetDouble("/environment/params/base-wind-speed-kt",
114 fgGetDouble("/environment/wind-speed-kt"));
115 if (!fgHasNode("/environment/params/gust-wind-speed-kt"))
116 fgSetDouble("/environment/params/gust-wind-speed-kt",
117 fgGetDouble("/environment/params/base-wind-speed-kt"));
119 _base_wind_speed_node =
120 fgGetNode("/environment/params/base-wind-speed-kt", true);
121 _gust_wind_speed_node =
122 fgGetNode("/environment/params/gust-wind-speed-kt", true);
124 _current_wind_speed_kt = _base_wind_speed_node->getDoubleValue();
125 _delta_wind_speed_kt = 0.1;
129 FGUserDefEnvironmentCtrl::update (double dt)
131 double base_wind_speed = _base_wind_speed_node->getDoubleValue();
132 double gust_wind_speed = _gust_wind_speed_node->getDoubleValue();
134 if (gust_wind_speed < base_wind_speed) {
135 gust_wind_speed = base_wind_speed;
136 _gust_wind_speed_node->setDoubleValue(gust_wind_speed);
139 if (base_wind_speed == gust_wind_speed) {
140 _current_wind_speed_kt = base_wind_speed;
142 int rn = rand() % 128;
143 int sign = (_delta_wind_speed_kt < 0 ? -1 : 1);
144 double gust = _current_wind_speed_kt - base_wind_speed;
145 double incr = gust / 50;
148 _delta_wind_speed_kt = - _delta_wind_speed_kt;
150 _delta_wind_speed_kt -= incr * sign;
152 _delta_wind_speed_kt += incr * sign;
154 _current_wind_speed_kt += _delta_wind_speed_kt;
156 if (_current_wind_speed_kt < base_wind_speed) {
157 _current_wind_speed_kt = base_wind_speed;
158 _delta_wind_speed_kt = 0.01;
159 } else if (_current_wind_speed_kt > gust_wind_speed) {
160 _current_wind_speed_kt = gust_wind_speed;
161 _delta_wind_speed_kt = -0.01;
165 if (_environment != 0)
166 _environment->set_wind_speed_kt(_current_wind_speed_kt);
171 ////////////////////////////////////////////////////////////////////////
172 // Implementation of FGInterpolateEnvironmentCtrl.
173 ////////////////////////////////////////////////////////////////////////
175 FGInterpolateEnvironmentCtrl::FGInterpolateEnvironmentCtrl ()
179 FGInterpolateEnvironmentCtrl::~FGInterpolateEnvironmentCtrl ()
182 for (i = 0; i < _boundary_table.size(); i++)
183 delete _boundary_table[i];
184 for (i = 0; i < _aloft_table.size(); i++)
185 delete _aloft_table[i];
191 FGInterpolateEnvironmentCtrl::init ()
193 read_table(fgGetNode("/environment/config/boundary", true),
195 read_table(fgGetNode("/environment/config/aloft", true),
200 FGInterpolateEnvironmentCtrl::reinit ()
203 for (i = 0; i < _boundary_table.size(); i++)
204 delete _boundary_table[i];
205 for (i = 0; i < _aloft_table.size(); i++)
206 delete _aloft_table[i];
207 _boundary_table.clear();
208 _aloft_table.clear();
213 FGInterpolateEnvironmentCtrl::read_table (const SGPropertyNode * node,
214 vector<bucket *> &table)
216 for (int i = 0; i < node->nChildren(); i++) {
217 const SGPropertyNode * child = node->getChild(i);
218 if ( strcmp(child->getName(), "entry") == 0
219 && child->getStringValue("elevation-ft", "")[0] != '\0'
220 && ( child->getDoubleValue("elevation-ft") > 0.1 || i == 0 ) )
222 bucket * b = new bucket;
224 b->environment.copy(table[i-1]->environment);
225 b->environment.read(child);
226 b->altitude_ft = b->environment.get_elevation_ft();
230 sort(table.begin(), table.end());
234 FGInterpolateEnvironmentCtrl::update (double delta_time_sec)
237 double altitude_ft = fgGetDouble("/position/altitude-ft");
238 double altitude_agl_ft = fgGetDouble("/position/altitude-agl-ft");
239 double boundary_transition =
240 fgGetDouble("/environment/config/boundary-transition-ft", 500);
242 // double ground_elevation_ft = altitude_ft - altitude_agl_ft;
244 int length = _boundary_table.size();
248 double boundary_limit = _boundary_table[length-1]->altitude_ft;
249 if (boundary_limit >= altitude_agl_ft) {
250 do_interpolate(_boundary_table, altitude_agl_ft,
253 } else if ((boundary_limit + boundary_transition) >= altitude_agl_ft) {
255 do_interpolate(_boundary_table, altitude_agl_ft, &env1);
256 do_interpolate(_aloft_table, altitude_ft, &env2);
258 (altitude_agl_ft - boundary_limit) / boundary_transition;
259 interpolate(&env1, &env2, fraction, _environment);
265 do_interpolate(_aloft_table, altitude_ft, _environment);
269 FGInterpolateEnvironmentCtrl::do_interpolate (vector<bucket *> &table,
271 FGEnvironment * environment)
273 int length = table.size();
277 // Boundary conditions
278 if ((length == 1) || (table[0]->altitude_ft >= altitude_ft)) {
279 environment->copy(table[0]->environment);
281 } else if (table[length-1]->altitude_ft <= altitude_ft) {
282 environment->copy(table[length-1]->environment);
286 // Search the interpolation table
287 for (int i = 0; i < length - 1; i++) {
288 if ((i == length - 1) || (table[i]->altitude_ft <= altitude_ft)) {
289 FGEnvironment * env1 = &(table[i]->environment);
290 FGEnvironment * env2 = &(table[i+1]->environment);
292 if (table[i]->altitude_ft == table[i+1]->altitude_ft)
296 ((altitude_ft - table[i]->altitude_ft) /
297 (table[i+1]->altitude_ft - table[i]->altitude_ft));
298 interpolate(env1, env2, fraction, environment);
306 FGInterpolateEnvironmentCtrl::bucket::operator< (const bucket &b) const
308 return (altitude_ft < b.altitude_ft);
313 ////////////////////////////////////////////////////////////////////////
314 // Implementation of FGMetarEnvironmentCtrl.
315 ////////////////////////////////////////////////////////////////////////
317 FGMetarEnvironmentCtrl::FGMetarEnvironmentCtrl ()
318 : env( new FGInterpolateEnvironmentCtrl ),
320 search_interval_sec( 60.0 ), // 1 minute
321 same_station_interval_sec( 900.0 ), // 15 minutes
322 search_elapsed( 9999.0 ),
323 fetch_elapsed( 9999.0 ),
324 proxy_host( fgGetNode("/sim/presets/proxy/host", true) ),
325 proxy_port( fgGetNode("/sim/presets/proxy/port", true) ),
326 proxy_auth( fgGetNode("/sim/presets/proxy/authentication", true) ),
327 metar_max_age( fgGetNode("/environment/params/metar-max-age-min", true) ),
333 #if defined(ENABLE_THREADS)
334 thread = new MetarThread(this);
336 #endif // ENABLE_THREADS
339 FGMetarEnvironmentCtrl::~FGMetarEnvironmentCtrl ()
341 #if defined(ENABLE_THREADS)
344 #endif // ENABLE_THREADS
351 // use a "command" to set station temp at station elevation
352 static void set_temp_at_altitude( float temp_degc, float altitude_ft ) {
354 SGPropertyNode *node = args.getNode("temp-degc", 0, true);
355 node->setFloatValue( temp_degc );
356 node = args.getNode("altitude-ft", 0, true);
357 node->setFloatValue( altitude_ft );
358 globals->get_commands()->execute("set-outside-air-temp-degc", &args);
362 static void set_dewpoint_at_altitude( float dewpoint_degc, float altitude_ft ) {
364 SGPropertyNode *node = args.getNode("dewpoint-degc", 0, true);
365 node->setFloatValue( dewpoint_degc );
366 node = args.getNode("altitude-ft", 0, true);
367 node->setFloatValue( altitude_ft );
368 globals->get_commands()->execute("set-dewpoint-temp-degc", &args);
373 FGMetarEnvironmentCtrl::update_env_config ()
375 fgSetupWind( fgGetDouble("/environment/metar/base-wind-range-from"),
376 fgGetDouble("/environment/metar/base-wind-range-to"),
377 fgGetDouble("/environment/metar/base-wind-speed-kt"),
378 fgGetDouble("/environment/metar/gust-wind-speed-kt") );
380 fgDefaultWeatherValue( "visibility-m",
381 fgGetDouble("/environment/metar/min-visibility-m") );
382 set_temp_at_altitude( fgGetDouble("/environment/metar/temperature-degc"),
383 station_elevation_ft );
384 set_dewpoint_at_altitude( fgGetDouble("/environment/metar/dewpoint-degc"),
385 station_elevation_ft );
386 fgDefaultWeatherValue( "pressure-sea-level-inhg",
387 fgGetDouble("/environment/metar/pressure-inhg") );
391 FGMetarEnvironmentCtrl::init ()
393 const SGPropertyNode *longitude
394 = fgGetNode( "/position/longitude-deg", true );
395 const SGPropertyNode *latitude
396 = fgGetNode( "/position/latitude-deg", true );
398 bool found_metar = false;
399 long max_age = metar_max_age->getLongValue();
400 // Don't check max age during init so that we don't loop over a lot
401 // of airports metar if there is a problem.
402 // The update() calls will find a correct metar if things went wrong here
403 metar_max_age->setLongValue(0);
405 while ( !found_metar && (_error_count < 3) ) {
406 const FGAirport* a = globals->get_airports()
407 ->search( longitude->getDoubleValue(),
408 latitude->getDoubleValue(),
411 FGMetarResult result = fetch_data( a->getId() );
412 if ( result.m != NULL ) {
413 SG_LOG( SG_GENERAL, SG_INFO, "closest station w/ metar = "
417 search_elapsed = 0.0;
419 update_metar_properties( result.m );
424 // mark as no metar so it doesn't show up in subsequent
426 SG_LOG( SG_GENERAL, SG_INFO, "no metar at metar = "
428 globals->get_airports()->no_metar( a->getId() );
432 metar_max_age->setLongValue(max_age);
436 FGMetarEnvironmentCtrl::reinit ()
449 FGMetarEnvironmentCtrl::update(double delta_time_sec)
452 _dt += delta_time_sec;
453 if (_error_count >= 3)
456 FGMetarResult result;
458 static const SGPropertyNode *longitude
459 = fgGetNode( "/position/longitude-deg", true );
460 static const SGPropertyNode *latitude
461 = fgGetNode( "/position/latitude-deg", true );
462 search_elapsed += delta_time_sec;
463 fetch_elapsed += delta_time_sec;
465 // if time for a new search request, push it onto the request
467 if ( search_elapsed > search_interval_sec ) {
468 const FGAirport* a = globals->get_airports()
469 ->search( longitude->getDoubleValue(),
470 latitude->getDoubleValue(),
473 if ( last_apt.getId() != a->getId()
474 || fetch_elapsed > same_station_interval_sec )
476 SG_LOG( SG_GENERAL, SG_INFO, "closest station w/ metar = "
478 request_queue.push( a->getId() );
481 search_elapsed = 0.0;
484 search_elapsed = 0.0;
485 SG_LOG( SG_GENERAL, SG_INFO, "same station, waiting = "
486 << same_station_interval_sec - fetch_elapsed );
489 SG_LOG( SG_GENERAL, SG_WARN,
490 "Unable to find any airports with metar" );
494 #if !defined(ENABLE_THREADS)
495 // No loader thread running so manually fetch the data
497 while ( !request_queue.empty() ) {
498 id = request_queue.front();
503 SG_LOG( SG_GENERAL, SG_INFO, "inline fetching = " << id );
504 result = fetch_data( id );
505 result_queue.push( result );
507 #endif // ENABLE_THREADS
509 // process any results from the loader.
510 while ( !result_queue.empty() ) {
511 result = result_queue.front();
513 if ( result.m != NULL ) {
514 update_metar_properties( result.m );
519 // mark as no metar so it doesn't show up in subsequent
520 // searches, and signal an immediate re-search.
521 SG_LOG( SG_GENERAL, SG_WARN,
522 "no metar at station = " << result.icao );
523 globals->get_airports()->no_metar( result.icao );
524 search_elapsed = 9999.0;
528 env->update(delta_time_sec);
533 FGMetarEnvironmentCtrl::setEnvironment (FGEnvironment * environment)
535 env->setEnvironment(environment);
539 FGMetarEnvironmentCtrl::fetch_data( const string &icao )
541 FGMetarResult result;
544 // if the last error was more than three seconds ago,
545 // then pretent nothing happened.
554 // fetch station elevation if exists
555 const FGAirport* a = globals->get_airports()->search( icao );
557 station_elevation_ft = a->getElevation();
560 // fetch current metar data
562 string host = proxy_host->getStringValue();
563 string auth = proxy_auth->getStringValue();
564 string port = proxy_port->getStringValue();
565 result.m = new FGMetar( icao, host, port, auth);
567 long max_age = metar_max_age->getLongValue();
568 long age = result.m->getAge_min();
569 if (max_age && age > max_age) {
570 SG_LOG( SG_GENERAL, SG_WARN, "METAR data too old (" << age << " min).");
574 if (++_stale_count > 10) {
576 throw sg_io_exception("More than 10 stale METAR messages in a row."
577 " Check your system time!");
582 } catch (const sg_io_exception& e) {
583 SG_LOG( SG_GENERAL, SG_WARN, "Error fetching live weather data: "
584 << e.getFormattedMessage().c_str() );
585 #if defined(ENABLE_THREADS)
586 if (_error_count++ >= 3) {
587 SG_LOG( SG_GENERAL, SG_WARN, "Stop fetching data permanently.");
603 FGMetarEnvironmentCtrl::update_metar_properties( const FGMetar *m )
609 fgSetString("/environment/metar/real-metar", m->getData());
610 // don't update with real weather when we use a custom weather scenario
611 const char *current_scenario = fgGetString("/environment/weather-scenario", "METAR");
612 if( strcmp(current_scenario, "METAR") && strcmp(current_scenario, "none"))
614 fgSetString("/environment/metar/last-metar", m->getData());
615 fgSetString("/environment/metar/station-id", m->getId());
616 fgSetDouble("/environment/metar/min-visibility-m",
617 m->getMinVisibility().getVisibility_m() );
618 fgSetDouble("/environment/metar/max-visibility-m",
619 m->getMaxVisibility().getVisibility_m() );
621 const SGMetarVisibility *dirvis = m->getDirVisibility();
622 for (i = 0; i < 8; i++, dirvis++) {
623 const char *min = "/environment/metar/visibility[%d]/min-m";
624 const char *max = "/environment/metar/visibility[%d]/max-m";
626 d = dirvis->getVisibility_m();
628 snprintf(s, 128, min, i);
630 snprintf(s, 128, max, i);
634 fgSetInt("/environment/metar/base-wind-range-from",
635 m->getWindRangeFrom() );
636 fgSetInt("/environment/metar/base-wind-range-to",
637 m->getWindRangeTo() );
638 fgSetDouble("/environment/metar/base-wind-speed-kt",
639 m->getWindSpeed_kt() );
640 fgSetDouble("/environment/metar/gust-wind-speed-kt",
641 m->getGustSpeed_kt() );
642 fgSetDouble("/environment/metar/temperature-degc",
643 m->getTemperature_C() );
644 fgSetDouble("/environment/metar/dewpoint-degc",
645 m->getDewpoint_C() );
646 fgSetDouble("/environment/metar/rel-humidity-norm",
647 m->getRelHumidity() );
648 fgSetDouble("/environment/metar/pressure-inhg",
649 m->getPressure_inHg() );
651 vector<SGMetarCloud> cv = m->getClouds();
652 vector<SGMetarCloud>::const_iterator cloud;
654 const char *cl = "/environment/clouds/layer[%i]";
655 for (i = 0, cloud = cv.begin(); cloud != cv.end(); cloud++, i++) {
656 const char *coverage_string[5] =
657 { "clear", "few", "scattered", "broken", "overcast" };
658 const double thickness[5] = { 0, 65, 600,750, 1000};
661 snprintf(s, 128, cl, i);
662 strncat(s, "/coverage", 128);
663 q = cloud->getCoverage();
664 fgSetString(s, coverage_string[q] );
666 snprintf(s, 128, cl, i);
667 strncat(s, "/elevation-ft", 128);
668 fgSetDouble(s, cloud->getAltitude_ft() + station_elevation_ft);
670 snprintf(s, 128, cl, i);
671 strncat(s, "/thickness-ft", 128);
672 fgSetDouble(s, thickness[q]);
674 snprintf(s, 128, cl, i);
675 strncat(s, "/span-m", 128);
676 fgSetDouble(s, 40000.0);
679 for (; i < FGEnvironmentMgr::MAX_CLOUD_LAYERS; i++) {
680 snprintf(s, 128, cl, i);
681 strncat(s, "/coverage", 128);
682 fgSetString(s, "clear");
684 snprintf(s, 128, cl, i);
685 strncat(s, "/elevation-ft", 128);
686 fgSetDouble(s, -9999);
688 snprintf(s, 128, cl, i);
689 strncat(s, "/thickness-ft", 128);
692 snprintf(s, 128, cl, i);
693 strncat(s, "/span-m", 128);
694 fgSetDouble(s, 40000.0);
697 fgSetDouble("/environment/metar/rain-norm", m->getRain());
698 fgSetDouble("/environment/metar/hail-norm", m->getHail());
699 fgSetDouble("/environment/metar/snow-norm", m->getSnow());
700 fgSetBool("/environment/metar/snow-cover", m->getSnowCover());
704 #if defined(ENABLE_THREADS)
709 FGMetarEnvironmentCtrl::MetarThread::run()
711 pthread_cleanup_push( metar_cleanup_handler, fetcher );
714 set_cancel( SGThread::CANCEL_DISABLE );
716 string icao = fetcher->request_queue.pop();
717 SG_LOG( SG_GENERAL, SG_INFO, "Thread: fetch metar data = " << icao );
718 FGMetarResult result = fetcher->fetch_data( icao );
720 set_cancel( SGThread::CANCEL_DEFERRED );
722 fetcher->result_queue.push( result );
724 pthread_cleanup_pop(1);
728 * Ensure mutex is unlocked.
731 metar_cleanup_handler( void* arg )
733 FGMetarEnvironmentCtrl* fetcher = (FGMetarEnvironmentCtrl*) arg;
734 fetcher->mutex.unlock();
736 #endif // ENABLE_THREADS
739 // end of environment_ctrl.cxx