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);
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)
497 m++, modifier = SGMetarVisibility::LESS_THAN;
499 if (!scanNumber(&m, &i, 1, 2))
505 if (!scanNumber(&m, &i, 1, 2))
508 } else if (*m == ' ') {
511 if (!scanNumber(&m, &i, 1, 2))
515 if (!scanNumber(&m, &denom, 1, 2))
517 distance += (double)i / denom;
520 if (!strncmp(m, "SM", 2))
521 distance *= SG_SM_TO_METER, m += 2;
522 else if (!strncmp(m, "KM", 2))
523 distance *= 1000, m += 2;
527 if (!scanBoundary(&m))
530 SGMetarVisibility *v;
532 v = &_dir_visibility[dir / 45];
533 else if (_min_visibility._distance == NaN)
534 v = &_min_visibility;
536 v = &_max_visibility;
538 v->_distance = distance;
539 v->_modifier = modifier;
547 // R\d\d[LCR]?/([PM]?\d{4}V)?[PM]?\d{4}(FT)?[DNU]?
548 bool SGMetar::scanRwyVisRange()
555 if (!scanNumber(&m, &i, 2))
557 if (*m == 'L' || *m == 'C' || *m == 'R')
561 strncpy(id, _m + 1, i = m - _m - 1);
569 m++, r._min_visibility._modifier = SGMetarVisibility::GREATER_THAN;
571 m++, r._min_visibility._modifier = SGMetarVisibility::LESS_THAN;
572 if (!scanNumber(&m, &from, 4))
577 m++, r._max_visibility._modifier = SGMetarVisibility::GREATER_THAN;
579 m++, r._max_visibility._modifier = SGMetarVisibility::LESS_THAN;
580 if (!scanNumber(&m, &to, 4))
585 if (!strncmp(m, "FT", 2)) {
586 from = int(from * SG_FEET_TO_METER);
587 to = int(to * SG_FEET_TO_METER);
590 r._min_visibility._distance = from;
591 r._max_visibility._distance = to;
593 if (*m == '/') // this is not in the spec!
596 m++, r._min_visibility._tendency = SGMetarVisibility::DECREASING;
598 m++, r._min_visibility._tendency = SGMetarVisibility::STABLE;
600 m++, r._min_visibility._tendency = SGMetarVisibility::INCREASING;
602 if (!scanBoundary(&m))
606 _runways[id]._min_visibility = r._min_visibility;
607 _runways[id]._max_visibility = r._max_visibility;
613 static const struct Token special[] = {
614 { "NSW", "no significant weather" },
615 { "VCSH", "showers in the vicinity" },
616 { "VCTS", "thunderstorm in the vicinity" },
621 static const struct Token description[] = {
622 { "SH", "showers of" },
623 { "TS", "thunderstorm with" },
624 { "BC", "patches of" },
626 { "DR", "low drifting" },
627 { "FZ", "freezing" },
634 static const struct Token phenomenon[] = {
637 { "GS", "small hail and/or snow pellets" },
638 { "IC", "ice crystals" },
639 { "PE", "ice pellets" },
641 { "SG", "snow grains" },
643 { "UP", "unknown precipitation" },
645 { "DU", "widespread dust" },
647 { "FGBR", "fog bank" },
652 { "VA", "volcanic ash" },
653 { "DS", "duststorm" },
654 { "FC", "funnel cloud/tornado waterspout" },
655 { "PO", "well-developed dust/sand whirls" },
657 { "SS", "sandstorm" },
658 { "UP", "unknown" }, // ... due to failed automatic acquisition
663 // (+|-|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}
664 bool SGMetar::scanWeather()
668 const struct Token *a;
669 if ((a = scanToken(&m, special))) {
670 if (!scanBoundary(&m))
672 _weather.push_back(a->text);
680 m++, pre = "light ", intensity = 1;
682 m++, pre = "heavy ", intensity = 3;
683 else if (!strncmp(m, "VC", 2))
684 m += 2, post = "in the vicinity ";
686 pre = "moderate ", intensity = 2;
689 for (i = 0; i < 3; i++) {
690 if (!(a = scanToken(&m, description)))
692 weather += string(a->text) + " ";
694 for (i = 0; i < 3; i++) {
695 if (!(a = scanToken(&m, phenomenon)))
697 weather += string(a->text) + " ";
698 if (!strcmp(a->id, "RA"))
700 else if (!strcmp(a->id, "HA"))
702 else if (!strcmp(a->id, "SN"))
705 if (!weather.length())
707 if (!scanBoundary(&m))
710 weather = pre + weather + post;
711 weather.erase(weather.length() - 1);
712 _weather.push_back(weather);
718 static const struct Token cloud_types[] = {
719 { "AC", "altocumulus" },
720 { "ACC", "altocumulus castellanus" },
721 { "ACSL", "altocumulus standing lenticular" },
722 { "AS", "altostratus" },
723 { "CB", "cumulonimbus" },
724 { "CBMAM", "cumulonimbus mammatus" },
725 { "CC", "cirrocumulus" },
726 { "CCSL", "cirrocumulus standing lenticular" },
728 { "CS", "cirrostratus" },
730 { "CUFRA", "cumulus fractus" },
731 { "NS", "nimbostratus" },
732 { "SAC", "stratoaltocumulus" }, // guessed
733 { "SC", "stratocumulus" },
734 { "SCSL", "stratocumulus standing lenticular" },
736 { "STFRA", "stratus fractus" },
737 { "TCU", "towering cumulus" },
742 // (FEW|SCT|BKN|OVC|SKC|CLR|CAVOK|VV)([0-9]{3}|///)?[:cloud_type:]?
743 bool SGMetar::scanSkyCondition()
749 if (!strncmp(m, "//////", 6)) {
751 if (!scanBoundary(&m))
757 if (!strncmp(m, "CLR", i = 3) // clear
758 || !strncmp(m, "SKC", i = 3) // sky clear
759 || !strncmp(m, "NSC", i = 3) // no significant clouds
760 || !strncmp(m, "CAVOK", i = 5)) { // ceiling and visibility OK (implies 9999)
762 if (!scanBoundary(&m))
767 _clouds.push_back(cl);
775 if (!strncmp(m, "VV", i = 2)) // vertical visibility
777 else if (!strncmp(m, "FEW", i = 3))
779 else if (!strncmp(m, "SCT", i = 3))
781 else if (!strncmp(m, "BKN", i = 3))
783 else if (!strncmp(m, "OVC", i = 3))
789 if (!strncmp(m, "///", 3)) // vis not measurable (e.g. because of heavy snowing)
791 else if (scanBoundary(&m)) {
793 return true; // ignore single OVC/BKN/...
794 } else if (!scanNumber(&m, &i, 3))
797 if (cl._coverage == -1) {
798 if (!scanBoundary(&m))
800 if (i == -1) // 'VV///'
801 _vert_visibility._modifier = SGMetarVisibility::NOGO;
803 _vert_visibility._distance = i * 100 * SG_FEET_TO_METER;
809 cl._altitude = i * 100 * SG_FEET_TO_METER;
811 const struct Token *a;
812 if ((a = scanToken(&m, cloud_types))) {
814 cl._type_long = a->text;
816 if (!scanBoundary(&m))
818 _clouds.push_back(cl);
825 // M?[0-9]{2}/(M?[0-9]{2})? (spec)
826 // (M?[0-9]{2}|XX)/(M?[0-9]{2}|XX)? (Namibia)
827 bool SGMetar::scanTemperature()
830 int sign = 1, temp, dew;
831 if (!strncmp(m, "XX/XX", 5)) { // not spec compliant!
833 return scanBoundary(&_m);
838 if (!scanNumber(&m, &temp, 2))
844 if (!scanBoundary(&m)) {
845 if (!strncmp(m, "XX", 2)) // not spec compliant!
846 m += 2, sign = 0, dew = temp;
851 if (!scanNumber(&m, &dew, 2))
854 if (!scanBoundary(&m))
866 double SGMetar::getRelHumidity() const
868 if (_temp == NaN || _dewp == NaN)
870 double dewp = pow(10.0, 7.5 * _dewp / (237.7 + _dewp));
871 double temp = pow(10.0, 7.5 * _temp / (237.7 + _temp));
872 return dewp * 100 / temp;
877 // [AQ]\d{2}(\d{2}|//) (Namibia)
878 bool SGMetar::scanPressure()
885 factor = SG_INHG_TO_PA / 100;
891 if (!scanNumber(&m, &press, 2))
894 if (!strncmp(m, "//", 2)) // not spec compliant!
896 else if (scanNumber(&m, &i, 2))
900 if (!scanBoundary(&m))
902 _pressure = press * factor;
909 static const char *runway_deposit[] = {
923 static const char *runway_deposit_extent[] = {
924 0, "1-10%", "11-25%", 0, 0, "26-50%", 0, 0, 0, "51-100%"
928 static const char *runway_friction[] = {
930 "poor braking action",
931 "poor/medium braking action",
932 "medium braking action",
933 "medium/good braking action",
934 "good braking action",
936 "friction: unreliable measurement"
940 // \d\d(CLRD|[\d/]{4})(\d\d|//)
941 bool SGMetar::scanRunwayReport()
948 if (!scanNumber(&m, &i, 2))
953 strcpy(id, "REP"); // repetition of previous report
956 id[0] = i / 10 + '0', id[1] = i % 10 + '0', id[2] = 'R', id[3] = '\0';
958 id[0] = i / 10 + '0', id[1] = i % 10 + '0', id[2] = '\0';
960 if (!strncmp(m, "CLRD", 4)) {
961 m += 4; // runway cleared
962 r._deposit_string = "cleared";
964 if (scanNumber(&m, &i, 1)) {
966 r._deposit_string = runway_deposit[i];
967 } else if (*m == '/')
972 if (*m == '1' || *m == '2' || *m == '5' || *m == '9') { // extent of deposit
973 r._extent = *m - '0';
974 r._extent_string = runway_deposit_extent[*m - '0'];
975 } else if (*m != '/')
980 if (!strncmp(m, "//", 2))
982 else if (!scanNumber(&m, &i, 2))
986 r._depth = 0.0005; // < 1 mm deep (let's say 0.5 :-)
987 else if (i > 0 && i <= 90)
988 r._depth = i / 1000.0; // i mm deep
989 else if (i >= 92 && i <= 98)
990 r._depth = (i - 90) / 20.0;
992 r._comment = "runway not in use";
993 else if (i == -1) // no depth given ("//")
999 if (m[0] == '/' && m[1] == '/')
1001 else if (!scanNumber(&m, &i, 2))
1003 if (i >= 1 && i < 90) {
1004 r._friction = i / 100.0;
1005 } else if ((i >= 91 && i <= 95) || i == 99) {
1006 r._friction_string = runway_friction[i - 90];
1008 if (!scanBoundary(&m))
1011 _runways[id]._deposit = r._deposit;
1012 _runways[id]._deposit_string = r._deposit_string;
1013 _runways[id]._extent = r._extent;
1014 _runways[id]._extent_string = r._extent_string;
1015 _runways[id]._depth = r._depth;
1016 _runways[id]._friction = r._friction;
1017 _runways[id]._friction_string = r._friction_string;
1018 _runways[id]._comment = r._comment;
1025 // WS (ALL RWYS?|RWY ?\d\d[LCR]?)?
1026 bool SGMetar::scanWindShear()
1029 if (strncmp(m, "WS", 2))
1032 if (!scanBoundary(&m))
1035 if (!strncmp(m, "ALL", 3)) {
1037 if (!scanBoundary(&m))
1039 if (strncmp(m, "RWY", 3))
1044 if (!scanBoundary(&m))
1046 _runways["ALL"]._wind_shear = true;
1053 for (cnt = 0;; cnt++) { // ??
1054 if (strncmp(m, "RWY", 3))
1059 if (!scanNumber(&m, &i, 2))
1061 if (*m == 'L' || *m == 'C' || *m == 'R')
1063 strncpy(id, mm, i = m - mm);
1065 if (!scanBoundary(&m))
1067 _runways[id]._wind_shear = true;
1070 _runways["ALL"]._wind_shear = true;
1076 bool SGMetar::scanTrendForecast()
1079 if (strncmp(m, "NOSIG", 5))
1083 if (!scanBoundary(&m))
1090 // (BLU|WHT|GRN|YLO|AMB|RED)
1091 static const struct Token colors[] = {
1092 { "BLU", "Blue" }, // 2500 ft, 8.0 km
1093 { "WHT", "White" }, // 1500 ft, 5.0 km
1094 { "GRN", "Green" }, // 700 ft, 3.7 km
1095 { "YLO", "Yellow" }, // 300 ft, 1.6 km
1096 { "AMB", "Amber" }, // 200 ft, 0.8 km
1097 { "RED", "Red" }, // <200 ft, <0.8 km
1102 bool SGMetar::scanColorState()
1105 const struct Token *a;
1106 if (!(a = scanToken(&m, colors)))
1108 if (!scanBoundary(&m))
1110 //printf(Y"Code %s\n"N, a->text);
1116 bool SGMetar::scanRemark()
1118 if (strncmp(_m, "RMK", 3))
1121 if (!scanBoundary(&_m))
1125 if (!scanRunwayReport()) {
1126 while (*_m && !isspace(*_m))
1135 bool SGMetar::scanRemainder()
1138 if (!(strncmp(m, "NOSIG", 5))) {
1140 if (scanBoundary(&m))
1141 _m = m; //_comment.push_back("No significant tendency");
1144 if (!scanBoundary(&m))
1151 bool SGMetar::scanBoundary(char **s)
1153 if (**s && !isspace(**s))
1155 while (isspace(**s))
1161 int SGMetar::scanNumber(char **src, int *num, int min, int max)
1166 for (i = 0; i < min; i++) {
1170 *num = *num * 10 + *s++ - '0';
1172 for (; i < max && isdigit(*s); i++)
1173 *num = *num * 10 + *s++ - '0';
1179 // find longest match of str in list
1180 const struct Token *SGMetar::scanToken(char **str, const struct Token *list)
1182 const struct Token *longest = 0;
1183 int maxlen = 0, len;
1185 for (int i = 0; (s = list[i].id); i++) {
1187 if (!strncmp(s, *str, len) && len > maxlen) {
1197 void SGMetarCloud::set(double alt, int cov)
1205 void SGMetarVisibility::set(double dist, int dir, int mod, int tend)