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>
34 #include <simgear/io/sg_socket.hxx>
35 #include <simgear/debug/logstream.hxx>
36 #include <simgear/structure/exception.hxx>
40 #define NaN SGMetarNaN
43 * The constructor takes a Metar string, or a four-letter ICAO code. In the
44 * latter case the metar string is downloaded from
45 * http://weather.noaa.gov/pub/data/observations/metar/stations/.
46 * The constructor throws sg_io_exceptions on failure. The "METAR"
47 * keyword has no effect (apart from incrementing the group counter
48 * @a grpcount) and can be left away. A keyword "SPECI" is
51 * @param m ICAO station id or metar string
52 * @param proxy proxy host (optional; default: "")
53 * @param port proxy port (optional; default: "80")
54 * @param auth proxy authorization information (optional; default: "")
58 * SGMetar *m = new SGMetar("METAR KSFO 061656Z 19004KT 9SM SCT100 OVC200 08/03 A3013");
59 * double t = m->getTemperature_F();
62 * SGMetar n("KSFO", "proxy.provider.foo", "3128", "proxy-password");
63 * double d = n.getDewpoint_C();
66 SGMetar::SGMetar(const string& m, const string& proxy, const string& port,
67 const string& auth, const time_t time) :
89 if (m.length() == 4 && isalnum(m[0]) && isalnum(m[1]) && isalnum(m[2]) && isalnum(m[3])) {
90 for (int i = 0; i < 4; i++)
91 _icao[i] = toupper(m[i]);
93 _data = loadData(_icao, proxy, port, auth, time);
95 _data = new char[m.length() + 2]; // make room for " \0"
96 strcpy(_data, m.c_str());
105 if (!scanPreambleDate())
111 if (!scanId() || !scanDate()) {
113 throw sg_io_exception("metar data bogus ", sg_location(_url));
120 while (scanVisibility()) ;
121 while (scanRwyVisRange()) ;
122 while (scanWeather()) ;
123 while (scanSkyCondition()) ;
126 while (scanSkyCondition()) ;
127 while (scanRunwayReport()) ;
131 while (scanColorState()) ;
133 while (scanRunwayReport()) ;
139 throw sg_io_exception("metar data incomplete ", sg_location(_url));
147 * Clears lists and maps to discourage access after destruction.
158 void SGMetar::useCurrentDate()
161 time_t now_sec = time(0);
162 #if defined( _MSC_VER ) || defined ( __MINGW32__ )
163 now = *gmtime(&now_sec);
165 gmtime_r(&now_sec, &now);
167 _year = now.tm_year + 1900;
168 _month = now.tm_mon + 1;
173 * If called with "KSFO" loads data from
175 * http://weather.noaa.gov/pub/data/observations/metar/stations/KSFO.TXT.
177 * Throws sg_io_exception on failure. Gives up after waiting longer than 10 seconds.
179 * @param id four-letter ICAO Metar station code, e.g. "KSFO".
180 * @param proxy proxy host (optional; default: "")
181 * @param port proxy port (optional; default: "80")
182 * @param auth proxy authorization information (optional; default: "")
183 * @return pointer to Metar data string, allocated by new char[].
184 * @see rfc2068.txt for proxy spec ("Proxy-Authorization")
186 char *SGMetar::loadData(const char *id, const string& proxy, const string& port,
187 const string& auth, time_t time)
189 const int buflen = 512;
190 char buf[2 * buflen];
192 string host = proxy.empty() ? "weather.noaa.gov" : proxy;
193 string path = "/pub/data/observations/metar/stations/";
195 path += string(id) + ".TXT";
196 _url = "http://weather.noaa.gov" + path;
198 SGSocket *sock = new SGSocket(host, port.empty() ? "80" : port, "tcp");
199 sock->set_timeout(10000);
200 if (!sock->open(SG_IO_OUT)) {
202 throw sg_io_exception("cannot connect to ", sg_location(host));
207 get += "http://weather.noaa.gov";
209 sprintf(buf, "%ld", time);
210 get += path + " HTTP/1.0\015\012X-Time: " + buf + "\015\012";
213 get += "Proxy-Authorization: " + auth + "\015\012";
216 sock->writestring(get.c_str());
221 while ((i = sock->readline(buf, buflen))) {
222 if (i <= 2 && isspace(buf[0]) && (!buf[1] || isspace(buf[1])))
224 if (!strncmp(buf, "X-MetarProxy: ", 13))
228 i = sock->readline(buf, buflen);
230 sock->readline(&buf[i], buflen);
239 throw sg_io_exception("no metar data available from ",
242 char *metar = new char[strlen(b) + 2]; // make room for " \0"
249 * Replace any number of subsequent spaces by just one space, and add
250 * a trailing space. This makes scanning for things like "ALL RWY" easier.
252 void SGMetar::normalizeData()
255 for (src = dest = _data; (*dest++ = *src++); )
256 while (*src == ' ' && src[1] == ' ')
258 for (dest--; isspace(*--dest); ) ;
264 // \d\d\d\d/\d\d/\d\d
265 bool SGMetar::scanPreambleDate()
268 int year, month, day;
269 if (!scanNumber(&m, &year, 4))
273 if (!scanNumber(&m, &month, 2))
277 if (!scanNumber(&m, &day, 2))
279 if (!scanBoundary(&m))
290 bool SGMetar::scanPreambleTime()
294 if (!scanNumber(&m, &hour, 2))
298 if (!scanNumber(&m, &minute, 2))
300 if (!scanBoundary(&m))
310 bool SGMetar::scanType()
312 if (strncmp(_m, "METAR ", 6) && strncmp(_m, "SPECI ", 6))
321 bool SGMetar::scanId()
324 for (int i = 0; i < 4; m++, i++)
325 if (!(isalpha(*m) || isdigit(*m)))
327 if (!scanBoundary(&m))
329 strncpy(_icao, _m, 4);
338 bool SGMetar::scanDate()
341 int day, hour, minute;
342 if (!scanNumber(&m, &day, 2))
344 if (!scanNumber(&m, &hour, 2))
346 if (!scanNumber(&m, &minute, 2))
350 if (!scanBoundary(&m))
361 // (NIL|AUTO|COR|RTD)
362 bool SGMetar::scanModifier()
366 if (!strncmp(m, "NIL", 3)) {
370 if (!strncmp(m, "AUTO", 4)) // automatically generated
372 else if (!strncmp(m, "COR", 3)) // manually corrected
374 else if (!strncmp(m, "RTD", 3)) // routine delayed
378 if (!scanBoundary(&m))
387 // (\d{3}|VRB)\d{1,3}(G\d{2,3})?(KT|KMH|MPS)
388 bool SGMetar::scanWind()
392 if (!strncmp(m, "VRB", 3))
394 else if (!scanNumber(&m, &dir, 3))
398 if (!scanNumber(&m, &i, 2, 3))
405 if (!scanNumber(&m, &i, 2, 3))
410 if (!strncmp(m, "KT", 2))
411 m += 2, factor = SG_KT_TO_MPS;
412 else if (!strncmp(m, "KMH", 3))
413 m += 3, factor = SG_KMH_TO_MPS;
414 else if (!strncmp(m, "KPH", 3)) // ??
415 m += 3, factor = SG_KMH_TO_MPS;
416 else if (!strncmp(m, "MPS", 3))
417 m += 3, factor = 1.0;
420 if (!scanBoundary(&m))
424 _wind_speed = speed * factor;
426 _gust_speed = gust * factor;
433 bool SGMetar::scanVariability()
437 if (!scanNumber(&m, &from, 3))
441 if (!scanNumber(&m, &to, 3))
443 if (!scanBoundary(&m))
446 _wind_range_from = from;
453 bool SGMetar::scanVisibility()
454 // TODO: if only directed vis are given, do still set min/max
456 if (!strncmp(_m, "//// ", 5)) { // spec compliant?
465 int modifier = SGMetarVisibility::EQUALS;
466 // \d{4}(N|NE|E|SE|S|SW|W|NW)?
467 if (scanNumber(&m, &i, 4)) {
472 else if (*m == 'N') {
480 } else if (*m == 'S') {
490 i = 50, modifier = SGMetarVisibility::LESS_THAN;
492 i++, modifier = SGMetarVisibility::GREATER_THAN;
495 // M?(\d{1,2}|\d{1,2}/\d{1,2}|\d{1,2} \d{1,2}/\d{1,2})(SM|KM)
498 m++, modifier = SGMetarVisibility::LESS_THAN;
500 if (!scanNumber(&m, &i, 1, 2))
506 if (!scanNumber(&m, &i, 1, 2))
509 } else if (*m == ' ') {
512 if (!scanNumber(&m, &i, 1, 2))
516 if (!scanNumber(&m, &denom, 1, 2))
518 distance += (double)i / denom;
521 if (!strncmp(m, "SM", 2))
522 distance *= SG_SM_TO_METER, m += 2;
523 else if (!strncmp(m, "KM", 2))
524 distance *= 1000, m += 2;
528 if (!scanBoundary(&m))
531 SGMetarVisibility *v;
533 v = &_dir_visibility[dir / 45];
534 else if (_min_visibility._distance == NaN)
535 v = &_min_visibility;
537 v = &_max_visibility;
539 v->_distance = distance;
540 v->_modifier = modifier;
548 // R\d\d[LCR]?/([PM]?\d{4}V)?[PM]?\d{4}(FT)?[DNU]?
549 bool SGMetar::scanRwyVisRange()
556 if (!scanNumber(&m, &i, 2))
558 if (*m == 'L' || *m == 'C' || *m == 'R')
562 strncpy(id, _m + 1, i = m - _m - 1);
570 m++, r._min_visibility._modifier = SGMetarVisibility::GREATER_THAN;
572 m++, r._min_visibility._modifier = SGMetarVisibility::LESS_THAN;
573 if (!scanNumber(&m, &from, 4))
578 m++, r._max_visibility._modifier = SGMetarVisibility::GREATER_THAN;
580 m++, r._max_visibility._modifier = SGMetarVisibility::LESS_THAN;
581 if (!scanNumber(&m, &to, 4))
586 if (!strncmp(m, "FT", 2)) {
587 from = int(from * SG_FEET_TO_METER);
588 to = int(to * SG_FEET_TO_METER);
591 r._min_visibility._distance = from;
592 r._max_visibility._distance = to;
594 if (*m == '/') // this is not in the spec!
597 m++, r._min_visibility._tendency = SGMetarVisibility::DECREASING;
599 m++, r._min_visibility._tendency = SGMetarVisibility::STABLE;
601 m++, r._min_visibility._tendency = SGMetarVisibility::INCREASING;
603 if (!scanBoundary(&m))
607 _runways[id]._min_visibility = r._min_visibility;
608 _runways[id]._max_visibility = r._max_visibility;
614 static const struct Token special[] = {
615 { "NSW", "no significant weather" },
616 { "VCSH", "showers in the vicinity" },
617 { "VCTS", "thunderstorm in the vicinity" },
622 static const struct Token description[] = {
623 { "SH", "showers of" },
624 { "TS", "thunderstorm with" },
625 { "BC", "patches of" },
627 { "DR", "low drifting" },
628 { "FZ", "freezing" },
635 static const struct Token phenomenon[] = {
638 { "GS", "small hail and/or snow pellets" },
639 { "IC", "ice crystals" },
640 { "PE", "ice pellets" },
642 { "SG", "snow grains" },
644 { "UP", "unknown precipitation" },
646 { "DU", "widespread dust" },
648 { "FGBR", "fog bank" },
653 { "VA", "volcanic ash" },
654 { "DS", "duststorm" },
655 { "FC", "funnel cloud/tornado waterspout" },
656 { "PO", "well-developed dust/sand whirls" },
658 { "SS", "sandstorm" },
659 { "UP", "unknown" }, // ... due to failed automatic acquisition
664 // (+|-|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}
665 bool SGMetar::scanWeather()
669 const struct Token *a;
670 if ((a = scanToken(&m, special))) {
671 if (!scanBoundary(&m))
673 _weather.push_back(a->text);
681 m++, pre = "light ", intensity = 1;
683 m++, pre = "heavy ", intensity = 3;
684 else if (!strncmp(m, "VC", 2))
685 m += 2, post = "in the vicinity ";
687 pre = "moderate ", intensity = 2;
690 for (i = 0; i < 3; i++) {
691 if (!(a = scanToken(&m, description)))
693 weather += string(a->text) + " ";
695 for (i = 0; i < 3; i++) {
696 if (!(a = scanToken(&m, phenomenon)))
698 weather += string(a->text) + " ";
699 if (!strcmp(a->id, "RA"))
701 else if (!strcmp(a->id, "HA"))
703 else if (!strcmp(a->id, "SN"))
706 if (!weather.length())
708 if (!scanBoundary(&m))
711 weather = pre + weather + post;
712 weather.erase(weather.length() - 1);
713 _weather.push_back(weather);
719 static const struct Token cloud_types[] = {
720 { "AC", "altocumulus" },
721 { "ACC", "altocumulus castellanus" },
722 { "ACSL", "altocumulus standing lenticular" },
723 { "AS", "altostratus" },
724 { "CB", "cumulonimbus" },
725 { "CBMAM", "cumulonimbus mammatus" },
726 { "CC", "cirrocumulus" },
727 { "CCSL", "cirrocumulus standing lenticular" },
729 { "CS", "cirrostratus" },
731 { "CUFRA", "cumulus fractus" },
732 { "NS", "nimbostratus" },
733 { "SAC", "stratoaltocumulus" }, // guessed
734 { "SC", "stratocumulus" },
735 { "SCSL", "stratocumulus standing lenticular" },
737 { "STFRA", "stratus fractus" },
738 { "TCU", "towering cumulus" },
743 // (FEW|SCT|BKN|OVC|SKC|CLR|CAVOK|VV)([0-9]{3}|///)?[:cloud_type:]?
744 bool SGMetar::scanSkyCondition()
750 if (!strncmp(m, "CLR", i = 3) // clear
751 || !strncmp(m, "SKC", i = 3) // sky clear
752 || !strncmp(m, "NSC", i = 3) // no significant clouds
753 || !strncmp(m, "CAVOK", i = 5)) { // ceiling and visibility OK (implies 9999)
755 if (!scanBoundary(&m))
760 _clouds.push_back(cl);
768 if (!strncmp(m, "VV", i = 2)) // vertical visibility
770 else if (!strncmp(m, "FEW", i = 3))
772 else if (!strncmp(m, "SCT", i = 3))
774 else if (!strncmp(m, "BKN", i = 3))
776 else if (!strncmp(m, "OVC", i = 3))
782 if (!strncmp(m, "///", 3)) // vis not measurable (e.g. because of heavy snowing)
784 else if (scanBoundary(&m)) {
786 return true; // ignore single OVC/BKN/...
787 } else if (!scanNumber(&m, &i, 3))
790 if (cl._coverage == -1) {
791 if (!scanBoundary(&m))
793 if (i == -1) // 'VV///'
794 _vert_visibility._modifier = SGMetarVisibility::NOGO;
796 _vert_visibility._distance = i * 100 * SG_FEET_TO_METER;
802 cl._altitude = i * 100 * SG_FEET_TO_METER;
804 const struct Token *a;
805 if ((a = scanToken(&m, cloud_types))) {
807 cl._type_long = a->text;
809 if (!scanBoundary(&m))
811 _clouds.push_back(cl);
818 // M?[0-9]{2}/(M?[0-9]{2})? (spec)
819 // (M?[0-9]{2}|XX)/(M?[0-9]{2}|XX)? (Namibia)
820 bool SGMetar::scanTemperature()
823 int sign = 1, temp, dew;
824 if (!strncmp(m, "XX/XX", 5)) { // not spec compliant!
826 return scanBoundary(&_m);
831 if (!scanNumber(&m, &temp, 2))
837 if (!scanBoundary(&m)) {
838 if (!strncmp(m, "XX", 2)) // not spec compliant!
844 if (!scanNumber(&m, &dew, 2))
847 if (!scanBoundary(&m))
859 double SGMetar::getRelHumidity() const
861 if (_temp == NaN || _dewp == NaN)
863 double dewp = pow(10.0, 7.5 * _dewp / (237.7 + _dewp));
864 double temp = pow(10.0, 7.5 * _temp / (237.7 + _temp));
865 return dewp * 100 / temp;
870 // [AQ]\d{2}(\d{2}|//) (Namibia)
871 bool SGMetar::scanPressure()
878 factor = SG_INHG_TO_PA / 100;
884 if (!scanNumber(&m, &press, 2))
887 if (!strncmp(m, "//", 2)) // not spec compliant!
889 else if (scanNumber(&m, &i, 2))
893 if (!scanBoundary(&m))
895 _pressure = press * factor;
902 static const char *runway_deposit[] = {
916 static const char *runway_deposit_extent[] = {
917 0, "1-10%", "11-25%", 0, 0, "26-50%", 0, 0, 0, "51-100%"
921 static const char *runway_friction[] = {
923 "poor braking action",
924 "poor/medium braking action",
925 "medium braking action",
926 "medium/good braking action",
927 "good braking action",
929 "friction: unreliable measurement"
933 // \d\d(CLRD|[\d/]{4})(\d\d|//)
934 bool SGMetar::scanRunwayReport()
941 if (!scanNumber(&m, &i, 2))
946 strcpy(id, "REP"); // repetition of previous report
949 id[0] = i / 10 + '0', id[1] = i % 10 + '0', id[2] = 'R', id[3] = '\0';
951 id[0] = i / 10 + '0', id[1] = i % 10 + '0', id[2] = '\0';
953 if (!strncmp(m, "CLRD", 4)) {
954 m += 4; // runway cleared
955 r._deposit_string = "cleared";
957 if (scanNumber(&m, &i, 1)) {
959 r._deposit_string = runway_deposit[i];
960 } else if (*m == '/')
965 if (*m == '1' || *m == '2' || *m == '5' || *m == '9') { // extent of deposit
966 r._extent = *m - '0';
967 r._extent_string = runway_deposit_extent[*m - '0'];
968 } else if (*m != '/')
973 if (!strncmp(m, "//", 2))
975 else if (!scanNumber(&m, &i, 2))
979 r._depth = 0.0005; // < 1 mm deep (let's say 0.5 :-)
980 else if (i > 0 && i <= 90)
981 r._depth = i / 1000.0; // i mm deep
982 else if (i >= 92 && i <= 98)
983 r._depth = (i - 90) / 20.0;
985 r._comment = "runway not in use";
986 else if (i == -1) // no depth given ("//")
992 if (m[0] == '/' && m[1] == '/')
994 else if (!scanNumber(&m, &i, 2))
996 if (i >= 1 && i < 90) {
997 r._friction = i / 100.0;
998 } else if ((i >= 91 && i <= 95) || i == 99) {
999 r._friction_string = runway_friction[i - 90];
1001 if (!scanBoundary(&m))
1004 _runways[id]._deposit = r._deposit;
1005 _runways[id]._deposit_string = r._deposit_string;
1006 _runways[id]._extent = r._extent;
1007 _runways[id]._extent_string = r._extent_string;
1008 _runways[id]._depth = r._depth;
1009 _runways[id]._friction = r._friction;
1010 _runways[id]._friction_string = r._friction_string;
1011 _runways[id]._comment = r._comment;
1018 // WS (ALL RWYS?|RWY ?\d\d[LCR]?)?
1019 bool SGMetar::scanWindShear()
1022 if (strncmp(m, "WS", 2))
1025 if (!scanBoundary(&m))
1028 if (!strncmp(m, "ALL", 3)) {
1030 if (!scanBoundary(&m))
1032 if (strncmp(m, "RWY", 3))
1037 if (!scanBoundary(&m))
1039 _runways["ALL"]._wind_shear = true;
1046 for (cnt = 0;; cnt++) { // ??
1047 if (strncmp(m, "RWY", 3))
1052 if (!scanNumber(&m, &i, 2))
1054 if (*m == 'L' || *m == 'C' || *m == 'R')
1056 strncpy(id, mm, i = m - mm);
1058 if (!scanBoundary(&m))
1060 _runways[id]._wind_shear = true;
1063 _runways["ALL"]._wind_shear = true;
1069 bool SGMetar::scanTrendForecast()
1072 if (strncmp(m, "NOSIG", 5))
1076 if (!scanBoundary(&m))
1083 // (BLU|WHT|GRN|YLO|AMB|RED)
1084 static const struct Token colors[] = {
1085 { "BLU", "Blue" }, // 2500 ft, 8.0 km
1086 { "WHT", "White" }, // 1500 ft, 5.0 km
1087 { "GRN", "Green" }, // 700 ft, 3.7 km
1088 { "YLO", "Yellow" }, // 300 ft, 1.6 km
1089 { "AMB", "Amber" }, // 200 ft, 0.8 km
1090 { "RED", "Red" }, // <200 ft, <0.8 km
1095 bool SGMetar::scanColorState()
1098 const struct Token *a;
1099 if (!(a = scanToken(&m, colors)))
1101 if (!scanBoundary(&m))
1103 //printf(Y"Code %s\n"N, a->text);
1109 bool SGMetar::scanRemark()
1111 if (strncmp(_m, "RMK", 3))
1114 if (!scanBoundary(&_m))
1118 if (!scanRunwayReport()) {
1119 while (*_m && !isspace(*_m))
1128 bool SGMetar::scanRemainder()
1131 if (!(strncmp(m, "NOSIG", 5))) {
1133 if (scanBoundary(&m))
1134 _m = m; //_comment.push_back("No significant tendency");
1137 if (!scanBoundary(&m))
1144 bool SGMetar::scanBoundary(char **s)
1146 if (**s && !isspace(**s))
1148 while (isspace(**s))
1154 int SGMetar::scanNumber(char **src, int *num, int min, int max)
1159 for (i = 0; i < min; i++) {
1163 *num = *num * 10 + *s++ - '0';
1165 for (; i < max && isdigit(*s); i++)
1166 *num = *num * 10 + *s++ - '0';
1172 // find longest match of str in list
1173 const struct Token *SGMetar::scanToken(char **str, const struct Token *list)
1175 const struct Token *longest = 0;
1176 int maxlen = 0, len;
1178 for (int i = 0; (s = list[i].id); i++) {
1180 if (!strncmp(s, *str, len) && len > maxlen) {
1190 void SGMetarCloud::set(double alt, int cov)
1198 void SGMetarVisibility::set(double dist, int dir, int mod, int tend)