#!/usr/bin/perl # Usage: ./solar_2.pl forecast.csv profile.csv $power use DateTime; my @csv_forecast; my @csv_profile; my $line_number = "0"; open (my $fforecast, '<', $ARGV[0]) or die "Failed to open $ARGV[0]"; while ( my $line = <$fforecast>) { $line =~ s/\R/\012/; chomp ($line); my ($power,$timestamp) = (split "," , $line)[0,3]; ${csv_forecast[$line_number]}{"power"} = $power; ${csv_forecast[$line_number]}{"timestamp"} = $timestamp; ++$line_number; } close ($fforecast); $line_number = 0; open (my $fprofile, '<', $ARGV[1]) or die "Failed to open $ARGV[1]"; while ( my $line = <$fprofile>) { chomp ($line); my ($timestamp,$percentage) = (split "," , $line); ${csv_profile[$line_number]}{"timestamp"} = $timestamp; ${csv_profile[$line_number]}{"percentage"} = $percentage; ++$line_number; } close ($fprofile); # For each 30 minutes period, calculate whether we are going to produce # more power than we are going to consume (and therefore waste it), # or whether we are going to consume more power than we produce (and # therefore have deficit). my $waste = "0"; my $deficit = "0"; my $produced = "0"; my ( $y,$m,$d,$h,$mt,$sec ); my ( $i,$j ); for ( $i = 1 ; $i < @csv_forecast ; ++$i ) { ($y,$m,$d) = $csv_forecast[$i]{"timestamp"} =~ /^([\d]{4})\-([\d]{2})\-([\d]{2})/; ($h,$mt,$sec) = $csv_forecast[$i]{"timestamp"} =~ /T([\d]{2})\:([\d]{2})\:([\d]{2})Z$/; unless ( defined ($h) ) { ($h,$mt,$sec) = ( '0', '0', '0') }; my $forecast_time = DateTime->new( year => $y, month => $m, day => $d, hour => $h, minute => $mt, second => $sec, time_zone => 'UTC' ); $forecast_time->set_time_zone('local'); my $consumption; my ( $hour,$minute ); for ( $j = 1 ; $j < @csv_profile ; ++$j ) { ($hour,$minute) = $csv_profile[$j]{"timestamp"} =~ /([\d]{2})\:([\d]{2})$/; if ( $hour == $forecast_time->hour() and $minute == $forecast_time->minute() ) { $consumption = $csv_profile[$j]{"percentage"} * $ARGV[2] * 0.01; } } if ( $consumption > ( $csv_forecast[$i]{"power"} * 0.5 )) { $deficit += $consumption - ( $csv_forecast[$i]{"power"} * 0.5 ); } else { $waste += ( $csv_forecast[$i]{"power"} * 0.5 ) - $consumption; } $produced += $csv_forecast[$i]{"power"} * 0.5; # If the day has changed, print information for the day. if ( $forecast_time->hour() == "0" and $forecast_time->minute() == "0" ) { $forecast_time->subtract( days=> "1"); print "INFORMATION FOR DATE ". $forecast_time->date() . "\n"; print "Total power produced will be $produced kWh\n"; print "About $deficit kWh will be taken from the grid (deficit)\n"; print "About $waste kWh will be produced but not used (wasted)\n\n"; $deficit = 0; $waste = 0; $produced = 0; } } exit;