Debian Codegraph @

src/Main/metar_main.cxx

raw symbols SCIP
1 // metar interface class demo
2 //
3 // Written by Melchior FRANZ, started December 2003.
4 //
5 // Copyright (C) 2003 Melchior FRANZ - [email protected]
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/environment/metar.hxx>
32 #include <simgear/structure/exception.hxx>
33
34 #include <simgear/io/HTTPClient.hxx>
35 #include <simgear/io/HTTPMemoryRequest.hxx>
36 #include <simgear/io/raw_socket.hxx>
37 #include <simgear/timing/timestamp.hxx>
38 #include <simgear/misc/strutils.hxx>
39
40
41 using namespace std;
42 using namespace simgear;
43
44 // text color
45 #if defined(__linux__) || defined(__sun) || defined(__CYGWIN__) || defined( __FreeBSD__ ) || defined( __OpenBSD__ ) || defined ( sgi )
46 # define R "\033[31;1m" // red
47 # define G "\033[32;1m" // green
48 # define Y "\033[33;1m" // yellow
49 # define B "\033[34;1m" // blue
50 # define M "\033[35;1m" // magenta
51 # define C "\033[36;1m" // cyan
52 # define W "\033[37;1m" // white
53 # define N "\033[m" // normal
54 #else
55 # define R ""
56 # define G ""
57 # define Y ""
58 # define B ""
59 # define M ""
60 # define C ""
61 # define W ""
62 # define N ""
63 #endif
64
65
66
67 const char *azimuthName(double d)
68 {
69 const char *dir[] = {
70 "N", "NNE", "NE", "ENE",
71 "E", "ESE", "SE", "SSE",
72 "S", "SSW", "SW", "WSW",
73 "W", "WNW", "NW", "NNW"
74 };
75 d += 11.25;
76 while (d < 0)
77 d += 360;
78 while (d >= 360)
79 d -= 360;
80 return dir[int(d / 22.5)];
81 }
82
83
84 // round double to 10^g
85 double rnd(double r, int g = 0)
86 {
87 double f = pow(10.0, g);
88 return f * floor(r / f + 0.5);
89 }
90
91
92 ostream& operator<<(ostream& s, const SGMetarVisibility& v)
93 {
94 ostringstream buf;
95 int m = v.getModifier();
96 const char *mod;
97 if (m == SGMetarVisibility::GREATER_THAN)
98 mod = ">=";
99 else if (m == SGMetarVisibility::LESS_THAN)
100 mod = "<";
101 else
102 mod = "";
103 buf << mod;
104
105 double dist = rnd(v.getVisibility_m(), 1);
106 if (dist < 1000.0)
107 buf << rnd(dist, 1) << " m";
108 else
109 buf << rnd(dist / 1000.0, -1) << " km";
110
111 const char *dir = "";
112 int i;
113 if ((i = v.getDirection()) != -1) {
114 dir = azimuthName(i);
115 buf << " " << dir;
116 }
117 buf << "\t\t\t\t\t" << mod << rnd(v.getVisibility_sm(), -1) << " US-miles " << dir;
118 return s << buf.str();
119 }
120
121
122 void printReport(SGMetar *m)
123 {
124 cout << m->getDescription(0);
125 }
126
127
128 void printArgs(SGMetar *m, double airport_elevation)
129 {
130 #define NaN SGMetarNaN
131 vector<string> args;
132 char buf[256];
133 int i;
134
135 // ICAO id
136 sprintf(buf, "--airport=%s ", m->getId());
137 args.push_back(buf);
138
139 // report time
140 sprintf(buf, "--start-date-gmt=%4d:%02d:%02d:%02d:%02d:00 ",
141 m->getYear(), m->getMonth(), m->getDay(),
142 m->getHour(), m->getMinute());
143 args.push_back(buf);
144
145 // cloud layers
146 const char *coverage_string[5] = {
147 "clear", "few", "scattered", "broken", "overcast"
148 };
149 vector<SGMetarCloud> cv = m->getClouds();
150 vector<SGMetarCloud>::iterator cloud;
151 for (i = 0, cloud = cv.begin(); i < 5; i++) {
152 int coverage = 0;
153 double altitude = -99999;
154 if (cloud != cv.end()) {
155 coverage = cloud->getCoverage();
156 altitude = coverage ? cloud->getAltitude_ft() + airport_elevation : -99999;
157 cloud++;
158 }
159 sprintf(buf, "--prop:/environment/clouds/layer[%d]/coverage=%s ", i, coverage_string[coverage]);
160 args.push_back(buf);
161 sprintf(buf, "--prop:/environment/clouds/layer[%d]/elevation-ft=%.0lf ", i, altitude);
162 args.push_back(buf);
163 sprintf(buf, "--prop:/environment/clouds/layer[%d]/thickness-ft=500 ", i);
164 args.push_back(buf);
165 }
166
167 // environment (temperature, dewpoint, visibility, pressure)
168 // metar sets don't provide aloft information; we have to
169 // set the same values for all boundary levels
170 int wind_dir = m->getWindDir();
171 double visibility = m->getMinVisibility().getVisibility_m();
172 double dewpoint = m->getDewpoint_C();
173 double temperature = m->getTemperature_C();
174 double pressure = m->getPressure_inHg();
175 double wind_speed = m->getWindSpeed_kt();
176 double elevation = -100;
177 for (i = 0; i < 3; i++, elevation += 2000.0) {
178 sprintf(buf, "--prop:/environment/config/boundary/entry[%d]/", i);
179 int pos = strlen(buf);
180
181 sprintf(&buf[pos], "elevation-ft=%.0lf", elevation);
182 args.push_back(buf);
183 sprintf(&buf[pos], "turbulence-norm=%.0lf", 0.0);
184 args.push_back(buf);
185
186 if (visibility != NaN) {
187 sprintf(&buf[pos], "visibility-m=%.0lf", visibility);
188 args.push_back(buf);
189 }
190 if (temperature != NaN) {
191 sprintf(&buf[pos], "temperature-degc=%.0lf", temperature);
192 args.push_back(buf);
193 }
194 if (dewpoint != NaN) {
195 sprintf(&buf[pos], "dewpoint-degc=%.0lf", dewpoint);
196 args.push_back(buf);
197 }
198 if (pressure != NaN) {
199 sprintf(&buf[pos], "pressure-sea-level-inhg=%.0lf", pressure);
200 args.push_back(buf);
201 }
202 if (wind_dir != NaN) {
203 sprintf(&buf[pos], "wind-from-heading-deg=%d", wind_dir);
204 args.push_back(buf);
205 }
206 if (wind_speed != NaN) {
207 sprintf(&buf[pos], "wind-speed-kt=%.0lf", wind_speed);
208 args.push_back(buf);
209 }
210 }
211
212 // wind dir@speed
213 int range_from = m->getWindRangeFrom();
214 int range_to = m->getWindRangeTo();
215 double gust_speed = m->getGustSpeed_kt();
216 if (wind_speed != NaN && wind_dir != -1) {
217 strcpy(buf, "--wind=");
218 if (range_from != -1 && range_to != -1)
219 sprintf(&buf[strlen(buf)], "%d:%d", range_from, range_to);
220 else
221 sprintf(&buf[strlen(buf)], "%d", wind_dir);
222 sprintf(&buf[strlen(buf)], "@%.0lf", wind_speed);
223 if (gust_speed != NaN)
224 sprintf(&buf[strlen(buf)], ":%.0lf", gust_speed);
225 args.push_back(buf);
226 }
227
228
229 // output everything
230 //cout << "fgfs" << endl;
231 vector<string>::iterator arg;
232 for (i = 0, arg = args.begin(); arg != args.end(); i++, arg++) {
233 cout << "\t" << *arg << endl;
234 }
235 cout << endl;
236 #undef NaN
237 }
238
239
240 void getproxy(string& host, string& port)
241 {
242 host = "";
243 port = "80";
244
245 const char *p = getenv("http_proxy");
246 if (!p)
247 return;
248 while (isspace(*p))
249 p++;
250 if (!strncmp(p, "http://", 7))
251 p += 7;
252 if (!*p)
253 return;
254
255 char s[256], *t;
256 strncpy(s, p, 255);
257 s[255] = '\0';
258
259 for (t = s + strlen(s); t > s; t--)
260 if (!isspace(t[-1]) && t[-1] != '/')
261 break;
262 *t = '\0';
263
264 t = strchr(s, ':');
265 if (t) {
266 *t++ = '\0';
267 port = t;
268 }
269 host = s;
270 }
271
272
273 void usage()
274 {
275 printf(
276 "Usage: metar [-v] [-e elevation] [-r|-c] <list of ICAO airport ids or METAR strings>\n"
277 " metar -h\n"
278 "\n"
279 " -h|--help show this help\n"
280 " -v|--verbose verbose output\n"
281 " -r|--report print report (default)\n"
282 " -c|--command-line print command line\n"
283 " -e E|--elevation E set airport elevation to E meters\n"
284 " (added to cloud bases in command line mode)\n"
285 " -s|--string <METAR string>\n"
286 "Environment:\n"
287 " http_proxy set proxy in the form \"http://host:port/\"\n"
288 "\n"
289 "Examples:\n"
290 " $ metar ksfo koak\n"
291 " $ metar -c ksfo -r ksfo\n"
292 " $ metar -s \"LOWL 161500Z 19004KT 160V240 9999 FEW035 SCT300 29/23 Q1006 NOSIG\"\n"
293 " $ fgfs `metar -e 183 -c loww`\n"
294 " $ http_proxy=http://localhost:3128/ metar ksfo\n"
295 "\n"
296 );
297 }
298
299 int main(int argc, char *argv[])
300 {
301 bool report = true;
302 bool verbose = false;
303 double elevation = 0.0;
304
305 if (argc <= 1) {
306 usage();
307 return 0;
308 }
309
310 string proxy_host, proxy_port;
311 getproxy(proxy_host, proxy_port);
312
313 Socket::initSockets();
314
315 HTTP::Client http;
316 http.setProxy(proxy_host, atoi(proxy_port.c_str()));
317
318 for (int i = 1; i < argc; i++) {
319 if (!strcmp(argv[i], "-h") || !strcmp(argv[i], "--help"))
320 usage();
321 else if (!strcmp(argv[i], "-v") || !strcmp(argv[i], "--verbose"))
322 verbose = true;
323 else if (!strcmp(argv[i], "-r") || !strcmp(argv[i], "--report"))
324 report = true;
325 else if (!strcmp(argv[i], "-c") || !strcmp(argv[i], "--command-line"))
326 report = false;
327 else if (!strcmp(argv[i], "-e") || !strcmp(argv[i], "--elevation")) {
328 if (++i >= argc) {
329 cerr << "-e option used without elevation" << endl;
330 return 1;
331 }
332 elevation = strtod(argv[i], 0);
333 }
334 else if (!strcmp(argv[i], "-s") || !strcmp(argv[i], "--string")) {
335 if (++i >= argc) {
336 cerr << "-s option used with out string\n";
337 return 1;
338 }
339 const char* string = argv[i];
340 SGMetar metar(string);
341 printReport(&metar);
342 }
343 else {
344 static bool shown = false;
345 if (verbose && !shown) {
346 cerr << "Proxy host: '" << proxy_host << "'" << endl;
347 cerr << "Proxy port: '" << proxy_port << "'" << endl << endl;
348 shown = true;
349 }
350
351 try
352 {
353 static const std::string NOAA_BASE_URL =
354 "https://tgftp.nws.noaa.gov/data/observations/metar/stations/";
355 HTTP::MemoryRequest* mr = new HTTP::MemoryRequest
356 (
357 NOAA_BASE_URL + strutils::uppercase(argv[i]) + ".TXT"
358 );
359 HTTP::Request_ptr own(mr);
360 http.makeRequest(mr);
361
362 // spin until the request completes, fails or times out
363 SGTimeStamp start(SGTimeStamp::now());
364 while (start.elapsedMSec() < 8000) {
365 http.update();
366 if( mr->isComplete() )
367 break;
368 SGTimeStamp::sleepForMSec(1);
369 }
370
371 if( !mr->isComplete() )
372 throw sg_io_exception("metar download timed out");
373 if( mr->responseCode() != 200 )
374 {
375 std::cerr << "metar download failed: "
376 << mr->url()
377 << " (" << mr->responseCode()
378 << " " << mr->responseReason() << ")"
379 << std::endl;
380 throw sg_io_exception("metar download failed");
381 }
382
383 SGMetar *m = new SGMetar(mr->responseBody());
384
385 //SGMetar *m = new SGMetar("2004/01/11 01:20\nLOWG 110120Z AUTO VRB01KT 0050 1600N R35/0600 FG M06/M06 Q1019 88//////\n");
386
387 if (verbose) {
388 cerr << G "INPUT: " << m->getDataString() << "" N << endl;
389
390 const auto unused = m->getUnparsedData();
391 if (!unused.empty())
392 cerr << R "UNUSED: " << unused << "" N << endl;
393 }
394
395 if (report)
396 printReport(m);
397 else
398 printArgs(m, elevation);
399
400 delete m;
401 } catch (const sg_io_exception& e) {
402 cerr << R "ERROR: " << e.getFormattedMessage().c_str() << "" N << endl << endl;
403 }
404 }
405 }
406 return 0;
407 }
408
409