#endif
#include "realwx_ctrl.hxx"
-#include "tiedpropertylist.hxx"
#include "metarproperties.hxx"
#include "metarairportfilter.hxx"
#include "fgmetar.hxx"
#include <Main/fg_props.hxx>
+#include <boost/foreach.hpp>
+
#include <simgear/structure/exception.hxx>
#include <simgear/misc/strutils.hxx>
+#include <simgear/props/tiedpropertylist.hxx>
+#include <simgear/io/HTTPClient.hxx>
+#include <simgear/io/HTTPRequest.hxx>
+#include <simgear/timing/sg_time.hxx>
+
#include <algorithm>
-#if defined(ENABLE_THREADS)
-#include <OpenThreads/Thread>
-#include <simgear/threads/SGQueue.hxx>
-#endif
+using simgear::PropertyList;
namespace Environment {
+/* -------------------------------------------------------------------------------- */
+
+class LiveMetarProperties : public MetarProperties {
+public:
+ LiveMetarProperties( SGPropertyNode_ptr rootNode );
+ virtual ~LiveMetarProperties();
+ virtual void update( double dt );
+
+ virtual double getTimeToLive() const { return _timeToLive; }
+ virtual void setTimeToLive( double value ) { _timeToLive = value; }
+private:
+ double _timeToLive;
+
+};
+
+typedef SGSharedPtr<LiveMetarProperties> LiveMetarProperties_ptr;
+
+LiveMetarProperties::LiveMetarProperties( SGPropertyNode_ptr rootNode ) :
+ MetarProperties( rootNode ),
+ _timeToLive(0.0)
+{
+ _tiedProperties.Tie("time-to-live", &_timeToLive );
+}
+
+LiveMetarProperties::~LiveMetarProperties()
+{
+ _tiedProperties.Untie();
+}
+
+void LiveMetarProperties::update( double dt )
+{
+ _timeToLive -= dt;
+ if( _timeToLive < 0.0 ) _timeToLive = 0.0;
+}
+
+/* -------------------------------------------------------------------------------- */
+
class BasicRealWxController : public RealWxController
{
public:
bool _enabled;
bool __enabled;
- TiedPropertyList _tiedProperties;
- MetarProperties _metarProperties;
+ simgear::TiedPropertyList _tiedProperties;
+ typedef std::vector<LiveMetarProperties_ptr> MetarPropertiesList;
+ MetarPropertiesList _metarProperties;
+
};
/* -------------------------------------------------------------------------------- */
_ground_elevation_n( fgGetNode( "/position/ground-elev-m", true )),
_max_age_n( fgGetNode( "/environment/params/metar-max-age-min", false ) ),
_enabled(true),
- __enabled(false),
- _metarProperties( fgGetNode( rootNode->getStringValue("metar", "/environment/metar"), true ) )
+ __enabled(false)
{
+ // at least instantiate MetarProperties for /environment/metar
+ _metarProperties.push_back( new LiveMetarProperties(
+ fgGetNode( rootNode->getStringValue("metar", "/environment/metar"), true ) ) );
+
+ PropertyList metars = rootNode->getChildren("metar");
+ for( PropertyList::size_type i = 1; i < metars.size(); i++ ) {
+ SG_LOG( SG_ALL, SG_INFO, "Adding metar properties at " << metars[i]->getStringValue() );
+ _metarProperties.push_back( new LiveMetarProperties(
+ fgGetNode( metars[i]->getStringValue(), true )));
+ }
}
BasicRealWxController::~BasicRealWxController()
void BasicRealWxController::update( double dt )
{
if( _enabled ) {
- update( !__enabled, dt );
+ bool firstIteration = !__enabled; // first iteration after being enabled?
+
+ // clock tick for every METAR in stock
+ for( MetarPropertiesList::iterator it = _metarProperties.begin();
+ it != _metarProperties.end(); it++ ) {
+ // first round? All received METARs are outdated
+ if( firstIteration ) (*it)->setTimeToLive( 0.0 );
+ (*it)->update(dt);
+ }
+
+ update( firstIteration, dt );
__enabled = true;
} else {
__enabled = false;
NoaaMetarRealWxController( SGPropertyNode_ptr rootNode );
virtual ~NoaaMetarRealWxController();
virtual void update (bool first, double delta_time_sec);
+ virtual void shutdown ();
- class MetarLoadRequest {
- public:
- MetarLoadRequest( const string & stationId ) {
- _stationId = stationId;
- _proxyHost = fgGetNode("/sim/presets/proxy/host", true)->getStringValue();
- _proxyPort = fgGetNode("/sim/presets/proxy/port", true)->getStringValue();
- _proxyAuth = fgGetNode("/sim/presets/proxy/authentication", true)->getStringValue();
- }
- string _stationId;
- string _proxyHost;
- string _proxyPort;
- string _proxyAuth;
- private:
- };
+ /**
+ * callback from MetarGetRequest when a download succeeds
+ */
+ void gotMetar(const string& stationId, const string& metar);
private:
- double _metarTimeToLive;
double _positionTimeToLive;
- double _minimumRequestInterval;
+ double _requestTimer;
+
+ simgear::HTTP::Client _http;
+};
+
+class MetarGetRequest : public simgear::HTTP::Request
+{
+public:
+ MetarGetRequest(NoaaMetarRealWxController* con, const string& s) :
+ Request(""),
+ stationId(s),
+ fromProxy(false),
+ wxController(con)
+ {
+ setUrl("http://weather.noaa.gov/pub/data/observations/metar/stations/" + stationId + ".TXT");
+ }
- SGPropertyNode_ptr _metarDataNode;
- SGPropertyNode_ptr _metarValidNode;
- SGPropertyNode_ptr _metarStationIdNode;
-
-
-#if defined(ENABLE_THREADS)
- class MetarLoadThread : public OpenThreads::Thread {
- public:
- MetarLoadThread( long maxAge );
- void requestMetar( const MetarLoadRequest & metarRequest, bool background = true );
- bool hasMetar() { return _responseQueue.size() > 0; }
- string getMetar() { return _responseQueue.pop(); }
- virtual void run();
- private:
- void fetch( const MetarLoadRequest & );
- long _maxAge;
- SGBlockingQueue <MetarLoadRequest> _requestQueue;
- SGBlockingQueue <string> _responseQueue;
- };
-
- MetarLoadThread * _metarLoadThread;
-#endif
+ virtual string_list requestHeaders() const
+ {
+ string_list r;
+ r.push_back("X-Time");
+ return r;
+ }
+
+ virtual string header(const string& name) const
+ {
+ if (name == "X-Time") {
+ char buf[16];
+ snprintf(buf, 16, "%ld", globals->get_time_params()->get_cur_time());
+ return buf;
+ }
+
+ return Request::header(name);
+ }
+
+ virtual void responseHeader(const string& key, const string& value)
+ {
+ if (key == "x-metarproxy") {
+ fromProxy = true;
+ }
+ }
+
+ virtual void gotBodyData(const char* s, int n)
+ {
+ metar += string(s, n);
+ }
+
+ virtual void responseComplete()
+ {
+ if (responseCode() == 200) {
+ wxController->gotMetar(stationId, metar);
+ } else {
+ SG_LOG(SG_IO, SG_WARN, "metar download failed:" << url() << ": reason:" << responseReason());
+ }
+ }
+
+ bool fromMetarProxy() const
+ { return fromProxy; }
+private:
+ string stationId;
+ string metar;
+ bool fromProxy;
+ NoaaMetarRealWxController* wxController;
};
+
+
NoaaMetarRealWxController::NoaaMetarRealWxController( SGPropertyNode_ptr rootNode ) :
BasicRealWxController(rootNode),
- _metarTimeToLive(0.0),
_positionTimeToLive(0.0),
- _minimumRequestInterval(0.0),
- _metarDataNode(_metarProperties.get_root_node()->getNode("data",true)),
- _metarValidNode(_metarProperties.get_root_node()->getNode("valid",true)),
- _metarStationIdNode(_metarProperties.get_root_node()->getNode("station-id",true))
+ _requestTimer(0.0)
+{
+ string proxyHost(fgGetString("/sim/presets/proxy/host"));
+ int proxyPort(fgGetInt("/sim/presets/proxy/port"));
+ string proxyAuth(fgGetString("/sim/presets/proxy/auth"));
+
+ if (!proxyHost.empty()) {
+ _http.setProxy(proxyHost, proxyPort, proxyAuth);
+ }
+}
+
+void NoaaMetarRealWxController::shutdown()
{
-#if defined(ENABLE_THREADS)
- _metarLoadThread = new MetarLoadThread(getMetarMaxAgeMin());
- _metarLoadThread->start();
-#endif
}
NoaaMetarRealWxController::~NoaaMetarRealWxController()
{
-#if defined(ENABLE_THREADS)
- if( _metarLoadThread ) {
- MetarLoadRequest request("");
- _metarLoadThread->requestMetar(request);
- _metarLoadThread->join();
- delete _metarLoadThread;
- }
-#endif // ENABLE_THREADS
}
void NoaaMetarRealWxController::update( bool first, double dt )
{
- _metarTimeToLive -= dt;
+ _http.update();
+
_positionTimeToLive -= dt;
- _minimumRequestInterval -= dt;
-
- bool valid = _metarValidNode->getBoolValue();
- string stationId = valid ? _metarStationIdNode->getStringValue() : "";
+ _requestTimer -= dt;
-
- if( _metarTimeToLive <= 0.0 ) {
- valid = false;
- _metarTimeToLive = 900;
- _positionTimeToLive = 0;
- }
-
- if( _positionTimeToLive <= 0.0 || valid == false ) {
+ if( _positionTimeToLive <= 0.0 ) {
+ // check nearest airport
+ SG_LOG(SG_ALL, SG_INFO, "NoaaMetarRealWxController::update(): (re) checking nearby airport with METAR" );
_positionTimeToLive = 60.0;
SGGeod pos = SGGeod::fromDeg(_longitude_n->getDoubleValue(), _latitude_n->getDoubleValue());
return;
}
- if( stationId != nearestAirport->ident() ) {
- valid = false;
- stationId = nearestAirport->ident();
- }
-
- }
-
- if( !valid ) {
- if( _minimumRequestInterval <= 0 && stationId.length() > 0 ) {
- MetarLoadRequest request( stationId );
- // load the first metar in the foreground to make sure a metar is received
- // before the automatic runway selection code runs. All subsequent calls
- // run in the background
- _metarLoadThread->requestMetar( request, !first );
- _minimumRequestInterval = 10;
+ SG_LOG(SG_ALL, SG_INFO,
+ "NoaaMetarRealWxController::update(): nearest airport with METAR is: " << nearestAirport->ident() );
+
+ // if it has changed, invalidate the associated METAR
+ if( _metarProperties[0]->getStationId() != nearestAirport->ident() ) {
+ SG_LOG(SG_ALL, SG_INFO,
+ "NoaaMetarRealWxController::update(): nearest airport with METAR has changed. Old: '" <<
+ _metarProperties[0]->getStationId() <<
+ "', new: '" << nearestAirport->ident() << "'" );
+ _metarProperties[0]->setStationId( nearestAirport->ident() );
+ _metarProperties[0]->setTimeToLive( 0.0 );
}
}
-
- if( _metarLoadThread->hasMetar() ) {
- string metar = _metarLoadThread->getMetar();
- SG_LOG( SG_ALL, SG_ALERT, "NoaaMetarRwalWxController::update() received METAR " << metar );
- _metarDataNode->setStringValue( metar );
+
+ if( _requestTimer <= 0.0 ) {
+ _requestTimer = 10.0;
+
+ BOOST_FOREACH(LiveMetarProperties* p, _metarProperties) {
+ if( p->getTimeToLive() > 0.0 ) continue;
+ const std::string & stationId = p->getStationId();
+ if( stationId.empty() ) continue;
+
+ SG_LOG(SG_ALL, SG_INFO,
+ "NoaaMetarRealWxController::update(): spawning load request for station-id '" << stationId << "'" );
+
+ _http.makeRequest(new MetarGetRequest(this, stationId));
+ } // of MetarProperties iteration
}
-
-
}
-/* -------------------------------------------------------------------------------- */
-
-#if defined(ENABLE_THREADS)
-NoaaMetarRealWxController::MetarLoadThread::MetarLoadThread( long maxAge ) :
- _maxAge(maxAge)
+void NoaaMetarRealWxController::gotMetar(const string& stationId, const string& metar)
{
-}
-
-void NoaaMetarRealWxController::MetarLoadThread::requestMetar( const MetarLoadRequest & metarRequest, bool background )
-{
- if( background ) {
- if( _requestQueue.size() > 10 ) {
- SG_LOG(SG_ALL,SG_ALERT,
- "NoaaMetarRealWxController::MetarLoadThread::requestMetar() more than 10 outstanding METAR requests, dropping "
- << metarRequest._stationId );
- return;
- }
-
- _requestQueue.push( metarRequest );
- } else {
- fetch( metarRequest );
- }
-}
-
-void NoaaMetarRealWxController::MetarLoadThread::run()
-{
- for( ;; ) {
- const MetarLoadRequest request = _requestQueue.pop();
-
- if( request._stationId.size() == 0 )
- break;
-
- fetch( request );
+ SG_LOG( SG_ALL, SG_INFO, "NoaaMetarRwalWxController::update() received METAR for " << stationId << ": " << metar );
+ BOOST_FOREACH(LiveMetarProperties* p, _metarProperties) {
+ if (p->getStationId() != stationId)
+ continue;
+
+ p->setTimeToLive(900);
+ p->setMetar( metar );
}
}
-void NoaaMetarRealWxController::MetarLoadThread::fetch( const MetarLoadRequest & request )
-{
- SGSharedPtr<FGMetar> result = NULL;
-
- try {
- result = new FGMetar( request._stationId, request._proxyHost, request._proxyPort, request._proxyAuth );
- } catch (const sg_io_exception& e) {
- SG_LOG( SG_GENERAL, SG_WARN, "NoaaMetarRealWxController::fetchMetar(): can't get METAR for "
- << request._stationId << ":" << e.getFormattedMessage().c_str() );
- return;
- }
-
- string reply = result->getData();
- std::replace(reply.begin(), reply.end(), '\n', ' ');
- string metar = simgear::strutils::strip( reply );
-
- if( metar.empty() ) {
- SG_LOG( SG_GENERAL, SG_WARN, "NoaaMetarRealWxController::fetchMetar(): dropping empty METAR for "
- << request._stationId );
- return;
- }
-
- if( _maxAge && result->getAge_min() > _maxAge ) {
- SG_LOG( SG_GENERAL, SG_ALERT, "NoaaMetarRealWxController::fetchMetar(): dropping outdated METAR "
- << metar );
- return;
- }
-
- _responseQueue.push( metar );
-}
-#endif
-
/* -------------------------------------------------------------------------------- */
RealWxController * RealWxController::createInstance( SGPropertyNode_ptr rootNode )