1 // metar interface class demo
3 // Written by Melchior FRANZ, started December 2003.
5 // Copyright (C) 2003 Melchior FRANZ - mfranz@aon.at
7 // This program is free software; you can redistribute it and/or
8 // modify it under the terms of the GNU General Public License as
9 // published by the Free Software Foundation; either version 2 of the
10 // License, or (at your option) any later version.
12 // This program is distributed in the hope that it will be useful, but
13 // WITHOUT ANY WARRANTY; without even the implied warranty of
14 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 // General Public License for more details.
17 // You should have received a copy of the GNU General Public License
18 // along with this program; if not, write to the Free Software
19 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
31 #include <boost/algorithm/string.hpp>
33 #include <simgear/environment/metar.hxx>
34 #include <simgear/structure/exception.hxx>
36 #include <simgear/io/HTTPClient.hxx>
37 #include <simgear/io/HTTPMemoryRequest.hxx>
38 #include <simgear/io/raw_socket.hxx>
39 #include <simgear/timing/timestamp.hxx>
42 using namespace simgear;
45 #if defined(__linux__) || defined(__sun) || defined(__CYGWIN__) || defined( __FreeBSD__ ) || defined ( sgi )
46 # define R "\033[31;1m" // red
47 # define G "\033[32;1m" // green
48 # define Y "\033[33;1m" // yellow
49 # define B "\033[34;1m" // blue
50 # define M "\033[35;1m" // magenta
51 # define C "\033[36;1m" // cyan
52 # define W "\033[37;1m" // white
53 # define N "\033[m" // normal
67 const char *azimuthName(double d)
70 "N", "NNE", "NE", "ENE",
71 "E", "ESE", "SE", "SSE",
72 "S", "SSW", "SW", "WSW",
73 "W", "WNW", "NW", "NNW"
80 return dir[int(d / 22.5)];
84 // round double to 10^g
85 double rnd(double r, int g = 0)
87 double f = pow(10.0, g);
88 return f * floor(r / f + 0.5);
92 ostream& operator<<(ostream& s, const SGMetarVisibility& v)
95 int m = v.getModifier();
97 if (m == SGMetarVisibility::GREATER_THAN)
99 else if (m == SGMetarVisibility::LESS_THAN)
105 double dist = rnd(v.getVisibility_m(), 1);
107 buf << rnd(dist, 1) << " m";
109 buf << rnd(dist / 1000.0, -1) << " km";
111 const char *dir = "";
113 if ((i = v.getDirection()) != -1) {
114 dir = azimuthName(i);
117 buf << "\t\t\t\t\t" << mod << rnd(v.getVisibility_sm(), -1) << " US-miles " << dir;
118 return s << buf.str();
122 void printReport(SGMetar *m)
124 #define NaN SGMetarNaN
130 if ((i = m->getReportType()) == SGMetar::AUTO)
131 s = "\t\t(automatically generated)";
132 else if (i == SGMetar::COR)
133 s = "\t\t(manually corrected)";
134 else if (i == SGMetar::RTD)
135 s = "\t\t(routine delayed)";
139 cout << "METAR Report" << s << endl;
140 cout << "============" << endl;
141 cout << "Airport-Id:\t\t" << m->getId() << endl;
145 int year = m->getYear();
146 int month = m->getMonth();
147 cout << "Report time:\t\t" << year << '/' << month << '/' << m->getDay();
148 cout << ' ' << m->getHour() << ':';
149 cout << setw(2) << setfill('0') << m->getMinute() << " UTC" << endl;
153 SGMetarVisibility minvis = m->getMinVisibility();
154 SGMetarVisibility maxvis = m->getMaxVisibility();
155 double min = minvis.getVisibility_m();
156 double max = maxvis.getVisibility_m();
159 cout << "min. Visibility:\t" << minvis << endl;
160 cout << "max. Visibility:\t" << maxvis << endl;
162 cout << "Visibility:\t\t" << minvis << endl;
166 // directed visibility
167 const SGMetarVisibility *dirvis = m->getDirVisibility();
168 for (i = 0; i < 8; i++, dirvis++)
169 if (dirvis->getVisibility_m() != NaN)
170 cout << "\t\t\t" << *dirvis << endl;
173 // vertical visibility
174 SGMetarVisibility vertvis = m->getVertVisibility();
175 if ((d = vertvis.getVisibility_ft()) != NaN)
176 cout << "Vert. visibility:\t" << vertvis << endl;
177 else if (vertvis.getModifier() == SGMetarVisibility::NOGO)
178 cout << "Vert. visibility:\timpossible to determine" << endl;
182 d = m->getWindSpeed_kmh();
183 cout << "Wind:\t\t\t";
185 cout << "none" << endl;
187 if ((i = m->getWindDir()) == -1)
188 cout << "from variable directions";
190 cout << "from the " << azimuthName(i) << " (" << i << "°)";
191 cout << " at " << rnd(d, -1) << " km/h";
193 cout << "\t\t" << rnd(m->getWindSpeed_kt(), -1) << " kt";
194 cout << " = " << rnd(m->getWindSpeed_mph(), -1) << " mph";
195 cout << " = " << rnd(m->getWindSpeed_mps(), -1) << " m/s";
198 if ((d = m->getGustSpeed_kmh()) != NaN) {
199 cout << "\t\t\twith gusts at " << rnd(d, -1) << " km/h";
200 cout << "\t\t\t" << rnd(m->getGustSpeed_kt(), -1) << " kt";
201 cout << " = " << rnd(m->getGustSpeed_mph(), -1) << " mph";
202 cout << " = " << rnd(m->getGustSpeed_mps(), -1) << " m/s";
206 int from = m->getWindRangeFrom();
207 int to = m->getWindRangeTo();
209 cout << "\t\t\tvariable from " << azimuthName(from);
210 cout << " to " << azimuthName(to);
211 cout << " (" << from << "°--" << to << "°)" << endl;
216 // temperature/humidity/air pressure
217 if ((d = m->getTemperature_C()) != NaN) {
218 cout << "Temperature:\t\t" << d << "°C\t\t\t\t\t";
219 cout << rnd(m->getTemperature_F(), -1) << "°F" << endl;
221 if ((d = m->getDewpoint_C()) != NaN) {
222 cout << "Dewpoint:\t\t" << d << "°C\t\t\t\t\t";
223 cout << rnd(m->getDewpoint_F(), -1) << "°F" << endl;
224 cout << "Rel. Humidity:\t\t" << rnd(m->getRelHumidity()) << "%" << endl;
227 if ((d = m->getPressure_hPa()) != NaN) {
228 cout << "Pressure:\t\t" << rnd(d) << " hPa\t\t\t\t";
229 cout << rnd(m->getPressure_inHg(), -2) << " in. Hg" << endl;
234 vector<string> wv = m->getWeather();
235 vector<string>::iterator weather;
236 for (i = 0, weather = wv.begin(); weather != wv.end(); weather++, i++) {
237 cout << (i ? ", " : "Weather:\t\t") << weather->c_str();
244 const char *coverage_string[5] = {
245 "clear skies", "few clouds", "scattered clouds", "broken clouds", "sky overcast"
247 vector<SGMetarCloud> cv = m->getClouds();
248 vector<SGMetarCloud>::iterator cloud;
249 for (lineno = 0, cloud = cv.begin(); cloud != cv.end(); cloud++, lineno++) {
250 cout << (lineno ? "\t\t\t" : "Sky condition:\t\t");
252 if ((i = cloud->getCoverage()) != -1)
253 cout << coverage_string[i];
254 if ((d = cloud->getAltitude_ft()) != NaN)
255 cout << " at " << rnd(d, 1) << " ft";
256 if ((s = cloud->getTypeLongString()))
257 cout << " (" << s << ')';
259 cout << "\t\t\t" << rnd(cloud->getAltitude_m(), 1) << " m";
265 map<string, SGMetarRunway> rm = m->getRunways();
266 map<string, SGMetarRunway>::iterator runway;
267 for (runway = rm.begin(); runway != rm.end(); runway++) {
269 if (!strcmp(runway->first.c_str(), "ALL"))
270 cout << "All runways:\t\t";
272 cout << "Runway " << runway->first << ":\t\t";
273 SGMetarRunway rwy = runway->second;
275 // assemble surface string
276 vector<string> surface;
277 if ((s = rwy.getDepositString()) && strlen(s))
278 surface.push_back(s);
279 if ((s = rwy.getExtentString()) && strlen(s))
280 surface.push_back(s);
281 if ((d = rwy.getDepth()) != NaN) {
282 sprintf(buf, "%.1lf mm", d * 1000.0);
283 surface.push_back(buf);
285 if ((s = rwy.getFrictionString()) && strlen(s))
286 surface.push_back(s);
287 if ((d = rwy.getFriction()) != NaN) {
288 sprintf(buf, "friction: %.2lf", d);
289 surface.push_back(buf);
292 if (! surface.empty()) {
293 vector<string>::iterator rwysurf = surface.begin();
294 for (i = 0; rwysurf != surface.end(); rwysurf++, i++) {
302 // assemble visibility string
303 SGMetarVisibility minvis = rwy.getMinVisibility();
304 SGMetarVisibility maxvis = rwy.getMaxVisibility();
305 if ((d = minvis.getVisibility_m()) != NaN) {
307 cout << endl << "\t\t\t";
310 if (maxvis.getVisibility_m() != d) {
311 cout << endl << "\t\t\t" << maxvis << endl;
315 if (rwy.getWindShear()) {
317 cout << endl << "\t\t\t";
318 cout << "critical wind shear" << endl;
327 void printArgs(SGMetar *m, double airport_elevation)
329 #define NaN SGMetarNaN
335 sprintf(buf, "--airport=%s ", m->getId());
339 sprintf(buf, "--start-date-gmt=%4d:%02d:%02d:%02d:%02d:00 ",
340 m->getYear(), m->getMonth(), m->getDay(),
341 m->getHour(), m->getMinute());
345 const char *coverage_string[5] = {
346 "clear", "few", "scattered", "broken", "overcast"
348 vector<SGMetarCloud> cv = m->getClouds();
349 vector<SGMetarCloud>::iterator cloud;
350 for (i = 0, cloud = cv.begin(); i < 5; i++) {
352 double altitude = -99999;
353 if (cloud != cv.end()) {
354 coverage = cloud->getCoverage();
355 altitude = coverage ? cloud->getAltitude_ft() + airport_elevation : -99999;
358 sprintf(buf, "--prop:/environment/clouds/layer[%d]/coverage=%s ", i, coverage_string[coverage]);
360 sprintf(buf, "--prop:/environment/clouds/layer[%d]/elevation-ft=%.0lf ", i, altitude);
362 sprintf(buf, "--prop:/environment/clouds/layer[%d]/thickness-ft=500 ", i);
366 // environment (temperature, dewpoint, visibility, pressure)
367 // metar sets don't provide aloft information; we have to
368 // set the same values for all boundary levels
369 int wind_dir = m->getWindDir();
370 double visibility = m->getMinVisibility().getVisibility_m();
371 double dewpoint = m->getDewpoint_C();
372 double temperature = m->getTemperature_C();
373 double pressure = m->getPressure_inHg();
374 double wind_speed = m->getWindSpeed_kt();
375 double elevation = -100;
376 for (i = 0; i < 3; i++, elevation += 2000.0) {
377 sprintf(buf, "--prop:/environment/config/boundary/entry[%d]/", i);
378 int pos = strlen(buf);
380 sprintf(&buf[pos], "elevation-ft=%.0lf", elevation);
382 sprintf(&buf[pos], "turbulence-norm=%.0lf", 0.0);
385 if (visibility != NaN) {
386 sprintf(&buf[pos], "visibility-m=%.0lf", visibility);
389 if (temperature != NaN) {
390 sprintf(&buf[pos], "temperature-degc=%.0lf", temperature);
393 if (dewpoint != NaN) {
394 sprintf(&buf[pos], "dewpoint-degc=%.0lf", dewpoint);
397 if (pressure != NaN) {
398 sprintf(&buf[pos], "pressure-sea-level-inhg=%.0lf", pressure);
401 if (wind_dir != NaN) {
402 sprintf(&buf[pos], "wind-from-heading-deg=%d", wind_dir);
405 if (wind_speed != NaN) {
406 sprintf(&buf[pos], "wind-speed-kt=%.0lf", wind_speed);
412 int range_from = m->getWindRangeFrom();
413 int range_to = m->getWindRangeTo();
414 double gust_speed = m->getGustSpeed_kt();
415 if (wind_speed != NaN && wind_dir != -1) {
416 strcpy(buf, "--wind=");
417 if (range_from != -1 && range_to != -1)
418 sprintf(&buf[strlen(buf)], "%d:%d", range_from, range_to);
420 sprintf(&buf[strlen(buf)], "%d", wind_dir);
421 sprintf(&buf[strlen(buf)], "@%.0lf", wind_speed);
422 if (gust_speed != NaN)
423 sprintf(&buf[strlen(buf)], ":%.0lf", gust_speed);
429 //cout << "fgfs" << endl;
430 vector<string>::iterator arg;
431 for (i = 0, arg = args.begin(); arg != args.end(); i++, arg++) {
432 cout << "\t" << *arg << endl;
439 void getproxy(string& host, string& port)
444 const char *p = getenv("http_proxy");
449 if (!strncmp(p, "http://", 7))
458 for (t = s + strlen(s); t > s; t--)
459 if (!isspace(t[-1]) && t[-1] != '/')
475 "Usage: metar [-v] [-e elevation] [-r|-c] <list of ICAO airport ids or METAR strings>\n"
478 " -h|--help show this help\n"
479 " -v|--verbose verbose output\n"
480 " -r|--report print report (default)\n"
481 " -c|--command-line print command line\n"
482 " -e E|--elevation E set airport elevation to E meters\n"
483 " (added to cloud bases in command line mode)\n"
485 " http_proxy set proxy in the form \"http://host:port/\"\n"
488 " $ metar ksfo koak\n"
489 " $ metar -c ksfo -r ksfo\n"
490 " $ metar \"LOWL 161500Z 19004KT 160V240 9999 FEW035 SCT300 29/23 Q1006 NOSIG\"\n"
491 " $ fgfs `metar -e 183 -c loww`\n"
492 " $ http_proxy=http://localhost:3128/ metar ksfo\n"
497 int main(int argc, char *argv[])
500 bool verbose = false;
501 double elevation = 0.0;
508 string proxy_host, proxy_port;
509 getproxy(proxy_host, proxy_port);
511 Socket::initSockets();
514 http.setProxy(proxy_host, atoi(proxy_port.c_str()));
516 for (int i = 1; i < argc; i++) {
517 if (!strcmp(argv[i], "-h") || !strcmp(argv[i], "--help"))
519 else if (!strcmp(argv[i], "-v") || !strcmp(argv[i], "--verbose"))
521 else if (!strcmp(argv[i], "-r") || !strcmp(argv[i], "--report"))
523 else if (!strcmp(argv[i], "-c") || !strcmp(argv[i], "--command-line"))
525 else if (!strcmp(argv[i], "-e") || !strcmp(argv[i], "--elevation")) {
527 cerr << "-e option used without elevation" << endl;
530 elevation = strtod(argv[i], 0);
532 static bool shown = false;
533 if (verbose && !shown) {
534 cerr << "Proxy host: '" << proxy_host << "'" << endl;
535 cerr << "Proxy port: '" << proxy_port << "'" << endl << endl;
541 static const std::string NOAA_BASE_URL =
542 "http://weather.noaa.gov/pub/data/observations/metar/stations/";
543 HTTP::MemoryRequest* mr = new HTTP::MemoryRequest
546 + boost::to_upper_copy<std::string>(argv[i]) + ".TXT"
548 HTTP::Request_ptr own(mr);
549 http.makeRequest(mr);
551 // spin until the request completes, fails or times out
552 SGTimeStamp start(SGTimeStamp::now());
553 while (start.elapsedMSec() < 8000) {
555 if( mr->isComplete() )
557 SGTimeStamp::sleepForMSec(1);
560 if( !mr->isComplete() )
561 throw sg_io_exception("metar download timed out");
562 if( mr->responseCode() != 200 )
564 std::cerr << "metar download failed: "
566 << " (" << mr->responseCode()
567 << " " << mr->responseReason() << ")"
569 throw sg_io_exception("metar download failed");
572 SGMetar *m = new SGMetar(mr->responseBody());
574 //SGMetar *m = new SGMetar("2004/01/11 01:20\nLOWG 110120Z AUTO VRB01KT 0050 1600N R35/0600 FG M06/M06 Q1019 88//////\n");
577 cerr << G "INPUT: " << m->getData() << "" N << endl;
579 const char *unused = m->getUnusedData();
581 cerr << R "UNUSED: " << unused << "" N << endl;
587 printArgs(m, elevation);
590 } catch (const sg_io_exception& e) {
591 cerr << R "ERROR: " << e.getFormattedMessage().c_str() << "" N << endl << endl;