]> git.mxchange.org Git - flightgear.git/blob - src/Main/metar_main.cxx
Support for multiple data dirs.
[flightgear.git] / src / Main / metar_main.cxx
1 // metar interface class demo
2 //
3 // Written by Melchior FRANZ, started December 2003.
4 //
5 // Copyright (C) 2003  Melchior FRANZ - mfranz@aon.at
6 //
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.
11 //
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.
16 //
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.
20 //
21 // $Id$
22
23 #include <iomanip>
24 #include <sstream>
25 #include <iostream>
26 #include <string.h>
27 #include <time.h>
28 #include <cstdlib>
29 #include <cstdio>
30
31 #include <simgear/debug/logstream.hxx>
32 #include <simgear/environment/metar.hxx>
33 #include <simgear/structure/exception.hxx>
34
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>
39
40 using namespace std;
41 using namespace simgear;
42
43 class MetarRequest : public HTTP::Request
44 {
45 public:
46     bool complete;
47     bool failed;
48     string metarData;
49     bool fromProxy;
50     
51     MetarRequest(const std::string& stationId) : 
52         HTTP::Request("http://weather.noaa.gov/pub/data/observations/metar/stations/" + stationId + ".TXT"),
53         complete(false),
54         failed(false)
55     {
56         fromProxy = false;
57     }
58     
59 protected:
60     
61     virtual void responseHeader(const string& key, const string& value)
62     {
63         if (key == "x-metarproxy") {
64             fromProxy = true;
65         }
66     }
67
68     virtual void gotBodyData(const char* s, int n)
69     {
70         metarData += string(s, n);
71     }
72
73     virtual void responseComplete()
74     {
75         if (responseCode() == 200) {
76             complete = true;
77         } else {
78             SG_LOG(SG_ENVIRONMENT, SG_WARN, "metar download failed:" << url() << ": reason:" << responseReason());
79             failed = true;
80         }
81     }
82 };
83
84 // text color
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
95 #else
96 #       define R ""
97 #       define G ""
98 #       define Y ""
99 #       define B ""
100 #       define M ""
101 #       define C ""
102 #       define W ""
103 #       define N ""
104 #endif
105
106
107
108 const char *azimuthName(double d)
109 {
110         const char *dir[] = {
111                 "N", "NNE", "NE", "ENE",
112                 "E", "ESE", "SE", "SSE",
113                 "S", "SSW", "SW", "WSW",
114                 "W", "WNW", "NW", "NNW"
115         };
116         d += 11.25;
117         while (d < 0)
118                 d += 360;
119         while (d >= 360)
120                 d -= 360;
121         return dir[int(d / 22.5)];
122 }
123
124
125 // round double to 10^g
126 double rnd(double r, int g = 0)
127 {
128         double f = pow(10.0, g);
129         return f * floor(r / f + 0.5);
130 }
131
132
133 ostream& operator<<(ostream& s, const SGMetarVisibility& v)
134 {
135         ostringstream buf;
136         int m = v.getModifier();
137         const char *mod;
138         if (m == SGMetarVisibility::GREATER_THAN)
139                 mod = ">=";
140         else if (m == SGMetarVisibility::LESS_THAN)
141                 mod = "<";
142         else
143                 mod = "";
144         buf << mod;
145
146         double dist = rnd(v.getVisibility_m(), 1);
147         if (dist < 1000.0)
148                 buf << rnd(dist, 1) << " m";
149         else
150                 buf << rnd(dist / 1000.0, -1) << " km";
151
152         const char *dir = "";
153         int i;
154         if ((i = v.getDirection()) != -1) {
155                 dir = azimuthName(i);
156                 buf << " " << dir;
157         }
158         buf << "\t\t\t\t\t" << mod << rnd(v.getVisibility_sm(), -1) << " US-miles " << dir;
159         return s << buf.str();
160 }
161
162
163 void printReport(SGMetar *m)
164 {
165 #define NaN SGMetarNaN
166         const char *s;
167         char buf[256];
168         double d;
169         int i, lineno;
170
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)";
177         else
178                 s = "";
179
180         cout << "METAR Report" << s << endl;
181         cout << "============" << endl;
182         cout << "Airport-Id:\t\t" << m->getId() << endl;
183
184
185         // date/time
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;
191
192
193         // visibility
194         SGMetarVisibility minvis = m->getMinVisibility();
195         SGMetarVisibility maxvis = m->getMaxVisibility();
196         double min = minvis.getVisibility_m();
197         double max = maxvis.getVisibility_m();
198         if (min != NaN) {
199                 if (max != NaN) {
200                         cout << "min. Visibility:\t" << minvis << endl;
201                         cout << "max. Visibility:\t" << maxvis << endl;
202                 } else
203                         cout << "Visibility:\t\t" << minvis << endl;
204         }
205
206
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;
212
213
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;
220
221
222         // wind
223         d = m->getWindSpeed_kmh();
224         cout << "Wind:\t\t\t";
225         if (d < .1)
226                 cout << "none" << endl;
227         else {
228                 if ((i = m->getWindDir()) == -1)
229                         cout << "from variable directions";
230                 else
231                         cout << "from the " << azimuthName(i) << " (" << i << "°)";
232                 cout << " at " << rnd(d, -1) << " km/h";
233
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";
237                 cout << endl;
238
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";
244                         cout << endl;
245                 }
246
247                 int from = m->getWindRangeFrom();
248                 int to = m->getWindRangeTo();
249                 if (from != to) {
250                         cout << "\t\t\tvariable from " << azimuthName(from);
251                         cout << " to " << azimuthName(to);
252                         cout << " (" << from << "°--" << to << "°)" << endl;
253                 }
254         }
255
256
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;
261
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;
266                 }
267         }
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;
271         }
272
273
274         // weather phenomena
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();
279         }
280         if (i)
281                 cout << endl;
282
283
284         // cloud layers
285         const char *coverage_string[5] = {
286                 "clear skies", "few clouds", "scattered clouds", "broken clouds", "sky overcast"
287         };
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");
292
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 << ')';
299                 if (d != NaN)
300                         cout << "\t\t\t" << rnd(cloud->getAltitude_m(), 1) << " m";
301                 cout << endl;
302         }
303
304
305         // runways
306         map<string, SGMetarRunway> rm = m->getRunways();
307         map<string, SGMetarRunway>::iterator runway;
308         for (runway = rm.begin(); runway != rm.end(); runway++) {
309                 lineno = 0;
310                 if (!strcmp(runway->first.c_str(), "ALL"))
311                         cout << "All runways:\t\t";
312                 else
313                         cout << "Runway " << runway->first << ":\t\t";
314                 SGMetarRunway rwy = runway->second;
315
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);
325                 }
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);
331                 }
332
333                 if (! surface.empty()) {
334                         vector<string>::iterator rwysurf = surface.begin();
335                         for (i = 0; rwysurf != surface.end(); rwysurf++, i++) {
336                                 if (i)
337                                         cout << ", ";
338                                 cout << *rwysurf;
339                         }
340                         lineno++;
341                 }
342
343                 // assemble visibility string
344                 SGMetarVisibility minvis = rwy.getMinVisibility();
345                 SGMetarVisibility maxvis = rwy.getMaxVisibility();
346                 if ((d = minvis.getVisibility_m()) != NaN) {
347                         if (lineno++)
348                                 cout << endl << "\t\t\t";
349                         cout << minvis;
350                 }
351                 if (maxvis.getVisibility_m() != d) {
352                         cout << endl << "\t\t\t" << maxvis << endl;
353                         lineno++;
354                 }
355
356                 if (rwy.getWindShear()) {
357                         if (lineno++)
358                                 cout << endl << "\t\t\t";
359                         cout << "critical wind shear" << endl;
360                 }
361                 cout << endl;
362         }
363         cout << endl;
364 #undef NaN
365 }
366
367
368 void printArgs(SGMetar *m, double airport_elevation)
369 {
370 #define NaN SGMetarNaN
371         vector<string> args;
372         char buf[256];
373         int i;
374
375         // ICAO id
376         sprintf(buf, "--airport=%s ", m->getId());
377         args.push_back(buf);
378
379         // report time
380         sprintf(buf, "--start-date-gmt=%4d:%02d:%02d:%02d:%02d:00 ",
381                         m->getYear(), m->getMonth(), m->getDay(),
382                         m->getHour(), m->getMinute());
383         args.push_back(buf);
384
385         // cloud layers
386         const char *coverage_string[5] = {
387                 "clear", "few", "scattered", "broken", "overcast"
388         };
389         vector<SGMetarCloud> cv = m->getClouds();
390         vector<SGMetarCloud>::iterator cloud;
391         for (i = 0, cloud = cv.begin(); i < 5; i++) {
392                 int coverage = 0;
393                 double altitude = -99999;
394                 if (cloud != cv.end()) {
395                         coverage = cloud->getCoverage();
396                         altitude = coverage ? cloud->getAltitude_ft() + airport_elevation : -99999;
397                         cloud++;
398                 }
399                 sprintf(buf, "--prop:/environment/clouds/layer[%d]/coverage=%s ", i, coverage_string[coverage]);
400                 args.push_back(buf);
401                 sprintf(buf, "--prop:/environment/clouds/layer[%d]/elevation-ft=%.0lf ", i, altitude);
402                 args.push_back(buf);
403                 sprintf(buf, "--prop:/environment/clouds/layer[%d]/thickness-ft=500 ", i);
404                 args.push_back(buf);
405         }
406
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);
420
421                 sprintf(&buf[pos], "elevation-ft=%.0lf", elevation);
422                 args.push_back(buf);
423                 sprintf(&buf[pos], "turbulence-norm=%.0lf", 0.0);
424                 args.push_back(buf);
425
426                 if (visibility != NaN) {
427                         sprintf(&buf[pos], "visibility-m=%.0lf", visibility);
428                         args.push_back(buf);
429                 }
430                 if (temperature != NaN) {
431                         sprintf(&buf[pos], "temperature-degc=%.0lf", temperature);
432                         args.push_back(buf);
433                 }
434                 if (dewpoint != NaN) {
435                         sprintf(&buf[pos], "dewpoint-degc=%.0lf", dewpoint);
436                         args.push_back(buf);
437                 }
438                 if (pressure != NaN) {
439                         sprintf(&buf[pos], "pressure-sea-level-inhg=%.0lf", pressure);
440                         args.push_back(buf);
441                 }
442                 if (wind_dir != NaN) {
443                         sprintf(&buf[pos], "wind-from-heading-deg=%d", wind_dir);
444                         args.push_back(buf);
445                 }
446                 if (wind_speed != NaN) {
447                         sprintf(&buf[pos], "wind-speed-kt=%.0lf", wind_speed);
448                         args.push_back(buf);
449                 }
450         }
451
452         // wind dir@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);
460                 else
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);
465                 args.push_back(buf);
466         }
467         
468
469         // output everything
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;
474         }
475         cout << endl;
476 #undef NaN
477 }
478
479
480 void getproxy(string& host, string& port)
481 {
482         host = "";
483         port = "80";
484
485         const char *p = getenv("http_proxy");
486         if (!p)
487                 return;
488         while (isspace(*p))
489                 p++;
490         if (!strncmp(p, "http://", 7))
491                 p += 7;
492         if (!*p)
493                 return;
494
495         char s[256], *t;
496         strncpy(s, p, 255);
497         s[255] = '\0';
498
499         for (t = s + strlen(s); t > s; t--)
500                 if (!isspace(t[-1]) && t[-1] != '/')
501                         break;
502         *t = '\0';
503
504         t = strchr(s, ':');
505         if (t) {
506                 *t++ = '\0';
507                 port = t;
508         }
509         host = s;
510 }
511
512
513 void usage()
514 {
515         printf(
516                 "Usage: metar [-v] [-e elevation] [-r|-c] <list of ICAO airport ids or METAR strings>\n"
517                 "       metar -h\n"
518                 "\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"
525                 "Environment:\n"
526                 "       http_proxy           set proxy in the form \"http://host:port/\"\n"
527                 "\n"
528                 "Examples:\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"
534                 "\n"
535         );
536 }
537
538 int main(int argc, char *argv[])
539 {
540         bool report = true;
541         bool verbose = false;
542         double elevation = 0.0;
543
544         if (argc <= 1) {
545                 usage();
546                 return 0;
547         }
548
549         string proxy_host, proxy_port;
550         getproxy(proxy_host, proxy_port);
551
552   Socket::initSockets();
553   
554     HTTP::Client http;
555     http.setProxy(proxy_host, atoi(proxy_port.c_str()));
556     
557         for (int i = 1; i < argc; i++) {
558                 if (!strcmp(argv[i], "-h") || !strcmp(argv[i], "--help"))
559                         usage();
560                 else if (!strcmp(argv[i], "-v") || !strcmp(argv[i], "--verbose"))
561                         verbose = true;
562                 else if (!strcmp(argv[i], "-r") || !strcmp(argv[i], "--report"))
563                         report = true;
564                 else if (!strcmp(argv[i], "-c") || !strcmp(argv[i], "--command-line"))
565                         report = false;
566                 else if (!strcmp(argv[i], "-e") || !strcmp(argv[i], "--elevation")) {
567                         if (++i >= argc) {
568                                 cerr << "-e option used without elevation" << endl;
569                                 return 1;
570                         }
571                         elevation = strtod(argv[i], 0);
572                 } else {
573                         static bool shown = false;
574                         if (verbose && !shown) {
575                                 cerr << "Proxy host: '" << proxy_host << "'" << endl;
576                                 cerr << "Proxy port: '" << proxy_port << "'" << endl << endl;
577                                 shown = true;
578                         }
579
580                         try {
581                 MetarRequest* mr = new MetarRequest(argv[i]);
582                 HTTP::Request_ptr own(mr);
583                 http.makeRequest(mr);
584                 
585             // spin until the request completes, fails or times out
586                 SGTimeStamp start(SGTimeStamp::now());
587                 while (start.elapsedMSec() <  8000) {
588                     http.update();
589                     if (mr->complete || mr->failed) {
590                         break;
591                     }
592                     SGTimeStamp::sleepForMSec(1);
593                 }
594                 
595                 if (!mr->complete) {
596                     throw sg_io_exception("metar download failed (or timed out)");
597                 }
598                                 SGMetar *m = new SGMetar(mr->metarData);
599                                 
600                                 //SGMetar *m = new SGMetar("2004/01/11 01:20\nLOWG 110120Z AUTO VRB01KT 0050 1600N R35/0600 FG M06/M06 Q1019 88//////\n");
601
602                                 if (verbose) {
603                                         cerr << G"INPUT: " << m->getData() << ""N << endl;
604
605                                         const char *unused = m->getUnusedData();
606                                         if (*unused)
607                                                 cerr << R"UNUSED: " << unused << ""N << endl;
608                                 }
609
610                                 if (report)
611                                         printReport(m);
612                                 else
613                                         printArgs(m, elevation);
614
615                                 delete m;
616                         } catch (const sg_io_exception& e) {
617                                 cerr << R"ERROR: " << e.getFormattedMessage().c_str() << ""N << endl << endl;
618                         }
619                 }
620         }
621         return 0;
622 }
623
624