#!/usr/bin/perl # # Downloads, parses and prints the current load shedding status. # It is suggested that you run this script every 5-20 minutes. # # Written by Timothy Allen use strict; use warnings; use Getopt::Long; use LWP::Simple; use MIME::Lite; use Time::Piece; use Time::Seconds; my $url = "http://www.capetown.gov.za/en/electricity/Pages/LoadShedding.aspx"; my $status_file = "$ENV{HOME}/.loadshedding_status"; my @recipients = (); my $verbose = 0; GetOptions( "t|to=s{1,}" => \@recipients, "v|verbose" => \$verbose, ) or die "Usage: $0 [-t ... ] \n"; my ($last_status, $current_status, $last_str, $current_str, $last_time, $current_time, $diff); $current_time = localtime; $current_str = $current_time->strftime('%Y-%m-%dT%H:%M:%S%z'); if (-f $status_file) { open STATUS, "<", $status_file or die $!; my @lines = ; close STATUS or die $!; chomp($last_status = $lines[0]) if ($lines[0] =~ s#^\s*Status:\s*##i); chomp($last_str = $lines[1]) if ($lines[1] =~ s#^\s*Time:\s*##i); if ($last_str) { $last_time = Time::Piece->strptime($last_str, '%Y-%m-%dT%H:%M:%S%z'); $diff = $current_time - $last_time; } } my ($content, $output); unless ($content = get $url) { warn "Couldn't get $url"; $content = get "http://www.capetown.gov.za/loadshedding/Loadshedding.html" or die "Couldn't get alternate url"; } if ($content =~ m#]*id="WebPartWPQ3"[^>]*>.*?]*>(.*?)#ims) { $current_status = $1; $current_status =~ s#\s*(]*>|\n)\s*# #imsg; $current_status =~ s#<.*?>##imsg; } elsif ($content =~ m#]*class="MainHeadText"[^>]*>.{0,1500}?
(.*?)
#ims) { $current_status = $1; $current_status =~ s#\s*(]*>|\n)\s*# #imsg; $current_status =~ s#<.*?>##imsg; } else { die "Unable to parse status; load shedding page must have changed.\n"; } if (($current_status !~ /no items/i) && (!defined $last_status || $current_status ne $last_status)) { open STATUS, ">", $status_file or die $!; print STATUS "Status: $current_status\n"; print STATUS "Time: $current_str\n"; close STATUS or die $!; if (defined $last_status) { $output .= "The City of Cape Town's website indicates that the load shedding status has changed from: $last_status to: $current_status\n"; } else { $output .= "Load shedding status for the City of Cape Town: $current_status\n"; } $output .= "Time since last change: " . $diff->pretty . "\n" if defined $diff and $verbose; } else { $output .= "Load shedding status: $current_status\n" if $verbose; } if (defined $output) { if (scalar @recipients < 1) { print $output; } else { foreach my $to (@recipients) { my $message = MIME::Lite->new( From => 'Loadshedding Alerts ', To => $to, Subject => 'Load shedding status change', Data => $output, ); # send the message $message->send(); } } } # vim: set indentexpr= expandtab sw=2 softtabstop=2 tw=10000 :