Friday, September 4, 2009

Moving Planters Indoors for the Winter

Winter will be here in a couple of months, and if you're like me, you might have some potted plants outside that you want to move inside when it starts getting too cold. Unfortunately, if you're like me, you're probably also not very good at checking the weather forecast to know when it's expected to be cold. Heck, sometimes I don't even know that it's going to be raining sometimes until I step outside into the rain without an umbrella or rain coat.

Fortunately, computers have made a lot of types of automation easier, like checking the weather for you. Since weather.gov is paid for by your tax dollars (if you're American), the data on that site is freely available. And bonus: you can now download a 7-day forecast for your area in XML format, suitable for easy parsing.

The quick link to the page you need to look at is http://www.wrh.noaa.gov/forecast/wxtables/. When you get there, you can click on the XML radio button, type in your city and state, and click "Go". The URL of the next page will be the link that you need to grab for your automated reports.

There are plenty of tools and programming languages out there for you to choose from to handle this, but if you're in the aforementioned class of people who are like me, you've probably already chosen Perl. Let me make your life a little easier, and give you the source code for a cron that I tossed together this morning. I have it set up to run at 6:30am every morning:




#!/usr/bin/perl

use strict;
use XML::Simple;
use LWP::UserAgent;

my $xs = XML::Simple->new();
my $ua = LWP::UserAgent->new();

my $url = 'http://www.wrh.noaa.gov/forecast/xml/xml.php?duration=168&interval=6&lat=40.69651&lon=-112.091784';
my $response = $ua->get( $url );
my $content = $response->decoded_content();
my $xml = $xs->XMLin( $content );
my %temps;

for my $day ( @{$xml->{forecastDay}} ) {
eval {
for my $hour ( @{$day->{period}} ) {
my $temp = $hour->{temperature}{content};
$temps{$temp} = 1;
}
}
}

my @temps = sort keys %temps;
my $lowtemp = $temps[0];

if ( $lowtemp < 40 ) {
use Net::SMTP::TLS;
my $smtp = Net::SMTP::TLS->new(
'smtp.gmail.com',
'Port' => '587',
'User' => 'username',
'Password' => 'password',
);
$smtp->mail('username@gmail.com');
$smtp->to('000000000@messaging.sprintpcs.com');
$smtp->data();
$smtp->datasend("Subject: Cold Weather\n");
$smtp->datasend("\n");
$smtp->datasend("Temps as low as $lowtemp coming up");
$smtp->dataend();
$smtp->quit();
}

exit;



Note to Perl programmers: This was a quick script, and it does the job. If you would like to offer improvements, I would love to hear them.

Note to non-Perl programmers: I'm sorry I didn't write it in (Python|Ruby|PHP) or whatever other language you prefer. You're more than welcome to write your own.

No comments:

Post a Comment

Comments for posts over 14 days are moderated