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>
31 #include <boost/algorithm/string/case_conv.hpp>
33 #include <simgear/structure/exception.hxx>
34 #include <simgear/misc/strutils.hxx>
35 #include <simgear/props/tiedpropertylist.hxx>
36 #include <simgear/io/HTTPRequest.hxx>
37 #include <simgear/timing/sg_time.hxx>
38 #include <simgear/structure/event_mgr.hxx>
39 #include <simgear/structure/commands.hxx>
41 #include "metarproperties.hxx"
42 #include "metarairportfilter.hxx"
43 #include "fgmetar.hxx"
44 #include <Network/HTTPClient.hxx>
45 #include <Main/fg_props.hxx>
47 namespace Environment {
50 /* -------------------------------------------------------------------------------- */
52 class MetarDataHandler {
54 virtual void handleMetarData( const std::string & data ) = 0;
57 class MetarRequester {
59 virtual void requestMetar( MetarDataHandler * metarDataHandler, const std::string & id ) = 0;
62 /* -------------------------------------------------------------------------------- */
64 class LiveMetarProperties : public MetarProperties, MetarDataHandler {
66 LiveMetarProperties( SGPropertyNode_ptr rootNode, MetarRequester * metarRequester, int maxAge );
67 virtual ~LiveMetarProperties();
68 virtual void update( double dt );
70 virtual double getTimeToLive() const { return _timeToLive; }
71 virtual void resetTimeToLive()
72 { _timeToLive = 0.00; _pollingTimer = 0.0; }
74 // implementation of MetarDataHandler
75 virtual void handleMetarData( const std::string & data );
77 static const unsigned MAX_POLLING_INTERVAL_SECONDS = 10;
78 static const unsigned DEFAULT_TIME_TO_LIVE_SECONDS = 900;
83 MetarRequester * _metarRequester;
87 typedef SGSharedPtr<LiveMetarProperties> LiveMetarProperties_ptr;
89 LiveMetarProperties::LiveMetarProperties( SGPropertyNode_ptr rootNode, MetarRequester * metarRequester, int maxAge ) :
90 MetarProperties( rootNode ),
93 _metarRequester(metarRequester),
96 _tiedProperties.Tie("time-to-live", &_timeToLive );
99 LiveMetarProperties::~LiveMetarProperties()
101 _tiedProperties.Untie();
104 void LiveMetarProperties::update( double dt )
108 if( _timeToLive <= 0.0 ) {
110 std::string stationId = getStationId();
111 if( stationId.empty() ) return;
112 if( _pollingTimer > 0.0 ) return;
113 _metarRequester->requestMetar( this, stationId );
114 _pollingTimer = MAX_POLLING_INTERVAL_SECONDS;
118 void LiveMetarProperties::handleMetarData( const std::string & data )
120 SG_LOG( SG_ENVIRONMENT, SG_DEBUG, "LiveMetarProperties::handleMetarData() received METAR for " << getStationId() << ": " << data );
121 _timeToLive = DEFAULT_TIME_TO_LIVE_SECONDS;
123 SGSharedPtr<FGMetar> m;
125 m = new FGMetar(data.c_str());
127 catch( sg_io_exception ) {
128 SG_LOG( SG_ENVIRONMENT, SG_WARN, "Can't parse metar: " << data );
132 if (_maxAge && (m->getAge_min() > _maxAge)) {
133 // METAR is older than max-age, ignore
134 SG_LOG( SG_ENVIRONMENT, SG_DEBUG, "Ignoring outdated METAR for " << getStationId());
141 /* -------------------------------------------------------------------------------- */
143 class BasicRealWxController : public RealWxController
146 BasicRealWxController( SGPropertyNode_ptr rootNode, MetarRequester * metarRequester );
147 virtual ~BasicRealWxController ();
149 virtual void init ();
150 virtual void reinit ();
151 virtual void shutdown ();
154 * Create a metar-property binding at the specified property path,
155 * and initiate a request for the specified station-ID (which may be
156 * empty). If the property path is already mapped, the station ID
159 void addMetarAtPath(const string& propPath, const string& icao);
161 void removeMetarAtPath(const string& propPath);
165 void update( double dt );
167 void checkNearbyMetar();
169 long getMetarMaxAgeMin() const { return _max_age_n == NULL ? 0 : _max_age_n->getLongValue(); }
171 SGPropertyNode_ptr _rootNode;
172 SGPropertyNode_ptr _ground_elevation_n;
173 SGPropertyNode_ptr _max_age_n;
177 simgear::TiedPropertyList _tiedProperties;
178 typedef std::vector<LiveMetarProperties_ptr> MetarPropertiesList;
179 MetarPropertiesList _metarProperties;
180 MetarRequester* _requester;
184 static bool commandRequestMetar(const SGPropertyNode* arg)
186 SGSubsystemGroup* envMgr = (SGSubsystemGroup*) globals->get_subsystem("environment");
191 BasicRealWxController* self = (BasicRealWxController*) envMgr->get_subsystem("realwx");
196 string icao(arg->getStringValue("station"));
197 boost::to_upper(icao);
198 string path = arg->getStringValue("path");
199 self->addMetarAtPath(path, icao);
203 static bool commandClearMetar(const SGPropertyNode* arg)
205 SGSubsystemGroup* envMgr = (SGSubsystemGroup*) globals->get_subsystem("environment");
210 BasicRealWxController* self = (BasicRealWxController*) envMgr->get_subsystem("realwx");
215 string path = arg->getStringValue("path");
216 self->removeMetarAtPath(path);
220 /* -------------------------------------------------------------------------------- */
223 ~/enabled: bool Enables/Disables the realwx controller
224 ~/metar[1..n]: string Target property path for metar data
227 BasicRealWxController::BasicRealWxController( SGPropertyNode_ptr rootNode, MetarRequester * metarRequester ) :
229 _ground_elevation_n( fgGetNode( "/position/ground-elev-m", true )),
230 _max_age_n( fgGetNode( "/environment/params/metar-max-age-min", false ) ),
233 _requester(metarRequester)
235 // at least instantiate MetarProperties for /environment/metar
236 _metarProperties.push_back( new LiveMetarProperties(
237 fgGetNode( rootNode->getStringValue("metar", "/environment/metar"), true ),
239 getMetarMaxAgeMin()));
241 BOOST_FOREACH( SGPropertyNode_ptr n, rootNode->getChildren("metar") ) {
242 SGPropertyNode_ptr metarNode = fgGetNode( n->getStringValue(), true );
243 addMetarAtPath(metarNode->getPath(), "");
246 SGCommandMgr::instance()->addCommand("request-metar", commandRequestMetar);
247 SGCommandMgr::instance()->addCommand("clear-metar", commandClearMetar);
250 BasicRealWxController::~BasicRealWxController()
252 //SGCommandMgr::instance()->removeCommand("request-metar");
255 void BasicRealWxController::init()
260 update(0); // fetch data ASAP
262 globals->get_event_mgr()->addTask("checkNearbyMetar", this,
263 &BasicRealWxController::checkNearbyMetar, 60 );
266 void BasicRealWxController::reinit()
270 update(0); // fetch data ASAP
273 void BasicRealWxController::shutdown()
275 globals->get_event_mgr()->removeTask("checkNearbyMetar");
278 void BasicRealWxController::bind()
280 _tiedProperties.setRoot( _rootNode );
281 _tiedProperties.Tie( "enabled", &_enabled );
284 void BasicRealWxController::unbind()
286 _tiedProperties.Untie();
289 void BasicRealWxController::update( double dt )
292 bool firstIteration = !_wasEnabled;
293 // clock tick for every METAR in stock
294 BOOST_FOREACH(LiveMetarProperties* p, _metarProperties) {
295 // first round? All received METARs are outdated
296 if( firstIteration ) p->resetTimeToLive();
306 void BasicRealWxController::addMetarAtPath(const string& propPath, const string& icao)
308 // check for duplicate entries
309 BOOST_FOREACH( LiveMetarProperties_ptr p, _metarProperties ) {
310 if( p->get_root_node()->getPath() == propPath ) {
312 if (p->getStationId() != icao) {
313 p->setStationId(icao);
314 p->resetTimeToLive();
319 } // of exitsing metar properties iteration
321 SGPropertyNode_ptr metarNode = fgGetNode(propPath, true);
322 SG_LOG( SG_ENVIRONMENT, SG_INFO, "Adding metar properties at " << propPath );
323 LiveMetarProperties_ptr p(new LiveMetarProperties( metarNode, _requester, getMetarMaxAgeMin() ));
324 _metarProperties.push_back(p);
325 p->setStationId(icao);
328 void BasicRealWxController::removeMetarAtPath(const string &propPath)
330 MetarPropertiesList::iterator it = _metarProperties.begin();
331 for (; it != _metarProperties.end(); ++it) {
332 LiveMetarProperties_ptr p(*it);
333 if( p->get_root_node()->getPath() == propPath ) {
334 _metarProperties.erase(it);
335 // final ref will drop, and delete the MetarProperties, when we return
340 SG_LOG(SG_ENVIRONMENT, SG_WARN, "no metar properties at " << propPath);
343 void BasicRealWxController::checkNearbyMetar()
346 const SGGeod & pos = globals->get_aircraft_position();
348 // check nearest airport
349 SG_LOG(SG_ENVIRONMENT, SG_DEBUG, "NoaaMetarRealWxController::update(): (re) checking nearby airport with METAR" );
351 FGAirport * nearestAirport = FGAirport::findClosest(pos, 10000.0, MetarAirportFilter::instance() );
352 if( nearestAirport == NULL ) {
353 SG_LOG(SG_ENVIRONMENT,SG_WARN,"RealWxController::update can't find airport with METAR within 10000NM" );
357 SG_LOG(SG_ENVIRONMENT, SG_DEBUG,
358 "NoaaMetarRealWxController::update(): nearest airport with METAR is: " << nearestAirport->ident() );
360 // if it has changed, invalidate the associated METAR
361 if( _metarProperties[0]->getStationId() != nearestAirport->ident() ) {
362 SG_LOG(SG_ENVIRONMENT, SG_INFO,
363 "NoaaMetarRealWxController::update(): nearest airport with METAR has changed. Old: '" <<
364 _metarProperties[0]->getStationId() <<
365 "', new: '" << nearestAirport->ident() << "'" );
366 _metarProperties[0]->setStationId( nearestAirport->ident() );
367 _metarProperties[0]->resetTimeToLive();
370 catch( sg_exception & ) {
376 /* -------------------------------------------------------------------------------- */
378 class NoaaMetarRealWxController : public BasicRealWxController, MetarRequester {
380 NoaaMetarRealWxController( SGPropertyNode_ptr rootNode );
382 // implementation of MetarRequester
383 virtual void requestMetar( MetarDataHandler * metarDataHandler, const std::string & id );
389 NoaaMetarRealWxController::NoaaMetarRealWxController( SGPropertyNode_ptr rootNode ) :
390 BasicRealWxController(rootNode, this )
394 void NoaaMetarRealWxController::requestMetar( MetarDataHandler * metarDataHandler, const std::string & id )
396 class NoaaMetarGetRequest : public simgear::HTTP::Request
399 NoaaMetarGetRequest(MetarDataHandler* metarDataHandler, const string& stationId ) :
400 Request("http://weather.noaa.gov/pub/data/observations/metar/stations/" + stationId + ".TXT"),
402 _metarDataHandler(metarDataHandler)
406 virtual string_list requestHeaders() const
409 reply.push_back("X-TIME");
413 virtual std::string header(const std::string& name) const
417 if( name == "X-TIME" ) {
418 std::ostringstream buf;
419 buf << globals->get_time_params()->get_cur_time();
426 virtual void responseHeader(const string& key, const string& value)
428 if (key == "x-metarproxy") {
433 virtual void gotBodyData(const char* s, int n)
435 _metar += string(s, n);
438 virtual void responseComplete()
440 if (responseCode() == 200) {
441 _metarDataHandler->handleMetarData( simgear::strutils::simplify(_metar) );
443 SG_LOG(SG_ENVIRONMENT, SG_WARN, "metar download failed:" << url() << ": reason:" << responseReason());
447 virtual void failed()
449 SG_LOG(SG_ENVIRONMENT, SG_INFO, "metar download failure");
452 // bool fromMetarProxy() const
453 // { return _fromProxy; }
457 MetarDataHandler * _metarDataHandler;
460 string upperId = boost::to_upper_copy(id);
462 SG_LOG(SG_ENVIRONMENT, SG_INFO,
463 "NoaaMetarRealWxController::update(): spawning load request for station-id '" << upperId << "'" );
464 FGHTTPClient* http = static_cast<FGHTTPClient*>(globals->get_subsystem("http"));
466 http->makeRequest(new NoaaMetarGetRequest(metarDataHandler, upperId));
470 /* -------------------------------------------------------------------------------- */
472 RealWxController * RealWxController::createInstance( SGPropertyNode_ptr rootNode )
474 return new NoaaMetarRealWxController( rootNode );
477 /* -------------------------------------------------------------------------------- */
479 } // namespace Environment