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 "tiedpropertylist.hxx"
29 #include "metarproperties.hxx"
30 #include "metarairportfilter.hxx"
31 #include "fgmetar.hxx"
33 #include <Main/fg_props.hxx>
35 #include <simgear/structure/exception.hxx>
36 #include <simgear/misc/strutils.hxx>
38 #if defined(ENABLE_THREADS)
39 #include <OpenThreads/Thread>
40 #include <simgear/threads/SGQueue.hxx>
44 namespace Environment {
46 /* -------------------------------------------------------------------------------- */
48 class LiveMetarProperties : public MetarProperties {
50 LiveMetarProperties( SGPropertyNode_ptr rootNode );
51 virtual ~LiveMetarProperties();
52 virtual void update( double dt );
54 virtual double getTimeToLive() const { return _timeToLive; }
55 virtual void setTimeToLive( double value ) { _timeToLive = value; }
61 typedef SGSharedPtr<LiveMetarProperties> LiveMetarProperties_ptr;
63 LiveMetarProperties::LiveMetarProperties( SGPropertyNode_ptr rootNode ) :
64 MetarProperties( rootNode ),
67 _tiedProperties.Tie("time-to-live", &_timeToLive );
70 LiveMetarProperties::~LiveMetarProperties()
74 void LiveMetarProperties::update( double dt )
77 if( _timeToLive < 0.0 ) _timeToLive = 0.0;
80 /* -------------------------------------------------------------------------------- */
82 class BasicRealWxController : public RealWxController
85 BasicRealWxController( SGPropertyNode_ptr rootNode );
86 virtual ~BasicRealWxController ();
89 virtual void reinit ();
94 void update( double dt );
96 virtual void update( bool first, double dt ) = 0;
98 long getMetarMaxAgeMin() const { return _max_age_n == NULL ? 0 : _max_age_n->getLongValue(); }
100 SGPropertyNode_ptr _rootNode;
101 SGPropertyNode_ptr _longitude_n;
102 SGPropertyNode_ptr _latitude_n;
103 SGPropertyNode_ptr _ground_elevation_n;
104 SGPropertyNode_ptr _max_age_n;
108 TiedPropertyList _tiedProperties;
109 ; typedef std::vector<LiveMetarProperties_ptr> MetarPropertiesList;
110 MetarPropertiesList _metarProperties;
113 /* -------------------------------------------------------------------------------- */
116 ~/enabled: bool Enables/Disables the realwx controller
117 ~/metar[1..n]: string Target property path for metar data
120 BasicRealWxController::BasicRealWxController( SGPropertyNode_ptr rootNode ) :
122 _longitude_n( fgGetNode( "/position/longitude-deg", true )),
123 _latitude_n( fgGetNode( "/position/latitude-deg", true )),
124 _ground_elevation_n( fgGetNode( "/position/ground-elev-m", true )),
125 _max_age_n( fgGetNode( "/environment/params/metar-max-age-min", false ) ),
129 // at least instantiate MetarProperties for /environment/metar
130 _metarProperties.push_back( new LiveMetarProperties(
131 fgGetNode( rootNode->getStringValue("metar", "/environment/metar"), true ) ) );
133 PropertyList metars = rootNode->getChildren("metar");
134 for( PropertyList::size_type i = 1; i < metars.size(); i++ ) {
135 SG_LOG( SG_ALL, SG_INFO, "Adding metar properties at " << metars[i]->getStringValue() );
136 _metarProperties.push_back( new LiveMetarProperties(
137 fgGetNode( metars[i]->getStringValue(), true )));
141 BasicRealWxController::~BasicRealWxController()
145 void BasicRealWxController::init()
148 update(0); // fetch data ASAP
151 void BasicRealWxController::reinit()
156 void BasicRealWxController::bind()
158 _tiedProperties.setRoot( _rootNode );
159 _tiedProperties.Tie( "enabled", &_enabled );
162 void BasicRealWxController::unbind()
164 _tiedProperties.Untie();
167 void BasicRealWxController::update( double dt )
170 bool firstIteration = !__enabled; // first iteration after being enabled?
172 // clock tick for every METAR in stock
173 for( MetarPropertiesList::iterator it = _metarProperties.begin();
174 it != _metarProperties.end(); it++ ) {
175 // first round? All received METARs are outdated
176 if( firstIteration ) (*it)->setTimeToLive( 0.0 );
180 update( firstIteration, dt );
187 /* -------------------------------------------------------------------------------- */
189 class NoaaMetarRealWxController : public BasicRealWxController {
191 NoaaMetarRealWxController( SGPropertyNode_ptr rootNode );
192 virtual ~NoaaMetarRealWxController();
193 virtual void update (bool first, double delta_time_sec);
195 class MetarLoadRequest {
197 MetarLoadRequest( const string & stationId ) :
198 _stationId(stationId),
199 _proxyHost(fgGetNode("/sim/presets/proxy/host", true)->getStringValue()),
200 _proxyPort(fgGetNode("/sim/presets/proxy/port", true)->getStringValue()),
201 _proxyAuth(fgGetNode("/sim/presets/proxy/authentication", true)->getStringValue())
203 MetarLoadRequest( const MetarLoadRequest & other ) :
204 _stationId(other._stationId),
205 _proxyHost(other._proxyAuth),
206 _proxyPort(other._proxyPort),
207 _proxyAuth(other._proxyAuth)
216 class MetarLoadResponse {
218 MetarLoadResponse( const string & stationId, const string metar ) {
219 _stationId = stationId;
222 MetarLoadResponse( const MetarLoadResponse & other ) {
223 _stationId = other._stationId;
224 _metar = other._metar;
230 double _positionTimeToLive;
231 double _requestTimer;
233 #if defined(ENABLE_THREADS)
234 class MetarLoadThread : public OpenThreads::Thread {
236 MetarLoadThread( long maxAge );
237 void requestMetar( const MetarLoadRequest & metarRequest, bool background = true );
238 bool hasMetar() { return _responseQueue.size() > 0; }
239 MetarLoadResponse getMetar() { return _responseQueue.pop(); }
242 void fetch( const MetarLoadRequest & );
244 long _minRequestInterval;
245 SGBlockingQueue <MetarLoadRequest> _requestQueue;
246 SGBlockingQueue <MetarLoadResponse> _responseQueue;
249 MetarLoadThread * _metarLoadThread;
253 NoaaMetarRealWxController::NoaaMetarRealWxController( SGPropertyNode_ptr rootNode ) :
254 BasicRealWxController(rootNode),
255 _positionTimeToLive(0.0),
258 #if defined(ENABLE_THREADS)
259 _metarLoadThread = new MetarLoadThread(getMetarMaxAgeMin());
260 _metarLoadThread->start();
264 NoaaMetarRealWxController::~NoaaMetarRealWxController()
266 #if defined(ENABLE_THREADS)
267 if( _metarLoadThread ) {
268 MetarLoadRequest request("");
269 _metarLoadThread->requestMetar(request);
270 _metarLoadThread->join();
271 delete _metarLoadThread;
273 #endif // ENABLE_THREADS
276 void NoaaMetarRealWxController::update( bool first, double dt )
278 _positionTimeToLive -= dt;
281 if( _positionTimeToLive <= 0.0 ) {
282 // check nearest airport
283 SG_LOG(SG_ALL, SG_INFO, "NoaaMetarRealWxController::update(): (re) checking nearby airport with METAR" );
284 _positionTimeToLive = 60.0;
286 SGGeod pos = SGGeod::fromDeg(_longitude_n->getDoubleValue(), _latitude_n->getDoubleValue());
288 FGAirport * nearestAirport = FGAirport::findClosest(pos, 10000.0, MetarAirportFilter::instance() );
289 if( nearestAirport == NULL ) {
290 SG_LOG(SG_ALL,SG_WARN,"RealWxController::update can't find airport with METAR within 10000NM" );
294 SG_LOG(SG_ALL, SG_INFO,
295 "NoaaMetarRealWxController::update(): nearest airport with METAR is: " << nearestAirport->ident() );
297 // if it has changed, invalidate the associated METAR
298 if( _metarProperties[0]->getStationId() != nearestAirport->ident() ) {
299 SG_LOG(SG_ALL, SG_INFO,
300 "NoaaMetarRealWxController::update(): nearest airport with METAR has changed. Old: '" <<
301 _metarProperties[0]->getStationId() <<
302 "', new: '" << nearestAirport->ident() << "'" );
303 _metarProperties[0]->setStationId( nearestAirport->ident() );
304 _metarProperties[0]->setTimeToLive( 0.0 );
308 if( _requestTimer <= 0.0 ) {
309 _requestTimer = 10.0;
311 for( MetarPropertiesList::iterator it = _metarProperties.begin();
312 it != _metarProperties.end(); it++ ) {
314 if( (*it)->getTimeToLive() > 0.0 ) continue;
315 const std::string & stationId = (*it)->getStationId();
316 if( stationId.empty() ) continue;
318 SG_LOG(SG_ALL, SG_INFO,
319 "NoaaMetarRealWxController::update(): spawning load request for station-id '" << stationId << "'" );
321 MetarLoadRequest request( stationId );
322 // load the metar for the neares airport in the foreground if the fdm is uninitialized
323 // to make sure a metar is received
324 // before the automatic runway selection code runs. All subsequent calls
325 // run in the background
326 bool background = fgGetBool("/sim/fdm-initialized", false ) || it != _metarProperties.begin();
327 _metarLoadThread->requestMetar( request, background );
331 // pick all the received responses from the result queue and update the associated
333 while( _metarLoadThread->hasMetar() ) {
334 MetarLoadResponse metar = _metarLoadThread->getMetar();
335 SG_LOG( SG_ALL, SG_INFO, "NoaaMetarRwalWxController::update() received METAR for " << metar._stationId << ": " << metar._metar );
336 for( MetarPropertiesList::iterator it = _metarProperties.begin();
337 it != _metarProperties.end(); it++ ) {
338 if( (*it)->getStationId() != metar._stationId )
340 (*it)->setTimeToLive(900);
341 (*it)->setMetar( metar._metar );
346 /* -------------------------------------------------------------------------------- */
348 #if defined(ENABLE_THREADS)
349 NoaaMetarRealWxController::MetarLoadThread::MetarLoadThread( long maxAge ) :
351 _minRequestInterval(2000)
355 void NoaaMetarRealWxController::MetarLoadThread::requestMetar( const MetarLoadRequest & metarRequest, bool background )
358 if( _requestQueue.size() > 10 ) {
359 SG_LOG(SG_ALL,SG_ALERT,
360 "NoaaMetarRealWxController::MetarLoadThread::requestMetar() more than 10 outstanding METAR requests, dropping "
361 << metarRequest._stationId );
365 _requestQueue.push( metarRequest );
367 fetch( metarRequest );
371 void NoaaMetarRealWxController::MetarLoadThread::run()
373 SGTimeStamp lastRun = SGTimeStamp::fromSec(0);
375 SGTimeStamp dt = SGTimeStamp::now() - lastRun;
377 if( dt.getSeconds() * 1000 < _minRequestInterval )
378 microSleep( (_minRequestInterval - dt.getSeconds() * 1000 ) * 1000 );
380 lastRun = SGTimeStamp::now();
382 const MetarLoadRequest request = _requestQueue.pop();
384 if( request._stationId.size() == 0 )
392 void NoaaMetarRealWxController::MetarLoadThread::fetch( const MetarLoadRequest & request )
394 SGSharedPtr<FGMetar> result = NULL;
397 result = new FGMetar( request._stationId, request._proxyHost, request._proxyPort, request._proxyAuth );
398 _minRequestInterval = 2000;
399 } catch (const sg_io_exception& e) {
400 SG_LOG( SG_GENERAL, SG_WARN, "NoaaMetarRealWxController::fetchMetar(): can't get METAR for "
401 << request._stationId << ":" << e.getFormattedMessage().c_str() );
402 _minRequestInterval += _minRequestInterval/2;
403 if( _minRequestInterval > 30000 )
404 _minRequestInterval = 30000;
408 string reply = result->getData();
409 std::replace(reply.begin(), reply.end(), '\n', ' ');
410 string metar = simgear::strutils::strip( reply );
412 if( metar.empty() ) {
413 SG_LOG( SG_GENERAL, SG_WARN, "NoaaMetarRealWxController::fetchMetar(): dropping empty METAR for "
414 << request._stationId );
418 if( _maxAge && result->getAge_min() > _maxAge ) {
419 SG_LOG( SG_GENERAL, SG_ALERT, "NoaaMetarRealWxController::fetchMetar(): dropping outdated METAR "
424 MetarLoadResponse response( request._stationId, metar );
425 _responseQueue.push( response );
429 /* -------------------------------------------------------------------------------- */
431 RealWxController * RealWxController::createInstance( SGPropertyNode_ptr rootNode )
433 // string dataSource = rootNode->getStringValue("data-source", "noaa" );
434 // if( dataSource == "nwx" ) {
435 // return new NwxMetarRealWxController( rootNode );
437 return new NoaaMetarRealWxController( rootNode );
441 /* -------------------------------------------------------------------------------- */
443 } // namespace Environment