Changed xoap parsing method to xpath, in preparation to include forecast data
[monky] / src / weather.c
1 /*
2  * Conky, a system monitor, based on torsmo
3  *
4  * Please see COPYING for details
5  *
6  * Copyright (c) 2005-2009 Brenden Matthews, Philip Kovacs, et. al.
7  *      (see AUTHORS)
8  * All rights reserved.
9  *
10  * This program is free software: you can redistribute it and/or modify
11  * it under the terms of the GNU General Public License as published by
12  * the Free Software Foundation, either version 3 of the License, or
13  * (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  * GNU General Public License for more details.
19  * You should have received a copy of the GNU General Public License
20  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
21  *
22  */
23
24 /*
25  * TODO: Add weather forecast info from weather.com
26  *
27  */
28
29 #include "conky.h"
30 #include "logging.h"
31 #include "weather.h"
32 #include "temphelper.h"
33 #include "ccurl_thread.h"
34 #include <time.h>
35 #include <ctype.h>
36 #ifdef MATH
37 #include <math.h>
38 #endif /* MATH */
39 #ifdef XOAP
40 #include <libxml/parser.h>
41 #include <libxml/xpath.h>
42
43 /* Xpath expressions for XOAP xml parsing */
44 #define NUM_XPATH_EXPRESSIONS 7
45 const char *xpath_expression[NUM_XPATH_EXPRESSIONS] = {
46         "/weather/cc/lsup", "/weather/cc/tmp", "/weather/cc/t",
47         "/weather/cc/bar/r", "/weather/cc/wind/s", "/weather/cc/wind/d",
48         "/weather/cc/hmid"
49 };
50 #endif /* XOAP */
51
52 /* Possible sky conditions */
53 #define NUM_CC_CODES 6
54 const char *CC_CODES[NUM_CC_CODES] = {
55         "SKC", "CLR", "FEW", "SCT", "BKN", "OVC"
56 };
57
58 /* Possible weather modifiers */
59 #define NUM_WM_CODES 9
60 const char *WM_CODES[NUM_WM_CODES] = {
61         "VC", "MI", "BC", "PR", "TS", "BL",
62         "SH", "DR", "FZ"
63 };
64
65 /* Possible weather conditions */
66 #define NUM_WC_CODES 17
67 const char *WC_CODES[NUM_WC_CODES] = {
68         "DZ", "RA", "GR", "GS", "SN", "SG",
69         "FG", "HZ", "FU", "BR", "DU", "SA",
70         "FC", "PO", "SQ", "SS", "DS"
71 };
72
73 static ccurl_location_t *locations_head = 0;
74
75 void weather_free_info(void)
76 {
77         ccurl_free_locations(&locations_head);
78 }
79
80 int rel_humidity(int dew_point, int air) {
81         const float a = 17.27f;
82         const float b = 237.7f;
83
84         float diff = a*(dew_point/(b+dew_point)-air/(b+air));
85 #ifdef MATH
86         return (int)(100.f*expf(diff));
87 #else
88         return (int)(16.666667163372f*(6.f+diff*(6.f+diff*(3.f+diff))));
89 #endif /* MATH */
90 }
91
92 #ifdef XOAP
93 static void parse_cc(PWEATHER *res, xmlXPathContextPtr xpathCtx)
94 {
95         int i;
96         char *content;
97         xmlXPathObjectPtr xpathObj;
98
99         for (i = 0; i < NUM_XPATH_EXPRESSIONS; i++) {
100           xpathObj = xmlXPathEvalExpression((xmlChar *)xpath_expression[i], xpathCtx);
101                 if ((xpathObj != NULL) && (xpathObj->nodesetval->nodeTab[0]->type == XML_ELEMENT_NODE)) {
102                   content = (char *)xmlNodeGetContent(xpathObj->nodesetval->nodeTab[0]);
103                   switch(i) {
104                        case 0:
105                             strncpy(res->lastupd, content, 31);
106                        break;
107                        case 1:
108                             res->temp = atoi(content);
109                        break;
110                        case 2:
111                             if(res->xoap_t[0] == '\0') {
112                                 strncpy(res->xoap_t, content, 31);
113                                 }
114                        break;
115                        case 3:
116                             res->bar = atoi(content);
117                        break;
118                        case 4:
119                             res->wind_s = atoi(content);
120                        break;
121                        case 5:
122                             if (isdigit((char)content[0])) {
123                                 res->wind_d = atoi(content);
124                             }
125                             break;
126                        case 6:
127                             res->hmid = atoi(content);
128                   }
129                   xmlFree(content);
130                 }
131                 xmlXPathFreeObject(xpathObj);
132         }
133         return;
134 }
135
136 static void parse_weather_xml(PWEATHER *res, const char *data)
137 {
138         xmlDocPtr doc;
139         xmlXPathContextPtr xpathCtx;
140
141         if (!(doc = xmlReadMemory(data, strlen(data), "", NULL, 0))) {
142                 ERR("weather: can't read xml data");
143                 return;
144         }
145
146         xpathCtx = xmlXPathNewContext(doc);
147         if(xpathCtx == NULL) {
148                 ERR("weather: unable to create new XPath context");
149                 xmlFreeDoc(doc);
150                 return;
151         }
152
153         parse_cc(res, xpathCtx);
154         xmlXPathFreeContext(xpathCtx);
155         xmlFreeDoc(doc);
156         return;
157 }
158 #endif /* XOAP */
159
160 /*
161  * Horrible hack to avoid using regexes
162  *
163  */
164
165 static inline void parse_token(PWEATHER *res, char *token) {
166
167         int i;
168         char s_tmp[64];
169
170         switch (strlen(token)) {
171
172                 //Check all tokens 2 chars long
173                 case 2:
174
175                         //Check if token is a weather condition
176                         for (i=0; i<2; i++) {
177                                 if (!isalpha(token[i])) break;
178                         }
179                         if (i==2) {
180                                 for(i=0; i<NUM_WC_CODES; i++) {
181                                         if (!strncmp(token, WC_CODES[i], 2)) {
182                                                 res->wc=i+1;
183                                                 break;
184                                         }
185                                 }
186                                 return;
187                         }
188
189                         //Check for CB
190                         if (!strcmp(token, "CB")) {
191                                 res->cc = 8;
192                                 return;
193                         }
194
195                         break;
196
197                         //Check all tokens 3 chars long
198                 case 3:
199
200                         //Check if token is a modified weather condition
201                         if ((token[0] == '+') || (token[0] == '-')) {
202                                 for (i=1; i<3; i++) {
203                                         if (!isalpha(token[i])) break;
204                                 }
205                                 if (i==3) {
206                                         for(i=0; i<NUM_WC_CODES; i++) {
207                                                 if (!strncmp(&token[1], WC_CODES[i], 2)) {
208                                                         res->wc=i+1;
209                                                         break;
210                                                 }
211                                         }
212                                         return;
213                                 }
214                         }
215
216                         //Check for NCD or NSC
217                         if ((!strcmp(token, "NCD")) || (!strcmp(token, "NSC"))) {
218                                 res->cc = 1;
219                                 return;
220                         }
221
222                         //Check for TCU
223                         if (!strcmp(token, "TCU")) {
224                                 res->cc = 7;
225                                 return;
226                         }
227
228                         break;
229
230                         //Check all tokens 4 chars long
231                 case 4:
232
233                         //Check if token is a modified weather condition
234                         for(i=0; i<NUM_WM_CODES; i++) {
235                                 if (!strncmp(token, WM_CODES[i], 2)) {
236                                         for(i=0; i<NUM_WC_CODES; i++) {
237                                                 if (!strncmp(&token[2], WC_CODES[i], 2)) {
238                                                         res->wc=i+1;
239                                                         return;
240                                                 }
241                                         }
242                                         break;
243                                 }
244                         }
245
246                         break;
247
248                         //Check all tokens 5 chars long
249                 case 5:
250
251                         //Check for CAVOK
252                         if (!strcmp(token, "CAVOK")) {
253                                 res->cc = 1;
254                                 return;
255                         }
256
257                         //Check if token is the temperature
258                         for (i=0; i<2; i++) {
259                                 if (!isdigit(token[i])) break;
260                         }
261                         if ((i==2) && (token[2] == '/')) {
262                                 for (i=3; i<5; i++) {
263                                         if (!isdigit(token[i])) break;
264                                 }
265                                 if (i==5) {
266                                         //First 2 digits gives the air temperature
267                                         res->temp=atoi(token);
268
269                                         //4th and 5th digits gives the dew point temperature
270                                         res->dew=atoi(&token[3]);
271
272                                         //Compute humidity
273                                         res->hmid = rel_humidity(res->dew, res->temp);
274
275                                         return;
276                                 }
277                         }
278
279                         //Check if token is the pressure
280                         if ((token[0] == 'Q') || (token[0] == 'A')) {
281                                 for (i=1; i<5; i++) {
282                                         if (!isdigit(token[i])) break;
283                                 }
284                                 if (i==5) {
285                                         if (token[0] == 'A') {
286                                                 //Convert inches of mercury to mbar
287                                                 res->bar = (int)(atoi(&token[1])*0.338637526f);
288                                                 return;
289                                         }
290
291                                         //Last 4 digits is pressure im mbar
292                                         res->bar = atoi(&token[1]);
293                                         return;
294                                 }
295                         }
296
297                         //Check if token is a modified weather condition
298                         if ((token[0] == '+') || (token[0] == '-')) {
299                                 for(i=0; i<NUM_WM_CODES; i++) {
300                                         if (!strncmp(&token[1], WM_CODES[i], 2)) {
301                                                 for(i=0; i<NUM_WC_CODES; i++) {
302                                                         if (!strncmp(&token[3], WC_CODES[i], 2)) {
303                                                                 res->wc=i+1;
304                                                                 return;
305                                                         }
306                                                 }
307                                                 break;
308                                         }
309                                 }
310                         }
311                         break;
312
313                         //Check all tokens 6 chars long
314                 case 6:
315
316                         //Check if token is the cloud cover
317                         for (i=0; i<3; i++) {
318                                 if (!isalpha(token[i])) break;
319                         }
320                         if (i==3) {
321                                 for (i=3; i<6; i++) {
322                                         if (!isdigit(token[i])) break;
323                                 }
324                                 if (i==6) {
325                                         //Check if first 3 digits gives the cloud cover condition
326                                         for(i=0; i<NUM_CC_CODES; i++) {
327                                                 if (!strncmp(token, CC_CODES[i], 3)) {
328                                                         res->cc=i+1;
329                                                         break;
330                                                 }
331                                         }
332                                         return;
333                                 }
334                         }
335
336                         //Check if token is positive temp and negative dew
337                         for (i=0; i<2; i++) {
338                                 if (!isdigit(token[i])) break;
339                         }
340                         if ((i==2) && (token[2] == '/')  && (token[3] == 'M')) {
341                                 for (i=4; i<6; i++) {
342                                         if (!isdigit(token[i])) break;
343                                 }
344                                 if (i==6) {
345                                         //1st and 2nd digits gives the temperature
346                                         res->temp = atoi(token);
347
348                                         //5th and 6th digits gives the dew point temperature
349                                         res->dew = -atoi(&token[4]);
350
351                                         //Compute humidity
352                                         res->hmid = rel_humidity(res->dew, res->temp);
353
354                                         return;
355                                 }
356                         }
357
358                         break;
359
360                         //Check all tokens 7 chars long
361                 case 7:
362
363                         //Check if token is the observation time
364                         for (i=0; i<6; i++) {
365                                 if (!isdigit(token[i])) break;
366                         }
367                         if ((i==6) && (token[6] == 'Z')) return;
368
369                         //Check if token is the wind speed/direction in knots
370                         for (i=0; i<5; i++) {
371                                 if (!isdigit(token[i])) break;
372                         }
373                         if ((i==5) && (token[5] == 'K') &&  (token[6] == 'T')) {
374
375                                 //First 3 digits are wind direction
376                                 strncpy(s_tmp, token, 3);
377                                 s_tmp[3]='\0';
378                                 res->wind_d=atoi(s_tmp);
379
380                                 //4th and 5th digit are wind speed in knots (convert to km/hr)
381                                 res->wind_s = (int)(atoi(&token[3])*1.852);
382
383                                 return;
384                         }
385
386                         //Check if token is negative temperature
387                         if ((token[0] == 'M') && (token[4] == 'M')) {
388                                 for (i=1; i<3; i++) {
389                                         if (!isdigit(token[i])) break;
390                                 }
391                                 if ((i==3) && (token[3] == '/')) {
392                                         for (i=5; i<7; i++) {
393                                                 if (!isdigit(token[i])) break;
394                                         }
395                                         if (i==7) {
396                                                 //2nd and 3rd digits gives the temperature
397                                                 res->temp = -atoi(&token[1]);
398
399                                                 //6th and 7th digits gives the dew point temperature
400                                                 res->dew = -atoi(&token[5]);
401
402                                                 //Compute humidity
403                                                 res->hmid = rel_humidity(res->dew, res->temp);
404
405                                                 return;
406                                         }
407                                 }
408                         }
409
410                         //Check if token is wind variability
411                         for (i=0; i<3; i++) {
412                                 if (!isdigit(token[i])) break;
413                         }
414                         if ((i==3) && (token[3] == 'V')) {
415                                 for (i=4; i<7; i++) {
416                                         if (!isdigit(token[i])) break;
417                                 }
418                                 if (i==7) return;
419                         }
420
421                         break;
422
423                         //Check all tokens 8 chars long
424                 case 8:
425
426                         //Check if token is the wind speed/direction in m/s
427                         for (i=0; i<5; i++) {
428                                 if (!isdigit(token[i])) break;
429                         }
430                         if ((i==5)&&(token[5] == 'M')&&(token[6] == 'P')&&(token[7] == 'S')) {
431
432                                 //First 3 digits are wind direction
433                                 strncpy(s_tmp, token, 3);
434                                 s_tmp[3]='\0';
435                                 res->wind_d=atoi(s_tmp);
436
437                                 //4th and 5th digit are wind speed in m/s (convert to km/hr)
438                                 res->wind_s = (int)(atoi(&token[3])*3.6);
439
440                                 return;
441                         }
442
443                 default:
444
445                         //printf("token : %s\n", token);
446                         break;
447         }
448 }
449
450 void parse_weather(void *result, const char *data)
451 {
452         PWEATHER *res = (PWEATHER*)result;
453         /* Reset results */
454         memset(res, 0, sizeof(PWEATHER));
455
456 #ifdef XOAP
457         //Check if it is an xml file
458         if ( strncmp(data, "<?xml ", 6) == 0 ) {
459                 parse_weather_xml(res, data);
460         } else
461 #endif /* XOAP */
462         {
463                 //We assume its a text file
464                 char s_tmp[256];
465                 const char delim[] = " ";
466
467                 //Divide time stamp and metar data
468                 if (sscanf(data, "%[^'\n']\n%[^'\n']", res->lastupd, s_tmp) == 2) {
469
470                         //Process all tokens
471                         char *p_tok = NULL;
472                         char *p_save = NULL;
473
474                         if ((strtok_r(s_tmp, delim, &p_save)) != NULL) {
475
476                                 //Jump first token, must be icao
477                                 p_tok = strtok_r(NULL, delim, &p_save);
478
479                                 do {
480
481                                         parse_token(res, p_tok);
482                                         p_tok = strtok_r(NULL, delim, &p_save);
483
484                                 } while (p_tok != NULL);
485                         }
486                         return;
487                 }
488                 else {
489                         return;
490                 }
491         }
492 }
493
494 void weather_process_info(char *p, int p_max_size, char *uri, char *data_type, int interval)
495 {
496         static const char *wc[] = {
497                 "", "drizzle", "rain", "hail", "soft hail",
498                 "snow", "snow grains", "fog", "haze", "smoke",
499                 "mist", "dust", "sand", "funnel cloud tornado",
500                 "dust/sand", "squall", "sand storm", "dust storm"
501         };
502         PWEATHER *data;
503
504         ccurl_location_t *curloc = ccurl_find_location(&locations_head, uri);
505         if (!curloc->p_timed_thread) {
506                 curloc->result = malloc(sizeof(PWEATHER));
507                 memset(curloc->result, 0, sizeof(PWEATHER));
508                 curloc->process_function = &parse_weather;
509                 ccurl_init_thread(curloc, interval);
510                 if (!curloc->p_timed_thread) {
511                         ERR("error setting up weather thread");
512                 }
513         }
514
515         timed_thread_lock(curloc->p_timed_thread);
516         data = (PWEATHER*)curloc->result;
517         if (strcmp(data_type, "last_update") == EQUAL) {
518                 strncpy(p, data->lastupd, p_max_size);
519         } else if (strcmp(data_type, "temperature") == EQUAL) {
520                 temp_print(p, p_max_size, data->temp, TEMP_CELSIUS);
521         } else if (strcmp(data_type, "cloud_cover") == EQUAL) {
522 #ifdef XOAP
523                 if (data->xoap_t[0] != '\0') {
524                         strncpy(p, data->xoap_t, p_max_size);
525                 } else
526 #endif /* XOAP */
527                         if (data->cc == 0) {
528                                 strncpy(p, "", p_max_size);
529                         } else if (data->cc < 3) {
530                                 strncpy(p, "clear", p_max_size);
531                         } else if (data->cc < 5) {
532                                 strncpy(p, "partly cloudy", p_max_size);
533                         } else if (data->cc == 5) {
534                                 strncpy(p, "cloudy", p_max_size);
535                         } else if (data->cc == 6) {
536                                 strncpy(p, "overcast", p_max_size);
537                         } else if (data->cc == 7) {
538                                 strncpy(p, "towering cumulus", p_max_size);
539                         } else  {
540                                 strncpy(p, "cumulonimbus", p_max_size);
541                         }
542         } else if (strcmp(data_type, "pressure") == EQUAL) {
543                 snprintf(p, p_max_size, "%d", data->bar);
544         } else if (strcmp(data_type, "wind_speed") == EQUAL) {
545                 snprintf(p, p_max_size, "%d", data->wind_s);
546         } else if (strcmp(data_type, "wind_dir") == EQUAL) {
547                 if ((data->wind_d >= 349) || (data->wind_d < 12)) {
548                         strncpy(p, "N", p_max_size);
549                 } else if (data->wind_d < 33) {
550                         strncpy(p, "NNE", p_max_size);
551                 } else if (data->wind_d < 57) {
552                         strncpy(p, "NE", p_max_size);
553                 } else if (data->wind_d < 79) {
554                         strncpy(p, "ENE", p_max_size);
555                 } else if (data->wind_d < 102) {
556                         strncpy(p, "E", p_max_size);
557                 } else if (data->wind_d < 124) {
558                         strncpy(p, "ESE", p_max_size);
559                 } else if (data->wind_d < 147) {
560                         strncpy(p, "SE", p_max_size);
561                 } else if (data->wind_d < 169) {
562                         strncpy(p, "SSE", p_max_size);
563                 } else if (data->wind_d < 192) {
564                         strncpy(p, "S", p_max_size);
565                 } else if (data->wind_d < 214) {
566                         strncpy(p, "SSW", p_max_size);
567                 } else if (data->wind_d < 237) {
568                         strncpy(p, "SW", p_max_size);
569                 } else if (data->wind_d < 259) {
570                         strncpy(p, "WSW", p_max_size);
571                 } else if (data->wind_d < 282) {
572                         strncpy(p, "W", p_max_size);
573                 } else if (data->wind_d < 304) {
574                         strncpy(p, "WNW", p_max_size);
575                 } else if (data->wind_d < 327) {
576                         strncpy(p, "NW", p_max_size);
577                 } else if (data->wind_d < 349) {
578                         strncpy(p, "NNW", p_max_size);
579                 };
580         } else if (strcmp(data_type, "wind_dir_DEG") == EQUAL) {
581                 snprintf(p, p_max_size, "%d", data->wind_d);
582
583         } else if (strcmp(data_type, "humidity") == EQUAL) {
584                 snprintf(p, p_max_size, "%d", data->hmid);
585         } else if (strcmp(data_type, "weather") == EQUAL) {
586                 strncpy(p, wc[data->wc], p_max_size);
587         }
588
589         timed_thread_unlock(curloc->p_timed_thread);
590 }
591
592 #ifdef XOAP
593
594 /* xoap suffix for weather from weather.com */
595 static char *xoap = NULL;
596
597 /*
598  * TODO: make the xoap keys file readable from the config file
599  *       make the keys directly readable from the config file
600  *       make the xoap keys file giveable as a command line option
601  */
602 void load_xoap_keys(void)
603 {
604         FILE *fp;
605         char *par = (char *) malloc(11 * sizeof(char));
606         char *key = (char *) malloc(17 * sizeof(char));
607
608         xoap = (char *) malloc(64 * sizeof(char));
609         to_real_path(xoap, XOAP_FILE);
610         fp = fopen(xoap, "r");
611         if (fp != NULL) {
612                 if (fscanf(fp, "%10s %16s", par, key) == 2) {
613                         strcpy(xoap, "?cc=*&link=xoap&prod=xoap&par=");
614                         strcat(xoap, par);
615                         strcat(xoap, "&key=");
616                         strcat(xoap, key);
617                         strcat(xoap, "&unit=m");
618                 } else {
619                         free(xoap);
620                         xoap = NULL;
621                 }
622                 fclose(fp);
623         } else {
624                 free(xoap);
625                 xoap = NULL;
626         }
627         free(par);
628         free(key);
629 }
630 #endif /* XOAP */
631
632 int process_weather_uri(char *uri, char *locID)
633 {
634         /* locID MUST BE upper-case */
635         char *tmp_p = locID;
636         while (*tmp_p) {
637                 *tmp_p = toupper(*tmp_p);
638                 tmp_p++;
639         }
640
641         /* Construct complete uri */
642 #ifdef XOAP
643         if (strstr(uri, "xoap.weather.com")) {
644                 if (xoap != NULL) {
645                         strcat(uri, locID);
646                         strcat(uri, xoap);
647                 } else {
648                         free(uri);
649                         uri = NULL;
650                 }
651         } else 
652 #endif /* XOAP */
653         if (strstr(uri, "weather.noaa.gov")) {
654                 strcat(uri, locID);
655                 strcat(uri, ".TXT");
656         } else  if (!strstr(uri, "localhost") && !strstr(uri, "127.0.0.1")) {
657                 return -1;
658         }
659         return 0;
660 }
661