1 // realwx_ctrl.cxx -- Process real weather data
3 // Written by David Megginson, started February 2002.
4 // Rewritten by Torsten Dreyer, August 2010
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"
28 #include "metarproperties.hxx"
29 #include "metarairportfilter.hxx"
30 #include "fgmetar.hxx"
32 #include <Main/fg_props.hxx>
34 #include <boost/foreach.hpp>
36 #include <simgear/structure/exception.hxx>
37 #include <simgear/misc/strutils.hxx>
38 #include <simgear/props/tiedpropertylist.hxx>
39 #include <simgear/io/HTTPClient.hxx>
40 #include <simgear/io/HTTPRequest.hxx>
41 #include <simgear/timing/sg_time.hxx>
45 using simgear::PropertyList;
47 namespace Environment {
49 /* -------------------------------------------------------------------------------- */
51 class LiveMetarProperties : public MetarProperties {
53 LiveMetarProperties( SGPropertyNode_ptr rootNode );
54 virtual ~LiveMetarProperties();
55 virtual void update( double dt );
57 virtual double getTimeToLive() const { return _timeToLive; }
58 virtual void setTimeToLive( double value ) { _timeToLive = value; }
64 typedef SGSharedPtr<LiveMetarProperties> LiveMetarProperties_ptr;
66 LiveMetarProperties::LiveMetarProperties( SGPropertyNode_ptr rootNode ) :
67 MetarProperties( rootNode ),
70 _tiedProperties.Tie("time-to-live", &_timeToLive );
73 LiveMetarProperties::~LiveMetarProperties()
75 _tiedProperties.Untie();
78 void LiveMetarProperties::update( double dt )
81 if( _timeToLive < 0.0 ) _timeToLive = 0.0;
84 /* -------------------------------------------------------------------------------- */
86 class BasicRealWxController : public RealWxController
89 BasicRealWxController( SGPropertyNode_ptr rootNode );
90 virtual ~BasicRealWxController ();
93 virtual void reinit ();
98 void update( double dt );
100 virtual void update( bool first, double dt ) = 0;
102 long getMetarMaxAgeMin() const { return _max_age_n == NULL ? 0 : _max_age_n->getLongValue(); }
104 SGPropertyNode_ptr _rootNode;
105 SGPropertyNode_ptr _longitude_n;
106 SGPropertyNode_ptr _latitude_n;
107 SGPropertyNode_ptr _ground_elevation_n;
108 SGPropertyNode_ptr _max_age_n;
112 simgear::TiedPropertyList _tiedProperties;
113 typedef std::vector<LiveMetarProperties_ptr> MetarPropertiesList;
114 MetarPropertiesList _metarProperties;
118 /* -------------------------------------------------------------------------------- */
121 ~/enabled: bool Enables/Disables the realwx controller
122 ~/metar[1..n]: string Target property path for metar data
125 BasicRealWxController::BasicRealWxController( SGPropertyNode_ptr rootNode ) :
127 _longitude_n( fgGetNode( "/position/longitude-deg", true )),
128 _latitude_n( fgGetNode( "/position/latitude-deg", true )),
129 _ground_elevation_n( fgGetNode( "/position/ground-elev-m", true )),
130 _max_age_n( fgGetNode( "/environment/params/metar-max-age-min", false ) ),
134 // at least instantiate MetarProperties for /environment/metar
135 _metarProperties.push_back( new LiveMetarProperties(
136 fgGetNode( rootNode->getStringValue("metar", "/environment/metar"), true ) ) );
138 PropertyList metars = rootNode->getChildren("metar");
139 for( PropertyList::size_type i = 1; i < metars.size(); i++ ) {
140 SG_LOG( SG_ALL, SG_INFO, "Adding metar properties at " << metars[i]->getStringValue() );
141 _metarProperties.push_back( new LiveMetarProperties(
142 fgGetNode( metars[i]->getStringValue(), true )));
146 BasicRealWxController::~BasicRealWxController()
150 void BasicRealWxController::init()
153 update(0); // fetch data ASAP
156 void BasicRealWxController::reinit()
161 void BasicRealWxController::bind()
163 _tiedProperties.setRoot( _rootNode );
164 _tiedProperties.Tie( "enabled", &_enabled );
167 void BasicRealWxController::unbind()
169 _tiedProperties.Untie();
172 void BasicRealWxController::update( double dt )
175 bool firstIteration = !__enabled; // first iteration after being enabled?
177 // clock tick for every METAR in stock
178 for( MetarPropertiesList::iterator it = _metarProperties.begin();
179 it != _metarProperties.end(); it++ ) {
180 // first round? All received METARs are outdated
181 if( firstIteration ) (*it)->setTimeToLive( 0.0 );
185 update( firstIteration, dt );
192 /* -------------------------------------------------------------------------------- */
194 class NoaaMetarRealWxController : public BasicRealWxController {
196 NoaaMetarRealWxController( SGPropertyNode_ptr rootNode );
197 virtual ~NoaaMetarRealWxController();
198 virtual void update (bool first, double delta_time_sec);
199 virtual void shutdown ();
202 * callback from MetarGetRequest when a download succeeds
204 void gotMetar(const string& stationId, const string& metar);
206 double _positionTimeToLive;
207 double _requestTimer;
209 simgear::HTTP::Client _http;
212 class MetarGetRequest : public simgear::HTTP::Request
215 MetarGetRequest(NoaaMetarRealWxController* con, const string& s) :
221 setUrl("http://weather.noaa.gov/pub/data/observations/metar/stations/" + stationId + ".TXT");
224 virtual string_list requestHeaders() const
227 r.push_back("X-Time");
231 virtual string header(const string& name) const
233 if (name == "X-Time") {
235 snprintf(buf, 16, "%ld", globals->get_time_params()->get_cur_time());
239 return Request::header(name);
242 virtual void responseHeader(const string& key, const string& value)
244 if (key == "x-metarproxy") {
249 virtual void gotBodyData(const char* s, int n)
251 metar += string(s, n);
254 virtual void responseComplete()
256 if (responseCode() == 200) {
257 wxController->gotMetar(stationId, metar);
259 SG_LOG(SG_IO, SG_WARN, "metar download failed:" << url() << ": reason:" << responseReason());
263 bool fromMetarProxy() const
264 { return fromProxy; }
269 NoaaMetarRealWxController* wxController;
274 NoaaMetarRealWxController::NoaaMetarRealWxController( SGPropertyNode_ptr rootNode ) :
275 BasicRealWxController(rootNode),
276 _positionTimeToLive(0.0),
279 string proxyHost(fgGetString("/sim/presets/proxy/host"));
280 int proxyPort(fgGetInt("/sim/presets/proxy/port"));
281 string proxyAuth(fgGetString("/sim/presets/proxy/auth"));
283 if (!proxyHost.empty()) {
284 _http.setProxy(proxyHost, proxyPort, proxyAuth);
288 void NoaaMetarRealWxController::shutdown()
292 NoaaMetarRealWxController::~NoaaMetarRealWxController()
296 void NoaaMetarRealWxController::update( bool first, double dt )
300 _positionTimeToLive -= dt;
303 if( _positionTimeToLive <= 0.0 ) {
304 // check nearest airport
305 SG_LOG(SG_ALL, SG_INFO, "NoaaMetarRealWxController::update(): (re) checking nearby airport with METAR" );
306 _positionTimeToLive = 60.0;
308 SGGeod pos = SGGeod::fromDeg(_longitude_n->getDoubleValue(), _latitude_n->getDoubleValue());
310 FGAirport * nearestAirport = FGAirport::findClosest(pos, 10000.0, MetarAirportFilter::instance() );
311 if( nearestAirport == NULL ) {
312 SG_LOG(SG_ALL,SG_WARN,"RealWxController::update can't find airport with METAR within 10000NM" );
316 SG_LOG(SG_ALL, SG_INFO,
317 "NoaaMetarRealWxController::update(): nearest airport with METAR is: " << nearestAirport->ident() );
319 // if it has changed, invalidate the associated METAR
320 if( _metarProperties[0]->getStationId() != nearestAirport->ident() ) {
321 SG_LOG(SG_ALL, SG_INFO,
322 "NoaaMetarRealWxController::update(): nearest airport with METAR has changed. Old: '" <<
323 _metarProperties[0]->getStationId() <<
324 "', new: '" << nearestAirport->ident() << "'" );
325 _metarProperties[0]->setStationId( nearestAirport->ident() );
326 _metarProperties[0]->setTimeToLive( 0.0 );
330 if( _requestTimer <= 0.0 ) {
331 _requestTimer = 10.0;
333 BOOST_FOREACH(LiveMetarProperties* p, _metarProperties) {
334 if( p->getTimeToLive() > 0.0 ) continue;
335 const std::string & stationId = p->getStationId();
336 if( stationId.empty() ) continue;
338 SG_LOG(SG_ALL, SG_INFO,
339 "NoaaMetarRealWxController::update(): spawning load request for station-id '" << stationId << "'" );
341 _http.makeRequest(new MetarGetRequest(this, stationId));
342 } // of MetarProperties iteration
346 void NoaaMetarRealWxController::gotMetar(const string& stationId, const string& metar)
348 SG_LOG( SG_ALL, SG_INFO, "NoaaMetarRwalWxController::update() received METAR for " << stationId << ": " << metar );
349 BOOST_FOREACH(LiveMetarProperties* p, _metarProperties) {
350 if (p->getStationId() != stationId)
353 p->setTimeToLive(900);
354 p->setMetar( metar );
358 /* -------------------------------------------------------------------------------- */
360 RealWxController * RealWxController::createInstance( SGPropertyNode_ptr rootNode )
362 // string dataSource = rootNode->getStringValue("data-source", "noaa" );
363 // if( dataSource == "nwx" ) {
364 // return new NwxMetarRealWxController( rootNode );
366 return new NoaaMetarRealWxController( rootNode );
370 /* -------------------------------------------------------------------------------- */
372 } // namespace Environment