1 // metar interface class
3 // Written by Melchior FRANZ, started December 2003.
5 // Copyright (C) 2003 Melchior FRANZ - mfranz@aon.at
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.
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.
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.
25 * Interface for encoded Meteorological Aerodrome Reports (METAR).
28 # include <simgear_config.h>
35 #include <simgear/io/sg_socket.hxx>
36 #include <simgear/debug/logstream.hxx>
37 #include <simgear/structure/exception.hxx>
41 #define NaN SGMetarNaN
44 * The constructor takes a Metar string, or a four-letter ICAO code. In the
45 * latter case the metar string is downloaded from
46 * http://weather.noaa.gov/pub/data/observations/metar/stations/.
47 * The constructor throws sg_io_exceptions on failure. The "METAR"
48 * keyword has no effect (apart from incrementing the group counter
49 * @a grpcount) and can be left away. A keyword "SPECI" is
52 * @param m ICAO station id or metar string
53 * @param proxy proxy host (optional; default: "")
54 * @param port proxy port (optional; default: "80")
55 * @param auth proxy authorization information (optional; default: "")
59 * SGMetar *m = new SGMetar("METAR KSFO 061656Z 19004KT 9SM SCT100 OVC200 08/03 A3013");
60 * double t = m->getTemperature_F();
63 * SGMetar n("KSFO", "proxy.provider.foo", "3128", "proxy-password");
64 * double d = n.getDewpoint_C();
67 SGMetar::SGMetar(const string& m, const string& proxy, const string& port,
68 const string& auth, const time_t time) :
90 if (m.length() == 4 && isalnum(m[0]) && isalnum(m[1]) && isalnum(m[2]) && isalnum(m[3])) {
91 for (int i = 0; i < 4; i++)
92 _icao[i] = toupper(m[i]);
94 _data = loadData(_icao, proxy, port, auth, time);
96 _data = new char[m.length() + 2]; // make room for " \0"
97 strcpy(_data, m.c_str());
106 if (!scanPreambleDate())
112 if (!scanId() || !scanDate()) {
114 throw sg_io_exception("metar data bogus ", sg_location(_url));
121 while (scanVisibility()) ;
122 while (scanRwyVisRange()) ;
123 while (scanWeather()) ;
124 while (scanSkyCondition()) ;
127 while (scanSkyCondition()) ;
128 while (scanRunwayReport()) ;
132 while (scanColorState()) ;
134 while (scanRunwayReport()) ;
140 throw sg_io_exception("metar data incomplete ", sg_location(_url));
148 * Clears lists and maps to discourage access after destruction.
159 void SGMetar::useCurrentDate()
162 time_t now_sec = time(0);
164 now = *gmtime(&now_sec);
166 gmtime_r(&now_sec, &now);
168 _year = now.tm_year + 1900;
169 _month = now.tm_mon + 1;
174 * If called with "KSFO" loads data from
176 * http://weather.noaa.gov/pub/data/observations/metar/stations/KSFO.TXT.
178 * Throws sg_io_exception on failure. Gives up after waiting longer than 10 seconds.
180 * @param id four-letter ICAO Metar station code, e.g. "KSFO".
181 * @param proxy proxy host (optional; default: "")
182 * @param port proxy port (optional; default: "80")
183 * @param auth proxy authorization information (optional; default: "")
184 * @return pointer to Metar data string, allocated by new char[].
185 * @see rfc2068.txt for proxy spec ("Proxy-Authorization")
187 char *SGMetar::loadData(const char *id, const string& proxy, const string& port,
188 const string& auth, time_t time)
190 const int buflen = 512;
191 char buf[2 * buflen];
193 string metar_server = "weather.noaa.gov";
194 string host = proxy.empty() ? metar_server : proxy;
195 string path = "/pub/data/observations/metar/stations/";
197 path += string(id) + ".TXT";
198 _url = "http://" + metar_server + path;
200 SGSocket *sock = new SGSocket(host, port.empty() ? "80" : port, "tcp");
201 sock->set_timeout(10000);
202 if (!sock->open(SG_IO_OUT)) {
204 throw sg_io_exception("cannot connect to ", sg_location(host));
209 get += "http://" + metar_server;
211 sprintf(buf, "%ld", time);
212 get += path + " HTTP/1.0\015\012X-Time: " + buf + "\015\012";
213 get += "Host: " + metar_server + "\015\012";
216 get += "Proxy-Authorization: " + auth + "\015\012";
219 sock->writestring(get.c_str());
224 while ((i = sock->readline(buf, buflen))) {
225 if (i <= 2 && isspace(buf[0]) && (!buf[1] || isspace(buf[1])))
227 if (!strncmp(buf, "X-MetarProxy: ", 13))
231 i = sock->readline(buf, buflen);
233 sock->readline(&buf[i], buflen);
242 throw sg_io_exception("no metar data available from ",
245 char *metar = new char[strlen(b) + 2]; // make room for " \0"
252 * Replace any number of subsequent spaces by just one space, and add
253 * a trailing space. This makes scanning for things like "ALL RWY" easier.
255 void SGMetar::normalizeData()
258 for (src = dest = _data; (*dest++ = *src++); )
259 while (*src == ' ' && src[1] == ' ')
261 for (dest--; isspace(*--dest); ) ;
267 // \d\d\d\d/\d\d/\d\d
268 bool SGMetar::scanPreambleDate()
271 int year, month, day;
272 if (!scanNumber(&m, &year, 4))
276 if (!scanNumber(&m, &month, 2))
280 if (!scanNumber(&m, &day, 2))
282 if (!scanBoundary(&m))
293 bool SGMetar::scanPreambleTime()
297 if (!scanNumber(&m, &hour, 2))
301 if (!scanNumber(&m, &minute, 2))
303 if (!scanBoundary(&m))
313 bool SGMetar::scanType()
315 if (strncmp(_m, "METAR ", 6) && strncmp(_m, "SPECI ", 6))
324 bool SGMetar::scanId()
327 for (int i = 0; i < 4; m++, i++)
328 if (!(isalpha(*m) || isdigit(*m)))
330 if (!scanBoundary(&m))
332 strncpy(_icao, _m, 4);
341 bool SGMetar::scanDate()
344 int day, hour, minute;
345 if (!scanNumber(&m, &day, 2))
347 if (!scanNumber(&m, &hour, 2))
349 if (!scanNumber(&m, &minute, 2))
353 if (!scanBoundary(&m))
364 // (NIL|AUTO|COR|RTD)
365 bool SGMetar::scanModifier()
369 if (!strncmp(m, "NIL", 3)) {
373 if (!strncmp(m, "AUTO", 4)) // automatically generated
375 else if (!strncmp(m, "COR", 3)) // manually corrected
377 else if (!strncmp(m, "RTD", 3)) // routine delayed
381 if (!scanBoundary(&m))
390 // (\d{3}|VRB)\d{1,3}(G\d{2,3})?(KT|KMH|MPS)
391 bool SGMetar::scanWind()
395 if (!strncmp(m, "VRB", 3))
397 else if (!scanNumber(&m, &dir, 3))
401 if (!scanNumber(&m, &i, 2, 3))
408 if (!scanNumber(&m, &i, 2, 3))
413 if (!strncmp(m, "KT", 2))
414 m += 2, factor = SG_KT_TO_MPS;
415 else if (!strncmp(m, "KMH", 3))
416 m += 3, factor = SG_KMH_TO_MPS;
417 else if (!strncmp(m, "KPH", 3)) // ??
418 m += 3, factor = SG_KMH_TO_MPS;
419 else if (!strncmp(m, "MPS", 3))
420 m += 3, factor = 1.0;
423 if (!scanBoundary(&m))
427 _wind_speed = speed * factor;
429 _gust_speed = gust * factor;
436 bool SGMetar::scanVariability()
440 if (!scanNumber(&m, &from, 3))
444 if (!scanNumber(&m, &to, 3))
446 if (!scanBoundary(&m))
449 _wind_range_from = from;
456 bool SGMetar::scanVisibility()
457 // TODO: if only directed vis are given, do still set min/max
459 if (!strncmp(_m, "//// ", 5)) { // spec compliant?
468 int modifier = SGMetarVisibility::EQUALS;
469 // \d{4}(N|NE|E|SE|S|SW|W|NW)?
470 if (scanNumber(&m, &i, 4)) {
471 if( strncmp( m, "NDV",3 ) == 0 ) {
472 m+=3; // tolerate NDV (no directional validation)
473 } else if (*m == 'E') {
475 } else if (*m == 'W') {
477 } else if (*m == 'N') {
485 } else if (*m == 'S') {
495 i = 50, modifier = SGMetarVisibility::LESS_THAN;
497 i++, modifier = SGMetarVisibility::GREATER_THAN;
500 // M?(\d{1,2}|\d{1,2}/\d{1,2}|\d{1,2} \d{1,2}/\d{1,2})(SM|KM)
502 m++, modifier = SGMetarVisibility::LESS_THAN;
504 if (!scanNumber(&m, &i, 1, 2))
510 if (!scanNumber(&m, &i, 1, 2))
513 } else if (*m == ' ') {
516 if (!scanNumber(&m, &i, 1, 2))
520 if (!scanNumber(&m, &denom, 1, 2))
522 distance += (double)i / denom;
525 if (!strncmp(m, "SM", 2))
526 distance *= SG_SM_TO_METER, m += 2;
527 else if (!strncmp(m, "KM", 2))
528 distance *= 1000, m += 2;
532 if (!scanBoundary(&m))
535 SGMetarVisibility *v;
537 v = &_dir_visibility[dir / 45];
538 else if (_min_visibility._distance == NaN)
539 v = &_min_visibility;
541 v = &_max_visibility;
543 v->_distance = distance;
544 v->_modifier = modifier;
552 // R\d\d[LCR]?/([PM]?\d{4}V)?[PM]?\d{4}(FT)?[DNU]?
553 bool SGMetar::scanRwyVisRange()
560 if (!scanNumber(&m, &i, 2))
562 if (*m == 'L' || *m == 'C' || *m == 'R')
566 strncpy(id, _m + 1, i = m - _m - 1);
574 m++, r._min_visibility._modifier = SGMetarVisibility::GREATER_THAN;
576 m++, r._min_visibility._modifier = SGMetarVisibility::LESS_THAN;
577 if (!scanNumber(&m, &from, 4))
582 m++, r._max_visibility._modifier = SGMetarVisibility::GREATER_THAN;
584 m++, r._max_visibility._modifier = SGMetarVisibility::LESS_THAN;
585 if (!scanNumber(&m, &to, 4))
590 if (!strncmp(m, "FT", 2)) {
591 from = int(from * SG_FEET_TO_METER);
592 to = int(to * SG_FEET_TO_METER);
595 r._min_visibility._distance = from;
596 r._max_visibility._distance = to;
598 if (*m == '/') // this is not in the spec!
601 m++, r._min_visibility._tendency = SGMetarVisibility::DECREASING;
603 m++, r._min_visibility._tendency = SGMetarVisibility::STABLE;
605 m++, r._min_visibility._tendency = SGMetarVisibility::INCREASING;
607 if (!scanBoundary(&m))
611 _runways[id]._min_visibility = r._min_visibility;
612 _runways[id]._max_visibility = r._max_visibility;
618 static const struct Token special[] = {
619 { "NSW", "no significant weather" },
620 { "VCSH", "showers in the vicinity" },
621 { "VCTS", "thunderstorm in the vicinity" },
626 static const struct Token description[] = {
627 { "SH", "showers of" },
628 { "TS", "thunderstorm with" },
629 { "BC", "patches of" },
631 { "DR", "low drifting" },
632 { "FZ", "freezing" },
639 static const struct Token phenomenon[] = {
642 { "GS", "small hail and/or snow pellets" },
643 { "IC", "ice crystals" },
644 { "PE", "ice pellets" },
646 { "SG", "snow grains" },
648 { "UP", "unknown precipitation" },
650 { "DU", "widespread dust" },
652 { "FGBR", "fog bank" },
657 { "VA", "volcanic ash" },
658 { "DS", "duststorm" },
659 { "FC", "funnel cloud/tornado waterspout" },
660 { "PO", "well-developed dust/sand whirls" },
662 { "SS", "sandstorm" },
663 { "UP", "unknown" }, // ... due to failed automatic acquisition
668 // (+|-|VC)?(NSW|MI|PR|BC|DR|BL|SH|TS|FZ)?((DZ|RA|SN|SG|IC|PE|GR|GS|UP){0,3})(BR|FG|FU|VA|DU|SA|HZ|PY|PO|SQ|FC|SS|DS){0,3}
669 bool SGMetar::scanWeather()
673 const struct Token *a;
674 if ((a = scanToken(&m, special))) {
675 if (!scanBoundary(&m))
677 _weather.push_back(a->text);
685 m++, pre = "light ", intensity = 1;
687 m++, pre = "heavy ", intensity = 3;
688 else if (!strncmp(m, "VC", 2))
689 m += 2, post = "in the vicinity ";
691 pre = "moderate ", intensity = 2;
694 for (i = 0; i < 3; i++) {
695 if (!(a = scanToken(&m, description)))
697 weather += string(a->text) + " ";
699 for (i = 0; i < 3; i++) {
700 if (!(a = scanToken(&m, phenomenon)))
702 weather += string(a->text) + " ";
703 if (!strcmp(a->id, "RA"))
705 else if (!strcmp(a->id, "HA"))
707 else if (!strcmp(a->id, "SN"))
710 if (!weather.length())
712 if (!scanBoundary(&m))
715 weather = pre + weather + post;
716 weather.erase(weather.length() - 1);
717 _weather.push_back(weather);
723 static const struct Token cloud_types[] = {
724 { "AC", "altocumulus" },
725 { "ACC", "altocumulus castellanus" },
726 { "ACSL", "altocumulus standing lenticular" },
727 { "AS", "altostratus" },
728 { "CB", "cumulonimbus" },
729 { "CBMAM", "cumulonimbus mammatus" },
730 { "CC", "cirrocumulus" },
731 { "CCSL", "cirrocumulus standing lenticular" },
733 { "CS", "cirrostratus" },
735 { "CUFRA", "cumulus fractus" },
736 { "NS", "nimbostratus" },
737 { "SAC", "stratoaltocumulus" }, // guessed
738 { "SC", "stratocumulus" },
739 { "SCSL", "stratocumulus standing lenticular" },
741 { "STFRA", "stratus fractus" },
742 { "TCU", "towering cumulus" },
747 // (FEW|SCT|BKN|OVC|SKC|CLR|CAVOK|VV)([0-9]{3}|///)?[:cloud_type:]?
748 bool SGMetar::scanSkyCondition()
754 if (!strncmp(m, "//////", 6)) {
756 if (!scanBoundary(&m))
762 if (!strncmp(m, "CLR", i = 3) // clear
763 || !strncmp(m, "SKC", i = 3) // sky clear
764 || !strncmp(m, "NSC", i = 3) // no significant clouds
765 || !strncmp(m, "CAVOK", i = 5)) { // ceiling and visibility OK (implies 9999)
767 if (!scanBoundary(&m))
772 _clouds.push_back(cl);
780 if (!strncmp(m, "VV", i = 2)) // vertical visibility
782 else if (!strncmp(m, "FEW", i = 3))
784 else if (!strncmp(m, "SCT", i = 3))
786 else if (!strncmp(m, "BKN", i = 3))
788 else if (!strncmp(m, "OVC", i = 3))
794 if (!strncmp(m, "///", 3)) // vis not measurable (e.g. because of heavy snowing)
796 else if (scanBoundary(&m)) {
798 return true; // ignore single OVC/BKN/...
799 } else if (!scanNumber(&m, &i, 3))
802 if (cl._coverage == -1) {
803 if (!scanBoundary(&m))
805 if (i == -1) // 'VV///'
806 _vert_visibility._modifier = SGMetarVisibility::NOGO;
808 _vert_visibility._distance = i * 100 * SG_FEET_TO_METER;
814 cl._altitude = i * 100 * SG_FEET_TO_METER;
816 const struct Token *a;
817 if ((a = scanToken(&m, cloud_types))) {
819 cl._type_long = a->text;
821 if (!scanBoundary(&m))
823 _clouds.push_back(cl);
830 // M?[0-9]{2}/(M?[0-9]{2})? (spec)
831 // (M?[0-9]{2}|XX)/(M?[0-9]{2}|XX)? (Namibia)
832 bool SGMetar::scanTemperature()
835 int sign = 1, temp, dew;
836 if (!strncmp(m, "XX/XX", 5)) { // not spec compliant!
838 return scanBoundary(&_m);
843 if (!scanNumber(&m, &temp, 2))
849 if (!scanBoundary(&m)) {
850 if (!strncmp(m, "XX", 2)) // not spec compliant!
851 m += 2, sign = 0, dew = temp;
856 if (!scanNumber(&m, &dew, 2))
859 if (!scanBoundary(&m))
871 double SGMetar::getRelHumidity() const
873 if (_temp == NaN || _dewp == NaN)
875 double dewp = pow(10.0, 7.5 * _dewp / (237.7 + _dewp));
876 double temp = pow(10.0, 7.5 * _temp / (237.7 + _temp));
877 return dewp * 100 / temp;
882 // [AQ]\d{2}(\d{2}|//) (Namibia)
883 bool SGMetar::scanPressure()
890 factor = SG_INHG_TO_PA / 100;
896 if (!scanNumber(&m, &press, 2))
899 if (!strncmp(m, "//", 2)) // not spec compliant!
901 else if (scanNumber(&m, &i, 2))
905 if (!scanBoundary(&m))
907 _pressure = press * factor;
914 static const char *runway_deposit[] = {
928 static const char *runway_deposit_extent[] = {
929 0, "1-10%", "11-25%", 0, 0, "26-50%", 0, 0, 0, "51-100%"
933 static const char *runway_friction[] = {
935 "poor braking action",
936 "poor/medium braking action",
937 "medium braking action",
938 "medium/good braking action",
939 "good braking action",
941 "friction: unreliable measurement"
945 // \d\d(CLRD|[\d/]{4})(\d\d|//)
946 bool SGMetar::scanRunwayReport()
953 if (!scanNumber(&m, &i, 2))
958 strcpy(id, "REP"); // repetition of previous report
961 id[0] = i / 10 + '0', id[1] = i % 10 + '0', id[2] = 'R', id[3] = '\0';
963 id[0] = i / 10 + '0', id[1] = i % 10 + '0', id[2] = '\0';
965 if (!strncmp(m, "CLRD", 4)) {
966 m += 4; // runway cleared
967 r._deposit_string = "cleared";
969 if (scanNumber(&m, &i, 1)) {
971 r._deposit_string = runway_deposit[i];
972 } else if (*m == '/')
977 if (*m == '1' || *m == '2' || *m == '5' || *m == '9') { // extent of deposit
978 r._extent = *m - '0';
979 r._extent_string = runway_deposit_extent[*m - '0'];
980 } else if (*m != '/')
985 if (!strncmp(m, "//", 2))
987 else if (!scanNumber(&m, &i, 2))
991 r._depth = 0.0005; // < 1 mm deep (let's say 0.5 :-)
992 else if (i > 0 && i <= 90)
993 r._depth = i / 1000.0; // i mm deep
994 else if (i >= 92 && i <= 98)
995 r._depth = (i - 90) / 20.0;
997 r._comment = "runway not in use";
998 else if (i == -1) // no depth given ("//")
1004 if (m[0] == '/' && m[1] == '/')
1006 else if (!scanNumber(&m, &i, 2))
1008 if (i >= 1 && i < 90) {
1009 r._friction = i / 100.0;
1010 } else if ((i >= 91 && i <= 95) || i == 99) {
1011 r._friction_string = runway_friction[i - 90];
1013 if (!scanBoundary(&m))
1016 _runways[id]._deposit = r._deposit;
1017 _runways[id]._deposit_string = r._deposit_string;
1018 _runways[id]._extent = r._extent;
1019 _runways[id]._extent_string = r._extent_string;
1020 _runways[id]._depth = r._depth;
1021 _runways[id]._friction = r._friction;
1022 _runways[id]._friction_string = r._friction_string;
1023 _runways[id]._comment = r._comment;
1030 // WS (ALL RWYS?|RWY ?\d\d[LCR]?)?
1031 bool SGMetar::scanWindShear()
1034 if (strncmp(m, "WS", 2))
1037 if (!scanBoundary(&m))
1040 if (!strncmp(m, "ALL", 3)) {
1042 if (!scanBoundary(&m))
1044 if (strncmp(m, "RWY", 3))
1049 if (!scanBoundary(&m))
1051 _runways["ALL"]._wind_shear = true;
1058 for (cnt = 0;; cnt++) { // ??
1059 if (strncmp(m, "RWY", 3))
1064 if (!scanNumber(&m, &i, 2))
1066 if (*m == 'L' || *m == 'C' || *m == 'R')
1068 strncpy(id, mm, i = m - mm);
1070 if (!scanBoundary(&m))
1072 _runways[id]._wind_shear = true;
1075 _runways["ALL"]._wind_shear = true;
1081 bool SGMetar::scanTrendForecast()
1084 if (strncmp(m, "NOSIG", 5))
1088 if (!scanBoundary(&m))
1095 // (BLU|WHT|GRN|YLO|AMB|RED)
1096 static const struct Token colors[] = {
1097 { "BLU", "Blue" }, // 2500 ft, 8.0 km
1098 { "WHT", "White" }, // 1500 ft, 5.0 km
1099 { "GRN", "Green" }, // 700 ft, 3.7 km
1100 { "YLO", "Yellow" }, // 300 ft, 1.6 km
1101 { "AMB", "Amber" }, // 200 ft, 0.8 km
1102 { "RED", "Red" }, // <200 ft, <0.8 km
1107 bool SGMetar::scanColorState()
1110 const struct Token *a;
1111 if (!(a = scanToken(&m, colors)))
1113 if (!scanBoundary(&m))
1115 //printf(Y"Code %s\n"N, a->text);
1121 bool SGMetar::scanRemark()
1123 if (strncmp(_m, "RMK", 3))
1126 if (!scanBoundary(&_m))
1130 if (!scanRunwayReport()) {
1131 while (*_m && !isspace(*_m))
1140 bool SGMetar::scanRemainder()
1143 if (!(strncmp(m, "NOSIG", 5))) {
1145 if (scanBoundary(&m))
1146 _m = m; //_comment.push_back("No significant tendency");
1149 if (!scanBoundary(&m))
1156 bool SGMetar::scanBoundary(char **s)
1158 if (**s && !isspace(**s))
1160 while (isspace(**s))
1166 int SGMetar::scanNumber(char **src, int *num, int min, int max)
1171 for (i = 0; i < min; i++) {
1175 *num = *num * 10 + *s++ - '0';
1177 for (; i < max && isdigit(*s); i++)
1178 *num = *num * 10 + *s++ - '0';
1184 // find longest match of str in list
1185 const struct Token *SGMetar::scanToken(char **str, const struct Token *list)
1187 const struct Token *longest = 0;
1188 int maxlen = 0, len;
1190 for (int i = 0; (s = list[i].id); i++) {
1192 if (!strncmp(s, *str, len) && len > maxlen) {
1202 void SGMetarCloud::set(double alt, int cov)
1210 void SGMetarVisibility::set(double dist, int dir, int mod, int tend)