]> git.mxchange.org Git - flightgear.git/blob - src/Environment/realwx_ctrl.cxx
Reset: fix OSG stats handling
[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
29 #include <algorithm>
30 #include <boost/foreach.hpp>
31 #include <boost/algorithm/string/case_conv.hpp>
32
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>
40
41 #include "metarproperties.hxx"
42 #include "metarairportfilter.hxx"
43 #include "fgmetar.hxx"
44 #include <Network/HTTPClient.hxx>
45 #include <Main/fg_props.hxx>
46
47 namespace Environment {
48
49
50 /* -------------------------------------------------------------------------------- */
51
52 class MetarDataHandler {
53 public:
54     virtual void handleMetarData( const std::string & data ) = 0;
55     virtual void handleMetarFailure() = 0;
56 };
57
58 class MetarRequester {
59 public:
60     virtual void requestMetar( MetarDataHandler * metarDataHandler, const std::string & id ) = 0;
61 };
62
63 /* -------------------------------------------------------------------------------- */
64
65 class LiveMetarProperties : public MetarProperties, MetarDataHandler {
66 public:
67     LiveMetarProperties( SGPropertyNode_ptr rootNode, MetarRequester * metarRequester, int maxAge );
68     virtual ~LiveMetarProperties();
69     virtual void update( double dt );
70
71     virtual double getTimeToLive() const { return _timeToLive; }
72     virtual void resetTimeToLive()
73     { _timeToLive = 0.00; _pollingTimer = 0.0; }
74
75     // implementation of MetarDataHandler
76     virtual void handleMetarData( const std::string & data );
77     virtual void handleMetarFailure();
78   
79     static const unsigned MAX_POLLING_INTERVAL_SECONDS = 10;
80     static const unsigned DEFAULT_TIME_TO_LIVE_SECONDS = 900;
81
82 private:
83     double _timeToLive;
84     double _pollingTimer;
85     MetarRequester * _metarRequester;
86     int _maxAge;
87     bool _failure;
88 };
89
90 typedef SGSharedPtr<LiveMetarProperties> LiveMetarProperties_ptr;
91
92 LiveMetarProperties::LiveMetarProperties( SGPropertyNode_ptr rootNode, MetarRequester * metarRequester, int maxAge ) :
93     MetarProperties( rootNode ),
94     _timeToLive(0.0),
95     _pollingTimer(0.0),
96     _metarRequester(metarRequester),
97     _maxAge(maxAge),
98     _failure(false)
99 {
100     _tiedProperties.Tie("time-to-live", &_timeToLive );
101     _tiedProperties.Tie("failure", &_failure);
102 }
103
104 LiveMetarProperties::~LiveMetarProperties()
105 {
106     _tiedProperties.Untie();
107 }
108
109 void LiveMetarProperties::update( double dt )
110 {
111     _timeToLive -= dt;
112     _pollingTimer -= dt;
113     if( _timeToLive <= 0.0 ) {
114         _timeToLive = 0.0;
115         std::string stationId = getStationId();
116         if( stationId.empty() ) return;
117         if( _pollingTimer > 0.0 ) return;
118         _metarRequester->requestMetar( this, stationId );
119         _pollingTimer = MAX_POLLING_INTERVAL_SECONDS;
120     }
121 }
122
123 void LiveMetarProperties::handleMetarData( const std::string & data )
124 {
125     SG_LOG( SG_ENVIRONMENT, SG_DEBUG, "LiveMetarProperties::handleMetarData() received METAR for " << getStationId() << ": " << data );
126     _timeToLive = DEFAULT_TIME_TO_LIVE_SECONDS;
127     
128     SGSharedPtr<FGMetar> m;
129     try {
130         m = new FGMetar(data.c_str());
131     }
132     catch( sg_io_exception ) {
133         SG_LOG( SG_ENVIRONMENT, SG_WARN, "Can't parse metar: " << data );
134         _failure = true;
135         return;
136     }
137
138     if (_maxAge && (m->getAge_min() > _maxAge)) {
139         // METAR is older than max-age, ignore
140         SG_LOG( SG_ENVIRONMENT, SG_DEBUG, "Ignoring outdated METAR for " << getStationId());
141         return;
142     }
143   
144     _failure = false;
145     setMetar( m );
146 }
147
148 void LiveMetarProperties::handleMetarFailure()
149 {
150   _failure = true;
151 }
152   
153 /* -------------------------------------------------------------------------------- */
154
155 class BasicRealWxController : public RealWxController
156 {
157 public:
158     BasicRealWxController( SGPropertyNode_ptr rootNode, MetarRequester * metarRequester );
159     virtual ~BasicRealWxController ();
160
161     virtual void init ();
162     virtual void reinit ();
163     virtual void shutdown ();
164     
165     /**
166      * Create a metar-property binding at the specified property path,
167      * and initiate a request for the specified station-ID (which may be
168      * empty). If the property path is already mapped, the station ID
169      * will be updated.
170      */
171     void addMetarAtPath(const string& propPath, const string& icao);
172   
173     void removeMetarAtPath(const string& propPath);
174 protected:
175     void bind();
176     void unbind();
177     void update( double dt );
178
179     void checkNearbyMetar();
180
181     long getMetarMaxAgeMin() const { return _max_age_n == NULL ? 0 : _max_age_n->getLongValue(); }
182
183     SGPropertyNode_ptr _rootNode;
184     SGPropertyNode_ptr _ground_elevation_n;
185     SGPropertyNode_ptr _max_age_n;
186
187     bool _enabled;
188     bool _wasEnabled;
189     simgear::TiedPropertyList _tiedProperties;
190     typedef std::vector<LiveMetarProperties_ptr> MetarPropertiesList;
191     MetarPropertiesList _metarProperties;
192     MetarRequester* _requester;
193
194 };
195
196 static bool commandRequestMetar(const SGPropertyNode* arg)
197 {
198   SGSubsystemGroup* envMgr = (SGSubsystemGroup*) globals->get_subsystem("environment");
199   if (!envMgr) {
200     return false;
201   }
202   
203   BasicRealWxController* self = (BasicRealWxController*) envMgr->get_subsystem("realwx");
204   if (!self) {
205     return false;
206   }
207   
208   string icao(arg->getStringValue("station"));
209   boost::to_upper(icao);
210   string path = arg->getStringValue("path");
211   self->addMetarAtPath(path, icao);
212   return true;
213 }
214   
215 static bool commandClearMetar(const SGPropertyNode* arg)
216 {
217   SGSubsystemGroup* envMgr = (SGSubsystemGroup*) globals->get_subsystem("environment");
218   if (!envMgr) {
219     return false;
220   }
221   
222   BasicRealWxController* self = (BasicRealWxController*) envMgr->get_subsystem("realwx");
223   if (!self) {
224     return false;
225   }
226   
227   string path = arg->getStringValue("path");
228   self->removeMetarAtPath(path);
229   return true;
230 }
231   
232 /* -------------------------------------------------------------------------------- */
233 /*
234 Properties
235  ~/enabled: bool              Enables/Disables the realwx controller
236  ~/metar[1..n]: string        Target property path for metar data
237  */
238
239 BasicRealWxController::BasicRealWxController( SGPropertyNode_ptr rootNode, MetarRequester * metarRequester ) :
240   _rootNode(rootNode),
241   _ground_elevation_n( fgGetNode( "/position/ground-elev-m", true )),
242   _max_age_n( fgGetNode( "/environment/params/metar-max-age-min", false ) ),
243   _enabled(true),
244   _wasEnabled(false),
245   _requester(metarRequester)
246 {
247     
248     globals->get_commands()->addCommand("request-metar", commandRequestMetar);
249     globals->get_commands()->addCommand("clear-metar", commandClearMetar);
250 }
251
252 BasicRealWxController::~BasicRealWxController()
253 {
254     globals->get_commands()->removeCommand("request-metar");
255     globals->get_commands()->removeCommand("clear-metar");
256 }
257
258 void BasicRealWxController::init()
259 {
260     _wasEnabled = false;
261     
262     // at least instantiate MetarProperties for /environment/metar
263     SGPropertyNode_ptr metarNode = fgGetNode( _rootNode->getStringValue("metar", "/environment/metar"), true );
264     _metarProperties.push_back( new LiveMetarProperties(metarNode,
265                                                         _requester,
266                                                         getMetarMaxAgeMin()));
267     
268     BOOST_FOREACH( SGPropertyNode_ptr n, _rootNode->getChildren("metar") ) {
269         SGPropertyNode_ptr metarNode = fgGetNode( n->getStringValue(), true );
270         addMetarAtPath(metarNode->getPath(), "");
271     }
272
273     checkNearbyMetar();
274     update(0); // fetch data ASAP
275     
276     globals->get_event_mgr()->addTask("checkNearbyMetar", this,
277                                       &BasicRealWxController::checkNearbyMetar, 60 );
278 }
279
280 void BasicRealWxController::reinit()
281 {
282     _wasEnabled = false;
283     checkNearbyMetar();
284     update(0); // fetch data ASAP
285 }
286     
287 void BasicRealWxController::shutdown()
288 {
289     globals->get_event_mgr()->removeTask("checkNearbyMetar");
290 }
291
292 void BasicRealWxController::bind()
293 {
294     _tiedProperties.setRoot( _rootNode );
295     _tiedProperties.Tie( "enabled", &_enabled );
296 }
297
298 void BasicRealWxController::unbind()
299 {
300     _tiedProperties.Untie();
301 }
302
303 void BasicRealWxController::update( double dt )
304 {  
305   if( _enabled ) {
306     bool firstIteration = !_wasEnabled;
307     // clock tick for every METAR in stock
308     BOOST_FOREACH(LiveMetarProperties* p, _metarProperties) {
309       // first round? All received METARs are outdated
310       if( firstIteration ) p->resetTimeToLive();
311       p->update(dt);
312     }
313
314     _wasEnabled = true;
315   } else {
316     _wasEnabled = false;
317   }
318 }
319
320 void BasicRealWxController::addMetarAtPath(const string& propPath, const string& icao)
321 {
322   // check for duplicate entries
323   BOOST_FOREACH( LiveMetarProperties_ptr p, _metarProperties ) {
324     if( p->get_root_node()->getPath() == propPath ) {
325       // already exists
326       if (p->getStationId() != icao) {
327         p->setStationId(icao);
328         p->resetTimeToLive();
329       }
330       
331       return;
332     }
333   } // of exitsing metar properties iteration
334
335   SGPropertyNode_ptr metarNode = fgGetNode(propPath, true);
336   SG_LOG( SG_ENVIRONMENT, SG_INFO, "Adding metar properties at " << propPath );
337   LiveMetarProperties_ptr p(new LiveMetarProperties( metarNode, _requester, getMetarMaxAgeMin() ));
338   _metarProperties.push_back(p);
339   p->setStationId(icao);
340 }
341
342 void BasicRealWxController::removeMetarAtPath(const string &propPath)
343 {
344   MetarPropertiesList::iterator it = _metarProperties.begin();
345   for (; it != _metarProperties.end(); ++it) {
346     LiveMetarProperties_ptr p(*it);
347     if( p->get_root_node()->getPath() == propPath ) {
348       _metarProperties.erase(it);
349       // final ref will drop, and delete the MetarProperties, when we return
350       return;
351     }
352   }
353   
354   SG_LOG(SG_ENVIRONMENT, SG_WARN, "no metar properties at " << propPath);
355 }
356   
357 void BasicRealWxController::checkNearbyMetar()
358 {
359     try {
360       const SGGeod & pos = globals->get_aircraft_position();
361
362       // check nearest airport
363       SG_LOG(SG_ENVIRONMENT, SG_DEBUG, "NoaaMetarRealWxController::update(): (re) checking nearby airport with METAR" );
364
365       FGAirport * nearestAirport = FGAirport::findClosest(pos, 10000.0, MetarAirportFilter::instance() );
366       if( nearestAirport == NULL ) {
367           SG_LOG(SG_ENVIRONMENT,SG_WARN,"RealWxController::update can't find airport with METAR within 10000NM"  );
368           return;
369       }
370
371       SG_LOG(SG_ENVIRONMENT, SG_DEBUG, 
372           "NoaaMetarRealWxController::update(): nearest airport with METAR is: " << nearestAirport->ident() );
373
374       // if it has changed, invalidate the associated METAR
375       if( _metarProperties[0]->getStationId() != nearestAirport->ident() ) {
376           SG_LOG(SG_ENVIRONMENT, SG_INFO, 
377               "NoaaMetarRealWxController::update(): nearest airport with METAR has changed. Old: '" << 
378               _metarProperties[0]->getStationId() <<
379               "', new: '" << nearestAirport->ident() << "'" );
380           _metarProperties[0]->setStationId( nearestAirport->ident() );
381           _metarProperties[0]->resetTimeToLive();
382       }
383     }
384     catch( sg_exception & ) {
385       return;
386     }
387     
388 }
389
390 /* -------------------------------------------------------------------------------- */
391
392 class NoaaMetarRealWxController : public BasicRealWxController, MetarRequester {
393 public:
394     NoaaMetarRealWxController( SGPropertyNode_ptr rootNode );
395
396     // implementation of MetarRequester
397     virtual void requestMetar( MetarDataHandler * metarDataHandler, const std::string & id );
398
399     virtual ~NoaaMetarRealWxController()
400     {
401     }
402 private:
403     
404 };
405
406 NoaaMetarRealWxController::NoaaMetarRealWxController( SGPropertyNode_ptr rootNode ) :
407   BasicRealWxController(rootNode, this )
408 {
409 }
410
411 void NoaaMetarRealWxController::requestMetar
412 (
413   MetarDataHandler* metarDataHandler,
414   const std::string& id
415 )
416 {
417   static const std::string NOAA_BASE_URL =
418     "http://weather.noaa.gov/pub/data/observations/metar/stations/";
419   class NoaaMetarGetRequest:
420     public simgear::HTTP::MemoryRequest
421   {
422     public:
423       NoaaMetarGetRequest( MetarDataHandler* metarDataHandler,
424                            const std::string& stationId ):
425         MemoryRequest(NOAA_BASE_URL + stationId + ".TXT"),
426         _metarDataHandler(metarDataHandler)
427       {
428         std::ostringstream buf;
429         buf <<  globals->get_time_params()->get_cur_time();
430         requestHeader("X-TIME") = buf.str();
431       }
432
433       virtual void onDone()
434       {
435         if( responseCode() != 200 )
436         {
437           SG_LOG
438           (
439             SG_ENVIRONMENT,
440             SG_WARN,
441             "metar download failed:" << url() << ": reason:" << responseReason()
442           );
443           return;
444         }
445
446         _metarDataHandler->handleMetarData
447         (
448           simgear::strutils::simplify(responseBody())
449         );
450       }
451
452       virtual void onFail()
453       {
454         SG_LOG(SG_ENVIRONMENT, SG_INFO, "metar download failure");
455         _metarDataHandler->handleMetarFailure();
456       }
457
458     private:
459       MetarDataHandler * _metarDataHandler;
460   };
461
462   string upperId = boost::to_upper_copy(id);
463
464   SG_LOG
465   (
466     SG_ENVIRONMENT,
467     SG_INFO,
468     "NoaaMetarRealWxController::update(): "
469     "spawning load request for station-id '" << upperId << "'"
470   );
471   FGHTTPClient* http = static_cast<FGHTTPClient*>(globals->get_subsystem("http"));
472   if (http) {
473       http->makeRequest(new NoaaMetarGetRequest(metarDataHandler, upperId));
474   }
475 }
476
477 /* -------------------------------------------------------------------------------- */
478     
479 RealWxController * RealWxController::createInstance( SGPropertyNode_ptr rootNode )
480 {
481   return new NoaaMetarRealWxController( rootNode );
482 }
483     
484 RealWxController::~RealWxController()
485 {
486 }
487
488 /* -------------------------------------------------------------------------------- */
489
490 } // namespace Environment