]> git.mxchange.org Git - flightgear.git/blobdiff - src/Environment/environment_ctrl.cxx
More fixes to get the code working when threads are disabled.
[flightgear.git] / src / Environment / environment_ctrl.cxx
index 3ded1f43bdc3ef6fc1f6cb9d631780d634c4d967..d47f8e2d693b75087a2eb9c1bedc08c60d2052fb 100644 (file)
 #include <stdlib.h>
 #include <algorithm>
 
+#include <simgear/structure/commands.hxx>
+#include <simgear/structure/exception.hxx>
+
+#include <Airports/simple.hxx>
 #include <Main/fg_props.hxx>
+#include <Main/util.hxx>
 
 #include "environment_mgr.hxx"
 #include "environment_ctrl.hxx"
@@ -310,66 +315,260 @@ FGInterpolateEnvironmentCtrl::bucket::operator< (const bucket &b) const
 ////////////////////////////////////////////////////////////////////////
 
 FGMetarEnvironmentCtrl::FGMetarEnvironmentCtrl ()
-    : _icao( strdup( fgGetString("/sim/presets/airport-id") ) )
+    : env( new FGInterpolateEnvironmentCtrl ),
+      _icao( "" ),
+      search_interval_sec( 60.0 ),        // 1 minute
+      same_station_interval_sec( 900.0 ), // 15 minutes
+      search_elapsed( 9999.0 ),
+      fetch_elapsed( 9999.0 ),
+      proxy_host( fgGetNode("/sim/presets/proxy/host", true) ),
+      proxy_port( fgGetNode("/sim/presets/proxy/port", true) ),
+      proxy_auth( fgGetNode("/sim/presets/proxy/authentication", true) ),
+      _error_dt( 0.0 ),
+      _error_count( 0 )
 {
+#if defined(ENABLE_THREADS) && ENABLE_THREADS
+    thread = new MetarThread(this);
+    thread->start();
+#endif // ENABLE_THREADS
 }
 
 FGMetarEnvironmentCtrl::~FGMetarEnvironmentCtrl ()
 {
-    if (_icao) {
-      free(_icao);
-      _icao = NULL;
-    }
+#if defined(ENABLE_THREADS) && ENABLE_THREADS
+   thread->cancel();
+   thread->join();
+#endif // ENABLE_THREADS
+
+   delete env;
+   env = NULL;
+}
+
+
+// use a "command" to set station temp at station elevation
+static void set_temp_at_altitude( float temp_degc, float altitude_ft ) {
+    SGPropertyNode args;
+    SGPropertyNode *node = args.getNode("temp-degc", 0, true);
+    node->setFloatValue( temp_degc );
+    node = args.getNode("altitude-ft", 0, true);
+    node->setFloatValue( altitude_ft );
+    globals->get_commands()->execute("set-outside-air-temp-degc", &args);
 }
 
 
