]> git.mxchange.org Git - flightgear.git/blob - src/Environment/realwx_ctrl.cxx
Merge branch 'next' of gitorious.org:fg/flightgear into next
[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
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
43 #include <algorithm>
44
45 using simgear::PropertyList;
46
47 namespace Environment {
48
49 /* -------------------------------------------------------------------------------- */
50
51 class LiveMetarProperties : public MetarProperties {
52 public:
53     LiveMetarProperties( SGPropertyNode_ptr rootNode );
54     virtual ~LiveMetarProperties();
55     virtual void update( double dt );
56
57     virtual double getTimeToLive() const { return _timeToLive; }
58     virtual void setTimeToLive( double value ) { _timeToLive = value; }
59 private:
60     double _timeToLive;
61
62 };
63
64 typedef SGSharedPtr<LiveMetarProperties> LiveMetarProperties_ptr;
65
66 LiveMetarProperties::LiveMetarProperties( SGPropertyNode_ptr rootNode ) :
67     MetarProperties( rootNode ),
68     _timeToLive(0.0)
69 {
70     _tiedProperties.Tie("time-to-live", &_timeToLive );
71 }
72
73 LiveMetarProperties::~LiveMetarProperties()
74 {
75     _tiedProperties.Untie();
76 }
77
78 void LiveMetarProperties::update( double dt )
79 {
80     _timeToLive -= dt;
81     if( _timeToLive < 0.0 ) _timeToLive = 0.0;
82 }
83
84 /* -------------------------------------------------------------------------------- */
85
86 class BasicRealWxController : public RealWxController
87 {
88 public:
89     BasicRealWxController( SGPropertyNode_ptr rootNode );
90     virtual ~BasicRealWxController ();
91
92     virtual void init ();
93     virtual void reinit ();
94
95 protected:
96     void bind();
97     void unbind();
98     void update( double dt );
99
100     virtual void update( bool first, double dt ) = 0;
101
102     long getMetarMaxAgeMin() const { return _max_age_n == NULL ? 0 : _max_age_n->getLongValue(); }
103
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;
109
110     bool _enabled;
111     bool __enabled;
112     simgear::TiedPropertyList _tiedProperties;
113     typedef std::vector<LiveMetarProperties_ptr> MetarPropertiesList;
114     MetarPropertiesList _metarProperties;
115     
116 };
117
118 /* -------------------------------------------------------------------------------- */
119 /*
120 Properties
121  ~/enabled: bool              Enables/Disables the realwx controller
122  ~/metar[1..n]: string        Target property path for metar data
123  */
124
125 BasicRealWxController::BasicRealWxController( SGPropertyNode_ptr rootNode ) :
126   _rootNode(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 ) ),
131   _enabled(true),
132   __enabled(false)
133 {
134     // at least instantiate MetarProperties for /environment/metar
135     _metarProperties.push_back( new LiveMetarProperties( 
136             fgGetNode( rootNode->getStringValue("metar", "/environment/metar"), true ) ) );
137
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 )));
143     }
144 }
145
146 BasicRealWxController::~BasicRealWxController()
147 {
148 }
149
150 void BasicRealWxController::init()
151 {
152     __enabled = false;
153     update(0); // fetch data ASAP
154 }
155
156 void BasicRealWxController::reinit()
157 {
158     __enabled = false;
159 }
160
161 void BasicRealWxController::bind()
162 {
163     _tiedProperties.setRoot( _rootNode );
164     _tiedProperties.Tie( "enabled", &_enabled );
165 }
166
167 void BasicRealWxController::unbind()
168 {
169     _tiedProperties.Untie();
170 }
171
172 void BasicRealWxController::update( double dt )
173 {
174   if( _enabled ) {
175     bool firstIteration = !__enabled; // first iteration after being enabled?
176
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 );
182       (*it)->update(dt);
183     }
184
185     update( firstIteration, dt );
186     __enabled = true;
187   } else {
188     __enabled = false;
189   }
190 }
191
192 /* -------------------------------------------------------------------------------- */
193
194 class NoaaMetarRealWxController : public BasicRealWxController {
195 public:
196     NoaaMetarRealWxController( SGPropertyNode_ptr rootNode );
197     virtual ~NoaaMetarRealWxController();
198     virtual void update (bool first, double delta_time_sec);
199     virtual void shutdown ();
200
201     /**
202      * callback from MetarGetRequest when a download succeeds
203      */
204     void gotMetar(const string& stationId, const string& metar);
205 private:
206     double _positionTimeToLive;
207     double _requestTimer;
208
209     simgear::HTTP::Client _http;
210 };
211
212 class MetarGetRequest : public simgear::HTTP::Request
213 {
214 public:
215     MetarGetRequest(NoaaMetarRealWxController* con, const string& s) :
216         Request(""),
217         stationId(s),
218         fromProxy(false),
219         wxController(con)
220     {
221         setUrl("http://weather.noaa.gov/pub/data/observations/metar/stations/" + stationId + ".TXT");
222     }
223     
224     virtual string_list requestHeaders() const
225     {
226         string_list r;
227         r.push_back("X-Time");
228         return r;
229     }
230     
231     virtual string header(const string& name) const
232     {
233         if (name == "X-Time") {
234             char buf[16];
235             snprintf(buf, 16, "%ld", globals->get_time_params()->get_cur_time());
236             return buf;
237         }
238         
239         return Request::header(name);     
240     }
241     
242     virtual void responseHeader(const string& key, const string& value)
243     {
244         if (key == "x-metarproxy") {
245             fromProxy = true;
246         }
247     }
248     
249     virtual void gotBodyData(const char* s, int n)
250     {
251         metar += string(s, n);
252     }
253     
254     virtual void responseComplete()
255     {
256         if (responseCode() == 200) {
257             wxController->gotMetar(stationId, metar);
258         } else {
259             SG_LOG(SG_IO, SG_WARN, "metar download failed:" << url() << ": reason:" << responseReason());
260         }
261     }
262     
263     bool fromMetarProxy() const
264         { return fromProxy; }
265 private:  
266     string stationId;
267     string metar;
268     bool fromProxy;
269     NoaaMetarRealWxController* wxController;
270 };
271
272
273
274 NoaaMetarRealWxController::NoaaMetarRealWxController( SGPropertyNode_ptr rootNode ) :
275   BasicRealWxController(rootNode),
276   _positionTimeToLive(0.0),
277   _requestTimer(0.0)
278 {
279     string proxyHost(fgGetString("/sim/presets/proxy/host"));
280     int proxyPort(fgGetInt("/sim/presets/proxy/port"));
281     string proxyAuth(fgGetString("/sim/presets/proxy/auth"));
282     
283     if (!proxyHost.empty()) {
284         _http.setProxy(proxyHost, proxyPort, proxyAuth);
285     }
286 }
287
288 void NoaaMetarRealWxController::shutdown()
289 {
290 }
291
292 NoaaMetarRealWxController::~NoaaMetarRealWxController()
293 {
294 }
295
296 void NoaaMetarRealWxController::update( bool first, double dt )
297 {
298     _http.update();
299     
300     _positionTimeToLive -= dt;
301     _requestTimer -= dt;
302
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;
307
308         SGGeod pos = SGGeod::fromDeg(_longitude_n->getDoubleValue(), _latitude_n->getDoubleValue());
309
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"  );
313             return;
314         }
315
316         SG_LOG(SG_ALL, SG_INFO, 
317             "NoaaMetarRealWxController::update(): nearest airport with METAR is: " << nearestAirport->ident() );
318
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 );
327         }
328     }
329   
330     if( _requestTimer <= 0.0 ) {
331         _requestTimer = 10.0;
332         
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;
337
338             SG_LOG(SG_ALL, SG_INFO, 
339                 "NoaaMetarRealWxController::update(): spawning load request for station-id '" << stationId << "'" );
340             
341             _http.makeRequest(new MetarGetRequest(this, stationId));
342         } // of MetarProperties iteration
343     }
344 }
345
346 void NoaaMetarRealWxController::gotMetar(const string& stationId, const string& metar)
347 {
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)
351             continue;
352             
353         p->setTimeToLive(900);
354         p->setMetar( metar );
355     }
356 }
357
358 /* -------------------------------------------------------------------------------- */
359
360 RealWxController * RealWxController::createInstance( SGPropertyNode_ptr rootNode )
361 {
362 //    string dataSource = rootNode->getStringValue("data-source", "noaa" );
363 //    if( dataSource == "nwx" ) {
364 //      return new NwxMetarRealWxController( rootNode );
365 //    } else {
366       return new NoaaMetarRealWxController( rootNode );
367 //    }
368 }
369
370 /* -------------------------------------------------------------------------------- */
371
372 } // namespace Environment