1#!/usr/local/bin/perl -w
2#
3# Copyright (C) 2006 Lars Strand
4#
5# Plugin to fetch temperature from tgftp.nws.noaa.gov
6#
7# Parameters supported:
8#
9#       config
10#       autoconf
11#
12# Magic markers:
13#%# family=auto
14#%# capabilities=autoconf
15
16use strict;
17
18my $usehum = $ENV{humidity} || undef;   # set to "yes" to enable humidity
19my $wcode  = $ENV{wcode}    || "ENGM";  # Find areacode here http://tgftp.nws.noaa.gov/
20my $unit   = $ENV{unit}     || "C";     # "C" = Celsius, "F" = Fahrenheit
21my $proxy  = $ENV{proxy}    || undef;   # Example: "http://proxy.foo.bar:8080/"
22
23my $ret = undef;
24if (! eval "require LWP::UserAgent;") {
25    $ret = "LWP::UserAgent not found";
26}
27
28if (defined $ARGV[0] and $ARGV[0] eq "autoconf") {
29    if (defined $ret) {
30	print "no ($ret)\n";
31    } else {
32	print "yes\n";
33    }
34    exit 0;
35}
36
37# Extract weather-code from filename. Example: weather_CODE
38if ($0 =~ /^(?:|.*\/)temperature_([^_]+)$/) {
39    $wcode  = $1;
40}
41
42
43my $datasource = "http://tgftp.nws.noaa.gov/data/observations/metar/decoded/$wcode.TXT";
44
45my $ua = LWP::UserAgent->new(timeout => 30);
46$ua->agent('Munin');
47
48# Use proxy, if defined.
49if (defined $proxy) {
50    $ua->proxy(['http'], $proxy);
51}
52
53my $response = $ua->request(HTTP::Request->new('GET',$datasource));
54
55if (defined $ARGV[0] and $ARGV[0] eq "config") {
56
57    if ($response->content =~ /^((.*?),.*\)).*\n/) {
58	print "graph_title Temperature at $2\n";
59    } else {
60	print "graph_title Temperature at locationcode $wcode\n";
61    }
62
63    if ($unit =~ /F/) {
64	print "graph_vlabel temp in F\n";
65    } else {
66	print "graph_vlabel temp in C\n";
67    }
68
69    print "graph_args --base 1000 -l 0\n";
70    print "graph_category sensors\n";
71    print "graph_info Temperatures at $1 (fetched from weather.nooa.gov).\n";
72    print "temperature.label temperature\n";
73    if (defined $usehum) {
74	print "humidity.label humidity\n";
75	print "humidity.info Humidity in %.\n";
76    }
77    exit 0;
78}
79
80if ($response->content =~ /Temperature:\s*(.*)\s+F\s*\(\s*(.*)\s+C/) {
81    my ($f, $c) = ($1, $2);
82    if ($unit =~ /F/) {
83	print "temperature.value $f\n";
84    } else {
85	print "temperature.value $c\n";
86    }
87} else {
88    print "temperature.value U\n";
89}
90
91if (defined $usehum) {
92    if ($response->content =~ /Relative Humidity:\s*(\d+)\%.*/) {
93	print "humidity.value $1\n";
94    }
95}
96