1 // realwx_ctrl.cxx -- Process real weather data
3 // Written by David Megginson, started February 2002.
4 // Rewritten by Torsten Dreyer, August 2010, August 2011
6 // Copyright (C) 2002 David Megginson - david@megginson.com
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.
27 #include "realwx_ctrl.hxx"
30 #include <boost/foreach.hpp>
32 #include <simgear/structure/exception.hxx>
33 #include <simgear/misc/strutils.hxx>
34 #include <simgear/props/tiedpropertylist.hxx>
35 #include <simgear/io/HTTPRequest.hxx>
36 #include <simgear/timing/sg_time.hxx>
37 #include <simgear/structure/event_mgr.hxx>
39 #include "metarproperties.hxx"
40 #include "metarairportfilter.hxx"
41 #include "fgmetar.hxx"
42 #include <Network/HTTPClient.hxx>
43 #include <Main/fg_props.hxx>
45 namespace Environment {
48 /* -------------------------------------------------------------------------------- */
50 class MetarDataHandler {
52 virtual void handleMetarData( const std::string & data ) = 0;
55 class MetarRequester {
57 virtual void requestMetar( MetarDataHandler * metarDataHandler, const std::string & id ) = 0;
60 /* -------------------------------------------------------------------------------- */
62 class LiveMetarProperties : public MetarProperties, MetarDataHandler {
64 LiveMetarProperties( SGPropertyNode_ptr rootNode, MetarRequester * metarRequester );
65 virtual ~LiveMetarProperties();
66 virtual void update( double dt );
68 virtual double getTimeToLive() const { return _timeToLive; }
69 virtual void setTimeToLive( double value ) { _timeToLive = value; }
71 // implementation of MetarDataHandler
72 virtual void handleMetarData( const std::string & data );
74 static const unsigned MAX_POLLING_INTERVAL_SECONDS = 10;
75 static const unsigned DEFAULT_TIME_TO_LIVE_SECONDS = 900;
80 MetarRequester * _metarRequester;
83 typedef SGSharedPtr<LiveMetarProperties> LiveMetarProperties_ptr;
85 LiveMetarProperties::LiveMetarProperties( SGPropertyNode_ptr rootNode, MetarRequester * metarRequester ) :
86 MetarProperties( rootNode ),
89 _metarRequester(metarRequester)
91 _tiedProperties.Tie("time-to-live", &_timeToLive );
94 LiveMetarProperties::~LiveMetarProperties()
96 _tiedProperties.Untie();
99 void LiveMetarProperties::update( double dt )
103 if( _timeToLive < 0.0 ) {
105 std::string stationId = getStationId();
106 if( stationId.empty() ) return;
107 if( _pollingTimer > 0.0 ) return;
108 _metarRequester->requestMetar( this, stationId );
109 _pollingTimer = MAX_POLLING_INTERVAL_SECONDS;
113 void LiveMetarProperties::handleMetarData( const std::string & data )
115 SG_LOG( SG_ENVIRONMENT, SG_INFO, "LiveMetarProperties::handleMetarData() received METAR for " << getStationId() << ": " << data );
116 _timeToLive = DEFAULT_TIME_TO_LIVE_SECONDS;
120 /* -------------------------------------------------------------------------------- */
122 class BasicRealWxController : public RealWxController
125 BasicRealWxController( SGPropertyNode_ptr rootNode, MetarRequester * metarRequester );
126 virtual ~BasicRealWxController ();
128 virtual void init ();
129 virtual void reinit ();
130 virtual void shutdown ();
135 void update( double dt );
137 void checkNearbyMetar();
139 long getMetarMaxAgeMin() const { return _max_age_n == NULL ? 0 : _max_age_n->getLongValue(); }
141 SGPropertyNode_ptr _rootNode;
142 SGPropertyNode_ptr _ground_elevation_n;
143 SGPropertyNode_ptr _max_age_n;
147 simgear::TiedPropertyList _tiedProperties;
148 typedef std::vector<LiveMetarProperties_ptr> MetarPropertiesList;
149 MetarPropertiesList _metarProperties;
153 /* -------------------------------------------------------------------------------- */
156 ~/enabled: bool Enables/Disables the realwx controller
157 ~/metar[1..n]: string Target property path for metar data
160 BasicRealWxController::BasicRealWxController( SGPropertyNode_ptr rootNode, MetarRequester * metarRequester ) :
162 _ground_elevation_n( fgGetNode( "/position/ground-elev-m", true )),
163 _max_age_n( fgGetNode( "/environment/params/metar-max-age-min", false ) ),
167 // at least instantiate MetarProperties for /environment/metar
168 _metarProperties.push_back( new LiveMetarProperties(
169 fgGetNode( rootNode->getStringValue("metar", "/environment/metar"), true ), metarRequester ));
171 BOOST_FOREACH( SGPropertyNode_ptr n, rootNode->getChildren("metar") ) {
172 SGPropertyNode_ptr metarNode = fgGetNode( n->getStringValue(), true );
174 // check for duplicate entries
175 bool existingElement = false;
176 BOOST_FOREACH( LiveMetarProperties_ptr p, _metarProperties ) {
177 if( p->get_root_node()->getPath() == metarNode->getPath() ) {
178 existingElement = true;
183 if( existingElement )
186 SG_LOG( SG_ENVIRONMENT, SG_INFO, "Adding metar properties at " << metarNode->getPath() );
187 _metarProperties.push_back( new LiveMetarProperties( metarNode, metarRequester ));
191 BasicRealWxController::~BasicRealWxController()
195 void BasicRealWxController::init()
198 update(0); // fetch data ASAP
200 globals->get_event_mgr()->addTask("checkNearbyMetar", this,
201 &BasicRealWxController::checkNearbyMetar, 60 );
204 void BasicRealWxController::reinit()
209 void BasicRealWxController::shutdown()
211 globals->get_event_mgr()->removeTask("checkNearbyMetar");
214 void BasicRealWxController::bind()
216 _tiedProperties.setRoot( _rootNode );
217 _tiedProperties.Tie( "enabled", &_enabled );
220 void BasicRealWxController::unbind()
222 _tiedProperties.Untie();
225 void BasicRealWxController::update( double dt )
228 bool firstIteration = !__enabled; // first iteration after being enabled?
230 // clock tick for every METAR in stock
231 BOOST_FOREACH(LiveMetarProperties* p, _metarProperties) {
232 // first round? All received METARs are outdated
233 if( firstIteration ) p->setTimeToLive( 0.0 );
243 void BasicRealWxController::checkNearbyMetar()
246 const SGGeod & pos = globals->get_aircraft_position();
248 // check nearest airport
249 SG_LOG(SG_ENVIRONMENT, SG_DEBUG, "NoaaMetarRealWxController::update(): (re) checking nearby airport with METAR" );
251 FGAirport * nearestAirport = FGAirport::findClosest(pos, 10000.0, MetarAirportFilter::instance() );
252 if( nearestAirport == NULL ) {
253 SG_LOG(SG_ENVIRONMENT,SG_WARN,"RealWxController::update can't find airport with METAR within 10000NM" );
257 SG_LOG(SG_ENVIRONMENT, SG_DEBUG,
258 "NoaaMetarRealWxController::update(): nearest airport with METAR is: " << nearestAirport->ident() );
260 // if it has changed, invalidate the associated METAR
261 if( _metarProperties[0]->getStationId() != nearestAirport->ident() ) {
262 SG_LOG(SG_ENVIRONMENT, SG_INFO,
263 "NoaaMetarRealWxController::update(): nearest airport with METAR has changed. Old: '" <<
264 _metarProperties[0]->getStationId() <<
265 "', new: '" << nearestAirport->ident() << "'" );
266 _metarProperties[0]->setStationId( nearestAirport->ident() );
267 _metarProperties[0]->setTimeToLive( 0.0 );
270 catch( sg_exception & ) {
276 /* -------------------------------------------------------------------------------- */
278 class NoaaMetarRealWxController : public BasicRealWxController, MetarRequester {
280 NoaaMetarRealWxController( SGPropertyNode_ptr rootNode );
282 // implementation of MetarRequester
283 virtual void requestMetar( MetarDataHandler * metarDataHandler, const std::string & id );
289 NoaaMetarRealWxController::NoaaMetarRealWxController( SGPropertyNode_ptr rootNode ) :
290 BasicRealWxController(rootNode, this )
294 void NoaaMetarRealWxController::requestMetar( MetarDataHandler * metarDataHandler, const std::string & id )
296 class NoaaMetarGetRequest : public simgear::HTTP::Request
299 NoaaMetarGetRequest(MetarDataHandler* metarDataHandler, const string& stationId ) :
300 Request("http://weather.noaa.gov/pub/data/observations/metar/stations/" + stationId + ".TXT"),
302 _metarDataHandler(metarDataHandler)
306 virtual string_list requestHeaders() const
309 reply.push_back("X-TIME");
313 virtual std::string header(const std::string& name) const
317 if( name == "X-TIME" ) {
318 std::ostringstream buf;
319 buf << globals->get_time_params()->get_cur_time();
326 virtual void responseHeader(const string& key, const string& value)
328 if (key == "x-metarproxy") {
333 virtual void gotBodyData(const char* s, int n)
335 _metar += string(s, n);
338 virtual void responseComplete()
340 if (responseCode() == 200) {
341 _metarDataHandler->handleMetarData( simgear::strutils::simplify(_metar) );
343 SG_LOG(SG_ENVIRONMENT, SG_WARN, "metar download failed:" << url() << ": reason:" << responseReason());
347 // bool fromMetarProxy() const
348 // { return _fromProxy; }
352 MetarDataHandler * _metarDataHandler;
356 SG_LOG(SG_ENVIRONMENT, SG_INFO,
357 "NoaaMetarRealWxController::update(): spawning load request for station-id '" << id << "'" );
358 FGHTTPClient::instance()->makeRequest(new NoaaMetarGetRequest(metarDataHandler, id));
361 /* -------------------------------------------------------------------------------- */
363 RealWxController * RealWxController::createInstance( SGPropertyNode_ptr rootNode )
365 // string dataSource = rootNode->getStringValue("data-source", "noaa" );
366 // if( dataSource == "nwx" ) {
367 // return new NwxMetarRealWxController( rootNode );
369 return new NoaaMetarRealWxController( rootNode );
373 /* -------------------------------------------------------------------------------- */
375 } // namespace Environment