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__) \
46 || defined( __FreeBSD__ ) || defined ( sgi )
47 # define R "\033[31;1m" // red
48 # define G "\033[32;1m" // green
49 # define Y "\033[33;1m" // yellow
50 # define B "\033[34;1m" // blue
51 # define M "\033[35;1m" // magenta
52 # define C "\033[36;1m" // cyan
53 # define W "\033[37;1m" // white
54 # define N "\033[m" // normal
68 const char *azimuthName(double d)
71 "N", "NNE", "NE", "ENE",
72 "E", "ESE", "SE", "SSE",
73 "S", "SSW", "SW", "WSW",
74 "W", "WNW", "NW", "NNW"
81 return dir[int(d / 22.5)];
85 // round double to 10^g
86 double rnd(double r, int g = 0)
88 double f = pow(10.0, g);
89 return f * floor(r / f + 0.5);
93 ostream& operator<<(ostream& s, const SGMetarVisibility& v)
96 int m = v.getModifier();
98 if (m == SGMetarVisibility::GREATER_THAN)
100 else if (m == SGMetarVisibility::LESS_THAN)
106 double dist = rnd(v.getVisibility_m(), 1);
108 buf << rnd(dist, 1) << " m";
110 buf << rnd(dist / 1000.0, -1) << " km";
112 const char *dir = "";
114 if ((i = v.getDirection()) != -1) {
115 dir = azimuthName(i);
118 buf << "\t\t\t\t\t" << mod << rnd(v.getVisibility_sm(), -1) << " US-miles " << dir;
119 return s << buf.str();
123 void printReport(SGMetar *m)
125 #define NaN SGMetarNaN
131 if ((i = m->getReportType()) == SGMetar::AUTO)
132 s = "\t\t(automatically generated)";
133 else if (i == SGMetar::COR)
134 s = "\t\t(manually corrected)";
135 else if (i == SGMetar::RTD)
136 s = "\t\t(routine delayed)";
140 cout << "METAR Report" << s << endl;
141 cout << "============" << endl;
142 cout << "Airport-Id:\t\t" << m->getId() << endl;
146 int year = m->getYear();
147 int month = m->getMonth();
148 cout << "Report time:\t\t" << year << '/' << month << '/' << m->getDay();
149 cout << ' ' << m->getHour() << ':';
150 cout << setw(2) << setfill('0') << m->getMinute() << " UTC" << endl;
154 SGMetarVisibility minvis = m->getMinVisibility();
155 SGMetarVisibility maxvis = m->getMaxVisibility();
156 double min = minvis.getVisibility_m();
157 double max = maxvis.getVisibility_m();
160 cout << "min. Visibility:\t" << minvis << endl;
161 cout << "max. Visibility:\t" << maxvis << endl;
163 cout << "Visibility:\t\t" << minvis << endl;
167 // directed visibility
168 const SGMetarVisibility *dirvis = m->getDirVisibility();
169 for (i = 0; i < 8; i++, dirvis++)
170 if (dirvis->getVisibility_m() != NaN)
171 cout << "\t\t\t" << *dirvis << endl;
174 // vertical visibility
175 SGMetarVisibility vertvis = m->getVertVisibility();
176 if ((d = vertvis.getVisibility_ft()) != NaN)
177 cout << "Vert. visibility:\t" << vertvis << endl;
178 else if (vertvis.getModifier() == SGMetarVisibility::NOGO)
179 cout << "Vert. visibility:\timpossible to determine" << endl;
183 d = m->getWindSpeed_kmh();
184 cout << "Wind:\t\t\t";
186 cout << "none" << endl;
188 if ((i = m->getWindDir()) == -1)
189 cout << "from variable directions";
191 cout << "from the " << azimuthName(i) << " (" << i << "°)";
192 cout << " at " << rnd(d, -1) << " km/h";
194 cout << "\t\t" << rnd(m->getWindSpeed_kt(), -1) << " kt";
195 cout << " = " << rnd(m->getWindSpeed_mph(), -1) << " mph";
196 cout << " = " << rnd(m->getWindSpeed_mps(), -1) << " m/s";
199 if ((d = m->getGustSpeed_kmh()) != NaN) {
200 cout << "\t\t\twith gusts at " << rnd(d, -1) << " km/h";
201 cout << "\t\t\t" << rnd(m->getGustSpeed_kt(), -1) << " kt";
202 cout << " = " << rnd(m->getGustSpeed_mph(), -1) << " mph";
203 cout << " = " << rnd(m->getGustSpeed_mps(), -1) << " m/s";
207 int from = m->getWindRangeFrom();
208 int to = m->getWindRangeTo();
210 cout << "\t\t\tvariable from " << azimuthName(from);
211 cout << " to " << azimuthName(to);
212 cout << " (" << from << "°--" << to << "°)" << endl;
217 // temperature/humidity/air pressure
218 if ((d = m->getTemperature_C()) != NaN) {
219 cout << "Temperature:\t\t" << d << "°C\t\t\t\t\t";
220 cout << rnd(m->getTemperature_F(), -1) << "°F" << endl;
222 if ((d = m->getDewpoint_C()) != NaN) {
223 cout << "Dewpoint:\t\t" << d << "°C\t\t\t\t\t";
224 cout << rnd(m->getDewpoint_F(), -1) << "°F" << endl;
225 cout << "Rel. Humidity:\t\t" << rnd(m->getRelHumidity()) << "%" << endl;
228 if ((d = m->getPressure_hPa()) != NaN) {
229 cout << "Pressure:\t\t" << rnd(d) << " hPa\t\t\t\t";
230 cout << rnd(m->getPressure_inHg(), -2) << " in. Hg" << endl;
235 vector<string> wv = m->getWeather();
236 vector<string>::iterator weather;
237 for (i = 0, weather = wv.begin(); weather != wv.end(); weather++, i++) {
238 cout << (i ? ", " : "Weather:\t\t") << weather->c_str();
245 const char *coverage_string[5] = {
246 "clear skies", "few clouds", "scattered clouds", "broken clouds", "sky overcast"
248 vector<SGMetarCloud> cv = m->getClouds();
249 vector<SGMetarCloud>::iterator cloud;
250 for (lineno = 0, cloud = cv.begin(); cloud != cv.end(); cloud++, lineno++) {
251 cout << (lineno ? "\t\t\t" : "Sky condition:\t\t");
253 if ((i = cloud->getCoverage()) != -1)
254 cout << coverage_string[i];
255 if ((d = cloud->getAltitude_ft()) != NaN)
256 cout << " at " << rnd(d, 1) << " ft";
257 if ((s = cloud->getTypeLongString()))
258 cout << " (" << s << ')';
260 cout << "\t\t\t" << rnd(cloud->getAltitude_m(), 1) << " m";
266 map<string, SGMetarRunway> rm = m->getRunways();
267 map<string, SGMetarRunway>::iterator runway;
268 for (runway = rm.begin(); runway != rm.end(); runway++) {
270 if (!strcmp(runway->first.c_str(), "ALL"))
271 cout << "All runways:\t\t";
273 cout << "Runway " << runway->first << ":\t\t";
274 SGMetarRunway rwy = runway->second;
276 // assemble surface string
277 vector<string> surface;
278 if ((s = rwy.getDepositString()) && strlen(s))
279 surface.push_back(s);
280 if ((s = rwy.getExtentString()) && strlen(s))
281 surface.push_back(s);
282 if ((d = rwy.getDepth()) != NaN) {
283 sprintf(buf, "%.1lf mm", d * 1000.0);
284 surface.push_back(buf);
286 if ((s = rwy.getFrictionString()) && strlen(s))
287 surface.push_back(s);
288 if ((d = rwy.getFriction()) != NaN) {
289 sprintf(buf, "friction: %.2lf", d);
290 surface.push_back(buf);
293 if (! surface.empty()) {
294 vector<string>::iterator rwysurf = surface.begin();
295 for (i = 0; rwysurf != surface.end(); rwysurf++, i++) {
303 // assemble visibility string
304 SGMetarVisibility minvis = rwy.getMinVisibility();
305 SGMetarVisibility maxvis = rwy.getMaxVisibility();
306 if ((d = minvis.getVisibility_m()) != NaN) {
308 cout << endl << "\t\t\t";
311 if (maxvis.getVisibility_m() != d) {
312 cout << endl << "\t\t\t" << maxvis << endl;
316 if (rwy.getWindShear()) {
318 cout << endl << "\t\t\t";
319 cout << "critical wind shear" << endl;
328 void printArgs(SGMetar *m, double airport_elevation)
330 #define NaN SGMetarNaN
336 sprintf(buf, "--airport=%s ", m->getId());
340 sprintf(buf, "--start-date-gmt=%4d:%02d:%02d:%02d:%02d:00 ",
341 m->getYear(), m->getMonth(), m->getDay(),
342 m->getHour(), m->getMinute());
346 const char *coverage_string[5] = {
347 "clear", "few", "scattered", "broken", "overcast"
349 vector<SGMetarCloud> cv = m->getClouds();
350 vector<SGMetarCloud>::iterator cloud;
351 for (i = 0, cloud = cv.begin(); i < 5; i++) {
353 double altitude = -99999;
354 if (cloud != cv.end()) {
355 coverage = cloud->getCoverage();
356 altitude = coverage ? cloud->getAltitude_ft() + airport_elevation : -99999;
359 sprintf(buf, "--prop:/environment/clouds/layer[%d]/coverage=%s ", i, coverage_string[coverage]);
361 sprintf(buf, "--prop:/environment/clouds/layer[%d]/elevation-ft=%.0lf ", i, altitude);
363 sprintf(buf, "--prop:/environment/clouds/layer[%d]/thickness-ft=500 ", i);
367 // environment (temperature, dewpoint, visibility, pressure)
368 // metar sets don't provide aloft information; we have to
369 // set the same values for all boundary levels
370 int wind_dir = m->getWindDir();
371 double visibility = m->getMinVisibility().getVisibility_m();
372 double dewpoint = m->getDewpoint_C();
373 double temperature = m->getTemperature_C();
374 double pressure = m->getPressure_inHg();
375 double wind_speed = m->getWindSpeed_kt();
376 double elevation = -100;
377 for (i = 0; i < 3; i++, elevation += 2000.0) {
378 sprintf(buf, "--prop:/environment/config/boundary/entry[%d]/", i);
379 int pos = strlen(buf);
381 sprintf(&buf[pos], "elevation-ft=%.0lf", elevation);
383 sprintf(&buf[pos], "turbulence-norm=%.0lf", 0.0);
386 if (visibility != NaN) {
387 sprintf(&buf[pos], "visibility-m=%.0lf", visibility);
390 if (temperature != NaN) {
391 sprintf(&buf[pos], "temperature-degc=%.0lf", temperature);
394 if (dewpoint != NaN) {
395 sprintf(&buf[pos], "dewpoint-degc=%.0lf", dewpoint);
398 if (pressure != NaN) {
399 sprintf(&buf[pos], "pressure-sea-level-inhg=%.0lf", pressure);
402 if (wind_dir != NaN) {
403 sprintf(&buf[pos], "wind-from-heading-deg=%d", wind_dir);
406 if (wind_speed != NaN) {
407 sprintf(&buf[pos], "wind-speed-kt=%.0lf", wind_speed);
413 int range_from = m->getWindRangeFrom();
414 int range_to = m->getWindRangeTo();
415 double gust_speed = m->getGustSpeed_kt();
416 if (wind_speed != NaN && wind_dir != -1) {
417 strcpy(buf, "--wind=");
418 if (range_from != -1 && range_to != -1)
419 sprintf(&buf[strlen(buf)], "%d:%d", range_from, range_to);
421 sprintf(&buf[strlen(buf)], "%d", wind_dir);
422 sprintf(&buf[strlen(buf)], "@%.0lf", wind_speed);
423 if (gust_speed != NaN)
424 sprintf(&buf[strlen(buf)], ":%.0lf", gust_speed);
430 //cout << "fgfs" << endl;
431 vector<string>::iterator arg;
432 for (i = 0, arg = args.begin(); arg != args.end(); i++, arg++) {
433 cout << "\t" << *arg << endl;
440 void getproxy(string& host, string& port)
445 const char *p = getenv("http_proxy");
450 if (!strncmp(p, "http://", 7))
459 for (t = s + strlen(s); t > s; t--)
460 if (!isspace(t[-1]) && t[-1] != '/')
476 "Usage: metar [-v] [-e elevation] [-r|-c] <list of ICAO airport ids or METAR strings>\n"
479 " -h|--help show this help\n"
480 " -v|--verbose verbose output\n"
481 " -r|--report print report (default)\n"
482 " -c|--command-line print command line\n"
483 " -e E|--elevation E set airport elevation to E meters\n"
484 " (added to cloud bases in command line mode)\n"
486 " http_proxy set proxy in the form \"http://host:port/\"\n"
489 " $ metar ksfo koak\n"
490 " $ metar -c ksfo -r ksfo\n"
491 " $ metar \"LOWL 161500Z 19004KT 160V240 9999 FEW035 SCT300 29/23 Q1006 NOSIG\"\n"
492 " $ fgfs `metar -e 183 -c loww`\n"
493 " $ http_proxy=http://localhost:3128/ metar ksfo\n"
498 int main(int argc, char *argv[])
501 bool verbose = false;
502 double elevation = 0.0;
509 string proxy_host, proxy_port;
510 getproxy(proxy_host, proxy_port);
512 Socket::initSockets();
515 http.setProxy(proxy_host, atoi(proxy_port.c_str()));
517 for (int i = 1; i < argc; i++) {
518 if (!strcmp(argv[i], "-h") || !strcmp(argv[i], "--help"))
520 else if (!strcmp(argv[i], "-v") || !strcmp(argv[i], "--verbose"))
522 else if (!strcmp(argv[i], "-r") || !strcmp(argv[i], "--report"))
524 else if (!strcmp(argv[i], "-c") || !strcmp(argv[i], "--command-line"))
526 else if (!strcmp(argv[i], "-e") || !strcmp(argv[i], "--elevation")) {
528 cerr << "-e option used without elevation" << endl;
531 elevation = strtod(argv[i], 0);
533 static bool shown = false;
534 if (verbose && !shown) {
535 cerr << "Proxy host: '" << proxy_host << "'" << endl;
536 cerr << "Proxy port: '" << proxy_port << "'" << endl << endl;
542 static const std::string NOAA_BASE_URL =
543 "http://weather.noaa.gov/pub/data/observations/metar/stations/";
544 HTTP::MemoryRequest* mr = new HTTP::MemoryRequest
547 + boost::to_upper_copy<std::string>(argv[i]) + ".TXT"
549 HTTP::Request_ptr own(mr);
550 http.makeRequest(mr);
552 // spin until the request completes, fails or times out
553 SGTimeStamp start(SGTimeStamp::now());
554 while (start.elapsedMSec() < 8000) {
556 if( mr->isComplete() )
558 SGTimeStamp::sleepForMSec(1);
561 if( !mr->isComplete() )
562 throw sg_io_exception("metar download timed out");
563 if( mr->responseCode() != 200 )
565 std::cerr << "metar download failed: "
567 << " (" << mr->responseCode()
568 << " " << mr->responseReason() << ")"
570 throw sg_io_exception("metar download failed");
573 SGMetar *m = new SGMetar(mr->responseBody());
575 //SGMetar *m = new SGMetar("2004/01/11 01:20\nLOWG 110120Z AUTO VRB01KT 0050 1600N R35/0600 FG M06/M06 Q1019 88//////\n");
578 cerr << G"INPUT: " << m->getData() << ""N << endl;
580 const char *unused = m->getUnusedData();
582 cerr << R"UNUSED: " << unused << ""N << endl;
588 printArgs(m, elevation);
591 } catch (const sg_io_exception& e) {
592 cerr << R"ERROR: " << e.getFormattedMessage().c_str() << ""N << endl << endl;