+static void set_dewpoint_at_altitude( float dewpoint_degc, float altitude_ft ) {
+    SGPropertyNode args;
+    SGPropertyNode *node = args.getNode("dewpoint-degc", 0, true);
+    node->setFloatValue( dewpoint_degc );
+    node = args.getNode("altitude-ft", 0, true);
+    node->setFloatValue( altitude_ft );
+    globals->get_commands()->execute("set-dewpoint-temp-degc", &args);
+}
+
+
+void
+FGMetarEnvironmentCtrl::update_env_config ()
+{
+    fgSetupWind( fgGetDouble("/environment/metar/base-wind-range-from"),
+                 fgGetDouble("/environment/metar/base-wind-range-to"),
+                 fgGetDouble("/environment/metar/base-wind-speed-kt"),
+                 fgGetDouble("/environment/metar/gust-wind-speed-kt") );
+
+    fgDefaultWeatherValue( "visibility-m",
+                           fgGetDouble("/environment/metar/min-visibility-m") );
+    set_temp_at_altitude( fgGetDouble("/environment/metar/temperature-degc"),
+                          station_elevation_ft );
+    set_dewpoint_at_altitude( fgGetDouble("/environment/metar/dewpoint-degc"),
+                              station_elevation_ft );
+    fgDefaultWeatherValue( "pressure-sea-level-inhg",
+                           fgGetDouble("/environment/metar/pressure-inhg") );
+}
+
 void
 FGMetarEnvironmentCtrl::init ()
 {
-    if (_icao != NULL) {
-        free(_icao);
-        _icao = NULL;
+    const SGPropertyNode *longitude
+        = fgGetNode( "/position/longitude-deg", true );
+    const SGPropertyNode *latitude
+        = fgGetNode( "/position/latitude-deg", true );
+
+    bool found_metar = false;
+
+    while ( !found_metar && (_error_count < 3) ) {
+        FGAirport a = globals->get_airports()
+            ->search( longitude->getDoubleValue(),
+                      latitude->getDoubleValue(),
+                      true );
+        FGMetarResult result = fetch_data( a.id );
+        if ( result.m != NULL ) {
+            SG_LOG( SG_GENERAL, SG_INFO, "closest station w/ metar = " << a.id);
+            last_apt = a;
+            _icao = a.id;
+            search_elapsed = 0.0;
+            fetch_elapsed = 0.0;
+            update_metar_properties( result.m );
+            update_env_config();
+            env->init();
+            found_metar = true;
+        } else {
+            // mark as no metar so it doesn't show up in subsequent
+            // searches.
+            SG_LOG( SG_GENERAL, SG_INFO, "no metar at metar = " << a.id );
+            globals->get_airports()->no_metar( a.id );
+        }
     }
+}
+
+void
+FGMetarEnvironmentCtrl::reinit ()
+{
+    _error_count = 0;
+    _error_dt = 0.0;
 
-    read_table(_icao);
-    _base_wind_speed_node =
-        fgGetNode("/environment/metar/base-wind-range-from", true);
-    _gust_wind_speed_node =
-        fgGetNode("/environment/metar/gust-wind-speed-kt", true);
+#if 0
+    update_env_config();
+#endif
 
-    fgSetDouble("/environment/visibility-m",
-        fgGetDouble("/environment/metar/min-visibility-m"));
-    fgSetDouble("/environment/temperature-degc",
-        fgGetDouble("/environment/metar/temperature_degc"));
-    fgSetDouble("/environment/dewpoint-degc",
-        fgGetDouble("/environment/metar/dewpoint-degc"));
-    fgSetDouble("/environment/pressure-inhg",
-        fgGetDouble("/environment/metar/pressure-inhg"));
+    env->reinit();
 }
 
 void
-FGMetarEnvironmentCtrl::reinit ()
+FGMetarEnvironmentCtrl::update(double delta_time_sec)
 {
-    init();
+
+    _dt += delta_time_sec;
+    if (_error_count >= 3)
+       return;
+
+    FGMetarResult result;
+
+    static const SGPropertyNode *longitude
+        = fgGetNode( "/position/longitude-deg", true );
+    static const SGPropertyNode *latitude
+        = fgGetNode( "/position/latitude-deg", true );
+    search_elapsed += delta_time_sec;
+    fetch_elapsed += delta_time_sec;
+
+    // if time for a new search request, push it onto the request
+    // queue
+    if ( search_elapsed > search_interval_sec ) {
+        FGAirport a = globals->get_airports()
+            ->search( longitude->getDoubleValue(),
+                      latitude->getDoubleValue(),
+                      true );
+        if ( last_apt.id != a.id
+             || fetch_elapsed > same_station_interval_sec )
+        {
+            SG_LOG( SG_GENERAL, SG_INFO, "closest station w/ metar = " << a.id);
+            request_queue.push( a.id );
+            last_apt = a;
+            _icao = a.id;
+            search_elapsed = 0.0;
+            fetch_elapsed = 0.0;
+        } else {
+            search_elapsed = 0.0;
+            SG_LOG( SG_GENERAL, SG_INFO, "same station, waiting = "
+                 << same_station_interval_sec - fetch_elapsed );
+        }
+    }
+
+#if defined(ENABLE_THREADS) && ENABLE_THREADS
+    // No loader thread running so manually fetch the data
+    string id = "";
+    while ( !request_queue.empty() ) {
+        id = request_queue.front();
+        request_queue.pop();
+    }
+
+    if ( !id.empty() ) {
+        SG_LOG( SG_GENERAL, SG_INFO, "inline fetching = " << id );
+        result = fetch_data( id );
+        result_queue.push( result );
+    }
+#endif // ENABLE_THREADS
+
+    // process any results from the loader.
+    while ( !result_queue.empty() ) {
+        result = result_queue.front();
+        result_queue.pop();
+        if ( result.m != NULL ) {
+            update_metar_properties( result.m );
+            delete result.m;
+            update_env_config();
+            env->reinit();
+        } else {
+            // mark as no metar so it doesn't show up in subsequent
+            // searches, and signal an immediate re-search.
+            SG_LOG( SG_GENERAL, SG_WARN,
+                    "no metar at station = " << result.icao );
+            globals->get_airports()->no_metar( result.icao );
+            search_elapsed = 9999.0;
+        }
+    }
+
+    env->update(delta_time_sec);
 }
 
+
 void
-FGMetarEnvironmentCtrl::read_table (const char *icao)
+FGMetarEnvironmentCtrl::setEnvironment (FGEnvironment * environment)
 {
-    char s[128];
-    double d, dt;
-    int i;
+    env->setEnvironment(environment);
+}
 
-    if ((icao == NULL) && (_icao == NULL)) {
-        _icao = strdup( fgGetString("/sim/presets/airport-id") );
+FGMetarResult
+FGMetarEnvironmentCtrl::fetch_data( const string &icao )
+{
+    FGMetarResult result;
+    result.icao = icao;
+
+    // if the last error was more than three seconds ago,
+    // then pretent nothing happened.
+    if (_error_dt < 3) {
+        _error_dt += _dt;
+
+    } else {
+        _error_dt = 0.0;
+        _error_count = 0;
+    }
 
-    } else if (icao != NULL) {
-        if (_icao != NULL)
-            free(_icao);
+    // fetch station elevation if exists
+    FGAirport a = globals->get_airports()->search( icao );
+    station_elevation_ft = a.elevation;
+
+    // fetch current metar data
+    try {
+        string host = proxy_host->getStringValue();
+        string auth = proxy_auth->getStringValue();
+        string port = proxy_port->getStringValue();
+        result.m = new SGMetar( icao, host, port, auth);
+
+    } catch (const sg_io_exception& e) {
+        SG_LOG( SG_GENERAL, SG_WARN, "Error fetching live weather data: "
+                << e.getFormattedMessage().c_str() );
+#if defined(ENABLE_THREADS) && ENABLE_THREADS
+        if (_error_count++ >= 3) {
+           SG_LOG( SG_GENERAL, SG_WARN, "Stop fetching data permanently.");
+           thread->cancel();
+           thread->join();
+        }
+#endif
 
-        _icao = strdup(icao);
+        result.m = NULL;
     }
-    SGMetar *m = new SGMetar(_icao);
+
+    _dt = 0;
+
+    return result;
+}
+
+
+void
+FGMetarEnvironmentCtrl::update_metar_properties( SGMetar *m )
+{
+    int i;
+    double d, dt;
+    char s[128];
 
     d = m->getMinVisibility().getVisibility_m();
     d = (d != SGMetarNaN) ? d : 10000;
@@ -381,8 +580,8 @@ FGMetarEnvironmentCtrl::read_table (const char *icao)
 
     SGMetarVisibility *dirvis = m->getDirVisibility();
     for (i = 0; i < 8; i++, dirvis++) {
-        const char *min = "/environment/metar/visibility[%]/min-m";
-        const char *max = "/environment/metar/visibility[%]/max-m";
+        const char *min = "/environment/metar/visibility[%d]/min-m";
+        const char *max = "/environment/metar/visibility[%d]/max-m";
         char s[128];
 
         d = dirvis->getVisibility_m();
@@ -397,9 +596,9 @@ FGMetarEnvironmentCtrl::read_table (const char *icao)
     i = m->getWindDir();
     if ( i == -1 ) {
         fgSetInt("/environment/metar/base-wind-range-from",
-                    m->getWindRangeFrom() );
+                 m->getWindRangeFrom() );
         fgSetInt("/environment/metar/base-wind-range-to",
-                    m->getWindRangeTo() );
+                 m->getWindRangeTo() );
     } else {
         fgSetInt("/environment/metar/base-wind-range-from", i);
         fgSetInt("/environment/metar/base-wind-range-to", i);
@@ -418,9 +617,9 @@ FGMetarEnvironmentCtrl::read_table (const char *icao)
         fgSetDouble("/environment/metar/dewpoint-degc", dt);
         fgSetDouble("/environment/metar/rel-humidity-norm",
                     m->getRelHumidity() );
-    }   
+    }
     d = (d != SGMetarNaN) ? d : 15.0;
-    fgSetDouble("/environment/metar/temperature_degc", d);
+    fgSetDouble("/environment/metar/temperature-degc", d);
 
     d = m->getPressure_inHg();
     d = (d != SGMetarNaN) ? d : 30.0;
@@ -446,7 +645,7 @@ FGMetarEnvironmentCtrl::read_table (const char *icao)
         strncat(s, "/elevation-ft", 128);
         d = cloud->getAltitude_ft();
         d = (d != SGMetarNaN) ? d : -9999;
-        fgSetDouble(s, d);
+        fgSetDouble(s, d + station_elevation_ft);
 
         snprintf(s, 128, cl, i);
         strncat(s, "/thickness-ft", 128);
@@ -456,6 +655,7 @@ FGMetarEnvironmentCtrl::read_table (const char *icao)
         strncat(s, "/span-m", 128);
         fgSetDouble(s, 40000.0);
     }
