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.
30 #include <simgear/debug/logstream.hxx>
31 #include <simgear/environment/metar.hxx>
32 #include <simgear/structure/exception.hxx>
34 #include <simgear/io/HTTPClient.hxx>
35 #include <simgear/io/HTTPRequest.hxx>
36 #include <simgear/timing/timestamp.hxx>
39 using namespace simgear;
41 class MetarRequest : public HTTP::Request
49 MetarRequest(const std::string& stationId) :
50 HTTP::Request("http://weather.noaa.gov/pub/data/observations/metar/stations/" + stationId + ".TXT"),
59 virtual void responseHeader(const string& key, const string& value)
61 if (key == "x-metarproxy") {
66 virtual void gotBodyData(const char* s, int n)
68 metarData += string(s, n);
71 virtual void responseComplete()
73 if (responseCode() == 200) {
76 SG_LOG(SG_ENVIRONMENT, SG_WARN, "metar download failed:" << url() << ": reason:" << responseReason());
83 #if defined(__linux__) || defined(__sun) || defined(__CYGWIN__) \
84 || defined( __FreeBSD__ ) || defined ( sgi )
85 # define R "\033[31;1m" // red
86 # define G "\033[32;1m" // green
87 # define Y "\033[33;1m" // yellow
88 # define B "\033[34;1m" // blue
89 # define M "\033[35;1m" // magenta
90 # define C "\033[36;1m" // cyan
91 # define W "\033[37;1m" // white
92 # define N "\033[m" // normal
106 const char *azimuthName(double d)
108 const char *dir[] = {
109 "N", "NNE", "NE", "ENE",
110 "E", "ESE", "SE", "SSE",
111 "S", "SSW", "SW", "WSW",
112 "W", "WNW", "NW", "NNW"
119 return dir[int(d / 22.5)];
123 // round double to 10^g
124 double rnd(double r, int g = 0)
126 double f = pow(10.0, g);
127 return f * floor(r / f + 0.5);
131 ostream& operator<<(ostream& s, const SGMetarVisibility& v)
134 int m = v.getModifier();
136 if (m == SGMetarVisibility::GREATER_THAN)
138 else if (m == SGMetarVisibility::LESS_THAN)
144 double dist = rnd(v.getVisibility_m(), 1);
146 buf << rnd(dist, 1) << " m";
148 buf << rnd(dist / 1000.0, -1) << " km";
150 const char *dir = "";
152 if ((i = v.getDirection()) != -1) {
153 dir = azimuthName(i);
156 buf << "\t\t\t\t\t" << mod << rnd(v.getVisibility_sm(), -1) << " US-miles " << dir;
157 return s << buf.str();
161 void printReport(SGMetar *m)
163 #define NaN SGMetarNaN
169 if ((i = m->getReportType()) == SGMetar::AUTO)
170 s = "\t\t(automatically generated)";
171 else if (i == SGMetar::COR)
172 s = "\t\t(manually corrected)";
173 else if (i == SGMetar::RTD)
174 s = "\t\t(routine delayed)";
178 cout << "METAR Report" << s << endl;
179 cout << "============" << endl;
180 cout << "Airport-Id:\t\t" << m->getId() << endl;
184 int year = m->getYear();
185 int month = m->getMonth();
186 cout << "Report time:\t\t" << year << '/' << month << '/' << m->getDay();
187 cout << ' ' << m->getHour() << ':';
188 cout << setw(2) << setfill('0') << m->getMinute() << " UTC" << endl;
192 SGMetarVisibility minvis = m->getMinVisibility();
193 SGMetarVisibility maxvis = m->getMaxVisibility();
194 double min = minvis.getVisibility_m();
195 double max = maxvis.getVisibility_m();
198 cout << "min. Visibility:\t" << minvis << endl;
199 cout << "max. Visibility:\t" << maxvis << endl;
201 cout << "Visibility:\t\t" << minvis << endl;
205 // directed visibility
206 const SGMetarVisibility *dirvis = m->getDirVisibility();
207 for (i = 0; i < 8; i++, dirvis++)
208 if (dirvis->getVisibility_m() != NaN)
209 cout << "\t\t\t" << *dirvis << endl;
212 // vertical visibility
213 SGMetarVisibility vertvis = m->getVertVisibility();
214 if ((d = vertvis.getVisibility_ft()) != NaN)
215 cout << "Vert. visibility:\t" << vertvis << endl;
216 else if (vertvis.getModifier() == SGMetarVisibility::NOGO)
217 cout << "Vert. visibility:\timpossible to determine" << endl;
221 d = m->getWindSpeed_kmh();
222 cout << "Wind:\t\t\t";
224 cout << "none" << endl;
226 if ((i = m->getWindDir()) == -1)
227 cout << "from variable directions";
229 cout << "from the " << azimuthName(i) << " (" << i << "°)";
230 cout << " at " << rnd(d, -1) << " km/h";
232 cout << "\t\t" << rnd(m->getWindSpeed_kt(), -1) << " kt";
233 cout << " = " << rnd(m->getWindSpeed_mph(), -1) << " mph";
234 cout << " = " << rnd(m->getWindSpeed_mps(), -1) << " m/s";
237 if ((d = m->getGustSpeed_kmh()) != NaN) {
238 cout << "\t\t\twith gusts at " << rnd(d, -1) << " km/h";
239 cout << "\t\t\t" << rnd(m->getGustSpeed_kt(), -1) << " kt";
240 cout << " = " << rnd(m->getGustSpeed_mph(), -1) << " mph";
241 cout << " = " << rnd(m->getGustSpeed_mps(), -1) << " m/s";
245 int from = m->getWindRangeFrom();
246 int to = m->getWindRangeTo();
248 cout << "\t\t\tvariable from " << azimuthName(from);
249 cout << " to " << azimuthName(to);
250 cout << " (" << from << "°--" << to << "°)" << endl;
255 // temperature/humidity/air pressure
256 if ((d = m->getTemperature_C()) != NaN) {
257 cout << "Temperature:\t\t" << d << "°C\t\t\t\t\t";
258 cout << rnd(m->getTemperature_F(), -1) << "°F" << endl;
260 if ((d = m->getDewpoint_C()) != NaN) {
261 cout << "Dewpoint:\t\t" << d << "°C\t\t\t\t\t";
262 cout << rnd(m->getDewpoint_F(), -1) << "°F" << endl;
263 cout << "Rel. Humidity:\t\t" << rnd(m->getRelHumidity()) << "%" << endl;
266 if ((d = m->getPressure_hPa()) != NaN) {
267 cout << "Pressure:\t\t" << rnd(d) << " hPa\t\t\t\t";
268 cout << rnd(m->getPressure_inHg(), -2) << " in. Hg" << endl;
273 vector<string> wv = m->getWeather();
274 vector<string>::iterator weather;
275 for (i = 0, weather = wv.begin(); weather != wv.end(); weather++, i++) {
276 cout << (i ? ", " : "Weather:\t\t") << weather->c_str();
283 const char *coverage_string[5] = {
284 "clear skies", "few clouds", "scattered clouds", "broken clouds", "sky overcast"
286 vector<SGMetarCloud> cv = m->getClouds();
287 vector<SGMetarCloud>::iterator cloud;
288 for (lineno = 0, cloud = cv.begin(); cloud != cv.end(); cloud++, lineno++) {
289 cout << (lineno ? "\t\t\t" : "Sky condition:\t\t");
291 if ((i = cloud->getCoverage()) != -1)
292 cout << coverage_string[i];
293 if ((d = cloud->getAltitude_ft()) != NaN)
294 cout << " at " << rnd(d, 1) << " ft";
295 if ((s = cloud->getTypeLongString()))
296 cout << " (" << s << ')';
298 cout << "\t\t\t" << rnd(cloud->getAltitude_m(), 1) << " m";
304 map<string, SGMetarRunway> rm = m->getRunways();
305 map<string, SGMetarRunway>::iterator runway;
306 for (runway = rm.begin(); runway != rm.end(); runway++) {
308 if (!strcmp(runway->first.c_str(), "ALL"))
309 cout << "All runways:\t\t";
311 cout << "Runway " << runway->first << ":\t\t";
312 SGMetarRunway rwy = runway->second;
314 // assemble surface string
315 vector<string> surface;
316 if ((s = rwy.getDepositString()) && strlen(s))
317 surface.push_back(s);
318 if ((s = rwy.getExtentString()) && strlen(s))
319 surface.push_back(s);
320 if ((d = rwy.getDepth()) != NaN) {
321 sprintf(buf, "%.1lf mm", d * 1000.0);
322 surface.push_back(buf);
324 if ((s = rwy.getFrictionString()) && strlen(s))
325 surface.push_back(s);
326 if ((d = rwy.getFriction()) != NaN) {
327 sprintf(buf, "friction: %.2lf", d);
328 surface.push_back(buf);
331 if (surface.size()) {
332 vector<string>::iterator rwysurf = surface.begin();
333 for (i = 0; rwysurf != surface.end(); rwysurf++, i++) {
341 // assemble visibility string
342 SGMetarVisibility minvis = rwy.getMinVisibility();
343 SGMetarVisibility maxvis = rwy.getMaxVisibility();
344 if ((d = minvis.getVisibility_m()) != NaN) {
346 cout << endl << "\t\t\t";
349 if (maxvis.getVisibility_m() != d) {
350 cout << endl << "\t\t\t" << maxvis << endl;
354 if (rwy.getWindShear()) {
356 cout << endl << "\t\t\t";
357 cout << "critical wind shear" << endl;
366 void printArgs(SGMetar *m, double airport_elevation)
368 #define NaN SGMetarNaN
374 sprintf(buf, "--airport=%s ", m->getId());
378 sprintf(buf, "--start-date-gmt=%4d:%02d:%02d:%02d:%02d:00 ",
379 m->getYear(), m->getMonth(), m->getDay(),
380 m->getHour(), m->getMinute());
384 const char *coverage_string[5] = {
385 "clear", "few", "scattered", "broken", "overcast"
387 vector<SGMetarCloud> cv = m->getClouds();
388 vector<SGMetarCloud>::iterator cloud;
389 for (i = 0, cloud = cv.begin(); i < 5; i++) {
391 double altitude = -99999;
392 if (cloud != cv.end()) {
393 coverage = cloud->getCoverage();
394 altitude = coverage ? cloud->getAltitude_ft() + airport_elevation : -99999;
397 sprintf(buf, "--prop:/environment/clouds/layer[%d]/coverage=%s ", i, coverage_string[coverage]);
399 sprintf(buf, "--prop:/environment/clouds/layer[%d]/elevation-ft=%.0lf ", i, altitude);
401 sprintf(buf, "--prop:/environment/clouds/layer[%d]/thickness-ft=500 ", i);
405 // environment (temperature, dewpoint, visibility, pressure)
406 // metar sets don't provide aloft information; we have to
407 // set the same values for all boundary levels
408 int wind_dir = m->getWindDir();
409 double visibility = m->getMinVisibility().getVisibility_m();
410 double dewpoint = m->getDewpoint_C();
411 double temperature = m->getTemperature_C();
412 double pressure = m->getPressure_inHg();
413 double wind_speed = m->getWindSpeed_kt();
414 double elevation = -100;
415 for (i = 0; i < 3; i++, elevation += 2000.0) {
416 sprintf(buf, "--prop:/environment/config/boundary/entry[%d]/", i);
417 int pos = strlen(buf);
419 sprintf(&buf[pos], "elevation-ft=%.0lf", elevation);
421 sprintf(&buf[pos], "turbulence-norm=%.0lf", 0.0);
424 if (visibility != NaN) {
425 sprintf(&buf[pos], "visibility-m=%.0lf", visibility);
428 if (temperature != NaN) {
429 sprintf(&buf[pos], "temperature-degc=%.0lf", temperature);
432 if (dewpoint != NaN) {
433 sprintf(&buf[pos], "dewpoint-degc=%.0lf", dewpoint);
436 if (pressure != NaN) {
437 sprintf(&buf[pos], "pressure-sea-level-inhg=%.0lf", pressure);
440 if (wind_dir != NaN) {
441 sprintf(&buf[pos], "wind-from-heading-deg=%d", wind_dir);
444 if (wind_speed != NaN) {
445 sprintf(&buf[pos], "wind-speed-kt=%.0lf", wind_speed);
451 int range_from = m->getWindRangeFrom();
452 int range_to = m->getWindRangeTo();
453 double gust_speed = m->getGustSpeed_kt();
454 if (wind_speed != NaN && wind_dir != -1) {
455 strcpy(buf, "--wind=");
456 if (range_from != -1 && range_to != -1)
457 sprintf(&buf[strlen(buf)], "%d:%d", range_from, range_to);
459 sprintf(&buf[strlen(buf)], "%d", wind_dir);
460 sprintf(&buf[strlen(buf)], "@%.0lf", wind_speed);
461 if (gust_speed != NaN)
462 sprintf(&buf[strlen(buf)], ":%.0lf", gust_speed);
468 //cout << "fgfs" << endl;
469 vector<string>::iterator arg;
470 for (i = 0, arg = args.begin(); arg != args.end(); i++, arg++) {
471 cout << "\t" << *arg << endl;
478 void getproxy(string& host, string& port)
483 const char *p = getenv("http_proxy");
488 if (!strncmp(p, "http://", 7))
497 for (t = s + strlen(s); t > s; t--)
498 if (!isspace(t[-1]) && t[-1] != '/')
514 "Usage: metar [-v] [-e elevation] [-r|-c] <list of ICAO airport ids or METAR strings>\n"
517 " -h|--help show this help\n"
518 " -v|--verbose verbose output\n"
519 " -r|--report print report (default)\n"
520 " -c|--command-line print command line\n"
521 " -e E|--elevation E set airport elevation to E meters\n"
522 " (added to cloud bases in command line mode)\n"
524 " http_proxy set proxy in the form \"http://host:port/\"\n"
527 " $ metar ksfo koak\n"
528 " $ metar -c ksfo -r ksfo\n"
529 " $ metar \"LOWL 161500Z 19004KT 160V240 9999 FEW035 SCT300 29/23 Q1006 NOSIG\"\n"
530 " $ fgfs `metar -e 183 -c loww`\n"
531 " $ http_proxy=http://localhost:3128/ metar ksfo\n"
536 int main(int argc, char *argv[])
539 bool verbose = false;
540 double elevation = 0.0;
547 string proxy_host, proxy_port;
548 getproxy(proxy_host, proxy_port);
551 http.setProxy(proxy_host, atoi(proxy_port.c_str()));
553 for (int i = 1; i < argc; i++) {
554 if (!strcmp(argv[i], "-h") || !strcmp(argv[i], "--help"))
556 else if (!strcmp(argv[i], "-v") || !strcmp(argv[i], "--verbose"))
558 else if (!strcmp(argv[i], "-r") || !strcmp(argv[i], "--report"))
560 else if (!strcmp(argv[i], "-c") || !strcmp(argv[i], "--command-line"))
562 else if (!strcmp(argv[i], "-e") || !strcmp(argv[i], "--elevation")) {
564 cerr << "-e option used without elevation" << endl;
567 elevation = strtod(argv[i], 0);
569 static bool shown = false;
570 if (verbose && !shown) {
571 cerr << "Proxy host: '" << proxy_host << "'" << endl;
572 cerr << "Proxy port: '" << proxy_port << "'" << endl << endl;
577 MetarRequest* mr = new MetarRequest(argv[i]);
578 HTTP::Request_ptr own(mr);
579 http.makeRequest(mr);
581 // spin until the request completes, fails or times out
582 SGTimeStamp start(SGTimeStamp::now());
583 while (start.elapsedMSec() < 8000) {
585 if (mr->complete || mr->failed) {
588 SGTimeStamp::sleepForMSec(1);
592 throw sg_io_exception("metar download failed (or timed out)");
594 SGMetar *m = new SGMetar(mr->metarData);
596 //SGMetar *m = new SGMetar("2004/01/11 01:20\nLOWG 110120Z AUTO VRB01KT 0050 1600N R35/0600 FG M06/M06 Q1019 88//////\n");
599 cerr << G"INPUT: " << m->getData() << ""N << endl;
601 const char *unused = m->getUnusedData();
603 cerr << R"UNUSED: " << unused << ""N << endl;
609 printArgs(m, elevation);
612 } catch (const sg_io_exception& e) {
613 cerr << R"ERROR: " << e.getFormattedMessage().c_str() << ""N << endl << endl;