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