+
     for (; i < FGEnvironmentMgr::MAX_CLOUD_LAYERS; i++) {
         snprintf(s, 128, cl, i);
         strncat(s, "/coverage", 128);
@@ -473,62 +673,42 @@ FGMetarEnvironmentCtrl::read_table (const char *icao)
         strncat(s, "/span-m", 128);
         fgSetDouble(s, 40000.0);
     }
-
-    delete m;
 }
 
+
+#if defined(ENABLE_THREADS) && ENABLE_THREADS
+/**
+ *
+ */
 void
-FGMetarEnvironmentCtrl::update (double delta_time_sec)
+FGMetarEnvironmentCtrl::MetarThread::run()
 {
-  double base_wind_speed = _base_wind_speed_node->getDoubleValue();
-  double gust_wind_speed = _gust_wind_speed_node->getDoubleValue();
+    pthread_cleanup_push( metar_cleanup_handler, fetcher );
+    while ( true )
+    {
+        set_cancel( SGThread::CANCEL_DISABLE );
 
-  if (gust_wind_speed < base_wind_speed) {
-      gust_wind_speed = base_wind_speed;
-      _gust_wind_speed_node->setDoubleValue(gust_wind_speed);
-  }
+        string icao = fetcher->request_queue.pop();
+        SG_LOG( SG_GENERAL, SG_INFO, "Thread: fetch metar data = " << icao );
+        FGMetarResult result = fetcher->fetch_data( icao );
 
-  if (base_wind_speed == gust_wind_speed) {
-    _current_wind_speed_kt = base_wind_speed;
-  } else {
-    int rn = rand() % 128;
-    int sign = (_delta_wind_speed_kt < 0 ? -1 : 1);
-    double gust = _current_wind_speed_kt - base_wind_speed;
-    double incr = gust / 50;
+        set_cancel( SGThread::CANCEL_DEFERRED );
 
-    if (rn == 0)
-      _delta_wind_speed_kt = - _delta_wind_speed_kt;
-    else if (rn < 4)
-      _delta_wind_speed_kt -= incr * sign;
-    else if (rn < 16)
-      _delta_wind_speed_kt += incr * sign;
-
-    _current_wind_speed_kt += _delta_wind_speed_kt;
-
-    if (_current_wind_speed_kt < base_wind_speed) {
-      _current_wind_speed_kt = base_wind_speed;
-      _delta_wind_speed_kt = 0.01;
-    } else if (_current_wind_speed_kt > gust_wind_speed) {
-      _current_wind_speed_kt = gust_wind_speed;
-      _delta_wind_speed_kt = -0.01;
+        fetcher->result_queue.push( result );
     }
-  }
-
-  if (_environment != 0)
-    _environment->set_wind_speed_kt(_current_wind_speed_kt);
+    pthread_cleanup_pop(1);
 }
 
+/**
+ * Ensure mutex is unlocked.
+ */
 void
-FGMetarEnvironmentCtrl::do_interpolate (vector<bucket *> &table,
-                                              double altitude_ft,
-                                              FGEnvironment * environment)
+metar_cleanup_handler( void* arg )
 {
+    FGMetarEnvironmentCtrl* fetcher = (FGMetarEnvironmentCtrl*) arg;
+    fetcher->mutex.unlock();
 }
+#endif // ENABLE_THREADS
 
-bool
-FGMetarEnvironmentCtrl::bucket::operator< (const bucket &b) const
-{
-    return (altitude_ft < b.altitude_ft);
-}
 
 // end of environment_ctrl.cxx