]> git.mxchange.org Git - flightgear.git/blob - src/Main/metar_main.cxx
One more Mac helper moved into CocoaHelpers.mm
[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 <boost/algorithm/string.hpp>
32
33 #include <simgear/environment/metar.hxx>
34 #include <simgear/structure/exception.hxx>
35
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>
40
41 using namespace std;
42 using namespace simgear;
43
44 // text color
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
55 #else
56 #       define R ""
57 #       define G ""
58 #       define Y ""
59 #       define B ""
60 #       define M ""
61 #       define C ""
62 #       define W ""
63 #       define N ""
64 #endif
65
66
67
68 const char *azimuthName(double d)
69 {
70         const char *dir[] = {
71                 "N", "NNE", "NE", "ENE",
72                 "E", "ESE", "SE", "SSE",
73                 "S", "SSW", "SW", "WSW",
74                 "W", "WNW", "NW", "NNW"
75         };
76         d += 11.25;
77         while (d < 0)
78                 d += 360;
79         while (d >= 360)
80                 d -= 360;
81         return dir[int(d / 22.5)];
82 }
83
84
85 // round double to 10^g
86 double rnd(double r, int g = 0)
87 {
88         double f = pow(10.0, g);
89         return f * floor(r / f + 0.5);
90 }
91
92
93 ostream& operator<<(ostream& s, const SGMetarVisibility& v)
94 {
95         ostringstream buf;
96         int m = v.getModifier();
97         const char *mod;
98         if (m == SGMetarVisibility::GREATER_THAN)
99                 mod = ">=";
100         else if (m == SGMetarVisibility::LESS_THAN)
101                 mod = "<";
102         else
103                 mod = "";
104         buf << mod;
105
106         double dist = rnd(v.getVisibility_m(), 1);
107         if (dist < 1000.0)
108                 buf << rnd(dist, 1) << " m";
109         else
110                 buf << rnd(dist / 1000.0, -1) << " km";
111
112         const char *dir = "";
113         int i;
114         if ((i = v.getDirection()) != -1) {
115                 dir = azimuthName(i);
116                 buf << " " << dir;
117         }
118         buf << "\t\t\t\t\t" << mod << rnd(v.getVisibility_sm(), -1) << " US-miles " << dir;
119         return s << buf.str();
120 }
121
122
123 void printReport(SGMetar *m)
124 {
125 #define NaN SGMetarNaN
126         const char *s;
127         char buf[256];
128         double d;
129         int i, lineno;
130
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)";
137         else
138                 s = "";
139
140         cout << "METAR Report" << s << endl;
141         cout << "============" << endl;
142         cout << "Airport-Id:\t\t" << m->getId() << endl;
143
144
145         // date/time
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;
151
152
153         // visibility
154         SGMetarVisibility minvis = m->getMinVisibility();
155         SGMetarVisibility maxvis = m->getMaxVisibility();
156         double min = minvis.getVisibility_m();
157         double max = maxvis.getVisibility_m();
158         if (min != NaN) {
159                 if (max != NaN) {
160                         cout << "min. Visibility:\t" << minvis << endl;
161                         cout << "max. Visibility:\t" << maxvis << endl;
162                 } else
163                         cout << "Visibility:\t\t" << minvis << endl;
164         }
165
166
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;
172
173
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;
180
181
182         // wind
183         d = m->getWindSpeed_kmh();
184         cout << "Wind:\t\t\t";
185         if (d < .1)
186                 cout << "none" << endl;
187         else {
188                 if ((i = m->getWindDir()) == -1)
189                         cout << "from variable directions";
190                 else
191                         cout << "from the " << azimuthName(i) << " (" << i << "°)";
192                 cout << " at " << rnd(d, -1) << " km/h";
193
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";
197                 cout << endl;
198
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";
204                         cout << endl;
205                 }
206
207                 int from = m->getWindRangeFrom();
208                 int to = m->getWindRangeTo();
209                 if (from != to) {
210                         cout << "\t\t\tvariable from " << azimuthName(from);
211                         cout << " to " << azimuthName(to);
212                         cout << " (" << from << "°--" << to << "°)" << endl;
213                 }
214         }
215
216
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;
221
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;
226                 }
227         }
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;
231         }
232
233
234         // weather phenomena
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();
239         }
240         if (i)
241                 cout << endl;
242
243
244         // cloud layers
245         const char *coverage_string[5] = {
246                 "clear skies", "few clouds", "scattered clouds", "broken clouds", "sky overcast"
247         };
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");
252
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 << ')';
259                 if (d != NaN)
260                         cout << "\t\t\t" << rnd(cloud->getAltitude_m(), 1) << " m";
261                 cout << endl;
262         }
263
264
265         // runways
266         map<string, SGMetarRunway> rm = m->getRunways();
267         map<string, SGMetarRunway>::iterator runway;
268         for (runway = rm.begin(); runway != rm.end(); runway++) {
269                 lineno = 0;
270                 if (!strcmp(runway->first.c_str(), "ALL"))
271                         cout << "All runways:\t\t";
272                 else
273                         cout << "Runway " << runway->first << ":\t\t";
274                 SGMetarRunway rwy = runway->second;
275
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);
285                 }
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);
291                 }
292
293                 if (! surface.empty()) {
294                         vector<string>::iterator rwysurf = surface.begin();
295                         for (i = 0; rwysurf != surface.end(); rwysurf++, i++) {
296                                 if (i)
297                                         cout << ", ";
298                                 cout << *rwysurf;
299                         }
300                         lineno++;
301                 }
302
303                 // assemble visibility string
304                 SGMetarVisibility minvis = rwy.getMinVisibility();
305                 SGMetarVisibility maxvis = rwy.getMaxVisibility();
306                 if ((d = minvis.getVisibility_m()) != NaN) {
307                         if (lineno++)
308                                 cout << endl << "\t\t\t";
309                         cout << minvis;
310                 }
311                 if (maxvis.getVisibility_m() != d) {
312                         cout << endl << "\t\t\t" << maxvis << endl;
313                         lineno++;
314                 }
315
316                 if (rwy.getWindShear()) {
317                         if (lineno++)
318                                 cout << endl << "\t\t\t";
319                         cout << "critical wind shear" << endl;
320                 }
321                 cout << endl;
322         }
323         cout << endl;
324 #undef NaN
325 }
326
327
328 void printArgs(SGMetar *m, double airport_elevation)
329 {
330 #define NaN SGMetarNaN
331         vector<string> args;
332         char buf[256];
333         int i;
334
335         // ICAO id
336         sprintf(buf, "--airport=%s ", m->getId());
337         args.push_back(buf);
338
339         // report time
340         sprintf(buf, "--start-date-gmt=%4d:%02d:%02d:%02d:%02d:00 ",
341                         m->getYear(), m->getMonth(), m->getDay(),
342                         m->getHour(), m->getMinute());
343         args.push_back(buf);
344
345         // cloud layers
346         const char *coverage_string[5] = {
347                 "clear", "few", "scattered", "broken", "overcast"
348         };
349         vector<SGMetarCloud> cv = m->getClouds();
350         vector<SGMetarCloud>::iterator cloud;
351         for (i = 0, cloud = cv.begin(); i < 5; i++) {
352                 int coverage = 0;
353                 double altitude = -99999;
354                 if (cloud != cv.end()) {
355                         coverage = cloud->getCoverage();
356                         altitude = coverage ? cloud->getAltitude_ft() + airport_elevation : -99999;
357                         cloud++;
358                 }
359                 sprintf(buf, "--prop:/environment/clouds/layer[%d]/coverage=%s ", i, coverage_string[coverage]);
360                 args.push_back(buf);
361                 sprintf(buf, "--prop:/environment/clouds/layer[%d]/elevation-ft=%.0lf ", i, altitude);
362                 args.push_back(buf);
363                 sprintf(buf, "--prop:/environment/clouds/layer[%d]/thickness-ft=500 ", i);
364                 args.push_back(buf);
365         }
366
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);
380
381                 sprintf(&buf[pos], "elevation-ft=%.0lf", elevation);
382                 args.push_back(buf);
383                 sprintf(&buf[pos], "turbulence-norm=%.0lf", 0.0);
384                 args.push_back(buf);
385
386                 if (visibility != NaN) {
387                         sprintf(&buf[pos], "visibility-m=%.0lf", visibility);
388                         args.push_back(buf);
389                 }
390                 if (temperature != NaN) {
391                         sprintf(&buf[pos], "temperature-degc=%.0lf", temperature);
392                         args.push_back(buf);
393                 }
394                 if (dewpoint != NaN) {
395                         sprintf(&buf[pos], "dewpoint-degc=%.0lf", dewpoint);
396                         args.push_back(buf);
397                 }
398                 if (pressure != NaN) {
399                         sprintf(&buf[pos], "pressure-sea-level-inhg=%.0lf", pressure);
400                         args.push_back(buf);
401                 }
402                 if (wind_dir != NaN) {
403                         sprintf(&buf[pos], "wind-from-heading-deg=%d", wind_dir);
404                         args.push_back(buf);
405                 }
406                 if (wind_speed != NaN) {
407                         sprintf(&buf[pos], "wind-speed-kt=%.0lf", wind_speed);
408                         args.push_back(buf);
409                 }
410         }
411
412         // wind dir@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);
420                 else
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);
425                 args.push_back(buf);
426         }
427         
428
429         // output everything
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;
434         }
435         cout << endl;
436 #undef NaN
437 }
438
439
440 void getproxy(string& host, string& port)
441 {
442         host = "";
443         port = "80";
444
445         const char *p = getenv("http_proxy");
446         if (!p)
447                 return;
448         while (isspace(*p))
449                 p++;
450         if (!strncmp(p, "http://", 7))
451                 p += 7;
452         if (!*p)
453                 return;
454
455         char s[256], *t;
456         strncpy(s, p, 255);
457         s[255] = '\0';
458
459         for (t = s + strlen(s); t > s; t--)
460                 if (!isspace(t[-1]) && t[-1] != '/')
461                         break;
462         *t = '\0';
463
464         t = strchr(s, ':');
465         if (t) {
466                 *t++ = '\0';
467                 port = t;
468         }
469         host = s;
470 }
471
472
473 void usage()
474 {
475         printf(
476                 "Usage: metar [-v] [-e elevation] [-r|-c] <list of ICAO airport ids or METAR strings>\n"
477                 "       metar -h\n"
478                 "\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"
485                 "Environment:\n"
486                 "       http_proxy           set proxy in the form \"http://host:port/\"\n"
487                 "\n"
488                 "Examples:\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"
494                 "\n"
495         );
496 }
497
498 int main(int argc, char *argv[])
499 {
500         bool report = true;
501         bool verbose = false;
502         double elevation = 0.0;
503
504         if (argc <= 1) {
505                 usage();
506                 return 0;
507         }
508
509         string proxy_host, proxy_port;
510         getproxy(proxy_host, proxy_port);
511
512   Socket::initSockets();
513   
514     HTTP::Client http;
515     http.setProxy(proxy_host, atoi(proxy_port.c_str()));
516     
517         for (int i = 1; i < argc; i++) {
518                 if (!strcmp(argv[i], "-h") || !strcmp(argv[i], "--help"))
519                         usage();
520                 else if (!strcmp(argv[i], "-v") || !strcmp(argv[i], "--verbose"))
521                         verbose = true;
522                 else if (!strcmp(argv[i], "-r") || !strcmp(argv[i], "--report"))
523                         report = true;
524                 else if (!strcmp(argv[i], "-c") || !strcmp(argv[i], "--command-line"))
525                         report = false;
526                 else if (!strcmp(argv[i], "-e") || !strcmp(argv[i], "--elevation")) {
527                         if (++i >= argc) {
528                                 cerr << "-e option used without elevation" << endl;
529                                 return 1;
530                         }
531                         elevation = strtod(argv[i], 0);
532                 } else {
533                         static bool shown = false;
534                         if (verbose && !shown) {
535                                 cerr << "Proxy host: '" << proxy_host << "'" << endl;
536                                 cerr << "Proxy port: '" << proxy_port << "'" << endl << endl;
537                                 shown = true;
538                         }
539
540                         try
541                         {
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
545                 (
546                     NOAA_BASE_URL
547                   + boost::to_upper_copy<std::string>(argv[i]) + ".TXT"
548                 );
549                 HTTP::Request_ptr own(mr);
550                 http.makeRequest(mr);
551                 
552             // spin until the request completes, fails or times out
553                 SGTimeStamp start(SGTimeStamp::now());
554                 while (start.elapsedMSec() <  8000) {
555                     http.update();
556                     if( mr->isComplete() )
557                         break;
558                     SGTimeStamp::sleepForMSec(1);
559                 }
560                 
561                 if( !mr->isComplete() )
562                   throw sg_io_exception("metar download timed out");
563                 if( mr->responseCode() != 200 )
564                 {
565                   std::cerr << "metar download failed: "
566                             << mr->url()
567                             << " (" << mr->responseCode()
568                             << " " << mr->responseReason() << ")"
569                             << std::endl;
570                   throw sg_io_exception("metar download failed");
571                 }
572
573                                 SGMetar *m = new SGMetar(mr->responseBody());
574                                 
575                                 //SGMetar *m = new SGMetar("2004/01/11 01:20\nLOWG 110120Z AUTO VRB01KT 0050 1600N R35/0600 FG M06/M06 Q1019 88//////\n");
576
577                                 if (verbose) {
578                                         cerr << G"INPUT: " << m->getData() << ""N << endl;
579
580                                         const char *unused = m->getUnusedData();
581                                         if (*unused)
582                                                 cerr << R"UNUSED: " << unused << ""N << endl;
583                                 }
584
585                                 if (report)
586                                         printReport(m);
587                                 else
588                                         printArgs(m, elevation);
589
590                                 delete m;
591                         } catch (const sg_io_exception& e) {
592                                 cerr << R"ERROR: " << e.getFormattedMessage().c_str() << ""N << endl << endl;
593                         }
594                 }
595         }
596         return 0;
597 }
598
599