]> git.mxchange.org Git - flightgear.git/blob - src/Environment/realwx_ctrl.cxx
Refactor SGSky handling and ownership - sink into Renderer, remove global variable...
[flightgear.git] / src / Environment / realwx_ctrl.cxx
1 // realwx_ctrl.cxx -- Process real weather data
2 //
3 // Written by David Megginson, started February 2002.
4 // Rewritten by Torsten Dreyer, August 2010, August 2011
5 //
6 // Copyright (C) 2002  David Megginson - david@megginson.com
7 //
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.
12 //
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.
17 //
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.
21 //
22
23 #ifdef HAVE_CONFIG_H
24 #  include "config.h"
25 #endif
26
27 #include "realwx_ctrl.hxx"
28 #include "metarproperties.hxx"
29 #include "metarairportfilter.hxx"
30 #include "fgmetar.hxx"
31
32 #include <Main/fg_props.hxx>
33
34 #include <boost/foreach.hpp>
35
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>
42 #include <simgear/structure/event_mgr.hxx>
43
44 #include <algorithm>
45
46 namespace Environment {
47 /* -------------------------------------------------------------------------------- */
48
49 class FGHTTPClient : public simgear::HTTP::Client {
50 public:
51     FGHTTPClient();
52 };
53
54 FGHTTPClient::FGHTTPClient()
55 {
56     string proxyHost(fgGetString("/sim/presets/proxy/host"));
57     int proxyPort(fgGetInt("/sim/presets/proxy/port"));
58     string proxyAuth(fgGetString("/sim/presets/proxy/auth"));
59     
60     if (!proxyHost.empty()) {
61         setProxy(proxyHost, proxyPort, proxyAuth);
62     }
63 }
64
65 /* -------------------------------------------------------------------------------- */
66
67 class MetarDataHandler {
68 public:
69     virtual void handleMetarData( const std::string & data ) = 0;
70 };
71
72 class MetarRequester {
73 public:
74     virtual void requestMetar( MetarDataHandler * metarDataHandler, const std::string & id ) = 0;
75 };
76
77 /* -------------------------------------------------------------------------------- */
78
79 class LiveMetarProperties : public MetarProperties, MetarDataHandler {
80 public:
81     LiveMetarProperties( SGPropertyNode_ptr rootNode, MetarRequester * metarRequester );
82     virtual ~LiveMetarProperties();
83     virtual void update( double dt );
84
85     virtual double getTimeToLive() const { return _timeToLive; }
86     virtual void setTimeToLive( double value ) { _timeToLive = value; }
87
88     // implementation of MetarDataHandler
89     virtual void handleMetarData( const std::string & data );
90
91     static const unsigned MAX_POLLING_INTERVAL_SECONDS = 10;
92     static const unsigned DEFAULT_TIME_TO_LIVE_SECONDS = 900;
93
94 private:
95     double _timeToLive;
96     double _pollingTimer;
97     MetarRequester * _metarRequester;
98 };
99
100 typedef SGSharedPtr<LiveMetarProperties> LiveMetarProperties_ptr;
101
102 LiveMetarProperties::LiveMetarProperties( SGPropertyNode_ptr rootNode, MetarRequester * metarRequester ) :
103     MetarProperties( rootNode ),
104     _timeToLive(0.0),
105     _pollingTimer(0.0),
106     _metarRequester(metarRequester)
107 {
108     _tiedProperties.Tie("time-to-live", &_timeToLive );
109 }
110
111 LiveMetarProperties::~LiveMetarProperties()
112 {
113     _tiedProperties.Untie();
114 }
115
116 void LiveMetarProperties::update( double dt )
117 {
118     _timeToLive -= dt;
119     _pollingTimer -= dt;
120     if( _timeToLive < 0.0 ) {
121         _timeToLive = 0.0;
122         std::string stationId = getStationId();
123         if( stationId.empty() ) return;
124         if( _pollingTimer > 0.0 ) return;
125         _metarRequester->requestMetar( this, stationId );
126         _pollingTimer = MAX_POLLING_INTERVAL_SECONDS;
127     }
128 }
129
130 void LiveMetarProperties::handleMetarData( const std::string & data )
131 {
132     SG_LOG( SG_ENVIRONMENT, SG_INFO, "LiveMetarProperties::handleMetarData() received METAR for " << getStationId() << ": " << data );
133     _timeToLive = DEFAULT_TIME_TO_LIVE_SECONDS;
134     setMetar( data );
135 }
136
137 /* -------------------------------------------------------------------------------- */
138
139 class BasicRealWxController : public RealWxController
140 {
141 public:
142     BasicRealWxController( SGPropertyNode_ptr rootNode, MetarRequester * metarRequester );
143     virtual ~BasicRealWxController ();
144
145     virtual void init ();
146     virtual void reinit ();
147     virtual void shutdown ();
148     
149 protected:
150     void bind();
151     void unbind();
152     void update( double dt );
153
154     void checkNearbyMetar();
155
156     long getMetarMaxAgeMin() const { return _max_age_n == NULL ? 0 : _max_age_n->getLongValue(); }
157
158     SGPropertyNode_ptr _rootNode;
159     SGPropertyNode_ptr _ground_elevation_n;
160     SGPropertyNode_ptr _max_age_n;
161
162     bool _enabled;
163     bool __enabled;
164     simgear::TiedPropertyList _tiedProperties;
165     typedef std::vector<LiveMetarProperties_ptr> MetarPropertiesList;
166     MetarPropertiesList _metarProperties;
167
168 };
169
170 /* -------------------------------------------------------------------------------- */
171 /*
172 Properties
173  ~/enabled: bool              Enables/Disables the realwx controller
174  ~/metar[1..n]: string        Target property path for metar data
175  */
176
177 BasicRealWxController::BasicRealWxController( SGPropertyNode_ptr rootNode, MetarRequester * metarRequester ) :
178   _rootNode(rootNode),
179   _ground_elevation_n( fgGetNode( "/position/ground-elev-m", true )),
180   _max_age_n( fgGetNode( "/environment/params/metar-max-age-min", false ) ),
181   _enabled(true),
182   __enabled(false)
183 {
184     // at least instantiate MetarProperties for /environment/metar
185     _metarProperties.push_back( new LiveMetarProperties( 
186             fgGetNode( rootNode->getStringValue("metar", "/environment/metar"), true ), metarRequester ));
187
188     BOOST_FOREACH( SGPropertyNode_ptr n, rootNode->getChildren("metar") ) {
189        SG_LOG( SG_ENVIRONMENT, SG_INFO, "Adding metar properties at " << n->getStringValue() );
190         _metarProperties.push_back( new LiveMetarProperties( 
191             fgGetNode( n->getStringValue(), true ), metarRequester ));
192     }
193 }
194
195 BasicRealWxController::~BasicRealWxController()
196 {
197 }
198
199 void BasicRealWxController::init()
200 {
201     __enabled = false;
202     update(0); // fetch data ASAP
203     
204     globals->get_event_mgr()->addTask("checkNearbyMetar", this,
205                                       &BasicRealWxController::checkNearbyMetar, 60 );
206 }
207
208 void BasicRealWxController::reinit()
209 {
210     __enabled = false;
211 }
212     
213 void BasicRealWxController::shutdown()
214 {
215     globals->get_event_mgr()->removeTask("checkNearbyMetar");
216 }
217
218 void BasicRealWxController::bind()
219 {
220     _tiedProperties.setRoot( _rootNode );
221     _tiedProperties.Tie( "enabled", &_enabled );
222 }
223
224 void BasicRealWxController::unbind()
225 {
226     _tiedProperties.Untie();
227 }
228
229 void BasicRealWxController::update( double dt )
230 {
231   if( _enabled ) {
232     bool firstIteration = !__enabled; // first iteration after being enabled?
233
234     // clock tick for every METAR in stock
235     BOOST_FOREACH(LiveMetarProperties* p, _metarProperties) {
236       // first round? All received METARs are outdated
237       if( firstIteration ) p->setTimeToLive( 0.0 );
238       p->update(dt);
239     }
240
241     __enabled = true;
242   } else {
243     __enabled = false;
244   }
245 }
246
247 void BasicRealWxController::checkNearbyMetar()
248 {
249     try {
250       const SGGeod & pos = globals->get_aircraft_position();
251
252       // check nearest airport
253       SG_LOG(SG_ENVIRONMENT, SG_DEBUG, "NoaaMetarRealWxController::update(): (re) checking nearby airport with METAR" );
254
255       FGAirport * nearestAirport = FGAirport::findClosest(pos, 10000.0, MetarAirportFilter::instance() );
256       if( nearestAirport == NULL ) {
257           SG_LOG(SG_ENVIRONMENT,SG_WARN,"RealWxController::update can't find airport with METAR within 10000NM"  );
258           return;
259       }
260
261       SG_LOG(SG_ENVIRONMENT, SG_DEBUG, 
262           "NoaaMetarRealWxController::update(): nearest airport with METAR is: " << nearestAirport->ident() );
263
264       // if it has changed, invalidate the associated METAR
265       if( _metarProperties[0]->getStationId() != nearestAirport->ident() ) {
266           SG_LOG(SG_ENVIRONMENT, SG_INFO, 
267               "NoaaMetarRealWxController::update(): nearest airport with METAR has changed. Old: '" << 
268               _metarProperties[0]->getStationId() <<
269               "', new: '" << nearestAirport->ident() << "'" );
270           _metarProperties[0]->setStationId( nearestAirport->ident() );
271           _metarProperties[0]->setTimeToLive( 0.0 );
272       }
273     }
274     catch( sg_exception & ) {
275       return;
276     }
277     
278 }
279
280 /* -------------------------------------------------------------------------------- */
281
282 class NoaaMetarRealWxController : public BasicRealWxController, MetarRequester {
283 public:
284     NoaaMetarRealWxController( SGPropertyNode_ptr rootNode );
285     virtual ~NoaaMetarRealWxController();
286     virtual void update( double dt );
287
288     // implementation of MetarRequester
289     virtual void requestMetar( MetarDataHandler * metarDataHandler, const std::string & id );
290
291 private:
292     FGHTTPClient _http;
293 };
294
295 NoaaMetarRealWxController::NoaaMetarRealWxController( SGPropertyNode_ptr rootNode ) :
296   BasicRealWxController(rootNode, this )
297 {
298 }
299
300 NoaaMetarRealWxController::~NoaaMetarRealWxController()
301 {
302 }
303
304 void NoaaMetarRealWxController::update( double dt )
305 {
306     _http.update();
307     BasicRealWxController::update( dt );
308 }
309
310 void NoaaMetarRealWxController::requestMetar( MetarDataHandler * metarDataHandler, const std::string & id )
311 {
312     class NoaaMetarGetRequest : public simgear::HTTP::Request
313     {
314     public:
315         NoaaMetarGetRequest(MetarDataHandler* metarDataHandler, const string& stationId ) :
316               Request("http://weather.noaa.gov/pub/data/observations/metar/stations/" + stationId + ".TXT"),
317               _fromProxy(false),
318               _metarDataHandler(metarDataHandler)
319           {
320           }
321
322           virtual string_list requestHeaders() const
323           {
324               string_list reply;
325               reply.push_back("X-TIME");
326               return reply;
327           }
328
329           virtual std::string header(const std::string& name) const
330           {
331               string reply;
332
333               if( name == "X-TIME" ) {
334                   std::ostringstream buf;
335                   buf <<  globals->get_time_params()->get_cur_time();
336                   reply = buf.str();
337               }
338
339               return reply;
340           }
341
342           virtual void responseHeader(const string& key, const string& value)
343           {
344               if (key == "x-metarproxy") {
345                   _fromProxy = true;
346               }
347           }
348
349           virtual void gotBodyData(const char* s, int n)
350           {
351               _metar += string(s, n);
352           }
353
354           virtual void responseComplete()
355           {
356               if (responseCode() == 200) {
357                   _metarDataHandler->handleMetarData( _metar);
358               } else {
359                   SG_LOG(SG_ENVIRONMENT, SG_WARN, "metar download failed:" << url() << ": reason:" << responseReason());
360               }
361           }
362
363           bool fromMetarProxy() const
364           { return _fromProxy; }
365     private:  
366         string _metar;
367         bool _fromProxy;
368         MetarDataHandler * _metarDataHandler;
369     };
370
371
372     SG_LOG(SG_ENVIRONMENT, SG_INFO, 
373         "NoaaMetarRealWxController::update(): spawning load request for station-id '" << id << "'" );
374     _http.makeRequest(new NoaaMetarGetRequest(metarDataHandler, id));
375 }
376
377 /* -------------------------------------------------------------------------------- */
378
379 RealWxController * RealWxController::createInstance( SGPropertyNode_ptr rootNode )
380 {
381 //    string dataSource = rootNode->getStringValue("data-source", "noaa" );
382 //    if( dataSource == "nwx" ) {
383 //      return new NwxMetarRealWxController( rootNode );
384 //    } else {
385       return new NoaaMetarRealWxController( rootNode );
386 //    }
387 }
388
389 /* -------------------------------------------------------------------------------- */
390
391 } // namespace Environment