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 );
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;
86 typedef SGSharedPtr<LiveMetarProperties> LiveMetarProperties_ptr;
88 LiveMetarProperties::LiveMetarProperties( SGPropertyNode_ptr rootNode, MetarRequester * metarRequester ) :
89 MetarProperties( rootNode ),
92 _metarRequester(metarRequester)
94 _tiedProperties.Tie("time-to-live", &_timeToLive );
97 LiveMetarProperties::~LiveMetarProperties()
99 _tiedProperties.Untie();
102 void LiveMetarProperties::update( double dt )
106 if( _timeToLive <= 0.0 ) {
108 std::string stationId = getStationId();
109 if( stationId.empty() ) return;
110 if( _pollingTimer > 0.0 ) return;
111 _metarRequester->requestMetar( this, stationId );
112 _pollingTimer = MAX_POLLING_INTERVAL_SECONDS;
116 void LiveMetarProperties::handleMetarData( const std::string & data )
118 SG_LOG( SG_ENVIRONMENT, SG_INFO, "LiveMetarProperties::handleMetarData() received METAR for " << getStationId() << ": " << data );
119 _timeToLive = DEFAULT_TIME_TO_LIVE_SECONDS;
123 /* -------------------------------------------------------------------------------- */
125 class BasicRealWxController : public RealWxController
128 BasicRealWxController( SGPropertyNode_ptr rootNode, MetarRequester * metarRequester );
129 virtual ~BasicRealWxController ();
131 virtual void init ();
132 virtual void reinit ();
133 virtual void shutdown ();
136 * Create a metar-property binding at the specified property path,
137 * and initiate a request for the specified station-ID (which may be
138 * empty). If the property path is already mapped, the station ID
141 void addMetarAtPath(const string& propPath, const string& icao);
143 void removeMetarAtPath(const string& propPath);
147 void update( double dt );
149 void checkNearbyMetar();
151 long getMetarMaxAgeMin() const { return _max_age_n == NULL ? 0 : _max_age_n->getLongValue(); }
153 SGPropertyNode_ptr _rootNode;
154 SGPropertyNode_ptr _ground_elevation_n;
155 SGPropertyNode_ptr _max_age_n;
159 simgear::TiedPropertyList _tiedProperties;
160 typedef std::vector<LiveMetarProperties_ptr> MetarPropertiesList;
161 MetarPropertiesList _metarProperties;
162 MetarRequester* _requester;
166 static bool commandRequestMetar(const SGPropertyNode* arg)
168 SGSubsystemGroup* envMgr = (SGSubsystemGroup*) globals->get_subsystem("environment");
173 BasicRealWxController* self = (BasicRealWxController*) envMgr->get_subsystem("realwx");
178 string icao(arg->getStringValue("station"));
179 boost::to_upper(icao);
180 string path = arg->getStringValue("path");
181 self->addMetarAtPath(path, icao);
185 static bool commandClearMetar(const SGPropertyNode* arg)
187 SGSubsystemGroup* envMgr = (SGSubsystemGroup*) globals->get_subsystem("environment");
192 BasicRealWxController* self = (BasicRealWxController*) envMgr->get_subsystem("realwx");
197 string path = arg->getStringValue("path");
198 self->removeMetarAtPath(path);
202 /* -------------------------------------------------------------------------------- */
205 ~/enabled: bool Enables/Disables the realwx controller
206 ~/metar[1..n]: string Target property path for metar data
209 BasicRealWxController::BasicRealWxController( SGPropertyNode_ptr rootNode, MetarRequester * metarRequester ) :
211 _ground_elevation_n( fgGetNode( "/position/ground-elev-m", true )),
212 _max_age_n( fgGetNode( "/environment/params/metar-max-age-min", false ) ),
215 _requester(metarRequester)
217 // at least instantiate MetarProperties for /environment/metar
218 _metarProperties.push_back( new LiveMetarProperties(
219 fgGetNode( rootNode->getStringValue("metar", "/environment/metar"), true ), metarRequester ));
221 BOOST_FOREACH( SGPropertyNode_ptr n, rootNode->getChildren("metar") ) {
222 SGPropertyNode_ptr metarNode = fgGetNode( n->getStringValue(), true );
223 addMetarAtPath(metarNode->getPath(), "");
226 SGCommandMgr::instance()->addCommand("request-metar", commandRequestMetar);
227 SGCommandMgr::instance()->addCommand("clear-metar", commandClearMetar);
230 BasicRealWxController::~BasicRealWxController()
232 //SGCommandMgr::instance()->removeCommand("request-metar");
235 void BasicRealWxController::init()
240 update(0); // fetch data ASAP
242 globals->get_event_mgr()->addTask("checkNearbyMetar", this,
243 &BasicRealWxController::checkNearbyMetar, 60 );
246 void BasicRealWxController::reinit()
250 update(0); // fetch data ASAP
253 void BasicRealWxController::shutdown()
255 globals->get_event_mgr()->removeTask("checkNearbyMetar");
258 void BasicRealWxController::bind()
260 _tiedProperties.setRoot( _rootNode );
261 _tiedProperties.Tie( "enabled", &_enabled );
264 void BasicRealWxController::unbind()
266 _tiedProperties.Untie();
269 void BasicRealWxController::update( double dt )
272 bool firstIteration = !_wasEnabled;
273 // clock tick for every METAR in stock
274 BOOST_FOREACH(LiveMetarProperties* p, _metarProperties) {
275 // first round? All received METARs are outdated
276 if( firstIteration ) p->resetTimeToLive();
286 void BasicRealWxController::addMetarAtPath(const string& propPath, const string& icao)
288 // check for duplicate entries
289 BOOST_FOREACH( LiveMetarProperties_ptr p, _metarProperties ) {
290 if( p->get_root_node()->getPath() == propPath ) {
292 if (p->getStationId() != icao) {
293 p->setStationId(icao);
294 p->resetTimeToLive();
299 } // of exitsing metar properties iteration
301 SGPropertyNode_ptr metarNode = fgGetNode(propPath, true);
302 SG_LOG( SG_ENVIRONMENT, SG_INFO, "Adding metar properties at " << propPath );
303 LiveMetarProperties_ptr p(new LiveMetarProperties( metarNode, _requester ));
304 _metarProperties.push_back(p);
305 p->setStationId(icao);
308 void BasicRealWxController::removeMetarAtPath(const string &propPath)
310 MetarPropertiesList::iterator it = _metarProperties.begin();
311 for (; it != _metarProperties.end(); ++it) {
312 LiveMetarProperties_ptr p(*it);
313 if( p->get_root_node()->getPath() == propPath ) {
314 _metarProperties.erase(it);
315 // final ref will drop, and delete the MetarProperties, when we return
320 SG_LOG(SG_ENVIRONMENT, SG_WARN, "no metar properties at " << propPath);
323 void BasicRealWxController::checkNearbyMetar()
326 const SGGeod & pos = globals->get_aircraft_position();
328 // check nearest airport
329 SG_LOG(SG_ENVIRONMENT, SG_DEBUG, "NoaaMetarRealWxController::update(): (re) checking nearby airport with METAR" );
331 FGAirport * nearestAirport = FGAirport::findClosest(pos, 10000.0, MetarAirportFilter::instance() );
332 if( nearestAirport == NULL ) {
333 SG_LOG(SG_ENVIRONMENT,SG_WARN,"RealWxController::update can't find airport with METAR within 10000NM" );
337 SG_LOG(SG_ENVIRONMENT, SG_DEBUG,
338 "NoaaMetarRealWxController::update(): nearest airport with METAR is: " << nearestAirport->ident() );
340 // if it has changed, invalidate the associated METAR
341 if( _metarProperties[0]->getStationId() != nearestAirport->ident() ) {
342 SG_LOG(SG_ENVIRONMENT, SG_INFO,
343 "NoaaMetarRealWxController::update(): nearest airport with METAR has changed. Old: '" <<
344 _metarProperties[0]->getStationId() <<
345 "', new: '" << nearestAirport->ident() << "'" );
346 _metarProperties[0]->setStationId( nearestAirport->ident() );
347 _metarProperties[0]->resetTimeToLive();
350 catch( sg_exception & ) {
356 /* -------------------------------------------------------------------------------- */
358 class NoaaMetarRealWxController : public BasicRealWxController, MetarRequester {
360 NoaaMetarRealWxController( SGPropertyNode_ptr rootNode );
362 // implementation of MetarRequester
363 virtual void requestMetar( MetarDataHandler * metarDataHandler, const std::string & id );
369 NoaaMetarRealWxController::NoaaMetarRealWxController( SGPropertyNode_ptr rootNode ) :
370 BasicRealWxController(rootNode, this )
374 void NoaaMetarRealWxController::requestMetar( MetarDataHandler * metarDataHandler, const std::string & id )
376 class NoaaMetarGetRequest : public simgear::HTTP::Request
379 NoaaMetarGetRequest(MetarDataHandler* metarDataHandler, const string& stationId ) :
380 Request("http://weather.noaa.gov/pub/data/observations/metar/stations/" + stationId + ".TXT"),
382 _metarDataHandler(metarDataHandler)
386 virtual string_list requestHeaders() const
389 reply.push_back("X-TIME");
393 virtual std::string header(const std::string& name) const
397 if( name == "X-TIME" ) {
398 std::ostringstream buf;
399 buf << globals->get_time_params()->get_cur_time();
406 virtual void responseHeader(const string& key, const string& value)
408 if (key == "x-metarproxy") {
413 virtual void gotBodyData(const char* s, int n)
415 _metar += string(s, n);
418 virtual void responseComplete()
420 if (responseCode() == 200) {
421 _metarDataHandler->handleMetarData( simgear::strutils::simplify(_metar) );
423 SG_LOG(SG_ENVIRONMENT, SG_WARN, "metar download failed:" << url() << ": reason:" << responseReason());
427 virtual void failed()
429 SG_LOG(SG_ENVIRONMENT, SG_INFO, "metar download failure");
432 // bool fromMetarProxy() const
433 // { return _fromProxy; }
437 MetarDataHandler * _metarDataHandler;
440 string upperId = boost::to_upper_copy(id);
442 SG_LOG(SG_ENVIRONMENT, SG_INFO,
443 "NoaaMetarRealWxController::update(): spawning load request for station-id '" << upperId << "'" );
444 FGHTTPClient* http = static_cast<FGHTTPClient*>(globals->get_subsystem("http"));
446 http->makeRequest(new NoaaMetarGetRequest(metarDataHandler, upperId));
450 /* -------------------------------------------------------------------------------- */
452 RealWxController * RealWxController::createInstance( SGPropertyNode_ptr rootNode )
454 return new NoaaMetarRealWxController( rootNode );
457 /* -------------------------------------------------------------------------------- */
459 } // namespace Environment