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;
675 if ((a = scanToken(&m, special))) {
676 if (!scanBoundary(&m))
678 _weather.push_back(a->text);
686 m++, pre = "light ", w.intensity = LIGHT;
688 m++, pre = "heavy ", w.intensity = HEAVY;
689 else if (!strncmp(m, "VC", 2))
690 m += 2, post = "in the vicinity ", w.vincinity=true;
692 pre = "moderate ", w.intensity = MODERATE;
695 for (i = 0; i < 3; i++) {
696 if (!(a = scanToken(&m, description)))
698 w.descriptions.push_back(a->id);
699 weather += string(a->text) + " ";
702 for (i = 0; i < 3; i++) {
703 if (!(a = scanToken(&m, phenomenon)))
705 w.phenomena.push_back(a->id);
706 weather += string(a->text) + " ";
707 if (!strcmp(a->id, "RA"))
709 else if (!strcmp(a->id, "HA"))
711 else if (!strcmp(a->id, "SN"))
714 if (!weather.length())
716 if (!scanBoundary(&m))
719 weather = pre + weather + post;
720 weather.erase(weather.length() - 1);
721 _weather.push_back(weather);
722 if( w.phenomena.size() > 0 )
723 _weather2.push_back( w );
729 static const struct Token cloud_types[] = {
730 { "AC", "altocumulus" },
731 { "ACC", "altocumulus castellanus" },
732 { "ACSL", "altocumulus standing lenticular" },
733 { "AS", "altostratus" },
734 { "CB", "cumulonimbus" },
735 { "CBMAM", "cumulonimbus mammatus" },
736 { "CC", "cirrocumulus" },
737 { "CCSL", "cirrocumulus standing lenticular" },
739 { "CS", "cirrostratus" },
741 { "CUFRA", "cumulus fractus" },
742 { "NS", "nimbostratus" },
743 { "SAC", "stratoaltocumulus" }, // guessed
744 { "SC", "stratocumulus" },
745 { "SCSL", "stratocumulus standing lenticular" },
747 { "STFRA", "stratus fractus" },
748 { "TCU", "towering cumulus" },
753 // (FEW|SCT|BKN|OVC|SKC|CLR|CAVOK|VV)([0-9]{3}|///)?[:cloud_type:]?
754 bool SGMetar::scanSkyCondition()
760 if (!strncmp(m, "//////", 6)) {
762 if (!scanBoundary(&m))
768 if (!strncmp(m, "CLR", i = 3) // clear
769 || !strncmp(m, "SKC", i = 3) // sky clear
770 || !strncmp(m, "NSC", i = 3) // no significant clouds
771 || !strncmp(m, "CAVOK", i = 5)) { // ceiling and visibility OK (implies 9999)
773 if (!scanBoundary(&m))
777 cl._coverage = SGMetarCloud::COVERAGE_CLEAR;
778 _clouds.push_back(cl);
786 if (!strncmp(m, "VV", i = 2)) // vertical visibility
788 else if (!strncmp(m, "FEW", i = 3))
789 cl._coverage = SGMetarCloud::COVERAGE_FEW;
790 else if (!strncmp(m, "SCT", i = 3))
791 cl._coverage = SGMetarCloud::COVERAGE_SCATTERED;
792 else if (!strncmp(m, "BKN", i = 3))
793 cl._coverage = SGMetarCloud::COVERAGE_BROKEN;
794 else if (!strncmp(m, "OVC", i = 3))
795 cl._coverage = SGMetarCloud::COVERAGE_OVERCAST;
800 if (!strncmp(m, "///", 3)) // vis not measurable (e.g. because of heavy snowing)
802 else if (scanBoundary(&m)) {
804 return true; // ignore single OVC/BKN/...
805 } else if (!scanNumber(&m, &i, 3))
808 if (cl._coverage == SGMetarCloud::COVERAGE_NIL) {
809 if (!scanBoundary(&m))
811 if (i == -1) // 'VV///'
812 _vert_visibility._modifier = SGMetarVisibility::NOGO;
814 _vert_visibility._distance = i * 100 * SG_FEET_TO_METER;
820 cl._altitude = i * 100 * SG_FEET_TO_METER;
822 const struct Token *a;
823 if ((a = scanToken(&m, cloud_types))) {
825 cl._type_long = a->text;
827 if (!scanBoundary(&m))
829 _clouds.push_back(cl);
836 // M?[0-9]{2}/(M?[0-9]{2})? (spec)
837 // (M?[0-9]{2}|XX)/(M?[0-9]{2}|XX)? (Namibia)
838 bool SGMetar::scanTemperature()
841 int sign = 1, temp, dew;
842 if (!strncmp(m, "XX/XX", 5)) { // not spec compliant!
844 return scanBoundary(&_m);
849 if (!scanNumber(&m, &temp, 2))
855 if (!scanBoundary(&m)) {
856 if (!strncmp(m, "XX", 2)) // not spec compliant!
857 m += 2, sign = 0, dew = temp;
862 if (!scanNumber(&m, &dew, 2))
865 if (!scanBoundary(&m))
877 double SGMetar::getRelHumidity() const
879 if (_temp == NaN || _dewp == NaN)
881 double dewp = pow(10.0, 7.5 * _dewp / (237.7 + _dewp));
882 double temp = pow(10.0, 7.5 * _temp / (237.7 + _temp));
883 return dewp * 100 / temp;
888 // [AQ]\d{2}(\d{2}|//) (Namibia)
889 bool SGMetar::scanPressure()
896 factor = SG_INHG_TO_PA / 100;
902 if (!scanNumber(&m, &press, 2))
905 if (!strncmp(m, "//", 2)) // not spec compliant!
907 else if (scanNumber(&m, &i, 2))
911 if (!scanBoundary(&m))
913 _pressure = press * factor;
920 static const char *runway_deposit[] = {
934 static const char *runway_deposit_extent[] = {
935 0, "1-10%", "11-25%", 0, 0, "26-50%", 0, 0, 0, "51-100%"
939 static const char *runway_friction[] = {
941 "poor braking action",
942 "poor/medium braking action",
943 "medium braking action",
944 "medium/good braking action",
945 "good braking action",
947 "friction: unreliable measurement"
951 // \d\d(CLRD|[\d/]{4})(\d\d|//)
952 bool SGMetar::scanRunwayReport()
959 if (!scanNumber(&m, &i, 2))
964 strcpy(id, "REP"); // repetition of previous report
967 id[0] = i / 10 + '0', id[1] = i % 10 + '0', id[2] = 'R', id[3] = '\0';
969 id[0] = i / 10 + '0', id[1] = i % 10 + '0', id[2] = '\0';
971 if (!strncmp(m, "CLRD", 4)) {
972 m += 4; // runway cleared
973 r._deposit_string = "cleared";
975 if (scanNumber(&m, &i, 1)) {
977 r._deposit_string = runway_deposit[i];
978 } else if (*m == '/')
983 if (*m == '1' || *m == '2' || *m == '5' || *m == '9') { // extent of deposit
984 r._extent = *m - '0';
985 r._extent_string = runway_deposit_extent[*m - '0'];
986 } else if (*m != '/')
991 if (!strncmp(m, "//", 2))
993 else if (!scanNumber(&m, &i, 2))
997 r._depth = 0.0005; // < 1 mm deep (let's say 0.5 :-)
998 else if (i > 0 && i <= 90)
999 r._depth = i / 1000.0; // i mm deep
1000 else if (i >= 92 && i <= 98)
1001 r._depth = (i - 90) / 20.0;
1003 r._comment = "runway not in use";
1004 else if (i == -1) // no depth given ("//")
1010 if (m[0] == '/' && m[1] == '/')
1012 else if (!scanNumber(&m, &i, 2))
1014 if (i >= 1 && i < 90) {
1015 r._friction = i / 100.0;
1016 } else if ((i >= 91 && i <= 95) || i == 99) {
1017 r._friction_string = runway_friction[i - 90];
1019 if (!scanBoundary(&m))
1022 _runways[id]._deposit = r._deposit;
1023 _runways[id]._deposit_string = r._deposit_string;
1024 _runways[id]._extent = r._extent;
1025 _runways[id]._extent_string = r._extent_string;
1026 _runways[id]._depth = r._depth;
1027 _runways[id]._friction = r._friction;
1028 _runways[id]._friction_string = r._friction_string;
1029 _runways[id]._comment = r._comment;
1036 // WS (ALL RWYS?|RWY ?\d\d[LCR]?)?
1037 bool SGMetar::scanWindShear()
1040 if (strncmp(m, "WS", 2))
1043 if (!scanBoundary(&m))
1046 if (!strncmp(m, "ALL", 3)) {
1048 if (!scanBoundary(&m))
1050 if (strncmp(m, "RWY", 3))
1055 if (!scanBoundary(&m))
1057 _runways["ALL"]._wind_shear = true;
1064 for (cnt = 0;; cnt++) { // ??
1065 if (strncmp(m, "RWY", 3))
1070 if (!scanNumber(&m, &i, 2))
1072 if (*m == 'L' || *m == 'C' || *m == 'R')
1074 strncpy(id, mm, i = m - mm);
1076 if (!scanBoundary(&m))
1078 _runways[id]._wind_shear = true;
1081 _runways["ALL"]._wind_shear = true;
1087 bool SGMetar::scanTrendForecast()
1090 if (strncmp(m, "NOSIG", 5))
1094 if (!scanBoundary(&m))
1101 // (BLU|WHT|GRN|YLO|AMB|RED)
1102 static const struct Token colors[] = {
1103 { "BLU", "Blue" }, // 2500 ft, 8.0 km
1104 { "WHT", "White" }, // 1500 ft, 5.0 km
1105 { "GRN", "Green" }, // 700 ft, 3.7 km
1106 { "YLO", "Yellow" }, // 300 ft, 1.6 km
1107 { "AMB", "Amber" }, // 200 ft, 0.8 km
1108 { "RED", "Red" }, // <200 ft, <0.8 km
1113 bool SGMetar::scanColorState()
1116 const struct Token *a;
1117 if (!(a = scanToken(&m, colors)))
1119 if (!scanBoundary(&m))
1121 //printf(Y"Code %s\n"N, a->text);
1127 bool SGMetar::scanRemark()
1129 if (strncmp(_m, "RMK", 3))
1132 if (!scanBoundary(&_m))
1136 if (!scanRunwayReport()) {
1137 while (*_m && !isspace(*_m))
1146 bool SGMetar::scanRemainder()
1149 if (!(strncmp(m, "NOSIG", 5))) {
1151 if (scanBoundary(&m))
1152 _m = m; //_comment.push_back("No significant tendency");
1155 if (!scanBoundary(&m))
1162 bool SGMetar::scanBoundary(char **s)
1164 if (**s && !isspace(**s))
1166 while (isspace(**s))
1172 int SGMetar::scanNumber(char **src, int *num, int min, int max)
1177 for (i = 0; i < min; i++) {
1181 *num = *num * 10 + *s++ - '0';
1183 for (; i < max && isdigit(*s); i++)
1184 *num = *num * 10 + *s++ - '0';
1190 // find longest match of str in list
1191 const struct Token *SGMetar::scanToken(char **str, const struct Token *list)
1193 const struct Token *longest = 0;
1194 int maxlen = 0, len;
1196 for (int i = 0; (s = list[i].id); i++) {
1198 if (!strncmp(s, *str, len) && len > maxlen) {
1208 void SGMetarCloud::set(double alt, Coverage cov)
1216 void SGMetarVisibility::set(double dist, int dir, int mod, int tend)