]> git.mxchange.org Git - flightgear.git/blobdiff - src/Environment/environment_ctrl.cxx
Alex Romosan:
[flightgear.git] / src / Environment / environment_ctrl.cxx
index e40c3805af78622d1ec616ebefec158a99dba42c..361ca423cd518618902303a1f08177f99643daea 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>
 
@@ -35,9 +37,6 @@
 
 SG_USING_STD(sort);
 
-// FIXME, from options.cxx
-extern void fgSetupWind (double min_hdg, double max_hdg, double speed, double gust);
-
 
 \f
 ////////////////////////////////////////////////////////////////////////
@@ -317,31 +316,61 @@ FGInterpolateEnvironmentCtrl::bucket::operator< (const bucket &b) const
 
 FGMetarEnvironmentCtrl::FGMetarEnvironmentCtrl ()
     : env( new FGInterpolateEnvironmentCtrl ),
-      _icao( strdup( fgGetString("/sim/presets/airport-id") ) )
+      _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) ),
+      metar_max_age( fgGetNode("/environment/params/metar-max-age-min", true) ),
+      _error_count( 0 ),
+      _dt( 0.0 ),
+      _error_dt( 0.0 )
 {
+#if defined(ENABLE_THREADS) && ENABLE_THREADS
+    thread = new MetarThread(this);
+    thread->start( 1 );
+#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::init ()
+FGMetarEnvironmentCtrl::update_env_config ()
 {
-    if (_icao != NULL) {
-        free(_icao);
-        _icao = NULL;
-    }
-
-    fetch_data(_icao);
     fgSetupWind( fgGetDouble("/environment/metar/base-wind-range-from"),
                  fgGetDouble("/environment/metar/base-wind-range-to"),
                  fgGetDouble("/environment/metar/base-wind-speed-kt"),
@@ -349,49 +378,67 @@ FGMetarEnvironmentCtrl::init ()
 
     fgDefaultWeatherValue( "visibility-m",
                            fgGetDouble("/environment/metar/min-visibility-m") );
-
-    // FIXME: this isn't the correct place in the property tree to set
-    // the weather and it doesn't account for weather station
-    // elevation.
-    fgSetDouble("/environment/temperature-degc",
-        fgGetDouble("/environment/metar/temperature-degc"));
-    fgSetDouble("/environment/dewpoint-degc",
-        fgGetDouble("/environment/metar/dewpoint-degc"));
-
+    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") );
-
-    env->init();
 }
 
 void
-FGMetarEnvironmentCtrl::reinit ()
+FGMetarEnvironmentCtrl::init ()
 {
-#if 0
-    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;
+    long max_age = metar_max_age->getLongValue();
+    // Don't check max age during init so that we don't loop over a lot
+    // of airports metar if there is a problem.
+    // The update() calls will find a correct metar if things went wrong here
+    metar_max_age->setLongValue(60 * 24 * 7);
+
+    while ( !found_metar && (_error_count < 3) ) {
+        const FGAirport* a = globals->get_airports()
+                   ->search( longitude->getDoubleValue(),
+                             latitude->getDoubleValue(),
+                             true );
+        if ( a ) {  
+            FGMetarResult result = fetch_data( a->getId() );
+            if ( result.m != NULL ) {
+                SG_LOG( SG_GENERAL, SG_INFO, "closest station w/ metar = "
+                        << a->getId());
+                last_apt = *a;
+                _icao = a->getId();
+                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->getId() );
+                globals->get_airports()->no_metar( a->getId() );
+            }
+        }
     }
+    metar_max_age->setLongValue(max_age);
+}
 
-    fetch_data(_icao);
-    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") );
-
-    // FIXME: this isn't the correct place in the property tree to set
-    // the weather and it doesn't account for weather station
-    // elevation.
-    fgSetDouble("/environment/temperature-degc",
-        fgGetDouble("/environment/metar/temperature-degc"));
-    fgSetDouble("/environment/dewpoint-degc",
-        fgGetDouble("/environment/metar/dewpoint-degc"));
+void
+FGMetarEnvironmentCtrl::reinit ()
+{
+    _error_count = 0;
+    _error_dt = 0.0;
 
-    fgDefaultWeatherValue( "pressure-sea-level-inhg",
-                           fgGetDouble("/environment/metar/pressure-inhg") );
+#if 0
+    update_env_config();
 #endif
 
     env->reinit();
@@ -400,57 +447,174 @@ FGMetarEnvironmentCtrl::reinit ()
 void
 FGMetarEnvironmentCtrl::update(double delta_time_sec)
 {
+
+    _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 ) {
+        const FGAirport* a = globals->get_airports()
+                   ->search( longitude->getDoubleValue(),
+                             latitude->getDoubleValue(),
+                             true );
+        if ( a ) {
+            if ( last_apt.getId() != a->getId()
+                 || fetch_elapsed > same_station_interval_sec )
+            {
+                SG_LOG( SG_GENERAL, SG_INFO, "closest station w/ metar = "
+                        << a->getId());
+                request_queue.push( a->getId() );
+                last_apt = *a;
+                _icao = a->getId();
+                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 );
+            }
+        } else {
+            SG_LOG( SG_GENERAL, SG_WARN,
+                    "Unable to find any airports with metar" );
+        }
+    }
+
+#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::setEnvironment (FGEnvironment * environment)
 {
     env->setEnvironment(environment);
 }
 
-void
-FGMetarEnvironmentCtrl::fetch_data (const char *icao)
+FGMetarResult
+FGMetarEnvironmentCtrl::fetch_data( const string &icao )
 {
-    char s[128];
-    double d, dt;
-    int i;
+    FGMetarResult result;
+    result.icao = icao;
 
-    if ((icao == NULL) && (_icao == NULL)) {
-        _icao = strdup( fgGetString("/sim/presets/airport-id") );
+    // if the last error was more than three seconds ago,
+    // then pretent nothing happened.
+    if (_error_dt < 3) {
+        _error_dt += _dt;
 
-    } else if (icao != NULL) {
-        if (_icao != NULL)
-            free(_icao);
+    } else {
+        _error_dt = 0.0;
+        _error_count = 0;
+    }
 
-        _icao = strdup(icao);
+    // fetch station elevation if exists
+    const FGAirport* a = globals->get_airports()->search( icao );
+    if ( a ) {
+        station_elevation_ft = a->getElevation();
     }
 
-    SGMetar *m;
+    // fetch current metar data
     try {
-        m = new SGMetar(_icao);
+        string host = proxy_host->getStringValue();
+        string auth = proxy_auth->getStringValue();
+        string port = proxy_port->getStringValue();
+        result.m = new FGMetar( icao, host, port, auth);
+
+        long max_age = metar_max_age->getLongValue();
+        if (max_age && result.m->getAge_min() > max_age) {
+            SG_LOG( SG_GENERAL, SG_WARN, "METAR data too old");
+            delete result.m;
+            result.m = NULL;
+        }
+
     } catch (const sg_io_exception& e) {
         SG_LOG( SG_GENERAL, SG_WARN, "Error fetching live weather data: "
-                                      << e.getFormattedMessage().c_str() );
-        return;
+                << 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
+
+        result.m = NULL;
     }
 
-    d = m->getMinVisibility().getVisibility_m();
-    d = (d != SGMetarNaN) ? d : 10000;
-    fgSetDouble("/environment/metar/min-visibility-m", d);
+    _dt = 0;
 
-    dt =  m->getMaxVisibility().getVisibility_m();
-    d = (dt != SGMetarNaN) ? dt : d;
-    fgSetDouble("/environment/metar/max-visibility-m", d);
+    return result;
+}
+
+
+void
+FGMetarEnvironmentCtrl::update_metar_properties( const FGMetar *m )
+{
+    int i;
+    double d;
+    char s[128];
 
-    SGMetarVisibility *dirvis = m->getDirVisibility();
+    fgSetString("/environment/metar/real-metar", m->getData());
+       // don't update with real weather when we use a custom weather scenario
+       const char *current_scenario = fgGetString("/environment/weather-scenario", "METAR");
+       if( strcmp(current_scenario, "METAR") && strcmp(current_scenario, "none"))
+               return;
+    fgSetString("/environment/metar/last-metar", m->getData());
+    fgSetString("/environment/metar/station-id", m->getId());
+    fgSetDouble("/environment/metar/min-visibility-m",
+                m->getMinVisibility().getVisibility_m() );
+    fgSetDouble("/environment/metar/max-visibility-m",
+                m->getMaxVisibility().getVisibility_m() );
+
+    const SGMetarVisibility *dirvis = m->getDirVisibility();
     for (i = 0; i < 8; i++, dirvis++) {
         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();
-        d = (d != SGMetarNaN) ? d : 10000;
 
         snprintf(s, 128, min, i);
         fgSetDouble(s, d);
@@ -458,37 +622,22 @@ FGMetarEnvironmentCtrl::fetch_data (const char *icao)
         fgSetDouble(s, d);
     }
 
-    i = m->getWindDir();
-    if ( i == -1 ) {
-        fgSetInt("/environment/metar/base-wind-range-from",
-                    m->getWindRangeFrom() );
-        fgSetInt("/environment/metar/base-wind-range-to",
-                    m->getWindRangeTo() );
-    } else {
-        fgSetInt("/environment/metar/base-wind-range-from", i);
-        fgSetInt("/environment/metar/base-wind-range-to", i);
-    }
+    fgSetInt("/environment/metar/base-wind-range-from",
+             m->getWindRangeFrom() );
+    fgSetInt("/environment/metar/base-wind-range-to",
+             m->getWindRangeTo() );
     fgSetDouble("/environment/metar/base-wind-speed-kt",
                 m->getWindSpeed_kt() );
-
-    d = m->getGustSpeed_kt();
-    d = (d != SGMetarNaN) ? d : 0.0;
-    fgSetDouble("/environment/metar/gust-wind-speed-kt", d);
-
-    d = m->getTemperature_C();
-    if (d != SGMetarNaN) {
-        dt = m->getDewpoint_C();
-        dt = (dt != SGMetarNaN) ? dt : 0.0;
-        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);
-
-    d = m->getPressure_inHg();
-    d = (d != SGMetarNaN) ? d : 30.0;
-    fgSetDouble("/environment/metar/pressure-inhg", d);
+    fgSetDouble("/environment/metar/gust-wind-speed-kt",
+                m->getGustSpeed_kt() );
+    fgSetDouble("/environment/metar/temperature-degc",
+                m->getTemperature_C() );
+    fgSetDouble("/environment/metar/dewpoint-degc",
+                m->getDewpoint_C() );
+    fgSetDouble("/environment/metar/rel-humidity-norm",
+                m->getRelHumidity() );
+    fgSetDouble("/environment/metar/pressure-inhg",
+                m->getPressure_inHg() );
 
     vector<SGMetarCloud> cv = m->getClouds();
     vector<SGMetarCloud>::iterator cloud;
@@ -503,14 +652,11 @@ FGMetarEnvironmentCtrl::fetch_data (const char *icao)
         snprintf(s, 128, cl, i);
         strncat(s, "/coverage", 128);
         q = cloud->getCoverage();
-        q = (q != -1 ) ? q : 0;
         fgSetString(s, coverage_string[q] );
 
         snprintf(s, 128, cl, i);
         strncat(s, "/elevation-ft", 128);
-        d = cloud->getAltitude_ft();
-        d = (d != SGMetarNaN) ? d : -9999;
-        fgSetDouble(s, d);
+        fgSetDouble(s, cloud->getAltitude_ft() + station_elevation_ft);
 
         snprintf(s, 128, cl, i);
         strncat(s, "/thickness-ft", 128);
@@ -520,6 +666,7 @@ FGMetarEnvironmentCtrl::fetch_data (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);
@@ -538,8 +685,46 @@ FGMetarEnvironmentCtrl::fetch_data (const char *icao)
         fgSetDouble(s, 40000.0);
     }
 
-    delete m;
+    fgSetDouble("/environment/metar/rain-norm", m->getRain());
+    fgSetDouble("/environment/metar/hail-norm", m->getHail());
+    fgSetDouble("/environment/metar/snow-norm", m->getSnow());
+    fgSetBool("/environment/metar/snow-cover", m->getSnowCover());
+}
+
+
+#if defined(ENABLE_THREADS) && ENABLE_THREADS
+/**
+ *
+ */
+void
+FGMetarEnvironmentCtrl::MetarThread::run()
+{
+    pthread_cleanup_push( metar_cleanup_handler, fetcher );
+    while ( true )
+    {
+        set_cancel( SGThread::CANCEL_DISABLE );
+
+        string icao = fetcher->request_queue.pop();
+        SG_LOG( SG_GENERAL, SG_INFO, "Thread: fetch metar data = " << icao );
+        FGMetarResult result = fetcher->fetch_data( icao );
+
+        set_cancel( SGThread::CANCEL_DEFERRED );
+
+        fetcher->result_queue.push( result );
+    }
+    pthread_cleanup_pop(1);
+}
+
+/**
+ * Ensure mutex is unlocked.
+ */
+void
+metar_cleanup_handler( void* arg )
+{
+    FGMetarEnvironmentCtrl* fetcher = (FGMetarEnvironmentCtrl*) arg;
+    fetcher->mutex.unlock();
 }
+#endif // ENABLE_THREADS
 
 
 // end of environment_ctrl.cxx