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