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/io/raw_socket.hxx>
37 #include <simgear/timing/timestamp.hxx>
40 using namespace simgear;
42 class MetarRequest : public HTTP::Request
50 MetarRequest(const std::string& stationId) :
51 HTTP::Request("http://weather.noaa.gov/pub/data/observations/metar/stations/" + stationId + ".TXT"),
60 virtual void responseHeader(const string& key, const string& value)
62 if (key == "x-metarproxy") {
67 virtual void gotBodyData(const char* s, int n)
69 metarData += string(s, n);
72 virtual void responseComplete()
74 if (responseCode() == 200) {
77 SG_LOG(SG_ENVIRONMENT, SG_WARN, "metar download failed:" << url() << ": reason:" << responseReason());
84 #if defined(__linux__) || defined(__sun) || defined(__CYGWIN__) \
85 || defined( __FreeBSD__ ) || defined ( sgi )
86 # define R "\033[31;1m" // red
87 # define G "\033[32;1m" // green
88 # define Y "\033[33;1m" // yellow
89 # define B "\033[34;1m" // blue
90 # define M "\033[35;1m" // magenta
91 # define C "\033[36;1m" // cyan
92 # define W "\033[37;1m" // white
93 # define N "\033[m" // normal
107 const char *azimuthName(double d)
109 const char *dir[] = {
110 "N", "NNE", "NE", "ENE",
111 "E", "ESE", "SE", "SSE",
112 "S", "SSW", "SW", "WSW",
113 "W", "WNW", "NW", "NNW"
120 return dir[int(d / 22.5)];
124 // round double to 10^g
125 double rnd(double r, int g = 0)
127 double f = pow(10.0, g);
128 return f * floor(r / f + 0.5);
132 ostream& operator<<(ostream& s, const SGMetarVisibility& v)
135 int m = v.getModifier();
137 if (m == SGMetarVisibility::GREATER_THAN)
139 else if (m == SGMetarVisibility::LESS_THAN)
145 double dist = rnd(v.getVisibility_m(), 1);
147 buf << rnd(dist, 1) << " m";
149 buf << rnd(dist / 1000.0, -1) << " km";
151 const char *dir = "";
153 if ((i = v.getDirection()) != -1) {
154 dir = azimuthName(i);
157 buf << "\t\t\t\t\t" << mod << rnd(v.getVisibility_sm(), -1) << " US-miles " << dir;
158 return s << buf.str();
162 void printReport(SGMetar *m)
164 #define NaN SGMetarNaN
170 if ((i = m->getReportType()) == SGMetar::AUTO)
171 s = "\t\t(automatically generated)";
172 else if (i == SGMetar::COR)
173 s = "\t\t(manually corrected)";
174 else if (i == SGMetar::RTD)
175 s = "\t\t(routine delayed)";
179 cout << "METAR Report" << s << endl;
180 cout << "============" << endl;
181 cout << "Airport-Id:\t\t" << m->getId() << endl;
185 int year = m->getYear();
186 int month = m->getMonth();
187 cout << "Report time:\t\t" << year << '/' << month << '/' << m->getDay();
188 cout << ' ' << m->getHour() << ':';
189 cout << setw(2) << setfill('0') << m->getMinute() << " UTC" << endl;
193 SGMetarVisibility minvis = m->getMinVisibility();
194 SGMetarVisibility maxvis = m->getMaxVisibility();
195 double min = minvis.getVisibility_m();
196 double max = maxvis.getVisibility_m();
199 cout << "min. Visibility:\t" << minvis << endl;
200 cout << "max. Visibility:\t" << maxvis << endl;
202 cout << "Visibility:\t\t" << minvis << endl;
206 // directed visibility
207 const SGMetarVisibility *dirvis = m->getDirVisibility();
208 for (i = 0; i < 8; i++, dirvis++)
209 if (dirvis->getVisibility_m() != NaN)
210 cout << "\t\t\t" << *dirvis << endl;
213 // vertical visibility
214 SGMetarVisibility vertvis = m->getVertVisibility();
215 if ((d = vertvis.getVisibility_ft()) != NaN)
216 cout << "Vert. visibility:\t" << vertvis << endl;
217 else if (vertvis.getModifier() == SGMetarVisibility::NOGO)
218 cout << "Vert. visibility:\timpossible to determine" << endl;
222 d = m->getWindSpeed_kmh();
223 cout << "Wind:\t\t\t";
225 cout << "none" << endl;
227 if ((i = m->getWindDir()) == -1)
228 cout << "from variable directions";
230 cout << "from the " << azimuthName(i) << " (" << i << "°)";
231 cout << " at " << rnd(d, -1) << " km/h";
233 cout << "\t\t" << rnd(m->getWindSpeed_kt(), -1) << " kt";
234 cout << " = " << rnd(m->getWindSpeed_mph(), -1) << " mph";
235 cout << " = " << rnd(m->getWindSpeed_mps(), -1) << " m/s";
238 if ((d = m->getGustSpeed_kmh()) != NaN) {
239 cout << "\t\t\twith gusts at " << rnd(d, -1) << " km/h";
240 cout << "\t\t\t" << rnd(m->getGustSpeed_kt(), -1) << " kt";
241 cout << " = " << rnd(m->getGustSpeed_mph(), -1) << " mph";
242 cout << " = " << rnd(m->getGustSpeed_mps(), -1) << " m/s";
246 int from = m->getWindRangeFrom();
247 int to = m->getWindRangeTo();
249 cout << "\t\t\tvariable from " << azimuthName(from);
250 cout << " to " << azimuthName(to);
251 cout << " (" << from << "°--" << to << "°)" << endl;
256 // temperature/humidity/air pressure
257 if ((d = m->getTemperature_C()) != NaN) {
258 cout << "Temperature:\t\t" << d << "°C\t\t\t\t\t";
259 cout << rnd(m->getTemperature_F(), -1) << "°F" << endl;
261 if ((d = m->getDewpoint_C()) != NaN) {
262 cout << "Dewpoint:\t\t" << d << "°C\t\t\t\t\t";
263 cout << rnd(m->getDewpoint_F(), -1) << "°F" << endl;
264 cout << "Rel. Humidity:\t\t" << rnd(m->getRelHumidity()) << "%" << endl;
267 if ((d = m->getPressure_hPa()) != NaN) {
268 cout << "Pressure:\t\t" << rnd(d) << " hPa\t\t\t\t";
269 cout << rnd(m->getPressure_inHg(), -2) << " in. Hg" << endl;
274 vector<string> wv = m->getWeather();
275 vector<string>::iterator weather;
276 for (i = 0, weather = wv.begin(); weather != wv.end(); weather++, i++) {
277 cout << (i ? ", " : "Weather:\t\t") << weather->c_str();
284 const char *coverage_string[5] = {
285 "clear skies", "few clouds", "scattered clouds", "broken clouds", "sky overcast"
287 vector<SGMetarCloud> cv = m->getClouds();
288 vector<SGMetarCloud>::iterator cloud;
289 for (lineno = 0, cloud = cv.begin(); cloud != cv.end(); cloud++, lineno++) {
290 cout << (lineno ? "\t\t\t" : "Sky condition:\t\t");
292 if ((i = cloud->getCoverage()) != -1)
293 cout << coverage_string[i];
294 if ((d = cloud->getAltitude_ft()) != NaN)
295 cout << " at " << rnd(d, 1) << " ft";
296 if ((s = cloud->getTypeLongString()))
297 cout << " (" << s << ')';
299 cout << "\t\t\t" << rnd(cloud->getAltitude_m(), 1) << " m";
305 map<string, SGMetarRunway> rm = m->getRunways();
306 map<string, SGMetarRunway>::iterator runway;
307 for (runway = rm.begin(); runway != rm.end(); runway++) {
309 if (!strcmp(runway->first.c_str(), "ALL"))
310 cout << "All runways:\t\t";
312 cout << "Runway " << runway->first << ":\t\t";
313 SGMetarRunway rwy = runway->second;
315 // assemble surface string
316 vector<string> surface;
317 if ((s = rwy.getDepositString()) && strlen(s))
318 surface.push_back(s);
319 if ((s = rwy.getExtentString()) && strlen(s))
320 surface.push_back(s);
321 if ((d = rwy.getDepth()) != NaN) {
322 sprintf(buf, "%.1lf mm", d * 1000.0);
323 surface.push_back(buf);
325 if ((s = rwy.getFrictionString()) && strlen(s))
326 surface.push_back(s);
327 if ((d = rwy.getFriction()) != NaN) {
328 sprintf(buf, "friction: %.2lf", d);
329 surface.push_back(buf);
332 if (surface.size()) {
333 vector<string>::iterator rwysurf = surface.begin();
334 for (i = 0; rwysurf != surface.end(); rwysurf++, i++) {
342 // assemble visibility string
343 SGMetarVisibility minvis = rwy.getMinVisibility();
344 SGMetarVisibility maxvis = rwy.getMaxVisibility();
345 if ((d = minvis.getVisibility_m()) != NaN) {
347 cout << endl << "\t\t\t";
350 if (maxvis.getVisibility_m() != d) {
351 cout << endl << "\t\t\t" << maxvis << endl;
355 if (rwy.getWindShear()) {
357 cout << endl << "\t\t\t";
358 cout << "critical wind shear" << endl;
367 void printArgs(SGMetar *m, double airport_elevation)
369 #define NaN SGMetarNaN
375 sprintf(buf, "--airport=%s ", m->getId());
379 sprintf(buf, "--start-date-gmt=%4d:%02d:%02d:%02d:%02d:00 ",
380 m->getYear(), m->getMonth(), m->getDay(),
381 m->getHour(), m->getMinute());
385 const char *coverage_string[5] = {
386 "clear", "few", "scattered", "broken", "overcast"
388 vector<SGMetarCloud> cv = m->getClouds();
389 vector<SGMetarCloud>::iterator cloud;
390 for (i = 0, cloud = cv.begin(); i < 5; i++) {
392 double altitude = -99999;
393 if (cloud != cv.end()) {
394 coverage = cloud->getCoverage();
395 altitude = coverage ? cloud->getAltitude_ft() + airport_elevation : -99999;
398 sprintf(buf, "--prop:/environment/clouds/layer[%d]/coverage=%s ", i, coverage_string[coverage]);
400 sprintf(buf, "--prop:/environment/clouds/layer[%d]/elevation-ft=%.0lf ", i, altitude);
402 sprintf(buf, "--prop:/environment/clouds/layer[%d]/thickness-ft=500 ", i);
406 // environment (temperature, dewpoint, visibility, pressure)
407 // metar sets don't provide aloft information; we have to
408 // set the same values for all boundary levels
409 int wind_dir = m->getWindDir();
410 double visibility = m->getMinVisibility().getVisibility_m();
411 double dewpoint = m->getDewpoint_C();
412 double temperature = m->getTemperature_C();
413 double pressure = m->getPressure_inHg();
414 double wind_speed = m->getWindSpeed_kt();
415 double elevation = -100;
416 for (i = 0; i < 3; i++, elevation += 2000.0) {
417 sprintf(buf, "--prop:/environment/config/boundary/entry[%d]/", i);
418 int pos = strlen(buf);
420 sprintf(&buf[pos], "elevation-ft=%.0lf", elevation);
422 sprintf(&buf[pos], "turbulence-norm=%.0lf", 0.0);
425 if (visibility != NaN) {
426 sprintf(&buf[pos], "visibility-m=%.0lf", visibility);
429 if (temperature != NaN) {
430 sprintf(&buf[pos], "temperature-degc=%.0lf", temperature);
433 if (dewpoint != NaN) {
434 sprintf(&buf[pos], "dewpoint-degc=%.0lf", dewpoint);
437 if (pressure != NaN) {
438 sprintf(&buf[pos], "pressure-sea-level-inhg=%.0lf", pressure);
441 if (wind_dir != NaN) {
442 sprintf(&buf[pos], "wind-from-heading-deg=%d", wind_dir);
445 if (wind_speed != NaN) {
446 sprintf(&buf[pos], "wind-speed-kt=%.0lf", wind_speed);
452 int range_from = m->getWindRangeFrom();
453 int range_to = m->getWindRangeTo();
454 double gust_speed = m->getGustSpeed_kt();
455 if (wind_speed != NaN && wind_dir != -1) {
456 strcpy(buf, "--wind=");
457 if (range_from != -1 && range_to != -1)
458 sprintf(&buf[strlen(buf)], "%d:%d", range_from, range_to);
460 sprintf(&buf[strlen(buf)], "%d", wind_dir);
461 sprintf(&buf[strlen(buf)], "@%.0lf", wind_speed);
462 if (gust_speed != NaN)
463 sprintf(&buf[strlen(buf)], ":%.0lf", gust_speed);
469 //cout << "fgfs" << endl;
470 vector<string>::iterator arg;
471 for (i = 0, arg = args.begin(); arg != args.end(); i++, arg++) {
472 cout << "\t" << *arg << endl;
479 void getproxy(string& host, string& port)
484 const char *p = getenv("http_proxy");
489 if (!strncmp(p, "http://", 7))
498 for (t = s + strlen(s); t > s; t--)
499 if (!isspace(t[-1]) && t[-1] != '/')
515 "Usage: metar [-v] [-e elevation] [-r|-c] <list of ICAO airport ids or METAR strings>\n"
518 " -h|--help show this help\n"
519 " -v|--verbose verbose output\n"
520 " -r|--report print report (default)\n"
521 " -c|--command-line print command line\n"
522 " -e E|--elevation E set airport elevation to E meters\n"
523 " (added to cloud bases in command line mode)\n"
525 " http_proxy set proxy in the form \"http://host:port/\"\n"
528 " $ metar ksfo koak\n"
529 " $ metar -c ksfo -r ksfo\n"
530 " $ metar \"LOWL 161500Z 19004KT 160V240 9999 FEW035 SCT300 29/23 Q1006 NOSIG\"\n"
531 " $ fgfs `metar -e 183 -c loww`\n"
532 " $ http_proxy=http://localhost:3128/ metar ksfo\n"
537 int main(int argc, char *argv[])
540 bool verbose = false;
541 double elevation = 0.0;
548 string proxy_host, proxy_port;
549 getproxy(proxy_host, proxy_port);
551 Socket::initSockets();
554 http.setProxy(proxy_host, atoi(proxy_port.c_str()));
556 for (int i = 1; i < argc; i++) {
557 if (!strcmp(argv[i], "-h") || !strcmp(argv[i], "--help"))
559 else if (!strcmp(argv[i], "-v") || !strcmp(argv[i], "--verbose"))
561 else if (!strcmp(argv[i], "-r") || !strcmp(argv[i], "--report"))
563 else if (!strcmp(argv[i], "-c") || !strcmp(argv[i], "--command-line"))
565 else if (!strcmp(argv[i], "-e") || !strcmp(argv[i], "--elevation")) {
567 cerr << "-e option used without elevation" << endl;
570 elevation = strtod(argv[i], 0);
572 static bool shown = false;
573 if (verbose && !shown) {
574 cerr << "Proxy host: '" << proxy_host << "'" << endl;
575 cerr << "Proxy port: '" << proxy_port << "'" << endl << endl;
580 MetarRequest* mr = new MetarRequest(argv[i]);
581 HTTP::Request_ptr own(mr);
582 http.makeRequest(mr);
584 // spin until the request completes, fails or times out
585 SGTimeStamp start(SGTimeStamp::now());
586 while (start.elapsedMSec() < 8000) {
588 if (mr->complete || mr->failed) {
591 SGTimeStamp::sleepForMSec(1);
595 throw sg_io_exception("metar download failed (or timed out)");
597 SGMetar *m = new SGMetar(mr->metarData);
599 //SGMetar *m = new SGMetar("2004/01/11 01:20\nLOWG 110120Z AUTO VRB01KT 0050 1600N R35/0600 FG M06/M06 Q1019 88//////\n");
602 cerr << G"INPUT: " << m->getData() << ""N << endl;
604 const char *unused = m->getUnusedData();
606 cerr << R"UNUSED: " << unused << ""N << endl;
612 printArgs(m, elevation);
615 } catch (const sg_io_exception& e) {
616 cerr << R"ERROR: " << e.getFormattedMessage().c_str() << ""N << endl << endl;