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