]> git.mxchange.org Git - flightgear.git/blob - src/Environment/realwx_ctrl.cxx
Environment controller overhaul
[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 "tiedpropertylist.hxx"
29 #include "metarproperties.hxx"
30 #include "metarairportfilter.hxx"
31 #include "fgmetar.hxx"
32
33 #include <Main/fg_props.hxx>
34
35 #include <simgear/structure/exception.hxx>
36 #include <simgear/misc/strutils.hxx>
37 #include <algorithm>
38 #if defined(ENABLE_THREADS)
39 #include <OpenThreads/Thread>
40 #include <simgear/threads/SGQueue.hxx>
41 #endif
42
43
44 namespace Environment {
45
46 class BasicRealWxController : public RealWxController
47 {
48 public:
49     BasicRealWxController( SGPropertyNode_ptr rootNode );
50     virtual ~BasicRealWxController ();
51
52     virtual void init ();
53     virtual void reinit ();
54
55 protected:
56     void bind();
57     void unbind();
58
59     SGPropertyNode_ptr _rootNode;
60     SGPropertyNode_ptr _longitude_n;
61     SGPropertyNode_ptr _latitude_n;
62     SGPropertyNode_ptr _ground_elevation_n;
63
64     bool _enabled;
65     TiedPropertyList _tiedProperties;
66     MetarProperties  _metarProperties;
67 };
68
69 /* -------------------------------------------------------------------------------- */
70 /*
71 Properties
72  ~/enabled: bool              Enables/Disables the realwx controller
73  ~/metar[1..n]: string        Target property path for metar data
74  */
75
76 BasicRealWxController::BasicRealWxController( SGPropertyNode_ptr rootNode ) :
77   _rootNode(rootNode),
78   _longitude_n( fgGetNode( "/position/longitude-deg", true )),
79   _latitude_n( fgGetNode( "/position/latitude-deg", true )),
80   _ground_elevation_n( fgGetNode( "/position/ground-elev-m", true )),
81   _enabled(true),
82   _metarProperties( fgGetNode( rootNode->getStringValue("metar", "/environment/metar"), true ) )
83 {
84 }
85
86 BasicRealWxController::~BasicRealWxController()
87 {
88 }
89
90 void BasicRealWxController::init()
91 {
92     update(0); // fetch data ASAP
93 }
94
95 void BasicRealWxController::reinit()
96 {
97 }
98
99 void BasicRealWxController::bind()
100 {
101     _tiedProperties.setRoot( _rootNode );
102     _tiedProperties.Tie( "enabled", &_enabled );
103 }
104
105 void BasicRealWxController::unbind()
106 {
107     _tiedProperties.Untie();
108 }
109
110 /* -------------------------------------------------------------------------------- */
111
112 class NoaaMetarRealWxController : public BasicRealWxController {
113 public:
114     NoaaMetarRealWxController( SGPropertyNode_ptr rootNode );
115     virtual ~NoaaMetarRealWxController();
116     virtual void update (double delta_time_sec);
117
118     class MetarLoadRequest {
119     public:
120         MetarLoadRequest( const string & stationId ) {
121             _stationId = stationId;
122             _proxyHost = fgGetNode("/sim/presets/proxy/host", true)->getStringValue();
123             _proxyPort = fgGetNode("/sim/presets/proxy/port", true)->getStringValue();
124             _proxyAuth = fgGetNode("/sim/presets/proxy/authentication", true)->getStringValue();
125         }
126         string _stationId;
127         string _proxyHost;
128         string _proxyPort;
129         string _proxyAuth;
130     private:
131     };
132 private:
133     double _metarTimeToLive;
134     double _positionTimeToLive;
135     double _minimumRequestInterval;
136     
137     SGPropertyNode_ptr _metarDataNode;
138     SGPropertyNode_ptr _metarValidNode;
139     SGPropertyNode_ptr _metarStationIdNode;
140
141
142 #if defined(ENABLE_THREADS)
143      class MetarLoadThread : public OpenThreads::Thread {
144      public:
145          MetarLoadThread( NoaaMetarRealWxController & controller );
146          void requestMetar( const MetarLoadRequest & metarRequest );
147          bool hasMetar() { return _responseQueue.size() > 0; }
148          string getMetar() { return _responseQueue.pop(); }
149          virtual void run();
150      private:
151         NoaaMetarRealWxController & _controller;
152         SGBlockingQueue <MetarLoadRequest> _requestQueue;
153         SGBlockingQueue <string> _responseQueue;
154      };
155
156      MetarLoadThread * _metarLoadThread;
157 #endif
158 };
159
160 NoaaMetarRealWxController::NoaaMetarRealWxController( SGPropertyNode_ptr rootNode ) :
161   BasicRealWxController(rootNode),
162   _metarTimeToLive(0.0),
163   _positionTimeToLive(0.0),
164   _minimumRequestInterval(0.0),
165   _metarDataNode(_metarProperties.get_root_node()->getNode("data",true)),
166   _metarValidNode(_metarProperties.get_root_node()->getNode("valid",true)),
167   _metarStationIdNode(_metarProperties.get_root_node()->getNode("station-id",true))
168 {
169 #if defined(ENABLE_THREADS)
170     _metarLoadThread = new MetarLoadThread(*this);
171     _metarLoadThread->start();
172 #endif
173 }
174
175 NoaaMetarRealWxController::~NoaaMetarRealWxController()
176 {
177 #if defined(ENABLE_THREADS)
178     if( _metarLoadThread ) {
179         MetarLoadRequest request("");
180         _metarLoadThread->requestMetar(request);
181         _metarLoadThread->join();
182         delete _metarLoadThread;
183     }
184 #endif // ENABLE_THREADS
185 }
186
187 void NoaaMetarRealWxController::update( double dt )
188 {
189     if( !_enabled )
190         return;
191
192     if( _metarLoadThread->hasMetar() )
193         _metarDataNode->setStringValue( _metarLoadThread->getMetar() );
194
195     _metarTimeToLive -= dt;
196     _positionTimeToLive -= dt;
197     _minimumRequestInterval -= dt;
198
199     bool valid = _metarValidNode->getBoolValue();
200     string stationId = valid ? _metarStationIdNode->getStringValue() : "";
201
202
203     if( _metarTimeToLive <= 0.0 ) {
204         valid = false;
205         _metarTimeToLive = 900;
206         _positionTimeToLive = 0;
207     }
208
209     if( _positionTimeToLive <= 0.0 || valid == false ) {
210         _positionTimeToLive = 60.0;
211
212         SGGeod pos = SGGeod::fromDeg(_longitude_n->getDoubleValue(), _latitude_n->getDoubleValue());
213
214         FGAirport * nearestAirport = FGAirport::findClosest(pos, 10000.0, MetarAirportFilter::instance() );
215         if( nearestAirport == NULL ) {
216             SG_LOG(SG_ALL,SG_WARN,"RealWxController::update can't find airport with METAR within 10000NM"  );
217             return;
218         }
219
220         if( stationId != nearestAirport->ident() ) {
221             valid = false;
222             stationId = nearestAirport->ident();
223         }
224
225     }
226
227     if( !valid ) {
228         if( _minimumRequestInterval <= 0 && stationId.length() > 0 ) {
229             MetarLoadRequest request( stationId );
230             _metarLoadThread->requestMetar( request );
231             _minimumRequestInterval = 10;
232         }
233     }
234
235 }
236
237 /* -------------------------------------------------------------------------------- */
238
239 #if defined(ENABLE_THREADS)
240 NoaaMetarRealWxController::MetarLoadThread::MetarLoadThread( NoaaMetarRealWxController & controller ) :
241   _controller(controller)
242 {
243 }
244
245 void NoaaMetarRealWxController::MetarLoadThread::requestMetar( const MetarLoadRequest & metarRequest )
246 {
247     if( _requestQueue.size() > 10 ) {
248         SG_LOG(SG_ALL,SG_ALERT,
249             "NoaaMetarRealWxController::MetarLoadThread::requestMetar() more than 10 outstanding METAR requests, dropping " 
250             << metarRequest._stationId );
251         return;
252     }
253
254     _requestQueue.push( metarRequest );
255 }
256
257 void NoaaMetarRealWxController::MetarLoadThread::run()
258 {
259     for( ;; ) {
260         const MetarLoadRequest request = _requestQueue.pop();
261
262         if( request._stationId.size() == 0 )
263             break;
264
265        SGSharedPtr<FGMetar> result = NULL;
266
267         try {
268             result = new FGMetar( request._stationId, request._proxyHost, request._proxyPort, request._proxyAuth );
269         } catch (const sg_io_exception& e) {
270             SG_LOG( SG_GENERAL, SG_WARN, "NoaaMetarRealWxController::fetchMetar(): can't get METAR for " 
271                                         << request._stationId << ":" << e.getFormattedMessage().c_str() );
272             continue;
273         }
274
275         if( result == NULL )
276             continue;
277
278         string reply = result->getData();
279         std::replace(reply.begin(), reply.end(), '\n', ' ');
280         string metar = simgear::strutils::strip( reply );
281         if( metar.length() > 0 )
282             _responseQueue.push( metar );
283     }
284 }
285 #endif
286
287 /* -------------------------------------------------------------------------------- */
288
289 RealWxController * RealWxController::createInstance( SGPropertyNode_ptr rootNode )
290 {
291 //    string dataSource = rootNode->getStringValue("data-source", "noaa" );
292 //    if( dataSource == "nwx" ) {
293 //      return new NwxMetarRealWxController( rootNode );
294 //    } else {
295       return new NoaaMetarRealWxController( rootNode );
296 //    }
297 }
298
299 /* -------------------------------------------------------------------------------- */
300
301 } // namespace Environment