All pastes #593733 Raw Edit

stefantalpalaru

public text v1 · immutable
#593733 ·published 2007-06-28 14:38 UTC
rendered paste body
#!/usr/bin/perl -w
# Copyright (C) 2006 by Stefan Talpalaru <stefantalpalaru@yahoo.com>
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 as published by
# the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA  02111-1307  USA

# This script prints the current weather and a 5 day forecast from weather.com
# to a file given as argument. It should be run as a cron job every 5 minutes.
# The resulted file can be displayed on the desktop in "conky" or in the console.
# It will connect to the server only if the last update was done more than
# 30 minutes ago. The required module "Weather::Com" is available from CPAN
# and the weather station id can be found on the website.

use strict;

use Weather::Com; # get it from CPAN
use Time::Local;

# my $station_id = 'ROXX0034'; # Constantza, Romania (get yours from weather.com)
# my $station_id = 'ITXX0053'; # Novara, Italy (get yours from weather.com)
my $station_id = 'ITXX0081'; # Torino, Italy (get yours from weather.com)
my $update_interval = 30; # in minutes
my $forecast = 5; # in days

my $wc = Weather::Com->new(
    current => 1,
    forecast => $forecast,
    links => 0,
    units => 'm',
    debug => 0,
    partner_id => '1022846290',
    license => '0d63c9a8b0ac706d',
);

my $file = $ARGV[0];
die "Usage: $0 output_file\n" unless $file;

# read the date of the last update and convert it to a timestamp
open(FILE, '<', $file) or die "can't open \"$file\"";
my $last_updated = 0;
while (<FILE>) {
    next unless /^last updated/; # hard coded line format!
    my @line = split /[\s.:]+/;
    $last_updated = timelocal(0, $line[3], $line[2], $line[5], $line[4] - 1, $line[6]);
    last;
}

# exit if it was updated less than $update_interval minutes ago
my $age = int((time - $last_updated) / 60);
exit if $age < $update_interval; # we would get the same data

# get weather data
my $w = $wc->get_weather($station_id) or die;

# format the time of the last update
my @lsup = split(/[\s\/:]+/, $w->{cc}{lsup});
# print $w->{cc}{lsup}, "\n";
$lsup[3] += 12 if $lsup[5] eq 'PM' && $lsup[3] != 12;
$lsup[3] = 0 if $lsup[5] eq 'AM' && $lsup[3] == 12;

# truncate the file
open(FILE, '+>', $file) or die "can't open \"$file\"";

# print the good stuff
print FILE $w->{cc}{t},", ", $w->{cc}{tmp}, "°C, feels like: ", $w->{cc}{flik}, "°C\n",
  "humidity: ", $w->{cc}{hmid}, "%, wind: ", $w->{cc}{wind}{t}, ", ", $w->{cc}{wind}{s}, " km/h\n",
  "last updated: $lsup[3]:$lsup[4] $lsup[0].$lsup[1].20$lsup[2]\n\n";

for (@{$w->{dayf}{day}}) {
    my $tod = $_->{part}[0]{t} eq 'N/A' ? 1 : 0;
    print FILE $_->{t}, $tod ? " night" : "", ": ", $_->{part}[$tod]{t},
      " ", $tod ? $_->{low} : $_->{hi}, "°C; wind: ", $_->{part}[$tod]{wind}{t}, ", ",
      $_->{part}[$tod]{wind}{s}, " km/h\n";
}