AquariumHive
view release on metacpan or search on metacpan
lib/AquariumHive/Simulator.pm view on Meta::CPAN
$self->handle;
$self->pulse;
}
has _portable_socketpair => (
is => 'lazy',
init_arg => undef,
);
sub _build__portable_socketpair {
my ($fh1, $fh2) = portable_socketpair;
return [ $fh1, $fh2 ];
}
has handle => (
is => 'lazy',
init_arg => undef,
);
sub _build_handle {
my ( $self ) = @_;
my $handle = AnyEvent::Handle->new(
fh => $self->_portable_socketpair->[1],
);
$handle->on_read(sub {
$_[0]->push_read( hivejso => sub {
my ( $handle, $data ) = @_;
if (ref $data eq 'HiveJSO::Error') {
p($data->error); p($data->garbage);
return;
}
$self->on_hivejso($data);
});
});
return $handle;
}
has fh => (
is => 'lazy',
init_arg => undef,
);
sub _build_fh {
my ( $self ) = @_;
return $self->_portable_socketpair->[0];
}
has sensor_rows => (
is => 'lazy',
);
sub _build_sensor_rows { 2 }
has pulse => (
is => 'lazy',
);
sub _build_pulse {
my ( $self ) = @_;
return unless $self->sensor_rows;
return AE::timer 0, 60, sub {
for my $no (1..$self->sensor_rows) {
for my $sensor (qw( ph orp ec temp )) {
my $attr = $sensor.$no;
my $next = 'next_'.$sensor;
my $current = $self->state->{$attr};
my $new = $self->$next($current);
$self->state->{$attr} = $new;
}
}
};
}
has state => (
is => 'lazy',
init_arg => undef,
);
sub _build_state {
my ( $self ) = @_;
return {
(map { 'pwm'.$_, 0 } (1..6)),
(map { 'ph'.$_, $self->next_ph } (1..$self->sensor_rows)),
(map { 'orp'.$_, $self->next_orp } (1..$self->sensor_rows)),
(map { 'ec'.$_, $self->next_ec } (1..$self->sensor_rows)),
(map { 'temp'.$_, $self->next_temp } (1..$self->sensor_rows)),
};
}
sub hivejso_base {
return unit => 'aqhive';
}
sub state_to_hivejso {
my ( $self ) = @_;
my %state = %{$self->state};
my @data;
for my $key (keys %state) {
push @data, [$key, $state{$key}];
}
return HiveJSO->new( $self->hivejso_base, data => \@data );
}
sub on_hivejso {
my ( $self, $hivejso ) = @_;
if ($hivejso->has_command) {
# "o":"data"
if ($hivejso->command_cmd eq 'data') {
$self->send_state;
}
# "o":["set_pwm1",100]
if ($hivejso->command_cmd eq 'set_pwm') {
my ( $no, $value ) = $hivejso->command_args;
my $func = 'pwm'.$no;
$self->state->{$func} = $value;
$self->send_state;
}
}
}
sub send_state {
( run in 1.145 second using v1.01-cache-2.11-cpan-f56aa216473 )