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 host = proxy.empty() ? "weather.noaa.gov" : proxy;
194 string path = "/pub/data/observations/metar/stations/";
196 path += string(id) + ".TXT";
197 _url = "http://weather.noaa.gov" + path;
199 SGSocket *sock = new SGSocket(host, port.empty() ? "80" : port, "tcp");
200 sock->set_timeout(10000);
201 if (!sock->open(SG_IO_OUT)) {
203 throw sg_io_exception("cannot connect to ", sg_location(host));
208 get += "http://weather.noaa.gov";
210 sprintf(buf, "%ld", time);
211 get += path + " HTTP/1.0\015\012X-Time: " + buf + "\015\012";
214 get += "Proxy-Authorization: " + auth + "\015\012";
217 sock->writestring(get.c_str());
222 while ((i = sock->readline(buf, buflen))) {
223 if (i <= 2 && isspace(buf[0]) && (!buf[1] || isspace(buf[1])))
225 if (!strncmp(buf, "X-MetarProxy: ", 13))
229 i = sock->readline(buf, buflen);
231 sock->readline(&buf[i], buflen);
240 throw sg_io_exception("no metar data available from ",
243 char *metar = new char[strlen(b) + 2]; // make room for " \0"
250 * Replace any number of subsequent spaces by just one space, and add
251 * a trailing space. This makes scanning for things like "ALL RWY" easier.
253 void SGMetar::normalizeData()
256 for (src = dest = _data; (*dest++ = *src++); )
257 while (*src == ' ' && src[1] == ' ')
259 for (dest--; isspace(*--dest); ) ;
265 // \d\d\d\d/\d\d/\d\d
266 bool SGMetar::scanPreambleDate()
269 int year, month, day;
270 if (!scanNumber(&m, &year, 4))
274 if (!scanNumber(&m, &month, 2))
278 if (!scanNumber(&m, &day, 2))
280 if (!scanBoundary(&m))
291 bool SGMetar::scanPreambleTime()
295 if (!scanNumber(&m, &hour, 2))
299 if (!scanNumber(&m, &minute, 2))
301 if (!scanBoundary(&m))
311 bool SGMetar::scanType()
313 if (strncmp(_m, "METAR ", 6) && strncmp(_m, "SPECI ", 6))
322 bool SGMetar::scanId()
325 for (int i = 0; i < 4; m++, i++)
326 if (!(isalpha(*m) || isdigit(*m)))
328 if (!scanBoundary(&m))
330 strncpy(_icao, _m, 4);
339 bool SGMetar::scanDate()
342 int day, hour, minute;
343 if (!scanNumber(&m, &day, 2))
345 if (!scanNumber(&m, &hour, 2))
347 if (!scanNumber(&m, &minute, 2))
351 if (!scanBoundary(&m))
362 // (NIL|AUTO|COR|RTD)
363 bool SGMetar::scanModifier()
367 if (!strncmp(m, "NIL", 3)) {
371 if (!strncmp(m, "AUTO", 4)) // automatically generated
373 else if (!strncmp(m, "COR", 3)) // manually corrected
375 else if (!strncmp(m, "RTD", 3)) // routine delayed
379 if (!scanBoundary(&m))
388 // (\d{3}|VRB)\d{1,3}(G\d{2,3})?(KT|KMH|MPS)
389 bool SGMetar::scanWind()
393 if (!strncmp(m, "VRB", 3))
395 else if (!scanNumber(&m, &dir, 3))
399 if (!scanNumber(&m, &i, 2, 3))
406 if (!scanNumber(&m, &i, 2, 3))
411 if (!strncmp(m, "KT", 2))
412 m += 2, factor = SG_KT_TO_MPS;
413 else if (!strncmp(m, "KMH", 3))
414 m += 3, factor = SG_KMH_TO_MPS;
415 else if (!strncmp(m, "KPH", 3)) // ??
416 m += 3, factor = SG_KMH_TO_MPS;
417 else if (!strncmp(m, "MPS", 3))
418 m += 3, factor = 1.0;
421 if (!scanBoundary(&m))
425 _wind_speed = speed * factor;
427 _gust_speed = gust * factor;
434 bool SGMetar::scanVariability()
438 if (!scanNumber(&m, &from, 3))
442 if (!scanNumber(&m, &to, 3))
444 if (!scanBoundary(&m))
447 _wind_range_from = from;
454 bool SGMetar::scanVisibility()
455 // TODO: if only directed vis are given, do still set min/max
457 if (!strncmp(_m, "//// ", 5)) { // spec compliant?
466 int modifier = SGMetarVisibility::EQUALS;
467 // \d{4}(N|NE|E|SE|S|SW|W|NW)?
468 if (scanNumber(&m, &i, 4)) {
473 else if (*m == 'N') {
481 } else if (*m == 'S') {
491 i = 50, modifier = SGMetarVisibility::LESS_THAN;
493 i++, modifier = SGMetarVisibility::GREATER_THAN;
496 // 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, "//////", 6)) {
752 if (!scanBoundary(&m))
758 if (!strncmp(m, "CLR", i = 3) // clear
759 || !strncmp(m, "SKC", i = 3) // sky clear
760 || !strncmp(m, "NSC", i = 3) // no significant clouds
761 || !strncmp(m, "CAVOK", i = 5)) { // ceiling and visibility OK (implies 9999)
763 if (!scanBoundary(&m))
768 _clouds.push_back(cl);
776 if (!strncmp(m, "VV", i = 2)) // vertical visibility
778 else if (!strncmp(m, "FEW", i = 3))
780 else if (!strncmp(m, "SCT", i = 3))
782 else if (!strncmp(m, "BKN", i = 3))
784 else if (!strncmp(m, "OVC", i = 3))
790 if (!strncmp(m, "///", 3)) // vis not measurable (e.g. because of heavy snowing)
792 else if (scanBoundary(&m)) {
794 return true; // ignore single OVC/BKN/...
795 } else if (!scanNumber(&m, &i, 3))
798 if (cl._coverage == -1) {
799 if (!scanBoundary(&m))
801 if (i == -1) // 'VV///'
802 _vert_visibility._modifier = SGMetarVisibility::NOGO;
804 _vert_visibility._distance = i * 100 * SG_FEET_TO_METER;
810 cl._altitude = i * 100 * SG_FEET_TO_METER;
812 const struct Token *a;
813 if ((a = scanToken(&m, cloud_types))) {
815 cl._type_long = a->text;
817 if (!scanBoundary(&m))
819 _clouds.push_back(cl);
826 // M?[0-9]{2}/(M?[0-9]{2})? (spec)
827 // (M?[0-9]{2}|XX)/(M?[0-9]{2}|XX)? (Namibia)
828 bool SGMetar::scanTemperature()
831 int sign = 1, temp, dew;
832 if (!strncmp(m, "XX/XX", 5)) { // not spec compliant!
834 return scanBoundary(&_m);
839 if (!scanNumber(&m, &temp, 2))
845 if (!scanBoundary(&m)) {
846 if (!strncmp(m, "XX", 2)) // not spec compliant!
847 m += 2, sign = 0, dew = temp;
852 if (!scanNumber(&m, &dew, 2))
855 if (!scanBoundary(&m))
867 double SGMetar::getRelHumidity() const
869 if (_temp == NaN || _dewp == NaN)
871 double dewp = pow(10.0, 7.5 * _dewp / (237.7 + _dewp));
872 double temp = pow(10.0, 7.5 * _temp / (237.7 + _temp));
873 return dewp * 100 / temp;
878 // [AQ]\d{2}(\d{2}|//) (Namibia)
879 bool SGMetar::scanPressure()
886 factor = SG_INHG_TO_PA / 100;
892 if (!scanNumber(&m, &press, 2))
895 if (!strncmp(m, "//", 2)) // not spec compliant!
897 else if (scanNumber(&m, &i, 2))
901 if (!scanBoundary(&m))
903 _pressure = press * factor;
910 static const char *runway_deposit[] = {
924 static const char *runway_deposit_extent[] = {
925 0, "1-10%", "11-25%", 0, 0, "26-50%", 0, 0, 0, "51-100%"
929 static const char *runway_friction[] = {
931 "poor braking action",
932 "poor/medium braking action",
933 "medium braking action",
934 "medium/good braking action",
935 "good braking action",
937 "friction: unreliable measurement"
941 // \d\d(CLRD|[\d/]{4})(\d\d|//)
942 bool SGMetar::scanRunwayReport()
949 if (!scanNumber(&m, &i, 2))
954 strcpy(id, "REP"); // repetition of previous report
957 id[0] = i / 10 + '0', id[1] = i % 10 + '0', id[2] = 'R', id[3] = '\0';
959 id[0] = i / 10 + '0', id[1] = i % 10 + '0', id[2] = '\0';
961 if (!strncmp(m, "CLRD", 4)) {
962 m += 4; // runway cleared
963 r._deposit_string = "cleared";
965 if (scanNumber(&m, &i, 1)) {
967 r._deposit_string = runway_deposit[i];
968 } else if (*m == '/')
973 if (*m == '1' || *m == '2' || *m == '5' || *m == '9') { // extent of deposit
974 r._extent = *m - '0';
975 r._extent_string = runway_deposit_extent[*m - '0'];
976 } else if (*m != '/')
981 if (!strncmp(m, "//", 2))
983 else if (!scanNumber(&m, &i, 2))
987 r._depth = 0.0005; // < 1 mm deep (let's say 0.5 :-)
988 else if (i > 0 && i <= 90)
989 r._depth = i / 1000.0; // i mm deep
990 else if (i >= 92 && i <= 98)
991 r._depth = (i - 90) / 20.0;
993 r._comment = "runway not in use";
994 else if (i == -1) // no depth given ("//")
1000 if (m[0] == '/' && m[1] == '/')
1002 else if (!scanNumber(&m, &i, 2))
1004 if (i >= 1 && i < 90) {
1005 r._friction = i / 100.0;
1006 } else if ((i >= 91 && i <= 95) || i == 99) {
1007 r._friction_string = runway_friction[i - 90];
1009 if (!scanBoundary(&m))
1012 _runways[id]._deposit = r._deposit;
1013 _runways[id]._deposit_string = r._deposit_string;
1014 _runways[id]._extent = r._extent;
1015 _runways[id]._extent_string = r._extent_string;
1016 _runways[id]._depth = r._depth;
1017 _runways[id]._friction = r._friction;
1018 _runways[id]._friction_string = r._friction_string;
1019 _runways[id]._comment = r._comment;
1026 // WS (ALL RWYS?|RWY ?\d\d[LCR]?)?
1027 bool SGMetar::scanWindShear()
1030 if (strncmp(m, "WS", 2))
1033 if (!scanBoundary(&m))
1036 if (!strncmp(m, "ALL", 3)) {
1038 if (!scanBoundary(&m))
1040 if (strncmp(m, "RWY", 3))
1045 if (!scanBoundary(&m))
1047 _runways["ALL"]._wind_shear = true;
1054 for (cnt = 0;; cnt++) { // ??
1055 if (strncmp(m, "RWY", 3))
1060 if (!scanNumber(&m, &i, 2))
1062 if (*m == 'L' || *m == 'C' || *m == 'R')
1064 strncpy(id, mm, i = m - mm);
1066 if (!scanBoundary(&m))
1068 _runways[id]._wind_shear = true;
1071 _runways["ALL"]._wind_shear = true;
1077 bool SGMetar::scanTrendForecast()
1080 if (strncmp(m, "NOSIG", 5))
1084 if (!scanBoundary(&m))
1091 // (BLU|WHT|GRN|YLO|AMB|RED)
1092 static const struct Token colors[] = {
1093 { "BLU", "Blue" }, // 2500 ft, 8.0 km
1094 { "WHT", "White" }, // 1500 ft, 5.0 km
1095 { "GRN", "Green" }, // 700 ft, 3.7 km
1096 { "YLO", "Yellow" }, // 300 ft, 1.6 km
1097 { "AMB", "Amber" }, // 200 ft, 0.8 km
1098 { "RED", "Red" }, // <200 ft, <0.8 km
1103 bool SGMetar::scanColorState()
1106 const struct Token *a;
1107 if (!(a = scanToken(&m, colors)))
1109 if (!scanBoundary(&m))
1111 //printf(Y"Code %s\n"N, a->text);
1117 bool SGMetar::scanRemark()
1119 if (strncmp(_m, "RMK", 3))
1122 if (!scanBoundary(&_m))
1126 if (!scanRunwayReport()) {
1127 while (*_m && !isspace(*_m))
1136 bool SGMetar::scanRemainder()
1139 if (!(strncmp(m, "NOSIG", 5))) {
1141 if (scanBoundary(&m))
1142 _m = m; //_comment.push_back("No significant tendency");
1145 if (!scanBoundary(&m))
1152 bool SGMetar::scanBoundary(char **s)
1154 if (**s && !isspace(**s))
1156 while (isspace(**s))
1162 int SGMetar::scanNumber(char **src, int *num, int min, int max)
1167 for (i = 0; i < min; i++) {
1171 *num = *num * 10 + *s++ - '0';
1173 for (; i < max && isdigit(*s); i++)
1174 *num = *num * 10 + *s++ - '0';
1180 // find longest match of str in list
1181 const struct Token *SGMetar::scanToken(char **str, const struct Token *list)
1183 const struct Token *longest = 0;
1184 int maxlen = 0, len;
1186 for (int i = 0; (s = list[i].id); i++) {
1188 if (!strncmp(s, *str, len) && len > maxlen) {
1198 void SGMetarCloud::set(double alt, int cov)
1206 void SGMetarVisibility::set(double dist, int dir, int mod, int tend)