Created
March 30, 2011 14:59
-
-
Save amari3/894556 to your computer and use it in GitHub Desktop.
東京電力の電気使用量を表示するスクリプト
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env perl | |
use strict; | |
use warnings; | |
use Getopt::Long; | |
use Furl; | |
use JSON; | |
my $API_URL = 'http://api.linknode.net/tepco/v2/demand.json'; | |
&main;exit; | |
sub main { | |
# コマンドラインオプション | |
my %opt = ( | |
all => 0, # すべての時間帯 | |
reverse => 0, # all 指定時に出力を逆順にする | |
color => 1, # 出力時に色を付ける | |
help => 0, # ヘルプ | |
); | |
GetOptions( | |
\%opt, | |
qw/all reverse color! help/, | |
); | |
show_help() and return if $opt{help}; | |
# 東京電力の電力需給情報をJSON形式で取得 | |
my $json = get_tepco($API_URL); | |
show_all($json, $opt{reverse}) if $opt{all}; | |
show_now_usage($json, $opt{color}); | |
} | |
sub get_tepco { | |
my $url = shift || return; | |
my $furl = Furl->new( | |
agent => 'amari3', | |
timeout => 10, | |
); | |
my $res = $furl->get($url); | |
die "Cannot download $url: $!" unless $res->is_success; | |
return JSON->new->utf8(0)->decode($res->content); | |
} | |
sub show_all { | |
my ($tepco, $reverse) = @_; | |
my @all_demand | |
= $reverse ? reverse @{$tepco->{demand}} : @{$tepco->{demand}}; | |
print "日時\t当日実績(万kW)\t前日実績(万kW)\n"; | |
for my $demand (@all_demand) { | |
printf "%s %s\t%d\t%d\n", | |
$demand->{date}, | |
$demand->{time}, | |
$demand->{today}, | |
$demand->{yesterday}; | |
} | |
print "\n"; | |
} | |
sub show_now_usage { | |
my ($tepco, $color) = @_; | |
my $peak = $tepco->{peak}->{kw}; | |
my $now_demand = now_demand($tepco->{demand}); | |
my $now_usage = now_usage($now_demand, $peak); | |
$now_usage = set_color($now_usage) if $color; | |
print "使用量\t使用率\n"; | |
printf "%d万kW / %d万kW\t%s%%\n", $now_demand, $peak, $now_usage; | |
} | |
sub now_demand { | |
my $all_demand = shift; | |
my $now = 0; | |
for my $demand (@{$all_demand}) { | |
last unless $demand->{today}; | |
$now = $demand->{today}; | |
} | |
return $now; | |
} | |
sub now_usage { | |
my ($now, $peak) = @_; | |
return int($now / $peak * 100); | |
} | |
sub set_color { | |
my $usage = shift; | |
my $color = $usage < 80 ? 32 | |
: $usage < 90 ? 33 | |
: 31; | |
return sprintf "\33[%dm%d\033[0m", $color, $usage; | |
} | |
sub show_help { | |
print <<HELP; | |
Usage: $0 [options] | |
Options: | |
-a,--all すべての時間帯を出力 | |
-r,--reverse all 指定時に出力を逆順にする | |
--nocolor 出力時に色を付けない | |
-h,--help This help | |
HELP | |
return 1; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment