AquariumHive
view release on metacpan or search on metacpan
lib/App/AquariumHive.pm view on Meta::CPAN
has web_mounts => (
is => 'rw',
init_arg => undef,
default => sub {{}},
);
sub web_mount {
my ( $self, $mount, $psgi ) = @_;
$self->web_mounts->{$mount} = $psgi;
}
has tiles => (
is => 'rw',
init_arg => undef,
default => sub {{}},
);
sub tile {
my ( $self, $key ) = @_;
return $self->tiles->{$key};
}
sub add_tile {
my ( $self, $key, $tile ) = @_;
$self->tiles->{$key} = $tile;
}
has web => (
is => 'lazy',
init_arg => undef,
);
sub _build_web {
my ( $self ) = @_;
my $server = Twiggy::Server->new(
port => $self->port,
);
$server->register_service(builder {
enable sub {
my $app = shift;
sub {
$self->debug('Web Request '.$_[0]->{PATH_INFO});
my $res = $app->($_[0]);
return $res;
};
};
mount '/shutdown' => sub { exit 0 };
mount '/socket.io' => $self->pocketio;
for my $mount (sort { length($a) <=> length($b) || $a cmp $b } keys %{$self->web_mounts}) {
mount '/'.$mount, $self->web_mounts->{$mount};
}
mount '/tile' => sub {
my ( $tile ) = $_[0]->{PATH_INFO} =~ m!/(.*)!;
if ($self->tile($tile)) {
return [ 200, [ "Content-Type" => "application/json" ], [encode_json({
html => $self->tile($tile)->html,
$self->tile($tile)->has_js ? ( js => $self->tile($tile)->js ) : (),
})] ];
} else {
return [ 404, [ "Content-Type" => "application/json" ], [encode_json({
not => 'found',
})] ];
}
};
mount '/name' => sub {
return [ 200, [ "Content-Type" => "application/json" ], ['"'.$self->name.'"'] ];
};
mount '/tiles' => sub {
return [ 200, [ "Content-Type" => "application/json" ], [encode_json([sort { $a cmp $b } keys %{$self->tiles}])] ];
};
mount '/' => builder {
enable 'Rewrite',
rules => sub { s{^/$}{/index.html}; };
enable "Plack::Middleware::Static",
path => qr{^/},
root => $self->web_root;
};
});
return $server;
}
sub command_aqhive {
my ( $self, $command, @args ) = @_;
return unless defined $command;
my $hivejso;
if ($self->simulation) {
$hivejso = HiveJSO->new(
unit => 'rasputin',
command => scalar @args ? ([ $command, @args ]) : ($command),
)->hivejso_short;
} else {
$hivejso = encode_json({
o => scalar @args ? ([ $command, @args ]) : ($command),
});
}
$self->debug('HiveJSO OUT '.$hivejso);
$self->uart->push_write($hivejso);
}
sub run {
my ( $self ) = @_;
$self->plugins;
$self->web;
$self->uart;
$self->db;
$self->info("Starting App::AquariumHive (port ".$self->port.")...");
my $t = AE::timer 0, 15, sub { $self->command_aqhive('data') };
AE::cv->recv;
}
sub run_cmd {
my ( $self, $command ) = @_;
my @lines;
if ($command) {
require IPC::Open3; # core
# autoflush STDOUT so we can see command output right away
( run in 1.564 second using v1.01-cache-2.11-cpan-cdf2f3d4e48 )