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 <simgear/debug/logstream.hxx>
32 #include <simgear/environment/metar.hxx>
33 #include <simgear/structure/exception.hxx>
35 #include <simgear/io/HTTPClient.hxx>
36 #include <simgear/io/HTTPRequest.hxx>
37 #include <simgear/io/raw_socket.hxx>
38 #include <simgear/timing/timestamp.hxx>
41 using namespace simgear;
43 class MetarRequest : public HTTP::Request
51 MetarRequest(const std::string& stationId) :
52 HTTP::Request("http://weather.noaa.gov/pub/data/observations/metar/stations/" + stationId + ".TXT"),
61 virtual void responseHeader(const string& key, const string& value)
63 if (key == "x-metarproxy") {
68 virtual void gotBodyData(const char* s, int n)
70 metarData += string(s, n);
73 virtual void responseComplete()
75 if (responseCode() == 200) {
78 SG_LOG(SG_ENVIRONMENT, SG_WARN, "metar download failed:" << url() << ": reason:" << responseReason());
85 #if defined(__linux__) || defined(__sun) || defined(__CYGWIN__) \
86 || defined( __FreeBSD__ ) || defined ( sgi )
87 # define R "\033[31;1m" // red
88 # define G "\033[32;1m" // green
89 # define Y "\033[33;1m" // yellow
90 # define B "\033[34;1m" // blue
91 # define M "\033[35;1m" // magenta
92 # define C "\033[36;1m" // cyan
93 # define W "\033[37;1m" // white
94 # define N "\033[m" // normal
108 const char *azimuthName(double d)
110 const char *dir[] = {
111 "N", "NNE", "NE", "ENE",
112 "E", "ESE", "SE", "SSE",
113 "S", "SSW", "SW", "WSW",
114 "W", "WNW", "NW", "NNW"
121 return dir[int(d / 22.5)];
125 // round double to 10^g
126 double rnd(double r, int g = 0)
128 double f = pow(10.0, g);
129 return f * floor(r / f + 0.5);
133 ostream& operator<<(ostream& s, const SGMetarVisibility& v)
136 int m = v.getModifier();
138 if (m == SGMetarVisibility::GREATER_THAN)
140 else if (m == SGMetarVisibility::LESS_THAN)
146 double dist = rnd(v.getVisibility_m(), 1);
148 buf << rnd(dist, 1) << " m";
150 buf << rnd(dist / 1000.0, -1) << " km";
152 const char *dir = "";
154 if ((i = v.getDirection()) != -1) {
155 dir = azimuthName(i);
158 buf << "\t\t\t\t\t" << mod << rnd(v.getVisibility_sm(), -1) << " US-miles " << dir;
159 return s << buf.str();
163 void printReport(SGMetar *m)
165 #define NaN SGMetarNaN
171 if ((i = m->getReportType()) == SGMetar::AUTO)
172 s = "\t\t(automatically generated)";
173 else if (i == SGMetar::COR)
174 s = "\t\t(manually corrected)";
175 else if (i == SGMetar::RTD)
176 s = "\t\t(routine delayed)";
180 cout << "METAR Report" << s << endl;
181 cout << "============" << endl;
182 cout << "Airport-Id:\t\t" << m->getId() << endl;
186 int year = m->getYear();
187 int month = m->getMonth();
188 cout << "Report time:\t\t" << year << '/' << month << '/' << m->getDay();
189 cout << ' ' << m->getHour() << ':';
190 cout << setw(2) << setfill('0') << m->getMinute() << " UTC" << endl;
194 SGMetarVisibility minvis = m->getMinVisibility();
195 SGMetarVisibility maxvis = m->getMaxVisibility();
196 double min = minvis.getVisibility_m();
197 double max = maxvis.getVisibility_m();
200 cout << "min. Visibility:\t" << minvis << endl;
201 cout << "max. Visibility:\t" << maxvis << endl;
203 cout << "Visibility:\t\t" << minvis << endl;
207 // directed visibility
208 const SGMetarVisibility *dirvis = m->getDirVisibility();
209 for (i = 0; i < 8; i++, dirvis++)
210 if (dirvis->getVisibility_m() != NaN)
211 cout << "\t\t\t" << *dirvis << endl;
214 // vertical visibility
215 SGMetarVisibility vertvis = m->getVertVisibility();
216 if ((d = vertvis.getVisibility_ft()) != NaN)
217 cout << "Vert. visibility:\t" << vertvis << endl;
218 else if (vertvis.getModifier() == SGMetarVisibility::NOGO)
219 cout << "Vert. visibility:\timpossible to determine" << endl;
223 d = m->getWindSpeed_kmh();
224 cout << "Wind:\t\t\t";
226 cout << "none" << endl;
228 if ((i = m->getWindDir()) == -1)
229 cout << "from variable directions";
231 cout << "from the " << azimuthName(i) << " (" << i << "°)";
232 cout << " at " << rnd(d, -1) << " km/h";
234 cout << "\t\t" << rnd(m->getWindSpeed_kt(), -1) << " kt";
235 cout << " = " << rnd(m->getWindSpeed_mph(), -1) << " mph";
236 cout << " = " << rnd(m->getWindSpeed_mps(), -1) << " m/s";
239 if ((d = m->getGustSpeed_kmh()) != NaN) {
240 cout << "\t\t\twith gusts at " << rnd(d, -1) << " km/h";
241 cout << "\t\t\t" << rnd(m->getGustSpeed_kt(), -1) << " kt";
242 cout << " = " << rnd(m->getGustSpeed_mph(), -1) << " mph";
243 cout << " = " << rnd(m->getGustSpeed_mps(), -1) << " m/s";
247 int from = m->getWindRangeFrom();
248 int to = m->getWindRangeTo();
250 cout << "\t\t\tvariable from " << azimuthName(from);
251 cout << " to " << azimuthName(to);
252 cout << " (" << from << "°--" << to << "°)" << endl;
257 // temperature/humidity/air pressure
258 if ((d = m->getTemperature_C()) != NaN) {
259 cout << "Temperature:\t\t" << d << "°C\t\t\t\t\t";
260 cout << rnd(m->getTemperature_F(), -1) << "°F" << endl;
262 if ((d = m->getDewpoint_C()) != NaN) {
263 cout << "Dewpoint:\t\t" << d << "°C\t\t\t\t\t";
264 cout << rnd(m->getDewpoint_F(), -1) << "°F" << endl;
265 cout << "Rel. Humidity:\t\t" << rnd(m->getRelHumidity()) << "%" << endl;
268 if ((d = m->getPressure_hPa()) != NaN) {
269 cout << "Pressure:\t\t" << rnd(d) << " hPa\t\t\t\t";
270 cout << rnd(m->getPressure_inHg(), -2) << " in. Hg" << endl;
275 vector<string> wv = m->getWeather();
276 vector<string>::iterator weather;
277 for (i = 0, weather = wv.begin(); weather != wv.end(); weather++, i++) {
278 cout << (i ? ", " : "Weather:\t\t") << weather->c_str();
285 const char *coverage_string[5] = {
286 "clear skies", "few clouds", "scattered clouds", "broken clouds", "sky overcast"
288 vector<SGMetarCloud> cv = m->getClouds();
289 vector<SGMetarCloud>::iterator cloud;
290 for (lineno = 0, cloud = cv.begin(); cloud != cv.end(); cloud++, lineno++) {
291 cout << (lineno ? "\t\t\t" : "Sky condition:\t\t");
293 if ((i = cloud->getCoverage()) != -1)
294 cout << coverage_string[i];
295 if ((d = cloud->getAltitude_ft()) != NaN)
296 cout << " at " << rnd(d, 1) << " ft";
297 if ((s = cloud->getTypeLongString()))
298 cout << " (" << s << ')';
300 cout << "\t\t\t" << rnd(cloud->getAltitude_m(), 1) << " m";
306 map<string, SGMetarRunway> rm = m->getRunways();
307 map<string, SGMetarRunway>::iterator runway;
308 for (runway = rm.begin(); runway != rm.end(); runway++) {
310 if (!strcmp(runway->first.c_str(), "ALL"))
311 cout << "All runways:\t\t";
313 cout << "Runway " << runway->first << ":\t\t";
314 SGMetarRunway rwy = runway->second;
316 // assemble surface string
317 vector<string> surface;
318 if ((s = rwy.getDepositString()) && strlen(s))
319 surface.push_back(s);
320 if ((s = rwy.getExtentString()) && strlen(s))
321 surface.push_back(s);
322 if ((d = rwy.getDepth()) != NaN) {
323 sprintf(buf, "%.1lf mm", d * 1000.0);
324 surface.push_back(buf);
326 if ((s = rwy.getFrictionString()) && strlen(s))
327 surface.push_back(s);
328 if ((d = rwy.getFriction()) != NaN) {
329 sprintf(buf, "friction: %.2lf", d);
330 surface.push_back(buf);
333 if (surface.size()) {
334 vector<string>::iterator rwysurf = surface.begin();
335 for (i = 0; rwysurf != surface.end(); rwysurf++, i++) {
343 // assemble visibility string
344 SGMetarVisibility minvis = rwy.getMinVisibility();
345 SGMetarVisibility maxvis = rwy.getMaxVisibility();
346 if ((d = minvis.getVisibility_m()) != NaN) {
348 cout << endl << "\t\t\t";
351 if (maxvis.getVisibility_m() != d) {
352 cout << endl << "\t\t\t" << maxvis << endl;
356 if (rwy.getWindShear()) {
358 cout << endl << "\t\t\t";
359 cout << "critical wind shear" << endl;
368 void printArgs(SGMetar *m, double airport_elevation)
370 #define NaN SGMetarNaN
376 sprintf(buf, "--airport=%s ", m->getId());
380 sprintf(buf, "--start-date-gmt=%4d:%02d:%02d:%02d:%02d:00 ",
381 m->getYear(), m->getMonth(), m->getDay(),
382 m->getHour(), m->getMinute());
386 const char *coverage_string[5] = {
387 "clear", "few", "scattered", "broken", "overcast"
389 vector<SGMetarCloud> cv = m->getClouds();
390 vector<SGMetarCloud>::iterator cloud;
391 for (i = 0, cloud = cv.begin(); i < 5; i++) {
393 double altitude = -99999;
394 if (cloud != cv.end()) {
395 coverage = cloud->getCoverage();
396 altitude = coverage ? cloud->getAltitude_ft() + airport_elevation : -99999;
399 sprintf(buf, "--prop:/environment/clouds/layer[%d]/coverage=%s ", i, coverage_string[coverage]);
401 sprintf(buf, "--prop:/environment/clouds/layer[%d]/elevation-ft=%.0lf ", i, altitude);
403 sprintf(buf, "--prop:/environment/clouds/layer[%d]/thickness-ft=500 ", i);
407 // environment (temperature, dewpoint, visibility, pressure)
408 // metar sets don't provide aloft information; we have to
409 // set the same values for all boundary levels
410 int wind_dir = m->getWindDir();
411 double visibility = m->getMinVisibility().getVisibility_m();
412 double dewpoint = m->getDewpoint_C();
413 double temperature = m->getTemperature_C();
414 double pressure = m->getPressure_inHg();
415 double wind_speed = m->getWindSpeed_kt();
416 double elevation = -100;
417 for (i = 0; i < 3; i++, elevation += 2000.0) {
418 sprintf(buf, "--prop:/environment/config/boundary/entry[%d]/", i);
419 int pos = strlen(buf);
421 sprintf(&buf[pos], "elevation-ft=%.0lf", elevation);
423 sprintf(&buf[pos], "turbulence-norm=%.0lf", 0.0);
426 if (visibility != NaN) {
427 sprintf(&buf[pos], "visibility-m=%.0lf", visibility);
430 if (temperature != NaN) {
431 sprintf(&buf[pos], "temperature-degc=%.0lf", temperature);
434 if (dewpoint != NaN) {
435 sprintf(&buf[pos], "dewpoint-degc=%.0lf", dewpoint);
438 if (pressure != NaN) {
439 sprintf(&buf[pos], "pressure-sea-level-inhg=%.0lf", pressure);
442 if (wind_dir != NaN) {
443 sprintf(&buf[pos], "wind-from-heading-deg=%d", wind_dir);
446 if (wind_speed != NaN) {
447 sprintf(&buf[pos], "wind-speed-kt=%.0lf", wind_speed);
453 int range_from = m->getWindRangeFrom();
454 int range_to = m->getWindRangeTo();
455 double gust_speed = m->getGustSpeed_kt();
456 if (wind_speed != NaN && wind_dir != -1) {
457 strcpy(buf, "--wind=");
458 if (range_from != -1 && range_to != -1)
459 sprintf(&buf[strlen(buf)], "%d:%d", range_from, range_to);
461 sprintf(&buf[strlen(buf)], "%d", wind_dir);
462 sprintf(&buf[strlen(buf)], "@%.0lf", wind_speed);
463 if (gust_speed != NaN)
464 sprintf(&buf[strlen(buf)], ":%.0lf", gust_speed);
470 //cout << "fgfs" << endl;
471 vector<string>::iterator arg;
472 for (i = 0, arg = args.begin(); arg != args.end(); i++, arg++) {
473 cout << "\t" << *arg << endl;
480 void getproxy(string& host, string& port)
485 const char *p = getenv("http_proxy");
490 if (!strncmp(p, "http://", 7))
499 for (t = s + strlen(s); t > s; t--)
500 if (!isspace(t[-1]) && t[-1] != '/')
516 "Usage: metar [-v] [-e elevation] [-r|-c] <list of ICAO airport ids or METAR strings>\n"
519 " -h|--help show this help\n"
520 " -v|--verbose verbose output\n"
521 " -r|--report print report (default)\n"
522 " -c|--command-line print command line\n"
523 " -e E|--elevation E set airport elevation to E meters\n"
524 " (added to cloud bases in command line mode)\n"
526 " http_proxy set proxy in the form \"http://host:port/\"\n"
529 " $ metar ksfo koak\n"
530 " $ metar -c ksfo -r ksfo\n"
531 " $ metar \"LOWL 161500Z 19004KT 160V240 9999 FEW035 SCT300 29/23 Q1006 NOSIG\"\n"
532 " $ fgfs `metar -e 183 -c loww`\n"
533 " $ http_proxy=http://localhost:3128/ metar ksfo\n"
538 int main(int argc, char *argv[])
541 bool verbose = false;
542 double elevation = 0.0;
549 string proxy_host, proxy_port;
550 getproxy(proxy_host, proxy_port);
552 Socket::initSockets();
555 http.setProxy(proxy_host, atoi(proxy_port.c_str()));
557 for (int i = 1; i < argc; i++) {
558 if (!strcmp(argv[i], "-h") || !strcmp(argv[i], "--help"))
560 else if (!strcmp(argv[i], "-v") || !strcmp(argv[i], "--verbose"))
562 else if (!strcmp(argv[i], "-r") || !strcmp(argv[i], "--report"))
564 else if (!strcmp(argv[i], "-c") || !strcmp(argv[i], "--command-line"))
566 else if (!strcmp(argv[i], "-e") || !strcmp(argv[i], "--elevation")) {
568 cerr << "-e option used without elevation" << endl;
571 elevation = strtod(argv[i], 0);
573 static bool shown = false;
574 if (verbose && !shown) {
575 cerr << "Proxy host: '" << proxy_host << "'" << endl;
576 cerr << "Proxy port: '" << proxy_port << "'" << endl << endl;
581 MetarRequest* mr = new MetarRequest(argv[i]);
582 HTTP::Request_ptr own(mr);
583 http.makeRequest(mr);
585 // spin until the request completes, fails or times out
586 SGTimeStamp start(SGTimeStamp::now());
587 while (start.elapsedMSec() < 8000) {
589 if (mr->complete || mr->failed) {
592 SGTimeStamp::sleepForMSec(1);
596 throw sg_io_exception("metar download failed (or timed out)");
598 SGMetar *m = new SGMetar(mr->metarData);
600 //SGMetar *m = new SGMetar("2004/01/11 01:20\nLOWG 110120Z AUTO VRB01KT 0050 1600N R35/0600 FG M06/M06 Q1019 88//////\n");
603 cerr << G"INPUT: " << m->getData() << ""N << endl;
605 const char *unused = m->getUnusedData();
607 cerr << R"UNUSED: " << unused << ""N << endl;
613 printArgs(m, elevation);
616 } catch (const sg_io_exception& e) {
617 cerr << R"ERROR: " << e.getFormattedMessage().c_str() << ""N << endl << endl;