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/HTTPMemoryRequest.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;
55 virtual void handleMetarFailure() = 0;
58 class MetarRequester {
60 virtual void requestMetar( MetarDataHandler * metarDataHandler, const std::string & id ) = 0;
63 /* -------------------------------------------------------------------------------- */
65 class LiveMetarProperties : public MetarProperties, MetarDataHandler {
67 LiveMetarProperties( SGPropertyNode_ptr rootNode, MetarRequester * metarRequester, int maxAge );
68 virtual ~LiveMetarProperties();
69 virtual void update( double dt );
71 virtual double getTimeToLive() const { return _timeToLive; }
72 virtual void resetTimeToLive()
73 { _timeToLive = 0.00; _pollingTimer = 0.0; }
75 // implementation of MetarDataHandler
76 virtual void handleMetarData( const std::string & data );
77 virtual void handleMetarFailure();
79 static const unsigned MAX_POLLING_INTERVAL_SECONDS = 10;
80 static const unsigned DEFAULT_TIME_TO_LIVE_SECONDS = 900;
85 MetarRequester * _metarRequester;
90 typedef SGSharedPtr<LiveMetarProperties> LiveMetarProperties_ptr;
92 LiveMetarProperties::LiveMetarProperties( SGPropertyNode_ptr rootNode, MetarRequester * metarRequester, int maxAge ) :
93 MetarProperties( rootNode ),
96 _metarRequester(metarRequester),
100 _tiedProperties.Tie("time-to-live", &_timeToLive );
101 _tiedProperties.Tie("failure", &_failure);
104 LiveMetarProperties::~LiveMetarProperties()
106 _tiedProperties.Untie();
109 void LiveMetarProperties::update( double dt )
113 if( _timeToLive <= 0.0 ) {
116 std::string stationId = getStationId();
117 if( stationId.empty() ) return;
118 if( _pollingTimer > 0.0 ) return;
119 _metarRequester->requestMetar( this, stationId );
120 _pollingTimer = MAX_POLLING_INTERVAL_SECONDS;
124 void LiveMetarProperties::handleMetarData( const std::string & data )
126 SG_LOG( SG_ENVIRONMENT, SG_DEBUG, "LiveMetarProperties::handleMetarData() received METAR for " << getStationId() << ": " << data );
127 _timeToLive = DEFAULT_TIME_TO_LIVE_SECONDS;
129 SGSharedPtr<FGMetar> m;
131 m = new FGMetar(data.c_str());
133 catch( sg_io_exception ) {
134 SG_LOG( SG_ENVIRONMENT, SG_WARN, "Can't parse metar: " << data );
139 if (_maxAge && (m->getAge_min() > _maxAge)) {
140 // METAR is older than max-age, ignore
141 SG_LOG( SG_ENVIRONMENT, SG_DEBUG, "Ignoring outdated METAR for " << getStationId());
149 void LiveMetarProperties::handleMetarFailure()
154 /* -------------------------------------------------------------------------------- */
156 class BasicRealWxController : public RealWxController
159 BasicRealWxController( SGPropertyNode_ptr rootNode, MetarRequester * metarRequester );
160 virtual ~BasicRealWxController ();
162 virtual void init ();
163 virtual void reinit ();
164 virtual void shutdown ();
167 * Create a metar-property binding at the specified property path,
168 * and initiate a request for the specified station-ID (which may be
169 * empty). If the property path is already mapped, the station ID
172 void addMetarAtPath(const string& propPath, const string& icao);
174 void removeMetarAtPath(const string& propPath);
178 void update( double dt );
180 void checkNearbyMetar();
182 long getMetarMaxAgeMin() const { return _max_age_n == NULL ? 0 : _max_age_n->getLongValue(); }
184 SGPropertyNode_ptr _rootNode;
185 SGPropertyNode_ptr _ground_elevation_n;
186 SGPropertyNode_ptr _max_age_n;
190 simgear::TiedPropertyList _tiedProperties;
191 typedef std::vector<LiveMetarProperties_ptr> MetarPropertiesList;
192 MetarPropertiesList _metarProperties;
193 MetarRequester* _requester;
197 static bool commandRequestMetar(const SGPropertyNode* arg)
199 SGSubsystemGroup* envMgr = (SGSubsystemGroup*) globals->get_subsystem("environment");
204 BasicRealWxController* self = (BasicRealWxController*) envMgr->get_subsystem("realwx");
209 string icao(arg->getStringValue("station"));
210 boost::to_upper(icao);
211 string path = arg->getStringValue("path");
212 self->addMetarAtPath(path, icao);
216 static bool commandClearMetar(const SGPropertyNode* arg)
218 SGSubsystemGroup* envMgr = (SGSubsystemGroup*) globals->get_subsystem("environment");
223 BasicRealWxController* self = (BasicRealWxController*) envMgr->get_subsystem("realwx");
228 string path = arg->getStringValue("path");
229 self->removeMetarAtPath(path);
233 /* -------------------------------------------------------------------------------- */
236 ~/enabled: bool Enables/Disables the realwx controller
237 ~/metar[1..n]: string Target property path for metar data
240 BasicRealWxController::BasicRealWxController( SGPropertyNode_ptr rootNode, MetarRequester * metarRequester ) :
242 _ground_elevation_n( fgGetNode( "/position/ground-elev-m", true )),
243 _max_age_n( fgGetNode( "/environment/params/metar-max-age-min", false ) ),
246 _requester(metarRequester)
249 globals->get_commands()->addCommand("request-metar", commandRequestMetar);
250 globals->get_commands()->addCommand("clear-metar", commandClearMetar);
253 BasicRealWxController::~BasicRealWxController()
255 globals->get_commands()->removeCommand("request-metar");
256 globals->get_commands()->removeCommand("clear-metar");
259 void BasicRealWxController::init()
263 // at least instantiate MetarProperties for /environment/metar
264 SGPropertyNode_ptr metarNode = fgGetNode( _rootNode->getStringValue("metar", "/environment/metar"), true );
265 _metarProperties.push_back( new LiveMetarProperties(metarNode,
267 getMetarMaxAgeMin()));
269 BOOST_FOREACH( SGPropertyNode_ptr n, _rootNode->getChildren("metar") ) {
270 SGPropertyNode_ptr metarNode = fgGetNode( n->getStringValue(), true );
271 addMetarAtPath(metarNode->getPath(), "");
275 update(0); // fetch data ASAP
277 globals->get_event_mgr()->addTask("checkNearbyMetar", this,
278 &BasicRealWxController::checkNearbyMetar, 60 );
281 void BasicRealWxController::reinit()
285 update(0); // fetch data ASAP
288 void BasicRealWxController::shutdown()
290 globals->get_event_mgr()->removeTask("checkNearbyMetar");
293 void BasicRealWxController::bind()
295 _tiedProperties.setRoot( _rootNode );
296 _tiedProperties.Tie( "enabled", &_enabled );
299 void BasicRealWxController::unbind()
301 _tiedProperties.Untie();
304 void BasicRealWxController::update( double dt )
307 bool firstIteration = !_wasEnabled;
308 // clock tick for every METAR in stock
309 BOOST_FOREACH(LiveMetarProperties* p, _metarProperties) {
310 // first round? All received METARs are outdated
311 if( firstIteration ) p->resetTimeToLive();
321 void BasicRealWxController::addMetarAtPath(const string& propPath, const string& icao)
323 // check for duplicate entries
324 BOOST_FOREACH( LiveMetarProperties_ptr p, _metarProperties ) {
325 if( p->get_root_node()->getPath() == propPath ) {
327 if (p->getStationId() != icao) {
328 p->setStationId(icao);
329 p->resetTimeToLive();
334 } // of exitsing metar properties iteration
336 SGPropertyNode_ptr metarNode = fgGetNode(propPath, true);
337 SG_LOG( SG_ENVIRONMENT, SG_INFO, "Adding metar properties at " << propPath );
338 LiveMetarProperties_ptr p(new LiveMetarProperties( metarNode, _requester, getMetarMaxAgeMin() ));
339 _metarProperties.push_back(p);
340 p->setStationId(icao);
343 void BasicRealWxController::removeMetarAtPath(const string &propPath)
345 MetarPropertiesList::iterator it = _metarProperties.begin();
346 for (; it != _metarProperties.end(); ++it) {
347 LiveMetarProperties_ptr p(*it);
348 if( p->get_root_node()->getPath() == propPath ) {
349 _metarProperties.erase(it);
350 // final ref will drop, and delete the MetarProperties, when we return
355 SG_LOG(SG_ENVIRONMENT, SG_WARN, "no metar properties at " << propPath);
358 void BasicRealWxController::checkNearbyMetar()
361 const SGGeod & pos = globals->get_aircraft_position();
363 // check nearest airport
364 SG_LOG(SG_ENVIRONMENT, SG_DEBUG, "NoaaMetarRealWxController::update(): (re) checking nearby airport with METAR" );
366 FGAirport * nearestAirport = FGAirport::findClosest(pos, 10000.0, MetarAirportFilter::instance() );
367 if( nearestAirport == NULL ) {
368 SG_LOG(SG_ENVIRONMENT,SG_WARN,"RealWxController::update can't find airport with METAR within 10000NM" );
372 SG_LOG(SG_ENVIRONMENT, SG_DEBUG,
373 "NoaaMetarRealWxController::update(): nearest airport with METAR is: " << nearestAirport->ident() );
375 // if it has changed, invalidate the associated METAR
376 if( _metarProperties[0]->getStationId() != nearestAirport->ident() ) {
377 SG_LOG(SG_ENVIRONMENT, SG_INFO,
378 "NoaaMetarRealWxController::update(): nearest airport with METAR has changed. Old: '" <<
379 _metarProperties[0]->getStationId() <<
380 "', new: '" << nearestAirport->ident() << "'" );
381 _metarProperties[0]->setStationId( nearestAirport->ident() );
382 _metarProperties[0]->resetTimeToLive();
385 catch( sg_exception & ) {
391 /* -------------------------------------------------------------------------------- */
393 class NoaaMetarRealWxController : public BasicRealWxController, MetarRequester {
395 NoaaMetarRealWxController( SGPropertyNode_ptr rootNode );
397 // implementation of MetarRequester
398 virtual void requestMetar( MetarDataHandler * metarDataHandler, const std::string & id );
400 virtual ~NoaaMetarRealWxController()
407 NoaaMetarRealWxController::NoaaMetarRealWxController( SGPropertyNode_ptr rootNode ) :
408 BasicRealWxController(rootNode, this )
412 void NoaaMetarRealWxController::requestMetar
414 MetarDataHandler* metarDataHandler,
415 const std::string& id
418 static const std::string NOAA_BASE_URL =
419 "http://weather.noaa.gov/pub/data/observations/metar/stations/";
420 class NoaaMetarGetRequest:
421 public simgear::HTTP::MemoryRequest
424 NoaaMetarGetRequest( MetarDataHandler* metarDataHandler,
425 const std::string& stationId ):
426 MemoryRequest(NOAA_BASE_URL + stationId + ".TXT"),
427 _metarDataHandler(metarDataHandler)
429 std::ostringstream buf;
430 buf << globals->get_time_params()->get_cur_time();
431 requestHeader("X-TIME") = buf.str();
434 virtual void onDone()
436 if( responseCode() != 200 )
442 "metar download failed:" << url() << ": reason:" << responseReason()
447 _metarDataHandler->handleMetarData
449 simgear::strutils::simplify(responseBody())
453 virtual void onFail()
455 SG_LOG(SG_ENVIRONMENT, SG_INFO, "metar download failure");
456 _metarDataHandler->handleMetarFailure();
460 MetarDataHandler * _metarDataHandler;
463 string upperId = boost::to_upper_copy(id);
469 "NoaaMetarRealWxController::update(): "
470 "spawning load request for station-id '" << upperId << "'"
472 FGHTTPClient* http = static_cast<FGHTTPClient*>(globals->get_subsystem("http"));
474 http->makeRequest(new NoaaMetarGetRequest(metarDataHandler, upperId));
478 /* -------------------------------------------------------------------------------- */
480 RealWxController * RealWxController::createInstance( SGPropertyNode_ptr rootNode )
482 return new NoaaMetarRealWxController( rootNode );
485 RealWxController::~RealWxController()
489 /* -------------------------------------------------------------------------------- */
491 } // namespace Environment